diff --git a/AGENT_DOCUMENTATION.md b/AGENT_DOCUMENTATION.md index 5e3d84a..728f7aa 100644 --- a/AGENT_DOCUMENTATION.md +++ b/AGENT_DOCUMENTATION.md @@ -26,3 +26,5 @@ - [Private process protocol](docs/interfaces/process-protocol.md). - [Manual release preparation](docs/development/releases.md). + +- [Presentation notes sidecars and editor](docs/interfaces/presentation-notes.md). diff --git a/Cargo.lock b/Cargo.lock index 333bbd4..2841f52 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2221,7 +2221,7 @@ dependencies = [ [[package]] name = "pdf-presenter" -version = "0.1.51" +version = "0.1.52" dependencies = [ "bytemuck", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 700de65..a72006e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ default-members = ["crates/pdf-presenter"] resolver = "3" [workspace.package] -version = "0.1.51" +version = "0.1.52" edition = "2024" license = "MIT" repository = "https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter" diff --git a/crates/pdf-presenter/src/document.rs b/crates/pdf-presenter/src/document.rs index fc7e8dc..b6c607f 100644 --- a/crates/pdf-presenter/src/document.rs +++ b/crates/pdf-presenter/src/document.rs @@ -244,6 +244,9 @@ impl Document { } source = Source::Pdf(pdf); } + if load_notes && let Err(error) = crate::notes::overlay(&path, &names, &mut notes) { + warnings.push(format!("Presentation notes: {error}")); + } let title = path .file_name() .unwrap_or_default() diff --git a/crates/pdf-presenter/src/lib.rs b/crates/pdf-presenter/src/lib.rs index 8873a99..74a6445 100644 --- a/crates/pdf-presenter/src/lib.rs +++ b/crates/pdf-presenter/src/lib.rs @@ -87,3 +87,6 @@ mod artwork; /// Monotonic elapsed/countdown timer. pub mod timer; + +/// Editable presentation notes sidecars. +pub mod notes; diff --git a/crates/pdf-presenter/src/localization.rs b/crates/pdf-presenter/src/localization.rs index dab0984..f2d8e71 100644 --- a/crates/pdf-presenter/src/localization.rs +++ b/crates/pdf-presenter/src/localization.rs @@ -95,6 +95,22 @@ pub fn tr<'a>(ctx: &egui::Context, text: &'a str) -> &'a str { "Previous slide" => "Diapositive précédente", "Current slide" => "Diapositive actuelle", "Next slide" => "Diapositive suivante", + "Double-click to edit this slide’s notes" => { + "Double-cliquez pour modifier les notes de cette diapositive" + } + "Edit notes" => "Modifier les notes", + "Saving notes…" => "Enregistrement des notes…", + "Loading all notes and preparing sidecar…" => { + "Lecture des notes et préparation du fichier…" + } + "The file contains all slides. Save changes only this slide." => { + "Le fichier contient toutes les diapositives. Seule celle-ci sera modifiée." + } + "Note exceeds 256 KiB" => "La note dépasse 256 Kio", + "Save notes" => "Enregistrer les notes", + "Discard changes and close" => "Abandonner les modifications et fermer", + "Reload (discard edits)" => "Recharger (abandonner les modifications)", + "Retry" => "Réessayer", "Notes" => "Notes", "Elapsed time" => "Temps écoulé", "Time · HH:MM" => "Heure · HH:MM", diff --git a/crates/pdf-presenter/src/native.rs b/crates/pdf-presenter/src/native.rs index 31b88a9..b74cf1c 100644 --- a/crates/pdf-presenter/src/native.rs +++ b/crates/pdf-presenter/src/native.rs @@ -597,6 +597,11 @@ impl App { s.execute(Action::RevertRoutes); return; } + // Notes editing must never turn typing or Escape into presentation commands. + // Unsaved text is only discarded through the explicit editor control. + if role == Role::Presenter && s.notes_editor.is_some() { + return; + } if modifiers.ctrl || modifiers.alt || modifiers.command || consumed { return; } @@ -987,7 +992,14 @@ impl ApplicationHandler for App { match event { WindowEvent::CloseRequested => { if role == Role::Presenter { - el.exit(); + if let Some(s) = &mut self.studio { + s.execute(Action::Exit); + if s.close_requested { + el.exit(); + } else { + self.redraw(); + } + } } else if role == Role::Browser { if let Some(s) = &mut self.studio { s.execute(Action::CloseBrowser); diff --git a/crates/pdf-presenter/src/notes.rs b/crates/pdf-presenter/src/notes.rs new file mode 100644 index 0000000..cb1efe6 --- /dev/null +++ b/crates/pdf-presenter/src/notes.rs @@ -0,0 +1,196 @@ +//! Versioned presenter-only notes sidecars. All I/O runs in isolated workers. +use crate::document::{DeckInfo, Document, read_limited}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeMap, + io::Write, + path::{Path, PathBuf}, +}; + +pub const MAX_NOTE: usize = 256 * 1024; +const MAX_TEXT: usize = 8 * 1024 * 1024; +const MAX_FILE: u64 = 16 * 1024 * 1024; +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct NotesFile { + version: u32, + notes: BTreeMap, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Snapshot { + pub path: PathBuf, + pub revision: String, + pub notes: Vec, +} +/// PDF: sibling `talk.notes.toml`; image folder: sibling `folder.notes.toml`. +/// Called only in workers, because distinguishing folders requires filesystem access. +pub fn sidecar_path(source: &Path) -> PathBuf { + if source.is_dir() { + let mut name = source.file_name().unwrap_or_default().to_os_string(); + name.push(".notes.toml"); + source.with_file_name(name) + } else { + source.with_extension("notes.toml") + } +} +fn keys(source: &Path, names: &[String]) -> Vec { + if source.is_dir() { + names.to_vec() + } else { + (1..=names.len()).map(|n| n.to_string()).collect() + } +} +fn revision(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) +} +fn validate(file: &NotesFile) -> Result<(), String> { + if file.version != 1 { + return Err(format!("Unsupported notes version {}", file.version)); + } + if file.notes.len() > 10000 + || file.notes.values().any(|n| n.len() > MAX_NOTE) + || file.notes.values().map(String::len).sum::() > MAX_TEXT + { + return Err("Notes exceed limits (256 KiB per slide, 8 MiB total, 10000 entries)".into()); + } + Ok(()) +} +fn read(path: &Path) -> Result)>, String> { + match std::fs::symlink_metadata(path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e.to_string()), + Ok(meta) if !meta.file_type().is_file() => { + return Err("Notes sidecar must be a regular file, not a symlink or directory".into()); + } + _ => {} + } + let bytes = read_limited(path, MAX_FILE)?; + let file: NotesFile = toml::from_str(std::str::from_utf8(&bytes).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + validate(&file)?; + Ok(Some((file, bytes))) +} +/// Named sidecar entries override extracted notes, including explicitly empty entries. +pub fn overlay(source: &Path, names: &[String], notes: &mut [String]) -> Result<(), String> { + if let Some((file, _)) = read(&sidecar_path(source))? { + let mut merged = notes.to_vec(); + for (key, note) in keys(source, names).iter().zip(&mut merged) { + if let Some(value) = file.notes.get(key) { + *note = value.clone(); + } + } + if merged.iter().map(String::len).sum::() > MAX_TEXT { + return Err("Combined notes exceed 8 MiB".into()); + } + notes.clone_from_slice(&merged); + } + Ok(()) +} +type LoadedNotes = (DeckInfo, Option<(NotesFile, Vec)>); +fn document(source: &Path, cache: PathBuf, expected_source: &str) -> Result { + let path = sidecar_path(source); + let before = read(&path)?; + let info = Document::open(source, cache)?.info; + if info.sha256 != expected_source { + return Err("Presentation changed on disk. Reopen it before editing notes.".into()); + } + if let Some(warning) = info + .warnings + .iter() + .find(|w| w.starts_with("Presentation notes:")) + { + return Err(warning.clone()); + } + let after = read(&path)?; + if before.as_ref().map(|(_, b)| b) != after.as_ref().map(|(_, b)| b) { + return Err("Notes changed while loading. Retry to read the latest notes.".into()); + } + Ok((info, after)) +} +fn bytes(file: &NotesFile) -> Result, String> { + validate(file)?; + let bytes = toml::to_string_pretty(file) + .map_err(|e| e.to_string())? + .into_bytes(); + if bytes.len() as u64 > MAX_FILE { + return Err("Serialized notes exceed 16 MiB".into()); + } + Ok(bytes) +} +fn temporary(path: &Path, bytes: &[u8]) -> Result { + let mut file = tempfile::NamedTempFile::new_in(path.parent().ok_or("No notes parent folder")?) + .map_err(|e| e.to_string())?; + file.write_all(bytes) + .and_then(|_| file.as_file().sync_all()) + .map_err(|e| e.to_string())?; + Ok(file) +} +pub fn prepare(source: &Path, cache: PathBuf, expected_source: &str) -> Result { + let (info, existing) = document(source, cache, expected_source)?; + let path = sidecar_path(&info.path); + let bytes = match existing { + Some((_, bytes)) => bytes, + None => { + let file = NotesFile { + version: 1, + notes: keys(&info.path, &info.names) + .into_iter() + .zip(info.notes.iter().cloned()) + .collect(), + }; + let bytes = bytes(&file)?; + // Never replace a sidecar that appeared while extraction was running. + temporary(&path, &bytes)? + .persist_noclobber(&path) + .map_err(|e| { + format!("Could not create notes (retry if the file appeared meanwhile): {e}") + })?; + bytes + } + }; + Ok(Snapshot { + path, + revision: revision(&bytes), + notes: info.notes, + }) +} +pub fn save( + source: &Path, + cache: PathBuf, + expected_source: &str, + expected_revision: &str, + page: usize, + text: String, +) -> Result { + if text.len() > MAX_NOTE { + return Err("This note exceeds 256 KiB".into()); + } + let (mut info, existing) = document(source, cache, expected_source)?; + let key = keys(&info.path, &info.names) + .get(page) + .cloned() + .ok_or("Slide no longer exists")?; + let path = sidecar_path(&info.path); + let (mut file, previous) = existing.ok_or("Notes file was removed. Reload before saving.")?; + if revision(&previous) != expected_revision { + return Err("Notes changed on disk. Copy your edits, then reload before saving.".into()); + } + info.notes[page] = text.clone(); + if info.notes.iter().map(String::len).sum::() > MAX_TEXT { + return Err("Combined notes exceed 8 MiB; changes were not saved.".into()); + } + file.notes.insert(key, text.clone()); + let bytes = bytes(&file)?; + let temp = temporary(&path, &bytes)?; + let (_, latest) = read(&path)?.ok_or("Notes file was removed while saving")?; + if latest != previous { + return Err("Notes changed while saving; edits were not written.".into()); + } + temp.persist(&path).map_err(|e| e.to_string())?; + Ok(Snapshot { + path, + revision: revision(&bytes), + notes: info.notes, + }) +} diff --git a/crates/pdf-presenter/src/presenter_ui.rs b/crates/pdf-presenter/src/presenter_ui.rs index f03231f..738f48e 100644 --- a/crates/pdf-presenter/src/presenter_ui.rs +++ b/crates/pdf-presenter/src/presenter_ui.rs @@ -685,6 +685,13 @@ pub fn presenter(ui: &mut Ui, s: &mut Studio, native: &mut UiState) { } if s.layout.notes.show { let rect = notes_rect; + let response = ui.interact(rect, ui.id().with("presenter-notes"), Sense::click()); + response + .clone() + .on_hover_text(tr(&locale, "Double-click to edit this slide’s notes")); + if response.double_clicked() && s.count() > 0 { + s.actions.push(Action::EditNotes); + } ui.painter().rect_filled(rect, 8., ui.visuals().window_fill); ui.painter().text( rect.min + Vec2::splat(14.), @@ -1283,7 +1290,134 @@ pub fn presenter(ui: &mut Ui, s: &mut Studio, native: &mut UiState) { }); s.displays_open &= open; } + notes_editor_ui(&ctx, s); } +fn notes_editor_ui(ctx: &Context, s: &mut Studio) { + let Some(editor) = &mut s.notes_editor else { + return; + }; + let mut action = None; + let mut close = false; + egui::Window::new(format!( + "{} · {} {}", + tr(ctx, "Edit notes"), + tr(ctx, "Slide"), + editor.page + 1 + )) + .id(egui::Id::new("notes-editor")) + .collapsible(false) + .resizable(true) + .default_size(Vec2::new(640., 480.).min(ctx.content_rect().size() - Vec2::splat(48.))) + .min_size(Vec2::new(300., 220.)) + .max_size(ctx.content_rect().size() - Vec2::splat(32.)) + .show(ctx, |ui| { + if editor.busy { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(tr( + ctx, + if editor.snapshot.is_some() { + "Saving notes…" + } else { + "Loading all notes and preparing sidecar…" + }, + )); + }); + } + if let Some(snapshot) = &editor.snapshot { + ui.label( + snapshot + .path + .file_name() + .unwrap_or_default() + .to_string_lossy(), + ) + .on_hover_text(snapshot.path.display().to_string()); + ui.small(tr( + ctx, + "The file contains all slides. Save changes only this slide.", + )); + } + if let Some(error) = &editor.error { + ui.colored_label(ui.visuals().error_fg_color, error); + } + let ready = editor.snapshot.is_some() && !editor.busy; + egui::ScrollArea::vertical() + .id_salt("notes-editor-text-scroll") + .max_height((ui.available_height() - 76.).max(60.)) + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.add_enabled( + ready, + egui::TextEdit::multiline(&mut editor.text) + .id(egui::Id::new(( + "notes-editor-text", + s.generation, + editor.page, + ))) + .desired_width(f32::INFINITY) + .desired_rows(12) + .char_limit(crate::notes::MAX_NOTE), + ); + }); + if editor.text.len() > crate::notes::MAX_NOTE { + ui.colored_label(ui.visuals().error_fg_color, tr(ctx, "Note exceeds 256 KiB")); + } + ui.separator(); + ui.horizontal_wrapped(|ui| { + if ui + .add_enabled( + ready && editor.text.len() <= crate::notes::MAX_NOTE, + egui::Button::new(tr(ctx, "Save notes")), + ) + .clicked() + { + action = Some(Action::SaveNotes); + } + let dirty = editor.text != editor.saved_text; + if ui + .add_enabled( + !editor.busy, + egui::Button::new(tr( + ctx, + if dirty { + "Discard changes and close" + } else { + "Close" + }, + )), + ) + .clicked() + { + close = true; + } + if editor.error.is_some() + && ui + .add_enabled( + !editor.busy, + egui::Button::new(tr( + ctx, + if editor.snapshot.is_some() { + "Reload (discard edits)" + } else { + "Retry" + }, + )), + ) + .clicked() + { + action = Some(Action::ReloadNotes); + } + }); + }); + if let Some(action) = action { + s.actions.push(action); + } + if close { + s.notes_editor = None; + } +} + fn browser_preview_settings(ui: &mut Ui, s: &mut Studio) { let locale = ui.ctx().clone(); ui.horizontal(|ui| { diff --git a/crates/pdf-presenter/src/studio.rs b/crates/pdf-presenter/src/studio.rs index 6fd142f..f75c9fd 100644 --- a/crates/pdf-presenter/src/studio.rs +++ b/crates/pdf-presenter/src/studio.rs @@ -37,6 +37,17 @@ pub enum Action { ToggleFullscreen, ToggleTimer, RestartTimer, + EditNotes, + ReloadNotes, + SaveNotes, +} +pub struct NotesEditor { + pub page: usize, + pub text: String, + pub saved_text: String, + pub snapshot: Option, + pub busy: bool, + pub error: Option, } pub struct RouteTrial { pub id: u64, @@ -73,6 +84,9 @@ pub struct Studio { pub evicted_frames: usize, pub loading: bool, pub notes_loading: bool, + pub notes_editor: Option, + notes_io: Bridge, + notes_edited: bool, pub visible_thumbs: HashSet, pub layout_open: bool, pub displays_open: bool, @@ -166,6 +180,9 @@ impl Studio { evicted_frames: 0, loading: false, notes_loading: false, + notes_editor: None, + notes_io: Bridge::with_program(Duration::from_secs(30), worker_program.clone()), + notes_edited: false, visible_thumbs: HashSet::new(), layout_open: false, displays_open: false, @@ -282,6 +299,11 @@ impl Studio { pub fn execute(&mut self, action: Action) { match action { Action::Open(path) => { + if self.notes_editor.is_some() { + self.status = + "Close the notes editor before opening another presentation.".into(); + return; + } if self.fg_busy { self.fg = Bridge::with_program(Duration::from_secs(30), self.worker_program.clone()); @@ -439,7 +461,74 @@ impl Studio { self.pending_save = true; } Action::Refresh => self.dirty_routes = true, - Action::Exit => self.close_requested = true, + Action::Exit => { + if self + .notes_editor + .as_ref() + .is_some_and(|editor| editor.busy || editor.text != editor.saved_text) + { + self.status = "Save or discard notes before closing the presentation.".into(); + } else { + self.close_requested = true; + } + } + command @ (Action::EditNotes | Action::ReloadNotes) => { + if matches!(command, Action::EditNotes) && self.notes_editor.is_some() { + return; + } + if self.loading || self.notes_editor.as_ref().is_some_and(|e| e.busy) { + return; + } + if let Some(deck) = &self.deck { + let page = self + .notes_editor + .as_ref() + .map_or(self.requested, |e| e.page); + if page >= self.count() { + return; + } + if self.notes_io.submit( + self.generation, + 0, + Request::PrepareNotes { + path: deck.path.clone(), + cache: self.cache_path.clone(), + source_sha: deck.sha256.clone(), + }, + ) { + self.notes_editor = Some(NotesEditor { + page, + text: String::new(), + saved_text: String::new(), + snapshot: None, + busy: true, + error: None, + }); + self.jump.clear(); + } + } + } + Action::SaveNotes => { + if let (Some(deck), Some(editor)) = (&self.deck, &mut self.notes_editor) + && !editor.busy + && let Some(snapshot) = &editor.snapshot + && self.notes_io.submit( + self.generation, + 1, + Request::SaveNotes { + path: deck.path.clone(), + cache: self.cache_path.clone(), + source_sha: deck.sha256.clone(), + revision: snapshot.revision.clone(), + page: editor.page, + text: editor.text.clone(), + }, + ) + { + editor.busy = true; + editor.error = None; + } + } Action::ToggleTimer => self.timer.toggle(Instant::now(), self.timer_limit()), Action::RestartTimer => self.timer.restart(Instant::now()), Action::ToggleFullscreen => { @@ -495,6 +584,39 @@ impl Studio { }) } pub fn poll(&mut self) { + while let Ok(completion) = self.notes_io.rx.try_recv() { + if completion.generation != self.generation { + continue; + } + if let Some(editor) = &mut self.notes_editor { + editor.busy = false; + match completion.result { + Ok(packet) => { + editor.error = packet.reply.error; + if let Some(snapshot) = packet.reply.notes { + editor.text = + snapshot.notes.get(editor.page).cloned().unwrap_or_default(); + editor.saved_text = editor.text.clone(); + if let Some(deck) = &mut self.deck { + deck.notes = snapshot.notes.clone(); + } + editor.snapshot = Some(snapshot); + self.notes_edited = true; + self.status = if completion.tag == 1 { + "Notes saved." + } else { + "Notes editor ready." + } + .into(); + } + } + Err(error) => editor.error = Some(error), + } + if let Some(error) = &editor.error { + self.status = format!("Notes: {error}"); + } + } + } if self .route_trial .as_ref() @@ -591,7 +713,9 @@ impl Studio { if let Some(info) = packet.reply.info { if c.tag == u64::MAX { self.notes_loading = false; - if let Some(deck) = &mut self.deck { + if !self.notes_edited + && let Some(deck) = &mut self.deck + { deck.notes = info.notes; deck.warnings = info.warnings; if let Some(warning) = deck.warnings.first() { @@ -609,6 +733,7 @@ impl Studio { self.bg_job = None; self.notes_loading = false; self.notes_pending = true; + self.notes_edited = false; self.cached_slides = 0; self.evicted_frames = 0; self.generation += 1; diff --git a/crates/pdf-presenter/src/worker.rs b/crates/pdf-presenter/src/worker.rs index 4f090d2..001dde5 100644 --- a/crates/pdf-presenter/src/worker.rs +++ b/crates/pdf-presenter/src/worker.rs @@ -34,6 +34,19 @@ pub enum Request { path: PathBuf, cache: PathBuf, }, + PrepareNotes { + path: PathBuf, + cache: PathBuf, + source_sha: String, + }, + SaveNotes { + path: PathBuf, + cache: PathBuf, + source_sha: String, + revision: String, + page: usize, + text: String, + }, Preview { epoch: u64, path: PathBuf, @@ -60,6 +73,7 @@ pub struct Reply { pub info: Option, pub frame: Option, pub settings: Option, + pub notes: Option, pub picked: Option, pub bytes: usize, pub edge: Option, @@ -189,6 +203,30 @@ pub fn run() -> Result<(), String> { Request::Notes { path, cache } => { reply.info = Some(document::Document::open(&path, cache)?.info); } + Request::PrepareNotes { + path, + cache, + source_sha, + } => { + reply.notes = Some(crate::notes::prepare(&path, cache, &source_sha)?); + } + Request::SaveNotes { + path, + cache, + source_sha, + revision, + page, + text, + } => { + reply.notes = Some(crate::notes::save( + &path, + cache, + &source_sha, + &revision, + page, + text, + )?); + } Request::ReadFrame(path) => { let (width, height, rgba) = document::read_frame(&path)?; reply.frame = Some(FrameInfo { diff --git a/crates/pdf-presenter/tests/notes.rs b/crates/pdf-presenter/tests/notes.rs new file mode 100644 index 0000000..96ce610 --- /dev/null +++ b/crates/pdf-presenter/tests/notes.rs @@ -0,0 +1,281 @@ +mod common; +use pdf_presenter::{ + document::Document, + notes, + studio::{Action, Studio}, +}; +use std::time::{Duration, Instant}; + +#[test] +fn pdf_sidecar_precedence_creation_all_pages_and_source_preservation() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("presentation.X.pdf"); + let cache = temp.path().join("cache"); + common::pdf(&source); + let original = std::fs::read(&source).unwrap(); + let doc = Document::open(&source, cache.clone()).unwrap(); + assert_eq!(doc.info.notes, vec!["Speaker note\n", ""]); + let snapshot = notes::prepare(&source, cache.clone(), &doc.info.sha256).unwrap(); + assert_eq!(snapshot.path, temp.path().join("presentation.X.notes.toml")); + let file: toml::Value = + toml::from_str(&std::fs::read_to_string(&snapshot.path).unwrap()).unwrap(); + assert_eq!(file["version"].as_integer(), Some(1)); + assert_eq!(file["notes"]["1"].as_str(), Some("Speaker note\n")); + assert_eq!(file["notes"]["2"].as_str(), Some("")); + let saved = notes::save( + &source, + cache.clone(), + &doc.info.sha256, + &snapshot.revision, + 1, + "Second\n\"quoted\" é漢字".into(), + ) + .unwrap(); + assert_eq!(saved.notes[0], "Speaker note\n"); + let saved = notes::save( + &source, + cache.clone(), + &doc.info.sha256, + &saved.revision, + 0, + String::new(), + ) + .unwrap(); + assert_eq!( + Document::open(&source, cache.clone()).unwrap().info.notes, + saved.notes + ); + assert_eq!(saved.notes[0], ""); // An explicit empty note hides the PDF annotation. + std::fs::write(&snapshot.path, "version=1\n[notes]\n\"2\"='Override'").unwrap(); + let reopened = Document::open(&source, cache).unwrap(); + assert_eq!(reopened.info.notes, vec!["Speaker note\n", "Override"]); + assert_eq!(original, std::fs::read(&source).unwrap()); +} + +#[test] +fn editor_refuses_conflicts_invalid_sidecars_and_changed_sources() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("talk.pdf"); + let cache = temp.path().join("cache"); + common::pdf(&source); + let sha = Document::open(&source, cache.clone()).unwrap().info.sha256; + let snapshot = notes::prepare(&source, cache.clone(), &sha).unwrap(); + let external = "version=1\n[notes]\n\"1\"='External edit'\n\"99\"='Keep unknown page'"; + std::fs::write(&snapshot.path, external).unwrap(); + assert!( + notes::save( + &source, + cache.clone(), + &sha, + &snapshot.revision, + 0, + "Old edit".into() + ) + .unwrap_err() + .contains("changed on disk") + ); + assert_eq!(std::fs::read_to_string(&snapshot.path).unwrap(), external); + let fresh = notes::prepare(&source, cache.clone(), &sha).unwrap(); + notes::save( + &source, + cache.clone(), + &sha, + &fresh.revision, + 1, + "New".into(), + ) + .unwrap(); + assert!( + std::fs::read_to_string(&snapshot.path) + .unwrap() + .contains("Keep unknown page") + ); + for bad in [ + "not toml ]", + "version=2\n[notes]", + "version=1\nextra=true\n[notes]", + ] { + std::fs::write(&snapshot.path, bad).unwrap(); + let doc = Document::open(&source, cache.clone()).unwrap(); + assert_eq!(doc.info.notes[0], "Speaker note\n"); + assert!(!doc.info.warnings.is_empty()); + assert!(notes::prepare(&source, cache.clone(), &sha).is_err()); + assert_eq!(std::fs::read_to_string(&snapshot.path).unwrap(), bad); + } + std::fs::remove_file(&snapshot.path).unwrap(); + assert!( + notes::save( + &source, + cache.clone(), + &sha, + &fresh.revision, + 0, + "No file".into() + ) + .is_err() + ); + assert!(notes::prepare(&source, cache.clone(), "wrong source SHA").is_err()); + let fresh = notes::prepare(&source, cache.clone(), &sha).unwrap(); + assert!( + notes::save( + &source, + cache.clone(), + &sha, + &fresh.revision, + 7, + "No slide".into() + ) + .is_err() + ); + assert!( + notes::save( + &source, + cache, + &sha, + &fresh.revision, + 0, + "x".repeat(notes::MAX_NOTE + 1) + ) + .is_err() + ); +} + +#[test] +fn image_folder_sidecar_uses_filenames_and_keeps_original_notes() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("Images"); + std::fs::create_dir(&source).unwrap(); + common::image(&source.join("slide2.png"), [0, 0, 0, 255]); + common::image(&source.join("slide10.png"), [0, 0, 0, 255]); + std::fs::write(source.join("slide2.txt"), "Original").unwrap(); + std::fs::write(source.join("notes.toml"), "\"slide10.png\"='Global'").unwrap(); + let cache = temp.path().join("cache"); + let sha = Document::open(&source, cache.clone()).unwrap().info.sha256; + let snapshot = notes::prepare(&source, cache.clone(), &sha).unwrap(); + assert_eq!(snapshot.path, temp.path().join("Images.notes.toml")); + let saved = notes::save( + &source, + cache.clone(), + &sha, + &snapshot.revision, + 0, + "Edited".into(), + ) + .unwrap(); + assert_eq!(saved.notes, vec!["Edited", "Global"]); + assert_eq!( + Document::open(&source, cache).unwrap().info.notes, + saved.notes + ); + assert_eq!( + std::fs::read_to_string(source.join("slide2.txt")).unwrap(), + "Original" + ); +} + +#[cfg(unix)] +#[test] +fn symlink_sidecars_are_never_overwritten() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("talk.pdf"); + common::pdf(&source); + let cache = temp.path().join("cache"); + let sha = Document::open(&source, cache.clone()).unwrap().info.sha256; + let target = temp.path().join("external"); + std::fs::write(&target, "untouched").unwrap(); + std::os::unix::fs::symlink(&target, notes::sidecar_path(&source)).unwrap(); + assert!(notes::prepare(&source, cache, &sha).is_err()); + assert_eq!(std::fs::read_to_string(target).unwrap(), "untouched"); +} + +#[test] +fn editor_worker_saves_captured_page_and_keeps_draft_after_conflict() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("talk.pdf"); + common::pdf(&source); + let cache = temp.path().join("cache"); + let info = Document::open(&source, cache.clone()).unwrap().info; + let mut s = Studio::with_program(true, None, env!("CARGO_BIN_EXE_pdf-presenter").into()); + s.cache_path = cache; + s.deck = Some(info); + s.initialized = true; + s.requested = 1; + s.execute(Action::EditNotes); + fn finish(s: &mut Studio) { + let deadline = Instant::now() + Duration::from_secs(10); + while s.notes_editor.as_ref().unwrap().busy { + s.poll(); + assert!(Instant::now() < deadline, "notes editor stalled"); + std::thread::sleep(Duration::from_millis(2)); + } + } + finish(&mut s); + assert!(s.notes_editor.as_ref().unwrap().error.is_none()); + s.notes_editor.as_mut().unwrap().text = "Edited second slide".into(); + s.execute(Action::EditNotes); // Double-click again must not discard drafts. + assert_eq!(s.notes_editor.as_ref().unwrap().text, "Edited second slide"); + s.execute(Action::Open(source.clone())); + assert!(s.status.contains("Close the notes editor")); + s.requested = 0; // Editor remains bound to the slide captured when it opened. + s.execute(Action::SaveNotes); + finish(&mut s); + assert_eq!(s.deck.as_ref().unwrap().notes[1], "Edited second slide"); + assert_eq!(s.deck.as_ref().unwrap().notes[0], "Speaker note\n"); + let file = s + .notes_editor + .as_ref() + .unwrap() + .snapshot + .as_ref() + .unwrap() + .path + .clone(); + std::fs::write(&file, "version=1\n[notes]\n\"2\"='External'").unwrap(); + s.notes_editor.as_mut().unwrap().text = "My unsaved draft".into(); + s.execute(Action::SaveNotes); + finish(&mut s); + assert!(s.notes_editor.as_ref().unwrap().error.is_some()); + assert_eq!(s.notes_editor.as_ref().unwrap().text, "My unsaved draft"); + s.execute(Action::ReloadNotes); + finish(&mut s); + assert_eq!(s.notes_editor.as_ref().unwrap().text, "External"); +} + +#[test] +fn partial_sidecar_cannot_exceed_combined_notes_limit_with_fallback_text() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("Slides"); + std::fs::create_dir(&source).unwrap(); + let text = "x".repeat(notes::MAX_NOTE); + for page in 1..=33 { + common::image(&source.join(format!("slide{page}.png")), [0, 0, 0, 255]); + if page <= 32 { + std::fs::write(source.join(format!("slide{page}.txt")), &text).unwrap(); + } + } + let cache = temp.path().join("cache"); + let sha = Document::open(&source, cache.clone()).unwrap().info.sha256; + let sidecar = notes::sidecar_path(&source); + let empty = "version=1\n[notes]\n"; + std::fs::write(&sidecar, empty).unwrap(); + let snapshot = notes::prepare(&source, cache.clone(), &sha).unwrap(); + assert!( + notes::save( + &source, + cache.clone(), + &sha, + &snapshot.revision, + 32, + "x".into() + ) + .unwrap_err() + .contains("Combined notes") + ); + assert_eq!(std::fs::read_to_string(&sidecar).unwrap(), empty); + std::fs::write(&sidecar, "version=1\n[notes]\n\"slide33.png\"='x'").unwrap(); + assert!( + notes::prepare(&source, cache, &sha) + .unwrap_err() + .contains("Combined notes") + ); +} diff --git a/crates/pdf-presenter/tests/presenter_ui.rs b/crates/pdf-presenter/tests/presenter_ui.rs index 599a47e..6ab48f1 100644 --- a/crates/pdf-presenter/tests/presenter_ui.rs +++ b/crates/pdf-presenter/tests/presenter_ui.rs @@ -977,3 +977,93 @@ fn fullscreen_and_routing_changes_preserve_explicit_output_visibility() { } } } + +#[test] +fn double_click_notes_opens_editor_and_editor_keeps_unsaved_draft() { + fn text_pos(shapes: &[egui::epaint::ClippedShape], label: &str) -> Pos2 { + fn find(s: &egui::Shape, label: &str) -> Option { + match s { + egui::Shape::Text(t) if t.galley.text() == label => { + Some(t.pos + t.galley.size() * 0.5) + } + egui::Shape::Vec(v) => v.iter().find_map(|s| find(s, label)), + _ => None, + } + } + shapes + .iter() + .find_map(|s| find(&s.shape, label)) + .unwrap_or_else(|| panic!("missing {label}")) + } + let ctx = Context::default(); + let mut s = studio(); + s.layout.header = false; + s.layout.footer = false; + let mut native = UiState::default(); + let mut time = 0.; + let mut render = |s: &mut Studio, events| { + time += 0.04; + let mut raw = input(Vec2::new(1280., 900.)); + raw.events = events; + raw.time = Some(time); + ctx.run_ui(raw, |ui| presenter_ui::presenter(ui, s, &mut native)) + }; + let output = render(&mut s, vec![]); + let pos = text_pos(&output.shapes, "PRESENTER NOTES · AUTO-FIT") + Vec2::new(0., 60.); + for _ in 0..2 { + for pressed in [true, false] { + render( + &mut s, + vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }, + ], + ); + } + } + assert!(s.actions.iter().any(|a| matches!(a, Action::EditNotes))); + s.actions.clear(); + s.notes_editor = Some(pdf_presenter::studio::NotesEditor { + page: 0, + text: "Saved".into(), + saved_text: "Saved".into(), + busy: false, + error: None, + snapshot: Some(pdf_presenter::notes::Snapshot { + path: "demo.notes.toml".into(), + revision: "test".into(), + notes: vec!["Saved".into()], + }), + }); + for _ in 0..3 { + render(&mut s, vec![]); + } + s.notes_editor.as_mut().unwrap().text = "Unsaved notes".into(); + let output = render(&mut s, vec![]); + text_pos(&output.shapes, "Save notes"); + text_pos(&output.shapes, "Discard changes and close"); + s.execute(Action::Exit); + assert!(!s.close_requested); + assert_eq!(s.notes_editor.as_ref().unwrap().text, "Unsaved notes"); + let pos = text_pos(&output.shapes, "Save notes"); + for pressed in [true, false] { + render( + &mut s, + vec![ + egui::Event::PointerMoved(pos), + egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }, + ], + ); + } + assert!(s.actions.iter().any(|a| matches!(a, Action::SaveNotes))); +} diff --git a/docs/changelog.md b/docs/changelog.md index 9b5ee19..41cfbaf 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -2,6 +2,13 @@ ## Unreleased +### 0.1.52 + +- Load presentation-named notes sidecars before falling back to PDF/folder notes. + Double-click notes to create a full-deck sidecar if absent and edit the captured + slide in a resizable editor. Save atomically through an isolated worker, preserve + source files and other notes, detect external conflicts and retain failed drafts. + ### 0.1.51 - Preserve shown/manually blanked output through fullscreen and routing trials, diff --git a/docs/interfaces/examples/presentation.notes.toml b/docs/interfaces/examples/presentation.notes.toml new file mode 100644 index 0000000..9a41515 --- /dev/null +++ b/docs/interfaces/examples/presentation.notes.toml @@ -0,0 +1,9 @@ +version = 1 + +[notes] +"1" = "Welcome — introduce the presentation." +"2" = "" # Intentionally blank, even if the PDF contains an annotation. +"3" = """ +Explain the diagram. +Pause for questions. +""" diff --git a/docs/interfaces/picture-folders.md b/docs/interfaces/picture-folders.md index 0d4851b..24b6a33 100644 --- a/docs/interfaces/picture-folders.md +++ b/docs/interfaces/picture-folders.md @@ -13,6 +13,10 @@ case folding, then exact filename breaks ties. There is no locale collation or U normalization. Use UTF-8 filenames for portable notes keys. Missing/corrupt slides retain their position and report an error rather than renumbering the deck. +Since 0.1.52, a presentation-named sidecar beside the folder takes priority over +the sources below. See [presentation notes](presentation-notes.md) for its format +and the double-click editor. + A UTF-8 matching-stem sidecar (`slide_01.png` → `slide_01.txt`) overrides global notes, even when empty. Multiple images sharing that stem share its sidecar. Otherwise use one global notes file mapping exact image filenames to strings: diff --git a/docs/interfaces/presentation-notes.md b/docs/interfaces/presentation-notes.md new file mode 100644 index 0000000..99b8456 --- /dev/null +++ b/docs/interfaces/presentation-notes.md @@ -0,0 +1,60 @@ +# Presentation notes sidecars — version 1 + +Implemented in 0.1.52. A PDF `presentationX.pdf` uses +`presentationX.notes.toml` in the same directory. Image folder `Slides/` uses +`Slides.notes.toml` beside that folder. Paths follow the canonical source location. +Opening a presentation never creates or writes a sidecar. The PDF, image files, +legacy image `.txt` sidecars and folder-global notes are always left untouched. + +```toml +version = 1 + +[notes] +"1" = "Opening remarks" +"2" = "" # Explicitly suppress embedded notes on this page. +"3" = """ +First point +Second point +""" +``` + +PDF keys are one-based decimal page numbers. Image-folder keys are exact image +filenames, matching the natural-ordered frozen slide list (e.g. `"slide_02.png"`). +A named sidecar entry wins over PDF annotation text, or over the image folder's +existing `.txt`/global notes. Missing entries fall back to extracted notes; explicit +empty strings override them. Keys for other pages/files are ignored by display but +preserved on save. Unknown top-level fields and unsupported versions are rejected. +Malformed/unreadable sidecars produce a presenter warning and display falls back +to extracted notes; the editor refuses to overwrite the invalid file. + +Limits: 10000 entries, 256 KiB UTF-8 per note, 8 MiB combined note text, 16 MiB +serialized file. Reads and writes run in a dedicated supervised worker with a +30-second deadline, independently of rendering. Regular files only: symlink or +non-file sidecars are refused. JSON worker messages retain their 16 MiB bound; +pathological escape-heavy notes can exceed that transport bound and report an error. + +Double-clicking the notes pane opens the current slide's editor and prepares the +sidecar. If absent, all extracted/resolved notes (including empty slides) are written +using an atomically persisted temporary file with no-clobber creation. If already +present, preparation only reads it. The editor captures the slide index; subsequent +navigation does not retarget a draft. Save modifies that page's key, preserving all +other entries and showing saved text in the auto-fit pane after acknowledgement. +TOML formatting/comments are regenerated on save; text values round-trip unchanged. + +Creation and saves sync a temporary file in the sidecar directory before atomic +persistence. Saves compare the sidecar's SHA-256 with the editor revision and check +again just before replacement; detected external edits/removal fail without writing. +This is optimistic conflict detection, not a lock against an external writer racing +the final rename. Changed source SHA/slide identity is rejected; reopen the source. +Read-only directories, invalid files, conflicts and worker failures retain the draft +with explicit retry/reload/discard choices. Reload explicitly discards the draft. +A file created by opening the editor remains even if editing is canceled. + +The editor disables presentation keyboard shortcuts while open. Opening another +source is held until it closes; normal application exit is held while saving or +while a draft is dirty. Explicit Discard changes and close is available. Force-kill +or OS shutdown can still lose unsaved drafts. Editor state is transient and never +sent to presentation outputs or persisted in global/project layout settings. + +See [example](examples/presentation.notes.toml), `tests/notes.rs`, the pointer +interaction tests in `tests/presenter_ui.rs`, and the private worker protocol. diff --git a/docs/interfaces/process-protocol.md b/docs/interfaces/process-protocol.md index 157ebea..39d9980 100644 --- a/docs/interfaces/process-protocol.md +++ b/docs/interfaces/process-protocol.md @@ -112,3 +112,14 @@ including its current blank flag. Fullscreen/routing trials, confirmation, rollback and monitor topology changes preserve that flag. Missing outputs and operator privacy holds still suppress unavailable windows; no presenter content is sent to the output host. + +## Editable notes in 0.1.52 + +`PrepareNotes {path, cache, source_sha}` and +`SaveNotes {path, cache, source_sha, revision, page, text}` run through the dedicated +notes bridge. `page` is zero-based, `source_sha` identifies the loaded PDF/slide list, +and `revision` is the notes file SHA-256 observed when editing began. A successful +`Reply.notes` contains `{path, revision, notes}` with all resolved notes in slide +order. Errors use the existing error field. The presenter ignores stale-generation +completions and late background extraction after an editor snapshot has been accepted. +The current page draft survives save failure. None of this payload enters output IPC. diff --git a/docs/user-guide.md b/docs/user-guide.md index 0f7a794..aa8dc51 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -286,3 +286,25 @@ When Change on click is enabled, clicks switch the live slide and do not open pr The All slides grid fills the browser width and adapts as you resize it. Preview size sets the preferred thumbnail density; tiles share the available row width, with slides fitted without distortion. The scrollbar stays at the right edge. + +## Edit presenter notes + +A `presentationX.notes.toml` file beside `presentationX.pdf` takes priority over PDF +annotation notes. Missing page entries fall back to the PDF; an empty entry hides +its embedded notes. For an image folder, the named file sits beside the folder and +uses image filenames as keys. See the [notes format](interfaces/presentation-notes.md). + +**Double-click the notes pane** to edit that slide. If the named notes file does not +exist, PDF Presenter creates it with all notes found across the presentation before +opening the editable text. Creation and saving happen in the background. + +Choose **Save notes** to update this page and its auto-fit presenter text. Other +slides and the source PDF remain unchanged. Close keeps saved changes; +**Discard changes and close** abandons an unsaved draft. A newly created sidecar +remains in place. The editor stays bound to the slide you opened, even if slide +navigation occurs elsewhere. Finish editing before opening another presentation. + +Save errors keep your draft visible. If another program changed the notes file, +copy your draft before choosing **Reload (discard edits)**; the editor won't +silently replace a detected external edit. Notes files require a writable source +folder. They travel alongside the presentation, independently of saved layouts.