Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Photos: keywords and place in Info, as icloud.com keeps them

Yashwanth Kamireddid7eaf9606508
diff --git a/.uiverify/photos-info.mjs b/.uiverify/photos-info.mjs
new file mode 100644
index 0000000..ac12cf3
--- /dev/null
+++ b/.uiverify/photos-info.mjs
@@ -0,0 +1,38 @@
+// Info's place and keywords, as icloud.com's Info has them: where it was taken (the coordinates
+// Apple keeps, and the map opened at them); its keywords as chips, × to take one away, a word and
+// Return to add one — the letters typed are words, not the photo's keys.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Photos");
+await page.waitForTimeout(400);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+await page.locator(".px-tile").nth(1).dblclick();
+await page.waitForTimeout(600);
+await page.keyboard.press("i");
+ok((await page.locator(".px-place span").innerText()) === "17.7654° N, 83.3576° E", `the place it was taken ${await page.locator(".px-place span").innerText()}`);
+await page.getByRole("button", { name: "Open in Map" }).click();
+await page.waitForTimeout(100);
+ok((await page.evaluate(() => window.__maps?.at(-1))) === "p2", "Open in Map opens it there");
+ok((await page.locator(".px-chip").allInnerTexts()).join() === "beach", "its keywords, as chips");
+await page.getByLabel("Add a Keyword").click();
+await page.keyboard.type("ferry");
+ok((await page.evaluate(() => (window.__flags ?? []).length)) === 0, "the letters typed are words, not the photo's keys");
+await page.keyboard.press("Enter");
+await page.waitForTimeout(200);
+ok(JSON.stringify(await page.evaluate(() => window.__keywords?.at(-1))) === JSON.stringify({ id: "p2", keywords: ["beach", "ferry"] }),
+ "Return adds the word, and it goes to iCloud");
+ok((await page.locator(".px-chip").allInnerTexts()).join() === "beach,ferry", "shown at once");
+await page.getByRole("button", { name: "Remove beach" }).click();
+await page.waitForTimeout(200);
+ok(JSON.stringify(await page.evaluate(() => window.__keywords?.at(-1))) === JSON.stringify({ id: "p2", keywords: ["ferry"] }), "× takes one away");
+await page.locator(".px-tile").count();
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 7582017..75e5ded 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -312,7 +312,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
width: 4032, height: 3024, duration: null, filename: `IMG_${id}.JPG`, size: 2400000, uti: "public.jpeg",
favorite: false, hidden: false, deleted: false, deletedAt: null, subtype: 0, changeTag: null, ...extra });
const all = (window.__photos ??= [
- P("p1", 1792500000, { favorite: true }), P("p2", 1792400000), P("p3", 1792300000, { kind: "video", duration: 12.4, uti: "public.mpeg-4", filename: "clip.mp4" }),
+ P("p1", 1792500000, { favorite: true }), P("p2", 1792400000, { keywords: ["beach"], latitude: 17.7653751, longitude: 83.357605 }), P("p3", 1792300000, { kind: "video", duration: 12.4, uti: "public.mpeg-4", filename: "clip.mp4" }),
P("p4", 1789900000, { addedAt: 1792700000 }), P("p5", 1789800000, { rating: 5 }), P("p6", 1789700000, { deleted: true, deletedAt: 1792600000, expungeAt: Math.floor(Date.now() / 1000) + 2 * 86400 + 600 }),
]);
const live = all.filter((p) => !p.deleted && !p.hidden);
@@ -366,6 +366,13 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
}
return p;
}
+ case "photo_set_keywords": {
+ (window.__keywords ??= []).push(args);
+ const p = (window.__photos ?? []).find((x) => x.id === args.id);
+ if (p) p.keywords = args.keywords;
+ return p;
+ }
+ case "photo_open_map": (window.__maps ??= []).push(args.id); return null;
case "photo_set_rating": {
(window.__ratings ??= []).push(args);
const p = (window.__photos ?? []).find((x) => x.id === args.id);
diff --git a/Cargo.lock b/Cargo.lock
index daf8e91..56a5b48 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3335,6 +3335,7 @@ dependencies = [
"flate2",
"futures-util",
"jiff",
+ "plist",
"quince-core",
"reqwest 0.12.28",
"serde",
@@ -3363,6 +3364,7 @@ dependencies = [
"futures-util",
"image",
"jiff",
+ "plist",
"quince-auth",
"quince-core",
"quince-icloud",
diff --git a/check.sh b/check.sh
index 6beacd2..6cf8466 100755
--- a/check.sh
+++ b/check.sh
@@ -67,6 +67,7 @@ step "whole photos" node .uiverify/photos-fit.mjs
step "star ratings" node .uiverify/photos-rating.mjs
step "viewer, real sizes" node .uiverify/photos-viewer-real.mjs
step "filmstrip" node .uiverify/photos-strip.mjs
+step "place & keywords" node .uiverify/photos-info.mjs
step "notes delete" node .uiverify/notes-delete.mjs
step "empty today" node .uiverify/reminders-empty.mjs
step "calendar keys" node .uiverify/calendar-keys.mjs
@@ -117,6 +118,7 @@ step "webkit: whole photos" env ENGINE=webkit node .uiverify/photos-fit.mjs
step "webkit: ratings" env ENGINE=webkit node .uiverify/photos-rating.mjs
step "webkit: viewer sizes" env ENGINE=webkit node .uiverify/photos-viewer-real.mjs
step "webkit: filmstrip" env ENGINE=webkit node .uiverify/photos-strip.mjs
+step "webkit: place & keywords" env ENGINE=webkit node .uiverify/photos-info.mjs
step "webkit: delete" env ENGINE=webkit node .uiverify/notes-delete.mjs
step "webkit: row hover" env ENGINE=webkit node .uiverify/row-hover.mjs
step "webkit: fold" env ENGINE=webkit node .uiverify/sidebar-fold.mjs
diff --git a/crates/quince-core/src/photos.rs b/crates/quince-core/src/photos.rs
index a803d07..b9421c4 100644
--- a/crates/quince-core/src/photos.rs
+++ b/crates/quince-core/src/photos.rs
@@ -76,6 +76,14 @@ pub struct Photo {
/// Its star rating, 0 (none) to 5.
#[serde(default)]
pub rating: i64,
+ /// The words it is filed under (`keywordsEnc`).
+ #[serde(default)]
+ pub keywords: Vec<String>,
+ /// Where it was taken, in degrees, when Apple has it (`locationEnc`).
+ #[serde(default)]
+ pub latitude: Option<f64>,
+ #[serde(default)]
+ pub longitude: Option<f64>,
/// Photos' subtype: 1 and 3 mark screenshots and the like (`assetSubtypeV2`).
pub subtype: i64,
/// The asset's change tag, for writing back to it.
@@ -128,7 +136,8 @@ pub enum View {
}
const COLUMNS: &str = "id, master, taken_at, added_at, kind, width, height, duration, filename, \
- size, uti, favorite, hidden, deleted, deleted_at, subtype, change_tag, expunge_at, title, caption, rating";
+ size, uti, favorite, hidden, deleted, deleted_at, subtype, change_tag, expunge_at, title, caption, rating, \
+ keywords, latitude, longitude";
fn row_to_photo(r: &rusqlite::Row<'_>) -> rusqlite::Result<Photo> {
Ok(Photo {
@@ -153,6 +162,12 @@ fn row_to_photo(r: &rusqlite::Row<'_>) -> rusqlite::Result<Photo> {
title: r.get(18)?,
caption: r.get(19)?,
rating: r.get(20)?,
+ keywords: r
+ .get::<_, Option<String>>(21)?
+ .and_then(|k| serde_json::from_str(&k).ok())
+ .unwrap_or_default(),
+ latitude: r.get(22)?,
+ longitude: r.get(23)?,
})
}
@@ -164,8 +179,10 @@ impl Library {
let mut stmt = tx.prepare(
"INSERT INTO photos (id, master, taken_at, added_at, kind, width, height, duration,
filename, size, uti, favorite, hidden, deleted, deleted_at,
- subtype, change_tag, expunge_at, title, caption, rating)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21)
+ subtype, change_tag, expunge_at, title, caption, rating,
+ keywords, latitude, longitude)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21,
+ ?22, ?23, ?24)
ON CONFLICT(id) DO UPDATE SET
master = excluded.master, taken_at = excluded.taken_at,
added_at = excluded.added_at, kind = excluded.kind, width = excluded.width,
@@ -175,7 +192,9 @@ impl Library {
deleted = excluded.deleted, deleted_at = excluded.deleted_at,
subtype = excluded.subtype, change_tag = excluded.change_tag,
expunge_at = excluded.expunge_at, title = excluded.title,
- caption = excluded.caption, rating = excluded.rating",
+ caption = excluded.caption, rating = excluded.rating,
+ keywords = excluded.keywords, latitude = excluded.latitude,
+ longitude = excluded.longitude",
)?;
for p in photos {
stmt.execute(params![
@@ -199,7 +218,11 @@ impl Library {
p.expunge_at,
p.title,
p.caption,
- p.rating
+ p.rating,
+ (!p.keywords.is_empty())
+ .then(|| serde_json::to_string(&p.keywords).unwrap_or_default()),
+ p.latitude,
+ p.longitude
])?;
}
}
@@ -548,6 +571,9 @@ mod tests {
title: None,
caption: None,
rating: 0,
+ keywords: Vec::new(),
+ latitude: None,
+ longitude: None,
}
}
diff --git a/crates/quince-core/src/schema.rs b/crates/quince-core/src/schema.rs
index 90cdf2c..87fc669 100644
--- a/crates/quince-core/src/schema.rs
+++ b/crates/quince-core/src/schema.rs
@@ -467,4 +467,12 @@ pub const MIGRATIONS: &[&str] = &[
ALTER TABLE photos ADD COLUMN rating INTEGER NOT NULL DEFAULT 0;
UPDATE sync_state SET token = NULL WHERE service = 'photos';
"#,
+ // A photo's keywords (a JSON list) and where it was taken; Photos read again so every
+ // photo has its own.
+ r#"
+ ALTER TABLE photos ADD COLUMN keywords TEXT;
+ ALTER TABLE photos ADD COLUMN latitude REAL;
+ ALTER TABLE photos ADD COLUMN longitude REAL;
+ UPDATE sync_state SET token = NULL WHERE service = 'photos';
+ "#,
];
diff --git a/crates/quince-icloud/Cargo.toml b/crates/quince-icloud/Cargo.toml
index 847519e..309fe49 100644
--- a/crates/quince-icloud/Cargo.toml
+++ b/crates/quince-icloud/Cargo.toml
@@ -12,6 +12,7 @@ serde.workspace = true
serde_json.workspace = true
thiserror = "2"
jiff = "0.2.37"
+plist = "1.10"
base64 = "0.22"
flate2 = "1"
uuid = { workspace = true }
diff --git a/crates/quince-icloud/src/photos.rs b/crates/quince-icloud/src/photos.rs
index 7848ae6..14c1823 100644
--- a/crates/quince-icloud/src/photos.rs
+++ b/crates/quince-icloud/src/photos.rs
@@ -92,6 +92,45 @@ fn decoded(record: &Value, name: &str) -> Option<String> {
String::from_utf8(bytes).ok().filter(|s| !s.is_empty())
}
+/// A field Photos keeps as a binary property list, base64'd: keywords, a location.
+fn plist_field(record: &Value, name: &str) -> Option<plist::Value> {
+ let v = record.pointer(&format!("/fields/{name}/value"))?.as_str()?;
+ let bytes = base64::engine::general_purpose::STANDARD.decode(v).ok()?;
+ plist::from_bytes(&bytes).ok()
+}
+
+/// The words a photo is filed under: `keywordsEnc`, a list of strings.
+fn keywords_of(asset: &Value) -> Vec<String> {
+ plist_field(asset, "keywordsEnc")
+ .and_then(|v| v.into_array())
+ .map(|a| {
+ a.into_iter()
+ .filter_map(plist::Value::into_string)
+ .filter(|k| !k.trim().is_empty())
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+/// Where a photo was taken: `locationEnc` (or `locationV2Enc`), `lat` and `lon` in degrees.
+/// Apple marks no fix with values out of range; those are not a place.
+fn location_of(asset: &Value) -> Option<(f64, f64)> {
+ let d = plist_field(asset, "locationV2Enc")
+ .or_else(|| plist_field(asset, "locationEnc"))?
+ .into_dictionary()?;
+ let deg = |k: &str| {
+ d.get(k).and_then(|v| {
+ v.as_real()
+ .or_else(|| v.as_signed_integer().map(|i| i as f64))
+ })
+ };
+ let (lat, lon) = (deg("lat")?, deg("lon")?);
+ ((-90.0..=90.0).contains(&lat)
+ && (-180.0..=180.0).contains(&lon)
+ && !(lat == 0.0 && lon == 0.0))
+ .then_some((lat, lon))
+}
+
fn millis(record: &Value, name: &str) -> Option<i64> {
record
.pointer(&format!("/fields/{name}/value"))
@@ -161,6 +200,9 @@ pub fn photo_of(asset: &Value, master: &Value) -> Option<Photo> {
title: decoded(asset, "captionEnc"),
caption: decoded(asset, "extendedDescEnc"),
rating: field::int(asset, "rating").unwrap_or(0).clamp(0, 5),
+ keywords: keywords_of(asset),
+ latitude: location_of(asset).map(|l| l.0),
+ longitude: location_of(asset).map(|l| l.1),
expunge_at: (field::int(asset, "isDeleted") == Some(1))
.then(|| millis(asset, "dateExpunged"))
.flatten(),
@@ -189,6 +231,10 @@ fn with_asset(mut p: Photo, asset: &Value) -> Photo {
p.title = decoded(asset, "captionEnc");
p.caption = decoded(asset, "extendedDescEnc");
p.rating = field::int(asset, "rating").unwrap_or(0).clamp(0, 5);
+ p.keywords = keywords_of(asset);
+ if let Some((lat, lon)) = location_of(asset) {
+ (p.latitude, p.longitude) = (Some(lat), Some(lon));
+ }
p.expunge_at = if p.deleted {
millis(asset, "dateExpunged").or(p.expunge_at)
} else {
@@ -420,6 +466,34 @@ pub async fn set_rating(
.await
}
+/// A photo's keywords set, as icloud.com's Info sets them: `keywordsEnc`, a binary property
+/// list of the words, base64'd, against the asset's change tag. Answers the asset as it now is.
+pub async fn set_keywords(
+ http: &reqwest::Client,
+ ckdatabasews_root: &str,
+ params: Vec<(String, String)>,
+ asset: &str,
+ change_tag: Option<&str>,
+ keywords: &[String],
+) -> Result<Value> {
+ let list = plist::Value::Array(keywords.iter().cloned().map(plist::Value::String).collect());
+ let mut bytes = Vec::new();
+ plist::to_writer_binary(&mut bytes, &list)
+ .map_err(|e| crate::Error::Protocol(format!("keywords could not be written: {e}")))?;
+ let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
+ client
+ .update_record(
+ ZONE,
+ asset,
+ "CPLAsset",
+ change_tag,
+ serde_json::json!({
+ "keywordsEnc": { "value": base64::engine::general_purpose::STANDARD.encode(bytes) }
+ }),
+ )
+ .await
+}
+
/// An album's name as Photos writes it: base64 of its UTF-8 bytes, untyped.
fn album_name(name: &str) -> String {
base64::engine::general_purpose::STANDARD.encode(name.as_bytes())
@@ -781,4 +855,21 @@ mod tests {
.unwrap();
assert!(lib.photo("A1").unwrap().is_none());
}
+
+ /// Keywords and a place, from the bytes Apple holds for his photo titled "loupe": a binary
+ /// plist list of words, and one of where (`lat`, `lon`) with Apple's marks for no fix.
+ #[test]
+ fn keywords_and_place_are_read_as_apple_keeps_them() {
+ let asset = json!({"fields": {
+ "keywordsEnc": {"value": "YnBsaXN0MDChAVVsb3VwZQgKAAAAAAAAAQEAAAAAAAAAAgAAAAAAAAAAAAAAAAAAABA="},
+ "locationEnc": {"value": "YnBsaXN0MDDYAQIDBAUGBwgJCgsMDQ4PEFNhbHRWY291cnNlV2hvcnpBY2NXdmVydEFjY1NsYXRTbG9uVXNwZWVkWXRpbWVzdGFtcBAAE///////////E///////////E///////////I0Axw++gAAAAI0BU1uMAAAAAE///////////XxAYMjAyNi0xMC0xOFQxNTo0MDo0NS41ODJaCBkdJCw0ODxCTE5XYGlye4QAAAAAAAABAQAAAAAAAAARAAAAAAAAAAAAAAAAAAAAnw=="}
+ }});
+ assert_eq!(keywords_of(&asset), ["loupe"]);
+ let (lat, lon) = location_of(&asset).unwrap();
+ assert!((lat - 17.765_375).abs() < 1e-5 && (lon - 83.357_605).abs() < 1e-5);
+ assert!(
+ location_of(&json!({"fields": {}})).is_none(),
+ "no place is no place"
+ );
+ }
}
diff --git a/probe/Cargo.toml b/probe/Cargo.toml
index 5a71ca0..b70dcb4 100644
--- a/probe/Cargo.toml
+++ b/probe/Cargo.toml
@@ -19,6 +19,7 @@ jiff = "0.2.37"
base64 = "0.22"
uuid.workspace = true
flate2 = "1"
+plist = "1.10"
quince-auth = { path = "../crates/quince-auth" }
quince-core = { path = "../crates/quince-core" }
quince-icloud = { path = "../crates/quince-icloud" }
diff --git a/probe/examples/photos_keywords_roundtrip.rs b/probe/examples/photos_keywords_roundtrip.rs
new file mode 100644
index 0000000..9131bd0
--- /dev/null
+++ b/probe/examples/photos_keywords_roundtrip.rs
@@ -0,0 +1,58 @@
+//! Live, on a wallpaper he named as a throwaway: keywords set through Quince's own
+//! set_keywords, read back from Apple, then cleared. First checks that the binary plist Quince
+//! writes for ["loupe"] is byte for byte the one Apple wrote on his photo.
+use anyhow::{anyhow, Result};
+use base64::Engine;
+use quince_icloud::photos::{self, CONTAINER, ZONE};
+
+#[tokio::main]
+async fn main() -> Result<()> {
+ let apples = "YnBsaXN0MDChAVVsb3VwZQgKAAAAAAAAAQEAAAAAAAAAAgAAAAAAAAAAAAAAAAAAABA=";
+ let mut ours = Vec::new();
+ plist::to_writer_binary(
+ &mut ours,
+ &plist::Value::Array(vec![plist::Value::String("loupe".into())]),
+ )?;
+ println!(
+ "same bytes as Apple's: {}",
+ base64::engine::general_purpose::STANDARD.encode(&ours) == apples
+ );
+ let asset = std::env::args().nth(1).ok_or_else(|| anyhow!("asset id"))?;
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let ck = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &ck, CONTAINER, p.clone());
+ let words = |r: &serde_json::Value| -> Option<plist::Value> {
+ let v = r.pointer("/fields/keywordsEnc/value")?.as_str()?;
+ plist::from_bytes(&base64::engine::general_purpose::STANDARD.decode(v).ok()?).ok()
+ };
+ let before = zc
+ .lookup_record(ZONE, &asset)
+ .await?
+ .ok_or_else(|| anyhow!("gone"))?;
+ println!("before: {:?}", words(&before));
+ let tag = before.get("recordChangeTag").and_then(|t| t.as_str());
+ photos::set_keywords(
+ &http,
+ &ck,
+ p.clone(),
+ &asset,
+ tag,
+ &["spring".into(), "quince test ✿".into()],
+ )
+ .await?;
+ let now = zc.lookup_record(ZONE, &asset).await?.unwrap();
+ println!("set: {:?}", words(&now));
+ let tag = now.get("recordChangeTag").and_then(|t| t.as_str());
+ photos::set_keywords(&http, &ck, p.clone(), &asset, tag, &[]).await?;
+ let back = zc.lookup_record(ZONE, &asset).await?.unwrap();
+ println!("clear: {:?}", words(&back));
+ Ok(())
+}
diff --git a/probe/examples/plist_peek.rs b/probe/examples/plist_peek.rs
new file mode 100644
index 0000000..9c9a047
--- /dev/null
+++ b/probe/examples/plist_peek.rs
@@ -0,0 +1,37 @@
+//! Read-only: what keywordsEnc and locationEnc hold, decoded, for one photo.
+use anyhow::{anyhow, Result};
+use base64::Engine;
+#[tokio::main]
+async fn main() -> Result<()> {
+ let asset = std::env::args().nth(1).ok_or_else(|| anyhow!("asset id"))?;
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let ck = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ck"))?;
+ let zc = quince_icloud::cloudkit::ZoneClient::new(
+ client.http(),
+ &ck,
+ quince_icloud::photos::CONTAINER,
+ client.service_params(),
+ );
+ let r = zc
+ .lookup_record(quince_icloud::photos::ZONE, &asset)
+ .await?
+ .ok_or_else(|| anyhow!("gone"))?;
+ for f in ["keywordsEnc", "locationEnc", "locationV2Enc"] {
+ if let Some(v) = r
+ .pointer(&format!("/fields/{f}/value"))
+ .and_then(|v| v.as_str())
+ {
+ let bytes = base64::engine::general_purpose::STANDARD.decode(v)?;
+ let value: plist::Value = plist::from_bytes(&bytes)?;
+ println!("{f}: {value:?}");
+ }
+ }
+ Ok(())
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 4a9d00d..a87dc2c 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -3785,6 +3785,8 @@ fn main() {
photos::photos_album_remove,
photos::photo_set_text,
photos::photo_set_rating,
+ photos::photo_set_keywords,
+ photos::photo_open_map,
photos::photo_download,
note_table_add_row,
note_table_remove,
diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rs
index 6ee88ab..c01ac2c 100644
--- a/src-tauri/src/photos.rs
+++ b/src-tauri/src/photos.rs
@@ -633,6 +633,78 @@ pub async fn photo_play(id: String, app: AppHandle, data: State<'_, Data>) -> Ui
.map_err(|e| format!("No app on this computer opens that video: {e}"))
}
+/// A photo's keywords, as typed in its Info: each trimmed, empty and repeated ones dropped,
+/// Apple's answer taken at once.
+#[tauri::command]
+pub async fn photo_set_keywords(
+ id: String,
+ keywords: Vec<String>,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<Photo> {
+ let mut words: Vec<String> = Vec::new();
+ for k in keywords {
+ let k = k.trim().to_string();
+ if !k.is_empty() && !words.iter().any(|w| w.eq_ignore_ascii_case(&k)) {
+ words.push(k);
+ }
+ }
+ let _one = crate::PHOTOS_PASS.lock().await;
+ let mut photo = data
+ .0
+ .lock()
+ .await
+ .photo(&id)
+ .map_err(|e| e.to_string())?
+ .ok_or("That photo is no longer in the library.")?;
+ let (http, root, params) = crate::cloudkit_context(&auth).await?;
+ let answer = quince_icloud::photos::set_keywords(
+ &http,
+ &root,
+ params,
+ &id,
+ photo.change_tag.as_deref(),
+ &words,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ photo.keywords = words;
+ photo.change_tag = answer
+ .get("recordChangeTag")
+ .and_then(serde_json::Value::as_str)
+ .map(str::to_string)
+ .or(photo.change_tag);
+ data.0
+ .lock()
+ .await
+ .put_photos(std::slice::from_ref(&photo))
+ .map_err(|e| e.to_string())?;
+ Ok(photo)
+}
+
+/// Where a photo was taken, opened in a map in the browser: OpenStreetMap at its coordinates.
+/// Apple's place names come from Apple Maps, which is not here; the place itself is.
+#[tauri::command]
+pub async fn photo_open_map(id: String, app: AppHandle, data: State<'_, Data>) -> UiResult<()> {
+ let photo = data
+ .0
+ .lock()
+ .await
+ .photo(&id)
+ .map_err(|e| e.to_string())?
+ .ok_or("That photo is no longer in the library.")?;
+ let (Some(lat), Some(lon)) = (photo.latitude, photo.longitude) else {
+ return Err("This photo has no place.".into());
+ };
+ use tauri_plugin_opener::OpenerExt;
+ app.opener()
+ .open_url(
+ format!("https://www.openstreetmap.org/?mlat={lat:.6}&mlon={lon:.6}#map=16/{lat:.6}/{lon:.6}"),
+ None::<&str>,
+ )
+ .map_err(|e| format!("No browser on this computer opened the map: {e}"))
+}
+
/// How many photos each view holds. Asked after every sync, which is also when an upload queue
/// paused for a session coming back starts again.
#[tauri::command]
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 4ebc0a5..f008ce0 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -103,6 +103,8 @@ export const api = {
/** Title and caption together, as Info saves them. */
photoSetText: (id: string, title: string, caption: string) => invoke<Photo>("photo_set_text", { id, title, caption }),
photoSetRating: (id: string, rating: number) => invoke<Photo>("photo_set_rating", { id, rating }),
+ photoSetKeywords: (id: string, keywords: string[]) => invoke<Photo>("photo_set_keywords", { id, keywords }),
+ photoOpenMap: (id: string) => invoke<void>("photo_open_map", { id }),
/** Photos and videos (or folders of them) into the library. Answers the batch; progress
* arrives as PHOTO_UPLOAD events, in the same shape as Drive's. */
/** Into the library, and into `album` too when one is open. */
@@ -590,6 +592,10 @@ export type Photo = {
caption?: string | null;
/** Its star rating, 0 (none) to 5. */
rating?: number;
+ keywords?: string[];
+ /** Where it was taken, in degrees. */
+ latitude?: number | null;
+ longitude?: number | null;
subtype: number;
changeTag: string | null;
};
diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsx
index e21d2d0..5a405bc 100644
--- a/src/screens/PhotosView.tsx
+++ b/src/screens/PhotosView.tsx
@@ -69,6 +69,9 @@ const pickedWords = (list: Photo[]) => {
type Flag = "favorite" | "deleted" | "hidden" | "expunged";
+/** A coordinate as a map gives it: 17.7654° N. */
+const degrees = (v: number, plus: string, minus: string) => `${Math.abs(v).toFixed(4)}° ${v >= 0 ? plus : minus}`;
+
/** How a view is sorted, as Photos offers it: by the date taken or the date added, either way. */
type Sort = { by: "taken" | "added"; oldest: boolean };
const SORTS_KEY = "quince.photos.sort";
@@ -1148,6 +1151,17 @@ export function PhotosView() {
if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;
void words(p, titleField.current?.value ?? p.title ?? "", captionField.current?.value ?? p.caption ?? "");
};
+ const keywords = async (p: Photo, words: string[]) => {
+ const before = photos;
+ setPhotos((all) => (all ?? []).map((x) => (x.id === p.id ? { ...x, keywords: words } : x)));
+ try {
+ await api.photoSetKeywords(p.id, words);
+ } catch (e) {
+ setPhotos(before);
+ setError(messageOf(e));
+ }
+ };
+
const rate = async (p: Photo, rating: number) => {
const before = photos;
const leaves = view === "rated" && rating === 0;
@@ -1852,6 +1866,58 @@ export function PhotosView() {
<dd>{shown.size >= 1024 * 1024 ? `${(shown.size / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(shown.size / 1024))} KB`}</dd>
</>
) : null}
+ {shown.latitude != null && shown.longitude != null && (
+ <>
+ <dt>Place</dt>
+ <dd className="px-place">
+ <span>{degrees(shown.latitude, "N", "S")}, {degrees(shown.longitude, "E", "W")}</span>
+ <button className="px-link" onClick={() => void api.photoOpenMap(shown.id).catch((e) => setError(messageOf(e)))}>
+ Open in Map
+ </button>
+ </dd>
+ </>
+ )}
+ {/* Keywords, as Info keeps them: each its own chip, taken away with ×; a word
+ typed and Return adds one. */}
+ <dt>Keywords</dt>
+ <dd className="px-words-field">
+ {(shown.keywords ?? []).map((k) => (
+ <span key={k} className="px-chip">
+ {k}
+ {view !== "recentlyDeleted" && (
+ <button
+ aria-label={`Remove ${k}`}
+ onClick={() => void keywords(shown, (shown.keywords ?? []).filter((x) => x !== k))}
+ >
+ <X size={10} strokeWidth={3} aria-hidden="true" />
+ </button>
+ )}
+ </span>
+ ))}
+ {view !== "recentlyDeleted" && (
+ <input
+ key={`k${shown.id}`}
+ className="px-keyword-field"
+ aria-label="Add a Keyword"
+ placeholder="Add a Keyword"
+ maxLength={100}
+ onKeyDown={(e) => {
+ const word = e.currentTarget.value.trim();
+ if ((e.key === "Enter" || e.key === ",") && word) {
+ e.preventDefault();
+ e.currentTarget.value = "";
+ if (!(shown.keywords ?? []).some((x) => x.toLowerCase() === word.toLowerCase())) {
+ void keywords(shown, [...(shown.keywords ?? []), word]);
+ }
+ } else if (e.key === "Escape") {
+ e.currentTarget.value = "";
+ e.currentTarget.blur();
+ e.stopPropagation();
+ }
+ }}
+ />
+ )}
+ </dd>
</dl>
)}
</div>
diff --git a/src/styles/photos.css b/src/styles/photos.css
index adf44a7..d47b951 100644
--- a/src/styles/photos.css
+++ b/src/styles/photos.css
@@ -698,3 +698,44 @@
.px-slip img { width: 100%; height: 100%; object-fit: cover; display: block; }
.px-slip.is-shown { width: 54px; top: 0; height: 44px; opacity: 1; box-shadow: 0 0 0 2px var(--accent); }
@media (prefers-reduced-motion: reduce) { .px-strip-run { transition: none; } }
+
+/* Info's place and keywords. */
+.px-place { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; font-variant-numeric: tabular-nums; }
+.px-link { padding: 0; border: 0; background: none; color: var(--accent); font: inherit; cursor: default; }
+.px-link:hover { text-decoration: underline; }
+.px-words-field { display: flex; flex-wrap: wrap; gap: 5px; align-items: center; margin-top: 4px; }
+.px-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 2px 6px 2px 8px;
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--text) 9%, transparent);
+ font-size: var(--t-12, 12px);
+}
+.px-chip button {
+ display: grid;
+ place-items: center;
+ width: 14px;
+ height: 14px;
+ padding: 0;
+ border: 0;
+ border-radius: 50%;
+ background: transparent;
+ color: var(--text-2);
+ cursor: default;
+}
+.px-chip button:hover { background: color-mix(in srgb, var(--text) 14%, transparent); color: var(--text); }
+.px-keyword-field {
+ flex: 1;
+ min-width: 90px;
+ padding: 3px 4px;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: var(--text);
+ font: inherit;
+ font-size: var(--t-12, 12px);
+ outline: none;
+}
+.px-keyword-field:focus { box-shadow: 0 0 0 2px var(--accent-ring); }