forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

view_state.rs349 lines, 13.5 KiBHistoryRawDownload
1//! Where a project's view was left -- the scale, the scroll and each lane's
2//! height -- so a project reopens exactly as it was left (DESIGN §5).
3//!
4//! One small file per project, in a `views` directory beside the stance
5//! splits, named by a hash of the project's canonical path. The project file
6//! itself is never touched: a view that fails to write costs the next open its
7//! place, and a view that fails to read is no view at all -- never an error.
8
9use crate::*;
10use std::io;
11use std::path::{Path, PathBuf};
12
13/// First line of every view file. A file that does not start with it is not
14/// one of ours -- or is from a format this build does not know -- and loads as
15/// no view at all.
16const MAGIC: &str = "edith-view 1";
17
18/// The most pixels per second a saved view may ask for. The real zoom stops
19/// depend on the bed the timeline is drawn on ([`View::stops`]), which is not
20/// known at load; [`View::settled`] applies them on the first frame. This bound
21/// only keeps a corrupt number out of the arithmetic until then.
22const PPS_MAX_SAVED: f64 = 100_000.;
23
24/// What a project's view looked like when it was last saved.
25#[derive(Clone, Debug, PartialEq)]
26pub(crate) struct ViewState {
27 pub(crate) pps: f64,
28 pub(crate) start: f64,
29 /// Lane key ("v1", "a2", "s1") to the height it was dragged to.
30 pub(crate) lane_h: Vec<(String, f32)>,
31 /// The viewer's zoom, playback quality, guides and mask.
32 pub(crate) viewer: crate::viewer_view::Prefs,
33 /// The media bins the list shows folded, by bin id (ascending).
34 pub(crate) closed_bins: Vec<u32>,
35 /// Which Clip-tab sections are open, per clip kind (`video`, `audio`, ...): kind then the
36 /// sections' names, so the inspector comes back the way it was left on the next clip of that kind.
37 pub(crate) sections: Vec<(String, Vec<String>)>,
38 /// Whether audio clips draw their waveforms. On unless the file says `waveforms=off`.
39 pub(crate) waveforms: bool,
40 /// Whether a ruler scrub while paused plays a short snippet of sound ([`ActionId::ToggleScrubAudio`]).
41 pub(crate) scrub_audio: bool,
42}
43
44/// What a saved view puts on the [`crate::Player`]. The flags are the part
45/// that matters: a restored view must win over the first-import fit, so it
46/// reads as the hand's (`panned`) and the sticky fit is cancelled
47/// (`fitted_bed`, `fit_pending`). A project with no saved view never reaches
48/// this and keeps today's behaviour.
49#[derive(Debug, PartialEq)]
50pub(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
58pub(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/// The views directory: `views` beside the keybindings file, as the stance
72/// splits file sits beside it.
73pub(crate) fn views_dir() -> PathBuf {
74 crate::keymap::Keymap::config_path().with_file_name("views")
75}
76
77/// The file a project's view lives in. The canonical path keeps one project
78/// reached by two spellings on one file; a path that cannot be canonicalised
79/// (a project not yet written) is hashed as given.
80pub(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/// FNV-1a, 64 bit. A file name has to be the same from one launch to the next,
89/// which rules out the std hasher (its seed is random per process); FNV is
90/// small enough to write here rather than add a dependency for it.
91fn 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
100pub(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/// Parses a view file. Missing or unparsable scale values are corruption and
132/// give `None`; a lane line that does not parse is dropped on its own, and an
133/// unknown key is skipped so a newer file's extra lines do not lose the rest.
134/// The scale is clamped to what a view may hold ([`PPS_MIN`], [`PPS_MAX_SAVED`]
135/// and a start at or after the head).
136pub(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
201pub(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/// Written to a temporary file and renamed over the old one, so a quit in the
206/// middle of the write leaves the previous view or none, never a torn one.
207pub(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
215pub(crate) fn load(project: &Path) -> Option<ViewState> {
216 load_in(&views_dir(), project)
217}
218
219pub(crate) fn save(project: &Path, state: &ViewState) -> io::Result<()> {
220 save_in(&views_dir(), project, state)
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226
227 /// A scratch directory per test, so parallel tests never share a view file.
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 // Written in the one place a later launch will look for it.
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 // Each of these is a file this build must not read as a view.
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 // FNV-1a of the empty string and of "a", the published test vectors.
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}