forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

caption_cues.rs506 lines, 19.9 KiBHistoryRawDownload
1//! Captions as blocks of their own on a subtitle lane, the way an NLE draws them: each cue is a
2//! block with its words inside, a click picks that one cue, an edge drag trims it and a body drag
3//! moves it between its neighbours, and a right-click opens the caption menu.
4//!
5//! The engine keeps the words on the **track** and a lane only holds windows of it
6//! ([`engine::project::SubClip`]), so every edit here is a cue edit on the track
7//! ([`PlaybackSession::set_cue_times`], [`PlaybackSession::merge_cue_next`],
8//! [`PlaybackSession::split_cues_at`], [`PlaybackSession::delete_cue`]): one undo step each, and the
9//! placement is never touched.
10
11use engine::PlaybackSession;
12use engine::project::MIN_CUE_US;
13
14use crate::*;
15
16/// Which part of a cue block a drag holds.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub(crate) enum CueGrab {
19 Start,
20 End,
21 Body,
22}
23
24/// A caption being dragged. All times are on the track's own clock; the pointer is turned into
25/// that clock through the placement that shows the cue ([`PlaybackSession::cue_track_us_at`]).
26#[derive(Clone, Copy, Debug)]
27pub(crate) struct CueDrag {
28 pub(crate) lane: Lane,
29 pub(crate) track: usize,
30 pub(crate) cue: usize,
31 pub(crate) grab: CueGrab,
32 /// Where the pointer stood at the press.
33 pub(crate) press_us: i64,
34 /// The cue's times at the press, and as the drag has them now.
35 pub(crate) orig: (i64, i64),
36 pub(crate) now: (i64, i64),
37 /// The neighbours' walls ([`PlaybackSession::cue_room`]).
38 pub(crate) room: (i64, i64),
39}
40
41/// A number of the caption panel: where the caption starts and ends on the timeline. Its length
42/// is the difference of the two, so it only reads.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub(crate) enum CueNum {
45 Start,
46 End,
47}
48
49/// A panel number being dragged sideways: the number it is, where the drag began, the value it
50/// has now, and whether the pointer has left the press. Written once on the release, so a scrub
51/// is one undo step; a press that never moves is a click that types the number instead.
52#[derive(Clone, Copy, Debug)]
53pub(crate) struct CueNumScrub {
54 pub(crate) which: CueNum,
55 pub(crate) x0: f32,
56 pub(crate) v0: i64,
57 pub(crate) cur: i64,
58 pub(crate) moved: bool,
59}
60
61/// Seconds a panel number moves per pixel of drag (a fine drag, with shift, moves a tenth).
62const CUE_NUM_SECS_PER_PX: f64 = 0.02;
63
64/// The value a panel number scrubs to: `v0` moved by `dx` pixels, on whole frames, inside the
65/// range a caption can span (a frame, up to ten hours).
66pub(crate) fn scrubbed_us(v0: i64, dx: f32, fine: bool, fps: f64) -> i64 {
67 let fps = if fps.is_finite() && fps > 0. { fps } else { 25. };
68 let secs = crate::ui::kit::scrub_value(v0 as f64 / 1e6, dx, CUE_NUM_SECS_PER_PX, fine, 0., 36_000.);
69 ((secs * fps).round() / fps * 1e6).round() as i64
70}
71
72/// The open caption menu: the cue it names and where the click was.
73#[derive(Clone, Copy, Debug)]
74pub(crate) struct CueMenu {
75 pub(crate) lane: Lane,
76 pub(crate) track: usize,
77 pub(crate) cue: usize,
78 pub(crate) at: Point<Pixels>,
79}
80
81/// Where a drag leaves a cue: the edge in the hand follows `to`, a body keeps its length, and
82/// every result stays inside `room` and at least [`MIN_CUE_US`] long.
83pub(crate) fn dragged_times(grab: CueGrab, orig: (i64, i64), room: (i64, i64), press: i64, to: i64) -> (i64, i64) {
84 match grab {
85 CueGrab::Start => (to.clamp(room.0, (orig.1 - MIN_CUE_US).max(room.0)), orig.1),
86 CueGrab::End => (orig.0, to.clamp((orig.0 + MIN_CUE_US).min(room.1), room.1)),
87 CueGrab::Body => {
88 let by = (to - press).clamp(room.0 - orig.0, room.1 - orig.1);
89 (orig.0 + by, orig.1 + by)
90 }
91 }
92}
93
94impl Player {
95 /// The cue `(lane, track, cue)` if it is still there and a text one.
96 fn cue_ref(&self, track: usize, cue: usize) -> Option<&engine::subtitle::Cue> {
97 self.session.as_ref()?.subtitles().get(track)?.cues.get(cue)
98 }
99
100 /// Lets go of the selected caption, and of what its panel was holding open.
101 pub(crate) fn drop_sel_cue(&mut self) {
102 self.sel_cue = None;
103 self.cue_num = None;
104 self.cue_num_scrub = None;
105 if self.cue_edit.as_ref().is_some_and(|e| e.in_panel) {
106 self.cue_edit = None;
107 }
108 }
109
110 /// Picks one cue: the placement's own selection goes, so the ring is on the one block.
111 pub(crate) fn select_cue(&mut self, lane: Lane, track: usize, cue: usize, cx: &mut Context<Self>) {
112 if self.lane_locked_refusal(lane) {
113 return;
114 }
115 self.drop_title_selection(cx);
116 self.selected.clear();
117 self.gap = None;
118 self.cue_menu = None;
119 self.cue_num = None;
120 self.cue_num_scrub = None;
121 self.sel_cue = Some((lane, track, cue));
122 cx.notify();
123 }
124
125 /// The track's clock under window x, for the cue's placement, with the pointer snapped to
126 /// whole frames (a cue edge lands on a frame, as every cut does).
127 fn cue_us_under(&self, lane: Lane, track: usize, cue: usize, x: Pixels) -> Option<i64> {
128 let secs = self.scale.time_at(px_along(x, self.ruler.get()));
129 let tl_us = ((secs * self.fps).round() / self.fps * 1e6).round() as i64;
130 self.session.as_ref()?.cue_track_us_at(lane, track, cue, tl_us)
131 }
132
133 /// A press on a cue's edge or body: picks it and arms the drag. Nothing is written until the
134 /// release, and a press that never moves is only the pick.
135 pub(crate) fn start_cue_drag(
136 &mut self,
137 lane: Lane,
138 track: usize,
139 cue: usize,
140 grab: CueGrab,
141 x: Pixels,
142 cx: &mut Context<Self>,
143 ) {
144 if self.covers_room() || self.exporting().is_some() || self.lane_locked_refusal(lane) {
145 return;
146 }
147 let Some(c) = self.cue_ref(track, cue).filter(|c| c.image.is_none()) else {
148 return;
149 };
150 let orig = (c.start_us, c.end_us);
151 let Some(room) = self.session.as_ref().and_then(|s| s.cue_room(track, cue)) else {
152 return;
153 };
154 let press_us = self.cue_us_under(lane, track, cue, x).unwrap_or(orig.0);
155 self.select_cue(lane, track, cue, cx);
156 self.cue_drag = Some(CueDrag { lane, track, cue, grab, press_us, orig, now: orig, room });
157 cx.notify();
158 }
159
160 /// The pointer moved with a cue held.
161 pub(crate) fn cue_drag_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
162 let Some(drag) = self.cue_drag else {
163 return;
164 };
165 let Some(to) = self.cue_us_under(drag.lane, drag.track, drag.cue, x) else {
166 return;
167 };
168 let now = dragged_times(drag.grab, drag.orig, drag.room, drag.press_us, to);
169 if now != drag.now {
170 self.cue_drag = Some(CueDrag { now, ..drag });
171 cx.notify();
172 }
173 }
174
175 /// The release: the whole drag reaches the engine as one edit, so it is one undo step.
176 pub(crate) fn commit_cue_drag(&mut self, cx: &mut Context<Self>) {
177 let Some(drag) = self.cue_drag.take() else {
178 return;
179 };
180 if drag.now != drag.orig
181 && let Some(session) = self.session.as_mut()
182 {
183 match session.set_cue_times(drag.track, drag.cue, drag.now.0, drag.now.1) {
184 Ok(true) => self.mark_dirty(),
185 Ok(false) => {}
186 Err(e) => self.notify_user(format!("Caption not changed — {e}").into()),
187 }
188 }
189 cx.notify();
190 }
191
192 /// The times a cue is drawn at while it is being dragged, if it is the one.
193 pub(crate) fn dragged_cue(&self, track: usize, cue: usize) -> Option<CueDrag> {
194 self.cue_drag.filter(|d| (d.track, d.cue) == (track, cue))
195 }
196
197 /// The selected caption's own numbers on the timeline: `(start, end)` in microseconds, through
198 /// the placement that shows it. `None` when the selection no longer names a shown caption.
199 pub(crate) fn sel_cue_span(&self) -> Option<(Lane, usize, usize, i64, i64)> {
200 let (lane, track, cue) = self.sel_cue?;
201 let span = self
202 .session
203 .as_ref()?
204 .sub_lane_cue_spans(lane)
205 .into_iter()
206 .find(|s| s.track == track && s.cue == cue)?;
207 Some((lane, track, cue, span.start_us, span.end_us))
208 }
209
210 /// The caption panel's text field was pressed: the words open for typing in the panel.
211 pub(crate) fn open_panel_cue_edit(&mut self, cx: &mut Context<Self>) {
212 let Some((lane, track, cue)) = self.sel_cue else {
213 return;
214 };
215 if self.cue_edit.as_ref().is_some_and(|e| (e.track, e.cue) == (track, cue)) {
216 return;
217 }
218 self.cue_edit = None;
219 self.open_cue_edit(lane, track, cue, cx);
220 if let Some(edit) = self.cue_edit.as_mut() {
221 edit.in_panel = true;
222 }
223 }
224
225 /// A number of the panel was pressed: it opens for typing on what it shows.
226 pub(crate) fn begin_cue_num(&mut self, which: CueNum, cx: &mut Context<Self>) {
227 self.commit_cue_edit(cx);
228 let Some((_, _, _, start, end)) = self.sel_cue_span() else {
229 return;
230 };
231 let us = match which {
232 CueNum::Start => start,
233 CueNum::End => end,
234 };
235 self.cue_num = Some((which, crate::ui::kit::NumberEdit::begin(&cue_secs(us))));
236 cx.notify();
237 }
238
239 /// A panel number was pressed for a drag: the number follows the pointer sideways until the
240 /// button comes up ([`Player::cue_num_scrub_end`]). Nothing is written before the release.
241 pub(crate) fn begin_cue_num_scrub(&mut self, which: CueNum, x: f32, cx: &mut Context<Self>) {
242 self.commit_cue_edit(cx);
243 let Some((lane, _, _, start, end)) = self.sel_cue_span() else {
244 return;
245 };
246 if self.session.as_ref().is_some_and(|s| s.lane_locked(lane)) {
247 return;
248 }
249 let v0 = match which {
250 CueNum::Start => start,
251 CueNum::End => end,
252 };
253 self.cue_num_scrub = Some(CueNumScrub { which, x0: x, v0, cur: v0, moved: false });
254 cx.notify();
255 }
256
257 /// The pointer moved with a panel number held: the number shows the value it would take.
258 pub(crate) fn cue_num_scrub_move(&mut self, x: f32, fine: bool, cx: &mut Context<Self>) {
259 let Some(s) = self.cue_num_scrub else {
260 return;
261 };
262 let dx = x - s.x0;
263 let cur = scrubbed_us(s.v0, dx, fine, self.fps);
264 let moved = s.moved || dx.abs() > 3.;
265 if cur != s.cur || moved != s.moved {
266 self.cue_num_scrub = Some(CueNumScrub { cur, moved, ..s });
267 cx.notify();
268 }
269 }
270
271 /// The button came up over a panel number: a drag that moved is written as one cue edit.
272 /// A press that never moved is left to the field's click, which types it. `true` when a
273 /// scrub was in flight, so the release goes no further.
274 pub(crate) fn cue_num_scrub_end(&mut self, cx: &mut Context<Self>) -> bool {
275 let Some(s) = self.cue_num_scrub.take() else {
276 return false;
277 };
278 if s.moved && s.cur != s.v0 {
279 self.set_cue_num(s.which, s.cur, cx);
280 } else {
281 cx.notify();
282 }
283 true
284 }
285
286 /// Escape while a caption's words are typed: they are given up, as a title's are, so the old
287 /// words stay and a toast says so. `false` when no words were being typed.
288 pub(crate) fn escape_cue_edit(&mut self) -> bool {
289 if self.cue_edit.take().is_none() {
290 return false;
291 }
292 self.notify_user("Caption edit cancelled".into());
293 true
294 }
295
296 /// The keyboard while a caption's words are typed, in the box over its block or in the Clip
297 /// tab's panel: enter saves, shift+enter starts a new line, escape gives up, Ctrl+A selects the
298 /// words, and the rest is text.
299 pub(crate) fn cue_edit_key(&mut self, key: &str, ctrl: bool, shift: bool, alt: bool, key_char: Option<&str>, cx: &mut Context<Self>) {
300 match key {
301 "escape" => {
302 self.escape_cue_edit();
303 }
304 "enter" if shift => {
305 if let Some(edit) = self.cue_edit.as_mut() {
306 edit.newline();
307 }
308 }
309 "enter" => self.commit_cue_edit(cx),
310 "backspace" => {
311 if let Some(edit) = self.cue_edit.as_mut() {
312 edit.backspace();
313 }
314 }
315 "a" if ctrl && !alt => {
316 if let Some(edit) = self.cue_edit.as_mut() {
317 edit.select_all();
318 }
319 }
320 _ => {
321 // The character the layout made, not the key's name: a non-ASCII letter has no
322 // key name. A chord with ctrl or alt is not a letter.
323 if !ctrl
324 && !alt
325 && let Some(edit) = self.cue_edit.as_mut()
326 && let Some(chars) = key_char
327 {
328 for c in chars.chars() {
329 edit.typed(c);
330 }
331 }
332 }
333 }
334 cx.notify();
335 }
336
337 /// One key while a panel number is typed: Enter writes it, Escape drops it.
338 pub(crate) fn cue_num_key(&mut self, key: &str, ctrl: bool, alt: bool, key_char: Option<&str>, cx: &mut Context<Self>) {
339 use crate::player::text_field::FieldKey;
340 let Some((which, mut edit)) = self.cue_num.take() else {
341 return;
342 };
343 if self.sel_cue.is_none() {
344 return cx.notify();
345 }
346 match edit.key(key, ctrl, alt, key_char) {
347 FieldKey::Edited => self.cue_num = Some((which, edit)),
348 FieldKey::Cancel => {}
349 FieldKey::Commit => {
350 if let Some(secs) = edit.commit(0., 36_000.) {
351 self.set_cue_num(which, (secs * 1e6).round() as i64, cx);
352 }
353 }
354 }
355 cx.notify();
356 }
357
358 /// Writes one panel number as one cue edit: the times are the timeline's, turned into the
359 /// track's clock, and kept inside the neighbours and at least [`MIN_CUE_US`] long.
360 pub(crate) fn set_cue_num(&mut self, which: CueNum, us: i64, cx: &mut Context<Self>) {
361 let Some((lane, track, cue, _, _)) = self.sel_cue_span() else {
362 return;
363 };
364 if self.lane_locked_refusal(lane) {
365 return;
366 }
367 let Some(session) = self.session.as_ref() else {
368 return;
369 };
370 let Some(room) = session.cue_room(track, cue) else {
371 return;
372 };
373 let Some(c) = self.cue_ref(track, cue).filter(|c| c.image.is_none()) else {
374 return;
375 };
376 let (s0, e0) = (c.start_us, c.end_us);
377 let to_track = |tl: i64| session.cue_track_us_at(lane, track, cue, tl).unwrap_or(tl);
378 let (s, e) = match which {
379 CueNum::Start => (to_track(us).clamp(room.0, (e0 - MIN_CUE_US).max(room.0)), e0),
380 CueNum::End => (s0, to_track(us).clamp((s0 + MIN_CUE_US).min(room.1), room.1)),
381 };
382 if (s, e) == (s0, e0) {
383 return;
384 }
385 if let Some(session) = self.session.as_mut() {
386 match session.set_cue_times(track, cue, s, e) {
387 Ok(true) => self.mark_dirty(),
388 Ok(false) => {}
389 Err(e) => self.notify_user(format!("Caption not changed — {e}").into()),
390 }
391 }
392 cx.notify();
393 }
394
395 /// Opens the caption menu on a cue (a right-click on its block).
396 pub(crate) fn open_cue_menu(&mut self, lane: Lane, track: usize, cue: usize, at: Point<Pixels>, cx: &mut Context<Self>) {
397 if !self.menu_allowed() || self.lane_locked_refusal(lane) {
398 return;
399 }
400 self.context_menu = None;
401 self.drop_title_selection(cx);
402 self.sel_cue = Some((lane, track, cue));
403 self.selected.clear();
404 self.gap = None;
405 self.cue_menu = Some(CueMenu { lane, track, cue, at });
406 cx.notify();
407 }
408
409 /// Why Split at playhead cannot run on this cue, if it cannot.
410 pub(crate) fn cue_split_why(&self, m: CueMenu) -> Option<&'static str> {
411 let session = self.session.as_ref()?;
412 let c = self.cue_ref(m.track, m.cue)?;
413 if c.image.is_some() {
414 return Some("A picture caption cannot be split");
415 }
416 let at = session.cue_track_us_at(m.lane, m.track, m.cue, (session.now() * 1e6).round() as i64);
417 match at {
418 Some(t) if c.start_us < t && t < c.end_us => None,
419 _ => Some("Move the playhead onto this caption first"),
420 }
421 }
422
423 /// Why Merge with next cannot run on this cue, if it cannot.
424 pub(crate) fn cue_merge_why(&self, m: CueMenu) -> Option<&'static str> {
425 let cues = &self.session.as_ref()?.subtitles().get(m.track)?.cues;
426 match (cues.get(m.cue), cues.get(m.cue + 1)) {
427 (Some(a), Some(b)) if a.image.is_none() && b.image.is_none() => None,
428 (Some(a), Some(_)) if a.image.is_some() => Some("A picture caption cannot be merged"),
429 _ => Some("This is the last caption"),
430 }
431 }
432
433 /// Splits the cue at the playhead.
434 pub(crate) fn split_cue_at_playhead(&mut self, m: CueMenu, cx: &mut Context<Self>) {
435 self.cue_menu = None;
436 if let Some(why) = self.cue_split_why(m) {
437 self.notify_user(why.into());
438 return cx.notify();
439 }
440 let Some(session) = self.session.as_mut() else {
441 return;
442 };
443 let now = (session.now() * 1e6).round() as i64;
444 if let Some(t) = session.cue_track_us_at(m.lane, m.track, m.cue, now)
445 && session.split_cues_at(m.track, t)
446 {
447 self.sel_cue = Some((m.lane, m.track, m.cue));
448 self.mark_dirty();
449 } else {
450 self.notify_user("Not split — a caption needs a word on each side".into());
451 }
452 cx.notify();
453 }
454
455 /// Joins the cue with the next one.
456 pub(crate) fn merge_cue_with_next(&mut self, m: CueMenu, cx: &mut Context<Self>) {
457 self.cue_menu = None;
458 let Some(session) = self.session.as_mut() else {
459 return;
460 };
461 match session.merge_cue_next(m.track, m.cue) {
462 Ok(()) => self.mark_dirty(),
463 Err(e) => self.notify_user(format!("Not merged — {e}").into()),
464 }
465 cx.notify();
466 }
467
468 /// Takes the cue out of its track.
469 pub(crate) fn delete_cue_at(&mut self, m: CueMenu, cx: &mut Context<Self>) {
470 self.cue_menu = None;
471 if self.lane_locked_refusal(m.lane) {
472 return;
473 }
474 if let Some(session) = self.session.as_mut()
475 && PlaybackSession::delete_cue(session, m.track, m.cue)
476 {
477 self.drop_sel_cue();
478 self.mark_dirty();
479 }
480 cx.notify();
481 }
482}
483
484/// Seconds as the panel's fields show them: two places.
485pub(crate) fn cue_secs(us: i64) -> String {
486 format!("{:.2}", us as f64 / 1e6)
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492
493 #[test]
494 fn a_dragged_cue_stays_inside_its_neighbours_and_keeps_its_length() {
495 let (orig, room) = ((3_000_000, 5_000_000), (2_000_000, 6_000_000));
496 // An edge stops at the neighbour and at the other edge less the minimum.
497 assert_eq!(dragged_times(CueGrab::Start, orig, room, 0, 1_000_000), (2_000_000, 5_000_000));
498 assert_eq!(dragged_times(CueGrab::Start, orig, room, 0, 9_000_000), (5_000_000 - MIN_CUE_US, 5_000_000));
499 assert_eq!(dragged_times(CueGrab::End, orig, room, 0, 9_000_000), (3_000_000, 6_000_000));
500 assert_eq!(dragged_times(CueGrab::End, orig, room, 0, 0), (3_000_000, 3_000_000 + MIN_CUE_US));
501 // A body moves as a whole and stops when either end meets a wall.
502 assert_eq!(dragged_times(CueGrab::Body, orig, room, 4_000_000, 4_500_000), (3_500_000, 5_500_000));
503 assert_eq!(dragged_times(CueGrab::Body, orig, room, 4_000_000, 9_000_000), (4_000_000, 6_000_000));
504 assert_eq!(dragged_times(CueGrab::Body, orig, room, 4_000_000, 0), (2_000_000, 4_000_000));
505 }
506}