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.

Notes: a save keeps formatting changed elsewhere — a line not restyled here keeps Apple's current formatting, so a tick or bold made on the phone while the note was open is not undone (verified live)

Yashwanth Kamireddi152f7422f944
diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rs
index 386aba7..1c0c0d6 100644
--- a/crates/quince-icloud/src/ckdocument.rs
+++ b/crates/quince-icloud/src/ckdocument.rs
@@ -1065,6 +1065,109 @@ pub fn replace_rich_in_base64(original: &str, text: &str, runs: &[Run]) -> Optio
Some(B64.encode(gzip(&set_runs(&replaced, runs)?)))
}
+/// Each paragraph of `text` — its text with its newline — and the runs over it.
+fn paragraphs_of(text: &str, runs: &[Run]) -> Vec<(String, Vec<Run>)> {
+ let units: Vec<u16> = text.encode_utf16().collect();
+ let mut per: Vec<&Run> = Vec::with_capacity(units.len());
+ for r in runs {
+ for _ in 0..r.length {
+ per.push(r);
+ }
+ }
+ let mut out = Vec::new();
+ let mut start = 0usize;
+ for i in 0..=units.len() {
+ let end = i == units.len() || units[i] == u16::from(b'\n');
+ if !end {
+ continue;
+ }
+ let stop = if i < units.len() { i + 1 } else { i };
+ if stop == start && i == units.len() {
+ break;
+ }
+ let mut pruns: Vec<Run> = Vec::new();
+ for k in start..stop {
+ let Some(r) = per.get(k) else { break };
+ match pruns.last_mut() {
+ Some(last)
+ if *last
+ == Run {
+ length: last.length,
+ ..(*r).clone()
+ } =>
+ {
+ last.length += 1
+ }
+ _ => pruns.push(Run {
+ length: 1,
+ ..(*r).clone()
+ }),
+ }
+ }
+ out.push((String::from_utf16_lossy(&units[start..stop]), pruns));
+ start = stop;
+ }
+ out
+}
+
+/// The formatting to write: `mine` — what the editor shows over the text being saved —
+/// except on any paragraph this person did not restyle, which keeps the formatting Apple
+/// holds now. So a line ticked, unticked or made bold on the phone while the note was open
+/// here keeps that, unless it was restyled here too.
+///
+/// Paragraphs are matched by their text, in order: `base` is the formatting the editor began
+/// from, `theirs` Apple's now. A paragraph whose text is not found in both is mine as it is.
+#[must_use]
+pub fn keep_their_formatting(
+ base_text: &str,
+ base_runs: &[Run],
+ theirs_text: &str,
+ theirs_runs: &[Run],
+ text: &str,
+ mine: &[Run],
+) -> Vec<Run> {
+ let fits = |t: &str, r: &[Run]| {
+ r.iter().map(|x| x.length).sum::<u64>() == t.encode_utf16().count() as u64
+ };
+ if !fits(base_text, base_runs) || !fits(theirs_text, theirs_runs) || !fits(text, mine) {
+ return mine.to_vec();
+ }
+ let take = |list: Vec<(String, Vec<Run>)>| {
+ let mut by: std::collections::HashMap<String, std::collections::VecDeque<Vec<Run>>> =
+ std::collections::HashMap::new();
+ for (t, r) in list {
+ by.entry(t).or_default().push_back(r);
+ }
+ by
+ };
+ let mut base = take(paragraphs_of(base_text, base_runs));
+ let mut theirs = take(paragraphs_of(theirs_text, theirs_runs));
+ let mut out: Vec<Run> = Vec::new();
+ for (t, my_runs) in paragraphs_of(text, mine) {
+ let b = base.get_mut(&t).and_then(|q| q.pop_front());
+ let th = theirs.get_mut(&t).and_then(|q| q.pop_front());
+ let chosen = match (b, th) {
+ (Some(b), Some(th)) if b == my_runs && th != b => th,
+ _ => my_runs,
+ };
+ for r in chosen {
+ match out.last_mut() {
+ Some(last)
+ if *last
+ == Run {
+ length: last.length,
+ ..r.clone()
+ } =>
+ {
+ last.length += r.length
+ }
+ _ => out.push(r),
+ }
+ }
+ }
+ out
+}
+
/// `runs`, which describe `from`, laid over `to` — the same text with one stretch changed,
/// as another device's edit merged in changes it. The stretch that is new takes the setting
/// of what is just before it.
@@ -2769,6 +2872,43 @@ mod run_tests {
);
}
+ /// The phone ticked "Milk" while the note was open here; here, a line was typed at the
+ /// end. The save keeps the phone's tick — this window never restyled that line — and a
+ /// line restyled here takes this window's style.
+ #[test]
+ fn a_tick_made_elsewhere_survives_a_save_here() {
+ let item = |len: u64, done: bool| Run {
+ length: len,
+ style: Some(103),
+ checked: Some(done),
+ ..body(len)
+ };
+ let base_text = "Milk\nEggs\n";
+ let base = vec![item(5, false), item(5, false)];
+ let theirs = vec![item(5, true), item(5, false)];
+ let text = "Milk\nEggs\nJam";
+ let mine = vec![
+ item(5, false),
+ Run {
+ length: 5,
+ style: Some(1),
+ ..body(5)
+ },
+ body(3),
+ ];
+ let out = keep_their_formatting(base_text, &base, base_text, &theirs, text, &mine);
+ let read: Vec<(u64, Option<u64>, Option<bool>)> =
+ out.iter().map(|r| (r.length, r.style, r.checked)).collect();
+ assert_eq!(
+ read,
+ [
+ (5, Some(103), Some(true)),
+ (5, Some(1), None),
+ (3, None, None)
+ ]
+ );
+ }
+
#[test]
fn runs_follow_a_merged_edit() {
let runs = vec![
diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rs
index f4b7e2a..288f1ae 100644
--- a/crates/quince-icloud/src/notes.rs
+++ b/crates/quince-icloud/src/notes.rs
@@ -474,7 +474,17 @@ pub async fn edit_cloudkit_from(
base: Option<&str>,
body: &str,
) -> Result<String> {
- edit_rich_cloudkit_from(http, ckdatabasews_root, params, note, base, body, None).await
+ edit_rich_cloudkit_from(
+ http,
+ ckdatabasews_root,
+ params,
+ note,
+ base,
+ body,
+ None,
+ None,
+ )
+ .await
}
/// [`edit_cloudkit_from`], with the note's formatting as an editor shows it: `runs` describe
@@ -488,6 +498,7 @@ pub async fn edit_rich_cloudkit_from(
base: Option<&str>,
body: &str,
runs: Option<&[crate::ckdocument::Run]>,
+ base_runs: Option<&[crate::ckdocument::Run]>,
) -> Result<String> {
let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);
for _ in 0..3 {
@@ -522,6 +533,18 @@ pub async fn edit_rich_cloudkit_from(
let rewritten = match runs {
Some(runs) => {
let laid = if target == body { runs.to_vec() } else { crate::ckdocument::carry_runs(body, runs, &target) };
+ // Lines not restyled here keep what Apple holds — a tick made on the phone.
+ let laid = match (base, base_runs) {
+ (Some(base), Some(base_runs)) => crate::ckdocument::keep_their_formatting(
+ base,
+ base_runs,
+ &theirs,
+ &crate::ckdocument::runs_from_base64(encoded),
+ &target,
+ &laid,
+ ),
+ _ => laid,
+ };
crate::ckdocument::replace_rich_in_base64(encoded, &target, &laid)
}
None => crate::ckdocument::replace_text_in_base64(encoded, &target),
diff --git a/probe/examples/notes_branch_live.rs b/probe/examples/notes_branch_live.rs
index 7fb9896..b08c7e4 100644
--- a/probe/examples/notes_branch_live.rs
+++ b/probe/examples/notes_branch_live.rs
@@ -84,6 +84,7 @@ async fn main() -> Result<()> {
Some(&original),
&edited,
None,
+ None,
)
.await?;
let back = zc.lookup_record("Notes", &guid).await?.unwrap();
diff --git a/probe/examples/notes_rich_save.rs b/probe/examples/notes_rich_save.rs
index f7b775a..c1ef715 100644
--- a/probe/examples/notes_rich_save.rs
+++ b/probe/examples/notes_rich_save.rs
@@ -94,6 +94,7 @@ async fn main() -> Result<()> {
Some(body),
text,
Some(&runs),
+ None,
)
.await?;
let back = zc.lookup_record("Notes", &guid).await?.unwrap();
diff --git a/probe/examples/notes_table_edit_live.rs b/probe/examples/notes_table_edit_live.rs
index bb161d6..501a10e 100644
--- a/probe/examples/notes_table_edit_live.rs
+++ b/probe/examples/notes_table_edit_live.rs
@@ -83,6 +83,7 @@ async fn main() -> Result<()> {
Some(&original),
&edited,
None,
+ None,
)
.await?;
let back = zc.lookup_record("Notes", &guid).await?.unwrap();
diff --git a/probe/examples/notes_tick_merge_live.rs b/probe/examples/notes_tick_merge_live.rs
new file mode 100644
index 0000000..e3cab4b
--- /dev/null
+++ b/probe/examples/notes_tick_merge_live.rs
@@ -0,0 +1,136 @@
+//! Live, throwaway note only: a checklist saved as the editor saves it, one line then ticked
+//! as another device ticks it, then a save from an editor that never saw the tick — the tick
+//! must survive — and the note moved to Recently Deleted.
+use anyhow::{anyhow, Result};
+use quince_icloud::ckdocument::{runs_from_base64, Run};
+#[tokio::main]
+async fn main() -> Result<()> {
+ 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 root = client
+ .session()
+ .service_url("ckdatabasews")
+ .ok_or_else(|| anyhow!("no ckdatabasews"))?;
+ let (http, p) = (client.http().clone(), client.service_params());
+ let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());
+ let body = "Quince tick test\nplain";
+ let guid =
+ quince_icloud::notes::create_cloudkit(&http, &root, p.clone(), None, body, None).await?;
+ let note = quince_core::notes::Note {
+ guid: guid.clone(),
+ folder_guid: None,
+ title: "Quince tick test".into(),
+ snippet: None,
+ body: None,
+ locked: false,
+ pinned: false,
+ created_at: None,
+ modified_at: None,
+ editable: true,
+ etag: None,
+ runs: None,
+ };
+ let show = |r: &serde_json::Value| {
+ runs_from_base64(
+ r["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .unwrap_or(""),
+ )
+ .iter()
+ .map(|x| {
+ format!(
+ "{}:{:?}{}",
+ x.length,
+ x.style,
+ x.checked.map(|c| if c { "✓" } else { "○" }).unwrap_or("")
+ )
+ })
+ .collect::<Vec<_>>()
+ .join(" ")
+ };
+ let text = "Quince tick test\nMilk\nEggs";
+ let plain = |n: u64| Run {
+ length: n,
+ ..Run::default()
+ };
+ let item = |n: u64| Run {
+ style: Some(103),
+ checked: Some(false),
+ ..plain(n)
+ };
+ let runs = vec![
+ Run {
+ style: Some(0),
+ ..plain(17)
+ },
+ item(5),
+ item(4),
+ ];
+ quince_icloud::notes::edit_rich_cloudkit_from(
+ &http,
+ &root,
+ p.clone(),
+ &note,
+ Some(body),
+ text,
+ Some(&runs),
+ None,
+ )
+ .await?;
+ // Another device ticks Milk.
+ quince_icloud::notes::set_paragraph_cloudkit(
+ &http,
+ &root,
+ p.clone(),
+ &note,
+ 17,
+ quince_icloud::ckdocument::ParagraphChange::Checked(true),
+ Some("Milk"),
+ )
+ .await?;
+ // This window, which never saw the tick, adds a line.
+ let typed = "Quince tick test\nMilk\nEggs\nJam";
+ let mine = vec![
+ Run {
+ style: Some(0),
+ ..plain(17)
+ },
+ item(5),
+ item(5),
+ item(3),
+ ];
+ quince_icloud::notes::edit_rich_cloudkit_from(
+ &http,
+ &root,
+ p.clone(),
+ &note,
+ Some(text),
+ typed,
+ Some(&mine),
+ Some(&runs),
+ )
+ .await?;
+ let back = zc.lookup_record("Notes", &guid).await?.unwrap();
+ let got = runs_from_base64(
+ back["fields"]["TextDataEncrypted"]["value"]
+ .as_str()
+ .unwrap_or(""),
+ );
+ println!("runs back: {}", show(&back));
+ let milk = got
+ .iter()
+ .scan(0u64, |at, r| {
+ let s = *at;
+ *at += r.length;
+ Some((s, r.clone()))
+ })
+ .find(|(s, _)| *s == 17)
+ .map(|(_, r)| r.checked);
+ println!("Milk still ticked: {:?}", milk);
+ quince_icloud::notes::delete_cloudkit(&http, &root, p.clone(), &note).await?;
+ println!("moved to Recently Deleted");
+ Ok(())
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 1af82a3..da4968f 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1132,6 +1132,9 @@ async fn note_save(
base: Option<String>,
// The note's formatting, when it is edited formatted: runs over `body`.
runs: Option<Vec<quince_icloud::ckdocument::Run>>,
+ // The formatting the editor began from, over `base`: a line not restyled since keeps
+ // what Apple holds now, so a tick made on the phone is not undone.
+ base_runs: Option<Vec<quince_icloud::ckdocument::Run>>,
auth: State<'_, Auth>,
data: State<'_, Data>,
) -> UiResult<String> {
@@ -1150,6 +1153,7 @@ async fn note_save(
base.as_deref(),
&body,
runs.as_deref(),
+ base_runs.as_deref(),
)
.await
.map_err(|e| e.to_string())?;
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 86a1d7a..78feb7f 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -144,8 +144,13 @@ export const api = {
*/
noteBody: (guid: string) => invoke<string | null>("note_body", { guid }),
/** Answers with the text Apple now holds — ours, or ours combined with another device's. */
- noteSave: (guid: string, body: string, base: string | null, runs: import("../screens/notes/Formatted").Run[] | null = null) =>
- invoke<string>("note_save", { guid, body, base, runs }),
+ noteSave: (
+ guid: string,
+ body: string,
+ base: string | null,
+ runs: import("../screens/notes/Formatted").Run[] | null = null,
+ baseRuns: import("../screens/notes/Formatted").Run[] | null = null,
+ ) => invoke<string>("note_save", { guid, body, base, runs, baseRuns }),
noteCreate: (folderGuid: string | null, body: string) =>
invoke<string>("note_create", { folderGuid, body }),
noteDelete: (guid: string) => invoke<void>("note_delete", { guid }),
diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsx
index 4e755f7..1ba67c2 100644
--- a/src/screens/NotesView.tsx
+++ b/src/screens/NotesView.tsx
@@ -250,7 +250,7 @@ export function NotesView() {
* The text Apple last confirmed for the open note: what an edit began from. Sent with each
* save, so the save can tell an edit made on another device since and keep both.
*/
- const base = useRef<{ guid: string; text: string } | null>(null);
+ const base = useRef<{ guid: string; text: string; runs?: Run[] | null } | null>(null);
/** One save at a time: a second, started while the first was out, could land last with
* older text. Saves chain behind this. */
const inFlight = useRef<Promise<void>>(Promise.resolve());
@@ -261,13 +261,15 @@ export function NotesView() {
if (!next) return;
pending.current = null;
const from = base.current?.guid === next.guid ? base.current.text : null;
+ const fromRuns = base.current?.guid === next.guid ? (base.current.runs ?? null) : null;
let saved: string | null = null;
const ok = await write(async () => {
- saved = await api.noteSave(next.guid, next.body, from, next.runs);
+ saved = await api.noteSave(next.guid, next.body, from, next.runs, next.runs ? fromRuns : null);
});
if (!ok || saved === null) return;
const kept: string = saved;
- base.current = { guid: next.guid, text: kept };
+ const keptRunsForBase = next.runs ? (kept === next.body ? next.runs : carryRuns(next.body, next.runs, kept)) : null;
+ base.current = { guid: next.guid, text: kept, runs: keptRunsForBase };
setSaved(true);
// What Apple now holds becomes what this note reads, text and formatting together, so
// what is on screen and what was saved agree without a refresh.
@@ -303,7 +305,7 @@ export function NotesView() {
// Nothing may be typed into a note whose text has not arrived.
if (!open || body === null) return;
// The first keystroke in a note marks what it read as the base of the edit.
- if (base.current?.guid !== open.guid) base.current = { guid: open.guid, text: body };
+ if (base.current?.guid !== open.guid) base.current = { guid: open.guid, text: body, runs: formatSafe ? runs : null };
draftRuns.current = typedRuns;
setDraft(typed);
setEdits((n) => n + 1);