forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

titling.rs712 lines, 29.6 KiBHistoryRawDownload
1//! Titles on the window's side: Title in the File > New menu, the Title section of the Clip tab,
2//! the timeline's title row and the picture's double-click all go through here. The model is the
3//! engine's ([`engine::Title`], `PlaybackSession::{add,set,remove}_title`, the very calls MCP's
4//! `title_add`/`title_set`/`title_remove` make); every change here is one undo step. The words
5//! are typed into a draft the viewer shows live and are written when the field is left.
6
7use crate::player::text_field::{FieldKey, TextField};
8use crate::*;
9use engine::Title;
10use engine::project::{MAX_TITLE_CHARS, TitlePreset as Preset};
11use engine::text::{DEFAULT_SIZE, SIZE_RANGE, TextStyle};
12use engine::titleanim::{KEY_SCALE_RANGE, TitleKey};
13use engine::transform::{KeyEase, sample};
14
15/// How long a new title is up, in seconds.
16pub(crate) const NEW_SECS: f64 = 5.0;
17
18/// The words a new title starts with, selected so typing replaces them.
19pub(crate) const NEW_TEXT: &str = "Title";
20
21/// Which number of the selected title a drag is turning, or the block itself being moved.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub(crate) enum ScrubField {
24 Size,
25 Start,
26 Length,
27 /// How long the entrance and exit animations take, in frames.
28 AnimLength,
29 /// The box's opacity, in percent.
30 BoxOpacity,
31 /// The title's block dragged along the timeline: `Start` in timeline pixels.
32 Move,
33 /// The title's own key at the playhead: its horizontal shift, in percent of the width.
34 KeyX,
35 /// The key's vertical shift, in percent of the height, down positive.
36 KeyY,
37 /// The key's size multiplier, in percent.
38 KeyScale,
39 /// The key's opacity multiplier, in percent.
40 KeyOpacity,
41}
42
43impl ScrubField {
44 /// Whether the field is one of the title's key numbers, which write the key at the playhead.
45 pub(crate) fn is_key(self) -> bool {
46 matches!(self, ScrubField::KeyX | ScrubField::KeyY | ScrubField::KeyScale | ScrubField::KeyOpacity)
47 }
48}
49
50/// A title number being scrubbed: where the press was, the value it had, the value now, and the
51/// title frame a key field writes its key at.
52#[derive(Clone, Copy, Debug, PartialEq)]
53pub(crate) struct TitleScrub {
54 pub(crate) field: ScrubField,
55 pub(crate) x0: f32,
56 pub(crate) v0: i64,
57 pub(crate) cur: i64,
58 pub(crate) at: u32,
59}
60
61/// Which colour of the selected title a hex field is typing: the letters' or the box's.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub(crate) enum HexTarget {
64 Ink,
65 Box,
66}
67
68/// `ffcc00` or `#ffcc00` as red, green, blue.
69pub(crate) fn parse_hex(text: &str) -> Option<[u8; 3]> {
70 let t = text.trim().trim_start_matches('#');
71 if t.len() != 6 || !t.bytes().all(|b| b.is_ascii_hexdigit()) {
72 return None;
73 }
74 let v = u32::from_str_radix(t, 16).ok()?;
75 Some([(v >> 16) as u8, (v >> 8) as u8, v as u8])
76}
77
78/// A colour as six lower-case hex digits.
79pub(crate) fn hex_of(c: [u8; 3]) -> String {
80 format!("{:02x}{:02x}{:02x}", c[0], c[1], c[2])
81}
82
83/// The name a preset's chip wears in the title card.
84pub(crate) fn preset_label(preset: Preset) -> &'static str {
85 match preset {
86 Preset::LowerThird => "Lower third",
87 Preset::Centered => "Centered title",
88 Preset::CaptionBar => "Caption bar",
89 }
90}
91
92/// The value a scrub of `field` shows after the pointer moved `dx` px from where it was pressed.
93/// A size moves a unit per 3 px, timing a frame per 4 px; the block move is timeline pixels, so
94/// `pps` (px per second) turns them into frames. Held to the engine's own limits.
95pub(crate) fn scrub_value(field: ScrubField, v0: i64, dx: f32, fps: f64, pps: f64, frames: u32) -> i64 {
96 let by = |per_unit: f32| (dx / per_unit).round() as i64;
97 let max_end = i64::from(engine::project::MAX_TITLE_END);
98 match field {
99 ScrubField::Size => (v0 + by(3.)).clamp(i64::from(SIZE_RANGE.0), i64::from(SIZE_RANGE.1)),
100 ScrubField::Start => (v0 + by(4.)).clamp(0, max_end - i64::from(frames)),
101 ScrubField::Length => (v0 + by(4.)).clamp(1, max_end),
102 ScrubField::AnimLength => (v0 + by(4.)).clamp(1, i64::from(frames.max(1))),
103 ScrubField::BoxOpacity => (v0 + by(2.)).clamp(0, 100),
104 ScrubField::KeyX | ScrubField::KeyY | ScrubField::KeyScale | ScrubField::KeyOpacity => {
105 let (lo, hi) = key_range(field);
106 (v0 + by(2.)).clamp(lo, hi)
107 }
108 ScrubField::Move => {
109 let moved = if pps > 0. { (f64::from(dx) / pps * fps).round() as i64 } else { 0 };
110 (v0 + moved).clamp(0, max_end - i64::from(frames))
111 }
112 }
113}
114
115/// The words a draft writes as the title's text: trailing spaces and breaks are dropped. Blank
116/// words are `None`, and the title keeps the words it had.
117/// How many frames an animation takes when none was chosen: half a second at the project's rate.
118pub(crate) fn anim_default_frames(fps: f64) -> u32 {
119 (engine::titleanim::DEFAULT_SECS * fps).round().max(1.) as u32
120}
121
122pub(crate) fn committed_title_words(draft: &str) -> Option<String> {
123 let text = draft.trim_end();
124 (!text.trim().is_empty()).then(|| text.to_string())
125}
126
127impl Player {
128 /// The title the Clip tab is about: the selected one, while it is still there and no clip is
129 /// selected (picking a clip ends the title selection, `pick`/`select` clear it).
130 pub(crate) fn title_target(&self) -> Option<(usize, Title)> {
131 let idx = self.title_sel?;
132 if !self.selected.is_empty() || self.sel_cue.is_some() || self.gap_pick().is_some() {
133 return None;
134 }
135 let t = self.session.as_ref()?.titles().get(idx)?.clone();
136 Some((idx, t))
137 }
138
139 /// `title` as it is on screen right now: with the words being typed and the number being
140 /// scrubbed laid over what the project holds.
141 pub(crate) fn shown_title(&self, title: &Title) -> Title {
142 let mut t = title.clone();
143 if let Some(field) = &self.title_draft
144 && !field.text.trim().is_empty()
145 {
146 t.text = field.text.clone();
147 }
148 if let Some(s) = self.title_scrub {
149 set_field(&mut t, s.field, s.cur, s.at);
150 }
151 t
152 }
153
154 /// Adds a title at the playhead, centred and five seconds long, selects it and opens its
155 /// words for typing.
156 pub(crate) fn new_title(&mut self, cx: &mut Context<Self>) {
157 if self.exporting().is_some() {
158 return;
159 }
160 self.commit_title_draft(cx);
161 let Some(session) = &mut self.session else {
162 self.notify_user("Nothing to add to — no file open".into());
163 cx.notify();
164 return;
165 };
166 let fps = session.meta().frame_rate;
167 let want = frame_at(session.now(), fps);
168 let (start, frames) = free_title_slot(session.titles(), want, ((NEW_SECS * fps).round() as u32).max(1), fps);
169 let moved = start != want;
170 let mut title = Title {
171 start,
172 frames,
173 text: NEW_TEXT.into(),
174 style: TextStyle { size: DEFAULT_SIZE, ..TextStyle::default() },
175 fade_in: 0,
176 fade_out: 0,
177 in_anim: Default::default(),
178 out_anim: Default::default(),
179 anim_frames: 0,
180 keys: Vec::new(),
181 };
182 title.apply_preset(Preset::Centered, fps);
183 // Up at once: a fade-in would have the new words nearly invisible where the playhead is.
184 (title.fade_in, title.fade_out) = (0, 0);
185 match session.add_title(title) {
186 Ok(idx) => {
187 self.mark_dirty();
188 self.open_title(idx, true, cx);
189 let undo = self.keymap.display(ActionId::Undo);
190 let at = match moved {
191 true => " after the one already on the playhead",
192 false => "",
193 };
194 self.notify_user(format!("Title added{at} · undo {undo}").into());
195 }
196 Err(e) => self.notify_user(e.to_string().into()),
197 }
198 cx.notify();
199 }
200
201 /// Selects title `idx`, shows its section in the Clip tab and, with `typing`, gives its words
202 /// the keyboard with all of them selected.
203 pub(crate) fn open_title(&mut self, idx: usize, typing: bool, cx: &mut Context<Self>) {
204 self.commit_title_draft(cx);
205 let Some(text) = self.session.as_ref().and_then(|s| s.titles().get(idx)).map(|t| t.text.clone()) else {
206 return;
207 };
208 self.selected.clear();
209 self.gap = None;
210 self.drop_sel_cue();
211 self.context_menu = None;
212 self.close_card();
213 self.keys_open = false;
214 self.dock_src_active = false;
215 if self.exporting().is_none() {
216 self.export_open = false;
217 }
218 self.title_sel = Some(idx);
219 self.title_draft = typing.then(|| TextField::selected(text));
220 self.title_hex = None;
221 cx.notify();
222 }
223
224 /// Ends the title selection (a clip was picked, the project changed). The words being typed
225 /// are written first, so a click away never loses them.
226 pub(crate) fn drop_title_selection(&mut self, cx: &mut Context<Self>) {
227 self.commit_title_draft(cx);
228 self.title_sel = None;
229 self.title_scrub = None;
230 }
231
232 /// Writes the draft words as the title's text (one undo step) and gives the keyboard back.
233 /// Empty words keep the old ones: a title needs some.
234 pub(crate) fn commit_title_draft(&mut self, cx: &mut Context<Self>) {
235 self.commit_title_hex(cx);
236 let Some(field) = self.title_draft.take() else {
237 return;
238 };
239 match committed_title_words(&field.text) {
240 Some(text) => {
241 self.write_title(|t| t.text = text, cx);
242 }
243 None => self.notify_user("A title needs words — kept the old ones".into()),
244 }
245 cx.notify();
246 }
247
248 /// A press on a colour field: its hex opens for typing with all of it selected.
249 pub(crate) fn begin_title_hex(&mut self, target: HexTarget, cx: &mut Context<Self>) {
250 self.commit_title_draft(cx);
251 let Some((_, t)) = self.title_target() else {
252 return;
253 };
254 let now = match target {
255 HexTarget::Ink => t.style.ink,
256 HexTarget::Box => [t.style.box_color[0], t.style.box_color[1], t.style.box_color[2]],
257 };
258 self.title_hex = Some((target, TextField::selected(hex_of(now))));
259 cx.notify();
260 }
261
262 /// Writes the typed hex as the title's colour (one undo step) and gives the keyboard back. Not
263 /// six hex digits keeps the old colour and says so.
264 pub(crate) fn commit_title_hex(&mut self, cx: &mut Context<Self>) {
265 let Some((target, field)) = self.title_hex.take() else {
266 return;
267 };
268 match parse_hex(&field.text) {
269 Some(rgb) => {
270 self.write_title(
271 |t| match target {
272 HexTarget::Ink => t.style.ink = rgb,
273 HexTarget::Box => t.style.box_color = [rgb[0], rgb[1], rgb[2], t.style.box_color[3]],
274 },
275 cx,
276 );
277 }
278 None => self.notify_user("A colour is six hex digits, such as ffcc00 — kept the old one".into()),
279 }
280 cx.notify();
281 }
282
283 /// Changes the selected title with `edit` (one undo step), following it to wherever the
284 /// engine's start order puts it. `false` when nothing changed.
285 pub(crate) fn write_title(&mut self, edit: impl FnOnce(&mut Title), cx: &mut Context<Self>) -> bool {
286 self.named_step("Title text", |this| this.write_title_now(edit, cx))
287 }
288
289 /// The same write as [`Self::write_title`], named as a keyframe change in the undo history.
290 pub(crate) fn write_title_key(&mut self, edit: impl FnOnce(&mut Title), cx: &mut Context<Self>) -> bool {
291 self.named_step("Title keyframe", |this| this.write_title_now(edit, cx))
292 }
293
294 fn write_title_now(&mut self, edit: impl FnOnce(&mut Title), cx: &mut Context<Self>) -> bool {
295 let Some(idx) = self.title_sel else {
296 return false;
297 };
298 let Some(session) = &mut self.session else {
299 return false;
300 };
301 let Some(mut title) = session.titles().get(idx).cloned() else {
302 return false;
303 };
304 edit(&mut title);
305 if !session.set_title(idx, title.clone()) {
306 return false;
307 }
308 self.title_sel = session.titles().iter().rposition(|t| *t == title).or(Some(idx));
309 self.mark_dirty();
310 cx.notify();
311 true
312 }
313
314 /// Takes the selected title off the timeline (one undo step).
315 pub(crate) fn remove_title_selected(&mut self, cx: &mut Context<Self>) {
316 let Some(idx) = self.title_sel else {
317 return;
318 };
319 self.title_draft = None;
320 self.title_hex = None;
321 self.title_scrub = None;
322 if self.session.as_mut().is_some_and(|s| s.remove_title(idx)) {
323 self.title_sel = None;
324 self.mark_dirty();
325 let undo = self.keymap.display(ActionId::Undo);
326 self.notify_user(format!("Title removed · undo {undo}").into());
327 }
328 cx.notify();
329 }
330
331 /// Applies a one-click style to the selected title.
332 pub(crate) fn apply_title_preset(&mut self, preset: Preset, cx: &mut Context<Self>) {
333 let fps = self.session.as_ref().map_or(25., |s| s.meta().frame_rate);
334 self.write_title(|t| t.apply_preset(preset, fps), cx);
335 }
336
337 /// The keyboard while the title's words are being typed (ahead of the palette and every
338 /// chord): enter commits, shift+enter breaks the line (a title can run to several), escape
339 /// throws the typed words away and keeps the title's own, the rest is text.
340 pub(crate) fn title_key(&mut self, key: &str, ctrl: bool, shift: bool, alt: bool, key_char: Option<&str>, cx: &mut Context<Self>) {
341 if let Some((_, field)) = self.title_hex.as_mut() {
342 let result = field.key(key, ctrl, alt, key_char, 7);
343 field.text.retain(|c| c.is_ascii_hexdigit() || c == '#');
344 match result {
345 FieldKey::Commit => self.commit_title_hex(cx),
346 FieldKey::Cancel => self.title_hex = None,
347 FieldKey::Edited => {}
348 }
349 cx.notify();
350 return;
351 }
352 let Some(field) = self.title_draft.as_mut() else {
353 return;
354 };
355 match key {
356 // The words go back to the title's own: nothing typed is written.
357 "escape" => self.title_draft = None,
358 "enter" if ctrl => self.commit_title_draft(cx),
359 "enter" if shift => {
360 if field.all {
361 field.text.clear();
362 field.all = false;
363 }
364 if field.text.chars().count() < MAX_TITLE_CHARS {
365 field.text.push('\n');
366 }
367 }
368 "enter" => self.commit_title_draft(cx),
369 _ => {
370 field.key(key, ctrl, alt, key_char, MAX_TITLE_CHARS);
371 }
372 }
373 cx.notify();
374 }
375
376 /// A press on one of the selected title's numbers (or on its block): the drag that follows
377 /// turns it.
378 pub(crate) fn begin_title_scrub(&mut self, field: ScrubField, x: f32, cx: &mut Context<Self>) {
379 self.commit_title_draft(cx);
380 let Some((_, t)) = self.title_target() else {
381 return;
382 };
383 let at = self.title_key_frame(&t).unwrap_or(0);
384 let v0 = get_field(&t, field, at);
385 self.title_scrub = Some(TitleScrub { field, x0: x, v0, cur: v0, at });
386 }
387
388 /// The pointer moved with a title scrub in flight: the number follows, shown live.
389 pub(crate) fn title_scrub_move(&mut self, x: f32, cx: &mut Context<Self>) {
390 let Some(s) = self.title_scrub else {
391 return;
392 };
393 let (fps, frames) = self
394 .title_target()
395 .map_or((25., 1), |(_, t)| (self.session.as_ref().map_or(25., |s| s.meta().frame_rate), t.frames));
396 let cur = scrub_value(s.field, s.v0, x - s.x0, fps, self.scale.pps, frames);
397 if cur != s.cur {
398 self.title_scrub = Some(TitleScrub { cur, ..s });
399 cx.notify();
400 }
401 }
402
403 /// The button came up: the scrubbed number is written as one undo step.
404 pub(crate) fn title_scrub_end(&mut self, cx: &mut Context<Self>) -> bool {
405 let Some(s) = self.title_scrub.take() else {
406 return false;
407 };
408 if s.cur != s.v0 {
409 match s.field.is_key() {
410 true => self.write_title_key(|t| set_field(t, s.field, s.cur, s.at), cx),
411 false => self.write_title(|t| set_field(t, s.field, s.cur, s.at), cx),
412 };
413 }
414 cx.notify();
415 true
416 }
417
418 /// The frame of the title's own keys the playhead is on, counted from the title's first frame.
419 /// `None` when the playhead is outside the title, where no key can be written.
420 pub(crate) fn title_key_frame(&self, t: &Title) -> Option<u32> {
421 let now = self.key_frame();
422 (t.start <= now && now < t.end()).then(|| now - t.start)
423 }
424
425 /// The ease of the title's key on the playhead, `None` with no key there.
426 pub(crate) fn title_key_here(&self, idx: usize) -> Option<KeyEase> {
427 let t = self.session.as_ref()?.titles().get(idx)?;
428 let at = self.title_key_frame(t)?;
429 t.keys.iter().find(|k| k.at == at).map(|k| k.ease)
430 }
431
432 /// The diamond: adds a key at the playhead holding what the title's keys give there, or takes
433 /// the key that is there off. One undo step.
434 pub(crate) fn toggle_title_key(&mut self, cx: &mut Context<Self>) {
435 let Some((_, stored)) = self.title_target() else {
436 return;
437 };
438 let Some(at) = self.title_key_frame(&stored) else {
439 self.notify_user("The playhead is outside this title".into());
440 cx.notify();
441 return;
442 };
443 let there = stored.keys.iter().any(|k| k.at == at);
444 self.write_title_key(
445 |t| match there {
446 true => t.keys.retain(|k| k.at != at),
447 false => {
448 key_index_at(t, at);
449 }
450 },
451 cx,
452 );
453 }
454
455 /// Sets the ease of the title's key on the playhead to the one the ease row picked, one undo
456 /// step. Nothing changes with no key there, where the row is disabled.
457 pub(crate) fn set_title_key_ease_here(&mut self, idx: usize, ease: KeyEase, cx: &mut Context<Self>) {
458 if self.title_sel != Some(idx) {
459 return;
460 }
461 let Some((_, stored)) = self.title_target() else {
462 return;
463 };
464 let Some(at) = self.title_key_frame(&stored) else {
465 return;
466 };
467 self.write_title_key(
468 |t| {
469 if let Some(k) = t.keys.iter_mut().find(|k| k.at == at) {
470 k.ease = ease;
471 }
472 },
473 cx,
474 );
475 }
476
477 /// Seeks the playhead to the next (`forward`) or the previous key of the selected title, and
478 /// says so when there is none that way. Keys past the title's last frame are held but never
479 /// reached; when the only keys ahead are such keys, the message says that instead.
480 pub(crate) fn jump_title_key(&mut self, forward: bool, cx: &mut Context<Self>) {
481 let Some((_, t)) = self.title_target() else {
482 return;
483 };
484 let now = self.key_frame();
485 let frames: Vec<u32> = t.keys.iter().filter(|k| k.at < t.frames).map(|k| t.start + k.at).collect();
486 let hit = match forward {
487 true => frames.iter().copied().find(|&f| f > now),
488 false => frames.iter().copied().rev().find(|&f| f < now),
489 };
490 match hit {
491 Some(f) => {
492 let at = f64::from(f) / self.active_fps();
493 self.seek(at, cx);
494 }
495 None => {
496 // A key past the end sits after every frame of the title, so it can only be ahead
497 // of the playhead going forward.
498 let past_end_ahead = forward && t.keys.iter().any(|k| k.at >= t.frames && t.start + k.at > now);
499 let message = match (forward, past_end_ahead) {
500 (true, true) => "The next key is past the title's end",
501 (true, false) => "No later key on this title",
502 (false, _) => "No earlier key on this title",
503 };
504 self.notify_user(message.into());
505 cx.notify();
506 }
507 }
508 }
509
510 /// Writes a typed percent as the title's key field at the playhead, one undo step. The key is
511 /// added there if the title has none. Outside the title there is no key, so it says so.
512 pub(crate) fn set_title_key_percent(&mut self, field: ScrubField, v: f64, cx: &mut Context<Self>) {
513 let Some((_, stored)) = self.title_target() else {
514 return;
515 };
516 let Some(at) = self.title_key_frame(&stored) else {
517 self.notify_user("The playhead is outside this title".into());
518 cx.notify();
519 return;
520 };
521 self.write_title_key(|t| set_field(t, field, v.round() as i64, at), cx);
522 }
523}
524
525/// One scrubbable number of a title. A key field reads the title's key at `at`, a frame counted
526/// from the title's first frame, or the rest a title with no keys holds.
527pub(crate) fn get_field(t: &Title, field: ScrubField, at: u32) -> i64 {
528 match field {
529 ScrubField::Size => i64::from(t.style.size),
530 ScrubField::Start | ScrubField::Move => i64::from(t.start),
531 ScrubField::Length => i64::from(t.frames),
532 ScrubField::AnimLength => i64::from(t.anim_frames),
533 ScrubField::BoxOpacity => (i64::from(t.style.box_color[3]) * 100 + 127) / 255,
534 ScrubField::KeyX | ScrubField::KeyY | ScrubField::KeyScale | ScrubField::KeyOpacity => {
535 (f64::from(key_number(&held_at(&t.keys, at), field)) * 100.).round() as i64
536 }
537 }
538}
539
540fn set_field(t: &mut Title, field: ScrubField, v: i64, at: u32) {
541 let u = v.max(0) as u32;
542 match field {
543 ScrubField::KeyX | ScrubField::KeyY | ScrubField::KeyScale | ScrubField::KeyOpacity => set_key_field(t, field, v, at),
544 ScrubField::Size => t.style.size = u,
545 ScrubField::Start | ScrubField::Move => t.start = u,
546 ScrubField::Length => {
547 t.frames = u.max(1);
548 t.fade_in = t.fade_in.min(t.frames);
549 t.fade_out = t.fade_out.min(t.frames);
550 }
551 ScrubField::AnimLength => t.anim_frames = u.clamp(1, t.frames.max(1)),
552 ScrubField::BoxOpacity => t.style.box_color[3] = ((u.min(100) * 255 + 50) / 100) as u8,
553 }
554}
555
556/// The least and the most a key field may read, in percent: the engine's limits as the card shows
557/// them. A shift runs both ways, the scale and the opacity do not.
558fn key_range(field: ScrubField) -> (i64, i64) {
559 match field {
560 ScrubField::KeyScale => ((KEY_SCALE_RANGE.0 * 100.).round() as i64, (KEY_SCALE_RANGE.1 * 100.).round() as i64),
561 ScrubField::KeyOpacity => (0, 100),
562 _ => (-100, 100),
563 }
564}
565
566/// The number a key holds for a key field: a share of the width or height for the shifts, a
567/// multiple for the scale and the opacity.
568fn key_number(k: &TitleKey, field: ScrubField) -> f32 {
569 match field {
570 ScrubField::KeyX => k.x,
571 ScrubField::KeyY => k.y,
572 ScrubField::KeyScale => k.scale,
573 _ => k.opacity,
574 }
575}
576
577/// The key the title's keys give at `at`: the interpolated one, or the rest a title with no keys
578/// holds (no shift, full size, full opacity).
579fn held_at(keys: &[TitleKey], at: u32) -> TitleKey {
580 sample(keys, f64::from(at)).unwrap_or(TitleKey { at, x: 0., y: 0., scale: 1., opacity: 1., ease: KeyEase::Linear })
581}
582
583/// The index of the key at `at`, adding one first when there is none. A new key holds what the
584/// title's keys give there, so adding it moves nothing.
585fn key_index_at(t: &mut Title, at: u32) -> usize {
586 match t.keys.binary_search_by_key(&at, |k| k.at) {
587 Ok(i) => i,
588 Err(i) => {
589 let held = held_at(&t.keys, at);
590 t.keys.insert(i, TitleKey { at, ease: KeyEase::Linear, ..held });
591 i
592 }
593 }
594}
595
596/// Writes a key field's percent into the title's key at `at`, adding that key when there is none.
597/// The value is held to the engine's limits.
598fn set_key_field(t: &mut Title, field: ScrubField, v: i64, at: u32) {
599 let (lo, hi) = key_range(field);
600 let share = v.clamp(lo, hi) as f32 / 100.;
601 let i = key_index_at(t, at);
602 let k = &mut t.keys[i];
603 match field {
604 ScrubField::KeyX => k.x = share.clamp(-1., 1.),
605 ScrubField::KeyY => k.y = share.clamp(-1., 1.),
606 ScrubField::KeyScale => k.scale = share.clamp(KEY_SCALE_RANGE.0, KEY_SCALE_RANGE.1),
607 _ => k.opacity = share.clamp(0., 1.),
608 }
609}
610
611/// Where a new title goes so it never hides, or is hidden by, one already there: the playhead
612/// when that is free, else just after the title it would sit on; and no longer than the room
613/// before the next one (a gap under a second is skipped over).
614pub(crate) fn free_title_slot(titles: &[engine::project::Title], want: u32, frames: u32, fps: f64) -> (u32, u32) {
615 let min = (fps.round() as u32).max(1);
616 let mut start = want;
617 loop {
618 if let Some(t) = titles.iter().filter(|t| t.start <= start && start < t.end()).max_by_key(|t| t.end()) {
619 start = t.end();
620 continue;
621 }
622 match titles.iter().filter(|t| t.start > start).map(|t| t.start).min() {
623 Some(next) if next - start < min => start = titles.iter().filter(|t| t.start == next).map(|t| t.end()).max().unwrap_or(next),
624 Some(next) => return (start, frames.min(next - start)),
625 None => return (start, frames),
626 }
627 }
628}
629
630#[cfg(test)]
631mod tests {
632 use super::*;
633 use engine::text::{Align, HPlace, Outline, Place, Weight};
634
635 fn title() -> Title {
636 Title { start: 100, frames: 125, text: "Hi".into(), style: TextStyle::default(), fade_in: 0, fade_out: 0, in_anim: Default::default(), out_anim: Default::default(), anim_frames: 0, keys: Vec::new() }
637 }
638
639 #[test]
640 fn a_preset_keeps_words_and_timing_and_holds_fades_inside_the_title() {
641 let mut t = title();
642 t.apply_preset(Preset::LowerThird, 25.);
643 assert_eq!((t.text.as_str(), t.start, t.frames), ("Hi", 100, 125));
644 assert_eq!((t.style.place, t.style.boxed, t.fade_in, t.fade_out), (Place::Bottom, true, 13, 13));
645 t.apply_preset(Preset::CaptionBar, 25.);
646 assert_eq!((t.fade_in, t.fade_out, t.style.size), (0, 0, 40));
647 t.frames = 10;
648 t.apply_preset(Preset::Centered, 25.);
649 assert_eq!((t.style.place, t.style.outline, t.fade_in), (Place::Centre, Outline::Thin, 5));
650 }
651
652 #[test]
653 fn a_scrub_follows_the_pointer_and_stays_inside_the_engines_limits() {
654 assert_eq!(scrub_value(ScrubField::Size, 50, 30., 25., 60., 125), 60);
655 assert_eq!(scrub_value(ScrubField::Size, 50, -3000., 25., 60., 125), i64::from(SIZE_RANGE.0));
656 assert_eq!(scrub_value(ScrubField::Size, 50, 3000., 25., 60., 125), i64::from(SIZE_RANGE.1));
657 assert_eq!(scrub_value(ScrubField::Length, 5, -400., 25., 60., 125), 1);
658 assert_eq!(scrub_value(ScrubField::AnimLength, 0, 4000., 25., 60., 125), 125);
659 // 60 px/s at 25 fps: 60 px is one second, 25 frames.
660 assert_eq!(scrub_value(ScrubField::Move, 100, 60., 25., 60., 125), 125);
661 assert_eq!(scrub_value(ScrubField::Move, 100, -6000., 25., 60., 125), 0);
662 }
663
664 #[test]
665 fn shortening_a_title_pulls_its_fades_in_with_it() {
666 let mut t = title();
667 t.fade_in = 40;
668 t.fade_out = 60;
669 set_field(&mut t, ScrubField::Length, 30, 0);
670 assert_eq!((t.frames, t.fade_in, t.fade_out), (30, 30, 30));
671 }
672
673 #[test]
674 fn a_key_field_adds_its_key_at_the_playhead_and_holds_the_limits() {
675 let mut t = title();
676 set_field(&mut t, ScrubField::KeyX, 150, 10);
677 assert_eq!((t.keys.len(), t.keys[0].at, t.keys[0].x), (1, 10, 1.));
678 assert_eq!(get_field(&t, ScrubField::KeyX, 10), 100);
679 set_field(&mut t, ScrubField::KeyScale, 0, 10);
680 assert_eq!(t.keys[0].scale, KEY_SCALE_RANGE.0);
681 }
682
683 #[test]
684 fn the_lower_third_is_bold_bottom_left_and_a_hex_colour_parses_or_is_refused() {
685 let mut t = title();
686 t.apply_preset(Preset::LowerThird, 25.);
687 let st = &t.style;
688 assert_eq!((st.place, st.hplace, st.align, st.weight, st.boxed), (Place::Bottom, HPlace::Left, Align::Left, Weight::Bold, true));
689 assert_eq!(parse_hex("#FFcc00"), Some([255, 204, 0]));
690 assert_eq!(hex_of([1, 2, 255]), "0102ff");
691 for bad in ["fff", "ggg000", "", "ffcc000"] {
692 assert_eq!(parse_hex(bad), None, "{bad}");
693 }
694 let mut t = title();
695 set_field(&mut t, ScrubField::BoxOpacity, 50, 0);
696 assert_eq!(t.style.box_color[3], 128);
697 assert_eq!(get_field(&t, ScrubField::BoxOpacity, 0), 50);
698 }
699
700 #[test]
701 fn a_new_title_goes_after_the_one_on_the_playhead_and_fits_before_the_next() {
702 let t = |start, frames| Title { start, frames, text: "t".into(), style: TextStyle::default(), fade_in: 0, fade_out: 0, in_anim: Default::default(), out_anim: Default::default(), anim_frames: 0, keys: Vec::new() };
703 let titles = [t(0, 150), t(200, 150)];
704 // Free: where it was asked, and cut to the room before the next title.
705 assert_eq!(free_title_slot(&[], 10, 150, 30.), (10, 150));
706 // On a title: just after it, which leaves 50 frames before the next.
707 assert_eq!(free_title_slot(&titles, 0, 150, 30.), (150, 50));
708 // A gap under a second is skipped over to the room after the next title.
709 let tight = [t(0, 150), t(160, 150)];
710 assert_eq!(free_title_slot(&tight, 0, 150, 30.), (310, 150));
711 }
712}