| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | use crate::*; |
| 10 | use std::io; |
| 11 | use std::path::{Path, PathBuf}; |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | const MAGIC: &str = "edith-view 1"; |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | const PPS_MAX_SAVED: f64 = 100_000.; |
| 23 | |
| 24 | |
| 25 | #[derive(Clone, Debug, PartialEq)] |
| 26 | pub(crate) struct ViewState { |
| 27 | pub(crate) pps: f64, |
| 28 | pub(crate) start: f64, |
| 29 | |
| 30 | pub(crate) lane_h: Vec<(String, f32)>, |
| 31 | |
| 32 | pub(crate) viewer: crate::viewer_view::Prefs, |
| 33 | |
| 34 | pub(crate) closed_bins: Vec<u32>, |
| 35 | |
| 36 | |
| 37 | pub(crate) sections: Vec<(String, Vec<String>)>, |
| 38 | |
| 39 | pub(crate) waveforms: bool, |
| 40 | |
| 41 | pub(crate) scrub_audio: bool, |
| 42 | } |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | #[derive(Debug, PartialEq)] |
| 50 | pub(crate) struct Restored { |
| 51 | pub(crate) scale: Scale, |
| 52 | pub(crate) lane_h: Vec<(String, f32)>, |
| 53 | pub(crate) panned: bool, |
| 54 | pub(crate) fitted_bed: Option<f32>, |
| 55 | pub(crate) fit_pending: bool, |
| 56 | } |
| 57 | |
| 58 | pub(crate) fn restored(state: &ViewState) -> Restored { |
| 59 | Restored { |
| 60 | scale: Scale { |
| 61 | pps: state.pps, |
| 62 | start: state.start, |
| 63 | }, |
| 64 | lane_h: state.lane_h.clone(), |
| 65 | panned: true, |
| 66 | fitted_bed: None, |
| 67 | fit_pending: false, |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | |
| 72 | |
| 73 | pub(crate) fn views_dir() -> PathBuf { |
| 74 | crate::keymap::Keymap::config_path().with_file_name("views") |
| 75 | } |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | pub(crate) fn path_for(dir: &Path, project: &Path) -> PathBuf { |
| 81 | let canon = std::fs::canonicalize(project).unwrap_or_else(|_| project.to_path_buf()); |
| 82 | dir.join(format!( |
| 83 | "{:016x}", |
| 84 | fnv1a(canon.to_string_lossy().as_bytes()) |
| 85 | )) |
| 86 | } |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | fn fnv1a(bytes: &[u8]) -> u64 { |
| 92 | let mut hash = 0xcbf2_9ce4_8422_2325_u64; |
| 93 | for byte in bytes { |
| 94 | hash ^= u64::from(*byte); |
| 95 | hash = hash.wrapping_mul(0x0100_0000_01b3); |
| 96 | } |
| 97 | hash |
| 98 | } |
| 99 | |
| 100 | pub(crate) fn to_text(state: &ViewState) -> String { |
| 101 | let mut out = format!("{MAGIC}\npps={}\nstart={}\n", state.pps, state.start); |
| 102 | for (key, h) in &state.lane_h { |
| 103 | out.push_str(&format!("lane.{key}={h}\n")); |
| 104 | } |
| 105 | let v = &state.viewer; |
| 106 | out.push_str(&format!( |
| 107 | "zoom={}\nquality={}\nguides={}\nmask={}\n", |
| 108 | v.zoom.key(), |
| 109 | v.quality.key(), |
| 110 | v.guide.key(), |
| 111 | v.mask.key() |
| 112 | )); |
| 113 | if !state.waveforms { |
| 114 | out.push_str("waveforms=off\n"); |
| 115 | } |
| 116 | if !state.scrub_audio { |
| 117 | out.push_str("scrub_audio=off\n"); |
| 118 | } |
| 119 | if !state.closed_bins.is_empty() { |
| 120 | let ids: Vec<String> = state.closed_bins.iter().map(u32::to_string).collect(); |
| 121 | out.push_str(&format!("closed_bins={}\n", ids.join(","))); |
| 122 | } |
| 123 | for (kind, names) in &state.sections { |
| 124 | if !names.is_empty() { |
| 125 | out.push_str(&format!("sections.{kind}={}\n", names.join(","))); |
| 126 | } |
| 127 | } |
| 128 | out |
| 129 | } |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | pub(crate) fn from_text(text: &str) -> Option<ViewState> { |
| 137 | let mut lines = text.lines(); |
| 138 | if lines.next()? != MAGIC { |
| 139 | return None; |
| 140 | } |
| 141 | let (mut pps, mut start) = (None, None); |
| 142 | let mut lane_h = Vec::new(); |
| 143 | let mut viewer = crate::viewer_view::Prefs::default(); |
| 144 | let mut closed_bins = Vec::new(); |
| 145 | let mut sections: Vec<(String, Vec<String>)> = Vec::new(); |
| 146 | let mut waveforms = true; |
| 147 | let mut scrub_audio = true; |
| 148 | for line in lines { |
| 149 | let Some((key, value)) = line.split_once('=') else { |
| 150 | continue; |
| 151 | }; |
| 152 | match key { |
| 153 | "pps" => pps = Some(value.parse::<f64>().ok().filter(|v| v.is_finite())?), |
| 154 | "start" => start = Some(value.parse::<f64>().ok().filter(|v| v.is_finite())?), |
| 155 | "zoom" => viewer.zoom = crate::viewer_view::Zoom::from_key(value).unwrap_or_default(), |
| 156 | "quality" => viewer.quality = crate::viewer_view::Quality::from_key(value).unwrap_or_default(), |
| 157 | "guides" => viewer.guide = crate::viewer_view::Guide::from_key(value).unwrap_or_default(), |
| 158 | "mask" => viewer.mask = crate::viewer_view::Mask::from_key(value).unwrap_or_default(), |
| 159 | "waveforms" => waveforms = value != "off", |
| 160 | "scrub_audio" => scrub_audio = value != "off", |
| 161 | "closed_bins" => closed_bins = value.split(',').filter_map(|v| v.parse::<u32>().ok()).collect(), |
| 162 | _ if key.starts_with("sections.") => { |
| 163 | let kind = &key["sections.".len()..]; |
| 164 | if !kind.is_empty() && kind.chars().all(|c| c.is_ascii_alphanumeric()) { |
| 165 | let names = value |
| 166 | .split(',') |
| 167 | .filter(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_alphanumeric())) |
| 168 | .map(str::to_string) |
| 169 | .collect(); |
| 170 | sections.push((kind.to_string(), names)); |
| 171 | } |
| 172 | } |
| 173 | _ => { |
| 174 | let Some(name) = key.strip_prefix("lane.") else { |
| 175 | continue; |
| 176 | }; |
| 177 | let valid_name = |
| 178 | !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric()); |
| 179 | if let Ok(h) = value.parse::<f32>() |
| 180 | && h.is_finite() |
| 181 | && h > 0. |
| 182 | && valid_name |
| 183 | { |
| 184 | lane_h.push((name.to_string(), h)); |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | Some(ViewState { |
| 190 | pps: pps?.clamp(PPS_MIN, PPS_MAX_SAVED), |
| 191 | start: start?.max(0.), |
| 192 | lane_h, |
| 193 | viewer, |
| 194 | closed_bins, |
| 195 | sections, |
| 196 | waveforms, |
| 197 | scrub_audio, |
| 198 | }) |
| 199 | } |
| 200 | |
| 201 | pub(crate) fn load_in(dir: &Path, project: &Path) -> Option<ViewState> { |
| 202 | from_text(&std::fs::read_to_string(path_for(dir, project)).ok()?) |
| 203 | } |
| 204 | |
| 205 | |
| 206 | |
| 207 | pub(crate) fn save_in(dir: &Path, project: &Path, state: &ViewState) -> io::Result<()> { |
| 208 | std::fs::create_dir_all(dir)?; |
| 209 | let path = path_for(dir, project); |
| 210 | let tmp = path.with_extension("tmp"); |
| 211 | std::fs::write(&tmp, to_text(state))?; |
| 212 | std::fs::rename(&tmp, &path) |
| 213 | } |
| 214 | |
| 215 | pub(crate) fn load(project: &Path) -> Option<ViewState> { |
| 216 | load_in(&views_dir(), project) |
| 217 | } |
| 218 | |
| 219 | pub(crate) fn save(project: &Path, state: &ViewState) -> io::Result<()> { |
| 220 | save_in(&views_dir(), project, state) |
| 221 | } |
| 222 | |
| 223 | #[cfg(test)] |
| 224 | mod tests { |
| 225 | use super::*; |
| 226 | |
| 227 | |
| 228 | fn scratch(name: &str) -> PathBuf { |
| 229 | std::env::temp_dir().join(format!("edith-view-{}-{name}", std::process::id())) |
| 230 | } |
| 231 | |
| 232 | fn sample() -> ViewState { |
| 233 | ViewState { |
| 234 | pps: 75.5, |
| 235 | start: 12.25, |
| 236 | lane_h: vec![("v1".to_string(), 120.), ("a2".to_string(), 64.5)], |
| 237 | viewer: crate::viewer_view::Prefs { |
| 238 | zoom: crate::viewer_view::Zoom::P50, |
| 239 | quality: crate::viewer_view::Quality::Half, |
| 240 | guide: crate::viewer_view::Guide::Safe, |
| 241 | mask: crate::viewer_view::Mask::Vertical, |
| 242 | }, |
| 243 | closed_bins: vec![2, 7], |
| 244 | sections: vec![("video".to_string(), vec!["color".to_string(), "speed".to_string()])], |
| 245 | waveforms: false, |
| 246 | scrub_audio: false, |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | #[test] |
| 251 | fn a_saved_view_loads_back_as_it_was_written() { |
| 252 | let dir = scratch("round-trip"); |
| 253 | let project = dir.join("cut.edith"); |
| 254 | save_in(&dir, &project, &sample()).expect("save"); |
| 255 | assert_eq!(load_in(&dir, &project), Some(sample())); |
| 256 | |
| 257 | assert!(path_for(&dir, &project).is_file()); |
| 258 | let _ = std::fs::remove_dir_all(&dir); |
| 259 | } |
| 260 | |
| 261 | #[test] |
| 262 | fn a_missing_view_is_none_and_so_is_a_corrupt_one() { |
| 263 | let dir = scratch("corrupt"); |
| 264 | let project = dir.join("cut.edith"); |
| 265 | assert_eq!(load_in(&dir, &project), None, "no file, no view"); |
| 266 | std::fs::create_dir_all(&dir).expect("dir"); |
| 267 | std::fs::write(path_for(&dir, &project), "edith-view 1\npps=ninety\n").expect("write"); |
| 268 | assert_eq!(load_in(&dir, &project), None, "a bad number is corruption"); |
| 269 | let _ = std::fs::remove_dir_all(&dir); |
| 270 | |
| 271 | |
| 272 | for text in [ |
| 273 | "", |
| 274 | "edith-view 2\npps=40\nstart=0\n", |
| 275 | "pps=40\nstart=0\n", |
| 276 | "edith-view 1\npps=40\n", |
| 277 | "edith-view 1\nstart=0\n", |
| 278 | "edith-view 1\npps=NaN\nstart=0\n", |
| 279 | "edith-view 1\npps=40\nstart=inf\n", |
| 280 | ] { |
| 281 | assert_eq!(from_text(text), None, "{text:?}"); |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | #[test] |
| 286 | fn the_waveform_switch_is_on_unless_the_view_says_off() { |
| 287 | let on = from_text("edith-view 1\npps=40\nstart=0\n").expect("parses"); |
| 288 | assert!(on.waveforms, "a view with no line keeps the waveforms on"); |
| 289 | let off = from_text("edith-view 1\npps=40\nstart=0\nwaveforms=off\n").expect("parses"); |
| 290 | assert!(!off.waveforms); |
| 291 | assert!(on.scrub_audio, "a view with no line scrubs with sound"); |
| 292 | let quiet = from_text("edith-view 1\npps=40\nstart=0\nscrub_audio=off\n").expect("parses"); |
| 293 | assert!(!quiet.scrub_audio); |
| 294 | assert!(to_text(&off).contains("waveforms=off")); |
| 295 | assert!(!to_text(&on).contains("waveforms"), "an on view writes nothing for it"); |
| 296 | } |
| 297 | |
| 298 | #[test] |
| 299 | fn a_damaged_lane_line_costs_only_that_lane() { |
| 300 | let text = |
| 301 | "edith-view 1\npps=40\nstart=0\nlane.v1=oops\nlane.a2=50\nlane.x y=3\nfuture=1\n"; |
| 302 | let state = from_text(text).expect("the scale is intact"); |
| 303 | assert_eq!(state.lane_h, vec![("a2".to_string(), 50.)]); |
| 304 | } |
| 305 | |
| 306 | #[test] |
| 307 | fn a_loaded_scale_is_clamped_to_what_a_view_may_hold() { |
| 308 | let state = from_text("edith-view 1\npps=0.001\nstart=-5\n").expect("parses"); |
| 309 | assert_eq!((state.pps, state.start), (PPS_MIN, 0.)); |
| 310 | let state = from_text("edith-view 1\npps=1e300\nstart=3\n").expect("parses"); |
| 311 | assert_eq!(state.pps, PPS_MAX_SAVED); |
| 312 | } |
| 313 | |
| 314 | #[test] |
| 315 | fn restoring_a_view_takes_the_hand_and_cancels_the_first_import_fit() { |
| 316 | let restored = restored(&sample()); |
| 317 | assert_eq!( |
| 318 | restored.scale, |
| 319 | Scale { |
| 320 | pps: 75.5, |
| 321 | start: 12.25 |
| 322 | } |
| 323 | ); |
| 324 | assert!(restored.panned, "the restored view is the hand's"); |
| 325 | assert_eq!(restored.fitted_bed, None, "no sticky fit to refit against"); |
| 326 | assert!( |
| 327 | !restored.fit_pending, |
| 328 | "a fit waiting for a bed is cancelled" |
| 329 | ); |
| 330 | assert_eq!(restored.lane_h, sample().lane_h); |
| 331 | } |
| 332 | |
| 333 | #[test] |
| 334 | fn the_file_name_is_stable_and_follows_the_project() { |
| 335 | let dir = Path::new("/nonexistent-views"); |
| 336 | |
| 337 | assert_eq!(fnv1a(b""), 0xcbf2_9ce4_8422_2325); |
| 338 | assert_eq!(fnv1a(b"a"), 0xaf63_dc4c_8601_ec8c); |
| 339 | let one = path_for(dir, Path::new("/nonexistent-views/one.edith")); |
| 340 | assert_eq!( |
| 341 | one, |
| 342 | path_for(dir, Path::new("/nonexistent-views/one.edith")) |
| 343 | ); |
| 344 | assert_ne!( |
| 345 | one, |
| 346 | path_for(dir, Path::new("/nonexistent-views/two.edith")) |
| 347 | ); |
| 348 | } |
| 349 | } |