From ccc990723ab16b1213ad26bebec274626a30e5ec Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 3 Nov 2026 13:58:08 +0100 Subject: [PATCH] Add table-based rundown resolution and saved profiles --- Cargo.lock | 1 + crates/rundown-converter/Cargo.toml | 1 + crates/rundown-converter/src/detect.rs | 23 +- crates/rundown-converter/src/gui.rs | 606 ++++++++++++++++----- crates/rundown-converter/src/lib.rs | 1 + crates/rundown-converter/src/resolution.rs | 81 +++ docs/rundown-converter-plan.md | 6 +- docs/rundown-converter.md | 46 +- 8 files changed, 620 insertions(+), 145 deletions(-) create mode 100644 crates/rundown-converter/src/resolution.rs diff --git a/Cargo.lock b/Cargo.lock index e1e974f..0eae280 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3544,6 +3544,7 @@ dependencies = [ "anyhow", "clap", "csv", + "directories", "eframe", "open", "rfd", diff --git a/crates/rundown-converter/Cargo.toml b/crates/rundown-converter/Cargo.toml index 1d3ba3d..ab9bd7b 100644 --- a/crates/rundown-converter/Cargo.toml +++ b/crates/rundown-converter/Cargo.toml @@ -12,6 +12,7 @@ desktop = ["dep:eframe", "dep:rfd", "dep:open"] [dependencies] anyhow = "1" +directories = "6" clap = { version = "4", features = ["derive"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/crates/rundown-converter/src/detect.rs b/crates/rundown-converter/src/detect.rs index 87a1354..391495e 100644 --- a/crates/rundown-converter/src/detect.rs +++ b/crates/rundown-converter/src/detect.rs @@ -99,6 +99,24 @@ pub fn active_rows(table: &Table, header: usize, profile: &Profile) -> Vec Result> { + inspect(table, profile).0 +} + +/// Retain inference evidence even when a later ambiguity blocks the mapping. +pub fn inspect( + table: &Table, + profile: &Profile, +) -> (Result>, Vec) { + let mut evidence = Vec::new(); + let result = infer_inner(table, profile, &mut evidence); + (result, evidence) +} + +fn infer_inner( + table: &Table, + profile: &Profile, + evidence: &mut Vec, +) -> Result> { let header = if let Some(r) = profile.header_row { if r == 0 || r > table.rows.len() { return Err(vec![Diagnostic::new( @@ -136,6 +154,7 @@ pub fn infer(table: &Table, profile: &Profile) -> Result Result Result), - Analyzed(Box), + Analyzed(Box, Table), Exported(PathBuf), Failed(String), } @@ -47,6 +47,9 @@ struct App { neutral: bool, completed: Option, settings: bool, + profile_path: Option, + replace_profile: bool, + resolution_dir: Option, } impl Default for App { fn default() -> Self { @@ -68,6 +71,9 @@ impl Default for App { neutral: false, completed: None, settings: false, + profile_path: None, + replace_profile: false, + resolution_dir: resolution::directory(), } } } @@ -80,6 +86,8 @@ impl App { fn set_input(&mut self, path: PathBuf) { self.input = path.to_string_lossy().into(); self.output = path.with_extension("ontime.json").to_string_lossy().into(); + self.profile = "{}".into(); + self.profile_path = None; self.sheet.clear(); self.sheets.clear(); self.tables.clear(); @@ -118,18 +126,21 @@ impl App { let tx = self.begin(); let cancel = self.cancel.clone(); std::thread::spawn(move || { - let result = (|| -> anyhow::Result { + let result = (|| -> anyhow::Result<(Analysis, Table)> { let tables = reader::read(&path)?; let table = tables .iter() .find(|t| t.name == sheet) .ok_or_else(|| anyhow::anyhow!("Select a sheet after reading the workbook"))?; - Ok(pipeline::analyze(table, &profile, &cancel, |stage, msg| { - let _ = tx.send(Update::Progress(format!("{stage}/5 {msg}"))); - })) + Ok(( + pipeline::analyze(table, &profile, &cancel, |stage, msg| { + let _ = tx.send(Update::Progress(format!("{stage}/5 {msg}"))); + }), + table.clone(), + )) })(); let _ = tx.send(match result { - Ok(a) => Update::Analyzed(Box::new(a)), + Ok((a, table)) => Update::Analyzed(Box::new(a), table), Err(e) => Update::Failed(format!("{e:#}")), }); }); @@ -174,7 +185,9 @@ impl App { } self.status = "Select a sheet, then analyze".into(); } - Update::Analyzed(a) => { + Update::Analyzed(a, table) => { + self.tables.retain(|t| t.name != table.name); + self.tables.push(table); self.rx = None; self.tab = Tab::Review; self.status = if a.diagnostics.is_empty() { @@ -199,6 +212,370 @@ impl App { } } } + fn mapping_controls(&mut self, ui: &mut egui::Ui) { + ui.collapsing("Remap columns, header and units / advanced profile", |ui| { + self.mapping_fields(ui) + }); + } + fn mapping_fields(&mut self, ui: &mut egui::Ui) { + if let (Some(table), Ok(mut profile)) = ( + self.tables.iter().find(|t| t.name == self.sheet), + serde_json::from_str::(&self.profile), + ) { + let before = serde_json::to_string(&profile).unwrap(); + let mut header = profile + .header_row + .unwrap_or_else(|| { + self.analysis + .as_ref() + .and_then(|a| a.mapping.as_ref().map(|m| m.header_row)) + .unwrap_or_else(|| { + detect::inspect(table, &profile) + .1 + .first() + .and_then(|s| s.strip_prefix("Header row ")) + .and_then(|s| s.parse().ok()) + .unwrap_or(1) + }) + }) + .clamp(1, table.rows.len().max(1)); + ui.horizontal(|ui| { + ui.label("Header row"); + if ui + .add(egui::DragValue::new(&mut header).range(1..=table.rows.len().max(1))) + .changed() + { + profile.header_row = Some(header); + } + }); + let width = table.rows.iter().map(Vec::len).max().unwrap_or(0); + egui::Grid::new("mapping_controls").show(ui, |ui| { + for role in ["start", "end", "duration", "title"] { + ui.label(role); + let mut col = profile.columns.get(role).cloned().unwrap_or_default(); + egui::ComboBox::from_id_salt(role) + .selected_text(if col.is_empty() { + "Infer automatically" + } else { + &col + }) + .show_ui(ui, |ui| { + ui.selectable_value(&mut col, String::new(), "Infer automatically"); + for c in 0..width { + ui.selectable_value( + &mut col, + column_name(c), + format!( + "{} · {}", + column_name(c), + table.cell(header - 1, c).text + ), + ); + } + }); + ui.end_row(); + if col.is_empty() { + profile.columns.remove(role); + } else { + profile.columns.insert(role.into(), col); + } + } + }); + let mut unit = profile.duration_unit.clone().unwrap_or_default(); + egui::ComboBox::from_label("Duration unit") + .selected_text(if unit.is_empty() { + "Infer automatically" + } else { + &unit + }) + .show_ui(ui, |ui| { + ui.selectable_value(&mut unit, String::new(), "Infer automatically"); + for u in ["minutes", "seconds", "hh:mm", "mm:ss", "excel"] { + ui.selectable_value(&mut unit, u.into(), u); + } + }); + profile.duration_unit = (!unit.is_empty()).then_some(unit); + ui.checkbox( + &mut profile.untimed_as_notes, + "Treat untimed rows as notes on the preceding event", + ); + if before != serde_json::to_string(&profile).unwrap() { + self.profile = serde_json::to_string_pretty(&profile).unwrap(); + self.invalidate(); + } + } + ui.label("Optional JSON profile: columns (start/end/duration/title), duration_unit, row_kinds, durations, untimed_as_notes. Column letters and source rows are shown in diagnostics."); + if ui + .add( + egui::TextEdit::multiline(&mut self.profile) + .code_editor() + .desired_rows(8) + .desired_width(f32::INFINITY), + ) + .changed() + { + self.invalidate(); + } + } + + fn save_profile(&mut self, path: PathBuf, overwrite: bool) -> anyhow::Result<()> { + let profile: Profile = serde_json::from_str(&self.profile)?; + resolution::save( + &profile, + &path, + std::path::Path::new(&self.input), + overwrite, + )?; + self.status = format!("Resolution saved: {}", path.display()); + self.profile_path = Some(path); + Ok(()) + } + + fn memory_path(&self) -> anyhow::Result { + let dir = self.resolution_dir.as_ref().ok_or_else(|| { + anyhow::anyhow!("No user configuration directory available; use Save as") + })?; + let table = self + .tables + .iter() + .find(|t| t.name == self.sheet) + .ok_or_else(|| anyhow::anyhow!("Read and select a sheet first"))?; + resolution::remembered_path(dir, table) + } + + fn load_profile(&mut self, path: PathBuf) -> anyhow::Result<()> { + let profile = resolution::load(&path)?; + self.profile = serde_json::to_string_pretty(&profile)?; + self.profile_path = Some(path); + self.invalidate(); + self.status = "Resolution loaded; apply and recheck before export".into(); + Ok(()) + } + + fn remember(&mut self) -> anyhow::Result<()> { + anyhow::ensure!( + self.analysis + .as_ref() + .is_some_and(|a| a.completed_stage == 4 && a.diagnostics.is_empty()), + "Validate the resolution before remembering it" + ); + let path = self.memory_path()?; + std::fs::create_dir_all(path.parent().unwrap())?; + let profile: Profile = serde_json::from_str(&self.profile)?; + resolution::save(&profile, &path, std::path::Path::new(&self.input), true)?; + self.status = format!("Remembered for this exact sheet: {}", path.display()); + Ok(()) + } + + fn resolution_controls(&mut self, ui: &mut egui::Ui) { + ui.heading("Review and resolve"); + ui.label("Edit decisions below, then Apply & recheck. Source documents remain unchanged."); + ui.horizontal_wrapped(|ui| { + if ui.button("Load resolution…").clicked() + && let Some(path) = rfd::FileDialog::new() + .add_filter("Resolution JSON", &["json"]) + .pick_file() + && let Err(e) = self.load_profile(path) + { + self.error = Some(e.to_string()); + } + if ui + .add_enabled( + self.profile_path.is_some(), + egui::Button::new("Save (overwrite resolution)"), + ) + .clicked() + && let Err(e) = self.save_profile(self.profile_path.clone().unwrap(), true) + { + self.error = Some(e.to_string()); + } + if ui.button("Save resolution as…").clicked() + && let Some(path) = rfd::FileDialog::new() + .add_filter("Resolution JSON", &["json"]) + .set_file_name("rundown.resolution.json") + .save_file() + && let Err(e) = self.save_profile(path, self.replace_profile) + { + self.error = Some(e.to_string()); + } + ui.checkbox( + &mut self.replace_profile, + "Allow Save as to replace a resolution", + ); + if ui.button("Reset decisions").clicked() { + self.profile = "{}".into(); + self.profile_path = None; + self.invalidate(); + } + }); + if let Some(path) = &self.profile_path { + ui.label(format!("Resolution: {}", path.display())); + } + ui.horizontal_wrapped(|ui| { + let ready = self + .analysis + .as_ref() + .is_some_and(|a| a.completed_stage == 4 && a.diagnostics.is_empty()); + if ui + .add_enabled(ready, egui::Button::new("Remember resolution")) + .clicked() + && let Err(e) = self.remember() + { + self.error = Some(e.to_string()); + } + let path = self.memory_path().ok().filter(|p| p.exists()); + if ui + .add_enabled( + path.is_some(), + egui::Button::new("Reuse remembered resolution"), + ) + .clicked() + && let Err(e) = self.load_profile(path.clone().unwrap()) + { + self.error = Some(e.to_string()); + } + if ui + .add_enabled(path.is_some(), egui::Button::new("Forget")) + .clicked() + { + match std::fs::remove_file(path.unwrap()) { + Ok(()) => self.status = "Remembered resolution removed".into(), + Err(e) => self.error = Some(e.to_string()), + } + } + }); + ui.small("Remembered decisions match the complete sheet, including row order and timing formats. Reuse always requires validation."); + } + + fn source_table(&mut self, ui: &mut egui::Ui) { + let Some(table) = self.tables.iter().find(|t| t.name == self.sheet) else { + return; + }; + let Ok(mut profile) = serde_json::from_str::(&self.profile) else { + return; + }; + let before = serde_json::to_string(&profile).unwrap(); + let (mapping, evidence) = detect::inspect(table, &profile); + for text in &evidence { + ui.label(text); + } + let header = profile + .header_row + .or_else(|| { + evidence + .first() + .and_then(|s| s.strip_prefix("Header row ")) + .and_then(|s| s.parse().ok()) + }) + .unwrap_or(1) + .clamp(1, table.rows.len().max(1)); + let width = table.rows.iter().map(Vec::len).max().unwrap_or(0); + ui.separator(); + ui.strong("Source rows and resolution decisions"); + ui.label("Choose a column role to resolve ambiguity. Auto leaves inference in charge. Duration corrections need units (e.g. 2 min); blank restores the source value."); + egui::ScrollArea::both() + .max_height(320.0) + .id_salt("source_scroll") + .show(ui, |ui| { + egui::Grid::new("source_resolution") + .striped(true) + .show(ui, |ui| { + ui.strong("Row"); + ui.strong("Row meaning"); + ui.strong("Duration correction"); + for c in 0..width { + ui.vertical(|ui| { + let col = column_name(c); + ui.strong(format!("{col} · {}", table.cell(header - 1, c).text)); + let mut chosen = profile + .columns + .iter() + .find(|(_, v)| **v == col) + .map(|(k, _)| k.clone()) + .unwrap_or_default(); + let old = chosen.clone(); + egui::ComboBox::from_id_salt(("column_role", c)) + .selected_text(if chosen.is_empty() { "Auto" } else { &chosen }) + .show_ui(ui, |ui| { + ui.selectable_value(&mut chosen, String::new(), "Auto"); + for role in ["start", "end", "duration", "title"] { + ui.selectable_value(&mut chosen, role.into(), role); + } + }); + if chosen != old { + profile.columns.retain(|_, v| *v != col); + if !chosen.is_empty() { + profile.columns.insert(chosen, col); + } + } + if let Ok(m) = &mapping { + let role = if m.start == c { + "start" + } else if m.title == c { + "title" + } else if m.end == Some(c) { + "end" + } else if m.duration == Some(c) { + "duration" + } else { + "metadata" + }; + ui.small(format!("Detected: {role}")); + } + }); + } + ui.end_row(); + for row in header..table.rows.len() { + let number = row + 1; + ui.label(number.to_string()); + let mut kind = + profile.row_kinds.get(&number).cloned().unwrap_or_default(); + egui::ComboBox::from_id_salt(("row_kind", number)) + .selected_text(if kind.is_empty() { "Auto" } else { &kind }) + .show_ui(ui, |ui| { + ui.selectable_value(&mut kind, String::new(), "Auto"); + for k in ["event", "gap", "marker", "note", "ignore"] { + ui.selectable_value(&mut kind, k.into(), k); + } + }); + if kind.is_empty() { + profile.row_kinds.remove(&number); + } else { + profile.row_kinds.insert(number, kind); + } + let mut duration = + profile.durations.get(&number).cloned().unwrap_or_default(); + if ui + .add( + egui::TextEdit::singleline(&mut duration) + .id_salt(("duration", number)) + .desired_width(100.0) + .hint_text("Source value"), + ) + .changed() + { + if duration.trim().is_empty() { + profile.durations.remove(&number); + } else { + profile.durations.insert(number, duration); + } + } + for c in 0..width { + let value = table.cell(row, c).text; + ui.add(egui::Label::new(&value).truncate()) + .on_hover_text(value); + } + ui.end_row(); + } + }); + }); + if before != serde_json::to_string(&profile).unwrap() { + self.profile = serde_json::to_string_pretty(&profile).unwrap(); + self.invalidate(); + self.status = "Decisions changed; apply and recheck".into(); + } + } + fn pane(&mut self, ui: &mut egui::Ui) { match self.tab { Tab::Setup => { @@ -224,6 +601,9 @@ impl App { .changed() { self.sheets.clear(); + self.tables.clear(); + self.profile = "{}".into(); + self.profile_path = None; self.sheet.clear(); self.invalidate(); } @@ -236,6 +616,8 @@ impl App { .show_ui(ui, |ui| { for s in self.sheets.clone() { if ui.selectable_value(&mut self.sheet, s.clone(), s).changed() { + self.profile = "{}".into(); + self.profile_path = None; self.invalidate(); } } @@ -259,135 +641,13 @@ impl App { self.settings = !self.settings; } if self.settings { - if let (Some(table), Ok(mut profile)) = ( - self.tables.iter().find(|t| t.name == self.sheet), - serde_json::from_str::(&self.profile), - ) { - let before = serde_json::to_string(&profile).unwrap(); - let mut header = profile.header_row.unwrap_or_else(|| { - self.analysis - .as_ref() - .and_then(|a| a.mapping.as_ref().map(|m| m.header_row)) - .unwrap_or(1) - }); - ui.horizontal(|ui| { - ui.label("Header row"); - if ui - .add( - egui::DragValue::new(&mut header) - .range(1..=table.rows.len().max(1)), - ) - .changed() - { - profile.header_row = Some(header); - } - }); - let width = table.rows.iter().map(Vec::len).max().unwrap_or(0); - egui::Grid::new("mapping_controls").show(ui, |ui| { - for role in ["start", "end", "duration", "title"] { - ui.label(role); - let mut col = - profile.columns.get(role).cloned().unwrap_or_default(); - egui::ComboBox::from_id_salt(role) - .selected_text(if col.is_empty() { - "Infer automatically" - } else { - &col - }) - .show_ui(ui, |ui| { - ui.selectable_value( - &mut col, - String::new(), - "Infer automatically", - ); - for c in 0..width { - ui.selectable_value( - &mut col, - column_name(c), - format!( - "{} · {}", - column_name(c), - table.cell(header - 1, c).text - ), - ); - } - }); - ui.end_row(); - if col.is_empty() { - profile.columns.remove(role); - } else { - profile.columns.insert(role.into(), col); - } - } - }); - let mut unit = profile.duration_unit.clone().unwrap_or_default(); - egui::ComboBox::from_label("Duration unit") - .selected_text(if unit.is_empty() { - "Infer automatically" - } else { - &unit - }) - .show_ui(ui, |ui| { - ui.selectable_value( - &mut unit, - String::new(), - "Infer automatically", - ); - for u in ["minutes", "seconds", "hh:mm", "mm:ss", "excel"] { - ui.selectable_value(&mut unit, u.into(), u); - } - }); - profile.duration_unit = (!unit.is_empty()).then_some(unit); - ui.checkbox( - &mut profile.untimed_as_notes, - "Treat untimed rows as notes on the preceding event", - ); - if before != serde_json::to_string(&profile).unwrap() { - self.profile = serde_json::to_string_pretty(&profile).unwrap(); - self.invalidate(); - } - } - ui.label("Optional JSON profile: columns (start/end/duration/title), duration_unit, row_kinds, durations, untimed_as_notes. Column letters and source rows are shown in diagnostics."); - ui.horizontal(|ui| { - if ui.button("Load profile…").clicked() - && let Some(p) = rfd::FileDialog::new() - .add_filter("JSON", &["json"]) - .pick_file() - { - match std::fs::read_to_string(p) { - Ok(s) => { - self.profile = s; - self.invalidate(); - } - Err(e) => self.error = Some(e.to_string()), - } - } - if ui.button("Reset").clicked() { - self.profile = "{}".into(); - self.invalidate(); - } - }); - if ui - .add( - egui::TextEdit::multiline(&mut self.profile) - .code_editor() - .desired_rows(8) - .desired_width(f32::INFINITY), - ) - .changed() - { - self.invalidate(); - } + self.mapping_controls(ui); } } Tab::Review => { + self.resolution_controls(ui); + self.mapping_controls(ui); if let Some(a) = &self.analysis { - ui.heading(&a.sheet); - if let Some(m) = &a.mapping { - for text in &m.evidence { - ui.label(text); - } - } for d in &a.diagnostics { ui.colored_label( Color32::from_rgb(220, 130, 65), @@ -395,6 +655,10 @@ impl App { ); ui.add_space(6.0); } + } + self.source_table(ui); + if let Some(a) = &self.analysis { + ui.heading(format!("Schedule preview · {}", a.sheet)); if let Some(r) = &a.rundown { ui.separator(); ui.label(format!( @@ -438,7 +702,7 @@ impl App { }); } } else { - ui.label("Analyze a sheet to review the inferred schedule."); + ui.label("Apply & recheck to update the schedule. Export is blocked until these decisions pass validation."); } } Tab::Results => { @@ -515,7 +779,12 @@ impl App { .add_enabled( !self.sheet.is_empty(), egui::Button::new( - RichText::new("Analyze rundown").color(Color32::WHITE), + RichText::new(if self.tab == Tab::Review { + "Apply & recheck" + } else { + "Analyze rundown" + }) + .color(Color32::WHITE), ) .fill(Color32::from_rgb(87, 68, 181)), ) @@ -694,4 +963,69 @@ mod tests { app.tab = Tab::Review; frame(&mut app, 560.0, 400.0); } + + #[test] + fn resolve_save_reuse_and_revalidate_ambiguous_rundown() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("ambiguous.csv"); + let original = "Start,Timer,Timer,Title\n09:00,5 min,2 min,Welcome\n09:05,,,Closing\n"; + std::fs::write(&source, original).unwrap(); + let mut app = App { + resolution_dir: Some(dir.path().join("remembered")), + ..App::default() + }; + app.set_input(source.clone()); + app.inspect(); + wait(&mut app); + app.analyze(); + wait(&mut app); + assert_eq!( + app.analysis.as_ref().unwrap().diagnostics[0].code, + "AMBIGUOUS_COLUMN" + ); + let (_, evidence) = detect::inspect(&app.tables[0], &Profile::default()); + assert!(evidence.iter().any(|e| e == "Header suggests start in A")); + assert!(!evidence.iter().any(|e| e.starts_with("Every relevant"))); + frame(&mut app, 860.0, 620.0); + assert!(app.remember().is_err()); + app.profile = r#"{"columns":{"duration":"B"},"durations":{"3":"3 min"}}"#.into(); + app.invalidate(); + assert!(app.analysis.is_none()); + frame(&mut app, 560.0, 400.0); + app.analyze(); + wait(&mut app); + assert!(app.analysis.as_ref().unwrap().diagnostics.is_empty()); + let path = dir.path().join("resolution.json"); + app.save_profile(path.clone(), false).unwrap(); + assert!(app.save_profile(path.clone(), false).is_err()); + app.save_profile(path.clone(), true).unwrap(); + app.remember().unwrap(); + let memory = app.memory_path().unwrap(); + assert!(memory.exists()); + app.set_input(source.clone()); + assert_eq!(app.profile, "{}"); + app.inspect(); + wait(&mut app); + assert_eq!(app.memory_path().unwrap(), memory); + app.load_profile(memory).unwrap(); + assert!(app.analysis.is_none()); + app.analyze(); + wait(&mut app); + assert!(app.analysis.as_ref().unwrap().diagnostics.is_empty()); + app.output = dir.path().join("ontime.json").display().to_string(); + app.export(); + wait(&mut app); + assert!(app.completed.is_some()); + assert_eq!(std::fs::read_to_string(&source).unwrap(), original); + std::fs::write(&source, original.replace("09:05", "09:04")).unwrap(); + app.set_input(source); + app.inspect(); + wait(&mut app); + assert!(!app.memory_path().unwrap().exists()); + app.load_profile(path).unwrap(); + app.analyze(); + wait(&mut app); + assert!(!app.analysis.as_ref().unwrap().diagnostics.is_empty()); + assert!(app.remember().is_err()); + } } diff --git a/crates/rundown-converter/src/lib.rs b/crates/rundown-converter/src/lib.rs index a7832c5..353e939 100644 --- a/crates/rundown-converter/src/lib.rs +++ b/crates/rundown-converter/src/lib.rs @@ -6,4 +6,5 @@ pub mod gui; pub mod model; pub mod pipeline; pub mod reader; +pub mod resolution; pub mod time; diff --git a/crates/rundown-converter/src/resolution.rs b/crates/rundown-converter/src/resolution.rs new file mode 100644 index 0000000..d9fc7bd --- /dev/null +++ b/crates/rundown-converter/src/resolution.rs @@ -0,0 +1,81 @@ +//! Portable clarification profiles and exact-sheet remembered resolutions. +use crate::model::{Profile, Table}; +use anyhow::{Result, ensure}; +use std::{ + io::Write, + path::{Path, PathBuf}, +}; + +pub fn directory() -> Option { + directories::ProjectDirs::from("org", "beffroi", "rundown-converter") + .map(|p| p.config_dir().join("resolutions")) +} + +/// Include all cells, formats, formulas, merged ranges and the sheet name. +pub fn remembered_path(directory: &Path, table: &Table) -> Result { + let bytes = serde_json::to_vec(table)?; + let id = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, &bytes); + Ok(directory.join(format!("{id}.json"))) +} + +pub fn load(path: &Path) -> Result { + Ok(serde_json::from_slice(&std::fs::read(path)?)?) +} + +pub fn save(profile: &Profile, path: &Path, source: &Path, overwrite: bool) -> Result<()> { + ensure!( + path.extension().is_some_and(|e| e == "json"), + "Resolution files must use .json" + ); + ensure!( + source.canonicalize()? != path.canonicalize().unwrap_or_else(|_| path.to_path_buf()), + "A resolution must not replace the source document" + ); + ensure!( + !path.exists() || overwrite, + "Resolution exists; choose another name or explicitly enable replacement" + ); + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let mut temp = tempfile::NamedTempFile::new_in(parent)?; + serde_json::to_writer_pretty(&mut temp, profile)?; + writeln!(temp)?; + temp.as_file().sync_all()?; + if overwrite { + temp.persist(path)?; + } else { + temp.persist_noclobber(path)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn profiles_roundtrip_and_remember_only_identical_sheets() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("source.json"); + std::fs::write(&source, "original").unwrap(); + let mut table = Table { + name: "Show".into(), + rows: vec![vec![Default::default()]], + merges: vec![], + }; + let path = remembered_path(dir.path(), &table).unwrap(); + let mut profile = Profile::default(); + profile.durations.insert(2, "2 min".into()); + save(&profile, &path, &source, false).unwrap(); + assert_eq!(load(&path).unwrap().durations[&2], "2 min"); + assert!(save(&profile, &path, &source, false).is_err()); + save(&profile, &path, &source, true).unwrap(); + assert!(save(&profile, &source, &source, true).is_err()); + assert_eq!(std::fs::read_to_string(&source).unwrap(), "original"); + table.rows[0][0].text = "changed".into(); + assert_ne!(path, remembered_path(dir.path(), &table).unwrap()); + table.name = "Other sheet".into(); + assert!(!remembered_path(dir.path(), &table).unwrap().exists()); + } +} diff --git a/docs/rundown-converter-plan.md b/docs/rundown-converter-plan.md index 74a4ff8..33215ac 100644 --- a/docs/rundown-converter-plan.md +++ b/docs/rundown-converter-plan.md @@ -248,7 +248,11 @@ errors must remain visible with direct corrective actions. native rundown parser and metadata calculation at the recorded source commit. - [x] Add initial Setup/Review/Results GUI, source preview, column/unit selectors, shared profile controls and worker/cancellation tests. -- [ ] Add recent-file persistence, visual per-row editing, profile saving and +- [x] Keep inference evidence and the source table on Review after failures; + add column-role dropdowns, row classifications and duration corrections. +- [x] Save/overwrite/save-as portable resolution profiles and explicitly remember, + reuse or forget validated resolutions matched to the complete sheet. +- [ ] Add recent-file persistence, direct start/end/title editing and comprehensive native GUI interaction checks. - [ ] Inventory supplied examples by format/layout; record intended interpretations and the user's Ontime version. Decide first-release input coverage from these. diff --git a/docs/rundown-converter.md b/docs/rundown-converter.md index cfd7092..4bc3add 100644 --- a/docs/rundown-converter.md +++ b/docs/rundown-converter.md @@ -34,9 +34,23 @@ CLI logs are plain text on stderr; JSON results go to stdout. In the desktop app, choose or drop one file, read its sheets, select a sheet and click **Analyze rundown**. **Review** shows source rows, timing decisions, gaps and -blocking errors; **Export** is enabled only after validation. **Setup → Mapping -and clarification settings** offers column/unit selectors and an advanced JSON -profile. **Results** offers Open, Open output folder and Copy path. Cancel is +blocking errors; **Export** is enabled only after validation. Review keeps the +source table available even when column inference fails, with the evidence +collected before the error. Choose a role from a column's dropdown to resolve +ambiguity; selecting one duration column explicitly resolves duplicate TIMER +headers. **Auto** restores inference, rather than ignoring a column. Expand +**Remap columns, header and units / advanced profile** for role-to-column +selectors, header row, duration units and the JSON editor (also in Setup). + +In the source table, choose each row's meaning or enter a duration correction +with units, such as `2 min`. Blank corrections restore the source value. Click +**Apply & recheck** to rebuild and validate the schedule; editing decisions blocks +export until validation succeeds. Missing durations and untimed-row decisions +can be resolved here. Unsupported interpretations, invalid start/end values, +conflicting timings and unresolved overlaps still produce explicit errors; +correct the source when the available controls cannot express the intended fix. +The schedule preview below the source table shows the resulting timers and gaps. + **Results** offers Open, Open output folder and Copy path. Cancel is observed between analysis stages and before publishing an export; reading a workbook or an active stage finishes before it takes effect. @@ -161,6 +175,26 @@ timers. An ignored row is recorded as an explicit exclusion. Duration overrides retain original cell values and the fact that a correction was requested. Use `expected_headers` to guard reusable profiles against changed layouts. +**Save resolution as…** writes a portable profile JSON, usable with CLI +`--profile`. **Save (overwrite resolution)** replaces the loaded/saved profile; +Save as refuses existing files unless its replacement checkbox is enabled. +These actions save decisions, not a rewritten spreadsheet or an Ontime export. +Profiles may contain unfinished decisions; loading one always requires a fresh +analysis. Explicitly loaded profiles use worksheet row numbers, so review their +applicability when the document has changed. + +**Remember resolution** stores a validated profile in the platform's user +configuration directory, under `rundown-converter/resolutions` (on Linux, +`$XDG_CONFIG_HOME/rundown-converter/resolutions`, normally +`~/.config/rundown-converter/resolutions`). The status displays the exact path. +**Reuse remembered resolution** becomes available for an identical sheet and +loads its decisions for revalidation; **Forget** removes that remembered file. +Matching includes every cell, timing format, formula, merge, sheet name and row +order, so changed documents cannot silently inherit row corrections. This is +explicit reuse rather than automatic application. Changing file or sheet clears +current decisions. Remembered files contain profile decisions and a hash in their +filename, not a copy of the workbook; they remain local to this machine. + ## Current limits One selected sheet represents one sequential, single-day schedule. Parallel @@ -173,9 +207,9 @@ as notes. Unmerged untimed directions need explicit classification. A full-width merged text band is treated as a section/footnote and recorded in the IR. Nonempty unmerged text in a time column is a contradiction, not silently ignored. Missing end/duration in a start-only schedule remains unresolved. -The GUI currently keeps settings for the current session only; recent-file -persistence, richer row-editing controls and portable release bundles are future -work. JSON profiles provide row decisions in both interfaces. +Recent-file persistence, direct start/end/title editing and portable release +bundles remain future work. JSON profiles provide the same supported resolution +decisions in both interfaces. ## Stretch goal: reserve buffer time