mirror of
https://github.com/storytold/lightcraft.git
synced 2026-12-06 05:53:22 -05:00
LRC-MAP-VIEW: review fixes for the key file, tile bodies, saved locations, sidecar GPS and hidden pins
- The ArcGIS key file is created owner-only (0600 on Unix) before the key is written (safe_file::write_atomic_private), not chmod-ed after. - A tile body has a 60 s deadline: a server trickling bytes no longer holds a network slot. - locations.json with bad entries is never written back when its copy can't be made. - Which photos' GPS is LightCraft's is kept in prefs.json (gpsOwned), so a position cleared with automatic XMP writing off still leaves the sidecar after a reopen. - Pins hidden by the Untagged filter can't be dragged (drawing and hit testing share one rule). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
325557c4c3
commit
6a5cd46afc
13 files changed
+263
-28
No files matched your search
@@ -108,8 +108,9 @@ pub fn sync_dir(dir: &Path) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A new, empty temp file next to `path` (hidden, unique in this process and folder).
|
||||
fn create_temp(path: &Path) -> io::Result<(PathBuf, File)> {
|
||||
/// A new, empty temp file next to `path` (hidden, unique in this process and folder). When
|
||||
/// `private`, it is created readable by its owner only (`0600` on Unix) before any byte is written.
|
||||
fn create_temp(path: &Path, private: bool) -> io::Result<(PathBuf, File)> {
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
if path.file_name().is_none() {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{} is not a file path", path.display())));
|
||||
@@ -117,7 +118,16 @@ fn create_temp(path: &Path) -> io::Result<(PathBuf, File)> {
|
||||
let dir = parent_of(path);
|
||||
for _ in 0..1000 {
|
||||
let tmp = dir.join(format!(".lightcraft-{}-{}.tmp", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
|
||||
match OpenOptions::new().write(true).create_new(true).open(&tmp) {
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
if private {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = private;
|
||||
match options.open(&tmp) {
|
||||
Ok(f) => return Ok((tmp, f)),
|
||||
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e),
|
||||
@@ -128,8 +138,8 @@ fn create_temp(path: &Path) -> io::Result<(PathBuf, File)> {
|
||||
|
||||
/// Write a temp file next to `path` with what `fill` writes, synced to disk when `sync`. On
|
||||
/// failure the temp file is removed. Returns its path and length.
|
||||
fn write_temp(path: &Path, sync: bool, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result<(PathBuf, u64)> {
|
||||
let (tmp, file) = create_temp(path)?;
|
||||
fn write_temp(path: &Path, sync: bool, private: bool, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result<(PathBuf, u64)> {
|
||||
let (tmp, file) = create_temp(path, private)?;
|
||||
let r = (|| {
|
||||
let limit = FAIL_AFTER.with(Cell::get);
|
||||
let mut w = Limited { inner: io::BufWriter::with_capacity(1 << 20, file), n: 0, limit };
|
||||
@@ -160,19 +170,26 @@ pub fn write_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
|
||||
/// [`write_atomic`] with streamed content: `fill` writes it (an error aborts and leaves the old
|
||||
/// file). Returns the length written.
|
||||
pub fn write_atomic_with(path: &Path, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result<u64> {
|
||||
replace_with(path, true, fill)
|
||||
replace_with(path, true, false, fill)
|
||||
}
|
||||
|
||||
/// [`write_atomic`] for a secret (an API key): the temp file is created readable by its owner only
|
||||
/// (`0600` on Unix) before any byte is written, so the content is never readable by other users,
|
||||
/// not even while it is written. Elsewhere the folder's permissions apply.
|
||||
pub fn write_atomic_private(path: &Path, data: &[u8]) -> io::Result<()> {
|
||||
replace_with(path, true, true, &mut |w| w.write_all(data)).map(|_| ())
|
||||
}
|
||||
|
||||
/// Replace (or create) `path` with `data` atomically but **without syncing** it to disk — only for
|
||||
/// outputs that can always be recreated (exports, renders, screenshots); see the module docs.
|
||||
/// Anything that can't be made again goes through [`write_atomic`].
|
||||
pub fn write_atomic_nosync(path: &Path, data: &[u8]) -> io::Result<()> {
|
||||
replace_with(path, false, &mut |w| w.write_all(data)).map(|_| ())
|
||||
replace_with(path, false, false, &mut |w| w.write_all(data)).map(|_| ())
|
||||
}
|
||||
|
||||
/// Temp file (synced when `sync`) renamed over `path`, then the folder synced when `sync`.
|
||||
fn replace_with(path: &Path, sync: bool, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result<u64> {
|
||||
let (tmp, n) = write_temp(path, sync, fill)?;
|
||||
fn replace_with(path: &Path, sync: bool, private: bool, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result<u64> {
|
||||
let (tmp, n) = write_temp(path, sync, private, fill)?;
|
||||
if let Err(e) = fs::rename(&tmp, path) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(e);
|
||||
@@ -197,7 +214,7 @@ pub fn write_new_unique(candidates: &mut dyn Iterator<Item = PathBuf>, data: &[u
|
||||
let Some(first) = candidates.peek().cloned() else {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "no file name to write"));
|
||||
};
|
||||
let (tmp, _) = write_temp(&first, true, &mut |w| w.write_all(data))?;
|
||||
let (tmp, _) = write_temp(&first, true, false, &mut |w| w.write_all(data))?;
|
||||
let r = (|| {
|
||||
// Kept (issue #134 point 4): these files replace raws (Convert / Copy as DNG) or become
|
||||
// library photos (merges). On a local disk the read usually comes from the cache, but on a
|
||||
@@ -354,6 +371,27 @@ mod tests {
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_private_file_is_owner_only_from_its_creation() {
|
||||
let d = temp("private");
|
||||
let p = d.join("keys.json");
|
||||
fs::write(&p, b"old").unwrap();
|
||||
write_atomic_private(&p, b"secret").unwrap();
|
||||
assert_eq!(fs::read(&p).unwrap(), b"secret");
|
||||
assert_eq!(names(&d), vec!["keys.json".to_string()], "no temp file left");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
// the temp file was created 0600 and renamed: the mode is the one it was created with
|
||||
assert_eq!(fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600);
|
||||
let (tmp, f) = create_temp(&p, true).unwrap();
|
||||
assert_eq!(f.metadata().unwrap().permissions().mode() & 0o777, 0o600, "owner-only before a byte is written");
|
||||
drop(f);
|
||||
fs::remove_file(tmp).unwrap();
|
||||
}
|
||||
let _ = fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_publish_never_replaces_a_file_that_appears_at_the_same_time() {
|
||||
let d = temp("nolink-race");
|
||||
|
||||
@@ -729,6 +729,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
None => None,
|
||||
};
|
||||
let mut ops = Vec::new();
|
||||
let owned_before = s.gps_edited.len();
|
||||
for id in targets {
|
||||
let Some(ph) = s.catalog.photo(id) else { continue };
|
||||
let mut m = ph.meta.clone();
|
||||
@@ -786,6 +787,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
ops.push(Op::SetMeta { id, meta: Box::new(m) });
|
||||
}
|
||||
let n = ops.len();
|
||||
s.gps_owned_grew(owned_before);
|
||||
s.commit("Edit Info", Op::Batch { ops })?;
|
||||
// keywords just added become the Recent Keywords set
|
||||
let added: Vec<String> = strs("addKeywords").unwrap_or_default().into_iter().chain(strs("keywords").unwrap_or_default()).collect();
|
||||
|
||||
@@ -72,7 +72,9 @@ fn commit_gps(s: &mut Session, targets: &[lightcraft_catalog::PhotoId], gps: Opt
|
||||
let count = ops.len();
|
||||
if count > 0 {
|
||||
// before the commit: the sidecar written when it lands already follows LightCraft's position
|
||||
let before = s.gps_edited.len();
|
||||
s.gps_edited.extend(targets.iter().copied());
|
||||
s.gps_owned_grew(before);
|
||||
s.commit(label, Op::Batch { ops })?;
|
||||
}
|
||||
Ok(count)
|
||||
|
||||
@@ -402,7 +402,8 @@ pub struct Session {
|
||||
/// moved, Remove GPS Coordinates, the Info panel's GPS field): their sidecars take LightCraft's
|
||||
/// position as it is ([`sidecar::GPS_OWNED`]), so a cleared one (or an undone geotag) is removed
|
||||
/// from the sidecar too. Other photos' sidecar GPS is never removed (LightCraft doesn't read GPS
|
||||
/// from sidecars). Cleared when another library opens: photo ids are per library.
|
||||
/// from sidecars). Kept with the library's preferences (`prefs.json` `gpsOwned`), so it
|
||||
/// survives a reopen; another library brings its own (photo ids are per library).
|
||||
pub gps_edited: std::collections::HashSet<PhotoId>,
|
||||
/// Auto import: files seen in the watched folder and their size then (a file is imported once
|
||||
/// its size held between two scans).
|
||||
|
||||
@@ -357,6 +357,12 @@ struct PrefsFile {
|
||||
/// dropped on its own, never taking the other preferences with it.
|
||||
#[serde(skip_serializing_if = "Option::is_none", deserialize_with = "lenient_tile_source")]
|
||||
map_source: Option<crate::map::TileSource>,
|
||||
/// Photos whose position was set or cleared in LightCraft ([`Session::gps_edited`]), so a
|
||||
/// position cleared before the library closed still leaves the sidecar when it is written after
|
||||
/// a reopen (with automatic XMP writing off, that can be much later). Read leniently: an entry
|
||||
/// that isn't a photo id is skipped, never taking the other preferences with it.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
gps_owned: Vec<serde_json::Value>,
|
||||
}
|
||||
|
||||
fn presets_json(s: &Session) -> String {
|
||||
@@ -433,7 +439,15 @@ impl SettingsLoad {
|
||||
fn set_aside(&mut self, store: &mut dyn Store, name: &'static str, why: &str) {
|
||||
let bytes = match store.read(name) {
|
||||
Ok(Some(b)) => b,
|
||||
_ => return,
|
||||
// gone since it was read: nothing left to lose
|
||||
Ok(None) => return,
|
||||
// no copy can be made, so the file must not be written with less in it
|
||||
Err(e) => {
|
||||
log::error!("library: {name}: {why}, and it couldn't be read again: {e}");
|
||||
self.blocked.push(name);
|
||||
self.warnings.push(format!("{name}: {why}, and it couldn't be set aside ({e}). LightCraft won't overwrite the file."));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let secs = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
let keep = format!("{name}.corrupt-{secs}");
|
||||
@@ -781,6 +795,14 @@ impl Session {
|
||||
self.forget_local_days = prefs.forget_local_days.unwrap_or(lightcraft_catalog::DEFAULT_FORGET_DAYS);
|
||||
self.hold_view = prefs.hold_view;
|
||||
self.load_locations(files.as_mut(), &mut settings, prefs.saved_locations);
|
||||
// (only ids of this library's photos: the file may be older than the catalog)
|
||||
self.gps_edited = prefs
|
||||
.gps_owned
|
||||
.iter()
|
||||
.filter_map(serde_json::Value::as_u64)
|
||||
.map(lightcraft_catalog::PhotoId)
|
||||
.filter(|id| self.catalog.photo(*id).is_some())
|
||||
.collect();
|
||||
if let Some(notice) = self.map.load_source(prefs.map_source) {
|
||||
settings.warnings.push(notice);
|
||||
}
|
||||
@@ -1076,6 +1098,17 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// After a command added photos to [`Session::gps_edited`] (`before` = its size then): save
|
||||
/// the preferences that keep it across a reopen. A failure is logged, not the command's: the
|
||||
/// position is set, and the set stays for this session.
|
||||
pub(crate) fn gps_owned_grew(&mut self, before: usize) {
|
||||
if self.gps_edited.len() != before
|
||||
&& let Err(e) = self.save_prefs()
|
||||
{
|
||||
log::warn!("library: the photos' GPS ownership wasn't saved: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Save the library preferences (no-op for in-memory sessions).
|
||||
pub fn save_prefs(&mut self) -> Result<()> {
|
||||
let v = serde_json::to_vec_pretty(&PrefsFile {
|
||||
@@ -1107,6 +1140,11 @@ impl Session {
|
||||
hold_view: self.hold_view,
|
||||
saved_locations: self.legacy_locations.clone(),
|
||||
map_source: Some(self.map.source().clone()),
|
||||
gps_owned: {
|
||||
let mut ids: Vec<u64> = self.gps_edited.iter().filter(|id| self.catalog.photo(**id).is_some()).map(|id| id.0).collect();
|
||||
ids.sort_unstable();
|
||||
ids.into_iter().map(serde_json::Value::from).collect()
|
||||
},
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let Some(lib) = self.library.as_mut() else { return Ok(()) };
|
||||
|
||||
@@ -300,13 +300,8 @@ fn write_key_file(path: &std::path::Path, file: &KeyFile) -> std::io::Result<()>
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let data = serde_json::to_vec_pretty(file).map_err(std::io::Error::other)?;
|
||||
lightcraft_catalog::safe_file::write_atomic(path, &data)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
|
||||
}
|
||||
Ok(())
|
||||
// owner-only from its creation, not after the key is on disk
|
||||
lightcraft_catalog::safe_file::write_atomic_private(path, &data)
|
||||
}
|
||||
|
||||
impl Session {
|
||||
|
||||
@@ -96,18 +96,22 @@ pub trait Transport: Send + Sync {
|
||||
fn get(&self, url: &str, headers: &[(&'static str, String)], max_body: usize, cancel: &AtomicBool) -> Result<HttpResponse, String>;
|
||||
}
|
||||
|
||||
/// HTTPS through `lightcraft-fetch` (pure Rust, rustls), with connect and stall timeouts.
|
||||
/// HTTPS through `lightcraft-fetch` (pure Rust, rustls), with connect and stall timeouts, and a
|
||||
/// limit on the whole body: the stall timeout restarts with each read, so a server sending a few
|
||||
/// bytes now and then would otherwise hold one of the two network slots until the size cap.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HttpTransport {
|
||||
pub connect_timeout: Duration,
|
||||
pub stall_timeout: Duration,
|
||||
/// Longest time spent receiving one body, however often bytes arrive.
|
||||
pub body_timeout: Duration,
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl Default for HttpTransport {
|
||||
fn default() -> Self {
|
||||
HttpTransport { connect_timeout: Duration::from_secs(10), stall_timeout: Duration::from_secs(15) }
|
||||
HttpTransport { connect_timeout: Duration::from_secs(10), stall_timeout: Duration::from_secs(15), body_timeout: Duration::from_secs(60) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,7 +128,11 @@ impl Transport for HttpTransport {
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
let mut buf = [0u8; 16 * 1024];
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
if started.elapsed() >= self.body_timeout {
|
||||
return Err(format!("tile not received within {} s", self.body_timeout.as_secs()));
|
||||
}
|
||||
let n = r.read(&mut buf, &limits).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
|
||||
@@ -503,6 +503,36 @@ fn a_huge_announced_tile_length_is_an_error_not_an_allocation() {
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
/// A server that sends a byte now and then never trips the stall timeout, but the whole body has
|
||||
/// a deadline: the network slot is freed.
|
||||
#[test]
|
||||
fn a_trickling_tile_body_gives_up_at_its_deadline() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let url = format!("http://{}/6/25/31.png", listener.local_addr().unwrap());
|
||||
let server = std::thread::spawn(move || {
|
||||
let (mut s, _) = listener.accept().unwrap();
|
||||
let mut r = BufReader::new(s.try_clone().unwrap());
|
||||
let mut line = String::new();
|
||||
while r.read_line(&mut line).unwrap_or(0) > 0 && !line.trim().is_empty() {
|
||||
line.clear();
|
||||
}
|
||||
let _ = s.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 100000\r\n\r\n");
|
||||
for _ in 0..200 {
|
||||
if s.write_all(b"x").and_then(|()| s.flush()).is_err() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
});
|
||||
let t = HttpTransport { body_timeout: Duration::from_millis(600), ..HttpTransport::default() };
|
||||
let ua = vec![("User-Agent", USER_AGENT.to_string())];
|
||||
let start = std::time::Instant::now();
|
||||
let err = t.get(&url, &ua, MAX_TILE_BYTES, &AtomicBool::new(false)).unwrap_err();
|
||||
assert!(err.contains("not received within"), "{err}");
|
||||
assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed());
|
||||
server.join().unwrap();
|
||||
}
|
||||
|
||||
const KEY: &str = "AAPK0123456789abcdef_TEST-key.x";
|
||||
|
||||
fn esri_service(fake: Arc<Fake>, cache: Option<TileCache>) -> TileService {
|
||||
|
||||
@@ -375,3 +375,58 @@ fn a_corrupt_locations_json_is_kept_aside_even_with_old_prefs() {
|
||||
drop(s);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `locations.json` reads well twice (the open's check and parse), then fails: the copy kept aside
|
||||
/// before writing back the valid entries can't be made.
|
||||
#[derive(Clone, Default)]
|
||||
struct ReadsTwice {
|
||||
files: lightcraft_catalog::MemStore,
|
||||
reads: std::sync::Arc<std::sync::atomic::AtomicUsize>,
|
||||
}
|
||||
|
||||
impl lightcraft_catalog::Store for ReadsTwice {
|
||||
fn read(&mut self, name: &str) -> std::io::Result<Option<Vec<u8>>> {
|
||||
if name == "locations.json" && self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 2 {
|
||||
return Err(std::io::Error::other("locked by another process"));
|
||||
}
|
||||
self.files.read(name)
|
||||
}
|
||||
fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
|
||||
self.files.write_atomic(name, data)
|
||||
}
|
||||
fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> {
|
||||
self.files.append(name, data)
|
||||
}
|
||||
fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> {
|
||||
self.files.truncate(name, len)
|
||||
}
|
||||
fn describe(&self) -> String {
|
||||
"reads-twice".into()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_entries_are_never_dropped_without_a_copy() {
|
||||
let files = ReadsTwice::default();
|
||||
let text = serde_json::to_vec(&json!({"version": 1, "locations": [
|
||||
{"id": 1, "name": "Good", "lat": 48.0, "lon": 2.0, "radius": 100.0},
|
||||
{"id": 2, "name": "Bad", "lat": 1e308, "lon": 2.0, "radius": 100.0},
|
||||
]}))
|
||||
.unwrap();
|
||||
files.files.set("locations.json", text.clone());
|
||||
let mut s = Session::new();
|
||||
let stores = crate::library::LibraryStores {
|
||||
dir: "reads-twice".into(),
|
||||
catalog: Box::new(lightcraft_catalog::MemStore::new()),
|
||||
files: Box::new(files.clone()),
|
||||
on_disk: false,
|
||||
};
|
||||
s.open_library_in(stores, true).unwrap();
|
||||
assert_eq!(listed(&mut s).len(), 1);
|
||||
let w = s.take_library_warnings();
|
||||
assert!(w.iter().any(|w| w.contains("couldn't be set aside") && w.contains("won't overwrite")), "{w:?}");
|
||||
assert_eq!(files.files.get("locations.json"), Some(text), "the file with the rejected entry is left as it was");
|
||||
// and a later save says why it doesn't write
|
||||
let l = add(&mut s, json!({"name": "Home", "lat": 1.0, "lon": 1.0}));
|
||||
assert!(l["notSaved"].is_string(), "{l}");
|
||||
}
|
||||
@@ -1551,6 +1551,47 @@ fn map_geotag_writes_gps_to_the_sidecar_and_removing_or_undoing_takes_it_out() {
|
||||
let _ = std::fs::remove_dir_all(&lib);
|
||||
}
|
||||
|
||||
/// A position cleared with automatic writing off still leaves the sidecar when it is saved after
|
||||
/// the library was closed and opened again: which photos' GPS is LightCraft's is kept with the
|
||||
/// library (`prefs.json` `gpsOwned`), not only for the session.
|
||||
#[test]
|
||||
fn a_cleared_position_leaves_the_sidecar_after_a_reopen() {
|
||||
let src = temp_dir("geotag-reopen");
|
||||
let lib = temp_dir("geotag-reopen-lib");
|
||||
write_png(&src.join("g.png"), 9);
|
||||
let mut s = Session::new().with_fs();
|
||||
s.open_library(&lib, false).unwrap();
|
||||
s.execute("library.import", &json!({"paths": [src.to_string_lossy()]})).unwrap();
|
||||
let id = only(&s);
|
||||
let sidecar = src.join("g.xmp");
|
||||
let gps_in = |p: &Path| std::fs::read_to_string(p).ok().and_then(|x| lightcraft_meta::parse_xmp(&x).ok()).and_then(|m| m.metadata.gps);
|
||||
s.execute("photo.setGps", &json!({"ids": [id.0], "lat": 45.0, "lon": 6.0})).unwrap();
|
||||
s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(gps_in(&sidecar).is_some());
|
||||
// cleared, not written (automatic writing is off), and the library closed
|
||||
s.execute("photo.removeGps", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(gps_in(&sidecar).is_some(), "not written yet");
|
||||
drop(s);
|
||||
let mut s = Session::new().with_fs();
|
||||
s.open_library(&lib, false).unwrap();
|
||||
assert!(s.gps_edited.contains(&id), "kept with the library");
|
||||
s.execute("photo.saveMetadataToFile", &json!({"ids": [id.0]})).unwrap();
|
||||
assert!(gps_in(&sidecar).is_none(), "the cleared position leaves the sidecar");
|
||||
drop(s);
|
||||
// a damaged entry costs only itself
|
||||
let prefs = lib.join("prefs.json");
|
||||
let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&prefs).unwrap()).unwrap();
|
||||
v["gpsOwned"] = json!(["x", -1, 1e300, id.0, 987_654_321]);
|
||||
std::fs::write(&prefs, serde_json::to_vec(&v).unwrap()).unwrap();
|
||||
let mut s = Session::new().with_fs();
|
||||
s.open_library(&lib, false).unwrap();
|
||||
assert_eq!(s.gps_edited.iter().copied().collect::<Vec<_>>(), vec![id], "only this library's photos");
|
||||
assert!(s.take_library_warnings().is_empty());
|
||||
drop(s);
|
||||
let _ = std::fs::remove_dir_all(&src);
|
||||
let _ = std::fs::remove_dir_all(&lib);
|
||||
}
|
||||
|
||||
/// A photo whose position LightCraft never touched keeps another app's sidecar GPS when its
|
||||
/// sidecar is rewritten; and photo ids are per library, so a geotag in one library doesn't make
|
||||
/// the same id's photo in the next one claim its sidecar's GPS. Ported from PR #810.
|
||||
|
||||
@@ -161,6 +161,13 @@ fn choose_location(m: &mut crate::state::MapUi, mode: LocationFilter) {
|
||||
m.seen_area = None;
|
||||
}
|
||||
|
||||
/// The pins on the map: none with the Untagged filter (the filmstrip holds the photos without a
|
||||
/// position) or with Hide Pins. Drawing and the drag that moves a pin both use this, so a pin that
|
||||
/// isn't drawn can't be clicked, hovered or dragged.
|
||||
fn shown_points<'a>(points: &'a [MapPoint], map_ui: &crate::state::MapUi) -> &'a [MapPoint] {
|
||||
if map_ui.filter == LocationFilter::Untagged || !map_ui.show_pins { &[] } else { points }
|
||||
}
|
||||
|
||||
/// The location filter's choices as the menus list them: (mode, label).
|
||||
pub struct LocationFilterChoice;
|
||||
|
||||
@@ -523,9 +530,7 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui) {
|
||||
|
||||
// 2. Cluster the pins of the view (world-anchored cells: panning never regroups them)
|
||||
let started = web_time::Instant::now();
|
||||
// Untagged: the filmstrip holds the photos without a position, so no pins
|
||||
// (and Hide Pins: none at all, so none can be clicked, hovered or dragged)
|
||||
let shown: &[MapPoint] = if map_ui.filter == LocationFilter::Untagged || !map_ui.show_pins { &[] } else { &app.map_points.points };
|
||||
let shown = shown_points(&app.map_points.points, &map_ui);
|
||||
let clusters = lightcraft_engine::map::cluster::cluster(shown, &vp, CLUSTER_CELL);
|
||||
app.map_drawn.cluster_ms = started.elapsed().as_secs_f64() * 1e3;
|
||||
app.map_drawn.with_gps = app.map_points.points.len();
|
||||
@@ -630,7 +635,7 @@ fn navigate(
|
||||
// the active saved location's handles come first; then a drag that starts on a single photo's
|
||||
// pin moves it (unless markers are locked); any other drag (the empty map, a cluster) pans
|
||||
let busy = drag_location(app, ui, canvas_response, &vp, (canvas_rect, zone), map_ui);
|
||||
let pins: &[MapPoint] = if map_ui.show_pins { &app.map_points.points } else { &[] };
|
||||
let pins = shown_points(&app.map_points.points, map_ui);
|
||||
let before = lightcraft_engine::map::cluster::cluster(pins, &vp, CLUSTER_CELL);
|
||||
if canvas_response.drag_started() {
|
||||
map_ui.pin_drag = None;
|
||||
|
||||
@@ -347,3 +347,22 @@ fn the_first_showing_fits_the_photos_and_counts_those_without_gps() {
|
||||
assert!(widget(&e, "map:withoutGps").is_none());
|
||||
e.app.run("map.fit", json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// With the Untagged filter no pin is drawn, so none can be dragged: a drag where a pin was pans
|
||||
/// the map and moves no photo (hit testing used to ignore the filter).
|
||||
#[test]
|
||||
fn a_pin_hidden_by_the_untagged_filter_cant_be_dragged() {
|
||||
let (mut h, ids) = demo();
|
||||
view(&mut h, 48.857, 2.32, 14.0);
|
||||
let s = state(&mut h);
|
||||
let from = xy(&pin_of(&s, ids[0]));
|
||||
h.app.run("map.locationFilter", json!({"mode": "untagged"})).unwrap();
|
||||
frames(&mut h, 2);
|
||||
let s = state(&mut h);
|
||||
assert!(pins(&s).is_empty(), "{s}");
|
||||
let before_view = (s["lat"].clone(), s["lon"].clone());
|
||||
drag(&mut h, from, from + egui::vec2(90.0, 50.0));
|
||||
let s = state(&mut h);
|
||||
assert_eq!(gps(&h, ids[0]), Some(PLACES[0]), "the photo didn't move");
|
||||
assert_ne!((s["lat"].clone(), s["lon"].clone()), before_view, "the drag panned");
|
||||
}
|
||||
+4
-3
@@ -55,9 +55,10 @@ As in Lightroom Classic's Map module:
|
||||
wrapped into −180…180. Type a position closer to a pole in the Info panel's GPS field.
|
||||
- **Sidecars.** Positions are written to XMP sidecars as EXIF GPS (`exif:GPSLatitude`, `exif:GPSLongitude`)
|
||||
when sidecars are written (Photo ▸ Save Metadata to File, or at once with automatic XMP writing on). For a
|
||||
photo whose position you set or cleared in LightCraft this session (a drop, a pin move, Remove GPS
|
||||
Coordinates, the Info panel's GPS field), the sidecar takes LightCraft's position as it is: clearing it,
|
||||
or undoing a geotag, removes the GPS from the sidecar. A photo whose position you never touched here keeps
|
||||
photo whose position you set or cleared in LightCraft (a drop, a pin move, Remove GPS Coordinates, the Info
|
||||
panel's GPS field), the sidecar takes LightCraft's position as it is: clearing it, or undoing a geotag,
|
||||
removes the GPS from the sidecar. The library remembers these photos (`prefs.json` `gpsOwned`), so a
|
||||
position cleared before you close it still leaves the sidecar when it is written later. A photo whose position you never touched here keeps
|
||||
whatever GPS another app put in its sidecar, since LightCraft doesn't read GPS from sidecars.
|
||||
|
||||
`map.state` reports the view (`lat`, `lon`, `zoom`, `maxZoom`, `source`, `offline`, `attribution`), the map
|
||||
|
||||
Reference in new issue
Block a user