diff --git a/Cargo.lock b/Cargo.lock index 8ab653aa..8b61eaf8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -132,6 +132,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + [[package]] name = "aes" version = "0.8.4" @@ -295,6 +305,19 @@ dependencies = [ "x11rb", ] +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures 0.2.17", + "password-hash", + "zeroize", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -607,6 +630,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -811,6 +843,17 @@ dependencies = [ "libc", ] +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + [[package]] name = "chacha20" version = "0.10.2" @@ -822,6 +865,19 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20 0.9.1", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "chrono" version = "0.4.45" @@ -844,6 +900,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ "crypto-common", "inout", + "zeroize", ] [[package]] @@ -1265,6 +1322,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core 0.6.4", "typenum", ] @@ -3846,12 +3904,15 @@ dependencies = [ name = "notecraft-store" version = "0.0.25" dependencies = [ + "argon2", + "chacha20poly1305", "log", "notecraft-formats", "notecraft-ink", "notecraft-model", "notecraft-search", "serde_json", + "zeroize", ] [[package]] @@ -3904,6 +3965,7 @@ dependencies = [ "unicode-segmentation", "ureq", "web-time", + "zeroize", "zip 4.6.1", ] @@ -4384,6 +4446,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "open" version = "5.4.4" @@ -4510,6 +4578,17 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "pbkdf2" version = "0.12.2" @@ -4842,6 +4921,17 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336" +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + [[package]] name = "polycool" version = "0.4.0" @@ -5095,7 +5185,7 @@ version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ - "chacha20", + "chacha20 0.10.2", "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -5115,6 +5205,9 @@ name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] [[package]] name = "rand_core" @@ -6983,6 +7076,16 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + [[package]] name = "untrusted" version = "0.7.1" diff --git a/crates/model/src/anchors.rs b/crates/model/src/anchors.rs new file mode 100644 index 00000000..37c63b39 --- /dev/null +++ b/crates/model/src/anchors.rs @@ -0,0 +1,412 @@ +//! Paragraphs a link or a note points at, by an id that stays with the paragraph (issues #530 +//! and #522). +//! +//! Copy Link to Paragraph needs a name for one paragraph that still finds it after the page +//! around it changes: lines written above it, the page rearranged, the paragraph itself edited. +//! A block number does not survive the first of those, and the words alone do not survive the +//! last. So the page keeps, in its own metadata as it keeps table widths and justification, a +//! short id for each paragraph something points at, with where the paragraph was and a +//! fingerprint of its words: +//! +//! ```text +//! a1b2c3d4@3:9f2c41e07a35b6d1, 77e0ab12@8:03b1... +//! ``` +//! +//! Nothing is written into the words, so the page reads the same to any other program, and both +//! page formats carry the same line. +//! +//! Two things keep an id on its paragraph: +//! +//! - **NoteCraft's own saves** ([`Anchors::follow`]): the blocks before and after the save are +//! compared, paragraph by paragraph, so a paragraph that kept its words is found wherever it +//! went, and one that was edited is the one that took its place among the others. +//! - **Changes made elsewhere** ([`Anchors::find`]): a page rearranged by another program is +//! read with the paragraph whose words match the fingerprint, nearest the place it was. +//! +//! A paragraph that was deleted takes its id with it, and a link to it then says so. + +/// How many paragraphs of one page keep an id. A page with more than this many links into it was +/// not linked by hand. +const MAX_ANCHORS: usize = 2000; + +/// Above this many pairs of paragraphs the full comparison is not made: the paragraphs that +/// begin and end both pages alike are matched, and the rest by their words alone. +const MAX_COMPARE: usize = 4_000_000; + +/// One paragraph with an id. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Anchor { + /// The id a link names. Letters and digits only. + pub id: String, + /// Where the paragraph is among the page's blocks. + pub block: usize, + /// A fingerprint of its words: see [`print`]. + pub print: u64, +} + +/// The paragraphs of a page that have ids. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Anchors { + list: Vec, +} + +/// The fingerprint of a paragraph's words: case, and the spaces between the words, do not +/// count, so a paragraph made bold or reflowed is still the same paragraph. +pub fn print(text: &str) -> u64 { + // FNV-1a: small, stable across versions and platforms, which a hash map's is not. + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + let mut gap = false; + let mut started = false; + for c in text.chars() { + if c.is_whitespace() { + gap = started; + continue; + } + if gap { + hash = (hash ^ u64::from(b' ')).wrapping_mul(0x0100_0000_01b3); + gap = false; + } + started = true; + for lower in c.to_lowercase() { + let mut buf = [0u8; 4]; + for byte in lower.encode_utf8(&mut buf).bytes() { + hash = (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3); + } + } + } + hash +} + +/// Whether `id` can be an anchor's id: what [`Anchors::add`] makes and a link carries. +pub fn valid_id(id: &str) -> bool { + (4..=32).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric()) +} + +impl Anchors { + pub fn is_empty(&self) -> bool { + self.list.is_empty() + } + + pub fn len(&self) -> usize { + self.list.len() + } + + pub fn iter(&self) -> impl Iterator { + self.list.iter() + } + + /// The id of the paragraph at `block`, if it has one. + pub fn id_at(&self, block: usize) -> Option<&str> { + self.list.iter().find(|a| a.block == block).map(|a| a.id.as_str()) + } + + /// The paragraph `id` names, among blocks whose fingerprints are `prints`: where it was, if + /// the words there still match; else the nearest paragraph with its words; else, when the page + /// has as many blocks as the place needs, where it was. `None` when the id is not on this page + /// or the place is past the end. + pub fn find(&self, id: &str, prints: &[u64]) -> Option { + let anchor = self.list.iter().find(|a| a.id == id)?; + if prints.get(anchor.block) == Some(&anchor.print) { + return Some(anchor.block); + } + let nearest = + prints.iter().enumerate().filter(|(_, p)| **p == anchor.print).min_by_key(|(at, _)| at.abs_diff(anchor.block)).map(|(at, _)| at); + nearest.or_else(|| (anchor.block < prints.len()).then_some(anchor.block)) + } + + /// Gives the paragraph at `block`, with fingerprint `print`, an id, or returns the one it + /// has. `fresh` makes a candidate id; one already on the page is not used twice. `None` when + /// the page keeps no more ids. + pub fn add(&mut self, block: usize, print: u64, mut fresh: impl FnMut() -> String) -> Option { + if let Some(id) = self.id_at(block) { + return Some(id.to_string()); + } + if self.list.len() >= MAX_ANCHORS { + return None; + } + let id = (0..16).map(|_| fresh()).find(|id| valid_id(id) && !self.list.iter().any(|a| a.id == *id))?; + self.list.push(Anchor { id: id.clone(), block, print }); + self.list.sort_by_key(|a| a.block); + Some(id) + } + + /// Takes the id off its paragraph. True when there was one. + pub fn remove(&mut self, id: &str) -> bool { + let before = self.list.len(); + self.list.retain(|a| a.id != id); + self.list.len() != before + } + + /// The page was saved: its blocks had fingerprints `old` and have `new`. Each id moves with + /// its paragraph; one whose paragraph was deleted goes. Returns the ids that went. The + /// fingerprints are brought up to date, so an edited paragraph is known by its new words. + pub fn follow(&mut self, old: &[u64], new: &[u64]) -> Vec { + let map = block_map(old, new); + let mut gone = Vec::new(); + let mut kept = Vec::with_capacity(self.list.len()); + for mut anchor in std::mem::take(&mut self.list) { + // Where the paragraph was before this save: its place, unless something outside + // NoteCraft moved it since the id was written. + let was = match self.list_find(&anchor, old) { + Some(at) => at, + None => { + gone.push(anchor.id); + continue; + } + }; + match map.get(was).copied().flatten() { + Some(now) => { + anchor.block = now; + anchor.print = new[now]; + if !kept.iter().any(|a: &Anchor| a.block == now) { + kept.push(anchor); + } else { + gone.push(anchor.id); + } + } + None => gone.push(anchor.id), + } + } + kept.sort_by_key(|a| a.block); + self.list = kept; + gone + } + + fn list_find(&self, anchor: &Anchor, prints: &[u64]) -> Option { + let one = Anchors { list: vec![anchor.clone()] }; + one.find(&anchor.id, prints) + } +} + +/// For each block of `old`, where it is in `new`, or `None` when it was deleted. +/// +/// Blocks with the same words are matched as the longest common run of the two lists, then a +/// block left over on both sides with the same words is a paragraph that moved. Between two matched +/// blocks, the old blocks still unmatched are paired in order with the new ones: that is a +/// paragraph edited in place. Old blocks left over when the new gap is shorter were deleted. +fn block_map(old: &[u64], new: &[u64]) -> Vec> { + let pairs = matched(old, new); + let mut map = vec![None; old.len()]; + let mut taken = vec![false; new.len()]; + for &(o, n) in &pairs { + map[o] = Some(n); + taken[n] = true; + } + // Moves: the same words, unmatched on both sides, nearest first. + for o in 0..old.len() { + if map[o].is_some() { + continue; + } + if let Some(n) = (0..new.len()).filter(|&n| !taken[n] && new[n] == old[o]).min_by_key(|&n| n.abs_diff(o)) { + map[o] = Some(n); + taken[n] = true; + } + } + // Edits: between two blocks the comparison matched, what is left pairs up in order. + let mut bounds: Vec<(usize, usize)> = pairs.clone(); + bounds.push((old.len(), new.len())); + let (mut o, mut n) = (0usize, 0usize); + for &(mo, mn) in &bounds { + let left_old: Vec = (o..mo).filter(|&i| map[i].is_none()).collect(); + let left_new: Vec = (n..mn).filter(|&j| !taken[j]).collect(); + for (&i, &j) in left_old.iter().zip(&left_new) { + map[i] = Some(j); + taken[j] = true; + } + o = mo + 1; + n = mn + 1; + } + map +} + +/// The blocks of `new` that were written or changed since `old`: everything but the paragraphs that +/// kept their words, wherever they went. What Linked Notes ties to its source (issue #522). +pub fn written(old: &[u64], new: &[u64]) -> Vec { + let mut same = vec![false; new.len()]; + for (o, n) in block_map(old, new).into_iter().enumerate() { + if let Some(n) = n + && old[o] == new[n] + { + same[n] = true; + } + } + (0..new.len()).filter(|&n| !same[n]).collect() +} + +/// The pairs `(old, new)` of blocks matched as equal, in order. +fn matched(old: &[u64], new: &[u64]) -> Vec<(usize, usize)> { + let head = old.iter().zip(new).take_while(|(a, b)| a == b).count(); + let tail = old[head..].iter().rev().zip(new[head..].iter().rev()).take_while(|(a, b)| a == b).count(); + let (mid_old, mid_new) = (&old[head..old.len() - tail], &new[head..new.len() - tail]); + let mut pairs: Vec<(usize, usize)> = (0..head).map(|i| (i, i)).collect(); + if mid_old.len().saturating_mul(mid_new.len()) <= MAX_COMPARE { + pairs.extend(lcs(mid_old, mid_new).into_iter().map(|(a, b)| (a + head, b + head))); + } else { + // Too many to compare every pair: a paragraph whose words appear once on each side is + // matched, in order. + let mut last = 0usize; + for (i, p) in mid_old.iter().enumerate() { + if mid_old.iter().filter(|q| *q == p).count() != 1 { + continue; + } + let mut found = mid_new.iter().enumerate().filter(|(_, q)| *q == p); + if let (Some((j, _)), None) = (found.next(), found.next()) + && j >= last + { + pairs.push((i + head, j + head)); + last = j + 1; + } + } + } + pairs.extend((0..tail).map(|k| (old.len() - tail + k, new.len() - tail + k))); + pairs +} + +/// The longest common subsequence of two lists, as index pairs. +fn lcs(a: &[u64], b: &[u64]) -> Vec<(usize, usize)> { + let (n, m) = (a.len(), b.len()); + let mut table = vec![0u32; (n + 1) * (m + 1)]; + let at = |i: usize, j: usize| i * (m + 1) + j; + for i in (0..n).rev() { + for j in (0..m).rev() { + table[at(i, j)] = if a[i] == b[j] { table[at(i + 1, j + 1)] + 1 } else { table[at(i + 1, j)].max(table[at(i, j + 1)]) }; + } + } + let (mut i, mut j, mut out) = (0, 0, Vec::new()); + while i < n && j < m { + if a[i] == b[j] { + out.push((i, j)); + i += 1; + j += 1; + } else if table[at(i + 1, j)] >= table[at(i, j + 1)] { + i += 1; + } else { + j += 1; + } + } + out +} + +/// The line is `id@block:print`, comma separated. Front matter reads `#` as the start of a comment, +/// so the line has none. +/// Reads the line a page keeps. Anything that does not read is dropped: a page must open +/// whatever its metadata says, and the worst a lost id does is make a link say its paragraph is +/// gone. +pub fn parse(text: &str) -> Anchors { + let mut list: Vec = Vec::new(); + for item in text.split(',') { + let Some((id, rest)) = item.trim().split_once('@') else { continue }; + let Some((block, print)) = rest.split_once(':') else { continue }; + let (Ok(block), Ok(print)) = (block.trim().parse::(), u64::from_str_radix(print.trim(), 16)) else { continue }; + if valid_id(id) && !list.iter().any(|a| a.id == id) && list.len() < MAX_ANCHORS { + list.push(Anchor { id: id.to_string(), block, print }); + } + } + list.sort_by_key(|a| a.block); + Anchors { list } +} + +/// The line a page keeps: see [`parse`]. +pub fn write(anchors: &Anchors) -> String { + anchors.list.iter().map(|a| format!("{}@{}:{:016x}", a.id, a.block, a.print)).collect::>().join(", ") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn prints(words: &[&str]) -> Vec { + words.iter().map(|w| print(w)).collect() + } + + fn counter() -> impl FnMut() -> String { + let mut n = 0u32; + move || { + n += 1; + format!("id{n:04}") + } + } + + #[test] + fn a_fingerprint_ignores_case_and_spacing_but_not_words() { + assert_eq!(print("The quick\nfox"), print("the quick fox")); + assert_eq!(print(" lead"), print("lead")); + assert_ne!(print("the quick fox"), print("the quick dog")); + assert_ne!(print("ab c"), print("a bc")); + } + + #[test] + fn the_line_reads_back_and_junk_is_dropped() { + let mut a = Anchors::default(); + let mut fresh = counter(); + let first = a.add(3, 0xabc, &mut fresh).expect("an id"); + let second = a.add(1, 0x12, &mut fresh).expect("an id"); + assert_eq!(a.add(3, 0xabc, &mut fresh).as_deref(), Some(first.as_str()), "one id per paragraph"); + let line = write(&a); + assert_eq!(parse(&line), a); + assert_eq!(a.id_at(1), Some(second.as_str())); + let junky = format!("{line}, nonsense, x@y:z, bad!id@2:ff, {first}@9:01"); + assert_eq!(parse(&junky), a, "junk, a bad id and a repeated id are dropped"); + } + + #[test] + fn an_id_survives_lines_written_above_and_the_paragraph_moving() { + let before = prints(&["Title", "one", "two", "three"]); + let mut a = Anchors::default(); + let id = a.add(2, before[2], counter()).expect("an id"); + // A line written above it. + let after = prints(&["Title", "new line", "one", "two", "three"]); + assert!(a.follow(&before, &after).is_empty()); + assert_eq!(a.find(&id, &after), Some(3)); + // The paragraph moved to the end. + let moved = prints(&["Title", "new line", "one", "three", "two"]); + a.follow(&after, &moved); + assert_eq!(a.find(&id, &moved), Some(4)); + } + + #[test] + fn an_edited_paragraph_keeps_its_id_and_a_deleted_one_takes_it_away() { + let before = prints(&["one", "two", "three"]); + let mut a = Anchors::default(); + let id = a.add(1, before[1], counter()).expect("an id"); + let edited = prints(&["one", "two, said better", "three"]); + assert!(a.follow(&before, &edited).is_empty()); + assert_eq!(a.find(&id, &edited), Some(1), "edited in place"); + let gone = prints(&["one", "three"]); + assert_eq!(a.follow(&edited, &gone), vec![id.clone()]); + assert_eq!(a.find(&id, &gone), None); + } + + #[test] + fn a_page_rearranged_elsewhere_is_read_by_the_words() { + let before = prints(&["one", "two", "three"]); + let mut a = Anchors::default(); + let id = a.add(2, before[2], counter()).expect("an id"); + // Another program put two lines above it and did not touch the metadata. + assert_eq!(a.find(&id, &prints(&["x", "y", "one", "two", "three"])), Some(4)); + // Its words changed too: the place is all that is left. + assert_eq!(a.find(&id, &prints(&["one", "two", "other"])), Some(2)); + assert_eq!(a.find(&id, &prints(&["one"])), None, "past the end"); + assert_eq!(a.find("nosuch", &before), None); + } + + #[test] + fn what_was_written_is_the_new_and_the_edited_not_the_moved() { + let old = prints(&["one", "two", "three"]); + let new = prints(&["one", "added", "three", "two, edited", "two"]); + assert_eq!(written(&old, &new), vec![1, 3]); + assert!(written(&old, &old).is_empty()); + } + + #[test] + fn a_long_page_is_followed_without_comparing_every_pair() { + let old: Vec = (0..3000).collect(); + let mut new = old.clone(); + new.insert(10, 99_999); + new.swap(1500, 2500); + let mut a = Anchors::default(); + let id = a.add(2000, 2000, counter()).expect("an id"); + a.follow(&old, &new); + assert_eq!(a.find(&id, &new), Some(2001)); + } +} diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index c5b8179d..38c3ca96 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -4,6 +4,7 @@ //! Node kinds, page formats, the rules for folder and file names, ids, time, and //! a few small text helpers. No file system access and no dependencies. +pub mod anchors; pub mod color; pub mod container; pub mod format; @@ -11,6 +12,7 @@ pub mod id; pub mod justify; pub mod kind; pub mod kv; +pub mod linked; pub mod names; pub mod paper; pub mod tablecols; diff --git a/crates/model/src/linked.rs b/crates/model/src/linked.rs new file mode 100644 index 00000000..e3a9b201 --- /dev/null +++ b/crates/model/src/linked.rs @@ -0,0 +1,280 @@ +//! Linked Notes (issue #522): which paragraphs of a page were written with which source open. +//! +//! OneNote's Linked Notes notes, beside each paragraph written during a session, the web page or +//! document the person was reading. NoteCraft keeps the same in the page's own metadata, as two +//! lines beside the paragraph ids of [`crate::anchors`]: the sources, numbered, and which +//! paragraph id was written with which source. +//! +//! ```text +//! sources: 1|web|https://example.org/a|Example page; 2|file|C:/papers/b.pdf|b.pdf +//! linked: a1b2c3d4=1, 77e0ab12=2 +//! ``` +//! +//! A source is only ever one the person chose: a web address, a file, or another NoteCraft page. +//! Nothing is recorded unless a session was started, and nothing leaves the page. + +/// What kind of thing a source is, which decides how it is opened again. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// A web address, opened in the browser. + Web, + /// A file on this computer, opened in the program the system has for it. + File, + /// A NoteCraft page, by its `notecraft:` link. + Page, +} + +impl Kind { + pub fn id(self) -> &'static str { + match self { + Kind::Web => "web", + Kind::File => "file", + Kind::Page => "page", + } + } + + pub fn of(text: &str) -> Option { + match text.trim() { + "web" => Some(Kind::Web), + "file" => Some(Kind::File), + "page" => Some(Kind::Page), + _ => None, + } + } +} + +/// One source. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Source { + pub kind: Kind, + /// The address, path or `notecraft:` link. + pub target: String, + /// What it is called, as the person sees it. + pub title: String, +} + +impl Source { + /// A source for what the person typed or pasted: a web address, a NoteCraft link, or else a + /// path to a file. `None` for nothing at all. + pub fn from_text(text: &str) -> Option { + let target = text.trim().trim_matches('"').trim(); + if target.is_empty() { + return None; + } + let lower = target.to_ascii_lowercase(); + let kind = if lower.starts_with("https://") || lower.starts_with("http://") { + Kind::Web + } else if lower.starts_with("notecraft:") { + Kind::Page + } else { + Kind::File + }; + let title = match kind { + Kind::Web => target.split("://").nth(1).unwrap_or(target).trim_end_matches('/').to_string(), + Kind::File => target.rsplit(['/', '\\']).find(|p| !p.is_empty()).unwrap_or(target).to_string(), + Kind::Page => target.split(['?', '#']).next().unwrap_or(target).rsplit('/').find(|p| !p.is_empty()).unwrap_or(target).to_string(), + }; + Some(Source { kind, target: target.to_string(), title }) + } +} + +/// How many sources and links one page keeps. +const MAX_SOURCES: usize = 500; +const MAX_LINKS: usize = 2000; + +/// The sources of a page and the paragraphs written with each. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Linked { + sources: Vec<(u32, Source)>, + links: Vec<(String, u32)>, +} + +impl Linked { + pub fn is_empty(&self) -> bool { + self.links.is_empty() + } + + /// The source the paragraph with id `anchor` was written with. + pub fn source_of(&self, anchor: &str) -> Option<&Source> { + let n = self.links.iter().find(|(a, _)| a == anchor).map(|(_, n)| *n)?; + self.sources.iter().find(|(m, _)| *m == n).map(|(_, s)| s) + } + + /// Every paragraph id with its source, in the order they were linked. + pub fn iter(&self) -> impl Iterator { + self.links.iter().filter_map(|(a, n)| self.sources.iter().find(|(m, _)| m == n).map(|(_, s)| (a.as_str(), s))) + } + + /// Ties the paragraph `anchor` to `source`, in place of any source it had. False when the + /// page keeps no more. + pub fn link(&mut self, anchor: &str, source: &Source) -> bool { + let n = match self.sources.iter().find(|(_, s)| s == source) { + Some((n, _)) => *n, + None => { + if self.sources.len() >= MAX_SOURCES { + return false; + } + let n = self.sources.iter().map(|(n, _)| *n).max().unwrap_or(0) + 1; + self.sources.push((n, source.clone())); + n + } + }; + if let Some(link) = self.links.iter_mut().find(|(a, _)| a == anchor) { + link.1 = n; + } else if self.links.len() < MAX_LINKS { + self.links.push((anchor.to_string(), n)); + } else { + return false; + } + self.drop_unused(); + true + } + + /// Takes the source off the paragraph `anchor`. True when it had one. + pub fn unlink(&mut self, anchor: &str) -> bool { + let before = self.links.len(); + self.links.retain(|(a, _)| a != anchor); + self.drop_unused(); + self.links.len() != before + } + + /// Keeps only the paragraphs whose ids are still on the page. True when any went. + pub fn keep_anchors(&mut self, alive: impl Fn(&str) -> bool) -> bool { + let before = self.links.len(); + self.links.retain(|(a, _)| alive(a)); + self.drop_unused(); + self.links.len() != before + } + + fn drop_unused(&mut self) { + let links = &self.links; + self.sources.retain(|(n, _)| links.iter().any(|(_, m)| m == n)); + } +} + +/// Characters a source's fields cannot hold as they are, because the line is split on them. +fn encode(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for c in text.chars() { + match c { + '%' | '#' | '|' | ';' | ',' | '=' | '\n' | '\r' | '"' | '<' | '>' | '&' => { + let mut buf = [0u8; 4]; + for b in c.encode_utf8(&mut buf).bytes() { + out.push_str(&format!("%{b:02X}")); + } + } + c => out.push(c), + } + } + out +} + +fn decode(text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' + && let Some(hex) = text.get(i + 1..i + 3) + && let Ok(b) = u8::from_str_radix(hex, 16) + { + out.push(b); + i += 3; + continue; + } + out.push(bytes[i]); + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + +/// Reads the two lines a page keeps. Anything that does not read is dropped. +pub fn parse(sources: &str, links: &str) -> Linked { + let mut out = Linked::default(); + for item in sources.split(';') { + let mut parts = item.trim().splitn(4, '|'); + let (Some(n), Some(kind), Some(target), Some(title)) = (parts.next(), parts.next(), parts.next(), parts.next()) else { continue }; + let (Ok(n), Some(kind)) = (n.trim().parse::(), Kind::of(kind)) else { continue }; + let target = decode(target); + if target.is_empty() || out.sources.iter().any(|(m, _)| *m == n) || out.sources.len() >= MAX_SOURCES { + continue; + } + out.sources.push((n, Source { kind, target, title: decode(title) })); + } + for item in links.split(',') { + let Some((anchor, n)) = item.trim().split_once('=') else { continue }; + let Ok(n) = n.trim().parse::() else { continue }; + let anchor = anchor.trim(); + if crate::anchors::valid_id(anchor) + && out.sources.iter().any(|(m, _)| *m == n) + && !out.links.iter().any(|(a, _)| a == anchor) + && out.links.len() < MAX_LINKS + { + out.links.push((anchor.to_string(), n)); + } + } + out.drop_unused(); + out +} + +/// The two lines a page keeps, sources then links: see [`parse`]. +pub fn write(linked: &Linked) -> (String, String) { + let sources = + linked.sources.iter().map(|(n, s)| format!("{n}|{}|{}|{}", s.kind.id(), encode(&s.target), encode(&s.title))).collect::>().join("; "); + let links = linked.links.iter().map(|(a, n)| format!("{a}={n}")).collect::>().join(", "); + (sources, links) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn what_the_person_types_is_read_as_a_web_page_a_page_or_a_file() { + let web = Source::from_text(" https://example.org/a/b/ ").expect("web"); + assert_eq!((web.kind, web.title.as_str()), (Kind::Web, "example.org/a/b")); + let page = Source::from_text("notecraft:/Work/Plans/Budget?id=12").expect("page"); + assert_eq!((page.kind, page.title.as_str()), (Kind::Page, "Budget")); + let file = Source::from_text("\"C:\\papers\\report.pdf\"").expect("file"); + assert_eq!((file.kind, file.target.as_str(), file.title.as_str()), (Kind::File, "C:\\papers\\report.pdf", "report.pdf")); + assert_eq!(Source::from_text(" "), None); + } + + #[test] + fn the_lines_read_back_with_awkward_characters() { + let mut l = Linked::default(); + let odd = Source { kind: Kind::Web, target: "https://x.org/?a=1&b=2;c|d,e%f#frag|d,e%f".into(), title: "A \"quoted\" \nnext".into() }; + let file = Source { kind: Kind::File, target: "/home/me/ملف.pdf".into(), title: "ملف.pdf".into() }; + assert!(l.link("aaaa1111", &odd)); + assert!(l.link("bbbb2222", &file)); + assert!(l.link("cccc3333", &odd)); + let (sources, links) = write(&l); + assert!(!sources.contains('\n') && !sources.contains('"'), "{sources}"); + assert_eq!(parse(&sources, &links), l); + assert_eq!(l.source_of("cccc3333"), Some(&odd)); + } + + #[test] + fn a_source_no_paragraph_uses_goes() { + let mut l = Linked::default(); + let a = Source::from_text("https://a.org").expect("a"); + let b = Source::from_text("https://b.org").expect("b"); + l.link("aaaa1111", &a); + l.link("bbbb2222", &b); + assert!(l.keep_anchors(|id| id == "aaaa1111")); + let (sources, _) = write(&l); + assert!(!sources.contains("b.org"), "{sources}"); + l.link("aaaa1111", &b); + assert_eq!(l.source_of("aaaa1111"), Some(&b), "relinked"); + assert!(l.unlink("aaaa1111")); + assert!(l.is_empty()); + assert_eq!(write(&l), (String::new(), String::new())); + } + + #[test] + fn junk_is_dropped() { + let l = parse("x|web|a|b; 1|nope|a|b; 2|web||t; 3|web|https://ok.org|ok", "zz=3, abcd1234=9, abcd1234=3, abcd1234=3"); + assert_eq!(l.iter().count(), 1); + assert_eq!(l.source_of("abcd1234").map(|s| s.target.as_str()), Some("https://ok.org")); + } +} diff --git a/crates/store/Cargo.toml b/crates/store/Cargo.toml index e15fa44a..185f1b84 100644 --- a/crates/store/Cargo.toml +++ b/crates/store/Cargo.toml @@ -18,3 +18,12 @@ notecraft-search = { workspace = true } # Only to tell an ink file from an ordinary picture by its namespace. notecraft-ink = { workspace = true } log = { workspace = true } +# Clears what a password-protected section held from memory once it is done with (issue #523). +zeroize = "1" + +# Password-protected sections (issue #523): Argon2id turns the password into a key and +# XChaCha20-Poly1305 seals the section. Pure Rust. The web build keeps sections in the browser and +# has no protection, so these are left out there. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +argon2 = { version = "0.5", default-features = false, features = ["alloc", "zeroize"] } +chacha20poly1305 = { version = "0.10", default-features = false, features = ["alloc", "getrandom"] } diff --git a/crates/store/src/backup.rs b/crates/store/src/backup.rs index 5f045966..5b29eb47 100644 --- a/crates/store/src/backup.rs +++ b/crates/store/src/backup.rs @@ -147,6 +147,10 @@ fn page_ids(dir: &Path) -> std::collections::HashMap<String, PathBuf> { if node.info.kind == NodeKind::Page { out.insert(node.info.id.clone(), node.path.strip_prefix(root).map(Path::to_path_buf).unwrap_or_default()); } + // An unlocked protected section's pages are not in its backup: it is copied sealed. + if crate::protect::is_protected(&node.path) { + return; + } for child in &node.children { walk(child, root, out); } @@ -210,6 +214,9 @@ fn check_folder(notebook: &Path, folder: &Path) -> Result<()> { fn copy_folder(from: &Path, to: &Path) -> std::io::Result<u64> { fs::create_dir(to)?; let mut bytes = 0; + // A password-protected section is backed up sealed, as it is when locked, even while it is + // unlocked: its plain files are never copied (issue #523). + let sealed_only = crate::protect::is_protected(from); for entry in fs::read_dir(from)? { let entry = entry?; let kind = entry.file_type()?; @@ -217,6 +224,9 @@ fn copy_folder(from: &Path, to: &Path) -> std::io::Result<u64> { if [".git", ".hg", ".svn"].iter().any(|vcs| name == *vcs) { continue; } + if sealed_only && name != "_node.toml" && name != crate::protect::SEALED { + continue; + } let target = to.join(&name); if kind.is_dir() { bytes += copy_folder(&entry.path(), &target)?; diff --git a/crates/store/src/lib.rs b/crates/store/src/lib.rs index d6ad95c4..f55ce1b1 100644 --- a/crates/store/src/lib.rs +++ b/crates/store/src/lib.rs @@ -21,6 +21,8 @@ pub mod links; pub mod ops; pub mod page; pub mod page_templates; +pub mod paragraphs; +pub mod protect; pub mod read_state; pub mod recent; pub mod recycle; diff --git a/crates/store/src/links.rs b/crates/store/src/links.rs index f45478fb..66b9f05e 100644 --- a/crates/store/src/links.rs +++ b/crates/store/src/links.rs @@ -41,6 +41,26 @@ pub fn page_uri(roots: &[PathBuf], dir: &Path) -> Option<String> { }) } +/// A link to one paragraph of this page, as OneNote's Copy Link to Paragraph makes (issue #530): +/// the page's link with `p=` and the paragraph's id (see [`crate::paragraphs`]). A link with an id +/// the page no longer has still opens the page. +pub fn paragraph_uri(roots: &[PathBuf], dir: &Path, paragraph: &str) -> Option<String> { + if !notecraft_model::anchors::valid_id(paragraph) { + return None; + } + let page = page_uri(roots, dir)?; + let joiner = if page.contains('?') { '&' } else { '?' }; + Some(format!("{page}{joiner}p={paragraph}")) +} + +/// The paragraph id a `notecraft:` link names, if it names one. +pub fn paragraph_of(href: &str) -> Option<String> { + let href = href.trim(); + href.get(..SCHEME.len()).filter(|head| head.eq_ignore_ascii_case(SCHEME))?; + let (_, query) = href.split('#').next()?.split_once('?')?; + query.split('&').find_map(|pair| pair.strip_prefix("p=")).map(percent_decode).filter(|id| notecraft_model::anchors::valid_id(id)) +} + /// Where a link leads. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Link { @@ -480,6 +500,23 @@ mod tests { assert_eq!(resolve(&root, &a, "assets/日本語.txt"), Link::File(a.join("assets").join("日本語.txt"))); } + /// Issue #530: a link to a paragraph is the page's link with the paragraph's id; the page is + /// found as any page link finds it, and the id is read back. + #[test] + fn a_link_to_a_paragraph_names_its_page_and_the_paragraph() { + let (_t, root, a, _b) = fixture("links-paragraph"); + let roots = vec![root.clone()]; + let uri = paragraph_uri(&roots, &a, "a1b2c3d4").expect("a link"); + assert!(uri.starts_with(&page_uri(&roots, &a).expect("page link")) && uri.ends_with("p=a1b2c3d4"), "{uri}"); + assert_eq!(resolve_in(&roots, &a, &uri), Link::Node(a.clone()), "it opens the page"); + assert_eq!(paragraph_of(&uri).as_deref(), Some("a1b2c3d4")); + assert_eq!(paragraph_of(&format!("{uri}#x")).as_deref(), Some("a1b2c3d4"), "a fragment after it"); + assert_eq!(paragraph_of(&page_uri(&roots, &a).expect("page link")), None, "a page's link names no paragraph"); + assert_eq!(paragraph_of("https://example.test/?p=a1b2c3d4"), None, "only our own links"); + assert_eq!(paragraph_of("notecraft:/a/b?p=bad!id"), None); + assert_eq!(paragraph_uri(&roots, &a, "no good"), None); + } + #[test] fn percent_escapes_decode_and_junk_is_kept() { assert_eq!(percent_decode("a%20b"), "a b"); diff --git a/crates/store/src/ops.rs b/crates/store/src/ops.rs index f7b327b8..654a826f 100644 --- a/crates/store/src/ops.rs +++ b/crates/store/src/ops.rs @@ -214,6 +214,13 @@ fn check_destination(path: &Path, dest: &Path) -> Result<NodeKind> { if dest.starts_with(path) { return Err(StoreError::invalid("a page or section cannot go inside itself")); } + crate::protect::refuse_if_locked(dest)?; + // The key an unlocked section was opened with is held for its place: it is locked first + // (issue #523). Its content stays where it is while it is open, so nothing below it leaves + // the section by a move either way. + if crate::protect::state(path) == Some(crate::protect::State::Unlocked) { + return Err(StoreError::invalid("lock this section before moving or copying it")); + } Ok(kind) } @@ -550,6 +557,9 @@ pub fn copy_node(path: &Path, dest: &Path) -> Result<PathBuf> { let path = fs::canonicalize(path).map_err(|e| StoreError::io("open", path, e))?; let dest = fs::canonicalize(dest).map_err(|e| StoreError::io("open", dest, e))?; check_destination(&path, &dest)?; + if crate::protect::is_protected(&path) { + return Err(StoreError::invalid("a section with a password cannot be copied; take its password away first")); + } let order = next_order(&dest); let target = unique_child(&dest, &tree::folder_name(&path)); if let Err(e) = copy_tree(&path, &target) { @@ -769,6 +779,7 @@ fn create_node_inner( ) -> Result<PathBuf> { let parent_info = read_node(parent).ok_or_else(|| StoreError::NotFound(format!("{} is not a notebook, section, group or page", parent.display())))?; + crate::protect::refuse_if_locked(parent)?; if !parent_info.kind.may_contain().contains(&kind) { return Err(StoreError::invalid(format!("a {} cannot contain a {}", parent_info.kind.label().to_lowercase(), kind.label().to_lowercase()))); } diff --git a/crates/store/src/page.rs b/crates/store/src/page.rs index c5f5b346..0fa33112 100644 --- a/crates/store/src/page.rs +++ b/crates/store/src/page.rs @@ -1117,7 +1117,9 @@ fn update_body(format: PageFormat, text: &str, body: &str, now: &str, restore: b } }; // A body with its boxes in the text says everything the older line said, so the line goes. - if boxes::read(format, body).1.is_some() { without_old_boxes(format, &out) } else { out } + let out = if boxes::read(format, body).1.is_some() { without_old_boxes(format, &out) } else { out }; + // Paragraph ids move with their paragraphs (issues #530, #522). + crate::paragraphs::follow(format, text, out) } /// Writes a file by writing a temporary file next to it and renaming it over the diff --git a/crates/store/src/paragraphs.rs b/crates/store/src/paragraphs.rs new file mode 100644 index 00000000..f456cb3d --- /dev/null +++ b/crates/store/src/paragraphs.rs @@ -0,0 +1,289 @@ +//! Paragraph ids and the sources of Linked Notes, kept in a page's own file (issues #530 and +//! #522). The rules are in [`notecraft_model::anchors`] and [`notecraft_model::linked`]; this +//! module reads and writes their lines, in the head of an HTML page or the front matter of a +//! CMGFM one, and keeps the ids on their paragraphs whenever the page is saved. + +use crate::error::{Result, StoreError}; +use crate::page::write_atomic; +use crate::tree::page_file; +use notecraft_formats::{boxes, frontmatter, html, render}; +use notecraft_model::anchors::{self, Anchors}; +use notecraft_model::linked::{self, Linked, Source}; +use notecraft_model::{PageFormat, id::new_id}; +use std::fs; +use std::path::Path; + +const ANCHORS: (&str, &str) = ("notecraft:anchors", "anchors"); +const SOURCES: (&str, &str) = ("notecraft:sources", "sources"); +const LINKED: (&str, &str) = ("notecraft:linked", "linked"); + +/// The fingerprint of each block of a page body, in the order the window numbers them. +pub fn block_prints(format: PageFormat, body: &str) -> Vec<u64> { + boxes::read(format, body).0.iter().map(|b| anchors::print(&render::blocks_to_text(std::slice::from_ref(b)))).collect() +} + +fn line(format: PageFormat, text: &str, (meta, key): (&str, &str)) -> String { + match format { + PageFormat::Html => html::meta(text, meta).map(|v| html::unescape(&v)), + PageFormat::Cmgfm => frontmatter::value(&frontmatter::split_front(text).0, key), + } + .unwrap_or_default() +} + +fn set_line(format: PageFormat, text: &str, (meta, key): (&str, &str), value: &str) -> String { + match format { + PageFormat::Html if value.is_empty() => html::remove_meta(text, meta), + PageFormat::Html => html::set_meta(text, meta, &html::escape(value)), + PageFormat::Cmgfm => { + let (front, rest) = frontmatter::split_front(text); + let front = if value.is_empty() { frontmatter::remove_value(&front, key) } else { frontmatter::set_value(&front, key, value) }; + format!("{front}{rest}") + } + } +} + +fn body_of(format: PageFormat, text: &str) -> String { + match format { + PageFormat::Html => html::inner(text), + PageFormat::Cmgfm => frontmatter::split_front(text).1.trim_start_matches('\n').to_string(), + } +} + +fn read(dir: &Path) -> Result<(PageFormat, std::path::PathBuf, String)> { + let (format, file) = page_file(dir).ok_or_else(|| StoreError::NotFound(format!("{} is not a page", dir.display())))?; + let text = fs::read_to_string(&file).map_err(|e| StoreError::io("read", &file, e))?; + Ok((format, file, text)) +} + +fn linked_in(format: PageFormat, text: &str) -> Linked { + linked::parse(&line(format, text, SOURCES), &line(format, text, LINKED)) +} + +fn with_linked(format: PageFormat, text: &str, l: &Linked) -> String { + let (sources, links) = linked::write(l); + let text = set_line(format, text, SOURCES, &sources); + set_line(format, &text, LINKED, &links) +} + +/// A short id for a new paragraph anchor. +fn fresh() -> String { + // The last characters of a node id change fastest; mixed with a counter they make an id that + // is not on this page yet, which `Anchors::add` checks. + let id = new_id(); + let print = anchors::print(&id); + format!("{:08x}", (print ^ (print >> 32)) as u32) +} + +/// The paragraph ids of a page. +pub fn page_anchors(dir: &Path) -> Result<Anchors> { + let (format, _, text) = read(dir)?; + Ok(anchors::parse(&line(format, &text, ANCHORS))) +} + +/// Gives the block at `block` an id, or returns the one it has (Copy Link to Paragraph). +pub fn anchor_paragraph(dir: &Path, block: usize) -> Result<String> { + let writer = crate::coordination::page_writer(dir)?; + let _guard = writer.lock().map_err(|_| StoreError::invalid("the page writer is unavailable"))?; + let (format, file, text) = read(dir)?; + let prints = block_prints(format, &body_of(format, &text)); + let print = *prints.get(block).ok_or_else(|| StoreError::invalid("there is no such paragraph on the page"))?; + let mut list = anchors::parse(&line(format, &text, ANCHORS)); + // An id whose paragraph moved outside NoteCraft is put back on it first, so the block asked + // for is not given a second id. + let ids: Vec<String> = list.iter().map(|a| a.id.clone()).collect(); + let mut found = Anchors::default(); + for id in &ids { + if let Some(at) = list.find(id, &prints) { + found.add(at, prints[at], || id.clone()); + } + } + if found != list { + list = found; + } + let before = anchors::write(&list); + let id = list.add(block, print, fresh).ok_or_else(|| StoreError::invalid("this page keeps no more paragraph links"))?; + let after = anchors::write(&list); + if after != before { + write_atomic(&file, &set_line(format, &text, ANCHORS, &after))?; + } + Ok(id) +} + +/// Where the paragraph `id` is now. `None` when it is not on the page any more. +pub fn find_paragraph(dir: &Path, id: &str) -> Result<Option<usize>> { + let (format, _, text) = read(dir)?; + let prints = block_prints(format, &body_of(format, &text)); + Ok(anchors::parse(&line(format, &text, ANCHORS)).find(id, &prints)) +} + +/// One paragraph written during Linked Notes, with its source. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LinkedParagraph { + pub block: usize, + pub source: Source, +} + +/// The paragraphs of the page that have a source, in page order. +pub fn linked_paragraphs(dir: &Path) -> Result<Vec<LinkedParagraph>> { + let (format, _, text) = read(dir)?; + let prints = block_prints(format, &body_of(format, &text)); + let list = anchors::parse(&line(format, &text, ANCHORS)); + let mut out: Vec<LinkedParagraph> = linked_in(format, &text) + .iter() + .filter_map(|(id, source)| Some(LinkedParagraph { block: list.find(id, &prints)?, source: source.clone() })) + .collect(); + out.sort_by_key(|p| p.block); + out.dedup_by_key(|p| p.block); + Ok(out) +} + +/// Ties the blocks written since `old_body` (the page's body before the last save) to `source`. +/// Blocks that kept their words are left as they were. Returns how many were tied. +pub fn link_written(dir: &Path, old_body: &str, source: &Source) -> Result<usize> { + let writer = crate::coordination::page_writer(dir)?; + let _guard = writer.lock().map_err(|_| StoreError::invalid("the page writer is unavailable"))?; + let (format, file, text) = read(dir)?; + let body = body_of(format, &text); + let new = block_prints(format, &body); + let blocks = boxes::read(format, &body).0; + let written: Vec<usize> = anchors::written(&block_prints(format, old_body), &new) + .into_iter() + // A blank line is not a note. + .filter(|&b| blocks.get(b).is_some_and(|block| !render::blocks_to_text(std::slice::from_ref(block)).trim().is_empty())) + .collect(); + if written.is_empty() { + return Ok(0); + } + let mut list = anchors::parse(&line(format, &text, ANCHORS)); + let mut l = linked_in(format, &text); + let mut tied = 0; + for b in written { + if let Some(id) = list.add(b, new[b], fresh) + && l.link(&id, source) + { + tied += 1; + } + } + let out = set_line(format, &text, ANCHORS, &anchors::write(&list)); + write_atomic(&file, &with_linked(format, &out, &l))?; + Ok(tied) +} + +/// Takes the source off the paragraph at `block`. True when it had one. +pub fn unlink_paragraph(dir: &Path, block: usize) -> Result<bool> { + let writer = crate::coordination::page_writer(dir)?; + let _guard = writer.lock().map_err(|_| StoreError::invalid("the page writer is unavailable"))?; + let (format, file, text) = read(dir)?; + let prints = block_prints(format, &body_of(format, &text)); + let list = anchors::parse(&line(format, &text, ANCHORS)); + let Some(id) = list.iter().find(|a| list.find(&a.id, &prints) == Some(block)).map(|a| a.id.clone()) else { return Ok(false) }; + let mut l = linked_in(format, &text); + if !l.unlink(&id) { + return Ok(false); + } + write_atomic(&file, &with_linked(format, &text, &l))?; + Ok(true) +} + +/// The page's file `old` is being replaced by `new` (a save, or a version brought back): the ids +/// move with their paragraphs, and a paragraph that went takes its id and its source with it. +pub(crate) fn follow(format: PageFormat, old: &str, new: String) -> String { + let raw = line(format, old, ANCHORS); + if raw.is_empty() { + return new; + } + let mut list = anchors::parse(&raw); + let gone = list.follow(&block_prints(format, &body_of(format, old)), &block_prints(format, &body_of(format, &new))); + let out = set_line(format, &new, ANCHORS, &anchors::write(&list)); + if gone.is_empty() { + return out; + } + let mut l = linked_in(format, &out); + if l.keep_anchors(|id| !gone.iter().any(|g| g == id)) { with_linked(format, &out, &l) } else { out } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::TempDir; + + fn page(t: &TempDir, format: PageFormat, md: &str) -> std::path::PathBuf { + let settings = crate::settings::Settings::at(t.path().join("settings.toml")); + let notebook = crate::ops::create_notebook(t.path(), &format!("Notebook {}", format.id()), None, &settings).expect("notebook"); + let dir = crate::ops::create_node(¬ebook, "Page", notecraft_model::NodeKind::Page, Some(format), &settings).expect("page"); + let body = match format { + PageFormat::Html => render::blocks_to_html(¬ecraft_formats::markdown::parse(md)), + PageFormat::Cmgfm => md.to_string(), + }; + crate::page::save_body(&dir, &body).expect("body"); + dir + } + + fn body(dir: &Path) -> String { + crate::page::load_page(dir).expect("load").body + } + + #[test] + fn a_paragraph_id_survives_saves_that_move_and_edit_the_page_in_both_formats() { + let t = TempDir::new("paragraph-ids"); + for format in [PageFormat::Html, PageFormat::Cmgfm] { + let dir = page(&t, format, "First\n\nSecond\n\nThird\n"); + let id = anchor_paragraph(&dir, 1).expect("anchor"); + assert_eq!(anchor_paragraph(&dir, 1).expect("again"), id, "{format:?}: one id per paragraph"); + assert_eq!(find_paragraph(&dir, &id).expect("find"), Some(1)); + let add_above = |b: &str| match format { + PageFormat::Html => b.replacen("<p>First</p>", "<p>New one</p>\n<p>New two</p>\n<p>First</p>", 1), + PageFormat::Cmgfm => b.replacen("First", "New one\n\nNew two\n\nFirst", 1), + }; + crate::page::save_body(&dir, &add_above(&body(&dir))).expect("save"); + assert_eq!(find_paragraph(&dir, &id).expect("find"), Some(3), "{format:?}: two lines written above it"); + crate::page::save_body(&dir, &body(&dir).replace("Second", "Second, said better")).expect("save"); + assert_eq!(find_paragraph(&dir, &id).expect("find"), Some(3), "{format:?}: edited in place"); + } + } + + #[test] + fn a_deleted_paragraph_takes_its_id_away() { + let t = TempDir::new("paragraph-gone"); + for format in [PageFormat::Html, PageFormat::Cmgfm] { + let dir = page(&t, format, "One\n\nTwo\n\nThree\n"); + let id = anchor_paragraph(&dir, 1).expect("anchor"); + let cut = match format { + PageFormat::Html => body(&dir).replace("<p>Two</p>", ""), + PageFormat::Cmgfm => body(&dir).replace("Two\n\n", ""), + }; + crate::page::save_body(&dir, &cut).expect("save"); + assert_eq!(find_paragraph(&dir, &id).expect("find"), None, "{format:?}"); + assert!(page_anchors(&dir).expect("read").is_empty(), "{format:?}: the line is gone, not left empty"); + } + } + + #[test] + fn linked_notes_tie_what_was_written_to_the_source_and_let_it_go_with_its_paragraph() { + let t = TempDir::new("linked-notes"); + let web = Source::from_text("https://example.org/paper").expect("web"); + for format in [PageFormat::Html, PageFormat::Cmgfm] { + let dir = page(&t, format, "Before the session\n"); + let old = body(&dir); + let more = match format { + PageFormat::Html => format!("{old}\n<p>A note on the paper</p>\n<p></p>"), + PageFormat::Cmgfm => format!("{old}\nA note on the paper\n"), + }; + crate::page::save_body(&dir, &more).expect("save"); + assert_eq!(link_written(&dir, &old, &web).expect("link"), 1, "{format:?}: the new line, not the old or a blank one"); + let found = linked_paragraphs(&dir).expect("read"); + assert_eq!(found, vec![LinkedParagraph { block: 1, source: web.clone() }], "{format:?}"); + // A line written above moves it; the source goes with it. + let above = match format { + PageFormat::Html => body(&dir).replacen("<p>Before", "<p>Top line</p>\n<p>Before", 1), + PageFormat::Cmgfm => format!("Top line\n\n{}", body(&dir)), + }; + crate::page::save_body(&dir, &above).expect("save"); + assert_eq!(linked_paragraphs(&dir).expect("read")[0].block, 2, "{format:?}"); + assert!(unlink_paragraph(&dir, 2).expect("unlink"), "{format:?}"); + assert!(linked_paragraphs(&dir).expect("read").is_empty(), "{format:?}"); + let raw = fs::read_to_string(page_file(&dir).expect("file").1).expect("raw"); + assert!(!raw.contains("example.org"), "{format:?}: the source went with its last paragraph: {raw}"); + } + } +} diff --git a/crates/store/src/protect.rs b/crates/store/src/protect.rs new file mode 100644 index 00000000..99b996b0 --- /dev/null +++ b/crates/store/src/protect.rs @@ -0,0 +1,751 @@ +//! Password-protected sections (issue #523). +//! +//! A protected section keeps everything in it (its pages, their pictures, ink, attachments and +//! saved versions, and any subpages) in one sealed file, `_protected.ncsafe`, beside its +//! `_node.toml`, which says `protected = true`. While the section is locked nothing else is in +//! its folder, so nothing that reads the folder (the tree, search, export, backups, another +//! program) finds anything readable in it. +//! +//! Unlocking takes the section's content out of the sealed file into the folder, where it is +//! edited as any other section's. Locking seals the folder's content again, checks that the +//! sealed file opens, and deletes the plain files. The sealed file is kept while the section is +//! unlocked, so a section unlocked and never locked again (the program stopped) still has it. +//! +//! The password is turned into a key with Argon2id and the content sealed with +//! XChaCha20-Poly1305. The key is held only in memory, by whoever unlocked the section, and +//! cleared from memory when it is dropped. Files deleted from a disk may still be recovered from +//! it by tools made for that, as with any deleted file: locking is not a secure erase. +//! +//! A mark file, `_protected.open`, says the section is not locked. It reads `opening` while the +//! content is being taken out, `open` once it is all out, and `sealed` once the content has been +//! sealed again and the plain files are being deleted. A section found `opening` or `sealed` (the +//! program stopped part way) is tidied without its password: the sealed file holds all of it. A +//! section found `open` needs its password to be sealed again, since what was written into it +//! since it was unlocked is only in the plain files. + +use crate::error::{Result, StoreError}; +use crate::tree::{self, read_node}; +use notecraft_model::{NodeKind, kv}; +use std::fs; +use std::path::{Path, PathBuf}; + +/// The sealed file a protected section keeps its content in. +pub const SEALED: &str = "_protected.ncsafe"; +/// The mark that says a protected section is not locked. +pub const OPEN_MARK: &str = "_protected.open"; +/// The key in `_node.toml` that says a section is protected. +const KEY: &str = "protected"; +/// What a locked section's folder holds. Anything else in it is content. +const KEPT: [&str; 3] = ["_node.toml", SEALED, OPEN_MARK]; +/// What `StoreError::Invalid` says when the password does not open the section. +const WRONG_PASSWORD: &str = "that password does not open this section"; +/// What `StoreError::Invalid` says when a change is asked of a locked section. +const LOCKED: &str = "this section is locked with a password; unlock it first"; + +/// Whether a protected section is open to read and change. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum State { + Locked, + Unlocked, +} + +/// Whether this error says the password was wrong. +pub fn is_wrong_password(e: &StoreError) -> bool { + matches!(e, StoreError::Invalid(m) if m == WRONG_PASSWORD) +} + +/// Whether this error says the section is locked. +pub fn is_locked_error(e: &StoreError) -> bool { + matches!(e, StoreError::Invalid(m) if m == LOCKED) +} + +/// Whether `section`'s `_node.toml` says it is protected. +pub fn is_protected(section: &Path) -> bool { + fs::read_to_string(section.join("_node.toml")).is_ok_and(|t| kv::parse(&t).get(KEY).is_some_and(|v| v.trim() == "true")) +} + +fn mark(section: &Path) -> Option<String> { + fs::read_to_string(section.join(OPEN_MARK)).ok().map(|m| m.trim().to_string()) +} + +/// Whether a protected section is locked or unlocked; `None` for one that is not protected. +pub fn state(section: &Path) -> Option<State> { + is_protected(section).then(|| open_or_locked(section)) +} + +/// The same, for a folder whose `_node.toml` has been read already. +pub(crate) fn state_in(section: &Path, node: &std::collections::HashMap<String, String>) -> Option<State> { + node.get(KEY).is_some_and(|v| v.trim() == "true").then(|| open_or_locked(section)) +} + +fn open_or_locked(section: &Path) -> State { + if mark(section).as_deref() == Some("open") { State::Unlocked } else { State::Locked } +} + +/// The protected section `path` is in, or is: the nearest folder at or above it that is one. +pub fn section_of(path: &Path) -> Option<PathBuf> { + path.ancestors().find(|dir| is_protected(dir)).map(Path::to_path_buf) +} + +/// Whether `path` is, or is inside, a locked section. +pub fn is_locked_inside(path: &Path) -> bool { + section_of(path).is_some_and(|s| state(&s) == Some(State::Locked)) +} + +/// Refuses a change at `path` while it is in a locked section: nothing may be written there but +/// the sealed file. +pub fn refuse_if_locked(path: &Path) -> Result<()> { + if is_locked_inside(path) { Err(StoreError::invalid(LOCKED)) } else { Ok(()) } +} + +/// Every protected section under `root` (a notebook or a folder of them), at any depth. +pub fn protected_sections(root: &Path) -> Vec<PathBuf> { + fn walk(node: &tree::Node, out: &mut Vec<PathBuf>) { + if node.info.kind == NodeKind::Section && is_protected(&node.path) { + out.push(node.path.clone()); + } + for child in &node.children { + walk(child, out); + } + } + let mut out = Vec::new(); + if let Some(node) = tree::load_tree(root) { + walk(&node, &mut out); + } + out +} + +/// After the program stopped with sections unlocked (issue #523): every protected section under +/// `root` that was part way through unlocking or locking is locked again, since its sealed file +/// holds all of it. Returns the sections left unlocked, whose password is needed to seal what +/// was written into them. +pub fn recover(root: &Path) -> Vec<PathBuf> { + let mut open = Vec::new(); + for section in protected_sections(root) { + match mark(§ion).as_deref() { + Some("open") => open.push(section), + Some(_) => { + if let Err(e) = tidy(§ion) { + log::warn!("could not finish locking {}: {e}", section.display()); + } + } + None => {} + } + } + open +} + +/// A section's content: every file and folder in it but the ones a locked section keeps. +fn content(section: &Path) -> Result<Vec<PathBuf>> { + let entries = fs::read_dir(section).map_err(|e| StoreError::io("read", section, e))?; + let mut out = Vec::new(); + for entry in entries { + let entry = entry.map_err(|e| StoreError::io("read", section, e))?; + if !KEPT.iter().any(|kept| entry.file_name() == *kept) && !entry.file_name().to_string_lossy().starts_with(SEALED) { + out.push(entry.path()); + } + } + Ok(out) +} + +/// Deletes the section's plain content and its mark, leaving it locked. Only safe once the +/// sealed file holds all of it. +fn tidy(section: &Path) -> Result<()> { + for path in content(section)? { + let gone = if path.is_dir() { crate::ops::remove_tree(&path) } else { fs::remove_file(&path) }; + gone.map_err(|e| StoreError::io("delete", &path, e))?; + } + remove_mark(section) +} + +fn set_mark(section: &Path, value: &str) -> Result<()> { + let file = section.join(OPEN_MARK); + fs::write(&file, value).map_err(|e| StoreError::io("write", &file, e)) +} + +fn remove_mark(section: &Path) -> Result<()> { + let file = section.join(OPEN_MARK); + match fs::remove_file(&file) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(StoreError::io("delete", &file, e)), + _ => Ok(()), + } +} + +/// Sets or clears `protected` in the section's `_node.toml`, keeping every other line. +fn set_protected(section: &Path, on: bool) -> Result<()> { + let file = section.join("_node.toml"); + let text = fs::read_to_string(&file).map_err(|e| StoreError::io("read", &file, e))?; + let kept: String = text.lines().filter(|l| l.split_once('=').is_none_or(|(key, _)| key.trim() != KEY)).map(|l| format!("{l}\n")).collect(); + let out = if on { format!("{kept}{KEY} = true\n") } else { kept }; + crate::page::write_atomic(&file, &out) +} + +fn section_only(section: &Path) -> Result<()> { + if read_node(section).is_some_and(|n| n.kind == NodeKind::Section) { + Ok(()) + } else { + Err(StoreError::invalid("only a section can be protected with a password")) + } +} + +fn check_password(password: &str) -> Result<()> { + if password.is_empty() { Err(StoreError::invalid("a password cannot be empty")) } else { Ok(()) } +} + +/// Packs the section's content into one archive: for each folder and file, a kind byte (`d` or +/// `f`), its path in the section (with `/`) as a length and UTF-8, and for a file its length and +/// bytes. Links are not followed. +fn pack(section: &Path) -> Result<zeroize::Zeroizing<Vec<u8>>> { + fn put(out: &mut Vec<u8>, kind: u8, name: &str, bytes: Option<&[u8]>) { + out.push(kind); + out.extend_from_slice(&(name.len() as u32).to_le_bytes()); + out.extend_from_slice(name.as_bytes()); + if let Some(bytes) = bytes { + out.extend_from_slice(&(bytes.len() as u64).to_le_bytes()); + out.extend_from_slice(bytes); + } + } + fn walk(dir: &Path, prefix: &str, out: &mut Vec<u8>) -> Result<()> { + let mut entries: Vec<fs::DirEntry> = fs::read_dir(dir) + .map_err(|e| StoreError::io("read", dir, e))? + .collect::<std::io::Result<_>>() + .map_err(|e| StoreError::io("read", dir, e))?; + entries.sort_by_key(fs::DirEntry::file_name); + for entry in entries { + let name = entry.file_name(); + let Some(name) = name.to_str() else { + return Err(StoreError::invalid(format!("{} has a name that cannot be sealed", entry.path().display()))); + }; + let kind = entry.file_type().map_err(|e| StoreError::io("read", &entry.path(), e))?; + let path = if prefix.is_empty() { name.to_string() } else { format!("{prefix}/{name}") }; + if kind.is_dir() { + put(out, b'd', &path, None); + walk(&entry.path(), &path, out)?; + } else if kind.is_file() { + let bytes = zeroize::Zeroizing::new(fs::read(entry.path()).map_err(|e| StoreError::io("read", &entry.path(), e))?); + put(out, b'f', &path, Some(&bytes)); + } + } + Ok(()) + } + let mut out = zeroize::Zeroizing::new(b"NCPACK1\0".to_vec()); + for path in content(section)? { + let name = tree::folder_name(&path); + if path.is_dir() { + put(&mut out, b'd', &name, None); + walk(&path, &name, &mut out)?; + } else if path.is_file() { + let bytes = zeroize::Zeroizing::new(fs::read(&path).map_err(|e| StoreError::io("read", &path, e))?); + put(&mut out, b'f', &name, Some(&bytes)); + } + } + Ok(out) +} + +/// Writes an archive's folders and files into the section. A path that would leave the section, +/// or name one of the files a locked section keeps, is refused before anything is written. +fn unpack(section: &Path, archive: &[u8]) -> Result<()> { + let bad = || StoreError::invalid("the sealed section is damaged"); + let mut entries: Vec<(u8, &str, Option<&[u8]>)> = Vec::new(); + let mut rest = archive.strip_prefix(b"NCPACK1\0").ok_or_else(bad)?; + while let Some((&kind, after)) = rest.split_first() { + let (len, after) = after.split_first_chunk::<4>().ok_or_else(bad)?; + let len = u32::from_le_bytes(*len) as usize; + let (name, after) = after.split_at_checked(len).ok_or_else(bad)?; + let name = std::str::from_utf8(name).map_err(|_| bad())?; + let safe = !name.is_empty() + && name.split('/').all(|part| !part.is_empty() && part != "." && part != ".." && !part.contains(['\\', ':'])) + && !KEPT.contains(&name) + && !name.starts_with(SEALED); + if !safe { + return Err(bad()); + } + match kind { + b'd' => { + entries.push((kind, name, None)); + rest = after; + } + b'f' => { + let (size, after) = after.split_first_chunk::<8>().ok_or_else(bad)?; + let size = usize::try_from(u64::from_le_bytes(*size)).map_err(|_| bad())?; + let (bytes, after) = after.split_at_checked(size).ok_or_else(bad)?; + entries.push((kind, name, Some(bytes))); + rest = after; + } + _ => return Err(bad()), + } + } + for (kind, name, bytes) in entries { + let path = section.join(name); + match bytes { + None if kind == b'd' => fs::create_dir_all(&path).map_err(|e| StoreError::io("create", &path, e))?, + Some(bytes) => { + if let Some(parent) = path.parent() { + fs::create_dir_all(parent).map_err(|e| StoreError::io("create", parent, e))?; + } + fs::write(&path, bytes).map_err(|e| StoreError::io("write", &path, e))?; + } + None => {} + } + } + Ok(()) +} + +/// The key a section was unlocked with, held in memory to lock it again. Cleared when dropped. +pub struct Key(crypto::Key); + +impl std::fmt::Debug for Key { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Key(..)") + } +} + +fn read_sealed(section: &Path) -> Result<Vec<u8>> { + let file = section.join(SEALED); + fs::read(&file).map_err(|e| StoreError::io("read", &file, e)) +} + +/// Seals the archive into the section's sealed file: written beside it first, read back and +/// opened, and only then put in its place. +fn write_sealed(section: &Path, key: &crypto::Key, archive: &[u8]) -> Result<()> { + let sealed = crypto::seal(key, archive)?; + let file = section.join(SEALED); + let tmp = section.join(format!("{SEALED}.tmp-write")); + let written = (|| { + fs::write(&tmp, &sealed).map_err(|e| StoreError::io("write", &tmp, e))?; + let back = fs::read(&tmp).map_err(|e| StoreError::io("read", &tmp, e))?; + if crypto::open(key, &back).ok().is_none_or(|opened| opened.as_slice() != archive) { + return Err(StoreError::invalid("the sealed section did not read back whole; it was not locked")); + } + fs::rename(&tmp, &file).map_err(|e| StoreError::io("replace", &file, e)) + })(); + if written.is_err() { + let _ = fs::remove_file(&tmp); + } + written +} + +/// Protects a section with a password and locks it (issue #523). Everything in it is sealed and +/// the plain files deleted. +pub fn protect(section: &Path, password: &str) -> Result<()> { + section_only(section)?; + check_password(password)?; + if is_protected(section) { + return Err(StoreError::invalid("this section already has a password")); + } + let key = crypto::Key::new(password)?; + // Marked unlocked first, so a stop part way leaves a section that asks to be locked rather + // than one that says it is locked with its plain files still there. + set_mark(section, "open")?; + write_sealed(section, &key, &pack(section)?)?; + set_protected(section, true)?; + set_mark(section, "sealed")?; + tidy(section) +} + +/// Unlocks a locked section with its password: its content is taken out of the sealed file into +/// its folder. Returns the key to lock it with again. +pub fn unlock(section: &Path, password: &str) -> Result<Key> { + match state(section) { + None => return Err(StoreError::invalid("this section has no password")), + Some(State::Unlocked) => return Err(StoreError::invalid("this section is already unlocked")), + Some(State::Locked) => {} + } + let sealed = read_sealed(section)?; + let key = crypto::Key::derive(password, &sealed)?; + let archive = crypto::open(&key, &sealed)?; + // Whatever a stop part way through left is the sealed file's content again. + tidy(section)?; + set_mark(section, "opening")?; + if let Err(e) = unpack(section, &archive) { + let _ = tidy(section); + return Err(e); + } + set_mark(section, "open")?; + Ok(Key(key)) +} + +/// Locks an unlocked section with the key it was unlocked with: its content is sealed again and +/// the plain files deleted. +pub fn lock(section: &Path, key: &Key) -> Result<()> { + if state(section) != Some(State::Unlocked) { + return Err(StoreError::invalid("this section is not unlocked")); + } + // The key must still open the sealed file: a section whose password was changed elsewhere is + // not sealed with the old one. + crypto::open(&key.0, &read_sealed(section)?)?; + write_sealed(section, &key.0, &pack(section)?)?; + set_mark(section, "sealed")?; + tidy(section) +} + +/// Locks an unlocked section with its password, for one left unlocked when the program stopped. +pub fn lock_with_password(section: &Path, password: &str) -> Result<()> { + if state(section) != Some(State::Unlocked) { + return Err(StoreError::invalid("this section is not unlocked")); + } + let key = crypto::Key::derive(password, &read_sealed(section)?)?; + lock(section, &Key(key)) +} + +/// Changes a section's password. The old one must open it. A locked section stays locked; an +/// unlocked one is sealed with the new password as it is now and stays unlocked, and the key to +/// lock it with is returned. +pub fn change_password(section: &Path, old: &str, new: &str) -> Result<Option<Key>> { + check_password(new)?; + let was = state(section).ok_or_else(|| StoreError::invalid("this section has no password"))?; + let sealed = read_sealed(section)?; + let old_key = crypto::Key::derive(old, &sealed)?; + let archive = crypto::open(&old_key, &sealed)?; + let key = crypto::Key::new(new)?; + match was { + State::Locked => { + write_sealed(section, &key, &archive)?; + Ok(None) + } + State::Unlocked => { + write_sealed(section, &key, &pack(section)?)?; + Ok(Some(Key(key))) + } + } +} + +/// Takes a section's password away: it is unlocked if it is locked, and then kept as an +/// ordinary section, with its sealed file deleted. +pub fn unprotect(section: &Path, password: &str) -> Result<()> { + if state(section) == Some(State::Locked) { + unlock(section, password)?; + } else { + let sealed = read_sealed(section)?; + crypto::open(&crypto::Key::derive(password, &sealed)?, &sealed)?; + } + set_protected(section, false)?; + let file = section.join(SEALED); + fs::remove_file(&file).map_err(|e| StoreError::io("delete", &file, e))?; + remove_mark(section) +} + +#[cfg(not(target_arch = "wasm32"))] +mod crypto { + //! The sealed file: `NCSAFE1\0`, a version byte, Argon2id's memory (KiB), passes and lanes as + //! little-endian u32s, a 16-byte salt and a 24-byte nonce, then the XChaCha20-Poly1305 + //! ciphertext. The header is the cipher's associated data, so it cannot be changed unseen. + + use super::{StoreError, WRONG_PASSWORD}; + use crate::error::Result; + use chacha20poly1305::aead::rand_core::RngCore; + use chacha20poly1305::aead::{Aead, KeyInit, OsRng, Payload}; + use chacha20poly1305::{XChaCha20Poly1305, XNonce}; + use zeroize::Zeroizing; + + const MAGIC: &[u8; 8] = b"NCSAFE1\0"; + const VERSION: u8 = 1; + const HEADER: usize = 8 + 1 + 12 + 16 + 24; + /// Argon2id's cost: 64 MiB of memory and three passes, one lane. Tests use a small cost, so + /// they run quickly; a sealed file says its own cost, so either opens. + #[cfg(not(test))] + const COST: (u32, u32, u32) = (64 * 1024, 3, 1); + #[cfg(test)] + const COST: (u32, u32, u32) = (64, 1, 1); + /// The most a sealed file may ask for, so a damaged or made-up file cannot ask for more + /// memory or time than the program has. + const MOST: (u32, u32, u32) = (1024 * 1024, 64, 16); + + pub struct Key { + key: Zeroizing<[u8; 32]>, + salt: [u8; 16], + cost: (u32, u32, u32), + } + + fn derive(password: &str, salt: &[u8; 16], cost: (u32, u32, u32)) -> Result<Zeroizing<[u8; 32]>> { + let params = argon2::Params::new(cost.0, cost.1, cost.2, Some(32)) + .map_err(|e| StoreError::invalid(format!("the password settings are not valid: {e}")))?; + let argon = argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params); + let mut key = Zeroizing::new([0u8; 32]); + argon + .hash_password_into(password.as_bytes(), salt, key.as_mut()) + .map_err(|e| StoreError::invalid(format!("the key could not be made: {e}")))?; + Ok(key) + } + + fn damaged() -> StoreError { + StoreError::invalid("the sealed section is damaged or was not made by NoteCraft") + } + + impl Key { + /// A new key for `password`, with a salt of its own. + pub fn new(password: &str) -> Result<Key> { + let mut salt = [0u8; 16]; + OsRng.fill_bytes(&mut salt); + Ok(Key { key: derive(password, &salt, COST)?, salt, cost: COST }) + } + + /// The key `password` gives for a sealed file, with its salt and cost. + pub fn derive(password: &str, sealed: &[u8]) -> Result<Key> { + let header = sealed.get(..HEADER).ok_or_else(damaged)?; + if &header[..8] != MAGIC || header[8] != VERSION { + return Err(damaged()); + } + let word = |at: usize| header.get(at..at + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes).ok_or_else(damaged); + let cost = (word(9)?, word(13)?, word(17)?); + if cost.0 > MOST.0 || cost.1 > MOST.1 || cost.2 > MOST.2 { + return Err(damaged()); + } + let salt: [u8; 16] = header[21..37].try_into().map_err(|_| damaged())?; + Ok(Key { key: derive(password, &salt, cost)?, salt, cost }) + } + } + + /// Seals `plain` with a fresh nonce. + pub fn seal(key: &Key, plain: &[u8]) -> Result<Vec<u8>> { + let cipher = XChaCha20Poly1305::new(key.key.as_ref().into()); + let mut nonce = [0u8; 24]; + OsRng.fill_bytes(&mut nonce); + let mut out = Vec::with_capacity(HEADER + plain.len() + 16); + out.extend_from_slice(MAGIC); + out.push(VERSION); + for n in [key.cost.0, key.cost.1, key.cost.2] { + out.extend_from_slice(&n.to_le_bytes()); + } + out.extend_from_slice(&key.salt); + out.extend_from_slice(&nonce); + let sealed = cipher + .encrypt(XNonce::from_slice(&nonce), Payload { msg: plain, aad: &out }) + .map_err(|_| StoreError::invalid("the section could not be sealed"))?; + out.extend_from_slice(&sealed); + Ok(out) + } + + /// Opens a sealed file with `key`. A key that does not open it is a wrong password. + pub fn open(key: &Key, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>> { + let (header, body) = sealed.split_at_checked(HEADER).ok_or_else(damaged)?; + if header[21..37] != key.salt { + return Err(StoreError::invalid(WRONG_PASSWORD)); + } + let cipher = XChaCha20Poly1305::new(key.key.as_ref().into()); + cipher + .decrypt(XNonce::from_slice(&header[37..]), Payload { msg: body, aad: header }) + .map(Zeroizing::new) + .map_err(|_| StoreError::invalid(WRONG_PASSWORD)) + } +} + +#[cfg(target_arch = "wasm32")] +mod crypto { + //! The web build keeps its notebooks in the browser and has no section passwords. + + use super::StoreError; + use crate::error::Result; + use zeroize::Zeroizing; + + pub struct Key; + + fn missing() -> StoreError { + StoreError::invalid("section passwords are not available here") + } + + impl Key { + pub fn new(_password: &str) -> Result<Key> { + Err(missing()) + } + + pub fn derive(_password: &str, _sealed: &[u8]) -> Result<Key> { + Err(missing()) + } + } + + pub fn seal(_key: &Key, _plain: &[u8]) -> Result<Vec<u8>> { + Err(missing()) + } + + pub fn open(_key: &Key, _sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>> { + Err(missing()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::TempDir; + use crate::{PageFormat, Settings, ops, page}; + + const SECRET: &str = "Margarine-ostrich-quill"; + + /// A notebook with a section holding a page (with a picture and a subpage) whose text has + /// `SECRET` in it, in `format`. + fn notebook(t: &TempDir, format: PageFormat) -> (PathBuf, PathBuf, PathBuf) { + let settings = Settings::at(t.path().join("settings.toml")); + let book = ops::create_notebook(t.path(), "Book", Some(format), &settings).expect("notebook"); + let section = ops::create_node(&book, "Private", NodeKind::Section, Some(format), &settings).expect("section"); + let page = ops::create_node(§ion, "Diary", NodeKind::Page, Some(format), &settings).expect("page"); + add(&page, format, &format!("Today: {SECRET}.")); + fs::create_dir_all(page.join("assets")).expect("assets"); + fs::write(page.join("assets").join("photo.png"), format!("picture of {SECRET}")).expect("picture"); + ops::create_node(&page, "Inner", NodeKind::Page, Some(format), &settings).expect("subpage"); + (book, section, page) + } + + /// Adds a paragraph to a page, saved as the window saves it (an earlier version is kept). + fn add(page: &Path, format: PageFormat, words: &str) { + let body = page::load_page(page).expect("load").body; + let more = match format { + PageFormat::Html => format!("{}<p>{words}</p>\n", body.trim_end()), + PageFormat::Cmgfm => format!("{}\n\n{words}\n", body.trim_end()), + }; + page::save_body(page, &more).expect("save"); + } + + /// Every file under `dir` whose bytes hold `SECRET`. + fn readable(dir: &Path) -> Vec<PathBuf> { + let mut out = Vec::new(); + let mut stack = vec![dir.to_path_buf()]; + while let Some(d) = stack.pop() { + for entry in fs::read_dir(&d).into_iter().flatten().flatten() { + let p = entry.path(); + if p.is_dir() { + stack.push(p); + } else if fs::read(&p).is_ok_and(|b| b.windows(SECRET.len()).any(|w| w == SECRET.as_bytes())) { + out.push(p); + } + } + } + out + } + + #[test] + fn a_locked_section_holds_nothing_readable_and_opens_only_with_its_password() { + for format in PageFormat::ALL { + let t = TempDir::new("protect-lock"); + let (book, section, page) = notebook(&t, format); + protect(§ion, "hunter2").expect("protect"); + assert_eq!(state(§ion), Some(State::Locked)); + assert!(readable(&book).is_empty(), "{format:?}: {:?}", readable(&book)); + let mut left: Vec<String> = + fs::read_dir(§ion).expect("dir").flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + left.sort(); + assert_eq!(left, ["_node.toml", SEALED]); + assert!(tree::load_tree(§ion).is_some_and(|n| n.children.is_empty())); + assert!(crate::search::search(&book, SECRET, 10).is_empty()); + + let wrong = unlock(§ion, "hunter3").expect_err("wrong password"); + assert!(is_wrong_password(&wrong), "{wrong}"); + assert_eq!(state(§ion), Some(State::Locked)); + + // Reopened, as after the program starts again: only the password is needed. + let key = unlock(§ion, "hunter2").expect("unlock"); + assert_eq!(state(§ion), Some(State::Unlocked)); + assert!(page::load_page(&page).expect("page").body.contains(SECRET)); + assert!(page.join("assets").join("photo.png").is_file()); + add(&page, format, "And later: tapioca."); + lock(§ion, &key).expect("lock"); + assert!(readable(&book).is_empty()); + assert!(!page.exists()); + + let _key = unlock(§ion, "hunter2").expect("unlock again"); + let body = page::load_page(&page).expect("page").body; + assert!(body.contains(SECRET) && body.contains("tapioca"), "{format:?}: {body}"); + assert_eq!(tree::load_tree(§ion).map(|n| n.count()), Some(3), "the section, its page and the subpage"); + } + } + + #[test] + fn nothing_new_goes_into_a_locked_section() { + for format in PageFormat::ALL { + let t = TempDir::new("protect-guard"); + let (book, section, _) = notebook(&t, format); + let other = + ops::create_node(&book, "Open", NodeKind::Section, Some(format), &Settings::at(t.path().join("settings.toml"))).expect("section"); + let loose = ops::create_node(&other, "Loose", NodeKind::Page, Some(format), &Settings::at(t.path().join("settings.toml"))).expect("page"); + protect(§ion, "pw").expect("protect"); + let made = ops::create_node(§ion, "Sneaky", NodeKind::Page, Some(format), &Settings::at(t.path().join("settings.toml"))); + assert!(made.as_ref().is_err_and(is_locked_error), "{made:?}"); + assert!(ops::move_node(&loose, §ion).is_err_and(|e| is_locked_error(&e))); + assert!(ops::copy_node(&loose, §ion).is_err_and(|e| is_locked_error(&e))); + assert!(loose.is_dir()); + } + } + + #[test] + fn a_section_left_unlocked_is_found_and_locked_again() { + for format in PageFormat::ALL { + let t = TempDir::new("protect-recover"); + let (book, section, page) = notebook(&t, format); + protect(§ion, "pw").expect("protect"); + drop(unlock(§ion, "pw").expect("unlock")); + // The program stopped: the key is gone, the section is open. + assert_eq!(recover(&book), std::slice::from_ref(§ion)); + assert!(lock_with_password(§ion, "nope").is_err_and(|e| is_wrong_password(&e))); + lock_with_password(§ion, "pw").expect("lock"); + assert!(readable(&book).is_empty()); + assert!(recover(&book).is_empty()); + + // Stopped part way through unlocking: the sealed file is all of it, so it is + // simply locked again. + let _key = unlock(§ion, "pw").expect("unlock"); + set_mark(§ion, "opening").expect("mark"); + assert!(recover(&book).is_empty()); + assert_eq!(state(§ion), Some(State::Locked)); + assert!(!page.exists()); + assert!(readable(&book).is_empty()); + } + } + + #[test] + fn the_password_can_be_changed_and_taken_away() { + for format in PageFormat::ALL { + let t = TempDir::new("protect-change"); + let (book, section, page) = notebook(&t, format); + protect(§ion, "first").expect("protect"); + assert!(change_password(§ion, "wrong", "second").is_err_and(|e| is_wrong_password(&e))); + assert!(change_password(§ion, "first", "second").expect("change").is_none()); + assert!(unlock(§ion, "first").is_err_and(|e| is_wrong_password(&e))); + let key = unlock(§ion, "second").expect("unlock"); + let key = change_password(§ion, "second", "third").expect("change").unwrap_or(key); + lock(§ion, &key).expect("lock"); + unprotect(§ion, "third").expect("unprotect"); + assert_eq!(state(§ion), None); + assert!(!section.join(SEALED).exists()); + assert!(page::load_page(&page).expect("page").body.contains(SECRET)); + assert!(!fs::read_to_string(section.join("_node.toml")).expect("node").contains("protected")); + assert!(!readable(&book).is_empty()); + } + } + + #[test] + fn backups_and_the_recycle_bin_never_hold_a_plain_copy() { + for format in PageFormat::ALL { + let t = TempDir::new("protect-copies"); + let (book, section, page) = notebook(&t, format); + protect(§ion, "pw").expect("protect"); + let key = unlock(§ion, "pw").expect("unlock"); + let backups = t.path().join("backups"); + crate::backup::back_up(&book, &backups).expect("backup while unlocked"); + assert!(readable(&backups).is_empty(), "{format:?}: {:?}", readable(&backups)); + + // A page deleted while the section is open is gone, not kept readable in the bin. + let inner = tree::child_dirs(&page).into_iter().next().expect("subpage"); + assert_eq!(crate::recycle::delete(&book, &inner).expect("delete"), 1); + assert!(!inner.exists()); + assert!(crate::recycle::delete(&book, §ion).is_err(), "an open section is locked before it is deleted"); + lock(§ion, &key).expect("lock"); + crate::recycle::delete(&book, §ion).expect("delete the locked section"); + assert!(readable(&book).is_empty()); + assert_eq!(crate::recycle::list(&book).expect("bin").len(), 1); + } + } + + #[test] + fn a_damaged_archive_is_refused_before_anything_is_written() { + let t = TempDir::new("protect-unpack"); + let mut archive = b"NCPACK1\0".to_vec(); + let name = "../escape.txt"; + archive.push(b'f'); + archive.extend_from_slice(&(name.len() as u32).to_le_bytes()); + archive.extend_from_slice(name.as_bytes()); + archive.extend_from_slice(&3u64.to_le_bytes()); + archive.extend_from_slice(b"bad"); + assert!(unpack(t.path(), &archive).is_err()); + assert!(!t.path().parent().expect("parent").join("escape.txt").exists()); + assert!(unpack(t.path(), b"NCPACK1\0f\xff\xff").is_err()); + } +} diff --git a/crates/store/src/recycle.rs b/crates/store/src/recycle.rs index c2971ee9..cb24e5af 100644 --- a/crates/store/src/recycle.rs +++ b/crates/store/src/recycle.rs @@ -67,6 +67,17 @@ pub fn delete(notebook: &Path, path: &Path) -> Result<usize> { } let node = tree::load_tree(&path).ok_or_else(|| StoreError::invalid(format!("{} is not a NoteCraft node", path.display())))?; let count = node.count(); + // A password-protected section keeps no plain copy of what is in it outside its own folder + // (issue #523): a page deleted from it while it is unlocked is deleted, not kept in the bin, + // and the section itself goes to the bin only sealed. + if crate::protect::section_of(&path).is_some_and(|section| section != path) { + crate::protect::refuse_if_locked(&path)?; + crate::ops::remove_tree(&path).map_err(|e| StoreError::io("delete", &path, e))?; + return Ok(count); + } + if crate::protect::protected_sections(&path).iter().any(|s| crate::protect::state(s) == Some(crate::protect::State::Unlocked)) { + return Err(StoreError::invalid("lock its password-protected sections before deleting it")); + } let id = new_id(); let bin = checked_bin(¬ebook, true)?; let entry = bin.join(&id); diff --git a/crates/store/src/search.rs b/crates/store/src/search.rs index e9ce2c24..db0e91fd 100644 --- a/crates/store/src/search.rs +++ b/crates/store/src/search.rs @@ -292,6 +292,14 @@ fn cache() -> std::sync::MutexGuard<'static, Cache> { }) } +/// Forgets what was read for searching from every page under `dir`, for a section just locked +/// with a password (issue #523): nothing it held stays in memory for the next search. +pub fn forget_under(dir: &Path) { + let mut cache = cache(); + cache.pages.retain(|page, _| !page.starts_with(dir)); + cache.built.retain(|built| !built.key.iter().any(|(page, _)| page.starts_with(dir))); +} + /// The index over `pages`, built now or kept from an earlier search of the same, unchanged pages. fn built_for(pages: &[PathBuf]) -> std::sync::Arc<Built> { let stamps: Vec<Option<Stamp>> = pages.iter().map(|dir| stamp_of(dir)).collect(); diff --git a/crates/store/src/tree.rs b/crates/store/src/tree.rs index 7c19e6d7..c8529d72 100644 --- a/crates/store/src/tree.rs +++ b/crates/store/src/tree.rs @@ -20,6 +20,9 @@ pub struct NodeInfo { /// For a page, whether it is locked read only, as its own head says (issue #441). Always /// false for a notebook, group or section. pub read_only: bool, + /// For a section with a password, whether it is locked or open (issue #523). `None` for + /// everything else. + pub protected: Option<crate::protect::State>, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -110,6 +113,7 @@ pub fn read_node(dir: &Path) -> Option<NodeInfo> { id: id.unwrap_or_default(), order: order.unwrap_or(0), read_only: crate::page::read_only_in(format, &text), + protected: None, }); } let text = fs::read_to_string(dir.join("_node.toml")).ok()?; @@ -122,6 +126,7 @@ pub fn read_node(dir: &Path) -> Option<NodeInfo> { id: map.get("id").cloned().unwrap_or_default(), order: map.get("order").and_then(|v| v.parse().ok()).unwrap_or(0), read_only: false, + protected: crate::protect::state_in(dir, &map), }) } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 69abbd1c..8deb1eaa 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -15,6 +15,8 @@ default = [] voice = ["dep:craft-voice-core", "dep:craft-voice-runtime", "craft-voice-runtime/microphone"] [dependencies] +# Clears typed section passwords from memory once they are used (issue #523). +zeroize = "1" craft-voice-core = { workspace = true, optional = true } craft-voice-runtime = { workspace = true, optional = true } craft-i18n = { workspace = true } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index da0a470a..6adac8c7 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -89,8 +89,12 @@ fn fetch_page_files(dir: &Path, wait: Duration) -> Option<std::sync::mpsc::Recei /// How far a pen may move in a tap that is still a click, in points (egui allows a mouse 6). const PEN_CLICK_DIST: f32 = 12.0; const AUTOSAVE_AFTER: Duration = Duration::from_millis(900); +#[path = "app/linked_notes.rs"] +mod linked_notes; #[path = "app/proofing.rs"] mod proofing; +#[path = "app/section_locks.rs"] +mod section_locks; #[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))] mod transcribe; #[cfg(feature = "voice")] @@ -1812,6 +1816,10 @@ enum Act { MoveOrCopy(PathBuf), /// Open Merge into Another Section for a section (issue #517). MergeSection(PathBuf), + /// Ask for a section's password, to give, change or take it away (issue #523). + SectionPassword(PathBuf, section_locks::Ask), + /// Lock a password-protected section this window unlocked (issue #523). + LockSection(PathBuf), MakeSubpage(PathBuf), PromoteSubpage(PathBuf), MovePageUp(PathBuf), @@ -1980,6 +1988,10 @@ pub struct NoteCraftApp { last_find: String, /// Review > Check Accessibility's findings are shown beside the page (issue #520). accessibility_open: bool, + /// Review > Linked Notes: the pane and the session (issue #522). + linked_notes: linked_notes::LinkedNotes, + /// The keys of the password-protected sections this window unlocked (issue #523). + section_locks: section_locks::SectionLocks, /// Review > Spelling, Language and Thesaurus: the dictionaries, the language and the checker /// (issues #276 and #524). proofing: crate::spelling::Proofing, @@ -2341,6 +2353,8 @@ impl NoteCraftApp { page_find: None, last_find: String::new(), accessibility_open: false, + linked_notes: linked_notes::LinkedNotes::default(), + section_locks: section_locks::SectionLocks::default(), proofing: session_proofing, proofing_list: None, spelling: None, @@ -2577,6 +2591,8 @@ impl NoteCraftApp { /// and how far down the page is scrolled. pub fn before_close(&mut self) { self.save_now(); + // Nothing this window unlocked is left readable once it is gone (issue #523). + self.lock_all_sections(); if self.secondary_window { return; } @@ -5874,6 +5890,12 @@ impl NoteCraftApp { Act::Rename(path, title) => self.dialog = Some(Dialog::Rename { path, title }), Act::MoveOrCopy(path) => self.open_move_or_copy(&path), Act::MergeSection(path) => self.open_merge_section(&path), + Act::SectionPassword(path, ask) => self.ask_section_password(&path, ask), + Act::LockSection(path) => { + if let Err(e) = self.lock_section(&path) { + self.complain(&e); + } + } Act::MakeSubpage(path) => self.reparent_page(&path, "node.demote"), Act::PromoteSubpage(path) => self.reparent_page(&path, "node.promote"), Act::MovePageUp(path) => { @@ -6234,6 +6256,10 @@ impl NoteCraftApp { acts.push(Act::MoveOrCopy(node.path.clone())); ui.close(); } + // A section's password (issue #523), with OneNote's Password Protect This Section. + if node.info.kind == NodeKind::Section { + self.section_menu_rows(ui, &node.path, acts); + } // OneNote's Merge into Another Section, on a section's own menu (issue #517). if node.info.kind == NodeKind::Section && floating::menu_row_if(ui, !edits_off, Some(floating::Glyph::Icon(Icon::MoveDown)), crate::tl_id!("ui.merge_into_another_section"), t) @@ -7529,6 +7555,59 @@ impl NoteCraftApp { self.say(crate::i18n::format_message_id("ui.link_to_title_copied", &[("title", &title)])); } + /// The page's menu > Copy Link to Paragraph (issue #530): the paragraph is given an id kept in + /// the page's own file, and a link to the page with that id goes on the clipboard. The page is + /// saved first, so the paragraph numbered is the one on screen. + pub fn copy_link_to_paragraph(&mut self, block: usize) { + self.save_now(); + if self.page_conflict { + return; + } + let Some(ed) = self.editor.as_ref() else { return }; + let dir = ed.dir.clone(); + let words = ed.blocks.get(block).map(|b| notecraft_formats::render::blocks_to_text(std::slice::from_ref(b))).unwrap_or_default(); + let id = match notecraft_store::paragraphs::anchor_paragraph(&dir, block) { + Ok(id) => id, + Err(e) => { + self.complain(&e.to_string()); + return; + } + }; + // The id is in the page's head: the window's own write, not another's. + self.page_revision = crate::windows::Revision::read(&dir).ok(); + let mut roots = vec![self.session.root().to_path_buf()]; + roots.extend(self.session.opened_elsewhere().iter().cloned()); + let Some(uri) = notecraft_store::links::paragraph_uri(&roots, &dir, &id) else { + self.complain(crate::tl_id!("ui.that_page_is_not_in_a_notebook_that_is_open")); + return; + }; + let mut label: String = words.split_whitespace().collect::<Vec<_>>().join(" "); + if label.chars().count() > 60 { + label = format!("{}\u{2026}", label.chars().take(59).collect::<String>()); + } + if label.is_empty() { + label = notecraft_store::tree::read_node(&dir).map(|n| n.title).unwrap_or_else(|| "Page".to_string()); + } + self.pending_copy = Some(format!("{label} ({uri})")); + self.pending_copy_html = Some(crate::clipboard::html_link(&label, &uri)); + self.say(crate::tl_id!("ui.link_to_paragraph_copied")); + } + + /// After a link to a paragraph opened its page (issue #530): the caret goes to the paragraph, + /// brought into view, or the window says it is no longer there. + fn go_to_paragraph(&mut self, ctx: &Context, dir: &Path, id: &str) { + if self.editor.as_ref().is_none_or(|ed| ed.dir != dir) { + return; + } + match notecraft_store::paragraphs::find_paragraph(dir, id) { + Ok(Some(block)) => self.go_to_block(ctx, block), + _ => { + self.status = crate::tl_id!("ui.the_linked_paragraph_is_no_longer_on_this_page").to_string(); + self.status_is_error = true; + } + } + } + pub fn follow_link(&mut self, ctx: &Context, href: &str) { use notecraft_store::links::{Link, resolve_in}; let Some(page) = self.editor.as_ref().map(|e| e.dir.clone()) else { return }; @@ -7545,6 +7624,9 @@ impl NoteCraftApp { Link::Node(dir) => { if notecraft_store::tree::read_node(&dir).is_some_and(|n| n.kind == NodeKind::Page) { self.open_path(&path_str(&dir)); + if let Some(id) = notecraft_store::links::paragraph_of(href) { + self.go_to_paragraph(ctx, &dir, &id); + } } else if self.kind_in_tree(&dir) == Some(NodeKind::Section) { // A section's link opens it where it was left, or its first page, or says // it has none (issue #518), as choosing it in the notebooks does. @@ -7672,6 +7754,7 @@ impl NoteCraftApp { can_ink_redo: self.pad.as_ref().is_some_and(crate::inkpad::Pad::can_redo), ink_held: self.pad.as_ref().is_some_and(|pad| pad.holding() > 0), accessibility_open: self.accessibility_open, + linked_notes_open: self.linked_notes.open || self.linked_notes.session.is_some(), spelling_open: self.spelling.is_some(), thesaurus_open: self.thesaurus.is_some(), proofing_language: self.proofing.chosen(), @@ -8389,6 +8472,13 @@ impl NoteCraftApp { ribbon::Act::Paste => self.paste_here(), ribbon::Act::PastePlain => self.paste_plain(), ribbon::Act::PasteMerge => self.paste_merged(), + ribbon::Act::CopyParagraphLink(block) => self.copy_link_to_paragraph(block), + ribbon::Act::LinkedNotes => self.toggle_linked_notes(), + ribbon::Act::SectionPassword => self.section_password_for_current(), + ribbon::Act::LockAllSections => { + let locked = self.lock_all_sections(); + self.say(crate::i18n::format_count_message_id("ui.sections_locked_n", locked as u64, &[])); + } ribbon::Act::SetReadOnly(locked) => { if let Some(dir) = self.editor.as_ref().map(|e| e.dir.clone()) { self.set_read_only(&dir, locked); @@ -12189,14 +12279,20 @@ impl NoteCraftApp { /// Takes the page to a finding (issue #520): a picture block is selected, so its Alt Text is /// a right click away; anything else gets the caret at its start, brought into view. fn go_to_finding(&mut self, ctx: &Context, finding: &crate::accessibility::Finding) { + self.go_to_block(ctx, finding.block); + } + + /// Takes the page to one of its blocks: a picture is selected; anything else gets the caret at + /// its start, brought into view. + fn go_to_block(&mut self, ctx: &Context, at: usize) { let Some(ed) = self.editor.as_mut() else { return }; - let Some(block) = ed.blocks.get(finding.block) else { return }; + let Some(block) = ed.blocks.get(at) else { return }; if matches!(block, notecraft_formats::Block::Image { .. }) { ed.caret = None; - crate::containers::select_object(ctx, &ed.dir, finding.block, "image"); + crate::containers::select_object(ctx, &ed.dir, at, "image"); } else if pageedit::is_writable(block) { ed.caret = Some(pageedit::Caret { - block: finding.block, + block: at, text: pageedit::caret_text(block), focus: true, selection: (0, 0), @@ -12207,7 +12303,7 @@ impl NoteCraftApp { }); } let id = pageedit::find_marks_id(ctx); - ctx.data_mut(|d| d.get_temp_mut_or_default::<pageedit::FindMarks>(id).reveal = Some(finding.block)); + ctx.data_mut(|d| d.get_temp_mut_or_default::<pageedit::FindMarks>(id).reveal = Some(at)); pageedit::reveal_caret(ctx); } @@ -13540,6 +13636,8 @@ impl NoteCraftApp { }); } let section = self.current_section(self.session.tree()).map(|n| (n.path.clone(), n.info.title.clone(), n.children.clone(), n.info.color)); + // A locked section has no pages to list or add to (issue #523). + let locked = self.current_section(self.session.tree()).is_some_and(|n| n.info.protected == Some(notecraft_store::protect::State::Locked)); // In the tabs layout the pages can be on the right of the page instead (issue #534): a // panel of its own name, so each side keeps the width it was dragged to. let panel = match (self.tabs_layout && self.pages_right, narrow) { @@ -13578,6 +13676,11 @@ impl NoteCraftApp { }); // The same create-and-open as Ctrl+N and the menu's New page (issue #366): // one click is one new page, opened at its title, with no name to type first. + if locked { + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::tl_id!("ui.this_section_is_password_protected")).color(self.tokens.text)); + return; + } if self.add_page_row(ui, accent).clicked() { acts.push(Act::NewPage(path.clone())); } @@ -13751,6 +13854,15 @@ impl NoteCraftApp { } return; } + // A locked section shows a box for its password where its pages would be (issue #523). + if self.editor.is_none() + && let Some((section, title)) = &empty_section + && notecraft_store::protect::state(section) == Some(notecraft_store::protect::State::Locked) + { + let (section, title) = (section.clone(), title.clone()); + self.locked_section_panel(ui, §ion, &title); + return; + } if self.editor.is_none() && let Some((section, title)) = empty_section { @@ -16130,7 +16242,11 @@ impl NoteCraftApp { *count as u64, &[("title", title)], )); - ui.label(egui::RichText::new(crate::tl_id!("ui.you_can_restore_it_from_history")).color(self.tokens.muted)); + if notecraft_store::protect::section_of(path).is_some_and(|s| s != *path) { + ui.colored_label(self.tokens.warn, crate::tl_id!("ui.deleted_for_good_in_a_protected_section")); + } else { + ui.label(egui::RichText::new(crate::tl_id!("ui.you_can_restore_it_from_history")).color(self.tokens.muted)); + } } ui.add_space(12.0); ui.horizontal(|ui| { @@ -17391,6 +17507,8 @@ impl NoteCraftApp { "pickedPages": self.picked_in_order().iter().map(|p| self.shown(p)).collect::<Vec<_>>(), "pinnedSearch": self.pinned_search.as_ref().map(|p| json!({"query": p.query, "scope": p.scope, "hits": p.hits.len(), "chosen": p.chosen})), "proofing": self.proofing_state(), + "linkedNotes": self.linked_notes_state(), + "sectionLocks": self.section_locks_state(), "accessibility": json!({ "open": self.accessibility_open, "findings": self.editor.as_ref().map(|ed| crate::accessibility::check(&ed.blocks)).unwrap_or_default() @@ -17876,6 +17994,7 @@ impl NoteCraftApp { self.direction_keys(ctx); self.hierarchy_keys(ctx); self.restore_last_page(); + self.section_locks_tick(ctx); self.attach_dropped(ctx); if matches!(self.backstage, Some("Export" | "Share")) && self.dialog.is_none() @@ -17913,6 +18032,7 @@ impl NoteCraftApp { self.templates_panel(ui); self.pinned_search_panel(ui); self.accessibility_panel(ui); + self.linked_notes_panel(ui); self.spelling_panel(ui); self.thesaurus_panel(ui); self.page_find_bar(ui); @@ -20399,7 +20519,7 @@ mod band_title_tests { fn node(kind: NodeKind, path: &str, title: &str, children: Vec<Node>) -> Node { Node { path: PathBuf::from(path), - info: NodeInfo { kind, title: title.into(), color: None, format: None, id: title.into(), order: 0, read_only: false }, + info: NodeInfo { kind, title: title.into(), color: None, format: None, id: title.into(), order: 0, read_only: false, protected: None }, children, } } diff --git a/crates/ui-egui/src/app/linked_notes.rs b/crates/ui-egui/src/app/linked_notes.rs new file mode 100644 index 00000000..4537b4a2 --- /dev/null +++ b/crates/ui-egui/src/app/linked_notes.rs @@ -0,0 +1,320 @@ +//! Review > Linked Notes in the window (issue #522): a session the person starts with a source +//! they choose, while which every paragraph written on a page is tied to that source, and a pane +//! that lists the page's linked paragraphs and opens their sources again. +//! +//! OneNote's Linked Notes docks the window beside the browser or document being read, and notes +//! the page or file each paragraph was written against. NoteCraft does not look at other programs: +//! the source is what the person typed, pasted or picked (a web address, a file, a NoteCraft page), +//! so nothing is recorded that they did not choose. Starting docks the window as View > Dock to +//! Desktop does. The session is off until it is started, and nothing is kept outside the page. + +use super::NoteCraftApp; +#[cfg(target_os = "android")] +use crate::filepicker as rfd; +use egui::{Context, Ui}; +use notecraft_model::linked::{Kind, Source}; +use notecraft_store::paragraphs::LinkedParagraph; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +/// Linked Notes' state in a window. +#[derive(Default)] +pub(super) struct LinkedNotes { + /// Whether the pane is shown beside the page. + pub open: bool, + /// The source paragraphs are tied to while a session runs; `None` when none is. + pub session: Option<Source>, + /// What is typed in the pane's source box. + pub typed: String, + /// The page's body as last tied: what is written after it is what the session ties. + base: Option<(PathBuf, String)>, + /// Why the last start was refused. + pub problem: Option<String>, + /// The page's linked paragraphs, read again when the page changes. + listed: Option<(PathBuf, Option<crate::windows::Revision>, Vec<LinkedParagraph>)>, +} + +impl NoteCraftApp { + /// Review > Linked Notes: shows or hides the pane. + pub fn toggle_linked_notes(&mut self) { + self.linked_notes.open = !self.linked_notes.open; + } + + /// Whether a Linked Notes session is running. + pub fn linked_notes_running(&self) -> bool { + self.linked_notes.session.is_some() + } + + /// Starts a Linked Notes session with the source `text` names: a web address, a + /// `notecraft:` link to a page, or a file on this computer. The window docks to the side of + /// the screen, as OneNote's does, unless it is docked already. + pub fn start_linked_notes(&mut self, ctx: &Context, text: &str) -> Result<(), String> { + let Some(source) = Source::from_text(text) else { + let why = crate::tl_id!("ui.linked_notes_no_source").to_string(); + self.linked_notes.problem = Some(why.clone()); + return Err(why); + }; + let problem = match source.kind { + Kind::File if !Path::new(&source.target).is_file() => Some(crate::tl_id!("ui.linked_notes_no_such_file").to_string()), + Kind::Page if !matches!(self.resolve_source_page(&source.target), Some(notecraft_store::links::Link::Node(_))) => { + Some(crate::tl_id!("ui.linked_notes_no_such_page").to_string()) + } + _ => None, + }; + if let Some(why) = problem { + self.linked_notes.problem = Some(why.clone()); + return Err(why); + } + // What is on the page now was not written against this source. + self.save_now(); + self.linked_notes.base = self.editor.as_ref().map(|ed| (ed.dir.clone(), ed.saved_body.clone())); + self.linked_notes.problem = None; + self.linked_notes.typed = source.target.clone(); + self.say(crate::i18n::format_message_id("ui.linked_notes_started", &[("source", &source.title)])); + self.linked_notes.session = Some(source); + self.linked_notes.open = true; + if !self.is_docked() { + self.toggle_dock(ctx); + } + Ok(()) + } + + /// Stops the session. What was tied stays tied; the window stays where it is. + pub fn stop_linked_notes(&mut self) { + self.save_now(); + self.tie_linked_notes(); + if self.linked_notes.session.take().is_some() { + self.say(crate::tl_id!("ui.linked_notes_stopped")); + } + self.linked_notes.base = None; + } + + fn resolve_source_page(&self, target: &str) -> Option<notecraft_store::links::Link> { + let mut roots = vec![self.session.root().to_path_buf()]; + roots.extend(self.session.opened_elsewhere().iter().cloned()); + let here = self.editor.as_ref().map(|ed| ed.dir.clone()).unwrap_or_else(|| self.session.root().to_path_buf()); + Some(notecraft_store::links::resolve_in(&roots, &here, target)) + } + + /// While a session runs, the paragraphs written since the page was last tied are tied to its + /// source, once the page is saved. Called every frame; it does nothing until there is something + /// to tie. + pub(super) fn tie_linked_notes(&mut self) { + let Some(source) = self.linked_notes.session.clone() else { return }; + let Some(ed) = self.editor.as_ref() else { return }; + if self.page_conflict || self.saver.busy() || ed.saving.is_some() { + return; + } + let (dir, saved) = (ed.dir.clone(), ed.saved_body.clone()); + match &self.linked_notes.base { + Some((was, body)) if *was == dir => { + if *body == saved { + return; + } + let old = body.clone(); + match notecraft_store::paragraphs::link_written(&dir, &old, &source) { + Ok(tied) => { + if tied > 0 { + // The links are in the page's head: the window's own write. + self.page_revision = crate::windows::Revision::read(&dir).ok(); + self.linked_notes.listed = None; + } + } + Err(e) => log::warn!("linked notes: {e}"), + } + self.linked_notes.base = Some((dir, saved)); + } + // Another page: what it already has was not written in this session. + _ => self.linked_notes.base = Some((dir, saved)), + } + } + + /// The open page's paragraphs that have a source. + pub fn linked_paragraphs(&mut self) -> Vec<LinkedParagraph> { + let Some(dir) = self.editor.as_ref().map(|ed| ed.dir.clone()) else { return Vec::new() }; + let stamp = crate::windows::Revision::read(&dir).ok(); + if let Some((d, s, list)) = &self.linked_notes.listed + && *d == dir + && *s == stamp + { + return list.clone(); + } + let list = notecraft_store::paragraphs::linked_paragraphs(&dir).unwrap_or_default(); + self.linked_notes.listed = Some((dir, stamp, list.clone())); + list + } + + /// Opens a source again: a web page in the browser, a page in this window, a file in the + /// program the system has for it (after the same warning an attachment gets). + pub fn open_linked_source(&mut self, ctx: &Context, source: &Source) { + match source.kind { + Kind::Web => { + ctx.open_url(egui::OpenUrl::new_tab(source.target.clone())); + self.say(crate::i18n::format_message_id("ui.opened_url_in_the_browser", &[("url", &source.target)])); + } + Kind::Page => self.follow_link(ctx, &source.target.clone()), + Kind::File => { + let file = PathBuf::from(&source.target); + if !file.is_file() { + self.complain(crate::tl_id!("ui.linked_notes_no_such_file")); + } else if self.open_attachment_warning_suppressed { + if let Err(e) = super::open_file_for_viewer(&file) { + self.complain(&crate::i18n::format_message_id("ui.the_file_could_not_be_opened_error", &[("error", &e.to_string())])); + } + } else { + self.dialog = Some(super::Dialog::OpenAttachmentWarning { path: file }); + } + } + } + } + + /// Takes the source off the paragraph at `block`. + pub fn unlink_paragraph(&mut self, block: usize) { + let Some(dir) = self.editor.as_ref().map(|ed| ed.dir.clone()) else { return }; + self.save_now(); + match notecraft_store::paragraphs::unlink_paragraph(&dir, block) { + Ok(_) => { + self.page_revision = crate::windows::Revision::read(&dir).ok(); + self.linked_notes.listed = None; + } + Err(e) => self.complain(&e.to_string()), + } + } + + /// What `ui.inspect` reports. + pub(super) fn linked_notes_state(&self) -> Value { + let paragraphs = self.editor.as_ref().and_then(|ed| notecraft_store::paragraphs::linked_paragraphs(&ed.dir).ok()).unwrap_or_default(); + json!({ + "open": self.linked_notes.open, + "running": self.linked_notes.session.as_ref().map(|s| json!({"kind": s.kind.id(), "target": s.target, "title": s.title})), + "problem": self.linked_notes.problem, + "paragraphs": paragraphs.iter().map(|p| json!({"block": p.block, "source": p.source.target, "kind": p.source.kind.id()})).collect::<Vec<_>>(), + }) + } + + #[cfg(not(target_arch = "wasm32"))] + fn pick_source_file(&mut self) { + if let Some(file) = rfd::FileDialog::new().set_title(crate::tl_id!("ui.linked_notes_choose_file")).pick_file() { + self.linked_notes.typed = file.to_string_lossy().into_owned(); + } + } + + #[cfg(target_arch = "wasm32")] + fn pick_source_file(&mut self) {} + + /// The Linked Notes pane, beside the page. + pub(super) fn linked_notes_panel(&mut self, ui: &mut Ui) { + self.tie_linked_notes(); + if !self.linked_notes.open { + return; + } + let ctx = ui.ctx().clone(); + let tokens = self.tokens; + let paragraphs = self.linked_paragraphs(); + let blocks = self.editor.as_ref().map(|ed| ed.blocks.clone()).unwrap_or_default(); + let running = self.linked_notes.session.clone(); + let problem = self.linked_notes.problem.clone(); + let mut typed = self.linked_notes.typed.clone(); + let (mut close, mut start, mut stop, mut browse) = (false, false, false, false); + let (mut open, mut go, mut unlink) = (None::<Source>, None::<usize>, None::<usize>); + let panel = if self.compact { + egui::Panel::right("linked-notes-compact").resizable(false).exact_size(ui.available_width()) + } else { + egui::Panel::right("linked-notes").resizable(true).default_size(300.0).size_range(220.0..=600.0) + }; + panel.show(ui, |ui| { + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.strong(crate::tl_id!("ui.linked_notes")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl_id!("ui.close")).clicked() { + close = true; + } + }); + }); + match &running { + Some(source) => { + ui.label(crate::i18n::format_message_id("ui.linked_notes_linking_to", &[("source", &source.title)])); + ui.label(egui::RichText::new(&source.target).small().color(tokens.muted)); + if ui.button(crate::tl_id!("ui.linked_notes_stop")).clicked() { + stop = true; + } + } + None => { + ui.label(egui::RichText::new(crate::tl_id!("ui.linked_notes_about")).small().color(tokens.muted)); + ui.add( + egui::TextEdit::singleline(&mut typed).hint_text(crate::tl_id!("ui.linked_notes_source_hint")).desired_width(f32::INFINITY), + ) + .labelled_by(ui.label(crate::tl_id!("ui.linked_notes_source")).id); + ui.horizontal(|ui| { + if ui.button(crate::tl_id!("ui.linked_notes_browse")).clicked() { + browse = true; + } + if ui.add_enabled(!typed.trim().is_empty(), egui::Button::new(crate::tl_id!("ui.linked_notes_start"))).clicked() { + start = true; + } + }); + if let Some(why) = &problem { + ui.label(egui::RichText::new(why).small().color(tokens.warn)); + } + } + } + ui.separator(); + ui.label(egui::RichText::new(crate::tl_id!("ui.linked_notes_on_this_page")).strong()); + if paragraphs.is_empty() { + ui.label(egui::RichText::new(crate::tl_id!("ui.linked_notes_none")).small().color(tokens.muted)); + } + egui::ScrollArea::vertical().id_salt("linked-notes-list").auto_shrink([false, false]).show(ui, |ui| { + for (n, p) in paragraphs.iter().enumerate() { + ui.push_id(n, |ui| { + let words = blocks + .get(p.block) + .map(|b| notecraft_formats::render::blocks_to_text(std::slice::from_ref(b))) + .unwrap_or_default() + .split_whitespace() + .collect::<Vec<_>>() + .join(" "); + let shown: String = + if words.chars().count() > 80 { format!("{}\u{2026}", words.chars().take(79).collect::<String>()) } else { words }; + if ui.link(shown).clicked() { + go = Some(p.block); + } + ui.label(egui::RichText::new(&p.source.title).small().color(tokens.muted)).on_hover_text(&p.source.target); + ui.horizontal(|ui| { + let open_label = crate::i18n::format_message_id("ui.linked_notes_open_source", &[("source", &p.source.title)]); + if ui.small_button(crate::tl_id!("ui.linked_notes_open")).on_hover_text(open_label).clicked() { + open = Some(p.source.clone()); + } + if ui.small_button(crate::tl_id!("ui.linked_notes_unlink")).clicked() { + unlink = Some(p.block); + } + }); + ui.separator(); + }); + } + }); + }); + self.linked_notes.typed = typed.clone(); + if close { + self.linked_notes.open = false; + } + if browse { + self.pick_source_file(); + } + if start { + let _ = self.start_linked_notes(&ctx, &typed); + } + if stop { + self.stop_linked_notes(); + } + if let Some(source) = open { + self.open_linked_source(&ctx, &source); + } + if let Some(block) = go { + self.go_to_block(&ctx, block); + } + if let Some(block) = unlink { + self.unlink_paragraph(block); + } + } +} diff --git a/crates/ui-egui/src/app/section_locks.rs b/crates/ui-egui/src/app/section_locks.rs new file mode 100644 index 00000000..cedb9a03 --- /dev/null +++ b/crates/ui-egui/src/app/section_locks.rs @@ -0,0 +1,446 @@ +//! Password-protected sections in the window (issue #523). +//! +//! A section's menu protects it with a password, unlocks, locks, changes the password or takes it +//! away; Review > Password does the same for the open section and Review > Lock All locks every +//! section this window unlocked. A locked section shows a box for its password where its pages +//! would be. The store seals the section's content (see `notecraft_store::protect`); the window +//! holds the key of each section it unlocked, in memory only, and locks them all again after a +//! while with no input, and when it closes. A section the program left unlocked when it last +//! stopped is found when the window starts, and its password asked for to lock it again. + +use super::NoteCraftApp; +use crate::floating::{self, Glyph}; +use crate::icons::Icon; +use egui::{Context, Ui}; +use notecraft_model::NodeKind; +use notecraft_store::protect::{self, Key, State}; +use serde_json::{Value, json}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use zeroize::Zeroize; + +/// The setting for how many minutes without input lock the window's unlocked sections again. +pub(super) const IDLE_KEY: &str = "section_lock_idle_minutes"; +const IDLE_DEFAULT: u32 = 10; + +/// What a section's password is asked for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ask { + /// Give a section a password (and lock it). + Protect, + /// Change it: the old one, then the new one twice. + Change, + /// Take it away: the section is kept unlocked, as an ordinary section. + Remove, + /// Lock a section left unlocked when the program last stopped. + LockLeftOpen, +} + +/// The password window open for a section. +pub(super) struct Asking { + section: PathBuf, + ask: Ask, + password: String, + new_password: String, + confirm: String, + problem: Option<String>, + focus: bool, +} + +impl Drop for Asking { + fn drop(&mut self) { + self.password.zeroize(); + self.new_password.zeroize(); + self.confirm.zeroize(); + } +} + +/// The window's protected sections. +#[derive(Default)] +pub(super) struct SectionLocks { + /// The key of each section this window unlocked. + keys: HashMap<PathBuf, Key>, + asking: Option<Asking>, + /// Sections found unlocked when the window started, still to be asked about. + left_open: Vec<PathBuf>, + /// Whether the notebooks were looked at for sections left unlocked. + recovered: bool, + /// When input was last seen, in egui's seconds. + last_input: f64, + /// What is typed in the locked section's password box, and why the last try failed. + typed: String, + problem: Option<(PathBuf, String)>, + /// Pictures drawn from a section just locked are still in egui's memory: forgotten next frame. + forget_pictures: bool, + /// Minutes without input before unlocked sections lock again; read again after each unlock. + idle_minutes: Option<u32>, +} + +impl NoteCraftApp { + /// The section the open page is in, or the one selected in the navigator. + pub(super) fn section_of_open_page(&self) -> Option<PathBuf> { + let at = self.editor.as_ref().map(|ed| ed.dir.clone()).or_else(|| self.selected.clone())?; + at.ancestors().find(|dir| self.kind_in_tree(dir) == Some(NodeKind::Section)).map(Path::to_path_buf) + } + + /// Whether the open page is in `section`; it is saved first, and `false` with an error when it + /// cannot be, so nothing unsaved is sealed away or lost. + fn leave_section(&mut self, section: &Path) -> Result<(), String> { + if self.editor.as_ref().is_none_or(|ed| !ed.dir.starts_with(section)) { + return Ok(()); + } + self.save_now(); + if self.is_dirty() || self.page_conflict { + return Err(crate::tl_id!("ui.section_lock_save_first").to_string()); + } + if let Some(left) = self.editor.as_ref().map(|e| e.dir.clone()) { + self.note_read(&left, false); + } + self.editor = None; + self.pad = None; + self.opening = None; + self.page_revision = None; + self.selected = Some(section.to_path_buf()); + Ok(()) + } + + /// After a section is sealed: nothing read from it stays in the window's memory. + fn sealed(&mut self, section: &Path) { + self.section_locks.keys.remove(section); + self.section_locks.forget_pictures = true; + notecraft_store::search::forget_under(section); + if self.selected.as_ref().is_some_and(|s| s.starts_with(section)) { + self.selected = Some(section.to_path_buf()); + } + self.session.refresh(); + } + + /// Gives a section a password and locks it. + pub fn protect_section(&mut self, section: &Path, password: &str) -> Result<(), String> { + self.leave_section(section)?; + protect::protect(section, password).map_err(|e| e.to_string())?; + self.sealed(section); + self.say(crate::tl_id!("ui.section_protected")); + Ok(()) + } + + /// Unlocks a locked section with its password and opens it. + pub fn unlock_section(&mut self, section: &Path, password: &str) -> Result<(), String> { + let key = protect::unlock(section, password) + .map_err(|e| if protect::is_wrong_password(&e) { crate::tl_id!("ui.section_wrong_password").to_string() } else { e.to_string() })?; + self.section_locks.keys.insert(section.to_path_buf(), key); + self.section_locks.problem = None; + self.section_locks.idle_minutes = None; + self.session.refresh(); + self.say(crate::tl_id!("ui.section_unlocked")); + self.open_section(section); + Ok(()) + } + + /// Locks a section this window unlocked. + pub fn lock_section(&mut self, section: &Path) -> Result<(), String> { + if !self.section_locks.keys.contains_key(section) { + // Unlocked elsewhere, or before the window started: its password is asked for. + self.ask_section_password(section, Ask::LockLeftOpen); + return Ok(()); + } + self.leave_section(section)?; + let key = self.section_locks.keys.get(section).ok_or_else(|| crate::tl_id!("ui.section_lock_failed").to_string())?; + protect::lock(section, key).map_err(|e| e.to_string())?; + self.sealed(section); + Ok(()) + } + + /// Review > Lock All, the idle timer and closing: every section this window unlocked is + /// locked. Returns how many were; one that cannot be (its page will not save) stays open. + pub fn lock_all_sections(&mut self) -> usize { + let open: Vec<PathBuf> = self.section_locks.keys.keys().cloned().collect(); + let mut locked = 0; + for section in open { + match self.lock_section(§ion) { + Ok(()) => locked += 1, + Err(e) => log::warn!("could not lock {}: {e}", section.display()), + } + } + locked + } + + /// Changes a section's password. + pub fn change_section_password(&mut self, section: &Path, old: &str, new: &str) -> Result<(), String> { + let key = protect::change_password(section, old, new) + .map_err(|e| if protect::is_wrong_password(&e) { crate::tl_id!("ui.section_wrong_password").to_string() } else { e.to_string() })?; + if let Some(key) = key { + self.section_locks.keys.insert(section.to_path_buf(), key); + } + self.say(crate::tl_id!("ui.section_password_changed")); + Ok(()) + } + + /// Takes a section's password away; it is kept as an ordinary section, unlocked. + pub fn remove_section_password(&mut self, section: &Path, password: &str) -> Result<(), String> { + protect::unprotect(section, password) + .map_err(|e| if protect::is_wrong_password(&e) { crate::tl_id!("ui.section_wrong_password").to_string() } else { e.to_string() })?; + self.section_locks.keys.remove(section); + self.session.refresh(); + self.say(crate::tl_id!("ui.section_password_removed")); + Ok(()) + } + + /// Locks a section left unlocked when the program last stopped, with its password. + pub fn lock_left_open_section(&mut self, section: &Path, password: &str) -> Result<(), String> { + self.leave_section(section)?; + protect::lock_with_password(section, password) + .map_err(|e| if protect::is_wrong_password(&e) { crate::tl_id!("ui.section_wrong_password").to_string() } else { e.to_string() })?; + self.sealed(section); + Ok(()) + } + + pub(super) fn ask_section_password(&mut self, section: &Path, ask: Ask) { + self.section_locks.asking = Some(Asking { + section: section.to_path_buf(), + ask, + password: String::new(), + new_password: String::new(), + confirm: String::new(), + problem: None, + focus: true, + }); + } + + /// Review > Password: the open section's password, to give, or to change. + pub(super) fn section_password_for_current(&mut self) { + match self.section_of_open_page() { + Some(section) if protect::is_protected(§ion) => self.ask_section_password(§ion, Ask::Change), + Some(section) => self.ask_section_password(§ion, Ask::Protect), + None => self.say(crate::tl_id!("ui.section_password_no_section")), + } + } + + /// Every frame: the sections left unlocked when the program last stopped are looked for once, + /// the unlocked ones locked after the idle time, and the password window drawn. + pub(super) fn section_locks_tick(&mut self, ctx: &Context) { + if std::mem::take(&mut self.section_locks.forget_pictures) { + ctx.forget_all_images(); + } + if !self.section_locks.recovered && !self.secondary_window { + self.section_locks.recovered = true; + let notebooks: Vec<PathBuf> = self.session.tree().iter().map(|n| n.path.clone()).collect(); + for notebook in notebooks { + self.section_locks.left_open.extend(protect::recover(¬ebook)); + } + self.session.refresh(); + } + if self.section_locks.asking.is_none() + && let Some(section) = self.section_locks.left_open.pop() + && protect::state(§ion) == Some(State::Unlocked) + { + self.ask_section_password(§ion, Ask::LockLeftOpen); + } + let (now, busy) = ctx.input(|i| (i.time, !i.events.is_empty() || i.pointer.is_moving())); + if busy || self.section_locks.last_input == 0.0 { + self.section_locks.last_input = now; + } + if !self.section_locks.keys.is_empty() { + let settings = &self.session.settings; + let minutes = *self + .section_locks + .idle_minutes + .get_or_insert_with(|| settings.get(IDLE_KEY).and_then(|m| m.trim().parse::<u32>().ok()).unwrap_or(IDLE_DEFAULT)); + if minutes > 0 { + let idle = f64::from(minutes) * 60.0; + let waited = now - self.section_locks.last_input; + if waited >= idle { + // One try per idle time: a page that will not save is not saved again every frame. + self.section_locks.last_input = now; + if self.lock_all_sections() > 0 { + self.say(crate::tl_id!("ui.sections_locked_after_idle")); + } + } else { + ctx.request_repaint_after(std::time::Duration::from_secs_f64((idle - waited).max(1.0))); + } + } + } + self.section_password_window(ctx); + } + + fn section_password_window(&mut self, ctx: &Context) { + let Some(mut asking) = self.section_locks.asking.take() else { return }; + let tokens = self.tokens; + let title = self.title_in_tree(&asking.section).unwrap_or_else(|| notecraft_store::tree::folder_name(&asking.section)); + let (heading, about) = match asking.ask { + Ask::Protect => (crate::tl_id!("ui.password_protect_section"), crate::tl_id!("ui.password_protect_about")), + Ask::Change => (crate::tl_id!("ui.change_section_password"), crate::tl_id!("ui.change_section_password_about")), + Ask::Remove => (crate::tl_id!("ui.remove_section_password"), crate::tl_id!("ui.remove_section_password_about")), + Ask::LockLeftOpen => (crate::tl_id!("ui.lock_section_left_open"), crate::tl_id!("ui.lock_section_left_open_about")), + }; + let (mut keep, mut go) = (true, false); + let backdrop = super::modal_backdrop(ctx, "section-password-backdrop"); + egui::Window::new(heading) + .title_bar(false) + .collapsible(false) + .resizable(false) + .order(egui::Order::Foreground) + .fixed_size(egui::vec2(420.0, 0.0)) + .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0)) + .frame(super::modal_frame(&tokens)) + .show(ctx, |ui| { + super::stay_above(ui, backdrop); + super::modal_title(ui, &tokens, heading); + ui.label(egui::RichText::new(&title).strong()); + ui.label(egui::RichText::new(about).size(11.5).color(tokens.muted)); + ui.add_space(6.0); + let mut enter = false; + let mut field = |ui: &mut Ui, label: &str, text: &mut String, focus: bool| { + ui.label(label); + let r = ui.add(egui::TextEdit::singleline(text).password(true).desired_width(400.0)); + if focus { + r.request_focus(); + } + enter |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + }; + let first = std::mem::take(&mut asking.focus); + match asking.ask { + Ask::Protect => { + field(ui, crate::tl_id!("ui.section_password"), &mut asking.new_password, first); + field(ui, crate::tl_id!("ui.confirm_section_password"), &mut asking.confirm, false); + } + Ask::Change => { + field(ui, crate::tl_id!("ui.old_section_password"), &mut asking.password, first); + field(ui, crate::tl_id!("ui.new_section_password"), &mut asking.new_password, false); + field(ui, crate::tl_id!("ui.confirm_section_password"), &mut asking.confirm, false); + } + Ask::Remove | Ask::LockLeftOpen => field(ui, crate::tl_id!("ui.section_password"), &mut asking.password, first), + } + if matches!(asking.ask, Ask::Protect | Ask::Change) { + ui.label(egui::RichText::new(crate::tl_id!("ui.section_password_cannot_be_recovered")).size(11.5).color(tokens.warn)); + } + if let Some(problem) = &asking.problem { + ui.colored_label(tokens.warn, problem); + } + ui.add_space(6.0); + ui.horizontal(|ui| { + if super::modal_button(ui, &tokens, crate::tl_id!("ui.cancel"), false).clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) + { + keep = false; + } + if super::modal_button(ui, &tokens, crate::tl_id!("ui.ok"), true).clicked() || enter { + go = true; + } + }); + }); + if go { + let section = asking.section.clone(); + let new_twice = asking.new_password == asking.confirm; + let done = match asking.ask { + Ask::Protect | Ask::Change if asking.new_password.is_empty() => Err(crate::tl_id!("ui.section_password_empty").to_string()), + Ask::Protect | Ask::Change if !new_twice => Err(crate::tl_id!("ui.section_passwords_differ").to_string()), + Ask::Protect => { + let password = asking.new_password.clone(); + self.protect_section(§ion, &password) + } + Ask::Change => { + let (old, new) = (asking.password.clone(), asking.new_password.clone()); + self.change_section_password(§ion, &old, &new) + } + Ask::Remove => { + let password = asking.password.clone(); + self.remove_section_password(§ion, &password) + } + Ask::LockLeftOpen => { + let password = asking.password.clone(); + self.lock_left_open_section(§ion, &password) + } + }; + match done { + Ok(()) => keep = false, + Err(problem) => { + asking.problem = Some(problem); + asking.password.zeroize(); + asking.focus = true; + } + } + } + if keep { + self.section_locks.asking = Some(asking); + } + } + + /// Where a locked section's pages would be: its name and a box for its password. + pub(super) fn locked_section_panel(&mut self, ui: &mut Ui, section: &Path, title: &str) { + let tokens = self.tokens; + let mut typed = std::mem::take(&mut self.section_locks.typed); + let problem = self.section_locks.problem.as_ref().filter(|(at, _)| at == section).map(|(_, p)| p.clone()); + let mut go = false; + ui.vertical_centered(|ui| { + ui.add_space(ui.available_height() * 0.2); + let (rect, _) = ui.allocate_exact_size(egui::vec2(40.0, 40.0), egui::Sense::hover()); + crate::icons::paint_ribbon(ui, rect, Icon::Lock, tokens.text); + ui.add_space(6.0); + ui.label(egui::RichText::new(title).size(20.0).strong().color(tokens.text)); + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::tl_id!("ui.this_section_is_password_protected")).color(tokens.text)); + ui.add_space(8.0); + let r = + ui.add(egui::TextEdit::singleline(&mut typed).password(true).desired_width(260.0).hint_text(crate::tl_id!("ui.section_password"))); + go |= r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + if let Some(problem) = &problem { + ui.colored_label(tokens.warn, problem); + } + ui.add_space(8.0); + go |= super::modal_button(ui, &tokens, crate::tl_id!("ui.unlock_section"), true).clicked(); + }); + if go && !typed.is_empty() { + let tried = std::mem::take(&mut typed); + if let Err(problem) = self.unlock_section(section, &tried) { + self.section_locks.problem = Some((section.to_path_buf(), problem)); + } + let mut tried = tried; + tried.zeroize(); + } + self.section_locks.typed = typed; + } + + /// The section's own rows in its menu in the navigator. + pub(super) fn section_menu_rows(&self, ui: &mut Ui, section: &Path, acts: &mut Vec<super::Act>) { + let t = &self.tokens; + let state = protect::state(section); + let mut row = |ui: &mut Ui, icon: Icon, label: &str, act: super::Act| { + if floating::menu_row(ui, Some(Glyph::Icon(icon)), label, t).clicked() { + acts.push(act); + ui.close(); + } + }; + match state { + None => row( + ui, + Icon::Lock, + crate::tl_id!("ui.password_protect_this_section_ellipsis"), + super::Act::SectionPassword(section.to_path_buf(), Ask::Protect), + ), + Some(state) => { + if state == State::Unlocked { + row(ui, Icon::Lock, crate::tl_id!("ui.lock_section"), super::Act::LockSection(section.to_path_buf())); + } + row(ui, Icon::Lock, crate::tl_id!("ui.change_password_ellipsis"), super::Act::SectionPassword(section.to_path_buf(), Ask::Change)); + row(ui, Icon::Unlock, crate::tl_id!("ui.remove_password_ellipsis"), super::Act::SectionPassword(section.to_path_buf(), Ask::Remove)); + } + } + } + + /// For `ui.inspect`: the protected sections in the open notebooks, by title, and whether each + /// is locked, and whether a password is being asked for. + pub(super) fn section_locks_state(&self) -> Value { + fn walk(nodes: &[notecraft_store::Node], out: &mut Vec<Value>) { + for n in nodes { + if let Some(state) = n.info.protected { + out.push(json!({"title": n.info.title, "locked": state == State::Locked})); + } + walk(&n.children, out); + } + } + let mut sections = Vec::new(); + walk(self.session.tree(), &mut sections); + let asking = self.section_locks.asking.as_ref().map(|a| json!({"ask": format!("{:?}", a.ask), "problem": a.problem})); + json!({"sections": sections, "unlockedHere": self.section_locks.keys.len(), "asking": asking}) + } +} diff --git a/crates/ui-egui/src/containers.rs b/crates/ui-egui/src/containers.rs index 0df503b9..ec378d4a 100644 --- a/crates/ui-egui/src/containers.rs +++ b/crates/ui-egui/src/containers.rs @@ -386,6 +386,7 @@ pub fn show( ui.data_mut(|d| d.remove::<Vec<(usize, Rect, String)>>(crate::preview::object_hits_id())); ui.data_mut(|d| d.remove::<Vec<crate::preview::RenderedImage>>(crate::preview::rendered_images_id())); ui.data_mut(|d| d.remove::<Vec<(usize, f32)>>(pageedit::after_picture_tops_id())); + ui.data_mut(|d| d.remove::<Vec<(usize, f32, f32, f32)>>(pageedit::block_tops_id())); // A picture taken hold of while it shares its box with other blocks: the box is split so // the picture has one of its own, which is what a picture is moved by. Done after the // boxes are drawn, because it renumbers them. @@ -1706,6 +1707,7 @@ pub fn show_ink_view( d.remove::<Vec<crate::preview::RenderedImage>>(crate::preview::rendered_images_id()); d.remove::<Vec<(usize, Rect, String)>>(crate::preview::object_hits_id()); d.remove::<Vec<(usize, f32)>>(pageedit::after_picture_tops_id()); + d.remove::<Vec<(usize, f32, f32, f32)>>(pageedit::block_tops_id()); }); let area = ui.available_rect_before_wrap(); out.origin = area.min; diff --git a/crates/ui-egui/src/pageedit.rs b/crates/ui-egui/src/pageedit.rs index df23d4d9..6022a416 100644 --- a/crates/ui-egui/src/pageedit.rs +++ b/crates/ui-egui/src/pageedit.rs @@ -2152,6 +2152,21 @@ pub(crate) fn after_picture_tops_id() -> egui::Id { egui::Id::new("blocks-after-a-picture-tops") } +/// Where each block drawn this frame starts: its number, its top and the left and right of the +/// column it is in. The page's menu reads it to know which paragraph it was opened over (issue #530). +pub(crate) fn block_tops_id() -> egui::Id { + egui::Id::new("blocks-drawn-tops") +} + +/// The block drawn under `at` this frame: the one in the same column that starts last above it. +pub fn block_at(ctx: &egui::Context, at: egui::Pos2) -> Option<usize> { + ctx.data(|d| d.get_temp::<Vec<(usize, f32, f32, f32)>>(block_tops_id()))? + .into_iter() + .filter(|&(_, top, left, right)| top <= at.y + 1.0 && (left..=right).contains(&at.x)) + .max_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(block, ..)| block) +} + fn next_whole_block_image(blocks: &[Block], from: usize, shown_title: &str) -> Option<usize> { let image = from.checked_add(1)?; (blocks.get(image).is_some_and(|block| matches!(block, Block::Image { .. })) && !is_title_echo(blocks, image, shown_title)).then_some(image) @@ -2732,6 +2747,8 @@ pub fn show_blocks( // Where this block starts, so a frame can be drawn around it afterwards: the block // the caret is in gets one, the way a container is outlined in OneNote. let top = ui.cursor().min.y; + let column = ui.max_rect().x_range(); + ui.data_mut(|d| d.get_temp_mut_or_default::<Vec<(usize, f32, f32, f32)>>(block_tops_id()).push((i, top, column.min, column.max))); // The block right after a picture: where it starts is where the words that follow stay // when the picture is lifted out of the box (see `containers`). Only these are noted, so // a long page does not pay for it. diff --git a/crates/ui-egui/src/pagemenu.rs b/crates/ui-egui/src/pagemenu.rs index 8f0de482..54316cc4 100644 --- a/crates/ui-egui/src/pagemenu.rs +++ b/crates/ui-egui/src/pagemenu.rs @@ -128,6 +128,15 @@ pub fn show( } } } + // A link to the paragraph the menu was opened over, as OneNote's (issue #530). Copying + // is not an edit, so a locked page offers it too. + if let Some(block) = crate::pageedit::block_at(ui.ctx(), at.center()) { + floating::menu_separator(ui, t); + if floating::menu_row(ui, Some(Glyph::Icon(Icon::Link)), crate::tl_id!("ui.copy_link_to_paragraph"), t).clicked() { + acts.push(Act::CopyParagraphLink(block)); + picked = true; + } + } // The page's lock, as the navigator's menus offer it (issue #441). let (label, icon) = if locked { (crate::tl_id!("ui.unlock_read_only"), Icon::Unlock) } else { (crate::tl_id!("ui.lock_read_only"), Icon::Lock) }; diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index f48dc32d..78840551 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -158,6 +158,8 @@ pub enum Act { NewDockedWindow, /// Lock the page open in the editor read only, or unlock it (issue #441). SetReadOnly(bool), + /// The page's menu > Copy Link to Paragraph, for the block it was opened over (issue #530). + CopyParagraphLink(usize), QuickNote, /// Start dictating at the caret, or finish. #[cfg(feature = "voice")] @@ -234,6 +236,12 @@ pub enum Act { }, /// Review > Check Accessibility: show or hide the page's accessibility findings (issue #520). CheckAccessibility, + /// Review > Linked Notes: show or hide the Linked Notes pane (issue #522). + LinkedNotes, + /// Review > Password: give the open section a password, or change it (issue #523). + SectionPassword, + /// Review > Lock All: lock every password-protected section this window unlocked (issue #523). + LockAllSections, /// Review > Spelling (F7): show or hide the spelling pane, which lists the words spelt wrong /// and marks them on the page (issue #276). Spelling, @@ -766,6 +774,8 @@ pub struct View<'a> { pub ink_held: bool, /// Whether the accessibility findings are shown beside the page (issue #520). pub accessibility_open: bool, + /// Whether the Linked Notes pane is shown or a session runs (issue #522). + pub linked_notes_open: bool, /// Whether the spelling pane is shown beside the page (issue #276). pub spelling_open: bool, /// Whether the thesaurus is shown beside the page (issue #524). @@ -4712,6 +4722,21 @@ fn review_tab(ui: &mut Ui, view: &View<'_>, t: &Tokens, acts: &mut Vec<Act>) { acts.push(Act::CheckAccessibility); } }); + // OneNote's Review tab has Linked Notes in its Notes group (issue #522). + group(ui, crate::tl_id!("ui.notes_group"), t, |ui| { + if big_on(ui, Icon::Link, crate::tl_id!("ui.linked_notes"), crate::tl_id!("ui.linked_notes_tip"), view.linked_notes_open, t).clicked() { + acts.push(Act::LinkedNotes); + } + }); + // OneNote's Review tab has Password in its Section group (issue #523). + group(ui, crate::tl_id!("ui.review_section_group"), t, |ui| { + if big(ui, Icon::Lock, crate::tl_id!("ui.section_password_button"), crate::tl_id!("ui.section_password_tip"), t).clicked() { + acts.push(Act::SectionPassword); + } + if big(ui, Icon::Lock, crate::tl_id!("ui.lock_all_sections"), crate::tl_id!("ui.lock_all_sections_tip"), t).clicked() { + acts.push(Act::LockAllSections); + } + }); } /// Review > Language (issue #276): the language spelling is checked in, apart from the language diff --git a/crates/ui-egui/src/sectiontabs.rs b/crates/ui-egui/src/sectiontabs.rs index 678e5a07..8d1e0610 100644 --- a/crates/ui-egui/src/sectiontabs.rs +++ b/crates/ui-egui/src/sectiontabs.rs @@ -304,7 +304,7 @@ mod tests { fn node(kind: NodeKind, title: &str, children: Vec<Node>) -> Node { Node { path: PathBuf::from(format!("/nb/{title}")), - info: NodeInfo { kind, title: title.into(), color: None, format: None, id: title.into(), order: 0, read_only: false }, + info: NodeInfo { kind, title: title.into(), color: None, format: None, id: title.into(), order: 0, read_only: false, protected: None }, children, } } diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index 54e13d47..60760af0 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -21378,3 +21378,197 @@ fn a_timestamped_transcript_matches_between_html_and_cmgfm() { assert!(different * 100 <= html.pixels().len(), "{}: {different} different pixels", theme.id()); } } + +/// Issue #530: the page's menu over a paragraph copies a link to that paragraph. Followed from +/// another page it opens the page with the caret in that paragraph, after lines were written above +/// it, and once the paragraph is deleted it opens the page and says the paragraph is gone, in +/// either page format. +#[test] +fn a_link_to_a_paragraph_finds_it_after_the_page_changes_and_says_when_it_is_gone() { + for html in [false, true] { + let board = MemoryBoard::new(); + let (_t, app, s) = sample_app("ui-paragraph-link"); + let app = app.with_clipboard(Box::new(board.clone())); + let (page, other) = if html { (&s.html_page, &s.md_page) } else { (&s.md_page, &s.html_page) }; + let body = |lines: &[&str]| { + if html { lines.iter().map(|l| format!("<p>{l}</p>")).collect::<Vec<_>>().join("\n") } else { lines.join("\n\n") + "\n" } + }; + notecraft_store::page::save_body(page, &body(&["Alpha line", "Bravo line", "Charlie line"])).expect("fixture"); + let mut h = sized_harness(app, LIGHT, egui::vec2(1500.0, 900.0)); + h.state_mut().open_path(&page.to_string_lossy()); + settle(&mut h); + // The page's menu, opened over the second paragraph. + let bravo = h.query_all_by_label_contains("Bravo line").map(|n| n.rect()).next().expect("the paragraph is drawn"); + ask(&mut h, "ui.click", json!({"x": bravo.center().x, "y": bravo.center().y, "button": "right"})).expect("right click"); + for _ in 0..6 { + pump(&mut h); + } + h.get_by_label("Copy Link to Paragraph").click(); + for _ in 0..8 { + pump(&mut h); + forward_copies(&mut h, &board); + } + let text = board.read_text(); + assert!(text.starts_with("Bravo line ("), "html={html}: the paragraph's words name the link: {text}"); + let uri = text.rsplit_once('(').and_then(|(_, r)| r.strip_suffix(')')).map(str::to_owned).unwrap_or_default(); + assert!(uri.starts_with("notecraft:") && uri.contains("p="), "html={html}: {uri}"); + // Two lines are written above it, and the page saved. + let mut moved = h.state().body().unwrap_or_default().to_string(); + moved = if html { + moved.replacen("<p>Alpha line</p>", "<p>New one</p>\n<p>New two</p>\n<p>Alpha line</p>", 1) + } else { + format!("New one\n\nNew two\n\n{moved}") + }; + ask(&mut h, "engine.execute", json!({"command": "page.save", "params": {"path": page.to_string_lossy(), "body": moved}})) + .expect("save above"); + // From another page, the link opens the page at the paragraph. + h.state_mut().open_path(&other.to_string_lossy()); + settle(&mut h); + let ctx = h.ctx.clone(); + h.state_mut().follow_link(&ctx, &uri); + settle(&mut h); + assert!(shown_page(&h).is_some_and(|p| same_dir(&p, page)), "html={html}: the page opened"); + let caret = look_at(&mut h)["page"]["caret"].clone(); + assert_eq!(caret["block"], json!(3), "html={html}: the caret is in the paragraph, two lines further down: {caret}"); + assert_eq!(caret["text"], json!("Bravo line"), "html={html}"); + // The paragraph is deleted: the page still opens, and says so. + let cut = body(&["New one", "New two", "Alpha line", "Charlie line"]); + ask(&mut h, "engine.execute", json!({"command": "page.save", "params": {"path": page.to_string_lossy(), "body": cut}})).expect("save cut"); + h.state_mut().open_path(&other.to_string_lossy()); + settle(&mut h); + h.state_mut().follow_link(&ctx, &uri); + settle(&mut h); + assert!(shown_page(&h).is_some_and(|p| same_dir(&p, page)), "html={html}: the page opened"); + let status = look_at(&mut h); + assert_eq!( + status.pointer("/status/text").and_then(Value::as_str), + Some("The linked paragraph is no longer on this page. The page is open at its top."), + "html={html}" + ); + } +} + +/// Issue #522: Review > Linked Notes starts a session with a source the person chooses. What is +/// written while it runs is tied to that source and listed in the pane, where the source can be +/// opened again; what was there before, and what is written after Stop, is not. A source that is +/// not there is refused. The links are kept in the page, in either format. +#[test] +fn linked_notes_tie_what_is_written_to_the_chosen_source() { + for html in [false, true] { + let (t, app, s) = sample_app("ui-linked-notes"); + let (page, other) = if html { (&s.html_page, &s.md_page) } else { (&s.md_page, &s.html_page) }; + let body = if html { "<p>Read before</p>".to_string() } else { "Read before\n".to_string() }; + notecraft_store::page::save_body(page, &body).expect("fixture"); + let mut h = sized_harness(app, LIGHT, egui::vec2(1500.0, 900.0)); + h.state_mut().open_path(&page.to_string_lossy()); + settle(&mut h); + h.get_by_label("Review").click(); + settle(&mut h); + h.get_by_label("Linked Notes").click(); + settle(&mut h); + assert_eq!(look_at(&mut h)["linkedNotes"]["open"], json!(true), "html={html}: the pane opened"); + assert!(h.query_all_by_label("Start Taking Linked Notes").count() >= 1, "html={html}: and offers to start"); + let ctx = h.ctx.clone(); + // A file that is not there is not a source. + let missing = t.path().join("no-such-paper.pdf"); + assert!(h.state_mut().start_linked_notes(&ctx, &missing.to_string_lossy()).is_err(), "html={html}"); + assert_eq!(look_at(&mut h)["linkedNotes"]["running"], Value::Null); + h.state_mut().start_linked_notes(&ctx, "https://example.org/paper").expect("start"); + settle(&mut h); + assert_eq!(look_at(&mut h)["linkedNotes"]["running"]["target"], json!("https://example.org/paper"), "html={html}"); + // A new paragraph is written and saved. + ask(&mut h, "ui.caret", json!({"block": 0})).expect("caret"); + pump(&mut h); + ask(&mut h, "ui.key", json!({"key": "Enter"})).expect("new line"); + pump(&mut h); + ask(&mut h, "ui.text", json!({"text": "A note on the paper"})).expect("type"); + pump(&mut h); + h.state_mut().save_page_now(); + settle(&mut h); + let linked = look_at(&mut h)["linkedNotes"]["paragraphs"].clone(); + assert_eq!(linked, json!([{"block": 1, "source": "https://example.org/paper", "kind": "web"}]), "html={html}: only the new paragraph"); + assert!(h.query_all_by_label("A note on the paper").count() >= 1, "html={html}: the pane lists it"); + assert!(h.query_all_by_label("Open source").count() >= 1, "html={html}: with its source to open"); + // After Stop, what is written is not tied. + h.state_mut().stop_linked_notes(); + settle(&mut h); + ask(&mut h, "ui.caret", json!({"block": 1})).expect("caret"); + pump(&mut h); + ask(&mut h, "ui.key", json!({"key": "Enter"})).expect("new line"); + pump(&mut h); + ask(&mut h, "ui.text", json!({"text": "Written later"})).expect("type"); + pump(&mut h); + h.state_mut().save_page_now(); + settle(&mut h); + // Kept in the page: another page and back. + h.state_mut().open_path(&other.to_string_lossy()); + settle(&mut h); + h.state_mut().open_path(&page.to_string_lossy()); + settle(&mut h); + let v = look_at(&mut h)["linkedNotes"].clone(); + assert_eq!(v["running"], Value::Null, "html={html}"); + assert_eq!(v["paragraphs"], json!([{"block": 1, "source": "https://example.org/paper", "kind": "web"}]), "html={html}: {v}"); + // A file is a source too, and the pane's Remove link takes a source off. + let paper = t.path().join("paper.txt"); + std::fs::write(&paper, "words").expect("paper"); + h.state_mut().start_linked_notes(&ctx, &paper.to_string_lossy()).expect("a file"); + assert_eq!(look_at(&mut h)["linkedNotes"]["running"]["kind"], json!("file")); + h.state_mut().stop_linked_notes(); + h.state_mut().unlink_paragraph(1); + settle(&mut h); + assert_eq!(look_at(&mut h)["linkedNotes"]["paragraphs"], json!([]), "html={html}"); + } +} + +/// Issue #523: a section protected with a password holds nothing readable while it is locked, +/// opens only with its password, is locked again when the window closes, and a section left +/// unlocked by a program that stopped is offered to be locked when the window starts. +#[test] +fn a_password_protected_section_locks_unlocks_and_is_locked_again_on_close() { + for html in [false, true] { + let (t, app, s) = sample_app("ui-section-password"); + let page = if html { s.html_page.clone() } else { s.md_page.clone() }; + let word = if html { "Kickoff" } else { "outlive" }; + let section = page.parent().expect("section").to_path_buf(); + let mut h = sized_harness(app, LIGHT, egui::vec2(1500.0, 900.0)); + h.state_mut().open_path(&page.to_string_lossy()); + settle(&mut h); + h.get_by_label("Review").click(); + settle(&mut h); + assert!(h.query_all_by_label("Lock All").count() >= 1, "html={html}: Review has Lock All"); + h.get_by_label("Password").click(); + settle(&mut h); + assert_eq!(look_at(&mut h)["sectionLocks"]["asking"]["ask"], json!("Protect"), "html={html}: Password asks for one"); + assert!(h.query_all_by_label("A forgotten password cannot be recovered, and the section cannot be opened without it.").count() >= 1); + + h.state_mut().protect_section(§ion, "correct horse").expect("protect"); + settle(&mut h); + let v = look_at(&mut h)["sectionLocks"].clone(); + assert!(v["sections"].as_array().is_some_and(|all| all.iter().any(|s| s["locked"] == json!(true))), "html={html}: {v}"); + assert!(!page.exists(), "html={html}: the page's plain files are gone"); + assert!(h.query_all_by_label("This section is protected with a password.").count() >= 1, "html={html}: the section asks for its password"); + let wrong = h.state_mut().unlock_section(§ion, "wrong horse").expect_err("wrong password"); + assert!(wrong.contains("not right"), "html={html}: {wrong}"); + + h.state_mut().unlock_section(§ion, "correct horse").expect("unlock"); + settle(&mut h); + assert!(std::fs::read_to_string(notecraft_store::tree::page_file(&page).expect("page").1).expect("read").contains(word)); + assert_eq!(look_at(&mut h)["sectionLocks"]["unlockedHere"], json!(1)); + + // Closing the window locks what it unlocked. + h.state_mut().before_close(); + assert!(!page.exists(), "html={html}: locked again on close"); + assert_eq!(notecraft_store::protect::state(§ion), Some(notecraft_store::protect::State::Locked)); + + // A run that stopped with the section unlocked: the next window asks to lock it. + drop(notecraft_store::protect::unlock(§ion, "correct horse").expect("unlock elsewhere")); + drop(h); + let mut h = sized_harness(NoteCraftApp::new(session(&t)), LIGHT, egui::vec2(1500.0, 900.0)); + settle(&mut h); + assert_eq!(look_at(&mut h)["sectionLocks"]["asking"]["ask"], json!("LockLeftOpen"), "html={html}"); + assert!(h.query_all_by_label("Lock Protected Section").count() >= 1); + h.state_mut().lock_left_open_section(§ion, "correct horse").expect("lock"); + settle(&mut h); + assert!(!page.exists(), "html={html}"); + } +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index c62b5d0f..62e6062e 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -52,7 +52,7 @@ returns `{}`); later requests on the same connection may leave it out. Replies: | `auth` | none | `{}` | | `engine.commands` | none | every command: `id`, `label`, `params`, `changesTree` | | `engine.execute` | `command`, `params` (object) | the command's output; same as `notecraft-cli run` | -| `ui.inspect` | none | visible tree rows, open page, canvas `viewOffset` in screen points and `horizontalBar` and `horizontalThumb` (the page's sideways scroll bar and its thumb as `[left, top, right, bottom]` in screen points, or null when the page fits the view) (the caret: its block, text, `at` and `anchor` in characters; `containers`: the boxes the blocks are arranged in; `across`: a selection dragged across more than one block, as the block and byte at each end, or null; `selectedContainer`: the index of the box that is selected, or null; `edgesShown`: the boxes whose edges are showing, by index; `nav` (`back` and `forward` counts and the `current` page), `quickAccess` (which of Back, Forward, Undo and Redo are shown, `below`, `hidden`); `windowFrame` (`own` when the band across the top is the title bar, `system` when the system draws it); and `history`: how many steps of undo the page is keeping, where in them it is, and whether undo and redo have anywhere to go), theme, `pagePrefs` (File > Options: `centrePage`, `fitDateBox`, `outlineNewBoxes`), window size, `pageDiagrams` (the same counts for the Mermaid diagrams of the page as it is drawn, `found`, `drawn`, `drawing`, `failed`), `panes` (whether the side panel is split into organisers and pages, and whether the organisers column is showing), `tagsSummary` (while Home > Find Tags is open: its `scope`, `page`, `section`, `notebook` or `all`, whether it shows only `unchecked` To Do items, and the `lines` it lists, each with its `tag`, `text`, `done` (for a To Do), `page` and `section`; null while it is closed), `paper` (the rule lines behind the pages, by id), `proofing` (Review's spelling and thesaurus: the `language` checked in, the one `chosen` (empty for Automatic), `status` (`native`, `dictionary`, `no-dictionary`, `not-checked` or `not-loaded`), `spelling` while its pane is open (the `words` spelt wrong, each with its `word`, `block`, `cell`, `start` and `end` in characters, the `current` one, and `otherScript`, how many words in another script were passed over), and `thesaurus` while it is open (the `query`, the `place` of the word on the page, its `meanings` each with `part` and `words`, and `missing` when there is no thesaurus for the language)) and `pen` (see below) | +| `ui.inspect` | none | visible tree rows, open page, canvas `viewOffset` in screen points and `horizontalBar` and `horizontalThumb` (the page's sideways scroll bar and its thumb as `[left, top, right, bottom]` in screen points, or null when the page fits the view) (the caret: its block, text, `at` and `anchor` in characters; `containers`: the boxes the blocks are arranged in; `across`: a selection dragged across more than one block, as the block and byte at each end, or null; `selectedContainer`: the index of the box that is selected, or null; `edgesShown`: the boxes whose edges are showing, by index; `nav` (`back` and `forward` counts and the `current` page), `quickAccess` (which of Back, Forward, Undo and Redo are shown, `below`, `hidden`); `windowFrame` (`own` when the band across the top is the title bar, `system` when the system draws it); and `history`: how many steps of undo the page is keeping, where in them it is, and whether undo and redo have anywhere to go), theme, `pagePrefs` (File > Options: `centrePage`, `fitDateBox`, `outlineNewBoxes`), window size, `pageDiagrams` (the same counts for the Mermaid diagrams of the page as it is drawn, `found`, `drawn`, `drawing`, `failed`), `panes` (whether the side panel is split into organisers and pages, and whether the organisers column is showing), `tagsSummary` (while Home > Find Tags is open: its `scope`, `page`, `section`, `notebook` or `all`, whether it shows only `unchecked` To Do items, and the `lines` it lists, each with its `tag`, `text`, `done` (for a To Do), `page` and `section`; null while it is closed), `paper` (the rule lines behind the pages, by id), `proofing` (Review's spelling and thesaurus: the `language` checked in, the one `chosen` (empty for Automatic), `status` (`native`, `dictionary`, `no-dictionary`, `not-checked` or `not-loaded`), `spelling` while its pane is open (the `words` spelt wrong, each with its `word`, `block`, `cell`, `start` and `end` in characters, the `current` one, and `otherScript`, how many words in another script were passed over), and `thesaurus` while it is open (the `query`, the `place` of the word on the page, its `meanings` each with `part` and `words`, and `missing` when there is no thesaurus for the language)), `linkedNotes` (Review > Linked Notes: whether its pane is `open`, the source it is `running` with (`kind`, `target`, `title`) or null, and the page's linked `paragraphs`, each with its `block`, `source` and `kind`), `sectionLocks` (the password-protected `sections` in the open notebooks, each with its `title` and whether it is `locked`, how many this window holds unlocked, `unlockedHere`, and the password being `asking` for, with its `ask` (`Protect`, `Change`, `Remove` or `LockLeftOpen`) and `problem`, or null) and `pen` (see below) | | `ui.window.reload` | none | `{reloaded: bool}`; explicitly discard local changes and reload the page | | `ui.window.keep-copy` | none | `{path: string}`; keep local text and ink as a new sibling page | | `ui.open` | `path` (relative to the notebooks folder) | the same as `ui.inspect`, or an error | diff --git a/docs/feature-parity.md b/docs/feature-parity.md index f7420a82..9d0a5542 100644 --- a/docs/feature-parity.md +++ b/docs/feature-parity.md @@ -28,12 +28,12 @@ side by side. Status words: | Embedding | Images, files, video | Partial | Dropped files can be copied into the page folder, linked, or inserted as PDF printouts (native Rust rasterization; LibreOffice for Office formats). Includes image right-click "Save picture as...", Insert > Online Video links, and a 12-sticker gallery. Video embedding/playback, screen clipping, audio/video recording, and transcription are not built. | | Embedding | Live Office objects | Skip | Not portable. | | Retrieval | Full-text search | Done | Across all notebooks, title and body. | -| Retrieval | Links between pages | Partial | Clicking a link opens the named page, section, external file, or web URL. Copy link to page generates `notecraft:/book/section/page` links. Links are followed by path; links by ID, links inside table cells, and links inside mixed bidi lines are not built. | +| Retrieval | Links between pages | Partial | Clicking a link opens the named page, section, external file, or web URL. Copy link to page generates `notecraft:/book/section/page` links; the page's menu has Copy Link to Paragraph, which adds `?p=<id>` and keeps finding the paragraph after it moves (issue #530). Links are followed by path; links by ID, links inside table cells, and links inside mixed bidi lines are not built. | | Retrieval | Versions, recycle bin | Partial | History tab provides Page Versions (stores and restores snapshots of a page's file together with its ink and attachments, issue #553; versions taken before that are marked "words only") and Notebook Recycle Bin (restores or permanently removes deleted pages, sections, and section groups). Deleting entire notebooks is not supported in the bin. | | Retrieval | OCR, audio search | Partial | Printed text in pictures and printout pages is read on this computer with the `ocrs` models (setting `ocr_models`), found by search, and copied with the picture menu's Copy Text from Picture, for one picture or one or every printout page, shown for review first. Handwriting recognition and audio search are not built. Raw stroke data (`nc:dabs`) in ink files is preserved for future handwriting recognition. | | Sync | Cloud sync and backup | Done by design | Plain files in a synced folder (OneDrive, Dropbox, Nextcloud, Syncthing). File changes debounce and defer during active ink strokes. Real-time conflict merging is not built. | | Sync | Local backups | Partial | File > Info > Backups (issue #552): automatic or Back Up Now copies of each open notebook into a chosen folder, with an interval and a number kept. Open Backups shows a backup's sections and pages and restores a page, section or group as a copy, or the whole backup as a new notebook. Not in the browser build. | -| Sync | Section passwords | Later | | +| Sync | Section passwords | Partial | A section's menu has Password Protect This Section, Lock Section, Change Password and Remove Password; Review > Password and Lock All do the same for the open section and every unlocked one (issue #523). A locked section is one file sealed with XChaCha20-Poly1305 under an Argon2id key: its pages, pictures, ink and versions are not on disk, in search, in backups or in the recycle bin while it is locked. Unlocked sections lock again after 10 minutes with no input (setting `section_lock_idle_minutes`, 0 for never) and when the window closes; one left unlocked when the program stopped is offered to be locked at the next start. Not built: the web build's notebooks, wiping the plain files' old disk blocks, and importing OneNote's protected sections. | | Collaboration | Sharing | Partial | Shared folder sync; live co-authoring is Later. File > Share, File > Export, and Home > Send Page provide reviewed original-format folder exports (or browser ZIP downloads). History tab includes author tracking and Find by Author across open notebooks. Native OS share sheets are not integrated. | | Output | Export | Partial | File > Export produces reviewed original-format folder packages (downloaded as ZIP in the browser). Images offer "Save picture as...", drawings offer "Save picture" SVG export, tables export to CSV for GridCraft, and pages offer background printout rendering. File > Print and Ctrl+P print the page or its section, with a preview, paper size, orientation and margins, and save it as a PDF (pictures of the sheets, 200 dpi) or send it to a printer (CUPS on macOS and Linux; the PDF viewer on Windows). A text-based PDF writer and OneNote file export are not built. | | Output | Follow-up tasks | Partial | Home > Tags > Follow-up Task (issue #551) turns the selected words into a task with a due day and a link back to the page, reviewed first, then opened in the system task list or saved as a calendar task file (`.ics`). No task-service sign-in; the page and its To Do tags are not changed. | @@ -42,6 +42,6 @@ side by side. Status words: | Output | Add-ins, AI | Later | | | Look | Themes | Done | 14 themes, contrast checked. `themes.md`. | | Look | Ruled and grid page backgrounds | Done | Format Background on Draw or View provides none, lines, or squares with selectable rule line colours and page tint colours, stored per page in metadata (`notecraft:paper`, `notecraft:page-color`) and contrast-checked across themes. | -| Look | Office-style ribbon | Partial | Home, Insert, Draw, History and View tabs with Office-style groups, Styles and Tags galleries, contextual Table and Source tabs, section tabs layout, and File screen. Immersive Reader and Dock to Desktop are available. The Review tab has Spelling, Thesaurus, Language and Check Accessibility. A general Help tab remains unbuilt. | +| Look | Office-style ribbon | Partial | Home, Insert, Draw, History and View tabs with Office-style groups, Styles and Tags galleries, contextual Table and Source tabs, section tabs layout, and File screen. Immersive Reader and Dock to Desktop are available. The Review tab has Spelling, Thesaurus, Language, Check Accessibility, Linked Notes, and Password and Lock All for protected sections. A general Help tab remains unbuilt. | | Files | See what a page is made of | Done | The code view lists every file of a page and shows what is in each. The other app keeps a section in one binary file that a text editor cannot read. `how-to/look-inside-a-page.md`. | | Look | Platforms | Partial | Desktop builds (Windows MSI/zip, Linux deb/rpm/AppImage/tar.gz, macOS DMG/zip) and browser WASM demo are actively built and verified in CI. Android arm64 APK builds with a phone layout, but lacks native file pickers, system clipboard, and on-device signoff. | diff --git a/docs/folder-format.md b/docs/folder-format.md index 96cf9ce7..f90d0e31 100644 --- a/docs/folder-format.md +++ b/docs/folder-format.md @@ -159,6 +159,8 @@ tags: [] | `order` | Position among siblings (integers; new nodes get 10, 20, 30, ...). Ties and missing values sort by folder name. | no | | `created`, `updated` | UTC time, `YYYY-MM-DDTHH:MM:SSZ`. | no | | `tags` | Reserved. | no | +| `anchors` | Paragraph ids for links to a paragraph (issue #530): comma-separated `id@block:print`, where `block` is the paragraph's place on the page and `print` 16 hex digits made from its words. When the page is saved the ids follow their paragraphs; an id whose paragraph is gone is dropped. HTML: `notecraft:anchors`. | no | +| `sources`, `linked` | Linked Notes (issue #522): `sources` lists the sources notes were taken against as `n\|kind\|target\|title` separated by `; ` (`kind` is `web`, `file` or `page`); `linked` ties paragraph ids from `anchors` to them as `id=n, ...`. Values are percent-encoded where they would clash with these separators. HTML: `notecraft:sources`, `notecraft:linked`. | no | Unknown keys are kept. Times in front matter and `<meta>` are the truth; file modification times are not used, because sync tools change them. @@ -233,6 +235,26 @@ created = "2026-10-17T20:09:00Z" | `title`, `id`, `order`, `created` | As in 3.3. | | `format` | Optional. The default format for new pages below this node: `html` or `cmgfm`. A notebook always records one when it is created. | | `color` | Optional. The colour of this notebook cover or section tab, the way notebook apps colour them: `purple`, `blue`, `teal`, `green`, `yellow`, `orange`, `red`, `magenta` or `gray`. A name, not a hex value, so it stays readable in every theme. An unknown name is ignored. | +| `protected` | Optional, sections only. `true` when the section has a password (issue #523); see 4.1. | + +### 4.1 Password-protected sections + +A protected section keeps all of its content (its pages and subpages with their attachments, +ink and saved versions) in one sealed file, `_protected.ncsafe`, beside `_node.toml`. While it +is locked the folder holds nothing else. The sealed file starts with `NCSAFE1\0`, a version +byte (1), the Argon2id memory cost in KiB, passes and lanes as little-endian 32-bit numbers, a +16-byte salt and a 24-byte nonce; the rest is the section's content sealed with +XChaCha20-Poly1305 under the key Argon2id makes from the password, with that header as +associated data. The content is a list of folders and files, each a kind byte (`d` or `f`), its +path inside the section with `/`, and for a file its length and bytes. + +Unlocking writes the content back into the folder and leaves the sealed file in place. A file +`_protected.open` says the section is not locked: it reads `opening` while the content is +being written out, `open` once it is all out, and `sealed` while the plain files are being +deleted after the section was sealed again. A reader finding `opening` or `sealed` may delete +everything but `_node.toml` and `_protected.ncsafe`; one finding `open` must not, because what +was written while the section was open is only in the plain files. A backup copies only +`_node.toml` and `_protected.ncsafe` from a protected section, locked or not. The file is read with a small reader that understands `key = "value"` and `key = number` lines, `#` comments and blank lines. It is not a full TOML parser; NoteCraft writes only diff --git a/docs/gaps.md b/docs/gaps.md index 61f064ac..1c39e3c9 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -99,7 +99,7 @@ narrower than 600 points, on Android, a narrow desktop window or the browser bui Windows 10, are read too (`crates/onenote/src/packaged.rs`). Only the current version of each page is read; a data element split into fragments is skipped, and a cloud file card (a link to a file on OneDrive) has no bytes in the file to bring over. - Still missing: ink, tags, page dates and password-protected sections. + Still missing: ink, tags, page dates and importing password-protected sections. Underline and equation structure have nowhere to go in the page formats. - **Equations are KaTeX's TeX, not all of LaTeX.** No packages, no chemistry (`\ce`), no TikZ, and no visual formula editor. The engine (RaTeX) is young and has one main author; it is pinned to @@ -439,7 +439,7 @@ narrower than 600 points, on Android, a narrow desktop window or the browser bui visual blocks, and paste of copied file lists. Those need the Windows clipboard API; see [ADR 0001](adr/0001-clipboard-boundary.md). - **A box's right-click menu is short.** It has Cut, Copy and Delete, then the page's entries. OneNote's also has - Paste Options, Copy Link to Paragraph, Select, Order, Move and Resize, and a small formatting + Paste Options, Select, Order, Move and Resize, and a small formatting toolbar above it; none of those are here yet, and no entry is shown that does nothing. Move and resize are the bar and the right edge. A box is deleted without asking, as OneNote does, and Ctrl+Z brings it back: the page's history holds whole states of the page, boxes included. @@ -511,7 +511,24 @@ narrower than 600 points, on Android, a narrow desktop window or the browser bui they are not drawn. It does not appear on a box's menu (a selected box has no words for Bold to act on), beside a text selection, or on tables and pictures yet. - **Menu entries.** Rows carry OneNote's pictures. Still missing from a box's menu: Paste Options with - its pictures, Copy Link to Paragraph, Select, Order, Move and Resize. + its pictures, Select, Order, Move and Resize. +- **Copy Link to Paragraph** (issue #530) is on the page's menu, for the paragraph it was opened + over. The paragraph's id is kept in the page's own head (`anchors`) and follows the paragraph + when NoteCraft saves the page, through edits above it and moves; a paragraph moved by another + program is found again by its words. A link whose paragraph is gone opens the page at its top + and says so. Not built: a link to a cell inside a table, a box's own menu entry, and finding a + paragraph whose words were changed elsewhere as well as moved. +- **Linked Notes** (issue #522) ties each paragraph written while a session runs to a source the + person names (a web address, a file or a NoteCraft page); the pane lists the page's linked + paragraphs and opens their sources. NoteCraft does not watch other programs, so nothing is + linked that was not chosen, and the paragraphs carry no mark in the page's margin yet. +- **Password-protected sections** (issue #523) are sealed whole while locked. While one is + unlocked its files are ordinary files on disk, readable by any program; a page deleted from it + then is deleted for good rather than kept in the bin, and a section that is open cannot be moved, + copied or deleted until it is locked. Locking deletes the plain files the ordinary way, so a + disk-recovery tool may still find them. A note window of its own (Dock to Desktop) is a separate + program and is not told when another window locks the section its page is in. A section is + sealed in memory whole, so a very large section needs as much free memory to lock. - **Containers are a first pass.** A page can hold several boxes, each with its own place, width and blocks; a box is moved by the bar along its top and resized by its right edge, and the arrangement is kept in the page's own file. Clicking open paper starts a new box diff --git a/i18n/ar-XB.tsv b/i18n/ar-XB.tsv index 9052f93c..cda0f1c5 100644 --- a/i18n/ar-XB.tsv +++ b/i18n/ar-XB.tsv @@ -1967,3 +1967,64 @@ @id transcribe.invalid_path [[RLI]]$$$The recording path could not be read.@@@[[PDI]] @id transcribe.page_changed [[RLI]]$$$The destination page changed. Open its editable view to insert the transcript.@@@[[PDI]] @id transcribe.inserted [[RLI]]$$$Transcript inserted with its source audio.@@@[[PDI]] +@id ui.copy_link_to_paragraph [[RLI]]$$$Copy Link to Paragraph@@@[[PDI]] +@id ui.link_to_paragraph_copied [[RLI]]$$$Link to paragraph copied@@@[[PDI]] +@id ui.the_linked_paragraph_is_no_longer_on_this_page [[RLI]]$$$The linked paragraph is no longer on this page. The page is open at its top.@@@[[PDI]] +@id ui.notes_group [[RLI]]$$$Notes@@@[[PDI]] +@id ui.linked_notes [[RLI]]$$$Linked Notes@@@[[PDI]] +@id ui.linked_notes_tip [[RLI]]$$$Write notes tied to a web page, a file or a page you are reading, and open the source again later@@@[[PDI]] +@id ui.linked_notes_no_source [[RLI]]$$$Type or paste a web address, a file or a NoteCraft link first.@@@[[PDI]] +@id ui.linked_notes_no_such_file [[RLI]]$$$That file is not on this computer.@@@[[PDI]] +@id ui.linked_notes_no_such_page [[RLI]]$$$That NoteCraft link does not lead to a page in an open notebook.@@@[[PDI]] +@id ui.linked_notes_started [[RLI]]$$$Linked Notes started: what you write is linked to {source}@@@[[PDI]] +@id ui.linked_notes_stopped [[RLI]]$$$Linked Notes stopped@@@[[PDI]] +@id ui.linked_notes_choose_file [[RLI]]$$$Choose the file your notes are about@@@[[PDI]] +@id ui.linked_notes_linking_to [[RLI]]$$$Linking notes to {source}@@@[[PDI]] +@id ui.linked_notes_stop [[RLI]]$$$Stop Taking Linked Notes@@@[[PDI]] +@id ui.linked_notes_about [[RLI]]$$$Choose what you are reading. While Linked Notes runs, each paragraph you write is linked to it, so you can open it again from here.@@@[[PDI]] +@id ui.linked_notes_source_hint [[RLI]]$$$A web address, a file, or a NoteCraft link@@@[[PDI]] +@id ui.linked_notes_source [[RLI]]$$$Source@@@[[PDI]] +@id ui.linked_notes_browse [[RLI]]$$$Browse for a file…@@@[[PDI]] +@id ui.linked_notes_start [[RLI]]$$$Start Taking Linked Notes@@@[[PDI]] +@id ui.linked_notes_on_this_page [[RLI]]$$$Linked notes on this page@@@[[PDI]] +@id ui.linked_notes_none [[RLI]]$$$No paragraph on this page is linked to a source.@@@[[PDI]] +@id ui.linked_notes_open_source [[RLI]]$$$Open {source}@@@[[PDI]] +@id ui.linked_notes_open [[RLI]]$$$Open source@@@[[PDI]] +@id ui.linked_notes_unlink [[RLI]]$$$Remove link@@@[[PDI]] +@id ui.section_lock_save_first [[RLI]]$$$The open page in this section could not be saved, so the section was not locked.@@@[[PDI]] +@id ui.section_lock_failed [[RLI]]$$$The section could not be locked.@@@[[PDI]] +@id ui.section_protected [[RLI]]$$$The section is protected with a password and locked.@@@[[PDI]] +@id ui.section_wrong_password [[RLI]]$$$That password is not right. Passwords are case-sensitive.@@@[[PDI]] +@id ui.section_unlocked [[RLI]]$$$The section is unlocked.@@@[[PDI]] +@id ui.section_password_changed [[RLI]]$$$The section's password has been changed.@@@[[PDI]] +@id ui.section_password_removed [[RLI]]$$$The section's password has been removed.@@@[[PDI]] +@id ui.section_password_no_section [[RLI]]$$$Open a section first.@@@[[PDI]] +@id ui.sections_locked_after_idle [[RLI]]$$$Protected sections were locked after a time with no activity.@@@[[PDI]] +@id ui.password_protect_section [[RLI]]$$$Password Protect This Section@@@[[PDI]] +@id ui.password_protect_about [[RLI]]$$$Everything in the section is sealed with this password. While it is locked, its pages, pictures and earlier versions are not readable anywhere on this computer, in backups or in search.@@@[[PDI]] +@id ui.change_section_password [[RLI]]$$$Change Password@@@[[PDI]] +@id ui.change_section_password_about [[RLI]]$$$Enter the current password, then the new one twice.@@@[[PDI]] +@id ui.remove_section_password [[RLI]]$$$Remove Password@@@[[PDI]] +@id ui.remove_section_password_about [[RLI]]$$$The section is unlocked and kept as an ordinary section, readable without a password.@@@[[PDI]] +@id ui.lock_section_left_open [[RLI]]$$$Lock Protected Section@@@[[PDI]] +@id ui.lock_section_left_open_about [[RLI]]$$$This section was left unlocked when NoteCraft last closed. Enter its password to lock it again.@@@[[PDI]] +@id ui.section_password [[RLI]]$$$Password@@@[[PDI]] +@id ui.confirm_section_password [[RLI]]$$$Confirm password@@@[[PDI]] +@id ui.old_section_password [[RLI]]$$$Current password@@@[[PDI]] +@id ui.new_section_password [[RLI]]$$$New password@@@[[PDI]] +@id ui.section_password_cannot_be_recovered [[RLI]]$$$A forgotten password cannot be recovered, and the section cannot be opened without it.@@@[[PDI]] +@id ui.section_password_empty [[RLI]]$$$Enter a password.@@@[[PDI]] +@id ui.section_passwords_differ [[RLI]]$$$The passwords do not match.@@@[[PDI]] +@id ui.this_section_is_password_protected [[RLI]]$$$This section is protected with a password.@@@[[PDI]] +@id ui.unlock_section [[RLI]]$$$Unlock@@@[[PDI]] +@id ui.password_protect_this_section_ellipsis [[RLI]]$$$Password Protect This Section…@@@[[PDI]] +@id ui.lock_section [[RLI]]$$$Lock Section@@@[[PDI]] +@id ui.change_password_ellipsis [[RLI]]$$$Change Password…@@@[[PDI]] +@id ui.remove_password_ellipsis [[RLI]]$$$Remove Password…@@@[[PDI]] +@id ui.deleted_for_good_in_a_protected_section [[RLI]]$$$This section has a password, so what is deleted from it is deleted for good, not kept in the recycle bin.@@@[[PDI]] +@id ui.section_password_button [[RLI]]$$$Password@@@[[PDI]] +@id ui.section_password_tip [[RLI]]$$$Protect the open section with a password, or change its password.@@@[[PDI]] +@id ui.lock_all_sections [[RLI]]$$$Lock All@@@[[PDI]] +@id ui.lock_all_sections_tip [[RLI]]$$$Lock every password-protected section that is unlocked.@@@[[PDI]] +@id ui.sections_locked_n [[RLI]]$$$Locked {n} section.|Locked {n} sections.@@@[[PDI]] +@id ui.review_section_group [[RLI]]$$$Section@@@[[PDI]] diff --git a/i18n/en-XA.tsv b/i18n/en-XA.tsv index 4aa5fc3c..3fbc5ff4 100644 --- a/i18n/en-XA.tsv +++ b/i18n/en-XA.tsv @@ -1967,3 +1967,64 @@ @id transcribe.invalid_path $$$The recording path could not be read.@@@ @id transcribe.page_changed $$$The destination page changed. Open its editable view to insert the transcript.@@@ @id transcribe.inserted $$$Transcript inserted with its source audio.@@@ +@id ui.copy_link_to_paragraph $$$Copy Link to Paragraph@@@ +@id ui.link_to_paragraph_copied $$$Link to paragraph copied@@@ +@id ui.the_linked_paragraph_is_no_longer_on_this_page $$$The linked paragraph is no longer on this page. The page is open at its top.@@@ +@id ui.notes_group $$$Notes@@@ +@id ui.linked_notes $$$Linked Notes@@@ +@id ui.linked_notes_tip $$$Write notes tied to a web page, a file or a page you are reading, and open the source again later@@@ +@id ui.linked_notes_no_source $$$Type or paste a web address, a file or a NoteCraft link first.@@@ +@id ui.linked_notes_no_such_file $$$That file is not on this computer.@@@ +@id ui.linked_notes_no_such_page $$$That NoteCraft link does not lead to a page in an open notebook.@@@ +@id ui.linked_notes_started $$$Linked Notes started: what you write is linked to {source}@@@ +@id ui.linked_notes_stopped $$$Linked Notes stopped@@@ +@id ui.linked_notes_choose_file $$$Choose the file your notes are about@@@ +@id ui.linked_notes_linking_to $$$Linking notes to {source}@@@ +@id ui.linked_notes_stop $$$Stop Taking Linked Notes@@@ +@id ui.linked_notes_about $$$Choose what you are reading. While Linked Notes runs, each paragraph you write is linked to it, so you can open it again from here.@@@ +@id ui.linked_notes_source_hint $$$A web address, a file, or a NoteCraft link@@@ +@id ui.linked_notes_source $$$Source@@@ +@id ui.linked_notes_browse $$$Browse for a file…@@@ +@id ui.linked_notes_start $$$Start Taking Linked Notes@@@ +@id ui.linked_notes_on_this_page $$$Linked notes on this page@@@ +@id ui.linked_notes_none $$$No paragraph on this page is linked to a source.@@@ +@id ui.linked_notes_open_source $$$Open {source}@@@ +@id ui.linked_notes_open $$$Open source@@@ +@id ui.linked_notes_unlink $$$Remove link@@@ +@id ui.section_lock_save_first $$$The open page in this section could not be saved, so the section was not locked.@@@ +@id ui.section_lock_failed $$$The section could not be locked.@@@ +@id ui.section_protected $$$The section is protected with a password and locked.@@@ +@id ui.section_wrong_password $$$That password is not right. Passwords are case-sensitive.@@@ +@id ui.section_unlocked $$$The section is unlocked.@@@ +@id ui.section_password_changed $$$The section's password has been changed.@@@ +@id ui.section_password_removed $$$The section's password has been removed.@@@ +@id ui.section_password_no_section $$$Open a section first.@@@ +@id ui.sections_locked_after_idle $$$Protected sections were locked after a time with no activity.@@@ +@id ui.password_protect_section $$$Password Protect This Section@@@ +@id ui.password_protect_about $$$Everything in the section is sealed with this password. While it is locked, its pages, pictures and earlier versions are not readable anywhere on this computer, in backups or in search.@@@ +@id ui.change_section_password $$$Change Password@@@ +@id ui.change_section_password_about $$$Enter the current password, then the new one twice.@@@ +@id ui.remove_section_password $$$Remove Password@@@ +@id ui.remove_section_password_about $$$The section is unlocked and kept as an ordinary section, readable without a password.@@@ +@id ui.lock_section_left_open $$$Lock Protected Section@@@ +@id ui.lock_section_left_open_about $$$This section was left unlocked when NoteCraft last closed. Enter its password to lock it again.@@@ +@id ui.section_password $$$Password@@@ +@id ui.confirm_section_password $$$Confirm password@@@ +@id ui.old_section_password $$$Current password@@@ +@id ui.new_section_password $$$New password@@@ +@id ui.section_password_cannot_be_recovered $$$A forgotten password cannot be recovered, and the section cannot be opened without it.@@@ +@id ui.section_password_empty $$$Enter a password.@@@ +@id ui.section_passwords_differ $$$The passwords do not match.@@@ +@id ui.this_section_is_password_protected $$$This section is protected with a password.@@@ +@id ui.unlock_section $$$Unlock@@@ +@id ui.password_protect_this_section_ellipsis $$$Password Protect This Section…@@@ +@id ui.lock_section $$$Lock Section@@@ +@id ui.change_password_ellipsis $$$Change Password…@@@ +@id ui.remove_password_ellipsis $$$Remove Password…@@@ +@id ui.deleted_for_good_in_a_protected_section $$$This section has a password, so what is deleted from it is deleted for good, not kept in the recycle bin.@@@ +@id ui.section_password_button $$$Password@@@ +@id ui.section_password_tip $$$Protect the open section with a password, or change its password.@@@ +@id ui.lock_all_sections $$$Lock All@@@ +@id ui.lock_all_sections_tip $$$Lock every password-protected section that is unlocked.@@@ +@id ui.sections_locked_n $$$Locked {n} section.|Locked {n} sections.@@@ +@id ui.review_section_group $$$Section@@@ diff --git a/i18n/en.tsv b/i18n/en.tsv index 9ceb6c1b..8359944a 100644 --- a/i18n/en.tsv +++ b/i18n/en.tsv @@ -1967,3 +1967,64 @@ @id transcribe.invalid_path The recording path could not be read. @id transcribe.page_changed The destination page changed. Open its editable view to insert the transcript. @id transcribe.inserted Transcript inserted with its source audio. +@id ui.copy_link_to_paragraph Copy Link to Paragraph +@id ui.link_to_paragraph_copied Link to paragraph copied +@id ui.the_linked_paragraph_is_no_longer_on_this_page The linked paragraph is no longer on this page. The page is open at its top. +@id ui.notes_group Notes +@id ui.linked_notes Linked Notes +@id ui.linked_notes_tip Write notes tied to a web page, a file or a page you are reading, and open the source again later +@id ui.linked_notes_no_source Type or paste a web address, a file or a NoteCraft link first. +@id ui.linked_notes_no_such_file That file is not on this computer. +@id ui.linked_notes_no_such_page That NoteCraft link does not lead to a page in an open notebook. +@id ui.linked_notes_started Linked Notes started: what you write is linked to {source} +@id ui.linked_notes_stopped Linked Notes stopped +@id ui.linked_notes_choose_file Choose the file your notes are about +@id ui.linked_notes_linking_to Linking notes to {source} +@id ui.linked_notes_stop Stop Taking Linked Notes +@id ui.linked_notes_about Choose what you are reading. While Linked Notes runs, each paragraph you write is linked to it, so you can open it again from here. +@id ui.linked_notes_source_hint A web address, a file, or a NoteCraft link +@id ui.linked_notes_source Source +@id ui.linked_notes_browse Browse for a file… +@id ui.linked_notes_start Start Taking Linked Notes +@id ui.linked_notes_on_this_page Linked notes on this page +@id ui.linked_notes_none No paragraph on this page is linked to a source. +@id ui.linked_notes_open_source Open {source} +@id ui.linked_notes_open Open source +@id ui.linked_notes_unlink Remove link +@id ui.section_lock_save_first The open page in this section could not be saved, so the section was not locked. +@id ui.section_lock_failed The section could not be locked. +@id ui.section_protected The section is protected with a password and locked. +@id ui.section_wrong_password That password is not right. Passwords are case-sensitive. +@id ui.section_unlocked The section is unlocked. +@id ui.section_password_changed The section's password has been changed. +@id ui.section_password_removed The section's password has been removed. +@id ui.section_password_no_section Open a section first. +@id ui.sections_locked_after_idle Protected sections were locked after a time with no activity. +@id ui.password_protect_section Password Protect This Section +@id ui.password_protect_about Everything in the section is sealed with this password. While it is locked, its pages, pictures and earlier versions are not readable anywhere on this computer, in backups or in search. +@id ui.change_section_password Change Password +@id ui.change_section_password_about Enter the current password, then the new one twice. +@id ui.remove_section_password Remove Password +@id ui.remove_section_password_about The section is unlocked and kept as an ordinary section, readable without a password. +@id ui.lock_section_left_open Lock Protected Section +@id ui.lock_section_left_open_about This section was left unlocked when NoteCraft last closed. Enter its password to lock it again. +@id ui.section_password Password +@id ui.confirm_section_password Confirm password +@id ui.old_section_password Current password +@id ui.new_section_password New password +@id ui.section_password_cannot_be_recovered A forgotten password cannot be recovered, and the section cannot be opened without it. +@id ui.section_password_empty Enter a password. +@id ui.section_passwords_differ The passwords do not match. +@id ui.this_section_is_password_protected This section is protected with a password. +@id ui.unlock_section Unlock +@id ui.password_protect_this_section_ellipsis Password Protect This Section… +@id ui.lock_section Lock Section +@id ui.change_password_ellipsis Change Password… +@id ui.remove_password_ellipsis Remove Password… +@id ui.deleted_for_good_in_a_protected_section This section has a password, so what is deleted from it is deleted for good, not kept in the recycle bin. +@id ui.section_password_button Password +@id ui.section_password_tip Protect the open section with a password, or change its password. +@id ui.lock_all_sections Lock All +@id ui.lock_all_sections_tip Lock every password-protected section that is unlocked. +@id ui.sections_locked_n Locked {n} section.|Locked {n} sections. +@id ui.review_section_group Section diff --git a/tools/ocr-lab/src/app.rs b/tools/ocr-lab/src/app.rs index f15cc22f..66776f68 100644 --- a/tools/ocr-lab/src/app.rs +++ b/tools/ocr-lab/src/app.rs @@ -667,6 +667,7 @@ impl Lab { can_ink_redo: false, ink_held: false, accessibility_open: false, + linked_notes_open: false, spelling_open: false, thesaurus_open: false, proofing_language: "",