From 00d69dafed6c0a04a612893ec01dc3ac36b4e4fe Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 20 Nov 2026 07:56:33 +0100 Subject: [PATCH] Import TXT and Markdown notes into presentation sidecars --- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 42 +++++- crates/pdf-presenter/src/localization.rs | 13 ++ crates/pdf-presenter/src/native.rs | 14 +- crates/pdf-presenter/src/notes.rs | 161 +++++++++++++++++++++ crates/pdf-presenter/src/presenter_ui.rs | 61 ++++++++ crates/pdf-presenter/src/studio.rs | 129 ++++++++++++++++- crates/pdf-presenter/src/worker.rs | 47 ++++++ crates/pdf-presenter/tests/notes.rs | 157 ++++++++++++++++++++ crates/pdf-presenter/tests/presenter_ui.rs | 67 +++++++++ docs/changelog.md | 9 ++ docs/interfaces/presentation-notes.md | 43 ++++++ docs/interfaces/process-protocol.md | 13 ++ docs/user-guide.md | 9 ++ 15 files changed, 757 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2841f52..7ac2b46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2221,7 +2221,7 @@ dependencies = [ [[package]] name = "pdf-presenter" -version = "0.1.52" +version = "0.1.53" dependencies = [ "bytemuck", "chrono", diff --git a/Cargo.toml b/Cargo.toml index a72006e..cc0aa89 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ default-members = ["crates/pdf-presenter"] resolver = "3" [workspace.package] -version = "0.1.52" +version = "0.1.53" edition = "2024" license = "MIT" repository = "https://proxy.dandaedre.com/gitea/idle-org/pdf-presenter" diff --git a/README.md b/README.md index ffc8000..1b825e3 100644 --- a/README.md +++ b/README.md @@ -49,8 +49,8 @@ are not yet available. Test your display setup before using it for a live event. 4. **Present.** Use arrows or Space to advance. Type a slide number and press Enter to jump. All slides opens a thumbnail browser; B blanks or restores the output. -Opening a document shows the presentation by default. After changing displays, -use **Show presentation** to restore output. Hide the bars for more space; move the +Opening a document shows the presentation by default. Changing displays or fullscreen +preserves whether you have shown or blanked the output. Hide the bars for more space; move the pointer near an edge or right-click to recover them. Prepared slides are cached for reuse. The presenter shows loading progress, RAM use @@ -58,6 +58,44 @@ and an ETA when available; decks larger than the RAM budget use a rolling buffer Notes can come from the PDF or picture-folder sidecars. Themes and English/French controls are available in Menu. +## Import your notes + +Open your presentation, then choose **Menu → Import notes…**, or drop a `.txt` or +`.md` file onto the presenter window. Review the import and choose **Import and save +notes**. This creates or updates `presentation.notes.toml` beside `presentation.pdf` +(or `Slides.notes.toml` beside a picture folder named `Slides`). Your original notes +file and slides stay untouched. Double-click the notes pane to edit a slide later. + +**TXT:** separate slides with a line containing two or more hyphens: + +```text +Welcome everyone. +------- +Explain the results. +------- +Thank the audience. +``` + +**Markdown:** start each slide with a top-level `#` title. Titles are separators; +only their body becomes the slide's notes: + +```markdown +# Introduction +Welcome everyone. +# Results +Explain the results. +# Conclusion +Thank the audience. +``` + +Sections map to slides **in order, starting at slide 1**; titles do not select slide +numbers. Fewer sections preserve the remaining slides' notes; too many sections +reject the import without writing. Empty sections clear a slide's notes. TXT files +need no final separator (a final separator creates an empty section). Use UTF-8. +Markdown `##` subheadings and headings inside fenced code stay in the note; +nonblank text before the first `#` title is rejected. Notes display as plain text. +[Format details and limits →](docs/interfaces/presentation-notes.md#importing-txt-and-markdown) + [**Read the user guide →**](docs/user-guide.md) --- diff --git a/crates/pdf-presenter/src/localization.rs b/crates/pdf-presenter/src/localization.rs index f2d8e71..2dd4043 100644 --- a/crates/pdf-presenter/src/localization.rs +++ b/crates/pdf-presenter/src/localization.rs @@ -39,6 +39,19 @@ pub fn tr<'a>(ctx: &egui::Context, text: &'a str) -> &'a str { return text; } match text { + "Cancel" => "Annuler", + "Preview (first 3 slides)" => "Aperçu (3 premières diapositives)", + "Import notes…" => "Importer des notes…", + "Import notes" => "Importer des notes", + "Processing notes…" => "Traitement des notes…", + "Slides to update" => "Diapositives à modifier", + "Sections replace notes starting at slide 1. Remaining slides keep their notes." => { + "Les sections remplacent les notes à partir de la diapositive 1. Les suivantes conservent leurs notes." + } + "Update existing notes file" => "Mettre à jour le fichier de notes existant", + "Create notes file" => "Créer le fichier de notes", + "Empty note" => "Note vide", + "Import and save notes" => "Importer et enregistrer les notes", "File chooser already open" => "Sélecteur de fichiers déjà ouvert", "Page background" => "Fond de page", "Fit padding color" => "Couleur des marges", diff --git a/crates/pdf-presenter/src/native.rs b/crates/pdf-presenter/src/native.rs index b74cf1c..3c4feeb 100644 --- a/crates/pdf-presenter/src/native.rs +++ b/crates/pdf-presenter/src/native.rs @@ -599,7 +599,7 @@ impl App { } // 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() { + if role == Role::Presenter && (s.notes_editor.is_some() || s.notes_import.is_some()) { return; } if modifiers.ctrl || modifiers.alt || modifiers.command || consumed { @@ -671,7 +671,7 @@ impl App { repaint |= !actions.is_empty(); for action in actions { #[cfg(target_os = "windows")] - if matches!(action, Action::Pick(_)) && !s.dialog_busy { + if matches!(action, Action::Pick(_) | Action::PickNotes) && !s.dialog_busy { use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle}; s.dialog_owner = self .windows @@ -1016,8 +1016,14 @@ impl ApplicationHandler for App { } } WindowEvent::DroppedFile(path) => { - if let Some(s) = &mut self.studio { - s.execute(Action::Open(path)); + if role == Role::Presenter + && let Some(s) = &mut self.studio + { + s.execute(if crate::notes::is_import(&path) { + Action::ImportNotes(path) + } else { + Action::Open(path) + }); } } WindowEvent::KeyboardInput { event, .. } diff --git a/crates/pdf-presenter/src/notes.rs b/crates/pdf-presenter/src/notes.rs index cb1efe6..6532254 100644 --- a/crates/pdf-presenter/src/notes.rs +++ b/crates/pdf-presenter/src/notes.rs @@ -194,3 +194,164 @@ pub fn save( notes: info.notes, }) } + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ImportPreview { + pub path: PathBuf, + pub revision: Option, + pub sections: Vec, + pub total: usize, +} +/// Recognize imports without filesystem access on the input thread. +pub fn is_import(path: &Path) -> bool { + path.extension() + .and_then(|s| s.to_str()) + .is_some_and(|s| s.eq_ignore_ascii_case("txt") || s.eq_ignore_ascii_case("md")) +} +/// Plain UTF-8 notes; Markdown headings delimit slides, not rendered formatting. +pub fn parse_import(text: &str, markdown: bool) -> Result, String> { + if text.len() > MAX_TEXT { + return Err("Imported notes exceed 8 MiB".into()); + } + let text = text + .strip_prefix('\u{feff}') + .unwrap_or(text) + .replace("\r\n", "\n"); + let mut sections = Vec::new(); + let mut lines = Vec::new(); + let mut heading_seen = false; + let mut fence: Option<(u8, usize)> = None; + for line in text.lines() { + let trimmed = line.trim(); + let mut heading = false; + if markdown { + let start = line.trim_start_matches(' '); + let indent = line.len() - start.len(); + let marker = start.as_bytes().first().copied(); + let run = start.bytes().take_while(|b| Some(*b) == marker).count(); + if let Some((ch, len)) = fence { + if indent <= 3 && marker == Some(ch) && run >= len && start[run..].trim().is_empty() + { + fence = None; + } + } else if indent <= 3 && matches!(marker, Some(b'`' | b'~')) && run >= 3 { + fence = Some((marker.unwrap(), run)); + } else if indent <= 3 { + heading = start == "#" + || start + .strip_prefix('#') + .is_some_and(|tail| tail.starts_with([' ', '\t'])); + } + } + let separator = !markdown && trimmed.len() >= 2 && trimmed.bytes().all(|b| b == b'-'); + if heading || separator { + if markdown && !heading_seen { + if lines.iter().any(|line: &&str| !line.trim().is_empty()) { + return Err( + "Markdown notes must begin with a # slide title (blank lines are allowed)." + .into(), + ); + } + heading_seen = true; + } else { + sections.push(lines.join("\n").trim_matches('\n').to_owned()); + } + lines.clear(); + } else { + lines.push(line); + } + if sections.len() >= 10000 { + return Err("Imported notes exceed 10000 slides".into()); + } + } + if markdown && !heading_seen { + return Err("Markdown notes need # slide titles.".into()); + } + sections.push(lines.join("\n").trim_matches('\n').to_owned()); + if sections.iter().any(|s| s.len() > MAX_NOTE) { + return Err("An imported note exceeds 256 KiB".into()); + } + Ok(sections) +} +pub fn preview_import( + source: &Path, + cache: PathBuf, + source_sha: &str, + import: &Path, +) -> Result { + if !is_import(import) { + return Err("Choose a .txt or .md notes file.".into()); + } + let input = read_limited(import, MAX_TEXT as u64)?; + let text = std::str::from_utf8(&input).map_err(|_| "Notes imports must be UTF-8 text.")?; + let markdown = import + .extension() + .is_some_and(|e| e.eq_ignore_ascii_case("md")); + let sections = parse_import(text, markdown)?; + let (info, existing) = document(source, cache, source_sha)?; + if sections.len() > info.notes.len() { + return Err(format!( + "{} note sections, but only {} slides. Nothing was changed.", + sections.len(), + info.notes.len() + )); + } + Ok(ImportPreview { + path: sidecar_path(&info.path), + revision: existing.map(|(_, b)| revision(&b)), + sections, + total: info.notes.len(), + }) +} +pub fn apply_import( + source: &Path, + cache: PathBuf, + source_sha: &str, + preview: ImportPreview, +) -> Result { + let (mut info, existing) = document(source, cache, source_sha)?; + let path = sidecar_path(&info.path); + if path != preview.path + || info.notes.len() != preview.total + || preview.sections.len() > info.notes.len() + { + return Err("Presentation changed. Import the notes again.".into()); + } + let previous = existing.as_ref().map(|(_, b)| b); + if previous.map(|b| revision(b)) != preview.revision { + return Err("Notes changed on disk. Import again to review the latest notes.".into()); + } + for (note, imported) in info.notes.iter_mut().zip(preview.sections) { + *note = imported; + } + if info.notes.iter().map(String::len).sum::() > MAX_TEXT { + return Err("Combined notes exceed 8 MiB; nothing was saved.".into()); + } + let mut file = NotesFile { + version: 1, + notes: BTreeMap::new(), + }; + if let Some((existing, _)) = &existing { + file.notes.clone_from(&existing.notes); + } + file.notes.extend( + keys(&info.path, &info.names) + .into_iter() + .zip(info.notes.iter().cloned()), + ); + let bytes = bytes(&file)?; + let temp = temporary(&path, &bytes)?; + if read(&path)?.as_ref().map(|(_, b)| b) != previous { + return Err("Notes changed while importing; nothing was saved.".into()); + } + if previous.is_some() { + temp.persist(&path).map_err(|e| e.to_string())?; + } else { + temp.persist_noclobber(&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 738f48e..1521430 100644 --- a/crates/pdf-presenter/src/presenter_ui.rs +++ b/crates/pdf-presenter/src/presenter_ui.rs @@ -1290,8 +1290,54 @@ pub fn presenter(ui: &mut Ui, s: &mut Studio, native: &mut UiState) { }); s.displays_open &= open; } + notes_import_ui(&ctx, s); notes_editor_ui(&ctx, s); } +fn notes_import_ui(ctx: &Context, s: &mut Studio) { + let Some(import) = &s.notes_import else { + return; + }; + let mut apply = false; + let mut close = false; + egui::Window::new(tr(ctx, "Import notes")) + .id(egui::Id::new("notes-import")) + .collapsible(false).resizable(true) + .default_size(Vec2::new(560., 360.).min(ctx.content_rect().size() - Vec2::splat(48.))) + .max_size(ctx.content_rect().size() - Vec2::splat(32.)) + .show(ctx, |ui| { + if import.busy { + ui.horizontal(|ui| { ui.spinner(); ui.label(tr(ctx, "Processing notes…")); }); + } + egui::ScrollArea::vertical().max_height((ui.available_height() - 45.).max(60.)).show(ui, |ui| { + if let Some(preview) = &import.preview { + ui.label(format!("{}: {} / {}", tr(ctx, "Slides to update"), preview.sections.len(), preview.total)); + ui.label(tr(ctx, "Sections replace notes starting at slide 1. Remaining slides keep their notes.")); + ui.label(tr(ctx, if preview.revision.is_some() { "Update existing notes file" } else { "Create notes file" })); + ui.label(preview.path.display().to_string()); + ui.separator(); + ui.strong(tr(ctx, "Preview (first 3 slides)")); + for (index, note) in preview.sections.iter().enumerate().take(3) { + ui.strong(format!("{} {}", tr(ctx, "Slide"), index + 1)); + let mut excerpt: String = note.chars().take(500).collect(); + if excerpt.len() < note.len() { excerpt.push('…'); } + ui.label(if note.is_empty() { tr(ctx, "Empty note") } else { &excerpt }); + } + } + if let Some(error) = &import.error { ui.colored_label(ui.visuals().error_fg_color, error); } + }); + ui.separator(); + ui.horizontal(|ui| { + apply = ui.add_enabled(!import.busy && import.preview.is_some() && import.error.is_none(), egui::Button::new(tr(ctx, "Import and save notes"))).clicked(); + close = ui.add_enabled(!import.busy, egui::Button::new(tr(ctx, "Cancel"))).clicked(); + }); + }); + if apply { + s.actions.push(Action::ApplyNotesImport); + } + if close { + s.notes_import = None; + } +} fn notes_editor_ui(ctx: &Context, s: &mut Studio) { let Some(editor) = &mut s.notes_editor else { return; @@ -1720,6 +1766,21 @@ fn menu(ui: &mut Ui, s: &mut Studio) { if s.dialog_busy { ui.label(tr(&locale, "File chooser already open")); } + ui.add_enabled_ui( + !s.dialog_busy + && !s.loading + && s.deck.is_some() + && s.notes_editor.is_none() + && s.notes_import.is_none(), + |ui| { + button( + ui, + tr(&locale, "Import notes…"), + Action::PickNotes, + &mut s.actions, + ); + }, + ); ui.separator(); button( ui, diff --git a/crates/pdf-presenter/src/studio.rs b/crates/pdf-presenter/src/studio.rs index f75c9fd..ecd7f65 100644 --- a/crates/pdf-presenter/src/studio.rs +++ b/crates/pdf-presenter/src/studio.rs @@ -21,6 +21,9 @@ pub struct Monitor { pub enum Action { Open(PathBuf), Pick(bool), + PickNotes, + ImportNotes(PathBuf), + ApplyNotesImport, Go(usize), Blank, SaveProject, @@ -41,6 +44,11 @@ pub enum Action { ReloadNotes, SaveNotes, } +pub struct NotesImport { + pub preview: Option, + pub busy: bool, + pub error: Option, +} pub struct NotesEditor { pub page: usize, pub text: String, @@ -84,6 +92,7 @@ pub struct Studio { pub evicted_frames: usize, pub loading: bool, pub notes_loading: bool, + pub notes_import: Option, pub notes_editor: Option, notes_io: Bridge, notes_edited: bool, @@ -180,6 +189,7 @@ impl Studio { evicted_frames: 0, loading: false, notes_loading: false, + notes_import: None, notes_editor: None, notes_io: Bridge::with_program(Duration::from_secs(30), worker_program.clone()), notes_edited: false, @@ -299,9 +309,9 @@ impl Studio { pub fn execute(&mut self, action: Action) { match action { Action::Open(path) => { - if self.notes_editor.is_some() { + if self.notes_editor.is_some() || self.notes_import.is_some() || self.dialog_busy { self.status = - "Close the notes editor before opening another presentation.".into(); + "Close the notes editor/import or file chooser before opening another presentation.".into(); return; } if self.fg_busy { @@ -314,6 +324,75 @@ impl Studio { self.pending_open = Some(path); self.status = "Opening document in an isolated worker…".into(); } + Action::PickNotes => { + if !self.dialog_busy + && !self.loading + && self.deck.is_some() + && self.notes_editor.is_none() + && self.notes_import.is_none() + { + self.dialog_busy = self.dialog.submit( + self.generation, + 1, + Request::PickNotes { + owner: self.dialog_owner, + }, + ); + self.status = "Choose a TXT or Markdown notes file.".into(); + } + } + Action::ImportNotes(import) => { + if self.loading + || self.notes_editor.is_some() + || self.notes_import.is_some() + || self.dialog_busy + { + self.status = "Close the notes editor/import or file chooser and wait for the presentation to load.".into(); + return; + } + let Some(deck) = &self.deck else { + self.status = "Open a presentation before importing notes.".into(); + return; + }; + if self.notes_io.submit( + self.generation, + 2, + Request::PreviewNotesImport { + path: deck.path.clone(), + cache: self.cache_path.clone(), + source_sha: deck.sha256.clone(), + import, + }, + ) { + self.notes_import = Some(NotesImport { + preview: None, + busy: true, + error: None, + }); + self.jump.clear(); + self.status = "Reading notes for import…".into(); + } + } + Action::ApplyNotesImport => { + if let (Some(deck), Some(import)) = (&self.deck, &mut self.notes_import) + && !import.busy + && import.error.is_none() + && let Some(preview) = &import.preview + && self.notes_io.submit( + self.generation, + 3, + Request::ApplyNotesImport { + path: deck.path.clone(), + cache: self.cache_path.clone(), + source_sha: deck.sha256.clone(), + preview: preview.clone(), + }, + ) + { + import.busy = true; + self.status = "Saving imported notes…".into(); + } + } Action::Pick(folder) => { if !self.dialog_busy { self.dialog_busy = self.dialog.submit( @@ -462,6 +541,10 @@ impl Studio { } Action::Refresh => self.dirty_routes = true, Action::Exit => { + if self.notes_import.as_ref().is_some_and(|i| i.busy) { + self.status = "Wait for notes import to finish before closing.".into(); + return; + } if self .notes_editor .as_ref() @@ -476,7 +559,11 @@ impl Studio { 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) { + if self.loading + || self.notes_import.is_some() + || self.dialog_busy + || self.notes_editor.as_ref().is_some_and(|e| e.busy) + { return; } if let Some(deck) = &self.deck { @@ -588,6 +675,34 @@ impl Studio { if completion.generation != self.generation { continue; } + if completion.tag >= 2 { + if let Some(import) = &mut self.notes_import { + import.busy = false; + match completion.result { + Ok(packet) => { + import.error = packet.reply.error; + if let Some(preview) = packet.reply.notes_import { + import.preview = Some(preview); + self.status = "Review the notes import before saving.".into(); + } + if let Some(snapshot) = packet.reply.notes { + if let Some(deck) = &mut self.deck { + deck.notes = snapshot.notes; + } + self.notes_edited = true; + self.status = + format!("Notes imported: {}", snapshot.path.display()); + self.notes_import = None; + } + } + Err(error) => import.error = Some(error), + } + if let Some(error) = self.notes_import.as_ref().and_then(|i| i.error.as_ref()) { + self.status = format!("Notes import: {error}"); + } + } + continue; + } if let Some(editor) = &mut self.notes_editor { editor.busy = false; match completion.result { @@ -668,7 +783,13 @@ impl Studio { match c.result { Ok(p) => { if let Some(path) = p.reply.picked { - self.execute(Action::Open(path)); + if c.tag == 1 { + if c.generation == self.generation { + self.execute(Action::ImportNotes(path)); + } + } else { + self.execute(Action::Open(path)); + } } if let Some(e) = p.reply.error { self.status = e; diff --git a/crates/pdf-presenter/src/worker.rs b/crates/pdf-presenter/src/worker.rs index 001dde5..4e91bd3 100644 --- a/crates/pdf-presenter/src/worker.rs +++ b/crates/pdf-presenter/src/worker.rs @@ -34,6 +34,21 @@ pub enum Request { path: PathBuf, cache: PathBuf, }, + PreviewNotesImport { + path: PathBuf, + cache: PathBuf, + source_sha: String, + import: PathBuf, + }, + ApplyNotesImport { + path: PathBuf, + cache: PathBuf, + source_sha: String, + preview: crate::notes::ImportPreview, + }, + PickNotes { + owner: Option, + }, PrepareNotes { path: PathBuf, cache: PathBuf, @@ -74,6 +89,7 @@ pub struct Reply { pub frame: Option, pub settings: Option, pub notes: Option, + pub notes_import: Option, pub picked: Option, pub bytes: usize, pub edge: Option, @@ -203,6 +219,37 @@ pub fn run() -> Result<(), String> { Request::Notes { path, cache } => { reply.info = Some(document::Document::open(&path, cache)?.info); } + Request::PreviewNotesImport { + path, + cache, + source_sha, + import, + } => { + reply.notes_import = Some(crate::notes::preview_import( + &path, + cache, + &source_sha, + &import, + )?); + } + Request::ApplyNotesImport { + path, + cache, + source_sha, + preview, + } => { + reply.notes = Some(crate::notes::apply_import( + &path, + cache, + &source_sha, + preview, + )?); + } + Request::PickNotes { owner } => { + reply.picked = picker_dialog(owner)? + .add_filter("Notes (TXT, Markdown)", &["txt", "md"]) + .pick_file(); + } Request::PrepareNotes { path, cache, diff --git a/crates/pdf-presenter/tests/notes.rs b/crates/pdf-presenter/tests/notes.rs index 96ce610..e0cb696 100644 --- a/crates/pdf-presenter/tests/notes.rs +++ b/crates/pdf-presenter/tests/notes.rs @@ -279,3 +279,160 @@ fn partial_sidecar_cannot_exceed_combined_notes_limit_with_fallback_text() { .contains("Combined notes") ); } + +#[test] +fn text_and_markdown_import_sections_and_limits() { + assert_eq!( + notes::parse_import("\u{feff}First\r\n ------- \r\nSecond\n--\n--\n", false).unwrap(), + vec!["First", "Second", "", ""] + ); + assert_eq!( + notes::parse_import("one\n-\ninline -- text", false).unwrap(), + vec!["one\n-\ninline -- text"] + ); + assert_eq!(notes::parse_import("\n# Opening\nHello é漢字\n\n## Keep this heading\n```md\n# Not a slide\n```\n# Next\n~~~\n# Also code\n~~~\n# Empty\n", true).unwrap(), vec!["Hello é漢字\n\n## Keep this heading\n```md\n# Not a slide\n```", "~~~\n# Also code\n~~~", ""]); + assert!(notes::parse_import("No headings", true).is_err()); + assert!(notes::parse_import("Lost preamble\n# Title\nNote", true).is_err()); + assert!(notes::parse_import(&"x".repeat(notes::MAX_NOTE + 1), false).is_err()); + assert!(notes::parse_import(&"x".repeat(8 * 1024 * 1024 + 1), false).is_err()); + assert!(notes::parse_import(&"--\n".repeat(10000), false).is_err()); + assert!(notes::is_import(std::path::Path::new("NOTES.MD"))); + assert!(!notes::is_import(std::path::Path::new("talk.pdf"))); +} + +#[test] +fn import_preview_is_read_only_and_apply_preserves_remaining_and_unknown_notes() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("talk.pdf"); + common::pdf(&source); + let original = std::fs::read(&source).unwrap(); + let cache = temp.path().join("cache"); + let sha = Document::open(&source, cache.clone()).unwrap().info.sha256; + let input = temp.path().join("speaker.TXT"); + std::fs::write(&input, "Imported é\n-------\nSecond").unwrap(); + let preview = notes::preview_import(&source, cache.clone(), &sha, &input).unwrap(); + assert!(!preview.path.exists()); + let result = notes::apply_import(&source, cache.clone(), &sha, preview).unwrap(); + assert_eq!(result.notes, vec!["Imported é", "Second"]); + std::fs::write( + &result.path, + "version=1\n[notes]\n'1'='Old'\n'2'='Keep'\n'99'='Unknown'", + ) + .unwrap(); + std::fs::write(&input, "First only").unwrap(); + let preview = notes::preview_import(&source, cache.clone(), &sha, &input).unwrap(); + let saved = notes::apply_import(&source, cache.clone(), &sha, preview).unwrap(); + assert_eq!(saved.notes, vec!["First only", "Keep"]); + assert!( + std::fs::read_to_string(&result.path) + .unwrap() + .contains("Unknown") + ); + assert_eq!( + Document::open(&source, cache).unwrap().info.notes, + saved.notes + ); + assert_eq!(std::fs::read(source).unwrap(), original); + assert_eq!(std::fs::read_to_string(input).unwrap(), "First only"); +} + +#[test] +fn import_errors_and_conflicts_leave_files_untouched() { + 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 input = temp.path().join("notes.md"); + std::fs::write(&input, "# One\nFirst\n# Two\nSecond\n# Three\nExtra").unwrap(); + assert!(notes::preview_import(&source, cache.clone(), &sha, &input).is_err()); + assert!(!notes::sidecar_path(&source).exists()); + std::fs::write(&input, [0xff, 0xfe]).unwrap(); + assert!(notes::preview_import(&source, cache.clone(), &sha, &input).is_err()); + std::fs::write(&input, "# One\nFirst").unwrap(); + let preview = notes::preview_import(&source, cache.clone(), &sha, &input).unwrap(); + let external = "version=1\n[notes]\n'1'='External'"; + std::fs::write(&preview.path, external).unwrap(); + assert!(notes::apply_import(&source, cache.clone(), &sha, preview).is_err()); + let preview = notes::preview_import(&source, cache.clone(), &sha, &input).unwrap(); + std::fs::remove_file(&preview.path).unwrap(); + assert!(notes::apply_import(&source, cache.clone(), &sha, preview).is_err()); + assert!(!notes::sidecar_path(&source).exists()); + std::fs::write(notes::sidecar_path(&source), "invalid TOML").unwrap(); + assert!(notes::preview_import(&source, cache, &sha, &input).is_err()); + assert_eq!( + std::fs::read_to_string(notes::sidecar_path(&source)).unwrap(), + "invalid TOML" + ); +} + +#[test] +fn folder_import_uses_natural_slide_order() { + let temp = tempfile::tempdir().unwrap(); + let source = temp.path().join("Slides"); + std::fs::create_dir(&source).unwrap(); + common::image(&source.join("slide10.png"), [0, 0, 0, 255]); + common::image(&source.join("slide2.png"), [0, 0, 0, 255]); + let cache = temp.path().join("cache"); + let sha = Document::open(&source, cache.clone()).unwrap().info.sha256; + let input = temp.path().join("notes.md"); + std::fs::write(&input, "# Title is not a filename\nFirst\n# Slide\nSecond").unwrap(); + let preview = notes::preview_import(&source, cache.clone(), &sha, &input).unwrap(); + let saved = notes::apply_import(&source, cache, &sha, preview).unwrap(); + let file: toml::Value = toml::from_str(&std::fs::read_to_string(saved.path).unwrap()).unwrap(); + assert_eq!(file["notes"]["slide2.png"].as_str(), Some("First")); + assert_eq!(file["notes"]["slide10.png"].as_str(), Some("Second")); +} + +#[test] +fn worker_import_review_save_and_failure_keep_presentation_running() { + 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 input = temp.path().join("notes.txt"); + std::fs::write(&input, "Imported").unwrap(); + let mut s = Studio::with_program(true, None, env!("CARGO_BIN_EXE_pdf-presenter").into()); + s.cache_path = cache; + s.initialized = true; + s.execute(Action::ImportNotes(input.clone())); + assert!(s.status.contains("Open a presentation")); + s.deck = Some(info); + s.blanked = false; + s.execute(Action::ImportNotes(input.clone())); + s.execute(Action::Exit); + assert!(!s.close_requested); + s.execute(Action::EditNotes); + assert!(s.notes_editor.is_none()); + fn finish(s: &mut Studio) { + let deadline = Instant::now() + Duration::from_secs(10); + while s.notes_import.as_ref().is_some_and(|i| i.busy) { + s.poll(); + assert!(Instant::now() < deadline, "notes import stalled"); + std::thread::sleep(Duration::from_millis(2)); + } + } + finish(&mut s); + assert!(s.notes_import.as_ref().unwrap().error.is_none()); + assert!(!notes::sidecar_path(&source).exists()); + s.execute(Action::Open(source.clone())); + assert!(!s.loading); + s.execute(Action::ApplyNotesImport); + finish(&mut s); + assert!(s.notes_import.is_none()); + assert_eq!(s.deck.as_ref().unwrap().notes[0], "Imported"); + assert!(!s.blanked); + s.execute(Action::ImportNotes(input)); + finish(&mut s); + std::fs::write( + notes::sidecar_path(&source), + "version=1\n[notes]\n'1'='External'", + ) + .unwrap(); + s.execute(Action::ApplyNotesImport); + finish(&mut s); + assert!(s.notes_import.as_ref().unwrap().error.is_some()); + assert_eq!(s.deck.as_ref().unwrap().notes[0], "Imported"); + assert!(!s.blanked); +} diff --git a/crates/pdf-presenter/tests/presenter_ui.rs b/crates/pdf-presenter/tests/presenter_ui.rs index 6ab48f1..68e5a3f 100644 --- a/crates/pdf-presenter/tests/presenter_ui.rs +++ b/crates/pdf-presenter/tests/presenter_ui.rs @@ -1067,3 +1067,70 @@ fn double_click_notes_opens_editor_and_editor_keeps_unsaved_draft() { } assert!(s.actions.iter().any(|a| matches!(a, Action::SaveNotes))); } + +#[test] +fn notes_import_review_requires_explicit_save_and_cancel_discards_preview() { + fn label_pos(shape: &egui::Shape, label: &str) -> Option { + match shape { + egui::Shape::Text(t) if t.galley.text() == label => Some(t.pos + t.galley.size() * 0.5), + egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| label_pos(s, label)), + _ => None, + } + } + for (button, apply) in [("Import and save notes", true), ("Cancel", false)] { + let ctx = Context::default(); + let mut s = studio(); + let original = s.deck.as_ref().unwrap().notes.clone(); + s.notes_import = Some(pdf_presenter::studio::NotesImport { + busy: false, + error: None, + preview: Some(pdf_presenter::notes::ImportPreview { + path: "demo.notes.toml".into(), + revision: Some("revision".into()), + sections: vec!["New first note".into(), "".into()], + total: 30, + }), + }); + let mut state = UiState::default(); + let mut time = 0.; + let mut render = |s: &mut Studio, events| { + time += 0.04; + let mut raw = input(Vec2::new(900., 700.)); + raw.time = Some(time); + raw.events = events; + ctx.run_ui(raw, |ui| presenter_ui::presenter(ui, s, &mut state)) + }; + for _ in 0..3 { + render(&mut s, vec![]); + } + let output = render(&mut s, vec![]); + let pos = output + .shapes + .iter() + .find_map(|s| label_pos(&s.shape, button)) + .unwrap(); + assert_eq!(s.deck.as_ref().unwrap().notes, original); + 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_eq!( + s.actions + .iter() + .any(|a| matches!(a, Action::ApplyNotesImport)), + apply + ); + assert_eq!(s.notes_import.is_some(), apply); + assert_eq!(s.deck.as_ref().unwrap().notes, original); + } +} diff --git a/docs/changelog.md b/docs/changelog.md index 41cfbaf..8380f49 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -2,6 +2,15 @@ ## Unreleased +### 0.1.53 + +- Import UTF-8 TXT notes separated by hyphen lines or Markdown notes separated by + level-one headings, via Menu or presenter drag-and-drop. Review before converting + to a complete presentation notes sidecar; preserve remaining notes/source files, + detect external conflicts and keep processing off the presentation thread. + Document examples and mapping in the README. Linux regression coverage includes + parsers, worker flow, natural ordering, atomic saves and conflict handling. + ### 0.1.52 - Load presentation-named notes sidecars before falling back to PDF/folder notes. diff --git a/docs/interfaces/presentation-notes.md b/docs/interfaces/presentation-notes.md index 99b8456..3de6931 100644 --- a/docs/interfaces/presentation-notes.md +++ b/docs/interfaces/presentation-notes.md @@ -58,3 +58,46 @@ 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. + + +## Importing TXT and Markdown + +Implemented in 0.1.53, with no change to the version-1 TOML representation. A loaded +presentation accepts `.txt` and `.md` files (case-insensitive extensions) through +Menu → Import notes or drag-and-drop onto the presenter. Import review is read-only; +only **Import and save notes** writes the named sidecar. Cancel writes nothing. + +- Input is UTF-8, up to 8 MiB; an initial BOM is removed and CRLF becomes LF. +- TXT splits at a line whose trimmed content is only two or more ASCII hyphens. + Consecutive separators preserve empty sections, as do leading/trailing separators. + No separators means one slide's notes. A trailing newline is not a separator. +- Markdown splits at ATX level-one headings (`#` followed by space/tab, or `#` + alone), with up to three leading spaces. The title is omitted. Level-two and + deeper headings remain literal text. Backtick/tilde fences of at least three + markers protect headings inside them; closing fences use the same marker and + at least the opening length. A document without a heading, or with nonblank + preamble before the first heading, is rejected. Setext headings are unsupported. +- Blank newline characters at the beginning/end of each section are removed; + internal newlines, indentation and Markdown body text are retained, displayed + literally. This is section parsing, not Markdown rendering. +- Sections replace slides sequentially from slide 1, using natural filename order + for folders. Titles never match filenames or page numbers. Empty sections clear + notes. Missing trailing sections retain current sidecar/extracted notes. Excess + sections fail without writing. Limits remain 10000 sections and 256 KiB per note. +- Saving materializes all slides' effective notes and preserves unknown existing + page keys. Combined notes and serialized-file limits still apply. Existing TOML + comments/formatting are regenerated. The source notes import is never modified. + +Preview holds parsed sections in memory, the destination, slide count and optional +existing-sidecar SHA. Apply revalidates the source identity and sidecar revision; +external creation, edits or deletion since review cause a conflict. Atomic replace +and no-clobber creation use the same guarantees/limitations as the editor above. +Malformed existing sidecars are never overwritten. Errors appear in the import +window; cancel and import again after resolving the cause. The first three sections +are excerpted in the review; all sections are validated before writing. + +Parsing, extraction and writes run in the supervised notes worker, never on the +input/render thread. Presentation navigation and output continue independently. +Keyboard presentation shortcuts are suspended while the import window is open. +Opening another presentation/editing notes is held until the import closes; normal +exit is held during an active import job. No notes payload reaches output windows. diff --git a/docs/interfaces/process-protocol.md b/docs/interfaces/process-protocol.md index 39d9980..bd3da78 100644 --- a/docs/interfaces/process-protocol.md +++ b/docs/interfaces/process-protocol.md @@ -123,3 +123,16 @@ and `revision` is the notes file SHA-256 observed when editing began. A successf 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. + + +## Notes import in 0.1.53 + +`PickNotes {owner}` uses the existing owned, supervised file chooser with TXT/MD +filters. `PreviewNotesImport {path, cache, source_sha, import}` returns +`Reply.notes_import {path, revision, sections, total}`: destination sidecar path, +optional existing-file SHA, parsed strings and total slide count. It writes nothing. +`ApplyNotesImport {path, cache, source_sha, preview}` revalidates identity/revision, +merges notes and writes atomically, returning the existing `Reply.notes` snapshot. +Both notes jobs use the dedicated 30-second bridge, bounded JSON messages and source +generations. Notes picker results carry the source generation too. These messages +are private same-executable presenter/worker traffic, never output-host traffic. diff --git a/docs/user-guide.md b/docs/user-guide.md index aa8dc51..71137d8 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -308,3 +308,12 @@ 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. + + +### Import notes from text or Markdown + +With a presentation open, choose **Menu → Import notes…** or drop a `.txt`/`.md` +file onto the presenter. Review the destination and slide count, then choose +**Import and save notes** to create/update the presentation's `.notes.toml` file. +Cancel leaves files unchanged. See the [README examples](../README.md#import-your-notes) +and [format contract](interfaces/presentation-notes.md#importing-txt-and-markdown).