forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

preview.rs1370 lines, 64.3 KiBHistoryRawDownload
1//! The picture: what is drawn over it and what is read off it.
2
3use crate::titles;
4use crate::ui::hitmap;
5use crate::ui::icons::{Icon, IconSize};
6use crate::ui::type_scale::{self, Typeset};
7use crate::*;
8use std::path::{Path, PathBuf};
9
10/// What the preview's one cached cue picture is *of*: the lane, the moment,
11/// the cue's own end, and the picture itself.
12///
13/// The lane and the start microsecond alone are not a cue. Two bitmap cues can
14/// share both -- lift a caption off a lane and drop another track's caption at
15/// the same frame -- and with those two as the whole key the cache's `up == key`
16/// test matched, painting the picture of the cue that is gone over the one that
17/// is up.
18///
19/// The picture's own allocation ([`Arc::as_ptr`]) is the identity: the cue list
20/// a repaint is handed holds the same `Arc` for as long as that cue is in it, so
21/// two repaints of one cue compare equal -- which is the whole cache hit -- while
22/// two different cues never do. The bytes are never compared: a display set is
23/// tens of kilobytes and this test runs on every frame.
24#[derive(Clone, Copy, PartialEq, Eq, Debug)]
25pub(crate) struct SubImageKey {
26 pub(crate) lane: Lane,
27 pub(crate) start_us: i64,
28 /// The cue's own end, so the same picture recut over the same start reads as
29 /// a different cue here too.
30 pub(crate) end_us: i64,
31 /// Where that picture lives -- [`Arc::as_ptr`] of the cue's image.
32 pub(crate) picture: usize,
33}
34
35/// [`SubImageKey`] for one cue's picture: the one place the key is built, so the
36/// lookup that trusts a hit and the test that pins what a hit means cannot drift
37/// apart. `picture` is where the cue's image lives -- the caller passes
38/// `Arc::as_ptr` of it, and nothing about the bytes is ever read here.
39pub(crate) fn sub_image_key(lane: Lane, start_us: i64, end_us: i64, picture: usize) -> SubImageKey {
40 SubImageKey {
41 lane,
42 start_us,
43 end_us,
44 picture,
45 }
46}
47
48/// The width of the welcome hero, and the most of it a project's name may take in a recent row.
49const WELCOME_W: f32 = 460.;
50const WELCOME_NAME_MAX_W: f32 = 190.;
51/// A recent-project row, and the heading above the rows (with its gap): together they are the
52/// block the hero reserves, so the hero does not move when the list fills in.
53const WELCOME_ROW_H: f32 = 36.;
54const WELCOME_HEAD_H: f32 = 28.;
55/// The source strip's ruler: room for its labels over the ticks.
56const SOURCE_RULER_H: f32 = 28.;
57
58impl Player {
59 /// What a window with no project shows in the picture (REDESIGN §3.11): the welcome hero,
60 /// the one empty state of the app. New project and Open… are the two ways in, the recent
61 /// projects sit under them, and the window itself is the drop target (so the hint says so).
62 pub(crate) fn empty_viewer(&self, cx: &mut Context<Self>) -> impl IntoElement + use<> {
63 use crate::ui::kit::{Button, ButtonSize, ButtonStyle};
64 use crate::ui::theme::tokens;
65 let t = tokens();
66 // The viewer is only ~240px tall at 1280x720: the hero sheds its icon, then its recent
67 // rows, rather than clip (the probe reads 0 until the first frame has been laid out).
68 let avail = match f32::from(self.picture_box.get().size.height) {
69 h if h > 1. => h - 24.,
70 _ => 400.,
71 };
72 let pending = self.new_project.is_some();
73 let show_icon = avail >= 300.;
74 let base = if show_icon { 168. } else { 114. };
75 let rows = (((avail - base - 52.) / WELCOME_ROW_H).floor().max(0.) as usize).min(WELCOME_RECENT_MAX);
76 let all_recent = crate::recent::list();
77 let have_recent = !all_recent.is_empty();
78 let recent: Vec<crate::recent::Recent> = all_recent.into_iter().take(rows).collect();
79 let template_rows_now = if self.welcome_templates { Some(crate::ui::menubar::template_rows(cx, false)) } else { None };
80 let row = |i: usize, r: crate::recent::Recent| {
81 let open = r.missing.is_none();
82 let path = r.path.clone();
83 let reason = r.missing.map(crate::recent::Missing::reason);
84 // What is left of the row once the icon, the name and the gaps are paid for.
85 let name_w = crate::ui::popup::text_w(&r.name, type_scale::BODY_PX, false).min(WELCOME_NAME_MAX_W);
86 let left = WELCOME_W - 20. - 16. - 20. - name_w - 6.;
87 let folder_chars = (left / crate::ui::popup::text_w("n", type_scale::CAPTION_PX, false)).floor().max(4.) as usize;
88 div()
89 .id(("welcome-recent", i))
90 .h(px(WELCOME_ROW_H))
91 .w_full()
92 .px(px(10.))
93 .flex()
94 .items_center()
95 .gap(px(10.))
96 .rounded(px(4.))
97 .when(open, |d| {
98 d.cursor_pointer().hover(move |s| s.bg(rgb(t.e2))).on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
99 this.open_recent(&path, cx);
100 }))
101 })
102 .child(Icon::Film.el(IconSize::Inline, if open { t.ink2 } else { t.ink4 }))
103 .child(
104 div()
105 .flex_none()
106 .max_w(px(WELCOME_NAME_MAX_W))
107 .truncate()
108 .type_style(type_scale::body_strong())
109 .text_color(rgb(if open { t.ink1 } else { t.ink3 }))
110 .child(r.name.clone()),
111 )
112 .child(
113 div()
114 .flex_1()
115 .min_w(px(0.))
116 .truncate()
117 .type_style(type_scale::caption())
118 .text_color(rgb(t.ink2))
119 .child(reason.map_or_else(|| crate::recent::middle(&r.folder, folder_chars), str::to_string)),
120 )
121 };
122 div()
123 .id("viewer-welcome")
124 .flex_none()
125 .w(px(WELCOME_W))
126 .flex()
127 .flex_col()
128 .items_center()
129 .gap(px(6.))
130 .when(show_icon, |d| d.child(Icon::Clapperboard.el(IconSize::Hero, t.ink3)))
131 .child(
132 div()
133 .mt(px(if show_icon { 8. } else { 0. }))
134 .type_style(type_scale::title())
135 .text_color(rgb(t.ink1))
136 .child(match &self.new_project {
137 Some(_) => self.name.to_string(),
138 None => EMPTY_VIEWER_TITLE.to_string(),
139 }),
140 )
141 .child(div().type_style(type_scale::body()).text_color(rgb(t.ink2)).child(match &self.new_project {
142 Some(_) => {
143 let (w, h) = self.pending_settings.0.unwrap_or((1920, 1080));
144 format!("{w}\u{d7}{h} at {:.0} fps: drop footage here or import media", self.pending_settings.1.unwrap_or(30.))
145 }
146 None => EMPTY_VIEWER_LINE.to_string(),
147 }))
148 .child(
149 div()
150 .mt(px(14.))
151 .flex()
152 .gap(px(8.))
153 .child(
154 // A project waiting for its footage: the import is the way forward, so it takes
155 // the primary style and New project says why it is not offered again.
156 Button::new("welcome-new")
157 .label("New project")
158 .icon(Icon::Plus)
159 .style(if pending { ButtonStyle::Secondary } else { ButtonStyle::Primary })
160 .size(ButtonSize::Hero)
161 .enabled(!pending)
162 .build()
163 .tooltip(match pending {
164 true => crate::ui::widgets::tip_hover("New project", "", Some("A project is waiting for footage: import media to start it")),
165 false => crate::ui::widgets::tip_hover("New project", "Name it, pick a size and rate", None),
166 })
167 .children(hitmap::control("welcome.new", "New project", true))
168 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.open_new_project(cx))),
169 )
170 .child({
171 // From template: the same list as the File menu's, as a dropdown under the button
172 // (absolute, so the buttons beside it do not move when it opens).
173 let mut slot = div().relative().child(
174 Button::new("welcome-template")
175 .label("From template")
176 .icon(Icon::Layers)
177 .style(ButtonStyle::Secondary)
178 .size(ButtonSize::Hero)
179 .build()
180 .tooltip(crate::ui::widgets::tip_hover("From template", "Start from a saved or built-in template", None))
181 .children(hitmap::control("welcome.template", "From template", true))
182 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
183 this.welcome_templates = !this.welcome_templates;
184 cx.notify();
185 })),
186 );
187 if let Some(rows) = template_rows_now {
188 // Deferred, so the viewer's clipping edge does not cut the list short.
189 slot = slot.child(gpui::deferred(crate::ui::popup::popup_plate("welcome-templates", 0., ButtonSize::Hero.height() + 6., 260.).children(rows)));
190 }
191 slot
192 })
193 .child(
194 Button::new("welcome-open")
195 .label("Open project…")
196 .icon(Icon::FolderOpen)
197 .style(ButtonStyle::Secondary)
198 .size(ButtonSize::Hero)
199 .build()
200 .tooltip(crate::ui::widgets::tip_hover("Open project", "", None))
201 .children(hitmap::control("welcome.open", "Open project", true))
202 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.pick_open_project(cx))),
203 )
204 .child(
205 Button::new("welcome-import")
206 .label("Import media…")
207 .icon(Icon::Download)
208 .style(if pending { ButtonStyle::Primary } else { ButtonStyle::Secondary })
209 .size(ButtonSize::Hero)
210 .build()
211 .tooltip(crate::ui::widgets::tip_hover("Import media", "Video, audio or images", None))
212 .children(hitmap::control("welcome.import", "Import media", true))
213 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.pick_and_import(cx))),
214 ),
215 )
216 // The recent block is always as tall as `rows` rows and its heading, whether the list
217 // is long, short or not loaded, so the buttons above it never move.
218 .child(
219 div()
220 .flex_none()
221 .w_full()
222 .h(px(if have_recent && rows > 0 { WELCOME_HEAD_H + 8. + rows as f32 * WELCOME_ROW_H } else { 0. }))
223 .mt(px(20.))
224 .flex()
225 .flex_col()
226 .when(!recent.is_empty(), |d| {
227 d.child(
228 div()
229 .h(px(WELCOME_HEAD_H))
230 .w_full()
231 .px(px(10.))
232 .flex()
233 .items_center()
234 .type_style(type_scale::section())
235 .text_color(rgb(t.ink2))
236 .child("Recent projects"),
237 )
238 .children(recent.into_iter().enumerate().map(|(i, r)| row(i, r)))
239 }),
240 )
241 }
242
243 /// The note over the picture when the clip under the playhead reads from a file that is no
244 /// longer on the disk: a compact banner along the top of the picture, a warning, the words,
245 /// and Relink… beside them, the same relink the media list offers ([`Player::relink_pick`]).
246 /// Along the top, not the middle, so the picture and its titles stay in view. `None` otherwise.
247 pub(crate) fn missing_clip_note(&self, cx: &mut Context<Self>) -> Option<impl IntoElement + use<>> {
248 use crate::ui::kit::{Button, ButtonStyle};
249 let session = self.session.as_ref()?;
250 let offline = session.offline_sources();
251 let (lane, idx) = self.under_playhead().into_iter().next()?;
252 let source = session.lane_clips(lane).get(idx)?.source;
253 let (_, path) = offline.into_iter().find(|(i, _)| *i == source)?;
254 let t = crate::ui::theme::tokens();
255 Some(
256 div()
257 .absolute()
258 .top(px(8.))
259 .left_0()
260 .right_0()
261 .flex()
262 .justify_center()
263 .child(
264 div()
265 .flex()
266 .items_center()
267 .gap(px(8.))
268 .pl(px(10.))
269 .pr(px(6.))
270 .py(px(4.))
271 .rounded(px(6.))
272 .bg(rgba(crate::ui::theme::with_alpha(t.e0, 0xD9)))
273 .border_1()
274 .border_color(rgba(crate::ui::theme::with_alpha(t.warn, 0x80)))
275 .type_style(type_scale::body())
276 .text_color(rgb(t.ink1))
277 .child(crate::ui::icons::Icon::TriangleAlert.el_px(px(14.), t.warn))
278 .child(div().whitespace_nowrap().child("This clip's file is missing"))
279 .child(
280 Button::new("viewer-relink")
281 .label("Relink…")
282 .style(ButtonStyle::Secondary)
283 .build()
284 .tooltip(crate::ui::widgets::tip_hover("Relink", "", None))
285 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| this.relink_pick(path.clone(), cx))),
286 ),
287 ),
288 )
289 }
290
291 /// The source monitor's strip (REDESIGN: the pro-NLE source viewer), a flex
292 /// sibling under the picture so nothing is drawn over it. Its mini ruler
293 /// spans the source's whole length: click or drag to scrub, the marked
294 /// part in..out is the shaded band between two brackets, the playhead is
295 /// the white line. Under it the marking and placing controls: In, Out,
296 /// clear, which halves go (picture, sound), and Insert / Overwrite at the
297 /// timeline's playhead. Every cell keeps its size whatever the state, so
298 /// marking or toggling moves nothing.
299 pub(crate) fn source_strip(&self, window: &Window, cx: &mut Context<Self>) -> Option<impl IntoElement> {
300 use crate::ui::kit::{Button, ButtonSize, ButtonStyle};
301 let session = self.preview_session.as_ref()?;
302 let t = crate::ui::theme::tokens();
303 let short = f32::from(window.viewport_size().height) < 800.;
304 let dur = session.timeline_duration().max(0.001);
305 let fps = self.active_fps();
306 let now = session.now().clamp(0., dur);
307 let (a, b) = self
308 .source_target
309 .as_ref()
310 .and_then(|k| self.source_marks.get(k))
311 .copied()
312 .unwrap_or((None, None));
313 let frac = |s: f64| crate::transport::preview_progress_along(s, dur);
314 let marked = match (a, b) {
315 (None, None) => dur,
316 (a, b) => (b.unwrap_or(dur) - a.unwrap_or(0.)).max(0.),
317 };
318 let path = self.source_target.as_ref().map(|(p, _)| p.clone());
319 let has_picture = path.as_ref().is_some_and(|p| !engine::is_audio(p));
320 let has_sound = path.as_ref().is_some_and(|p| !engine::is_image(p));
321 let can_edit = self.session.is_some() && self.exporting().is_none();
322 let cell = |text: String, w: f32| {
323 div()
324 .flex_none()
325 .w(px(w))
326 .type_style(type_scale::label_tabular(type_scale::BODY_PX, gpui::FontWeight::MEDIUM))
327 .text_color(rgb(t.ink1))
328 .whitespace_nowrap()
329 .child(text)
330 };
331 // The ruler's ticks: the timeline ruler's own step rule at this bar's width, a label on
332 // a tick only where the labels clear each other.
333 let bar_w = match f32::from(self.preview_bar.get().size.width) {
334 w if w > 1. => w,
335 _ => 700.,
336 };
337 let step = ruler_step(f64::from(bar_w) / dur, fps, 56.);
338 let step_secs = step.secs(fps).max(0.001);
339 let ticks: Vec<(f32, Option<String>)> = (0..)
340 .map(|i| (i, i as f64 * step_secs))
341 .take_while(|(i, at)| *at <= dur && *i < 400)
342 .map(|(i, at)| {
343 let labelled = f64::from(bar_w) * step_secs / dur >= 56. || i == 0;
344 (frac(at), labelled.then(|| ruler_label(step, i, fps)))
345 })
346 .collect();
347 let track = div()
348 .id("source-ruler")
349 .flex_1()
350 .min_w(px(0.))
351 .h(px(SOURCE_RULER_H))
352 .relative()
353 .rounded(px(3.))
354 .overflow_hidden()
355 .bg(rgb(t.e2))
356 .cursor_pointer()
357 .on_mouse_down(
358 MouseButton::Left,
359 cx.listener(|this, event: &MouseDownEvent, _, cx| {
360 this.preview_scrubbing = true;
361 this.preview_scrub_to(event.position.x, true, cx);
362 }),
363 )
364 .tooltip(crate::ui::widgets::tip_hover("Source ruler", "Click or drag", None))
365 .children(hitmap::control("source.ruler", "Source ruler", true))
366 .child(bounds_probe(self.preview_bar.clone()))
367 .when(a.is_some() || b.is_some(), |d| {
368 let (l, r) = (frac(a.unwrap_or(0.)), frac(b.unwrap_or(dur)));
369 d.child(
370 div()
371 .absolute()
372 .top_0()
373 .bottom_0()
374 .left(relative(l))
375 .w(relative((r - l).max(0.)))
376 .bg(rgb(crate::ui::theme::mix(t.e2, t.accent, 0.35))),
377 )
378 })
379 .children(ticks.into_iter().map(|(at, label)| {
380 // A label is skipped where an in or out marker would cover it.
381 let label = label.filter(|text| {
382 let x = at * bar_w + 3.;
383 let w = text.chars().count() as f32 * 7. + 2.;
384 [a, b].into_iter().flatten().all(|m| {
385 let mx = frac(m) * bar_w;
386 mx + 3. < x - 4. || mx - 3. > x + w + 2.
387 })
388 });
389 div()
390 .absolute()
391 .bottom_0()
392 .left(relative(at))
393 .w(px(1.))
394 .h(px(if label.is_some() { 9. } else { 5. }))
395 .bg(rgb(t.ink4))
396 .children(label.map(|text| {
397 div()
398 .absolute()
399 .bottom(px(7.))
400 .left(px(3.))
401 .whitespace_nowrap()
402 .type_style(type_scale::caption())
403 .text_color(rgb(t.ink3))
404 .child(text)
405 }))
406 }))
407 .children(a.map(|x| {
408 div().absolute().top_0().bottom_0().left(relative(frac(x))).w(px(3.)).bg(rgb(t.accent))
409 }))
410 .children(b.map(|x| {
411 div()
412 .absolute()
413 .top_0()
414 .bottom_0()
415 .left(relative(frac(x)))
416 .ml(px(-3.))
417 .w(px(3.))
418 .bg(rgb(t.accent))
419 }))
420 .child(
421 div()
422 .absolute()
423 .top_0()
424 .bottom_0()
425 .left(relative(frac(now)))
426 .w(px(2.))
427 .bg(rgb(t.ink1)),
428 );
429 let icon_toggle = |id: &'static str, icon: Icon, label: &'static str, on: bool, usable: bool| {
430 Button::new(id)
431 .style(ButtonStyle::Ghost)
432 .size(ButtonSize::Small)
433 .icon(icon)
434 .label(label)
435 .on(on && usable)
436 .enabled(usable)
437 .build()
438 };
439 // A mark is its icon and where it is set, one control: a press sets it at the playhead.
440 // The word says which mark it is; the value is the moment, or "Not set" in ink3 while unset.
441 let mark_btn = |id: &'static str, icon: Icon, word: &'static str, at: Option<f64>, action: ActionId, cx: &mut Context<Self>| {
442 let value = match at {
443 Some(s) => div().child(timecode(s, fps)),
444 None => div().text_color(rgb(t.ink3)).child("Not set"),
445 };
446 Button::new(id)
447 .style(ButtonStyle::Ghost)
448 .size(ButtonSize::Small)
449 .icon(icon)
450 .label(word)
451 .on(at.is_some())
452 .build()
453 .child(value)
454 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| this.act(action, window, cx)))
455 .tooltip(crate::ui::widgets::action_hover(self, action))
456 .children(hitmap::action(action, true))
457 };
458 let place_btn = |id: &'static str, icon: Icon, label: &'static str, action: ActionId, cx: &mut Context<Self>| {
459 Button::new(id)
460 .style(ButtonStyle::Secondary)
461 .size(ButtonSize::Small)
462 .icon(icon)
463 .label(label)
464 .enabled(can_edit)
465 .build()
466 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| this.act(action, window, cx)))
467 .tooltip(crate::ui::widgets::action_hover(self, action))
468 .children(hitmap::action(action, can_edit))
469 };
470 let marked_any = a.is_some() || b.is_some();
471 Some(
472 div()
473 .id("source-strip")
474 .flex_none()
475 .w_full()
476 .flex()
477 .flex_col()
478 .gap(px(4.))
479 .px(px(12.))
480 .pt(px(4.))
481 .pb(px(if short { 2. } else { 6. }))
482 .bg(rgb(t.matte))
483 .child(
484 div()
485 .flex()
486 .items_center()
487 .gap(px(10.))
488 .child(cell(timecode(now, fps), 96.))
489 .child(track)
490 .child(cell(timecode(marked, fps), 96.).text_color(rgb(t.ink3)).text_right()),
491 )
492 .child(
493 div()
494 .flex()
495 .items_center()
496 .gap(px(4.))
497 .child(mark_btn("src-in", Icon::SquareArrowDownRight, "In", a, ActionId::SetIn, cx))
498 .child(mark_btn("src-out", Icon::SquareArrowDownLeft, "Out", b, ActionId::SetOut, cx))
499 .child(
500 Button::new("src-clear")
501 .style(ButtonStyle::Ghost)
502 .size(ButtonSize::Small)
503 .icon(Icon::Eraser)
504 .label("Clear")
505 .enabled(marked_any)
506 .build()
507 .on_click(cx.listener(|this, _: &ClickEvent, window, cx| {
508 this.act(ActionId::ClearRange, window, cx)
509 }))
510 .tooltip(crate::ui::widgets::tip_hover(
511 "Clear",
512 &self.keymap.display(ActionId::ClearRange),
513 if marked_any { None } else { Some("No In or Out set") },
514 ))
515 .children(hitmap::action(ActionId::ClearRange, marked_any)),
516 )
517 .child(div().flex_1().min_w(px(0.)))
518 .child(
519 icon_toggle("src-video", Icon::Film, "Video", self.source_video, has_picture)
520 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
521 this.source_video = !this.source_video;
522 cx.notify();
523 }))
524 .tooltip(crate::ui::widgets::tip_hover(
525 "Video",
526 "",
527 Some(if has_picture {
528 "Insert and Overwrite place the picture when this is on"
529 } else {
530 "This clip has no picture"
531 }),
532 ))
533 .children(hitmap::control("source.video", "Source picture", has_picture)),
534 )
535 .child(
536 icon_toggle("src-audio", Icon::AudioWaveform, "Audio", self.source_audio, has_sound)
537 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
538 this.source_audio = !this.source_audio;
539 cx.notify();
540 }))
541 .tooltip(crate::ui::widgets::tip_hover(
542 "Audio",
543 "",
544 Some(if has_sound {
545 "Insert and Overwrite place the sound when this is on"
546 } else {
547 "This clip has no sound"
548 }),
549 ))
550 .children(hitmap::control("source.audio", "Source sound", has_sound)),
551 )
552 .child(div().w(px(8.)))
553 .child(place_btn("src-insert", Icon::ArrowRightToLine, "Insert", ActionId::InsertSource, cx))
554 .child(place_btn("src-overwrite", Icon::Layers, "Overwrite", ActionId::OverwriteSource, cx)),
555 ),
556 )
557 }
558
559 /// The frame on screen right now, written to a PNG -- at the size the
560 /// **project** is, not at the size the preview shows it.
561 ///
562 /// The picture area asks the session for frames the size of its own box
563 /// ([`PlaybackSession::set_view_size`]), so the atlas holds a preview-sized
564 /// picture: saving that would cost the user the resolution they asked for
565 /// (a still of a 1080p project, an 11th of it). So the seat is asked for
566 /// one picture at the project's own size and the file is written when it
567 /// lands ([`Player::flush_shot`], off `pump`'s frame-owed signal). Every
568 /// other part of the gesture is what it always was: the same directory,
569 /// the same name, the same notice.
570 ///
571 /// A library preview is the same rule about *its* file: the seat paints at
572 /// the file's own resolution for it, which is the full size a still of that
573 /// file wants.
574 pub(crate) fn take_screenshot(&mut self, cx: &mut Context<Self>) {
575 if self.shot_pending.is_some() {
576 return; // one at a time: the picture is on its way
577 }
578 let Some(session) = self.active_session() else {
579 self.notify_user("No frame to save: nothing is showing yet".into());
580 cx.notify();
581 return;
582 };
583 let full = (session.meta().width, session.meta().height);
584 let stem = session
585 .sources()
586 .first()
587 .map_or_else(|| self.name.to_string(), |s| file_name(&s.path));
588 let stem = std::path::Path::new(&stem)
589 .file_stem()
590 .map_or(stem.clone(), |s| s.to_string_lossy().into_owned());
591 let tc = timecode(session.now(), self.active_fps()).replace(':', "-");
592 // The *exact* setter, not the deadbanded push: a view within 8 px of
593 // the project is a still of the wrong size. `false` says the view is
594 // already at it -- and then the frame in hand *is* the project's frame,
595 // so waiting for a picture that would never come (nothing moved, so
596 // nothing reseeks) is exactly the trap this avoids.
597 let moved = self
598 .active_session_mut()
599 .is_some_and(|s| s.set_view_size_exact(full.0, full.1));
600 if moved {
601 // One frame at the project's own size, which is a reseek like any
602 // other edit: the frame it owes is what the flush waits on.
603 if let Some(session) = self.active_session_mut() {
604 session.resync_picture();
605 }
606 self.shot_pending = Some((self.session_gen, stem, tc));
607 self.reset_after_reseek();
608 } else if !self.write_shot(&stem, &tc) {
609 self.notify_user("No frame to save: nothing is showing yet".into());
610 }
611 cx.notify();
612 }
613
614 /// Writes the picture the atlas is holding, at the size it holds it, and
615 /// says whether there was one. The tail [`Player::take_screenshot`] and
616 /// [`Player::flush_shot`] share, so the two doors cannot write differently.
617 fn write_shot(&mut self, stem: &str, tc: &str) -> bool {
618 let Some(image) = self.image.clone() else {
619 return false;
620 };
621 let Some(bytes) = image.as_bytes(0) else {
622 return false;
623 };
624 let size = image.size(0);
625 match save_screenshot(bytes, size.width.0 as u32, size.height.0 as u32, stem, tc) {
626 Ok(path) => self.notify_user_action(
627 format!("Frame saved as {}", file_name(&path)).into(),
628 ToastAction::ShowInFolder(path),
629 ),
630 Err(e) => self.notify_user(format!("Couldn't save the frame: {e}").into()),
631 }
632 true
633 }
634
635 /// The screenshot a preview-sized picture had to wait for: written once the
636 /// seat's project-sized frame has landed, then the preview takes its own
637 /// size back ([`Player::push_view_size`] pushes it on the next repaint).
638 ///
639 /// A picture that never lands -- the timeline emptied, a source that died
640 /// -- gives up rather than leaving the preview stuck at the project's size:
641 /// the wait is bounded, and the notice names what happened.
642 pub(crate) fn flush_shot(&mut self, cx: &mut Context<Self>) {
643 let Some((asked, stem, tc)) = self.shot_pending.clone() else {
644 return;
645 };
646 if asked != self.session_gen {
647 // The session that asked is gone (a preview opened, another file
648 // opened, a session closed): its picture is not coming, and the new
649 // session's frame must not be written under its name.
650 self.shot_pending = None;
651 self.notify_user("No frame to save: the session changed meanwhile".into());
652 cx.notify();
653 return;
654 }
655 if self
656 .seek_since
657 .is_some_and(|since| since.elapsed() < std::time::Duration::from_secs(2))
658 {
659 return; // the frame is still being painted
660 }
661 self.shot_pending = None;
662 // The seat's own clamp is the truth about the size it can paint, which
663 // is what the ask settled on ([`PlaybackSession::set_view_size_exact`]),
664 // and with the push held while the shot is in flight
665 // ([`Player::push_view_size`]) it is still holding it here.
666 let want = self.active_session().map(PlaybackSession::view_size);
667 let landed = self
668 .image
669 .as_ref()
670 .map(|i| (i.size(0).width.0 as u32, i.size(0).height.0 as u32))
671 == want;
672 if !landed || !self.write_shot(&stem, &tc) {
673 self.notify_user("No frame to save: the picture could not be redrawn".into());
674 }
675 cx.notify();
676 }
677
678 /// The active session has been swapped (`session` or `preview_session`):
679 /// what anything keyed to a session has to hear. A screenshot in flight is
680 /// the one such thing ([`Player::shot_pending`]), and it is *keyed* rather
681 /// than cleared here because a door that forgot to call this would still be
682 /// caught by the key -- the picture it is holding came from a session that
683 /// is no longer the one on screen.
684 pub(crate) fn session_swapped(&mut self) {
685 self.session_gen += 1;
686 self.title_sel = None;
687 self.title_draft = None;
688 self.title_hex = None;
689 self.gen_hex = None;
690 self.title_scrub = None;
691 self.pan_scrub = None;
692 }
693
694 /// The title cards up at the playhead, over the picture and under the
695 /// captions ([`Player::picture_area`] mounts this before the cue plate).
696 /// Each title is set in its own style the way the engine burns it: its size
697 /// is a share of the *displayed* picture's height, the words sit in the
698 /// title-safe margins at the style's place, a box is the engine's translucent
699 /// black, and the opacity is the title's alpha at the playhead's frame.
700 ///
701 /// Only the timeline's own titles, and only with no preview open: a preview
702 /// is another file, as the captions are. Not an exact match of the export:
703 /// the words are the app's family, not the engine's bundled face, and the
704 /// wrap is the browser's line break.
705 pub(crate) fn title_overlay(&self, at: f64, dpr: f32, window: &Window, cx: &mut Context<Self>) -> Option<impl IntoElement + use<>> {
706 if self.preview_session.is_some() {
707 return None;
708 }
709 let session = self.session.as_ref()?;
710 if session.titles().is_empty() {
711 return None;
712 }
713 // The picture is contained in the region the way it is drawn, so the
714 // titles are placed against the picture and not the letterbox around it.
715 let region = self.picture_box.get();
716 let region = titles::Rect {
717 x: 0.,
718 y: 0.,
719 w: f32::from(region.size.width),
720 h: f32::from(region.size.height),
721 };
722 let meta = session.meta();
723 let picture = match self.viewer.zoom {
724 crate::viewer_view::Zoom::Fit => titles::contain(region, meta.width as f32, meta.height as f32),
725 // Zoomed and panned: against the picture as drawn, which may be
726 // bigger than the region (the region clips) or smaller than it.
727 _ => self.viewer_frame_local(dpr).map_or(region, |(x, y, w, h)| titles::Rect { x, y, w, h }),
728 };
729 if picture.w <= 0. || picture.h <= 0. {
730 return None;
731 }
732 let frame = frame_at(at, self.active_fps());
733 // The selected title is drawn as it is being edited: the words typed so far and the
734 // number being scrubbed laid over what the project holds.
735 let picked = self.title_target().map(|(i, _)| i);
736 let shown: Vec<engine::Title> = session
737 .titles()
738 .iter()
739 .enumerate()
740 .map(|(i, t)| if picked == Some(i) { self.shown_title(t) } else { t.clone() })
741 .collect();
742 // Each title's motion at this frame ([`engine::Title::motion_at`]), the same one the export draws.
743 let up: Vec<(usize, &engine::Title, u8, engine::titleanim::Motion)> = titles::active_titles(&shown, frame)
744 .into_iter()
745 .filter_map(|(t, a)| Some((shown.iter().position(|s| std::ptr::eq(s, t))?, t, a, t.motion_at(frame)?)))
746 .collect();
747 if up.is_empty() {
748 return None;
749 }
750 let family = self.sub_family.clone();
751 // The font a title's text is set in before its family and weight: the window's own.
752 let base_font = window.text_style().font();
753 // Each title is laid in the picture's own coordinates, so the layer
754 // below is picture-local and the whole stack sits at the picture's box.
755 let local = titles::Rect {
756 x: 0.,
757 y: 0.,
758 w: picture.w,
759 h: picture.h,
760 };
761 let area = titles::title_area(local);
762 // The transient bars along the bottom edge are over the picture, and a
763 // title that sits at the bottom steps up over them the way a caption
764 // does, so the words are not drawn under a notice.
765 let bars = f32::from(self.notice_h.get());
766 let layers = up.into_iter().map(|(i, title, alpha, motion)| {
767 // The size the animation has now, and the words it shows; the box and outline follow the size.
768 let mut style = title.style.clamped();
769 style.size = ((style.size as f32 * motion.scale).round() as u32).clamp(engine::text::SIZE_RANGE.0, engine::text::SIZE_RANGE.1);
770 // The letters the reveal has let through; the rest of the text is laid out, not drawn.
771 let shown = motion.revealed(&title.text).map(|s| s.chars);
772 let em = titles::em_px(&style, picture.h);
773 let (pad_x, pad_y) = (titles::BOX_PAD_X_EM * em, titles::BOX_PAD_Y_EM * em);
774 // How its lines line up, and whether the letters are bold: the engine's Align and Weight.
775 let look = (
776 match style.align {
777 engine::text::Align::Left => TextAlign::Left,
778 engine::text::Align::Centre => TextAlign::Center,
779 engine::text::Align::Right => TextAlign::Right,
780 },
781 style.weight == engine::text::Weight::Bold,
782 );
783 let [ir, ig, ib] = style.ink;
784 let [br, bg, bb, ba] = style.box_color;
785 let outline = titles::outline_offsets(style.outline, em)
786 .into_iter()
787 .map(|(dx, dy)| {
788 title_lines(&title.text, em, family.as_deref(), rgba(SUB_SHADE()), look, shown, &base_font)
789 .absolute()
790 .top(px(dy))
791 .left(px(dx))
792 .right(px(-dx))
793 });
794 // A press selects the title and a double-click puts the keyboard in its words.
795 let face = div()
796 .id(("preview-title", i))
797 .relative()
798 .on_click(cx.listener(move |this, event: &ClickEvent, _, cx| {
799 cx.stop_propagation();
800 this.open_title(i, event.click_count() >= 2, cx);
801 }))
802 .px(px(pad_x))
803 .py(px(pad_y))
804 .when(style.boxed, |el| {
805 // The default box is the subtitle plate's own; a chosen one is what was chosen.
806 el.bg(if style.box_color == engine::text::TextStyle::default().box_color {
807 rgba(SUB_SHADE())
808 } else {
809 rgba(u32::from_be_bytes([br, bg, bb, ba]))
810 })
811 })
812 .children(outline)
813 .child(title_lines(
814 &title.text,
815 em,
816 family.as_deref(),
817 if style.ink == engine::text::TextStyle::default().ink {
818 rgb(SUB_FG())
819 } else {
820 rgb(u32::from_be_bytes([0, ir, ig, ib]))
821 },
822 look,
823 shown,
824 &base_font,
825 ));
826 // The block hangs from the top, sits in the middle, or stands off
827 // the bottom of the area, as its place says: how tall it is depends
828 // on how its words wrap, so the flex column does the placing.
829 let lift = match style.place {
830 engine::text::Place::Bottom => bars,
831 _ => 0.,
832 };
833 let column = div()
834 .absolute()
835 .left(px(area.x))
836 .top(px(area.y))
837 .w(px(area.w))
838 .h(px(area.h - lift).max(px(0.)))
839 .flex()
840 .flex_col();
841 let column = match style.hplace {
842 engine::text::HPlace::Left => column.items_start(),
843 engine::text::HPlace::Centre => column.items_center(),
844 engine::text::HPlace::Right => column.items_end(),
845 };
846 let column = match style.place {
847 engine::text::Place::Top => column.justify_start(),
848 engine::text::Place::Centre => column.justify_center(),
849 engine::text::Place::Bottom => column.justify_end(),
850 };
851 // The slide is an offset of the whole column.
852 column
853 .left(px(area.x + motion.dx * picture.w))
854 .top(px(area.y + motion.dy * picture.h))
855 .opacity(titles::opacity(alpha))
856 .child(face)
857 });
858 Some(
859 div()
860 .absolute()
861 .left(px(picture.x))
862 .top(px(picture.y))
863 .w(px(picture.w))
864 .h(px(picture.h))
865 .overflow_hidden()
866 .children(layers.collect::<Vec<_>>()),
867 )
868 }
869
870 /// The cues the *subtitle lanes* put on screen at `at`, over the picture and
871 /// nothing else: bottom-centred where every player puts them, white on a
872 /// plate so the film underneath cannot swallow them, and each cue its own
873 /// plate so two at one moment stack rather than run together.
874 ///
875 /// What is drawn is what was *placed*: a track walked out of a file lands in
876 /// the palette and nothing more, exactly as a picture or a song does, and it
877 /// reaches the screen when a placement of it sits under the playhead
878 /// ([`PlaybackSession::sub_lane_cues`], the same map the export writes the
879 /// file with -- so what is read here is what the file will say). **One**
880 /// lane draws, the one that is shown ([`Player::active_sub_lane`]): a
881 /// picture carrying every lane's words at once is unreadable at three lanes
882 /// and nonsense at two hundred, which is the same one-track-at-a-time every
883 /// player offers. What an export writes is untouched by this -- every lane
884 /// on the timeline becomes a subtitle track of the file.
885 ///
886 /// `None` -- no element at all -- while the toggle is off, with nothing
887 /// placed, and between cues: the picture is what this window is for, and a
888 /// permanent empty band across it would be in the way of exactly that.
889 ///
890 /// A cue off a PGS track is a *picture* and not a line
891 /// ([`engine::subtitle::CueImage`]), and is drawn as one: the disc's whole
892 /// canvas fitted over the picture region exactly as the picture itself is,
893 /// which puts every cue where the disc put it relative to its own frame.
894 ///
895 /// corner-cut: exact only while the canvas and the encode are the same shape
896 /// -- a 16:9 canvas over a 2.39:1 encode fits to the region's height and
897 /// the film to its width, so a cue sits a little low on a scope film. The
898 /// upgrade path is the picture's own rect, which wants `VideoMeta`'s aspect
899 /// and the measured bounds rather than the shared `Contain`.
900 pub(crate) fn subtitle_overlay(
901 &mut self,
902 at: f64,
903 window: &mut Window,
904 ) -> Option<impl IntoElement + use<>> {
905 // One way out, and it lets the drawn picture go on the way: the toggle
906 // going off, the file closing and the gap between two cues are the same
907 // "nothing on screen", and an 8 MB atlas tile may not survive any of
908 // them (an early return above this leaked one per toggle-off).
909 // One lane's cues and never a walk of the lanes: the map is asked of the
910 // shown lane alone, so two hundred subtitle lanes cost this frame what
911 // one does.
912 let shown: Option<(Lane, Vec<engine::subtitle::Cue>)> = self
913 .active_sub_lane()
914 .filter(|_| self.subs_on)
915 // A preview is another file: the timeline's words over its
916 // picture would caption the wrong film.
917 .filter(|_| self.preview_session.is_none())
918 .and_then(|lane| {
919 let session = self.session.as_ref()?;
920 let cues = session.sub_lane_cues(lane);
921 let mut now: Vec<_> = cues_at(&cues, at).into_iter().cloned().collect();
922 // The words being typed into a caption show on the picture as they are typed,
923 // as a title's do: the cue being edited is drawn with the edit's words.
924 if let Some(edit) = self.cue_edit.as_ref() {
925 let refs = session.sub_lane_cue_refs(lane);
926 for cue in now.iter_mut() {
927 let is_edited = refs.iter().any(|&(start, end, track, idx)| {
928 start == cue.start_us && end == cue.end_us && (track, idx) == (edit.track, edit.cue)
929 });
930 if is_edited {
931 cue.text = edit.text.clone();
932 }
933 }
934 }
935 (!now.is_empty()).then_some((lane, now))
936 });
937 let Some((lane, cues)) = shown else {
938 self.drop_sub_image(window);
939 return None;
940 };
941 // The first picture cue up, decoded once and kept: two bitmap cues at
942 // one moment is a thing PGS composes into one display set, so there is
943 // never a second picture to stack under the first on one lane -- and one
944 // lane is all there is here.
945 let picture = cues
946 .iter()
947 .find_map(|cue| Some((cue.start_us, cue.end_us, cue.image.as_ref()?)))
948 .and_then(|(start_us, end_us, image)| {
949 self.sub_picture(lane, start_us, end_us, image, window)
950 });
951 // A picture is fitted onto the whole region and a plate hangs off the
952 // bottom of it, and a track is one or the other -- so they are two
953 // shapes and not one with the parts switched off.
954 // What the transient bars along the bottom edge are taking up right now:
955 // both shapes step up over it rather than be drawn under it.
956 let bars = f32::from(self.notice_h.get());
957 if let Some(image) = picture {
958 // A *flex* box with the canvas as its one growing item: a percentage
959 // size (`size_full`) inside an absolutely placed box has nothing to
960 // be a percentage of and lays the picture out to nothing, while a
961 // flex item is sized by the box itself. Fitted the way the picture
962 // above it is -- `Contain` over the same box -- so a canvas of the
963 // picture's own shape lands exactly on it.
964 // Slid up by the bars' height and not *shrunk* by it: the top and
965 // bottom insets cancel, so the box keeps the region's height and the
966 // canvas keeps the fit (and so the scale) it had with nothing
967 // hanging there -- a shorter box would refit the disc's canvas and
968 // move every cue on it, not just the one over the bar. The picture
969 // region clips (`overflow_hidden`), and what leaves the top of a
970 // subtitle canvas is transparent.
971 return Some(
972 div()
973 .absolute()
974 .top(px(-bars))
975 .bottom(px(bars))
976 .left_0()
977 .right_0()
978 .flex()
979 .child(letterboxed_image(image)),
980 );
981 }
982 // An animated (or re-chunked, or upper-cased) project caption is the
983 // engine's own drawing, bitmap and all: what the export burns is what
984 // this plate shows, and the word being spoken moves with the playhead.
985 if let Some(image) = self.animated_caption_image(lane, &cues, at, window) {
986 return Some(
987 div()
988 .absolute()
989 .top(px(-bars))
990 .bottom(px(bars))
991 .left_0()
992 .right_0()
993 .flex()
994 .child(letterboxed_image(image)),
995 );
996 }
997 Some(
998 div()
999 .absolute()
1000 .left_0()
1001 .right_0()
1002 .when(self.sub_place == SubPlace::Bottom, |d| {
1003 d.bottom(px(sub_bottom(bars)))
1004 })
1005 .when(self.sub_place == SubPlace::Top, |d| d.top(px(SUB_BOTTOM)))
1006 .flex()
1007 .flex_col()
1008 .items_center()
1009 .gap(px(2.))
1010 // The plate takes no click: the picture behind it is still the
1011 // drop target the whole window is.
1012 //
1013 // In the lane's own order: two cues at one moment -- a sign and
1014 // a line of dialogue -- stack, the first on the bottom line
1015 // where a single cue sits.
1016 .children(cues.into_iter().filter(|c| c.image.is_none()).map(|cue| {
1017 let family = self.sub_family.as_deref();
1018 // The outline is the same lines, in the box's own ink,
1019 // drawn behind the text at each offset. Pinned to the box's
1020 // edges with the offset taken out of both sides, so each
1021 // copy wraps and centres exactly as the text does.
1022 let outline = self.sub_outline.offsets().iter().map(|&(dx, dy)| {
1023 cue_lines(&cue.text, self.sub_text, family, rgba(SUB_SHADE()))
1024 .absolute()
1025 .top(px(dy))
1026 .left(px(dx))
1027 .right(px(-dx))
1028 });
1029 div()
1030 .relative()
1031 .max_w(relative(0.9))
1032 .px(px(6.))
1033 .rounded(px(3.))
1034 .when(self.sub_boxed, |el| el.bg(rgba(SUB_SHADE())))
1035 .children(outline)
1036 // A line of the cue is a line on screen: the break the
1037 // parser kept is not whitespace to be re-flowed. What a
1038 // *long* line does is wrap inside its own div, which is
1039 // what the width cap above is for.
1040 .child(cue_lines(&cue.text, self.sub_text, family, rgb(SUB_FG())))
1041 })),
1042 )
1043 }
1044
1045 /// The project caption style's drawing of `cues` at `at`, as the one cached
1046 /// picture ([`Player::sub_image`]); `None` while the style is plain (the
1047 /// text plate above draws that), with no session, or where nothing is up.
1048 /// The cache key is the drawn words and poses
1049 /// ([`subs::animated_caption_key`]), taken before any text is shaped, so a
1050 /// held cue costs a hash per repaint and a moving word one drawing per pose.
1051 pub(crate) fn animated_caption_image(
1052 &mut self,
1053 lane: Lane,
1054 cues: &[engine::subtitle::Cue],
1055 at: f64,
1056 window: &mut Window,
1057 ) -> Option<Arc<RenderImage>> {
1058 let session = self.session.as_ref()?;
1059 let caption = session.caption_style();
1060 if caption.is_plain() && !cues.iter().any(|c| c.real_karaoke().is_some()) {
1061 return None;
1062 }
1063 let style = engine::text::TextStyle {
1064 outline: match self.sub_outline {
1065 SubOutline::None => engine::text::Outline::None,
1066 SubOutline::Thin => engine::text::Outline::Thin,
1067 SubOutline::Thick => engine::text::Outline::Thick,
1068 },
1069 boxed: self.sub_boxed,
1070 place: match self.sub_place {
1071 SubPlace::Bottom => engine::text::Place::Bottom,
1072 SubPlace::Top => engine::text::Place::Top,
1073 },
1074 caption,
1075 // The family the viewer draws the plain caption in, so an animated one matches it.
1076 family: self.sub_family.clone(),
1077 ..engine::text::TextStyle::default()
1078 };
1079 let resolution = session.resolution();
1080 let (key, blocks) = animated_caption_key(&style, cues, frame_at(at, self.fps), self.fps)?;
1081 let key = sub_image_key(lane, i64::from(resolution.0), i64::from(resolution.1), key as usize);
1082 if let Some((up, ready)) = &self.sub_image
1083 && *up == key
1084 {
1085 return Some(ready.clone());
1086 }
1087 let (w, h, bgra) = animated_caption_bitmap(&style, &blocks, resolution)?;
1088 let buf = image::RgbaImage::from_raw(w, h, bgra)?;
1089 let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
1090 self.drop_sub_image(window);
1091 self.sub_image = Some((key, next.clone()));
1092 Some(next)
1093 }
1094
1095 /// The cue `lane` plays from `start_us` to `end_us` as a drawable picture,
1096 /// decoded on the first repaint it is up for and kept until another cue
1097 /// takes its place ([`Player::sub_image`]). `None` for a display set the
1098 /// decoder refuses, which draws nothing rather than failing the frame.
1099 ///
1100 /// Its atlas tile is released as the video's is: every [`RenderImage`] gets
1101 /// a fresh id and its own tile, so a film's worth of cues would grow the
1102 /// sprite atlas by the whole film.
1103 pub(crate) fn sub_picture(
1104 &mut self,
1105 lane: Lane,
1106 start_us: i64,
1107 end_us: i64,
1108 image: &Arc<engine::subtitle::CueImage>,
1109 window: &mut Window,
1110 ) -> Option<Arc<RenderImage>> {
1111 let key = sub_image_key(lane, start_us, end_us, Arc::as_ptr(image) as usize);
1112 if let Some((up, ready)) = &self.sub_image
1113 && *up == key
1114 {
1115 return Some(ready.clone());
1116 }
1117 let mut rgba = image.rgba()?;
1118 // gpui's atlas is BGRA with straight alpha; PGS decodes to RGBA with
1119 // straight alpha. The same swap the video frames get.
1120 for pixel in rgba.as_chunks_mut::<4>().0 {
1121 pixel.swap(0, 2);
1122 }
1123 let buf = image::RgbaImage::from_raw(image.width, image.height, rgba)?;
1124 let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
1125 self.drop_sub_image(window);
1126 self.sub_image = Some((key, next.clone()));
1127 Some(next)
1128 }
1129
1130 /// Lets go of the drawn cue and its atlas tile. Called where the cue stops
1131 /// being on screen, which is every gap between two of them: an 8 MB tile
1132 /// per cue is not a thing to leave behind a film.
1133 pub(crate) fn drop_sub_image(&mut self, window: &mut Window) {
1134 if let Some((_, old)) = self.sub_image.take() {
1135 let _ = window.drop_image(old);
1136 }
1137 }
1138}
1139
1140impl Player {
1141 /// Which cut the pointer or the keys are working on right now, as the
1142 /// outgoing clip's index (the incoming one is the next): a trim drag on an
1143 /// edge, a roll, slip or slide drag, or the `[`/`]` nudge mode
1144 /// ([`Player::loop_trim`]) on the selected clip. `None` at all other times,
1145 /// which is the only time the viewer is left whole.
1146 pub(crate) fn editing_cut(&self) -> Option<(Lane, Option<usize>)> {
1147 if let Some(t) = self.trim {
1148 return Some((t.lane, if t.edge == Edge::Start { t.idx.checked_sub(1) } else { Some(t.idx) }));
1149 }
1150 if let Some(p) = self.pro_drag {
1151 return Some((p.lane, if p.kind == ProKind::Roll { Some(p.idx) } else { p.idx.checked_sub(1) }));
1152 }
1153 self.loop_trim?;
1154 let (lane, idx) = self.selected.anchor()?;
1155 let session = self.session.as_ref()?;
1156 let clip = session.lane_clips(lane).get(idx)?;
1157 let now = frame_at(session.now(), self.fps);
1158 Some((lane, if now >= clip.end() { Some(idx) } else { idx.checked_sub(1) }))
1159 }
1160
1161 /// The two-up OUT|IN trim view (DESIGN §6): while an edit point is being
1162 /// trimmed, rolled, slipped, slid or nudged, the viewer's picture area is
1163 /// split side by side into the outgoing clip's side and the incoming one's.
1164 /// It is an `absolute()` fill of the screen, so it takes no room from
1165 /// anything and the picture's box is exactly as it was; once the gesture
1166 /// ends it is gone, and `None` is what every other frame draws.
1167 ///
1168 /// corner-cut: each half names its clip and edge frame rather than
1169 /// decoding that frame (a second decode off the neighbour's span).
1170 pub(crate) fn trim_two_up(&self) -> Option<impl IntoElement> {
1171 let (lane, cut) = self.editing_cut()?;
1172 let session = self.session.as_ref()?;
1173 let clips = session.lane_clips(lane);
1174 let name_of = |source: usize| {
1175 session
1176 .sources()
1177 .get(source)
1178 .map_or_else(|| "?".to_string(), |s| file_name(&s.path))
1179 };
1180 let out = cut.and_then(|i| clips.get(i)).map_or("Nothing before the cut".to_string(), |c| {
1181 let end = self.trim.filter(|t| t.edge == Edge::End && Some(t.idx) == cut).map_or(c.end(), |t| t.to);
1182 format!("{} · ends {}", name_of(c.source), frames_timecode(end, self.fps))
1183 });
1184 let inn = cut.map_or(0, |i| i + 1);
1185 let inn = clips.get(inn).map_or("Nothing after the cut".to_string(), |c| {
1186 let start = self.trim.filter(|t| t.edge == Edge::Start && t.idx == inn).map_or(c.start, |t| t.to);
1187 format!("{} · starts {}", name_of(c.source), frames_timecode(start, self.fps))
1188 });
1189 let half = |tag: &'static str, text: String| {
1190 div()
1191 .flex_1()
1192 .h_full()
1193 .flex()
1194 .flex_col()
1195 .items_center()
1196 .justify_center()
1197 .gap(px(4.))
1198 .bg(rgb(DARK_CANVAS()))
1199 .child(
1200 div()
1201 .text_size(px(type_scale::FLOOR_PX))
1202 .text_color(rgb(INK3()))
1203 .child(tag),
1204 )
1205 .child(
1206 div()
1207 .text_size(px(14.))
1208 .text_color(rgb(INK1()))
1209 .child(text),
1210 )
1211 };
1212 Some(
1213 div()
1214 .id("trim-two-up")
1215 .absolute()
1216 .top_0()
1217 .left_0()
1218 .size_full()
1219 .flex()
1220 .gap(px(1.))
1221 .bg(rgba(DARK_SEAM()))
1222 .child(half("OUT", out))
1223 .child(half("IN", inn)),
1224 )
1225 }
1226}
1227
1228/// A cue's lines in one ink: a line for each break the parser kept, each one
1229/// line high at `size` ([`sub_line_h_for`]). The text and each outline copy
1230/// are this, so they share every metric and differ only in where and in what.
1231fn cue_lines(text: &str, size: f32, family: Option<&str>, ink: gpui::Rgba) -> Div {
1232 div()
1233 .text_size(px(size))
1234 .text_color(ink)
1235 .text_align(TextAlign::Center)
1236 .when_some(family, |el, fam| el.font_family(fam.to_string()))
1237 .children(text.split('\n').map(|line| {
1238 div()
1239 .min_h(px(sub_line_h_for(size)))
1240 .child(line.to_string())
1241 }))
1242}
1243
1244/// A title's lines in one ink, each one line of the engine's pitch at `em` px
1245/// and centred, so a blank line keeps its height the way the rasteriser keeps it.
1246fn title_lines(
1247 text: &str,
1248 em: f32,
1249 family: Option<&str>,
1250 ink: gpui::Rgba,
1251 look: (TextAlign, bool),
1252 shown: Option<usize>,
1253 base: &gpui::Font,
1254) -> Div {
1255 let line = px(titles::line_px(em));
1256 let mut font = base.clone();
1257 if let Some(fam) = family {
1258 font.family = fam.to_string().into();
1259 }
1260 if look.1 {
1261 font.weight = gpui::FontWeight::BOLD;
1262 }
1263 let ink: gpui::Hsla = ink.into();
1264 // Characters before the line being laid, against `shown` (the reveal's count, `None` for all).
1265 let mut before = 0usize;
1266 let mut rows = Vec::new();
1267 for l in text.split('\n') {
1268 let n = l.chars().count();
1269 let child: gpui::AnyElement = match shown {
1270 Some(s) if s < before + n => {
1271 // The part of the line the reveal has let through keeps its ink; the rest is
1272 // in the same place and the same font, drawn in nothing.
1273 let local = s.saturating_sub(before);
1274 let cut = l.char_indices().nth(local).map_or(l.len(), |(i, _)| i);
1275 let hidden = gpui::transparent_black();
1276 let runs: Vec<gpui::TextRun> = [(cut, ink), (l.len() - cut, hidden)]
1277 .into_iter()
1278 .filter(|(len, _)| *len > 0)
1279 .map(|(len, color)| gpui::TextRun {
1280 len,
1281 font: font.clone(),
1282 color,
1283 background_color: None,
1284 underline: None,
1285 strikethrough: None,
1286 })
1287 .collect();
1288 gpui::StyledText::new(l.to_string()).with_runs(runs).into_any_element()
1289 }
1290 _ => l.to_string().into_any_element(),
1291 };
1292 rows.push(div().min_h(line).child(child));
1293 before += n + 1;
1294 }
1295 div()
1296 .text_size(px(em))
1297 .line_height(line)
1298 .text_color(ink)
1299 .text_align(look.0)
1300 .when(look.1, |el| el.font_weight(gpui::FontWeight::BOLD))
1301 .when_some(family, |el, fam| el.font_family(fam.to_string()))
1302 .children(rows)
1303}
1304
1305/// `~/Pictures/edith`, or `.` with no `HOME` -- [`keymap::config_path_in`]'s
1306/// own fallback, for the same reason: a screenshot has to land somewhere even
1307/// on a machine with no desktop environment set up.
1308pub(crate) fn screenshots_dir() -> PathBuf {
1309 std::env::var_os("HOME")
1310 .map_or_else(|| PathBuf::from("."), PathBuf::from)
1311 .join("Pictures")
1312 .join("edith")
1313}
1314
1315/// Where a screenshot goes: `stem-tc.png` in `dir`, or the same name with a
1316/// numeric suffix if that one is already taken -- a screenshot never
1317/// overwrites another the way an export overwrites its own path.
1318pub(crate) fn screenshot_path(dir: &Path, stem: &str, tc: &str) -> PathBuf {
1319 let base = format!("{stem}-{tc}");
1320 let first = dir.join(format!("{base}.png"));
1321 if !first.exists() {
1322 return first;
1323 }
1324 let mut n = 2;
1325 loop {
1326 let path = dir.join(format!("{base}-{n}.png"));
1327 if !path.exists() {
1328 return path;
1329 }
1330 n += 1;
1331 }
1332}
1333
1334/// The swap every BGRA frame needs to become the RGBA a PNG writes: gpui's
1335/// atlas is BGRA with straight alpha ([`Player::sub_picture`]'s own comment),
1336/// and the PNG encoder writes RGBA.
1337pub(crate) fn bgra_to_rgba(bgra: &[u8]) -> Vec<u8> {
1338 let mut out = bgra.to_vec();
1339 for pixel in out.as_chunks_mut::<4>().0 {
1340 pixel.swap(0, 2);
1341 }
1342 out
1343}
1344
1345/// Writes `bgra` (`w`x`h`, gpui's own layout) to a fresh PNG under
1346/// [`screenshots_dir`], creating the directory if this is the first one.
1347/// Never called on the render thread's own budget for more than a channel
1348/// swap and one PNG encode -- there is no decode here, only a copy already
1349/// in memory.
1350pub(crate) fn save_screenshot(
1351 bgra: &[u8],
1352 w: u32,
1353 h: u32,
1354 stem: &str,
1355 tc: &str,
1356) -> Result<PathBuf, String> {
1357 let dir = screenshots_dir();
1358 std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
1359 let path = screenshot_path(&dir, stem, tc);
1360 let rgba = bgra_to_rgba(bgra);
1361 let png = ec_image::png_encode::encode_rgba8(w, h, &rgba).map_err(|e| e.to_string())?;
1362 std::fs::write(&path, png).map_err(|e| format!("{}: {e}", path.display()))?;
1363 Ok(path)
1364}
1365
1366/// The welcome hero's headline and its second line.
1367pub(crate) const EMPTY_VIEWER_TITLE: &str = "Drop video, audio or images here";
1368pub(crate) const EMPTY_VIEWER_LINE: &str = "or start a project from your computer";
1369/// How many recent projects the hero lists.
1370pub(crate) const WELCOME_RECENT_MAX: usize = 4;