forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

sub.rs531 lines, 22.2 KiBHistoryRawDownload
1//! A placed caption's box on a subtitle lane (DESIGN §6).
2
3use super::clip::trim_plate;
4use super::*;
5use crate::player::caption_cues::{CueGrab, CueMenu};
6use gpui::{anchored, deferred};
7
8/// A placed caption's box, on a subtitle lane: [`clip_box`]'s twin, minus the
9/// thumbnail/waveform trace a caption has none of (DESIGN §6 -- "the subtitle
10/// cue edge IS a cut", so the same selection ring, drag, edge-trim and
11/// right-click menu a clip gets apply here too). Reused rather than
12/// reimplemented: `Player::trimmed_sub`/`SubDrag`/`sub_pick_name`/`cue_box`,
13/// the same plumbing `ui/timeline.rs`'s own caption box already drives.
14pub(super) fn sub_box(
15 player: &Player,
16 lane: Lane,
17 idx: usize,
18 sub: &SubClip,
19 scale: Scale,
20 (picks, pick_links): (&[(Lane, usize)], &[Option<u32>]),
21 cx: &mut Context<Player>,
22) -> impl IntoElement + use<> {
23 let placed = *sub;
24 let shown = player.trimmed_sub(lane, idx, placed);
25 let (start, len) = (
26 f64::from(shown.start) / player.fps,
27 f64::from(shown.frames) / player.fps,
28 );
29 let span = scale.width_px(len);
30 let width = clip_width(span);
31 let left = scale.px_at(start);
32 let on = marked((lane, idx), placed.link, picks, pick_links);
33 // The caption a move is carrying is dimmed where it stands, as a clip's
34 // is (`clip_box`), and the edge in the hand gets its plate from the
35 // caption's own old and in-flight lengths (`trim_plate`).
36 let dragging = player.drag_src == Some((lane, idx));
37 let dragged_edge = player
38 .trim
39 .filter(|trim| (trim.lane, trim.idx) == (lane, idx))
40 .map(|trim| (trim, placed.frames, shown.frames));
41 // This placement's own cues, where they fall in its body
42 // (`PlaybackSession::sub_lane_cue_spans`, the map the export and the picture's
43 // own plate go through). The lane's cues are clipped to each window and
44 // placements on a lane never overlap, so the ones that start inside this
45 // span are this placement's. Each keeps the (track, cue) it is, which is
46 // what a click, a drag and a right-click act on.
47 let cues: Vec<CueBlock> = player.session.as_ref().map_or_else(Vec::new, |s| {
48 s.sub_lane_cue_spans(lane)
49 .into_iter()
50 .filter_map(|span| {
51 let cue = s.subtitles().get(span.track)?.cues.get(span.cue)?;
52 let (mut cl, mut cw) = crate::subs::span_box(scale, span.start_us, span.end_us);
53 // A cue in the hand is drawn where the drag has it: the delta of its own clock,
54 // turned into the timeline's by the proportion the placement shows it at.
55 if let Some(d) = player.dragged_cue(span.track, span.cue) {
56 let shown = (span.end_us - span.start_us) as f64;
57 let window = (span.window.1 - span.window.0).max(1) as f64;
58 let px_per_track_us = scale.width_px(1e-6) * (shown / window) as f32;
59 cl += (d.now.0 - d.orig.0) as f32 * px_per_track_us;
60 cw += ((d.now.1 - d.now.0) - (d.orig.1 - d.orig.0)) as f32 * px_per_track_us;
61 }
62 let rel = cl - left;
63 (rel + cw > 0.0 && rel < width).then(|| CueBlock {
64 left: rel,
65 width: cw.max(1.),
66 track: span.track,
67 cue: span.cue,
68 // The words being typed show on the block as they are typed, not at the click away.
69 text: match player.cue_edit.as_ref().filter(|e| (e.lane, e.track, e.cue) == (lane, span.track, span.cue)) {
70 Some(edit) => edit.text.replace('\n', " "),
71 None => cue.text.replace('\n', " "),
72 },
73 picture: cue.image.is_some(),
74 })
75 })
76 .collect()
77 });
78 // The cue being retyped, if it is one of this placement's: a small plate floating over its
79 // own block (`cue_edit_plate`), so the lane's height never clips the words.
80 let editing = player.cue_edit.as_ref().filter(|edit| edit.lane == lane && !edit.in_panel).map(|e| (e.track, e.cue));
81 let selected_cue = player.sel_cue.filter(|&(l, _, _)| l == lane).map(|(_, t, c)| (t, c));
82 let menu = player
83 .cue_menu
84 .filter(|m| m.lane == lane && cues.iter().any(|c| (c.track, c.cue) == (m.track, m.cue)))
85 .map(|m| cue_menu_plate(player, m, cx));
86 let label = player
87 .session
88 .as_ref()
89 .and_then(|s| sub_pick_name(s.subtitles(), placed.track));
90 let ghost: SharedString = label.unwrap_or_else(|| lane.label()).into();
91 // The room a trim zone may spill into on each side: the middle of the gap
92 // to the neighbouring cue there (`interact::trim_zone`), exactly as a
93 // clip's is, so a cue edge is the same target a clip edge is.
94 let lane_subs: &[SubClip] = player
95 .session
96 .as_ref()
97 .map_or(&[][..], |s| s.sub_lane(lane));
98 let room_before = idx
99 .checked_sub(1)
100 .and_then(|p| lane_subs.get(p))
101 .map_or(f32::INFINITY, |p| {
102 scale.width_px(f64::from(shown.start.saturating_sub(p.end())) / player.fps)
103 });
104 let room_after = lane_subs.get(idx + 1).map_or(f32::INFINITY, |n| {
105 scale.width_px(f64::from(n.start.saturating_sub(shown.end())) / player.fps)
106 });
107 // Zones are siblings of the body, not children: the body clips its
108 // contents to its own edges, and a zone must reach past them.
109 let zones = [Edge::Start, Edge::End]
110 .into_iter()
111 .filter(|_| trims(span))
112 .map(|edge| {
113 let (inside, outside) = trim_zone(
114 span,
115 match edge {
116 Edge::Start => room_before,
117 Edge::End => room_after,
118 },
119 );
120 let zone = div()
121 .absolute()
122 .top_0()
123 .h_full()
124 .w(px(inside + outside))
125 .occlude()
126 .cursor(CursorStyle::ResizeLeftRight)
127 .hover(|s| s.bg(rgb(INK1())))
128 .on_mouse_down(
129 MouseButton::Left,
130 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
131 this.start_trim(lane, idx, edge, event.modifiers.control, cx);
132 }),
133 )
134 .on_mouse_down(
135 MouseButton::Right,
136 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
137 this.open_menu(lane, idx, event.position, cx);
138 }),
139 );
140 match edge {
141 Edge::Start => zone.left(px(-outside)),
142 Edge::End => zone.right(px(-outside)),
143 }
144 })
145 .collect::<Vec<_>>();
146 // The cues themselves: where in this window the track's words fall, each a block of its
147 // own with its words inside -- a placement is a window of a track, not full of speech. They
148 // are siblings of the body, which sits under them: a block's press stops there, so it is the
149 // caption's and never starts the placement's own drag (and no occlude, which would starve the
150 // root of the moves a drag inside the block needs).
151 let cue_blocks = cues
152 .into_iter()
153 .map(|c| {
154 let cx_app: &App = cx;
155 let this_edit = editing == Some((c.track, c.cue));
156 let on = selected_cue == Some((c.track, c.cue));
157 let (track, cue) = (c.track, c.cue);
158 let tone = crate::ui::theme::tokens().clip(crate::ui::theme::ClipKind::Caption);
159 let zone_w = (c.width / 3.).clamp(2., CUE_EDGE_W);
160 let zone = move |edge: Edge, cx: &mut Context<Player>| {
161 let grab = match edge {
162 Edge::Start => CueGrab::Start,
163 Edge::End => CueGrab::End,
164 };
165 let z = div()
166 .id(("bench-sub-cue-edge", (lane.ord * 1000 + idx) * 8192 + cue * 2 + usize::from(edge == Edge::End)))
167 .absolute()
168 .top_0()
169 .h_full()
170 .w(px(zone_w))
171 .cursor(CursorStyle::ResizeLeftRight)
172 .hover(|s| s.bg(rgba(crate::ui::theme::with_alpha(0xffffff, 0x40))))
173 .on_mouse_down(
174 MouseButton::Left,
175 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
176 cx.stop_propagation();
177 this.start_cue_drag(lane, track, cue, grab, event.position.x, cx);
178 }),
179 )
180 .on_mouse_down(
181 MouseButton::Right,
182 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
183 cx.stop_propagation();
184 this.open_cue_menu(lane, track, cue, event.position, cx);
185 }),
186 );
187 match edge {
188 Edge::Start => z.left_0(),
189 Edge::End => z.right_0(),
190 }
191 };
192 div()
193 .id(("bench-sub-cue", (lane.ord * 1000 + idx) * 8192 + cue))
194 .absolute()
195 .top(px(2.))
196 .bottom(px(2.))
197 .left(px(c.left))
198 .w(px((c.width - 1.).max(1.)))
199 .rounded(px(crate::layout::redesign::R_CLIP))
200 .bg(rgb(tone.strip))
201 .border_1()
202 .border_color(match on {
203 true => rgb(crate::ui::theme::tokens().accent),
204 false => rgba(crate::ui::theme::with_alpha(0x000000, 0x59)),
205 })
206 .when(on, |d| d.border_2())
207 .overflow_hidden()
208 .cursor_pointer()
209 .flex()
210 .items_center()
211 .px(px(6.))
212 // A click picks this one caption; a press on the body arms the move.
213 .on_mouse_down(
214 MouseButton::Left,
215 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
216 cx.stop_propagation();
217 this.start_cue_drag(lane, track, cue, CueGrab::Body, event.position.x, cx);
218 }),
219 )
220 // A double-click opens the words for typing in place.
221 .on_click(cx.listener(move |this, event: &ClickEvent, _, cx| {
222 if event.click_count() >= 2 {
223 this.open_cue_edit(lane, track, cue, cx);
224 }
225 }))
226 .on_mouse_down(
227 MouseButton::Right,
228 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
229 cx.stop_propagation();
230 this.open_cue_menu(lane, track, cue, event.position, cx);
231 }),
232 )
233 .when(!c.picture && !this_edit && player.cue_menu.is_none(), |d| {
234 d.tooltip(crate::ui::widgets::tip_hover(
235 &ellipsize(&c.text, 60),
236 "",
237 Some("Double-click to edit"),
238 ))
239 })
240 .child(
241 div()
242 .flex_none()
243 .whitespace_nowrap()
244 .type_style(cue_style())
245 .text_color(rgb(tone.label))
246 .child(match (c.picture, this_edit) {
247 (_, true) => SharedString::default(),
248 (true, false) => "Picture".into(),
249 (false, false) => fitted(cx_app, &c.text, (c.width - 15.).max(0.)).into(),
250 }),
251 )
252 .child(zone(Edge::Start, cx))
253 .child(zone(Edge::End, cx))
254 // The editor and the menu hang from this block's corner, in a zero-size holder so
255 // the block's own centring does not move them.
256 .children(player.cue_edit.as_ref().filter(|_| this_edit).map(|edit| {
257 div().absolute().top_0().left_0().size_0().child(cue_edit_plate(edit))
258 }))
259 })
260 .collect::<Vec<_>>();
261 let body = div()
262 .id(("bench-sub", lane.ord * 1000 + idx))
263 .absolute()
264 .top(px(2.))
265 .bottom(px(2.))
266 .left_0()
267 .w(px((width - 1.).max(1.)))
268 .overflow_hidden()
269 .rounded(px(crate::layout::redesign::R_CLIP))
270 .bg(rgb(crate::ui::theme::tokens().clip(crate::ui::theme::ClipKind::Caption).body))
271 .when(dragging, |d| d.opacity(0.85))
272 .cursor_pointer()
273 .on_mouse_down(
274 MouseButton::Left,
275 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
276 this.pick((lane, idx), event.modifiers.control, cx);
277 }),
278 )
279 // A plain click collapses a multi-pick to this one, exactly as a
280 // clip's own box does -- see the comment there.
281 .on_click(cx.listener(move |this, event: &ClickEvent, _, cx| {
282 if !press_modifiers(event).control {
283 this.select((lane, idx), cx);
284 }
285 }))
286 // Same door a clip's box opens its menu by (DESIGN §9).
287 .on_mouse_down(
288 MouseButton::Right,
289 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
290 this.open_menu(lane, idx, event.position, cx);
291 }),
292 )
293 .on_drag(
294 SubDrag {
295 lane,
296 idx,
297 sub: placed,
298 },
299 {
300 let ghost = ghost.clone();
301 let me = cx.entity();
302 move |_, _, _, cx| {
303 // A fresh gesture inherits nothing: `Player::drag_lane`
304 // and `Player::drag_x` are the *last live sample* of the
305 // drag being made, and a drag whose first sample lands
306 // outside every row would otherwise be let go onto the
307 // lane the previous one ended over.
308 me.update(cx, |this, cx| {
309 // Whatever the last gesture left up (a shadow, a
310 // snap line) goes before this one's source is set.
311 this.end_drag_preview(cx);
312 this.drag_lane = None;
313 this.drag_x = None;
314 this.drag_src = Some((lane, idx));
315 });
316 cx.new(|_| Tip(ghost.clone()))
317 }
318 },
319 )
320 .children(hitmap::dynamic(
321 move || {
322 (
323 format!("subtitle.{}.{}.{}", lane.label(), lane.ord, idx),
324 "Timeline subtitle".into(),
325 )
326 },
327 true,
328 ))
329 // The 1px inner border, black 45%.
330 .child(
331 div()
332 .absolute()
333 .size_full()
334 .rounded(px(crate::layout::redesign::R_CLIP))
335 .border_1()
336 .border_color(rgba(crate::ui::theme::with_alpha(0x000000, 0x73))),
337 )
338 // The plate of the edge in the hand, as a clip's is (`clip_box`).
339 .when_some(dragged_edge, |d, (trim, _, new)| {
340 d.child(trim_plate(trim, new, player.fps))
341 });
342 div()
343 .absolute()
344 .top_0()
345 .h_full()
346 .left(px(left))
347 .w(px(width))
348 .child(body)
349 .when(on, |d| {
350 d.child(
351 div()
352 .absolute()
353 .top_0()
354 .bottom_0()
355 .left(px(-2.))
356 .w(px((width - 1.).max(1.) + 4.))
357 .rounded(px(crate::layout::redesign::R_CLIP + 2.))
358 .border_2()
359 .border_color(rgb(crate::ui::theme::tokens().accent)),
360 )
361 })
362 .children(cue_blocks)
363 .children(zones)
364 .children(menu)
365}
366
367/// One caption's block on the lane: where it sits in the placement's body, and what it says.
368struct CueBlock {
369 left: f32,
370 width: f32,
371 track: usize,
372 cue: usize,
373 text: String,
374 picture: bool,
375}
376
377/// How wide the strip at each end of a cue block is that trims it, in pixels.
378const CUE_EDGE_W: f32 = 6.;
379
380/// The widest the floating cue editor is drawn.
381const CUE_EDIT_W: f32 = 300.;
382
383/// The face a caption's words are set in on its block.
384fn cue_style() -> type_scale::TypeStyle {
385 type_scale::label(type_scale::CHORD_METADATA_MIN_PX, gpui::FontWeight::MEDIUM)
386}
387
388/// `text` cut with an ellipsis so it is no wider than `max_w` pixels in the block's face. Measured
389/// with the font's own advances: a truncating text element keeps the width it was first measured at.
390fn fitted(cx: &App, text: &str, max_w: f32) -> String {
391 let style = cue_style();
392 let system = cx.text_system();
393 let id = system.resolve_font(&style.font);
394 let adv = |ch: char| system.advance(id, style.size, ch).map_or(7., |s| f32::from(s.width));
395 let ell = adv('\u{2026}');
396 let mut w = 0.;
397 let mut keep = 0;
398 for (i, ch) in text.char_indices() {
399 w += adv(ch);
400 if w + ell <= max_w {
401 keep = i + ch.len_utf8();
402 }
403 }
404 match w <= max_w {
405 true => text.to_string(),
406 false if keep == 0 => String::new(),
407 false => format!("{}\u{2026}", text[..keep].trim_end()),
408 }
409}
410
411/// `text` cut to `max` characters with an ellipsis, for a tooltip's title.
412fn ellipsize(text: &str, max: usize) -> String {
413 match text.char_indices().nth(max) {
414 Some((cut, _)) => format!("{}\u{2026}", text[..cut].trim_end()),
415 None => text.to_string(),
416 }
417}
418
419/// The in-place cue editor (DESIGN §7): a small plate floating over the cue's block, as wide as
420/// the words need up to [`CUE_EDIT_W`], with the words wrapped on as many lines as they take and
421/// the caret on them. A quiet line under them says which keys end the edit.
422fn cue_edit_plate(edit: &CueEdit) -> impl IntoElement + use<> {
423 let t = crate::ui::theme::tokens();
424 let words = match edit.caret_at_end {
425 true => format!("{}\u{258f}", edit.text),
426 false => format!("\u{258f}{}", edit.text),
427 };
428 deferred(
429 anchored().snap_to_window_with_margin(px(8.)).child(
430 crate::ui::kit::plate(6.)
431 .id("cue-edit-plate")
432 .w(px(CUE_EDIT_W))
433 .p(px(8.))
434 .flex()
435 .flex_col()
436 .gap(px(6.))
437 .occlude()
438 // A press on the plate is the editor's own: it must not reach the
439 // root's click-away, which would commit the words mid-typing.
440 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
441 .child(
442 div()
443 .w_full()
444 .min_h(px(type_scale::BODY_PX * 1.4))
445 .type_style(type_scale::body())
446 .text_color(rgb(t.ink1))
447 .child(words),
448 )
449 .child(
450 div()
451 .type_style(type_scale::caption())
452 .text_color(rgb(match &edit.refusal {
453 Some(_) => t.warn,
454 None => t.ink3,
455 }))
456 .child(match &edit.refusal {
457 Some(why) => why.clone(),
458 None => "Enter saves, Shift+Enter starts a new line, Esc cancels".to_string(),
459 }),
460 ),
461 ),
462 )
463 .with_priority(2)
464}
465
466/// The caption menu: Edit text, Split at playhead, Merge with next, Delete and Style, on the one
467/// popup plate. A row that cannot run says why on hover and ignores clicks.
468fn cue_menu_plate(player: &Player, m: CueMenu, cx: &mut Context<Player>) -> impl IntoElement + use<> {
469 use crate::ui::popup::{popup_row, popup_rule, popup_w};
470 let split_why = player.cue_split_why(m);
471 let merge_why = player.cue_merge_why(m);
472 let picture = player
473 .session
474 .as_ref()
475 .and_then(|s| s.subtitles().get(m.track))
476 .and_then(|t| t.cues.get(m.cue))
477 .is_some_and(|c| c.image.is_some());
478 let edit_why = picture.then_some("A picture caption has no words to edit");
479 let rows = [
480 ("Edit text", edit_why),
481 ("Split at playhead", split_why),
482 ("Merge with next", merge_why),
483 ("Delete", None),
484 ("Style\u{2026}", None),
485 ];
486 let w = popup_w(rows.iter().map(|(l, _)| (*l, "")), false);
487 let row = |id: usize, (label, why): (&'static str, Option<&'static str>), cx: &mut Context<Player>| {
488 let r = popup_row(("cue-menu-row", id), label, "", None, why);
489 match why {
490 Some(_) => r,
491 None => r.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
492 cx.stop_propagation();
493 match id {
494 0 => {
495 this.cue_menu = None;
496 this.open_cue_edit(m.lane, m.track, m.cue, cx);
497 }
498 1 => this.split_cue_at_playhead(m, cx),
499 2 => this.merge_cue_with_next(m, cx),
500 3 => this.delete_cue_at(m, cx),
501 _ => {
502 this.cue_menu = None;
503 this.open_subtitle_style(cx);
504 }
505 }
506 })),
507 }
508 };
509 deferred(
510 anchored().position(m.at).snap_to_window_with_margin(px(8.)).child(
511 crate::ui::kit::plate(6.)
512 .id("cue-menu")
513 .w(px(w))
514 .p(px(crate::layout::MENU_PAD))
515 .flex()
516 .flex_col()
517 .occlude()
518 .on_mouse_down_out(cx.listener(|this, _: &MouseDownEvent, _, cx| {
519 this.cue_menu = None;
520 cx.notify();
521 }))
522 .child(row(0, rows[0], cx))
523 .child(row(1, rows[1], cx))
524 .child(row(2, rows[2], cx))
525 .child(row(3, rows[3], cx))
526 .child(popup_rule())
527 .child(row(4, rows[4], cx)),
528 ),
529 )
530 .with_priority(2)
531}