forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

actions.rs1693 lines, 81.7 KiBHistoryRawDownload
1//! Every action arrives here: the one dispatch, the notice queue, and the
2//! delegations to the oracle that say whether an action can be asked for.
3
4use super::editkeys::Part;
5use super::timeline_edit::Switch;
6use crate::*;
7
8/// The name an action's step carries in Undo, Redo and the toast: its menu name without the
9/// ellipsis a dialog-opening row wears. `None` for Undo and Redo, which take a step back
10/// rather than make one, and for a name too long to read in a menu row.
11pub(crate) fn step_name(action: ActionId) -> Option<&'static str> {
12 let name = match action {
13 ActionId::Undo | ActionId::Redo => return None,
14 ActionId::ClipEnabled => "Enable/disable clip",
15 ActionId::ClipLabel => "Set clip label",
16 ActionId::NewSolid => "Add solid colour",
17 ActionId::NewGradient => "Add gradient",
18 ActionId::NewCountdown => "Add countdown",
19 ActionId::NewBars => "Add colour bars",
20 ActionId::NewTone => "Add tone",
21 ActionId::NewBarsAndTone => "Add bars and tone",
22 ActionId::NewAdjustment => "Add adjustment layer",
23 ActionId::NewRectangle => "Add rectangle shape",
24 ActionId::NewEllipse => "Add ellipse shape",
25 ActionId::NewLine => "Add line shape",
26 ActionId::NewArrow => "Add arrow shape",
27 _ => action.label().trim_end_matches('\u{2026}'),
28 };
29 (name.chars().count() < 30).then_some(name)
30}
31
32/// What Undo or Redo says on a menu row and in a tooltip: the step it takes back or walks to
33/// by name, plain "Undo" or "Redo" for a step nobody named, and "Nothing to undo" or
34/// "Nothing to redo" when no step is left.
35pub(crate) fn step_row_name(redo: bool, depth: usize, name: Option<&str>) -> String {
36 let verb = if redo { "Redo" } else { "Undo" };
37 match (depth, name) {
38 (0, _) => format!("Nothing to {}", verb.to_lowercase()),
39 (_, Some(name)) => format!("{verb} {name}"),
40 (_, None) => verb.to_string(),
41 }
42}
43
44/// The toast after a step is taken back or walked forward: "Undid Split", "Redid Split", or
45/// plain "Undone" and "Redone" for a step nobody named.
46pub(crate) fn step_toast(redo: bool, name: Option<&str>) -> String {
47 match (redo, name) {
48 (false, Some(name)) => format!("Undid {name}"),
49 (true, Some(name)) => format!("Redid {name}"),
50 (false, None) => "Undone".to_string(),
51 (true, None) => "Redone".to_string(),
52 }
53}
54
55impl Player {
56 /// What Undo and Redo are called on a menu row or a toolbar tooltip: the action's own
57 /// name, except that they name the step they take back or walk forward to
58 /// ([`step_row_name`]).
59 pub(crate) fn action_name(&self, action: ActionId) -> String {
60 let session = self.session.as_ref();
61 match action {
62 ActionId::Undo => {
63 let depth = session.map_or(0, |s| s.undo_depth());
64 step_row_name(false, depth, session.and_then(|s| s.undo_label()))
65 }
66 ActionId::Redo => {
67 let depth = session.map_or(0, |s| s.redo_depth());
68 step_row_name(true, depth, session.and_then(|s| s.redo_label()))
69 }
70 _ => action.label().to_string(),
71 }
72 }
73
74 /// What an action does, wherever it was asked for -- a stroke, or the clip
75 /// menu item that names the same action. One table, so the two can never
76 /// come to mean different things. The step an edit pushes is named after it
77 /// ([`step_name`]), so Undo and Redo can say what they take back.
78 pub(crate) fn act(&mut self, action: ActionId, window: &mut Window, cx: &mut Context<Self>) {
79 let mark = self.session.as_mut().map(PlaybackSession::step_mark);
80 self.run_action(action, window, cx);
81 if let (Some(mark), Some(name)) = (mark, step_name(action))
82 && let Some(session) = self.session.as_mut()
83 {
84 session.name_step(mark, name);
85 }
86 }
87
88 /// Runs one write -- a card's, a gesture's -- and names the step it pushed, if it pushed
89 /// one: a live sample pushes none, so only the committing write names anything.
90 pub(crate) fn named_step<T>(&mut self, name: &str, write: impl FnOnce(&mut Self) -> T) -> T {
91 let mark = self.session.as_mut().map(PlaybackSession::step_mark);
92 let out = write(self);
93 if let (Some(mark), Some(session)) = (mark, self.session.as_mut()) {
94 session.name_step(mark, name);
95 }
96 out
97 }
98
99 /// The dispatch itself, behind [`Player::act`], which names the step it leaves.
100 fn run_action(&mut self, action: ActionId, window: &mut Window, cx: &mut Context<Self>) {
101 // Two doors, one oracle. This used to be the asymmetry the whole
102 // toolbar was built on: the buttons dimmed themselves off
103 // [`enable`] while the keyboard walked straight past it, so with no
104 // file open `s` toggled the snap and `v` added a track while the very
105 // same controls sat dim and *dead* to the pointer. Whatever refuses the
106 // button refuses the key, in the oracle's own words -- and a refusal
107 // that is silent from the keyboard is a bug the same size.
108 match self.enable(action, None) {
109 Enable::Yes => {}
110 // A state refusal is spoken: the thing exists and cannot happen
111 // *now*, which is exactly what a silent key press fails to say.
112 Enable::No(why) => {
113 self.notify_user(format!("{} — {why}", action.label()).into());
114 cx.notify();
115 return;
116 }
117 // A class refusal is not: the action does not exist for what is in
118 // front of the user, and `esc` with nothing exporting must not
119 // answer with a line about exports.
120 Enable::Hidden(_) => return,
121 }
122 // The one choke point for every action that changes what a save would
123 // write: the timeline's clips, the tracks that hold them, the subtitle
124 // tracks. Marked before the match rather than once per arm below --
125 // an autosave a beat early over a refusal (nothing to regroup, say)
126 // costs nothing a real edit would not have earned anyway, and one list
127 // here is the whole answer instead of fifteen scattered calls.
128 //
129 // The two exceptions are the history pair, whose doors answer "there was
130 // a step to take" and are gated in their own arms below: `^z` with
131 // nothing to undo is not a stroke that earned an autosave, and the
132 // save-on-close question over a project nobody has touched is exactly
133 // what the card doors' own gate exists to prevent.
134 //
135 // This list is the *action* doors only, and that is the class to mind
136 // when adding an edit: a control that reaches the session from a
137 // *click* -- the Clip tab's look chips and wheel, the settings rows,
138 // the library row's own menu -- is behind no action, so nothing here
139 // arms it. Such a door has to call `Player::mark_dirty` itself, on its
140 // own "the write took" gate, or the edit is invisible to autosave, to
141 // the ledger's `unsaved` ghost and to `Player::close_needs_answer`,
142 // which all read that one flag: the work is silently lost on close,
143 // with no prompt to answer.
144 if matches!(
145 action,
146 ActionId::Paste
147 | ActionId::Cut
148 | ActionId::Regroup
149 | ActionId::Detach
150 | ActionId::Reverse
151 | ActionId::NewSolid
152 | ActionId::NewGradient
153 | ActionId::NewCountdown
154 | ActionId::NewBars
155 | ActionId::NewTone
156 | ActionId::NewBarsAndTone
157 | ActionId::NewAdjustment
158 | ActionId::NewRectangle
159 | ActionId::NewEllipse
160 | ActionId::NewLine
161 | ActionId::NewArrow
162 | ActionId::NewTitle
163 | ActionId::Group
164 | ActionId::Delete
165 | ActionId::Lift
166 | ActionId::AddVideoLane
167 | ActionId::RemoveVideoLane
168 | ActionId::AddAudioLane
169 | ActionId::RemoveAudioLane
170 | ActionId::AddSubtitleLane
171 | ActionId::RemoveSubtitleLane
172 | ActionId::ImportSubtitles
173 // `Crossfade` and `Dissolve` are NOT here, and that is the
174 // rule rather than an omission: their doors answer for
175 // themselves ([`Player::crossfade_selected`],
176 // [`Player::dissolve_selected`]) and the clip-menu row reaches
177 // `dissolve_selected` directly, never through this table, so a
178 // list entry armed the key path and left the menu path armed by
179 // nothing.
180 //
181 // The three `Remove*Lane` entries ARE still here and are still
182 // wrong in the same way -- `remove_lane` refuses a track that
183 // holds clips and the last of its kind, and it now carries its
184 // own arm ([`Player::remove_lane`]) -- but taking them off is
185 // a wider pass over this list than this change makes, so they
186 // stay until it does. Until then each of those removals arms
187 // twice over, which is the lesser fault beside arming once for
188 // a removal that did not happen.
189 | ActionId::Visualizer
190 | ActionId::NestClips
191 | ActionId::BreakApart
192 | ActionId::NewSequence
193 | ActionId::DuplicateSequence
194 | ActionId::DeleteSequence
195 ) {
196 self.mark_dirty();
197 }
198 match action {
199 ActionId::Play => self.toggle_or_restart(cx),
200 // No session touched at all: the pump reads the flag itself at
201 // the one place that already knows the end was reached.
202 ActionId::Loop => {
203 self.loop_on = !self.loop_on;
204 cx.notify();
205 }
206 ActionId::PlayAround => self.play_around(cx),
207 // The clips' waveforms: kept with the project's view, so it reopens as it was left.
208 ActionId::ToggleWaveforms => {
209 self.waveforms = !self.waveforms;
210 self.save_view_state();
211 cx.notify();
212 }
213 // Sound while a ruler scrub is paused: kept with the view, like the waveforms.
214 ActionId::ToggleScrubAudio => {
215 self.scrub_audio = !self.scrub_audio;
216 self.save_view_state();
217 cx.notify();
218 }
219 // The shuttle (DESIGN §10.2): L plays forward and J backward, each press
220 // while it runs stepping the rate 1x, 2x, 4x; K stops.
221 ActionId::ShuttleBack => self.shuttle(false, cx),
222 ActionId::ShuttleStop => {
223 if let Some(session) = self.active_session_mut().filter(|s| s.is_playing()) {
224 session.pause();
225 session.set_rate(1.0);
226 }
227 cx.notify();
228 }
229 ActionId::ShuttleForward => self.shuttle(true, cx),
230 // The shortcuts sheet: the same toggle the `?` stroke makes.
231 ActionId::ShowKeys => {
232 if self.keys_open {
233 self.keys_open = false;
234 cx.notify();
235 } else {
236 self.show_keys(cx);
237 }
238 }
239 ActionId::About => {
240 self.about_open = !self.about_open;
241 cx.notify();
242 }
243 ActionId::StepBack => self.step(-1, cx),
244 ActionId::StepForward => self.step(1, cx),
245 // A second is however many frames this timeline runs at.
246 ActionId::JumpBack => self.step(-(self.fps.round() as i64), cx),
247 ActionId::JumpForward => self.step(self.fps.round() as i64, cx),
248 // The ends, as a step nothing can be far enough from.
249 ActionId::GoStart => self.step(i64::MIN, cx),
250 ActionId::GoEnd => self.step(i64::MAX, cx),
251 ActionId::GoToTime => self.open_time_entry(cx),
252 // Not a step at all: the grid these land on is the *source's*, and
253 // where the next one is depends on the file rather than on the rate.
254 ActionId::PrevSyncPoint => self.jump_sync(false, cx),
255 ActionId::NextSyncPoint => self.jump_sync(true, cx),
256 // While a library item is previewed the marks are the item's own
257 // (the source monitor's in/out); otherwise the timeline's range.
258 ActionId::SetIn if self.preview_session.is_some() => self.mark_source(true, cx),
259 ActionId::SetOut if self.preview_session.is_some() => self.mark_source(false, cx),
260 ActionId::ClearRange if self.preview_session.is_some() => self.clear_source_marks(cx),
261 ActionId::SetIn => self.set_in(cx),
262 ActionId::SetOut => self.set_out(cx),
263 ActionId::ClearRange => {
264 self.range = None;
265 cx.notify();
266 }
267 ActionId::RenderInOut => self.render_preview(false, cx),
268 ActionId::RenderAll => self.render_preview(true, cx),
269 ActionId::CancelRender => self.cancel_render(),
270 ActionId::DeleteRenderFiles => self.delete_render_files(cx),
271 ActionId::InsertSource => self.source_edit(engine::SourceEdit::Insert, cx),
272 ActionId::OverwriteSource => self.source_edit(engine::SourceEdit::Overwrite, cx),
273 ActionId::Export => self.open_export(cx),
274 // Asked before the first overwrite of a file this window never
275 // put there ([`Player::save_guarded`]); the window's own file
276 // saves straight through.
277 ActionId::Save => self.save_guarded(cx),
278 ActionId::ReloadProject => self.reload_request(cx),
279 ActionId::NewProject => self.open_new_project(cx),
280 ActionId::SaveVersion => self.open_save_version(cx),
281 ActionId::SaveTemplate => self.open_save_template(cx),
282 ActionId::ExportCaptions => self.open_export_captions(cx),
283 ActionId::Versions => self.open_versions(cx),
284 ActionId::CollectMedia => self.open_collect(cx),
285 ActionId::ProjectNotes => self.open_project_notes(cx),
286 ActionId::ExportTimelineOtio => self.export_timeline("otio", cx),
287 ActionId::ExportTimelineFcpxml => self.export_timeline("fcpxml", cx),
288 ActionId::ExportTimelineEdl => self.export_timeline("edl", cx),
289 ActionId::ImportTimelineOtio => self.pick_and_import(cx),
290 ActionId::Copy => self.copy_selected(),
291 ActionId::Paste => self.paste(cx),
292 ActionId::Cut => self.cut(cx),
293 ActionId::Regroup => self.regroup(cx),
294 ActionId::Crossfade => self.crossfade_selected(cx),
295 ActionId::Dissolve => self.dissolve_selected(cx),
296 ActionId::TransitionDissolve
297 | ActionId::TransitionDipBlack
298 | ActionId::TransitionDipWhite
299 | ActionId::TransitionWipeLeft
300 | ActionId::TransitionWipeRight
301 | ActionId::TransitionWipeUp
302 | ActionId::TransitionWipeDown
303 | ActionId::TransitionSlideLeft
304 | ActionId::TransitionSlideRight
305 | ActionId::TransitionSlideUp
306 | ActionId::TransitionSlideDown
307 | ActionId::TransitionPushLeft
308 | ActionId::TransitionPushRight
309 | ActionId::TransitionPushUp
310 | ActionId::TransitionPushDown
311 | ActionId::TransitionZoom => {
312 if let Some(kind) = action.transition_kind() {
313 self.set_transition_kind(kind, cx);
314 }
315 }
316 ActionId::Detach => self.detach(cx),
317 ActionId::Group => self.group(cx),
318 ActionId::Select => self.select_under_playhead(cx),
319 ActionId::SelectNext => self.select_step(true, cx),
320 ActionId::SelectPrev => self.select_step(false, cx),
321 ActionId::SelectAll => self.select_all(cx),
322 // Last in escape's precedence chain (render.rs): nothing else
323 // claimed the key, so it empties every selection the timeline
324 // holds -- clips, a picked gap, a title and a caption -- and the
325 // Clip tab goes back to what it shows with nothing picked.
326 // In player fullscreen Escape leaves it first, the way every video player does; the
327 // picks stay where they are until the next Escape.
328 ActionId::Deselect if self.player_fullscreen => self.run_action(ActionId::Fullscreen, window, cx),
329 ActionId::Deselect => self.clear_picks(cx),
330 // A picked gap is what Delete closes (DESIGN §7); a clip mark or
331 // nothing at all falls through to the clip path as before.
332 ActionId::Delete if self.gap_pick().is_some() => self.close_selected_gap(cx),
333 // A picked envelope key is what Delete takes out before a clip is.
334 ActionId::Delete if self.gain_pick.is_some() => {
335 self.gain_delete_pick(cx);
336 }
337 ActionId::Delete => self.delete_selected(cx),
338 ActionId::Lift => self.lift_selected(cx),
339 ActionId::CloseGap => self.close_gap_here(cx),
340 ActionId::Freeze => self.freeze_frame(cx),
341 ActionId::PasteAttributes => self.paste_attributes(
342 &[Part::Color, Part::Effects, Part::Transform, Part::Speed, Part::Audio],
343 cx,
344 ),
345 ActionId::PasteColor => self.paste_attributes(&[Part::Color], cx),
346 ActionId::PasteEffects => self.paste_attributes(&[Part::Effects], cx),
347 ActionId::PasteTransform => self.paste_attributes(&[Part::Transform], cx),
348 ActionId::PasteSpeed => self.paste_attributes(&[Part::Speed], cx),
349 ActionId::PasteAudio => self.paste_attributes(&[Part::Audio], cx),
350 ActionId::MatchFrame => self.match_frame(cx),
351 ActionId::ReplaceEdit => self.replace_edit(cx),
352 ActionId::SelectForward => self.select_forward(false, cx),
353 ActionId::SelectForwardAll => self.select_forward(true, cx),
354 ActionId::ExtendAudio => self.split_edit(true, cx),
355 ActionId::CutSelectedWords => self.delete_selected_words(cx),
356 ActionId::ExtendVideo => self.split_edit(false, cx),
357 ActionId::NudgeBack => self.nudge_selected(-1, cx),
358 ActionId::NudgeForward => self.nudge_selected(1, cx),
359 ActionId::NudgeBack10 => self.nudge_selected(-10, cx),
360 ActionId::NudgeForward10 => self.nudge_selected(10, cx),
361 ActionId::Color => self.open_color(cx),
362 ActionId::AutoColour => self.auto_colour(cx),
363 ActionId::SaveLook => {
364 if self.color_open.is_none() {
365 self.open_color(cx);
366 }
367 self.begin_look_save(cx);
368 }
369 ActionId::CompareOff => self.set_compare(crate::viewer_view::Compare::Off, cx),
370 ActionId::CompareSplit => self.set_compare(crate::viewer_view::Compare::Split, cx),
371 ActionId::CompareSide => self.set_compare(crate::viewer_view::Compare::Side, cx),
372 ActionId::Transform => self.open_transform(cx),
373 ActionId::Effects => self.open_effects(cx),
374 ActionId::KeyPlacement => self.toggle_key_here(engine::project::KeyKind::Placement, cx),
375 ActionId::KeyOpacity => self.toggle_key_here(engine::project::KeyKind::Opacity, cx),
376 ActionId::KeyColor => self.toggle_key_here(engine::project::KeyKind::Color, cx),
377 ActionId::KeyEasing => self.open_key_easing(self.ledger_anchor(LedgerItem::Clip), cx),
378 ActionId::Fit => self.open_fit_list(self.ledger_anchor(LedgerItem::Clip), cx),
379 ActionId::Resolution => self.open_picker(Pick::Resolution, self.ledger_anchor(LedgerItem::Size), cx),
380 // The playhead is what a key zoom is aimed at: it is the one place
381 // on the timeline the user is certainly looking at, and keeping it
382 // still is what every editor does.
383 ActionId::ZoomIn => self.zoom(ZOOM_STEP, None, cx),
384 ActionId::ZoomOut => self.zoom(1. / ZOOM_STEP, None, cx),
385 ActionId::ZoomFit => self.zoom_fit(cx),
386 ActionId::ZoomToSelection => self.zoom_to_selection(cx),
387 ActionId::TrackSmall => self.set_all_track_sizes(crate::ui::bench_stance::TrackSize::Small, cx),
388 ActionId::TrackMedium => self.set_all_track_sizes(crate::ui::bench_stance::TrackSize::Medium, cx),
389 ActionId::TrackLarge => self.set_all_track_sizes(crate::ui::bench_stance::TrackSize::Large, cx),
390 ActionId::TracksSmaller => self.step_track_sizes(false, cx),
391 ActionId::TracksLarger => self.step_track_sizes(true, cx),
392 ActionId::Undo => {
393 let name = self.session.as_ref().and_then(|s| s.undo_label().map(str::to_string));
394 if self.undo(cx) {
395 self.mark_dirty();
396 self.settle_saved_point();
397 self.notify_user(step_toast(false, name.as_deref()).into());
398 }
399 }
400 ActionId::Redo => {
401 let name = self.session.as_ref().and_then(|s| s.redo_label().map(str::to_string));
402 if self.redo(cx) {
403 self.mark_dirty();
404 self.settle_saved_point();
405 self.notify_user(step_toast(true, name.as_deref()).into());
406 }
407 }
408 ActionId::History => self.open_history(cx),
409 ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx),
410 ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx),
411 // The last track of that kind: the one the add key put there, so the
412 // two strokes undo each other press for press. Any other track goes
413 // through the × in its own header.
414 ActionId::RemoveVideoLane => self.remove_last_lane(LaneKind::Video, cx),
415 ActionId::RemoveAudioLane => self.remove_last_lane(LaneKind::Audio, cx),
416 // The third kind of track, added and taken back exactly as the two
417 // above it: what a caption is dragged onto. The words themselves
418 // arrive by the door below, which places nothing.
419 ActionId::AddSubtitleLane => self.add_lane(LaneKind::Subtitle, cx),
420 ActionId::RemoveSubtitleLane => self.remove_last_lane(LaneKind::Subtitle, cx),
421 // The chooser the palette's own button opens: a file's tracks into
422 // the list, the file itself joining nothing.
423 ActionId::ImportSubtitles => self.pick_and_add_subtitles(cx),
424 ActionId::AddFiles => self.pick_and_import(cx),
425 ActionId::OpenProject => self.pick_open_project(cx),
426 ActionId::PasteFilePath => self.paste_file_path(cx),
427 ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx),
428 ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),
429 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),
430 ActionId::Equalizer => self.open_eq(cx),
431 ActionId::Speed => self.open_speed(cx),
432 ActionId::Reverse => self.toggle_reverse(cx),
433 ActionId::ClipEnabled => self.toggle_clip_enabled(cx),
434 ActionId::ClipLabel => self.open_label_list(cx),
435 ActionId::NewSolid
436 | ActionId::NewGradient
437 | ActionId::NewCountdown
438 | ActionId::NewBars
439 | ActionId::NewAdjustment
440 | ActionId::NewRectangle
441 | ActionId::NewEllipse
442 | ActionId::NewLine
443 | ActionId::NewArrow => self.new_generator(action, cx),
444 ActionId::NewTone | ActionId::NewBarsAndTone => self.new_tone(action, cx),
445 ActionId::NewTitle => self.new_title(cx),
446 ActionId::NewBin => self.new_bin(0, Vec::new(), cx),
447 ActionId::NewBinInside => self.new_bin_inside_selected(cx),
448 ActionId::RenameBin => self.rename_selected_bin(cx),
449 ActionId::RemoveBin => self.remove_selected_bin(cx),
450 ActionId::ToggleFavourite => self.toggle_favourite_picked(cx),
451 ActionId::MoveToBin => self.bin_picker_here(cx),
452 ActionId::ShowFavourites => self.show_favourites(true, cx),
453 ActionId::ShowAllMedia => self.show_favourites(false, cx),
454 ActionId::SpeedRampUp => self.set_ramp_preset(RampPreset::Up, cx),
455 ActionId::SpeedRampDown => self.set_ramp_preset(RampPreset::Down, cx),
456 ActionId::SpeedRampSlowFastSlow => self.set_ramp_preset(RampPreset::SlowFastSlow, cx),
457 ActionId::SpeedRampFastSlowFast => self.set_ramp_preset(RampPreset::FastSlowFast, cx),
458 ActionId::SpeedRampKey => self.add_ramp_key(cx),
459 ActionId::SpeedRampClear => self.clear_ramp(cx),
460 ActionId::Silence => self.open_silence(cx),
461 ActionId::Normalize => self.open_tools(crate::player::tools::Tool::Normalize, cx),
462 // Starts the listening straight away; the Tools card opens under it so the
463 // progress (and any plain reason it cannot start) is on screen.
464 ActionId::Captions => {
465 self.open_tools(crate::player::tools::Tool::Captions, cx);
466 self.start_listening(false, cx);
467 }
468 ActionId::Fillers => self.open_tools(crate::player::tools::Tool::Fillers, cx),
469 ActionId::Voiceover => self.open_tools(crate::player::tools::Tool::Voiceover, cx),
470 ActionId::RecordVoiceover => self.open_record_voiceover(cx),
471 ActionId::Visualizer => self.create_visualizer(cx),
472 ActionId::MarkBeats => self.open_beats(cx),
473 ActionId::Reframe => self.reframe_selected(cx),
474 ActionId::TrackMask => self.track_selected_mask(cx),
475 ActionId::NestClips => self.nest_selected(cx),
476 ActionId::CreateMulticam => self.create_multicam_selected(cx),
477 ActionId::FlattenMulticam => self.flatten_multicam_selected(cx),
478 ActionId::ToggleAngleMonitor => self.toggle_angle_monitor(cx),
479 ActionId::Angle1 => self.switch_angle_here(1, cx),
480 ActionId::Angle2 => self.switch_angle_here(2, cx),
481 ActionId::Angle3 => self.switch_angle_here(3, cx),
482 ActionId::Angle4 => self.switch_angle_here(4, cx),
483 ActionId::Angle5 => self.switch_angle_here(5, cx),
484 ActionId::Angle6 => self.switch_angle_here(6, cx),
485 ActionId::Angle7 => self.switch_angle_here(7, cx),
486 ActionId::Angle8 => self.switch_angle_here(8, cx),
487 ActionId::Angle9 => self.switch_angle_here(9, cx),
488 ActionId::BreakApart => self.break_apart_selected(cx),
489 ActionId::OpenCompound => self.open_compound_selected(cx),
490 ActionId::CloseCompound => self.close_compound(cx),
491 ActionId::NewSequence => self.new_sequence(cx),
492 ActionId::DuplicateSequence => self.duplicate_sequence(cx),
493 ActionId::RenameSequence => self.begin_seq_edit(cx),
494 ActionId::DeleteSequence => self.delete_sequence(cx),
495 ActionId::RenameLane => {
496 // From the palette there is no head to name: the selected clip's track, else V1.
497 let lane = self.selected.anchor().map_or(Lane::V1, |(lane, _)| lane);
498 self.begin_lane_edit(lane, cx)
499 }
500 ActionId::Mix => self.open_mix(None, cx),
501 ActionId::CleanVoice => match self.voice_target_lane() {
502 Some(lane) => self.clean_mix_voice(lane, engine::voice::Strength::Medium, cx),
503 None => {
504 self.notify_user("Nothing to clean — no audio track has sound".into());
505 cx.notify();
506 }
507 },
508 ActionId::VoiceDynamics => {
509 let lane = self.voice_target_lane();
510 self.open_mix(lane, cx);
511 if let Some(lane) = lane.filter(|&l| !self.mix_voice_open(l)) {
512 self.toggle_voice_section(lane, cx);
513 }
514 }
515 ActionId::SubtitleStyle => self.open_subtitle_style(cx),
516 ActionId::ToggleSnap => self.toggle_snap(cx),
517 ActionId::ToggleSubtitles => self.toggle_subtitles(cx),
518 ActionId::ToggleProxies => self.toggle_proxies(cx),
519 ActionId::ToggleAutoProxies => self.toggle_auto_proxies(cx),
520 // The keyboard's door to the same list the toolbar button opens.
521 // At the window's corner, since a stroke names no place -- and
522 // [`menu_at`] keeps it on screen from there.
523 ActionId::Theme => self.open_picker(Pick::Theme, Point::default(), cx),
524 ActionId::AccentColour => self.open_picker(Pick::Accent, Point::default(), cx),
525 ActionId::ToggleOutputWindow => self.toggle_output_window(cx),
526 ActionId::OutputDisplay => self.open_picker(Pick::OutputDisplay, Point::default(), cx),
527 ActionId::ViewZoom => {
528 let at = self.viewer_anchor(0);
529 self.picker_under(Pick::ViewZoom, at, cx)
530 },
531 ActionId::PlaybackQuality => {
532 let at = self.viewer_anchor(1);
533 self.picker_under(Pick::ViewQuality, at, cx)
534 },
535 ActionId::GuideMask => {
536 let at = self.viewer_anchor(3);
537 self.picker_under(Pick::ViewMask, at, cx)
538 },
539 ActionId::GuideStyle => {
540 let at = self.viewer_anchor(2);
541 self.picker_under(Pick::ViewGuides, at, cx)
542 }
543 // Not the window's own toggle alone -- every consumer video
544 // player fullscreens the *picture*, chrome and all, not just the
545 // OS frame around it -- so this flips both: `player_fullscreen`
546 // is what [`crate::render`] reads to draw the picture only, and
547 // the platform's own toggle is what actually grows the window to
548 // the monitor. The two are asked to agree rather than one being
549 // derived from the other, because a compositor keybind can move
550 // `window.is_fullscreen()` without this action ever firing.
551 ActionId::Fullscreen => {
552 self.player_fullscreen = !self.player_fullscreen;
553 if window.is_fullscreen() != self.player_fullscreen {
554 window.toggle_fullscreen();
555 }
556 }
557 // The ring's own door: nothing else in the app ever calls
558 // `window.focus` on one of the three surface handles
559 // (`ui::stance::Surface`), so without this the Tab handlers those
560 // surfaces carry (`stance.rs`'s `bench`, `dock_stance.rs`'s
561 // `cycle_on_key_down`) are unreachable dead code -- the ring never
562 // starts. Lands on the cycle's first stop (`stance::SURFACE_CYCLE`
563 // -- the dock); a second Tab from there walks it same as ever.
564 // F6 walks the same cycle Tab does, one panel per press, from wherever the focus is
565 // now (the media panel when it is on none of them), and names where it landed.
566 ActionId::FocusPanels => {
567 use crate::ui::stance::{Surface, next_surface};
568 let now = [Surface::Dock, Surface::Bench, Surface::Inspector]
569 .into_iter()
570 .find(|s| self.focus_handle(*s).is_focused(window));
571 let to = now.map_or(Surface::Dock, |s| next_surface(s, false));
572 self.focus_surface(to, window, cx);
573 let name = match to {
574 Surface::Bench => "the timeline",
575 Surface::Dock if self.dock_src_active => "Media",
576 Surface::Dock | Surface::Inspector => "the side panel",
577 };
578 self.notify_user(format!("Focus moved to {name}").into());
579 }
580 // `^esc` (or whatever the keymap now binds it to) reaches here
581 // through the plain `act()` dispatch even while an export is
582 // running (`ui::stance`'s key handler deliberately leaves
583 // `exporting()` out of its modal guard so this keeps working):
584 // was a no-op until now, the real gap the progress card's own
585 // "the chord as well" doc promised.
586 ActionId::CancelExport => self.cancel_export(),
587 ActionId::ShowActions => self.show_actions(cx),
588 ActionId::Settings => self.open_settings(cx),
589 ActionId::Screenshot => self.take_screenshot(cx),
590 // Cut machinery (DESIGN.md §6): the subject cut is the marked
591 // clip ([`Selection::anchor`]) -- the oracle already refused
592 // every one of these with nothing marked, so an anchor is here
593 // to read.
594 ActionId::AddMarker => self.add_marker_here(cx),
595 ActionId::MarkerHere => self.add_marker_at_menu(cx),
596 ActionId::RenameMarker => self.rename_marker_at_pick(cx),
597 ActionId::DeleteMarker => self.delete_marker_at_pick(cx),
598 ActionId::PlayheadHere => self.playhead_at_menu(cx),
599 ActionId::NextMarker => self.jump_marker(true, cx),
600 ActionId::PrevMarker => self.jump_marker(false, cx),
601 ActionId::Markers => self.open_markers(cx),
602 ActionId::WalkCutNext => self.walk_cut(true, cx),
603 ActionId::WalkCutPrev => self.walk_cut(false, cx),
604 ActionId::WalkCutNext10 => self.walk_cut_stride(true, 10, cx),
605 ActionId::WalkCutPrev10 => self.walk_cut_stride(false, 10, cx),
606 // `[` `]` close in on the clip like the brackets they are: `[`
607 // trims a frame off the head, `]` a frame off the tail -- no-aim,
608 // frame detents, clamped to the room the engine already answers
609 // ([`nudge_edge`]), which is what makes them work at any zoom
610 // down to a 4px clip with nothing to click.
611 ActionId::TrimIn => self.nudge_cut(Edge::Start, 1, cx),
612 ActionId::TrimOut => self.nudge_cut(Edge::End, -1, cx),
613 ActionId::LoopTrim => self.toggle_loop_trim(cx),
614 // Trim-to-playhead (debt #42): the same `Edge::Start`/`Edge::End`
615 // split as the nudge pair above, at the playhead's frame instead
616 // of a one-frame detent.
617 ActionId::TrimInToPlayhead => self.trim_cut_to_playhead(Edge::Start, false, cx),
618 ActionId::TrimOutToPlayhead => self.trim_cut_to_playhead(Edge::End, false, cx),
619 ActionId::RippleTrimInToPlayhead => self.trim_cut_to_playhead(Edge::Start, true, cx),
620 ActionId::RippleTrimOutToPlayhead => self.trim_cut_to_playhead(Edge::End, true, cx),
621 // Roll, slip and slide at frame detents, the keyboard's version of
622 // the shift-drags ([`Player::pro_nudge`]).
623 ActionId::RollBack => self.pro_nudge(ProKind::Roll, -1, cx),
624 ActionId::RollForward => self.pro_nudge(ProKind::Roll, 1, cx),
625 ActionId::SlipBack => self.pro_nudge(ProKind::Slip, -1, cx),
626 ActionId::SlipForward => self.pro_nudge(ProKind::Slip, 1, cx),
627 ActionId::SlideBack => self.pro_nudge(ProKind::Slide, -1, cx),
628 ActionId::SlideForward => self.pro_nudge(ProKind::Slide, 1, cx),
629 }
630 }
631
632 /// Dispatches a type-level keyboard verb from its concrete lane header.
633 /// The key still acts on the last lane of its kind; a header click must
634 /// keep the lane the hand named, so it enters through this targeted door.
635 pub(crate) fn act_lane(&mut self, action: ActionId, lane: Lane, cx: &mut Context<Self>) {
636 match enable_lane(action, lane, self.ctx(None)) {
637 Enable::Yes => {}
638 Enable::No(why) => {
639 self.notify_user(format!("{} — {why}", action.label()).into());
640 cx.notify();
641 return;
642 }
643 Enable::Hidden(_) => return,
644 }
645 match action {
646 ActionId::Mix => self.open_mix(Some(lane), cx),
647 ActionId::RenameLane => self.begin_lane_edit(lane, cx),
648 // The arm rides the door's own answer, like every arm in this
649 // window: `remove_lane` refuses a track that still holds clips or
650 // captions, and the last track of its kind, and arming before the
651 // ask lit the ledger's `unsaved` ghost, wrote a sidecar and put the
652 // close prompt up over a project whose bytes had not moved.
653 ActionId::RemoveVideoLane | ActionId::RemoveAudioLane => self.remove_lane(lane, cx),
654 _ => unreachable!("only lane-header actions reach act_lane"),
655 }
656 }
657
658 /// Says something to the user. The one door: every message in this editor
659 /// comes through here, so "queued rather than overwritten" is a property of
660 /// the field and not of seventy call sites remembering to be polite.
661 ///
662 /// A repeat of what is already at the back is dropped -- holding a key that
663 /// refuses would otherwise fill the queue with one sentence, and the count
664 /// on the bar would be a count of how long the key was held.
665 pub(crate) fn notify_user(&mut self, message: SharedString) {
666 if !message.starts_with(EXPORT_DONE) {
667 push_notice(&mut self.notices, message);
668 return;
669 }
670 // An export's outcome carries the way to its file: the toast's buttons
671 // play it or reveal it (DESIGN §8). Every other message has no button.
672 let path = self.export_path.clone();
673 self.notify_user_actions(
674 message,
675 vec![
676 ToastAction::Play(path.clone()),
677 ToastAction::ShowInFolder(path),
678 ],
679 );
680 }
681
682 /// [`Player::notify_user`] for a message whose toast has a button: the one
683 /// door that takes an action, and otherwise the same queue and the same
684 /// policy.
685 pub(crate) fn notify_user_action(&mut self, message: SharedString, action: ToastAction) {
686 self.notify_user_actions(message, vec![action]);
687 }
688
689 /// [`Player::notify_user_action`] for a toast with up to two buttons, drawn
690 /// in the order given.
691 pub(crate) fn notify_user_actions(&mut self, message: SharedString, actions: Vec<ToastAction>) {
692 let tone = Tone::of(&message);
693 push_toast(&mut self.notices, message, tone, actions);
694 }
695
696 /// A toast's button was pressed: the toast goes, and the action at `index`
697 /// runs. Any other button on it goes with the toast.
698 pub(crate) fn toast_action(&mut self, id: u64, index: usize, cx: &mut Context<Self>) {
699 let Some(action) = self
700 .notices
701 .iter()
702 .find(|toast| toast.id == id)
703 .and_then(|toast| toast.actions.get(index).cloned())
704 else {
705 return;
706 };
707 remove_toast(&mut self.notices, id);
708 match action {
709 ToastAction::Undo => {
710 if self.undo(cx) {
711 self.mark_dirty();
712 }
713 }
714 // The refusal was about the lock, so the lock is what goes: one
715 // undo step, the same as the head's own switch.
716 ToastAction::Unlock(lane) => self.set_lane_switch(lane, Switch::Locked, false, cx),
717 // Another process starting: off the UI thread, as the library's
718 // own Reveal does.
719 ToastAction::ShowInFolder(path) => {
720 cx.background_executor()
721 .spawn(async move { show_in_file_manager(&path) })
722 .detach();
723 }
724 // Same shape as Reveal: the player is another process, so it is
725 // started off the UI thread and nothing here waits on it.
726 ToastAction::Reload => self.reload_from_disk(cx),
727 // The toast is the whole of it: the window keeps what it holds.
728 ToastAction::KeepMine => {}
729 ToastAction::Recover => self.recover_from_sidecar(cx),
730 ToastAction::Discard => self.discard_recovery(),
731 ToastAction::SaveThenOpen(path) => {
732 self.save_project(cx);
733 // A refused save keeps the edits: the other project waits.
734 if !self.edited_since_save {
735 self.import(&path, cx);
736 }
737 }
738 ToastAction::OpenDiscarding(path) => {
739 // The edits are being let go, so their autosave must not come back as "recovery".
740 for armed in [true, false] {
741 if let Some(autosave) = Self::autosave_target(&self.project_path, armed) {
742 let _ = std::fs::remove_file(autosave);
743 }
744 }
745 self.autosave_dirty = false;
746 self.edited_since_save = false;
747 self.import(&path, cx);
748 }
749 ToastAction::Play(path) => {
750 cx.background_executor()
751 .spawn(async move { open_in_default_player(&path) })
752 .detach();
753 }
754 }
755 cx.notify();
756 }
757
758 /// A toast leaves by its own ✕, or by its timer. A missing id is not an
759 /// error: the timer for a toast that was already dismissed fires into
760 /// nothing, and that is the point of the id.
761 pub(crate) fn dismiss_toast(&mut self, id: u64, cx: &mut Context<Self>) {
762 if remove_toast(&mut self.notices, id) {
763 cx.notify();
764 }
765 }
766
767 /// The magnet off and on again, in words: a snap that stops working
768 /// silently reads as a bug, and one that starts working silently reads as
769 /// one too. The line goes with it -- nothing is being promised any more.
770 pub(crate) fn toggle_snap(&mut self, cx: &mut Context<Self>) {
771 self.snap = !self.snap;
772 self.snap_cue = None;
773 self.ghost.clear();
774 self.notify_user(match self.snap {
775 true => "Snap on".into(),
776 false => "Snap off".into(),
777 });
778 cx.notify();
779 }
780
781 /// The command palette (DESIGN §4.4), from Ctrl+K, the spine's `commands`
782 /// or a menu row. It opens empty with its field ready for typing, and the
783 /// whole list under it.
784 pub(crate) fn show_actions(&mut self, cx: &mut Context<Self>) {
785 self.palette_open = true;
786 self.palette_query.clear();
787 self.palette_sel = 0;
788 self.palette_scroll.set_offset(point(px(0.), px(0.)));
789 // One card at a time, the rule the other cards follow.
790 self.export_open = false;
791 cx.notify();
792 }
793
794 /// The keys list, from the spine's `?`: the dock swings to its KEYS tab,
795 /// scrolled to the top -- a list that opens where the last look left it
796 /// would hide most of itself for a reason nobody remembers.
797 pub(crate) fn show_keys(&mut self, cx: &mut Context<Self>) {
798 self.keys_open = true;
799 self.scroll_keys(None);
800 // One card at a time, the rule the other cards follow.
801 self.export_open = false;
802 self.transcript_open = false;
803 cx.notify();
804 }
805
806 /// The palette's rows for what its field holds now, best match first.
807 pub(crate) fn palette_list(&self) -> Vec<crate::menus::PaletteRow> {
808 crate::menus::palette_rows(&self.palette_query, |a| self.enable(a, None))
809 }
810
811 /// Moves the palette highlight by `by` rows, clamped to the list, and
812 /// scrolls it into view.
813 pub(crate) fn palette_move(&mut self, by: isize) {
814 let rows = self.palette_list();
815 if rows.is_empty() {
816 self.palette_sel = 0;
817 return;
818 }
819 let last = rows.len() - 1;
820 self.palette_sel = (self.palette_sel as isize + by).clamp(0, last as isize) as usize;
821 let grouped = self.palette_query.trim().is_empty();
822 let child = crate::menus::palette_child_index(&rows, self.palette_sel, grouped);
823 self.palette_scroll.scroll_to_item(child);
824 }
825
826 /// Runs the highlighted palette row. A runnable row closes the palette
827 /// first, so an action that opens a card is not drawn under it. A refused
828 /// row goes through [`Player::act`], which says why as a toast, and the
829 /// palette stays open for another pick.
830 pub(crate) fn palette_run(&mut self, window: &mut Window, cx: &mut Context<Self>) {
831 // The design kit's gallery is reached by typing its name; it is no
832 // action, so it has no row, no key and no menu entry.
833 if self.palette_query.trim().eq_ignore_ascii_case(crate::ui::gallery::PALETTE_PHRASE) {
834 self.palette_open = false;
835 self.palette_query.clear();
836 crate::ui::gallery::set_open(true);
837 cx.notify();
838 return;
839 }
840 let rows = self.palette_list();
841 let Some(row) = rows.get(self.palette_sel).copied() else {
842 cx.notify();
843 return;
844 };
845 if crate::menus::palette_closes_on_run(row) {
846 self.palette_open = false;
847 self.palette_query.clear();
848 // Command search reopening itself from its own row would be a
849 // palette that cannot be left by picking from it.
850 if row.action == ActionId::ShowActions {
851 cx.notify();
852 return;
853 }
854 }
855 self.act(row.action, window, cx);
856 cx.notify();
857 }
858
859 /// Moves the actions card's row list by `by` pixels, or puts it back at the
860 /// top (`None`). Back to the top after every keystroke that changes the
861 /// search: a filtered list is shorter than the offset a scrolled one left
862 /// behind, and a card showing the empty space past its last row reads as a
863 /// search that found nothing.
864 ///
865 /// Clamped to what there is to scroll, so the list cannot be pushed off
866 /// either end -- `max_offset` is what the last paint measured, which is the
867 /// only place that number exists.
868 pub(crate) fn scroll_keys(&self, by: Option<f32>) {
869 let at = match by {
870 Some(by) => (f32::from(self.keys_scroll.offset().y) + by)
871 .clamp(-f32::from(self.keys_scroll.max_offset().height), 0.),
872 None => 0.,
873 };
874 self.keys_scroll.set_offset(point(px(0.), px(at)));
875 }
876
877 /// The cues over the picture, off and on. Says which it is now *and* how
878 /// much is placed underneath: a toggle whose answer is invisible -- the
879 /// playhead between two cues, or a palette full of tracks nobody dragged
880 /// onto a lane -- would read as broken.
881 pub(crate) fn toggle_subtitles(&mut self, cx: &mut Context<Self>) {
882 self.subs_on = !self.subs_on;
883 // Lane facts and not the picked row: what draws is what is *placed*
884 // ([`Player::subtitle_overlay`]), so naming the palette selection here
885 // named a track the toggle never touched.
886 let placed = self.placed_captions();
887 self.notify_user(subtitle_toggle_notice(self.subs_on, placed).into());
888 cx.notify();
889 }
890
891 /// How many captions the subtitle lanes hold, all lanes together: what the
892 /// toggle and the toolbar's own label are about, now that the picture reads
893 /// the lanes rather than a pick ([`Player::subtitle_overlay`]). Zero with no
894 /// timeline, and zero for a palette full of tracks nobody placed -- both
895 /// show nothing, so both read "No subs".
896 pub(crate) fn placed_captions(&self) -> usize {
897 let Some(session) = self.session.as_ref() else {
898 return 0;
899 };
900 session
901 .subtitle_lanes()
902 .into_iter()
903 .map(|lane| session.sub_lane(lane).len())
904 .sum()
905 }
906
907 /// Whether the editor can be asked for `action` right now, and why not when
908 /// it cannot. `on` is the clip the question is about -- the one a clip menu
909 /// was opened on -- and `None` asks about the marked clip instead, which is
910 /// what a menu that hangs over no clip in particular means by "this one".
911 ///
912 /// The player's half of [`enable`]: it reads the state, the table decides.
913 pub(crate) fn enable(&self, action: ActionId, on: Option<(Lane, usize)>) -> Enable {
914 // A display list of one has nothing to choose between: the row is not drawn.
915 if action == ActionId::OutputDisplay && self.output_displays.len() < 2 {
916 return Enable::Hidden("only one display");
917 }
918 // A transition joins the clip to the one after it, so a picture clip
919 // with nothing right after it has no join to draw: said before the
920 // table, as the state of this moment, the way the menu row says why.
921 if action.transition_kind().is_some() && self.lacks_successor(on) {
922 return Enable::No("no clip after this one");
923 }
924 enable(action, self.ctx(on))
925 }
926
927 /// Whether the picture clip the question is about (or the marked one) has
928 /// no clip butted up against its right-hand end on its lane. Sound and
929 /// caption lanes answer `false`: the table refuses those by their class.
930 fn lacks_successor(&self, on: Option<(Lane, usize)>) -> bool {
931 let Some(session) = &self.session else {
932 return false;
933 };
934 let Some((lane, idx)) = on.or(self.selected.anchor()) else {
935 return false;
936 };
937 if lane.kind != LaneKind::Video {
938 return false;
939 }
940 let clips = session.lane_clips(lane);
941 clips.get(idx).is_some_and(|clip| !clips.get(idx + 1).is_some_and(|next| next.start == clip.end()))
942 }
943
944 /// The state every one of those questions is asked against, read off the
945 /// player once: [`menu_items`] filters a whole menu with it, so the rows a
946 /// menu draws and the answers it dims them by come from the same reading.
947 pub(crate) fn ctx(&self, on: Option<(Lane, usize)>) -> Ctx {
948 let Some(session) = &self.session else {
949 return Ctx::default();
950 };
951 let on = on.or(self.selected.anchor());
952 let clip =
953 on.and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| (clip.clone(), lane)));
954 let caption = on.is_some_and(|(lane, idx)| {
955 lane.kind == LaneKind::Subtitle && idx < session.sub_lane(lane).len()
956 });
957 // The selection's shape, over the picks that still name something:
958 // how many placements, and on how many lanes. The lane count is the
959 // manual group's one-per-lane question -- equal counts say a group, a
960 // short one says a lane is picked twice.
961 let (picks, _) = self.marks();
962 let mut lanes = Vec::new();
963 for &(lane, _) in &picks {
964 if !lanes.contains(&lane) {
965 lanes.push(lane);
966 }
967 }
968 let pick_lanes = lanes.len();
969 Ctx {
970 clip: clip.clone(),
971 // A selected title is taken off by Delete the way a picked gap is closed by it.
972 gap: self.gap_pick().is_some() || self.title_target().is_some(),
973 gap_here: self.gap_here().is_some(),
974 clip_here: !self.under_playhead().is_empty(),
975 words: self.transcript.selection().is_some(),
976 rendering: self.render.as_ref().is_some_and(|(job, _)| !job.is_finished()),
977 asset: self.selected_asset.is_some() || self.source_target.is_some(),
978 // The same pair read in the other index space: a subtitle lane's
979 // own, where the box that was clicked is a caption.
980 caption,
981 caption_link: caption
982 .then(|| {
983 on.and_then(|(lane, idx)| session.sub_lane(lane).get(idx))
984 .and_then(|s| s.link)
985 })
986 .flatten(),
987 image: clip.as_ref().is_some_and(|(clip, _)| {
988 session
989 .sources()
990 .get(clip.source)
991 .is_some_and(|s| engine::is_image(&s.path))
992 }),
993 // The probed stream table again, this time asking the other
994 // question of it: an empty list is a silent file
995 // ([`Player::streams`]), and a clip cut from one has no sound to
996 // scan whatever lane it sits on -- said before the row is drawn
997 // rather than after the scan comes back empty
998 // ([`Player::start_silence_scan`]'s `Ok(None)` arm).
999 no_sound: clip.as_ref().is_some_and(|(clip, _)| {
1000 session
1001 .sources()
1002 .get(clip.source)
1003 .is_some_and(|s| self.streams.get(&s.path).is_some_and(Vec::is_empty))
1004 }),
1005 // The clip or caption the question is about, or anything picked,
1006 // sits on a locked lane ([`oracle::enable`] refuses the edits).
1007 locked: on.is_some_and(|(lane, _)| session.lane_locked(lane))
1008 || lanes.iter().any(|&lane| session.lane_locked(lane)),
1009 playhead: frame_at(session.now(), self.fps),
1010 timeline: true,
1011 clipboard: !self.clipboard.is_empty(),
1012 subtitles: !session.subtitles().is_empty(),
1013 playable: !nothing_to_play(self.active_session()),
1014 exporting: self.exporting().is_some(),
1015 picks: picks.len(),
1016 pick_lanes,
1017 nothing_to_undo: session.undo_depth() == 0,
1018 nothing_to_redo: session.redo_depth() == 0,
1019 alone: clip.as_ref().is_some_and(|(c, _)| {
1020 // Its link is shared by no other clip (the lane's own index
1021 // is the clip itself).
1022 c.link.is_some_and(|id| {
1023 session
1024 .lanes()
1025 .into_iter()
1026 .map(|l| {
1027 session
1028 .lane_clips(l)
1029 .iter()
1030 .filter(|o| o.link == Some(id))
1031 .count()
1032 + session.sub_lane(l).iter().filter(|s| s.link == Some(id)).count()
1033 })
1034 .sum::<usize>()
1035 <= 1
1036 })
1037 }),
1038 no_partner: on.is_some_and(|(lane, idx)| {
1039 clip.is_some() && crate::timeline_math::span_partner(session, lane, idx).is_none()
1040 }),
1041 compound: clip.as_ref().is_some_and(|(c, _)| engine::project::is_sequence_source(c.source)),
1042 // Any piece of a multicam clip counts: the one asked about, any picked, or (with
1043 // nothing selected) the one under the playhead.
1044 multicam: on.is_some_and(|(lane, idx)| session.multicam_at(lane, idx).is_some())
1045 || picks.iter().any(|&(lane, idx)| session.multicam_at(lane, idx).is_some())
1046 || (on.is_none() && self.multicam_here().is_some()),
1047 media_picks: self.picked_sources().len(),
1048 monitor: self.angle_monitor,
1049 angles_here: self.multicam_here().map_or(0, |u| u.names.len()),
1050 sequences: session.sequences().len(),
1051 sequence_used: session.sequences().iter().any(|q| q.active && q.used > 0),
1052 parent: !self.seq_trail.is_empty(),
1053 no_join: !session.lanes().into_iter().any(|l| {
1054 rejoinable(session.lane_clips(l), frame_at(session.now(), self.fps))
1055 }),
1056 }
1057 }
1058
1059 /// The same reading for a library row: whether this file can join this
1060 /// timeline -- the very answer the list greys the row by, so the menu over a
1061 /// row and the row under it cannot disagree -- and how many clips play it.
1062 /// [`Player::ctx`] for the other panel.
1063 pub(crate) fn row_ctx(&self, path: &Path, stream: usize) -> RowCtx {
1064 let placed = self.session.as_ref().map_or(0, |session| {
1065 let of_row = session
1066 .sources()
1067 .iter()
1068 .position(|s| s.path == path && s.audio_stream == stream);
1069 of_row.map_or(0, |idx| {
1070 session
1071 .lanes()
1072 .into_iter()
1073 .flat_map(|lane| session.lane_clips(lane))
1074 .filter(|c| c.source == idx)
1075 .count()
1076 // ...and the clips inside the other sequences, which play it too.
1077 + session.source_uses_parked(idx).iter().map(|u| u.1).sum::<usize>()
1078 })
1079 });
1080 let sources = self
1081 .session
1082 .as_ref()
1083 .map_or(&[][..], PlaybackSession::sources);
1084 RowCtx {
1085 timeline: self.session.is_some(),
1086 exporting: self.exporting().is_some(),
1087 usable: library_rows(
1088 sources,
1089 &self.streams,
1090 &self.decoders,
1091 self.timeline_audio(),
1092 |path| {
1093 self.session
1094 .as_ref()
1095 .map_or(0, |session| session.file_frames(path))
1096 },
1097 )
1098 .iter()
1099 .any(|row| row.path == path && row.stream == stream && row.unusable.is_none()),
1100 placed,
1101 proxy_stops: matches!(
1102 self.proxies.get(path),
1103 Some(Proxy::Making(_) | Proxy::Cancelling(_))
1104 ),
1105 starred: sources.iter().any(|s| s.path == path && s.audio_stream == stream && s.fav),
1106 offline: self
1107 .session
1108 .as_ref()
1109 .is_some_and(|s| s.offline_sources().iter().any(|(_, p)| p == path)),
1110 media_picks: self.picked_sources().len(),
1111 }
1112 }
1113
1114 /// Which of [`Repeat`]'s three the window is in, for the hold gate at the
1115 /// top of the key handler. Not [`Player::modal`]: that asks whether an
1116 /// overlay is up at all, and here the cards with sliders in them are
1117 /// exactly the ones that answer differently from the keys menu and the
1118 /// export card.
1119 pub(crate) fn repeat_scope(&self) -> Repeat {
1120 // A number being typed is a value under the arrows, exactly as a card's
1121 // slider is -- so a held arrow runs it. Asked before the export card
1122 // below, which otherwise repeats nothing.
1123 if self.budget_edit.is_some() {
1124 Repeat::Card
1125 } else if self.export_open || self.exporting().is_some() {
1126 Repeat::Nothing
1127 } else if self.eq_open.is_some()
1128 || self.color_open.is_some()
1129 || self.transform_open.is_some()
1130 || self.speed_open.is_some()
1131 || self.effects_open.is_some()
1132 || self.silence_open.is_some()
1133 || self.mix_open
1134 || self.markers_open
1135 || self.history_open
1136 || self.tools.is_some()
1137 {
1138 Repeat::Card
1139 } else {
1140 Repeat::Keymap
1141 }
1142 }
1143
1144 /// One item of a library row's menu, done. Every one of them closes the
1145 /// menu first -- the list under it is about to be rebuilt -- except the one
1146 /// that turns the card over.
1147 pub(crate) fn act_on_row(&mut self, item: RowItem, cx: &mut Context<Self>) {
1148 let Some(menu) = self.library_menu.clone() else {
1149 return;
1150 };
1151 match item {
1152 RowItem::Relink => {
1153 self.library_menu = None;
1154 self.relink_pick(menu.path.clone(), cx);
1155 }
1156 RowItem::Properties => {
1157 if let Some(open) = &mut self.library_menu {
1158 open.details = true;
1159 }
1160 }
1161 RowItem::Add => {
1162 self.library_menu = None;
1163 self.append_source(&menu.path, menu.stream, cx);
1164 }
1165 RowItem::Insert => {
1166 self.library_menu = None;
1167 self.insert_source(&menu.path, menu.stream, None, None, cx);
1168 }
1169 RowItem::Remove => {
1170 self.library_menu = None;
1171 self.remove_source(&menu.path, menu.stream, cx);
1172 }
1173 RowItem::RemoveWithClips => {
1174 self.library_menu = None;
1175 self.remove_source_and_clips(&menu.path, menu.stream, cx);
1176 }
1177 // The row's two former ghosts (`▷`, `○`), each still the one
1178 // implementation it always called (cleanse round 2).
1179 RowItem::Preview => {
1180 self.library_menu = None;
1181 self.open_preview(&menu.path, menu.stream, cx);
1182 }
1183 RowItem::CreateMulticam => {
1184 self.library_menu = None;
1185 self.create_multicam_selected(cx);
1186 }
1187 RowItem::Proxy => {
1188 self.library_menu = None;
1189 let stops = matches!(
1190 self.proxies.get(&menu.path),
1191 Some(Proxy::Making(_) | Proxy::Cancelling(_))
1192 );
1193 self.toggle_proxy(&menu.path, stops, cx);
1194 }
1195 RowItem::Favourite => {
1196 self.library_menu = None;
1197 self.toggle_favourite_of(menu.path.clone(), menu.stream, cx);
1198 }
1199 RowItem::MoveToBin => {
1200 self.bin_picker(menu.at, cx);
1201 }
1202 RowItem::NewBin => {
1203 self.library_menu = None;
1204 let rows = self.rows_for((menu.path.clone(), menu.stream));
1205 self.new_bin(0, rows, cx);
1206 }
1207 RowItem::Reveal => {
1208 self.library_menu = None;
1209 // Another process starting: off the UI thread, exactly as the
1210 // export notice's own click starts it.
1211 cx.background_executor()
1212 .spawn(async move { show_in_file_manager(&menu.path) })
1213 .detach();
1214 }
1215 }
1216 cx.notify();
1217 }
1218
1219 /// The key-routed door into the picked row ([`crate::ui::dock_stance::media_key`]).
1220 /// No row menu is open on that path, so the row is the one
1221 /// [`Player::selected_asset`] names; the calls are the menu's own.
1222 pub(crate) fn act_on_picked_row(&mut self, item: RowItem, cx: &mut Context<Self>) {
1223 let Some((path, stream)) = self.selected_asset.clone() else {
1224 return;
1225 };
1226 match item {
1227 RowItem::Preview => self.open_preview(&path, stream, cx),
1228 // Asked of the row oracle like the menu's own Add: this key is a
1229 // second door to the same edit list, and an export is reading it.
1230 RowItem::Add => match crate::oracle::row_enable(item, self.row_ctx(&path, stream)) {
1231 Enable::No(why) => self.notify_user(format!("Add — {why}").into()),
1232 _ => self.append_source(&path, stream, cx),
1233 },
1234 RowItem::Insert => match crate::oracle::row_enable(item, self.row_ctx(&path, stream)) {
1235 Enable::No(why) => self.notify_user(format!("Insert — {why}").into()),
1236 _ => self.insert_source(&path, stream, None, None, cx),
1237 },
1238 _ => {}
1239 }
1240 cx.notify();
1241 }
1242
1243 /// Marks the playhead as an export's in point. `ordered_range` keeps the
1244 /// pair legal whichever one lands past the other.
1245 pub(crate) fn set_in(&mut self, cx: &mut Context<Self>) {
1246 let Some(session) = &self.session else {
1247 return;
1248 };
1249 let at = frame_at(session.now(), self.fps);
1250 let len = frame_at(session.timeline_duration(), self.fps);
1251 self.range = Some(mark_in(self.range, at, len));
1252 cx.notify();
1253 }
1254
1255 /// The out point's pair.
1256 pub(crate) fn set_out(&mut self, cx: &mut Context<Self>) {
1257 let Some(session) = &self.session else {
1258 return;
1259 };
1260 let at = frame_at(session.now(), self.fps);
1261 self.range = Some(mark_out(self.range, at));
1262 cx.notify();
1263 }
1264
1265 /// The odometer (DESIGN.md §6, `,` `.`): the subject cut steps to its
1266 /// neighbour along its own lane, one at a time, clamped rather than
1267 /// wrapping at either end ([`walk_cut`]). The playhead follows it there,
1268 /// which is what puts the screen at rest on the new cut for the two-up
1269 /// to draw.
1270 pub(crate) fn walk_cut(&mut self, forward: bool, cx: &mut Context<Self>) {
1271 self.walk_cut_stride(forward, 1, cx);
1272 }
1273
1274 /// [`Player::walk_cut`] with an explicit stride -- ten for
1275 /// [`ActionId::WalkCutNext10`]/[`ActionId::WalkCutPrev10`], its own
1276 /// bound key (DESIGN.md §6's "shift") rather than a modifier read off
1277 /// the bare walk, since gpui never delivers shift alongside `.`/`,`
1278 /// (see [`crate::keymap::Chord`]'s doc).
1279 pub(crate) fn walk_cut_stride(&mut self, forward: bool, stride: usize, cx: &mut Context<Self>) {
1280 let Some((lane, idx)) = self.selected.anchor() else {
1281 return;
1282 };
1283 let Some(session) = &self.session else {
1284 return;
1285 };
1286 let clips = session.lane_clips(lane);
1287 let next = walk_cut(idx, clips.len(), forward, stride);
1288 let at = clips.get(next).map(|c| f64::from(c.start) / self.fps);
1289 self.select((lane, next), cx);
1290 if let Some(at) = at {
1291 self.seek(at, cx);
1292 }
1293 }
1294
1295 /// The subject cut's own span, `[start, end)` in timeline frames --
1296 /// what loop-trim loops and what the odometer's readout counts against.
1297 pub(crate) fn cut_span(&self, lane: Lane, idx: usize) -> Option<(u32, u32)> {
1298 self.session
1299 .as_ref()?
1300 .lane_clips(lane)
1301 .get(idx)
1302 .map(|c| (c.start, c.end()))
1303 }
1304
1305 /// The no-aim trim (DESIGN.md §6, `[` `]`): one frame detent off the
1306 /// subject cut's chosen edge, clamped to the room the engine already
1307 /// answers ([`nudge_edge`]) -- the same wall a pointer drag is clamped
1308 /// to, so no aim and no hit-testing are needed at any zoom.
1309 pub(crate) fn nudge_cut(&mut self, edge: Edge, dir: i32, cx: &mut Context<Self>) {
1310 let Some((lane, idx)) = self.selected.anchor() else {
1311 return;
1312 };
1313 let Some(session) = &self.session else {
1314 return;
1315 };
1316 let Some((lo, hi)) = session.trim_room(lane, idx, edge) else {
1317 return;
1318 };
1319 let Some(current) = session.lane_clips(lane).get(idx).map(|c| match edge {
1320 Edge::Start => c.start,
1321 Edge::End => c.end(),
1322 }) else {
1323 return;
1324 };
1325 let to = nudge_edge(current, dir, lo, hi);
1326 let trimmed = self
1327 .session
1328 .as_mut()
1329 .is_some_and(|s| s.trim_clip(lane, idx, edge, to));
1330 if trimmed {
1331 // The arm rides the door's own answer: `trim_clip` is `false` for an
1332 // edge already where it was asked to go -- the `[`/`]` pressed
1333 // against the wall the edge is already on -- so the flag, the
1334 // autosave sidecar and the save-on-close question stay off a
1335 // project nobody has changed.
1336 self.mark_dirty();
1337 self.reset_after_reseek();
1338 // Loop-trim follows the edge it is trimming: the whole point of
1339 // the mode is hearing the cut as it moves.
1340 if self.loop_trim.is_some() {
1341 self.loop_trim = self.cut_span(lane, idx);
1342 }
1343 }
1344 cx.notify();
1345 }
1346
1347 /// Trim-to-playhead (debt #42): the keyboard's own version of the
1348 /// pointer's drag-the-edge-to-a-spot trim ([`Player::trim_to`] /
1349 /// [`Player::commit_trim`]) -- same [`PlaybackSession::trim_clip`]
1350 /// primitive either path ends at, so a hand on the keyboard gets the
1351 /// same undo step and the same room clamp a drag gets, just aimed at
1352 /// the playhead instead of wherever the pointer stopped. The oracle
1353 /// already refused this with no subject cut or a playhead off it, so an
1354 /// anchor and a frame are here to read.
1355 pub(crate) fn trim_cut_to_playhead(&mut self, edge: Edge, ripple: bool, cx: &mut Context<Self>) {
1356 let Some((lane, idx)) = self.selected.anchor() else {
1357 return;
1358 };
1359 let Some(session) = &self.session else {
1360 return;
1361 };
1362 let to = frame_at(session.now(), self.fps);
1363 let trimmed = self.session.as_mut().is_some_and(|s| match ripple {
1364 true => s.ripple_trim_clip(lane, idx, edge, to),
1365 false => s.trim_clip(lane, idx, edge, to),
1366 });
1367 if trimmed {
1368 // The door's own answer again: an edge the playhead is already on is
1369 // `false`, no undo step, and nothing for the unsaved ghost to be
1370 // about.
1371 self.mark_dirty();
1372 self.reset_after_reseek();
1373 // Loop-trim follows the edge it is trimming, same as the nudge
1374 // pair above.
1375 if self.loop_trim.is_some() {
1376 self.loop_trim = self.cut_span(lane, idx);
1377 }
1378 }
1379 cx.notify();
1380 }
1381
1382 /// Loop-trim (DESIGN.md §6, `/`): loops the transport around the subject
1383 /// cut's own span while `[`/`]` move its edges -- the modernized Avid
1384 /// trim mode. Neither direction touches play/pause: off drops the window
1385 /// and leaves playback exactly as it was found, and on arms the window
1386 /// without forcing a play -- a forced `session.play()` here used to start
1387 /// the clock as a side effect of arming, which left a paused transport
1388 /// already playing when the user's own `space` arrived next; that press
1389 /// then read as a toggle and paused it right back, pinned at the loop's
1390 /// start frame. Space is what starts it, playing or not.
1391 pub(crate) fn toggle_loop_trim(&mut self, cx: &mut Context<Self>) {
1392 if self.loop_trim.take().is_some() {
1393 self.notify_user("Loop trim off".into());
1394 cx.notify();
1395 return;
1396 }
1397 let Some((lane, idx)) = self.selected.anchor() else {
1398 return;
1399 };
1400 self.loop_trim = self.cut_span(lane, idx);
1401 if self.loop_trim.is_some() {
1402 self.notify_user("Loop trim on".into());
1403 }
1404 cx.notify();
1405 }
1406
1407 /// Whether there was a step to take, for the reason the action table arms
1408 /// nothing on its own: a `^z` with an empty history is not an edit, and it
1409 /// may not raise the save-on-close question over a project nobody has
1410 /// touched. The selection goes with the step for the same reason it used to
1411 /// go every time: a step back puts the indices on different clips, while a
1412 /// refused one leaves them naming exactly what they named.
1413 ///
1414 /// The step itself goes through [`Player::step_history`], which is what
1415 /// takes the window's own copy of the rate, the two proxy switches, the
1416 /// palette's pick and the plate over the picture back up with it.
1417 pub(crate) fn undo(&mut self, cx: &mut Context<Self>) -> bool {
1418 let stepped = self.step_history(PlaybackSession::undo);
1419 if stepped {
1420 self.selected.clear();
1421 // A cue's number can name another cue after the step.
1422 self.drop_sel_cue();
1423 self.cue_menu = None;
1424 }
1425 cx.notify();
1426 stepped
1427 }
1428
1429 /// [`Player::undo`]'s twin, the same answer and the same gate.
1430 pub(crate) fn redo(&mut self, cx: &mut Context<Self>) -> bool {
1431 let stepped = self.step_history(PlaybackSession::redo);
1432 if stepped {
1433 self.selected.clear();
1434 // A cue's number can name another cue after the step.
1435 self.drop_sel_cue();
1436 self.cue_menu = None;
1437 }
1438 cx.notify();
1439 stepped
1440 }
1441
1442 /// One step of the session's own history through the door both `^z` and
1443 /// `^y` go through, and the window-side state it moves taken back up
1444 /// afterwards ([`history_step`]).
1445 ///
1446 /// The plate the pick drew goes with the pick
1447 /// ([`Player::remove_subtitle_track`]'s own drop, for its own reason) and
1448 /// the frame owed to the screen is cleared
1449 /// ([`Player::reset_after_reseek`]): an undo reseeks inside the engine, and
1450 /// a picture left where it was is the frame before the step.
1451 ///
1452 /// `false` where there was nothing to step: no session at all, or a history
1453 /// step that refused ([`PlaybackSession::undo`]'s own answer), in which case
1454 /// nothing in the window moves either.
1455 pub(crate) fn step_history(&mut self, step: impl FnOnce(&mut PlaybackSession) -> bool) -> bool {
1456 let mut caches = SessionCaches {
1457 fps: self.fps,
1458 proxies_on: self.proxies_on,
1459 auto_proxies_on: self.auto_proxies_on,
1460 };
1461 let before = HistoryBefore::of(
1462 self.session.as_ref().map_or(&[][..], |s| s.subtitles()),
1463 self.sub_track,
1464 );
1465 let Some(outcome) = self
1466 .session
1467 .as_mut()
1468 .and_then(|session| history_step(&before, &mut caches, session, step))
1469 else {
1470 return false;
1471 };
1472 self.fps = caches.fps;
1473 self.proxies_on = caches.proxies_on;
1474 self.auto_proxies_on = caches.auto_proxies_on;
1475 self.sub_track = outcome.sub_track;
1476 if outcome.drop_sub_image {
1477 // corner-cut: its atlas tile is not released -- `close_session`'s
1478 // note, for its reason and with its upgrade path.
1479 self.sub_image = None;
1480 }
1481 self.reset_after_reseek();
1482 true
1483 }
1484}
1485
1486/// The three session settings a window keeps its own copy of, as a value so
1487/// that [`history_step`] can re-read them in place: the rate every
1488/// frame↔second conversion in the window counts in (`Player::timeline_at`,
1489/// `Scale::snap_frames`) and the two switches a project carries and the
1490/// Settings rows *show* (`settings_stance`).
1491#[derive(Clone, Copy, Debug, PartialEq)]
1492pub(crate) struct SessionCaches {
1493 pub(crate) fps: f64,
1494 pub(crate) proxies_on: bool,
1495 pub(crate) auto_proxies_on: bool,
1496}
1497
1498/// The window-side state of the palette as a history step finds it: the pick,
1499/// how many rows there are, and which row the pick names.
1500#[derive(Clone, Debug, PartialEq)]
1501pub(crate) struct HistoryBefore {
1502 pub(crate) sub_track: usize,
1503 pub(crate) sub_rows: usize,
1504 pub(crate) sub_row: Option<SubPickKey>,
1505}
1506
1507impl HistoryBefore {
1508 /// `tracks` as they stand and the index picked there -- an empty palette
1509 /// for a window with no session, which is the state a step cannot happen in
1510 /// anyway.
1511 pub(crate) fn of(tracks: &[engine::subtitle::SubtitleTrack], sub_track: usize) -> Self {
1512 Self {
1513 sub_track,
1514 sub_rows: tracks.len(),
1515 sub_row: SubPickKey::of(tracks, sub_track),
1516 }
1517 }
1518}
1519
1520/// What a history step leaves this window to take up beside the session's own
1521/// lanes.
1522#[derive(Clone, Copy, Debug, PartialEq)]
1523pub(crate) struct HistoryOutcome {
1524 pub(crate) sub_track: usize,
1525 /// The plate over the picture (`Player::sub_image`) has to go. Its tile is
1526 /// keyed by *where* a cue sits ([`Player::sub_picture`]'s `(lane,
1527 /// start_us)`) and carries no track, so a step that moves captions, takes
1528 /// one off, or renumbers the track a placement names
1529 /// ([`engine::Project::remove_subtitles`] walks `SubClip::track` down)
1530 /// cannot be asked of that cache -- the tile at a key can be served for a
1531 /// cue it was not drawn from. Conservative on purpose: at most one plate is
1532 /// redrawn by the next repaint.
1533 pub(crate) drop_sub_image: bool,
1534}
1535
1536/// One step of the session's own history ([`PlaybackSession::undo`],
1537/// [`PlaybackSession::redo`]) with everything this window caches re-read after
1538/// it. `None` when the step did not happen -- nothing to undo, nothing to redo
1539/// -- and then nothing here moves either.
1540///
1541/// A free function over the session and the caches rather than a [`Player`]
1542/// method: this test binary has no `TestAppContext` to build a `Player` in, so
1543/// what `^z` does to the session *and* to the caches beside it is pinned here,
1544/// and [`Player::step_history`] is this call plus the repaint.
1545///
1546/// The rate and the two switches are read off the *session*, exactly as the
1547/// doors that own them do ([`Player::apply_frame_rate`], the `.edith` load): a
1548/// history entry carries the project's settings beside its lanes
1549/// (`Project::snapshot`), so a step puts them back -- and a window that kept
1550/// its old copies counts a cut at the rate just undone, keeps reporting a
1551/// switch the session no longer has, and pushes that switch at the next session
1552/// it makes.
1553pub(crate) fn history_step(
1554 before: &HistoryBefore,
1555 caches: &mut SessionCaches,
1556 session: &mut PlaybackSession,
1557 step: impl FnOnce(&mut PlaybackSession) -> bool,
1558) -> Option<HistoryOutcome> {
1559 if !step(session) {
1560 return None;
1561 }
1562 caches.fps = session.meta().frame_rate;
1563 caches.proxies_on = session.proxies();
1564 caches.auto_proxies_on = session.auto_proxies();
1565 let tracks = session.subtitles();
1566 let sub_track = sub_pick_after_restore(before.sub_track, before.sub_row.as_ref(), tracks);
1567 Some(HistoryOutcome {
1568 sub_track,
1569 drop_sub_image: tracks.len() != before.sub_rows || sub_track != before.sub_track,
1570 })
1571}
1572
1573/// The half-open range a mark and a mark make, in either order: a person's two
1574/// keystrokes are not promised to land in order, so this is what turns
1575/// whichever came second into the pair `Player::start_export` wants a range in
1576/// -- and never an empty one, since a single frame marked in and out twice is
1577/// still a frame to export.
1578/// The range after an in mark at `at` on a timeline `len` frames long. A lone
1579/// in runs to the end, and an in at or past the out point does too -- the pair
1580/// is never a single frame the person did not ask for (that was a 0 s export).
1581pub(crate) fn mark_in(range: Option<(u32, u32)>, at: u32, len: u32) -> (u32, u32) {
1582 match range {
1583 Some((_, out)) if at < out => (at, out),
1584 _ => ordered_range(at, len.max(at)),
1585 }
1586}
1587
1588/// The out mark's pair: a lone out starts at the top, and an out at or before
1589/// the in point does too.
1590pub(crate) fn mark_out(range: Option<(u32, u32)>, at: u32) -> (u32, u32) {
1591 match range {
1592 Some((start, _)) if at > start => (start, at),
1593 _ => ordered_range(0, at),
1594 }
1595}
1596
1597pub(crate) fn ordered_range(a: u32, b: u32) -> (u32, u32) {
1598 let (start, end) = if a <= b { (a, b) } else { (b, a) };
1599 if start == end {
1600 (start, start + 1)
1601 } else {
1602 (start, end)
1603 }
1604}
1605
1606/// Opens a written file in the desktop's default player, the same way
1607/// [`show_in_file_manager`] reveals one: `xdg-open` hands the path to whatever
1608/// the user has registered for it. Failure is silent here, as the reveal's is:
1609/// the file is on disk and the toast's other button still reaches it.
1610pub(crate) fn open_in_default_player(path: &std::path::Path) {
1611 let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
1612 let _ = std::process::Command::new("xdg-open").arg(&path).status();
1613}
1614
1615/// Whether two halves of one take meet at `frame` on a lane's clips: touching
1616/// on the timeline and consecutive frames of the same source -- what a cut
1617/// leaves and Regroup closes.
1618pub(crate) fn rejoinable(clips: &[Clip], frame: u32) -> bool {
1619 clips.windows(2).any(|w| {
1620 let (a, b) = (&w[0], &w[1]);
1621 a.end() == frame
1622 && b.start == frame
1623 && a.source == b.source
1624 && a.reversed == b.reversed
1625 && match a.reversed {
1626 true => a.in_frame == b.out_frame,
1627 false => a.out_frame == b.in_frame,
1628 }
1629 })
1630}
1631
1632#[cfg(test)]
1633mod tests {
1634 use super::{mark_in, mark_out, ordered_range, step_name, step_row_name, step_toast};
1635 use crate::keymap::ActionId;
1636
1637 /// Undo and Redo name the step they take back or walk to, and say so when none is left;
1638 /// the toast names the step it just took. An unnamed step reads as plain Undo.
1639 #[test]
1640 fn undo_and_redo_name_their_step_in_the_menu_and_the_toast() {
1641 assert_eq!(step_row_name(false, 2, Some("Split")), "Undo Split");
1642 assert_eq!(step_row_name(false, 1, None), "Undo");
1643 assert_eq!(step_row_name(false, 0, Some("Split")), "Nothing to undo");
1644 assert_eq!(step_row_name(true, 1, Some("Add marker")), "Redo Add marker");
1645 assert_eq!(step_row_name(true, 1, None), "Redo");
1646 assert_eq!(step_row_name(true, 0, None), "Nothing to redo");
1647 assert_eq!(step_toast(false, Some("Split")), "Undid Split");
1648 assert_eq!(step_toast(true, Some("Split")), "Redid Split");
1649 assert_eq!(step_toast(false, None), "Undone");
1650 assert_eq!(step_toast(true, None), "Redone");
1651 }
1652
1653 /// A step takes its name from the action's menu name, without the ellipsis. Undo and Redo,
1654 /// and a name too long for a menu row, carry none.
1655 #[test]
1656 fn a_step_takes_its_menu_name() {
1657 assert_eq!(step_name(ActionId::Cut), Some("Split"));
1658 assert_eq!(step_name(ActionId::Color), Some("Colour"));
1659 assert_eq!(step_name(ActionId::AddMarker), Some("Add marker"));
1660 assert_eq!(step_name(ActionId::Delete), Some("Delete"));
1661 assert_eq!(step_name(ActionId::ClipEnabled), Some("Enable/disable clip"));
1662 assert_eq!(step_name(ActionId::NewTone), Some("Add tone"));
1663 assert_eq!(step_name(ActionId::Undo), None);
1664 assert_eq!(step_name(ActionId::Redo), None);
1665 for action in ActionId::ALL {
1666 if let Some(name) = step_name(action) {
1667 assert!(name.chars().count() < 30, "{action:?} names its step {name:?}, too long");
1668 assert!(!name.contains('\u{2026}'), "{action:?} keeps the ellipsis in {name:?}");
1669 }
1670 }
1671 }
1672
1673 #[test]
1674 fn lone_marks_run_to_the_end_or_the_top() {
1675 // The user's bug: I (or O) on its own made a one-frame range.
1676 assert_eq!(mark_in(None, 0, 3120), (0, 3120));
1677 assert_eq!(mark_in(None, 120, 3120), (120, 3120));
1678 assert_eq!(mark_out(None, 3120), (0, 3120));
1679 assert_eq!(mark_in(Some((10, 50)), 20, 3120), (20, 50));
1680 assert_eq!(mark_in(Some((10, 50)), 60, 3120), (60, 3120));
1681 assert_eq!(mark_out(Some((10, 50)), 40), (10, 40));
1682 assert_eq!(mark_out(Some((10, 50)), 5), (0, 5));
1683 assert_eq!(mark_in(None, 3120, 3120), (3120, 3121));
1684 }
1685
1686 #[test]
1687 fn ordered_range_never_empty_and_swaps_a_reversed_pair() {
1688 assert_eq!(ordered_range(5, 10), (5, 10));
1689 assert_eq!(ordered_range(10, 5), (5, 10));
1690 assert_eq!(ordered_range(7, 7), (7, 8));
1691 assert_eq!(ordered_range(0, 0), (0, 1));
1692 }
1693}