forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

dock_stance.rs3736 lines, 162.1 KiBHistoryRawDownload
1//! The dock's own content: the Sources/Clip tab pair and what each shows
2//! (DESIGN.md §5, §12 step 4). `stance.rs::dock()` owns the panel's frame
3//! (width, surfaces, border); this module owns what fills it.
4//!
5//! The Sources tab used to be `Player::library` verbatim -- the legacy
6//! panel's pill tabs, Media/Audio/Text row, filled Import button and amber
7//! accent, wearing the darkroom surfaces only because its tokens happened to
8//! alias into them. The user named that: "this place is not fitting design
9//! language. it's same as our original." This module now builds the tab
10//! fresh, off MOCK-SPEC.md's "Dock" section -- `library.rs`/`library_meta.rs`
11//! still supply the row facts ([`library_rows`], [`source_tint`],
12//! [`clip_middle`]...), only the anatomy around them is new.
13
14use crate::layout::redesign as r;
15use crate::player::sections::Section;
16use crate::player::project_dialogs::PathFor;
17use crate::ui::hitmap;
18use crate::ui::icons::{Icon, IconSize};
19use crate::ui::kit::{self, Button, ButtonSize, ButtonStyle, Segment};
20use crate::ui::stance::{Surface, is_focus_cycle_key, is_focus_exit_key, next_surface};
21use crate::ui::theme::tokens;
22use crate::ui::type_scale::{self, Typeset, head, label, label_tabular};
23use crate::*;
24use gpui::{FontWeight, PathBuilder, point};
25
26/// Where the dock tab pick lives: one word beside the theme and the
27/// keybindings (`ui::theme::config_path`/`save`/`load` is the exact pattern
28/// this follows -- a small, silent, config-file round trip is the mechanism
29/// this editor already uses for a preference that outlives the window, and
30/// the playhead's own continuity lives in the *project* file, which a dock
31/// tab pick is not: it is not part of the timeline, so it does not belong in
32/// a `.edith`).
33pub(crate) fn config_path() -> std::path::PathBuf {
34 crate::keymap::Keymap::config_path().with_file_name("dock-tab")
35}
36
37/// The pick from the last session, if there was one. Anything unreadable or
38/// unknown leaves the default (`Src`) in force, exactly as a bad theme file
39/// does -- neither is the user's work, so neither is worth a startup notice.
40pub(crate) fn load() -> bool {
41 std::fs::read_to_string(config_path())
42 .map(|text| text.trim() != "Clip")
43 .unwrap_or(true)
44}
45
46/// Writes the pick. One word, written whole.
47pub(crate) fn save(src_active: bool) {
48 let path = config_path();
49 if let Some(dir) = path.parent() {
50 let _ = std::fs::create_dir_all(dir);
51 }
52 let _ = std::fs::write(path, if src_active { "Src\n" } else { "Clip\n" });
53}
54
55/// Whether the room's one open param card is maximized -- the same
56/// small-file round trip as the dock tab pick above, its own word beside it
57/// ("a room reopens exactly as left", DESIGN.md:135), so a maximized EQ stays
58/// maximized across a close and reopen of the whole room, not just the card.
59pub(crate) fn maximized_config_path() -> std::path::PathBuf {
60 crate::keymap::Keymap::config_path().with_file_name("card-maximized")
61}
62
63#[cfg_attr(not(test), allow(dead_code))]
64pub(crate) fn load_maximized() -> bool {
65 std::fs::read_to_string(maximized_config_path())
66 .map(|text| text.trim() == "1")
67 .unwrap_or(false)
68}
69
70pub(crate) fn save_maximized(maximized: bool) {
71 let path = maximized_config_path();
72 if let Some(dir) = path.parent() {
73 let _ = std::fs::create_dir_all(dir);
74 }
75 let _ = std::fs::write(path, if maximized { "1\n" } else { "0\n" });
76}
77
78/// One tab of the Src/Clip pair (MOCK-SPEC "Dock": no pill, no fill, no
79/// rounded button -- a 1px `ink1` top rule and `ink1` text mark the showing
80/// tab; the resting one is `ink3`). The mock's own trailing letters (`L`,
81/// `I`) are dropped rather than bound: both bare keys are already this
82/// editor's own busiest edit strokes (`l` lifts a clip, `i` marks in), and
83/// DESIGN §11's frequency check puts a lift and a mark far ahead of a tab
84/// switch -- wearing a chord this room does not answer to would be exactly
85/// the lie DESIGN §4 forbids, so the letters go instead.
86fn dock_tab(
87 id: &'static str,
88 label_text: &'static str,
89 active: bool,
90 cx: &mut Context<Player>,
91) -> impl IntoElement {
92 // REDESIGN §3.7: 36px, `emph` label, `ink2` resting / `ink1` showing, a
93 // 2px `accent` underline on the showing tab. The underline is always in
94 // flow (transparent at rest), so picking a tab shifts nothing.
95 let t = tokens();
96 div()
97 .id(id)
98 .flex_1()
99 .flex()
100 .items_center()
101 .justify_center()
102 .h(px(r::CONTROL_XL))
103 .border_b_2()
104 .border_color(if active { rgb(t.accent).into() } else { gpui::transparent_black() })
105 .hover(move |s| s.bg(rgb(t.e2)))
106 .cursor_pointer()
107 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
108 // The keys list is body state, not a tab (user 2026-09-09:
109 // "remove keys section from here since we also have it next to
110 // ledger") -- picking either tab is also the way out of it, and
111 // the pair itself (`dock_src_active`) is what the file keeps.
112 this.keys_open = false;
113 if id == "dock-tab-export" {
114 this.open_export(cx);
115 return;
116 }
117 if id == "dock-tab-transcript" {
118 this.open_transcript(cx);
119 return;
120 }
121 this.transcript_open = false;
122 this.transcript.search_edit = false;
123 // Leaving for Media or Clip puts away whatever the other tab had
124 // up: the export panel (an export that runs carries on) or a card.
125 this.close_card();
126 let surface = match id == "dock-tab-src" {
127 true => Surface::Dock,
128 false => Surface::Inspector,
129 };
130 // Same dead-handle class as a tab swap: the tab being left
131 // takes its `FocusHandle`'s element out of the tree with it, so a
132 // ring that was on that handle has to move with the tab or the
133 // keyboard goes silent. Only when the ring is actually in the
134 // dock -- a tab picked while the bench (or nothing) has focus
135 // does not steal it.
136 let in_ring = window
137 .focused(cx)
138 .is_some_and(|f| f == this.focus_dock || f == this.focus_inspector);
139 match in_ring {
140 true => this.focus_surface(surface, window, cx),
141 false => {
142 this.dock_src_active = id == "dock-tab-src";
143 save(this.dock_src_active);
144 }
145 }
146 cx.notify();
147 }))
148 .tooltip(crate::ui::widgets::tip_hover(
149 match id {
150 "dock-tab-src" => "Imported files",
151 "dock-tab-clip" => "Tools for the selected clip",
152 _ => "Write the timeline to a file",
153 },
154 if id == "dock-tab-export" { "E" } else { "" },
155 None,
156 ))
157 .children(hitmap::control(id, label_text, true))
158 .child(
159 div()
160 .type_style(type_scale::emph())
161 .text_color(rgb(if active { t.ink1 } else { t.ink2 }))
162 .child(label_text),
163 )
164}
165
166/// A 12px uppercase Archivo section head, `ink3` (DESIGN §3).
167fn section_head(text: impl Into<SharedString>) -> impl IntoElement {
168 let style = head();
169 div()
170 .flex_none()
171 .font(style.font.clone())
172 .text_size(style.size)
173 .text_color(rgb(INK3()))
174 .child(text.into())
175}
176
177/// The empty search box's words.
178pub(crate) const SEARCH_PLACEHOLDER: &str = "Search media";
179
180/// The media list's one empty line.
181pub(crate) const EMPTY_LIBRARY_HINT: &str = "Imported media appears here.";
182
183/// What a source on no lane says about itself: where it is, not a state of
184/// the file ("unused" read as the file's own condition).
185pub(crate) const NOT_ON_TIMELINE: &str = "not on timeline";
186
187/// A refused row's height: one sentence on one line (the full text is the
188/// tooltip and `Details`), so it stays the fixed [`SOURCE_ROW_H`] (REDESIGN §3.8).
189pub(crate) const REFUSED_ROW_H: f32 = 64.;
190
191/// A poster frame's box in a media row (16:9).
192const POSTER_W: f32 = 88.;
193const POSTER_H: f32 = 50.;
194
195/// The row's height: fixed for a usable source, taller for a refused one.
196pub(crate) fn source_row_h(usable: bool) -> f32 {
197 if usable { SOURCE_ROW_H } else { REFUSED_ROW_H }
198}
199
200/// The poster frame of a source row or tile, or a quiet stand-in with the
201/// kind's icon while it loads, or if the file has none (or cannot be read).
202fn poster(player: &Player, path: &std::path::Path, show_frame: bool, radius: f32) -> Div {
203 let t = tokens();
204 let image = match player.thumbs.get(path) {
205 Some(Thumb::Ready(image)) if show_frame => Some(image.clone()),
206 _ => None,
207 };
208 // A file with no picture gets the wave, whatever its extension says (a song muxed into an .mp4).
209 let icon = if engine::is_image(path) {
210 Icon::Image
211 } else if engine::is_audio(path) || !player.has_video(path) {
212 Icon::AudioWaveform
213 } else {
214 Icon::Film
215 };
216 let base = div()
217 .relative()
218 .flex_none()
219 .rounded(px(radius))
220 .overflow_hidden()
221 .flex()
222 .items_center()
223 .justify_center()
224 .bg(rgb(t.e2));
225 match image {
226 Some(image) => base.child(crate::ui::bench_stance::cover_image(image)),
227 None => base.child(icon.el(IconSize::Inline, t.ink3)),
228 }
229}
230
231/// Every lane a source plays on right now, as its own `V1`/`A1` labels
232/// (MOCK-SPEC "Dock" §4's usage line). The clip *count* that used to trail it
233/// ("2 uses") is gone with cleanse round 2 (2026-09-10): the lanes are the
234/// answer to "is it in the film?", the number is a statistic, and the
235/// Properties side of the row menu still prints it whole.
236fn usage_labels(player: &Player, source_idx: usize) -> Vec<String> {
237 let lanes: Vec<String> = player.session.as_ref().map_or_else(Vec::new, |session| {
238 session
239 .lanes()
240 .into_iter()
241 .filter(|lane| {
242 session
243 .lane_clips(*lane)
244 .iter()
245 .any(|c| c.source == source_idx)
246 })
247 .map(Lane::label)
248 .collect()
249 });
250 // A source used only inside another sequence names that sequence, not "not on timeline".
251 // Named only in a project that has another sequence to tell apart; with one, the lanes say it all.
252 let inside: Vec<String> = player.session.as_ref().map_or_else(Vec::new, |session| {
253 if session.sequences().len() < 2 {
254 return Vec::new();
255 }
256 session
257 .source_uses_parked(source_idx)
258 .into_iter()
259 .filter_map(|(id, _)| session.sequence_name(id))
260 .collect()
261 });
262 lanes.into_iter().chain(inside).collect()
263}
264
265/// A row's detail line with the decoder seats taken out of it, which is what
266/// the dock draws: the seat is how this machine happens to read the file and
267/// the transport line and the Properties side both still say it, so the row
268/// says what the file *is* instead.
269///
270/// Only a whole part is dropped, and a part is a seat only when it is exactly
271/// a seat's word. That is what keeps a refusal: the row's detail for a file
272/// the decoder would not take is the refusal itself
273/// ([`crate::Decoder::Refused`]), and no seat is ever named by a sentence --
274/// so the one line that has to say why the file will not play reaches the
275/// dock whole.
276pub(crate) fn without_seats(detail: &str, seats: &[&str]) -> String {
277 detail
278 .split(" · ")
279 .filter(|part| !seats.contains(part))
280 .collect::<Vec<_>>()
281 .join(" · ")
282}
283
284/// A name cut to fit `width_px` at the body size, with an ellipsis where it is cut, so
285/// the cut shows as a cut and never as a letter sliced in half. Measured the way the
286/// popups measure ([`crate::ui::popup::text_w`]); the whole name is the tooltip.
287pub(crate) fn fit_name(text: &str, width_px: f32, size_px: f32) -> String {
288 if crate::ui::popup::text_w(text, size_px, false) <= width_px {
289 return text.to_string();
290 }
291 let chars: Vec<char> = text.chars().collect();
292 for keep in (0..chars.len()).rev() {
293 let cut: String = chars[..keep].iter().collect::<String>() + "\u{2026}";
294 if crate::ui::popup::text_w(&cut, size_px, false) <= width_px {
295 return cut;
296 }
297 }
298 "\u{2026}".to_string()
299}
300
301/// A name cut to fit `width_px` with the ellipsis in the MIDDLE: the start and the end both
302/// survive, so two names that share a long start still read apart by their endings.
303pub(crate) fn fit_middle(text: &str, width_px: f32, size_px: f32) -> String {
304 if crate::ui::popup::text_w(text, size_px, false) <= width_px {
305 return text.to_string();
306 }
307 let chars: Vec<char> = text.chars().collect();
308 for keep in (0..chars.len()).rev() {
309 let head = keep.div_ceil(2);
310 let tail = keep - head;
311 let cut: String = chars[..head].iter().collect::<String>()
312 + "\u{2026}"
313 + &chars[chars.len() - tail..].iter().collect::<String>();
314 if crate::ui::popup::text_w(&cut, size_px, false) <= width_px {
315 return cut;
316 }
317 }
318 "\u{2026}".to_string()
319}
320
321/// A row's name cut to fit like [`fit_middle`], but a multi-stream file's tag (`name [audio 2]`)
322/// is kept whole at the end: the stream is what tells the rows of one file apart, so the cut
323/// falls on the file's name and never on the part that says which track it is.
324pub(crate) fn fit_row_name(name: &str, width_px: f32, size_px: f32) -> String {
325 match name.rsplit_once(" [") {
326 Some((file, tail)) if tail.ends_with(']') => {
327 let tag = format!(" \u{00b7} {}", &tail[..tail.len() - 1]);
328 let room = width_px - crate::ui::popup::text_w(&tag, size_px, false);
329 format!("{}{tag}", fit_middle(file, room, size_px))
330 }
331 _ => fit_middle(name, width_px, size_px),
332 }
333}
334
335/// The width the media panel is drawn at, the one the list and the grid are laid out in.
336fn dock_width() -> f32 {
337 let w = f32::from_bits(crate::ui::widgets::DOCK_W_BITS.load(std::sync::atomic::Ordering::Relaxed));
338 if w > 0. { w } else { r::DOCK_W }
339}
340
341/// The file's name without its extension -- what the editor calls the film,
342/// not what the filesystem calls the bytes (cleanse round 2). A row that
343/// names several streams of one file keeps the stream half it was given
344/// ([`library_meta::row_name`] appends it after the file name).
345///
346/// corner-cut: private to the dock while U2's shared `stem()` is unlanded;
347/// the lead reconciles the two into `ui/widgets.rs` or `files.rs`.
348pub(crate) fn stem(name: &str) -> String {
349 let (file, tail) = match name.split_once(" [") {
350 Some((file, tail)) => (file, format!(" [{tail}")),
351 None => (name, String::new()),
352 };
353 match file.rsplit_once('.') {
354 // A name that is *all* extension (".srt") keeps it: it is the name.
355 Some(("", _)) | None => format!("{file}{tail}"),
356 Some((base, _)) => format!("{base}{tail}"),
357 }
358}
359
360/// Which row item a key answers while the dock's Media panel has focus, or
361/// `None` to let it fall through to the global keymap (DESIGN §4: a panel's
362/// keys act only while that panel has focus). With a row picked, a bare
363/// Space previews it and `↵` adds it -- the two chords the row's own menu
364/// prints (DESIGN §6.7 "Preview Space"). Anything with a modifier, or any
365/// key with no row picked, keeps its keymap meaning (Space is Play).
366pub(crate) fn media_key(
367 key: &str,
368 mods: gpui::Modifiers,
369 focused: bool,
370 selected: bool,
371) -> Option<RowItem> {
372 if !focused || !selected || mods != gpui::Modifiers::none() {
373 return None;
374 }
375 match key {
376 "space" | "enter" => Some(RowItem::Preview),
377 _ => None,
378 }
379}
380
381/// A media row's height, fixed (DESIGN §6.7; REDESIGN §3.8: 104 -> 64): the
382/// list reads as one even column whatever a row's metadata happens to say.
383pub(crate) const SOURCE_ROW_H: f32 = 64.;
384
385/// The list/grid pick, remembered like the dock tab (one word beside it).
386static GRID_VIEW: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
387static GRID_LOADED: std::sync::Once = std::sync::Once::new();
388
389fn grid_config_path() -> std::path::PathBuf {
390 crate::keymap::Keymap::config_path().with_file_name("media-view")
391}
392
393/// Whether the Media tab shows tiles (`true`) or rows (`false`).
394pub(crate) fn grid_view() -> bool {
395 GRID_LOADED.call_once(|| {
396 let on = std::fs::read_to_string(grid_config_path()).is_ok_and(|t| t.trim() == "grid");
397 GRID_VIEW.store(on, std::sync::atomic::Ordering::Relaxed);
398 });
399 GRID_VIEW.load(std::sync::atomic::Ordering::Relaxed)
400}
401
402fn set_grid_view(grid: bool) {
403 let _ = grid_view();
404 GRID_VIEW.store(grid, std::sync::atomic::Ordering::Relaxed);
405 let path = grid_config_path();
406 if let Some(dir) = path.parent() {
407 let _ = std::fs::create_dir_all(dir);
408 }
409 let _ = std::fs::write(path, if grid { "grid\n" } else { "list\n" });
410}
411
412/// The All / Favourites pick, remembered beside the list/grid one.
413static FAV_ONLY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
414static FAV_LOADED: std::sync::Once = std::sync::Once::new();
415
416fn fav_config_path() -> std::path::PathBuf {
417 crate::keymap::Keymap::config_path().with_file_name("media-filter")
418}
419
420/// Whether the Media tab lists only the starred sources.
421pub(crate) fn fav_only() -> bool {
422 FAV_LOADED.call_once(|| {
423 let on = std::fs::read_to_string(fav_config_path()).is_ok_and(|t| t.trim() == "favourites");
424 FAV_ONLY.store(on, std::sync::atomic::Ordering::Relaxed);
425 });
426 FAV_ONLY.load(std::sync::atomic::Ordering::Relaxed)
427}
428
429pub(crate) fn set_fav_only(only: bool) {
430 let _ = fav_only();
431 FAV_ONLY.store(only, std::sync::atomic::Ordering::Relaxed);
432 let path = fav_config_path();
433 if let Some(dir) = path.parent() {
434 let _ = std::fs::create_dir_all(dir);
435 }
436 let _ = std::fs::write(path, if only { "favourites\n" } else { "all\n" });
437}
438
439thread_local! {
440 /// The Media tab's sort (0 name, 1 date added, 2 length) and type filter (0 all, 1 video, 2
441 /// audio, 3 images), and whether their dropdown is open (with when it last closed, so the
442 /// click that closes it by pressing the button again does not reopen it).
443 static SORT: std::cell::Cell<usize> = const { std::cell::Cell::new(1) };
444 static KIND: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
445 static SORT_OPEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
446 static SORT_CLOSED: std::cell::Cell<Option<std::time::Instant>> = const { std::cell::Cell::new(None) };
447 /// The list's scroll, for the fade that says there is more below.
448 static LIST_SCROLL: gpui::ScrollHandle = gpui::ScrollHandle::new();
449 /// The clip panel's scroll, and the pick it was last showing: a new pick starts at the top,
450 /// so the editor a pick opens is in view rather than wherever the last one was scrolled to.
451 /// The pick is every kind at once (clip, caption, title), so any change of selection resets it.
452 static CLIP_SCROLL: gpui::ScrollHandle = gpui::ScrollHandle::new();
453 static CLIP_PICKED: std::cell::Cell<PanelPick> = const { std::cell::Cell::new((None, None, None)) };
454}
455
456/// What the clip panel was showing: the picked clip, the picked caption and the picked title.
457type PanelPick = (Option<(engine::project::Lane, usize)>, Option<(engine::project::Lane, usize, usize)>, Option<usize>);
458
459const SORTS: [&str; 3] = ["Name", "Date added", "Length"];
460const KINDS: [&str; 4] = ["All", "Video", "Audio", "Images"];
461
462/// Whether `path` is the kind the type filter asks for.
463pub(crate) fn kind_matches(kind: usize, path: &std::path::Path) -> bool {
464 match kind {
465 1 => !engine::is_audio(path) && !engine::is_image(path),
466 2 => engine::is_audio(path),
467 3 => engine::is_image(path),
468 _ => true,
469 }
470}
471
472/// The distinct files of the project that are gone from disk.
473fn offline_files(player: &Player) -> Vec<PathBuf> {
474 let mut out: Vec<PathBuf> = Vec::new();
475 for (_, path) in player.session.as_ref().map_or_else(Vec::new, |s| s.offline_sources()) {
476 if !out.contains(&path) {
477 out.push(path);
478 }
479 }
480 out
481}
482
483/// A source whose file is gone from disk: it stays in the library (its clips
484/// stay on the timeline), reads "Missing" and offers `Relink…`.
485fn is_offline(player: &Player, path: &std::path::Path) -> bool {
486 player.session.as_ref().is_some_and(|s| s.offline_sources().iter().any(|(_, p)| p == path))
487}
488
489impl Player {
490 /// `Relink…`: asks for the replacement file (the chooser is another
491 /// process, so on a background thread) and points the source at it. One
492 /// undo step ([`PlaybackSession::relink_source`]); a refusal is told in
493 /// plain words and changes nothing.
494 pub(crate) fn relink_pick(&mut self, path: PathBuf, cx: &mut Context<Self>) {
495 if self.exporting().is_some() {
496 return;
497 }
498 let picked = cx.background_executor().spawn(async { crate::files::pick_file("edith — relink media") });
499 cx.spawn(async move |this, cx| {
500 let picked = picked.await;
501 this.update(cx, |this, cx| {
502 match picked {
503 Ok(Some(new)) => this.relink_to(path, new, cx),
504 Ok(None) => {}
505 // No chooser here: the same question, typed, for the same missing file.
506 Err(_) => this.open_path_entry_from(PathFor::Relink, Some(path), cx),
507 }
508 cx.notify();
509 })
510 .ok();
511 })
512 .detach();
513 }
514
515 /// Points the missing source at `path` at `new`, and the same-named missing files of the same
516 /// length follow it. Shared by the chooser's answer and the typed path's.
517 pub(crate) fn relink_to(&mut self, path: PathBuf, new: PathBuf, cx: &mut Context<Self>) {
518 let Some(session) = self.session.as_mut() else { return };
519 let Some(idx) = session.sources().iter().position(|s| s.path == path) else { return };
520 let missing = session.offline_sources();
521 // What each missing source was, in timeline frames, read before anything moves.
522 let recorded: Vec<(usize, u32)> = missing.iter().map(|(i, p)| (*i, session.file_frames(p))).collect();
523 let fps = self.fps;
524 // The file the user picked goes through the engine's own check, which refuses
525 // a wrong file in words and changes nothing.
526 let Some(session) = self.session.as_mut() else { return };
527 match session.relink_source(idx, &new) {
528 Ok(warnings) => {
529 let followers = relink_followers(&missing, idx, &path, &new, |p| p.is_file(), |i, candidate| {
530 let want = recorded.iter().find(|(j, _)| *j == i).map_or(0, |(_, f)| *f);
531 same_length(want, candidate, fps)
532 });
533 let moved = match followers.is_empty() {
534 true => 0,
535 false => self.session.as_mut().map_or(0, |s| s.relink_all(&followers)),
536 };
537 let still = self.session.as_ref().map_or(0, |s| s.offline_sources().len());
538 self.mark_dirty();
539 self.reset_after_reseek();
540 let tail = warnings.first().map(|w| format!(" \u{2014} {w}")).unwrap_or_default();
541 self.notify_user(format!("{}{tail}", relink_words(1 + moved, still)).into());
542 }
543 Err(e) => self.notify_user(format!("Could not relink: {e}").into()),
544 }
545 cx.notify();
546 }
547}
548
549/// The other missing sources a relink of one missing file also points at: every missing source
550/// whose file of the same name sits in the picked file's new folder, and whose length matches
551/// what the source was ([`same_length`], decided by `matches(source index, candidate)`). The
552/// picked file itself is not here: the engine's own check takes it.
553fn relink_followers(
554 missing: &[(usize, PathBuf)],
555 picked_idx: usize,
556 old: &std::path::Path,
557 new: &std::path::Path,
558 is_file: impl Fn(&std::path::Path) -> bool,
559 matches: impl Fn(usize, &std::path::Path) -> bool,
560) -> Vec<(usize, PathBuf)> {
561 let mut pairs = Vec::new();
562 let Some(dir) = new.parent() else { return pairs };
563 for (idx, path) in missing {
564 if *idx == picked_idx || path == old {
565 continue;
566 }
567 let Some(file) = path.file_name() else { continue };
568 let candidate = dir.join(file);
569 if is_file(&candidate) && matches(*idx, &candidate) {
570 pairs.push((*idx, candidate));
571 }
572 }
573 pairs
574}
575
576/// The length rule relink uses: a file's length in timeline frames is within one frame of the
577/// frames the source was recorded at (the engine's own tolerance for a replacement). A still
578/// has no length of its own, so it always matches; a file that cannot be read never does.
579fn same_length(recorded: u32, candidate: &std::path::Path, fps: f64) -> bool {
580 if engine::is_image(candidate) {
581 return true;
582 }
583 let frames = match engine::is_audio(candidate) {
584 true => engine::AudioSession::duration_secs(candidate).ok().flatten().map(|secs| secs * fps),
585 false => engine::demux::Demuxer::open(candidate)
586 .ok()
587 .map(|(meta, _)| f64::from(meta.frame_count) / meta.frame_rate * fps),
588 };
589 frames.is_some_and(|f| recorded.abs_diff((f.max(0.)).round() as u32) <= 1)
590}
591
592/// The relink's answer in plain words: how many files moved, and how many are still missing.
593fn relink_words(moved: usize, still: usize) -> String {
594 let files = match moved {
595 1 => "1 file".to_string(),
596 n => format!("{n} files"),
597 };
598 match still {
599 0 => format!("Relinked {files}."),
600 1 => format!("Relinked {files}. 1 is still missing."),
601 n => format!("Relinked {files}. {n} are still missing."),
602 }
603}
604
605/// One media row (REDESIGN §3.8): an 88x50 poster with the length on it, the
606/// name, one plain-facts caption line, and where the source is used as small
607/// chips. `+` adds it at the playhead. Offline and refused rows keep the same
608/// 64px: the poster wears an `unlink` / `triangle-alert` badge and the line
609/// under the name says why in a sentence, with `Relink…` / `Details` beside
610/// it. Drag (gesture 1), `↵` (gesture 2, wired in `render.rs`'s key handler),
611/// double-click (gesture 3) and right-click (gesture 4) live in
612/// [`source_gestures`], shared with the grid tile.
613fn source_row(
614 player: &Player,
615 i: usize,
616 row: &Row,
617 placed: usize,
618 picked: bool,
619 star: Option<bool>,
620 cx: &mut Context<Player>,
621) -> impl IntoElement {
622 let t = tokens();
623 let usable = row.unusable.is_none();
624 let offline = is_offline(player, &row.path);
625 let name: SharedString = stem(&row.name).into();
626 let facts = row_facts(player, row);
627 let chips = if placed == 0 { Vec::new() } else { usage_labels(player, row.tint) };
628 let can_insert = usable && !offline && player.session.is_some() && player.exporting().is_none();
629 let (path, stream) = (row.path.clone(), row.stream);
630 let add_path = path.clone();
631 let details_path = path.clone();
632 let dot_path = path.clone();
633 let tip: SharedString = match (&row.unusable, offline) {
634 // The row says Missing and the banner above the list offers Relink; a plate here would only cover the next row.
635 (_, true) => SharedString::default(),
636 (Some(why), _) => refusal_sentence(why).into(),
637 _ if picked => PICK_HINT.into(),
638 _ if placed == 0 => "Not on the timeline — drag it to a lane".into(),
639 _ => "Drag it to a lane".into(),
640 };
641 // Second line: the facts, or the reason in the error ink.
642 // A layout the timeline cannot take is not an error in the file: it is ink2 under the warning icon.
643 let layout_refusal = row.unusable.as_deref().is_some_and(is_layout_refusal);
644 // The full sentence is the detail's tooltip; the row shows the short form so it is never cut.
645 let line2_tip: String = match &row.unusable {
646 Some(why) if layout_refusal => refusal_sentence(why),
647 _ => String::new(),
648 };
649 let (line2, line2_ink) = match (&row.unusable, offline) {
650 (_, true) => (String::new(), t.ink3),
651 (Some(_), _) if layout_refusal => (LAYOUT_SHORT.to_string(), t.ink2),
652 (Some(why), _) => (why.clone(), t.err),
653 _ => (length_line(player, row, &facts), t.ink3),
654 };
655 // A refused file wears the alert in the error ink; a missing one in the warning ink.
656 let poster = poster(player, &row.path, usable && !offline, r::R_CLIP)
657 .w(px(POSTER_W))
658 .h(px(POSTER_H))
659 .when(!usable || offline, |d| d.child(poster_badge(Icon::TriangleAlert, if offline { t.warn } else { t.err }, false)));
660 let group: SharedString = format!("dock-source-row-{i}").into();
661 // The star sits on the poster's top-right corner (the badges are on the left): always laid
662 // out, drawn when starred, picked or hovered, so the text beside the poster keeps its width.
663 let poster = poster.when_some(star, |d, starred| {
664 d.child(
665 div()
666 .absolute()
667 .top(px(2.))
668 .right(px(2.))
669 .child(star_button(("dock-star", i), starred, picked, group.clone(), row.path.clone(), row.stream, cx)),
670 )
671 });
672 let el = div()
673 .id(("dock-source", i))
674 .group(group.clone())
675 .relative()
676 .flex_none()
677 .h(px(source_row_h(usable)))
678 .overflow_hidden()
679 .flex()
680 .items_center()
681 .gap(px(8.))
682 .px(px(8.))
683 .rounded(px(r::R_CLIP))
684 // Picked is the accent wash with an accent edge; hover is the plain raised fill.
685 .border_1()
686 .border_color(if picked { rgba((t.accent << 8) | 0x59).into() } else { gpui::transparent_black() })
687 .when(picked, |d| d.bg(rgba(t.accent_wash)))
688 .when(!picked, |d| d.hover(move |s| s.bg(rgb(t.e2))))
689 .when(picked, |d| {
690 d.child(div().absolute().left_0().top_0().bottom_0().w(px(3.)).bg(rgb(t.accent)))
691 });
692 source_gestures(el, i, &row.path, row.stream, usable && !offline, name.clone(), tip, cx)
693 .child(poster)
694 .child(
695 div()
696 .flex_1()
697 .min_w(px(0.))
698 .overflow_hidden()
699 .flex()
700 .flex_col()
701 .justify_center()
702 .child(
703 div()
704 .flex()
705 .items_center()
706 .gap(px(6.))
707 .child(film_dot(i, row.tint, usable, dot_path, stream, cx))
708 .child(
709 div()
710 .id(("dock-name", i))
711 .flex_1()
712 .min_w(px(0.))
713 .truncate()
714 .type_style(type_scale::body_strong())
715 .text_color(rgb(if usable && !offline { t.ink1 } else { t.ink2 }))
716 .child(fit_row_name(&name, dock_width() - 170., type_scale::BODY_PX))
717 .tooltip(crate::ui::widgets::tip_hover(&name, "", None)),
718 )
719 .when(usable && !offline, |d| {
720 // Drawn only on hover or selection, but always laid out: no shift. It sits on
721 // the name's line so the detail line below keeps the row's whole width.
722 d.child(div().flex_none().when(!picked, |d| d.invisible().group_hover(group.clone(), |s| s.visible())).child(
723 Button::new("dock-add-at-playhead-btn")
724 .icon(Icon::Plus)
725 .style(ButtonStyle::Ghost)
726 .enabled(can_insert)
727 .build()
728 .id(("dock-add-at-playhead", i))
729 .when(can_insert, |d| {
730 d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
731 cx.stop_propagation();
732 this.append_source(&add_path, stream, cx);
733 cx.notify();
734 }))
735 })
736 .children(hitmap::dynamic(
737 move || (format!("source.{i}.add"), "Append to timeline end".into()),
738 can_insert,
739 ))
740 .tooltip(crate::ui::widgets::tip_hover("Append to timeline end", "", None)),
741 ))
742 }),
743 )
744 .child(
745 div()
746 .h(px(18.))
747 .flex()
748 .items_center()
749 .gap(px(6.))
750 .overflow_hidden()
751 .when(!line2.is_empty(), |d| {
752 d.child(
753 div()
754 .flex_1()
755 .min_w(px(0.))
756 .flex()
757 .items_center()
758 .gap(px(4.))
759 .overflow_hidden()
760 .when(layout_refusal, |d| d.child(Icon::TriangleAlert.el(IconSize::Inline, t.warn)))
761 .child(
762 div()
763 .id(("dock-detail", i))
764 .flex_1()
765 .min_w(px(0.))
766 .text_ellipsis()
767 .truncate()
768 .whitespace_nowrap()
769 .type_style(type_scale::caption())
770 .text_color(rgb(line2_ink))
771 .child(fit_name(&line2, dock_width() - 130., type_scale::CAPTION_PX))
772 .tooltip(crate::ui::widgets::tip_hover(if layout_refusal { &line2_tip } else { &line2 }, "", None)),
773 ),
774 )
775 })
776 .when(offline, |d| d.child(missing_chip())),
777 )
778 .child(
779 div()
780 .h(px(18.))
781 .flex()
782 .items_center()
783 .gap(px(4.))
784 .overflow_hidden()
785 .when(!usable && !offline, |d| {
786 d.child(
787 ghost_link(("dock-details", i), Icon::Info, "Details")
788 .on_click(cx.listener(move |this, event: &ClickEvent, _, cx| {
789 cx.stop_propagation();
790 this.selected_asset = Some((details_path.clone(), stream));
791 this.library_menu = Some(LibraryMenu {
792 path: details_path.clone(),
793 stream,
794 at: event.position(),
795 details: true,
796 });
797 cx.notify();
798 })),
799 )
800 })
801 .when(!chips.is_empty(), |d| d.child(usage_text(&chips, false))),
802 ),
803 )
804}
805
806/// The small corner badge a poster wears for a problem: an icon on a dark chip, top-left in a
807/// row (where the star is top-right) and bottom-left in a tile (where the star is top-left).
808fn poster_badge(icon: Icon, ink: u32, tile: bool) -> impl IntoElement {
809 div()
810 .absolute()
811 .when(!tile, |d| d.top(px(2.)))
812 .when(tile, |d| d.bottom(px(2.)))
813 .left(px(2.))
814 .size(px(18.))
815 .flex()
816 .items_center()
817 .justify_center()
818 .rounded(px(r::R_CLIP))
819 .bg(rgba(SUB_SHADE()))
820 .child(icon.el(IconSize::Inline, ink))
821}
822
823/// The star of a source row or tile: always laid out (24 px), drawn when the source is a
824/// favourite, picked, or the pointer is on its row -- so toggling never shifts anything.
825fn star_button(
826 id: (&'static str, usize),
827 starred: bool,
828 picked: bool,
829 group: SharedString,
830 path: PathBuf,
831 stream: usize,
832 cx: &mut Context<Player>,
833) -> impl IntoElement {
834 let t = tokens();
835 let tip = if starred { "Remove from favourites" } else { "Favourite" };
836 div()
837 .id(id)
838 .flex_none()
839 .size(px(24.))
840 .flex()
841 .items_center()
842 .justify_center()
843 .rounded(px(r::R_CLIP))
844 .cursor_pointer()
845 .bg(rgba(crate::ui::theme::with_alpha(t.e0, 0x99)))
846 .hover(move |s| s.bg(rgba(crate::ui::theme::with_alpha(t.e0, 0xd9))))
847 .when(!starred && !picked, |d| d.invisible().group_hover(group, |s| s.visible()))
848 .child((if starred { Icon::StarFilled } else { Icon::Star }).el(IconSize::Inline, if starred { t.accent } else { t.ink2 }))
849 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
850 cx.stop_propagation();
851 this.toggle_favourite_of(path.clone(), stream, cx);
852 }))
853 .children(hitmap::dynamic(move || (format!("source.{}.star", id.1), tip.into()), true))
854 .tooltip(crate::ui::widgets::tip_hover(tip, "", None))
855}
856
857/// A bin row of the media list (28 px): disclosure, folder, name, how many files it holds. A
858/// click folds or opens it and picks it, a double-click retypes the name, a right-click opens
859/// its menu, and media dragged onto it are filed in it. The name is edited in place without
860/// the row changing size.
861fn bin_row(
862 player: &Player,
863 bin: &engine::Bin,
864 depth: usize,
865 count: usize,
866 open: bool,
867 cx: &mut Context<Player>,
868) -> impl IntoElement {
869 let t = tokens();
870 let id = bin.id;
871 let picked = player.selected_bin == Some(id);
872 let editing = player.bin_edit.as_ref().filter(|(b, _)| *b == id).map(|(_, f)| f.clone());
873 let name: SharedString = match &editing {
874 Some(f) if f.all => f.text.clone().into(),
875 Some(f) => format!("{}▏", f.text).into(),
876 None => bin.name.clone().into(),
877 };
878 let selected_all = editing.as_ref().is_some_and(|f| f.all && !f.text.is_empty());
879 div()
880 .id(("dock-bin", id as usize))
881 .flex_none()
882 .relative()
883 .h(px(28.))
884 .flex()
885 .items_center()
886 .gap(px(6.))
887 .pl(px(6. + 14. * depth as f32))
888 .pr(px(8.))
889 .rounded(px(r::R_CLIP))
890 .cursor_pointer()
891 .when(picked, |d| d.bg(rgba(t.accent_wash)))
892 .when(!picked, |d| d.hover(move |s| s.bg(rgb(t.e2))))
893 .drag_over::<AssetDrag>(move |d, _, _, _| d.bg(rgb(crate::ui::theme::mix(t.well, t.accent, 0.22))))
894 .on_drop(cx.listener(move |this, drag: &AssetDrag, _, cx| {
895 cx.stop_propagation();
896 let rows = this.rows_for((drag.0.clone(), drag.1));
897 this.move_assets_to_bin(rows, id, cx);
898 }))
899 .on_click(cx.listener(move |this, event: &ClickEvent, _, cx| {
900 if this.bin_edit.is_some() {
901 return;
902 }
903 this.selected_bin = Some(id);
904 this.toggle_bin_open(id, cx);
905 if event.click_count() >= 2 {
906 // The first click of the pair folded it; the second puts it back and renames.
907 this.toggle_bin_open(id, cx);
908 this.begin_bin_edit(id, cx);
909 }
910 cx.notify();
911 }))
912 .on_mouse_down(
913 MouseButton::Right,
914 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
915 cx.stop_propagation();
916 this.open_bin_menu(id, event.position, cx);
917 }),
918 )
919 .when(picked, |d| d.child(div().absolute().left_0().top_0().bottom_0().w(px(2.)).bg(rgb(t.accent))))
920 .child((if open { Icon::ChevronDown } else { Icon::ChevronRight }).el(IconSize::Inline, t.ink3))
921 .child((if open { Icon::FolderOpen } else { Icon::Folder }).el(IconSize::Inline, t.ink2))
922 .child(
923 div()
924 .flex_1()
925 .min_w(px(0.))
926 .h(px(20.))
927 .flex()
928 .items_center()
929 .px(px(2.))
930 .rounded(px(r::R_CLIP))
931 .when(editing.is_some(), |d| d.bg(rgb(t.e3)))
932 .when(selected_all, |d| d.bg(rgb(t.ink3)).text_color(rgb(t.e1)))
933 .type_style(type_scale::body_strong())
934 .text_color(rgb(if selected_all { t.e1 } else { t.ink1 }))
935 .child(div().w_full().min_w(px(0.)).truncate().child(fit_row_name(&name, dock_width() - 84. - 14. * depth as f32, type_scale::BODY_PX))),
936 )
937 .child(
938 div()
939 .flex_none()
940 .type_style(type_scale::caption())
941 .text_color(rgb(t.ink3))
942 .child(count.to_string()),
943 )
944 .tooltip(crate::ui::widgets::tip_hover(&bin.name, "click to fold, double-click to rename", None))
945 .children(hitmap::dynamic(move || (format!("bin.{id}"), "Bin".into()), true))
946}
947
948/// A source's one caption line of plain facts: codec, picture height, and the
949/// stream half where a file has several. No decoder seat, no mono.
950fn row_facts(player: &Player, row: &Row) -> String {
951 // The decoder seat (`HW`/`SW`) is how this machine happens to read the
952 // file: the transport line and the Properties side still say it.
953 let seats = [Backend::Opening, Backend::Hardware, Backend::Software, Backend::Still, Backend::Gap]
954 .map(Backend::label);
955 let resolution = player
956 .facts
957 .get(&row.path)
958 .and_then(Option::as_ref)
959 .and_then(|facts| facts.video.as_ref())
960 .filter(|video| video.height > 0)
961 .map(|video| resolution_label(video.height))
962 .unwrap_or_default();
963 let detail = spoken_streams(player, row, &without_seats(&row.detail, &seats));
964 // A file with no picture says so in words, in place of the codec list its refusal names.
965 let detail = match player.has_video(&row.path) {
966 true => detail,
967 false => match detail.split_once(" · ") {
968 Some((first, rest)) if first.starts_with("no ") => format!("Audio only · {rest}"),
969 None if detail.starts_with("no ") => "Audio only".to_string(),
970 _ => detail,
971 },
972 };
973 join_detail(&detail, &resolution)
974}
975
976/// The stream half of a row's facts with its language spelt out: a track tagged `fra` reads
977/// "French", and one tagged `und` (nobody said) loses the word rather than showing a code.
978fn spoken_streams(player: &Player, row: &Row, detail: &str) -> String {
979 let lang = player
980 .streams
981 .get(&row.path)
982 .and_then(|of_file| of_file.iter().find(|s| s.index == row.stream))
983 .and_then(|info| info.lang.clone());
984 let Some(lang) = lang else { return detail.to_string() };
985 let name = language_name(&lang);
986 detail
987 .split(' ')
988 .filter_map(|word| match word == lang {
989 true => name,
990 false => Some(word),
991 })
992 .collect::<Vec<_>>()
993 .join(" ")
994}
995
996/// The English name of an ISO 639 language code as a muxer writes it, `None` for a code
997/// nobody named ("und") or one this table does not know. Both the 639-2 and the 639-1 forms.
998fn language_name(code: &str) -> Option<&'static str> {
999 Some(match code.to_ascii_lowercase().as_str() {
1000 "eng" | "en" => "English",
1001 "fra" | "fre" | "fr" => "French",
1002 "deu" | "ger" | "de" => "German",
1003 "spa" | "es" => "Spanish",
1004 "ita" | "it" => "Italian",
1005 "por" | "pt" => "Portuguese",
1006 "rus" | "ru" => "Russian",
1007 "jpn" | "ja" => "Japanese",
1008 "zho" | "chi" | "zh" => "Chinese",
1009 "kor" | "ko" => "Korean",
1010 "ara" | "ar" => "Arabic",
1011 "hin" | "hi" => "Hindi",
1012 "nld" | "dut" | "nl" => "Dutch",
1013 "pol" | "pl" => "Polish",
1014 "swe" | "sv" => "Swedish",
1015 "nor" | "nob" | "no" => "Norwegian",
1016 "dan" | "da" => "Danish",
1017 "fin" | "fi" => "Finnish",
1018 "tur" | "tr" => "Turkish",
1019 "ell" | "gre" | "el" => "Greek",
1020 "heb" | "he" => "Hebrew",
1021 "ces" | "cze" | "cs" => "Czech",
1022 "hun" | "hu" => "Hungarian",
1023 "ron" | "rum" | "ro" => "Romanian",
1024 "tha" | "th" => "Thai",
1025 "vie" | "vi" => "Vietnamese",
1026 "ind" | "id" => "Indonesian",
1027 _ => return None,
1028 })
1029}
1030
1031/// Where a source is used, as quiet text: "On V1, A1".
1032/// `bare` drops the "On" for a tile whose line shares its width with the Missing chip.
1033fn usage_text(labels: &[String], bare: bool) -> impl IntoElement {
1034 let full = format!("On {}", labels.join(", "));
1035 div()
1036 .id("dock-usage")
1037 .flex_1()
1038 .min_w(px(0.))
1039 .truncate()
1040 .whitespace_nowrap()
1041 .type_style(type_scale::caption())
1042 .text_color(rgb(tokens().ink3))
1043 .tooltip(crate::ui::widgets::overlay_tip_hover("Used on", "", Some(&labels.join(", "))))
1044 .child(if bare { labels.join(", ") } else { full })
1045}
1046
1047/// Whether a refusal is the timeline's layout (`the timeline is mono`): a track that is
1048/// fine in its file and only does not match the timeline, which is a warning, not an error.
1049fn is_layout_refusal(why: &str) -> bool {
1050 why.starts_with("the timeline is ")
1051}
1052
1053/// A refusal in plain words. A layout mismatch says what happened and what to do; anything
1054/// else is the engine's own reason, shown as it was given.
1055/// The short form of a layout refusal, for a row's detail line (its full sentence is the tooltip).
1056const LAYOUT_SHORT: &str = "Different sound layout";
1057
1058fn refusal_sentence(why: &str) -> String {
1059 match why.strip_prefix("the timeline is ") {
1060 Some(layout) => format!(
1061 "This track doesn't match the timeline's {layout} sound, so it can't go on the timeline. Use another track of this file that is {layout}."
1062 ),
1063 None => why.to_string(),
1064 }
1065}
1066
1067/// The one quiet word a missing file's row or tile wears.
1068fn missing_chip() -> impl IntoElement {
1069 let t = tokens();
1070 div()
1071 .flex_none()
1072 .h(px(16.))
1073 .px(px(6.))
1074 .flex()
1075 .items_center()
1076 .rounded(px(r::R_CLIP))
1077 .bg(rgb(t.e2))
1078 .type_style(type_scale::caption())
1079 .text_color(rgb(t.ink2))
1080 .child("Missing")
1081}
1082
1083/// A row's second line: the length (a still has none), then the plain facts.
1084fn length_line(player: &Player, row: &Row, facts: &str) -> String {
1085 if engine::is_image(&row.path) {
1086 return if facts.is_empty() { "Still image".to_string() } else { facts.to_string() };
1087 }
1088 let secs = f64::from(row.frames) / player.fps.max(1.);
1089 join_detail(&short_length(secs), facts)
1090}
1091
1092/// A clip's length for a badge or a line: `M:SS`, or under a second in tenths ("0.4 s"),
1093/// because a clock reads a quarter-second clip as "0:00".
1094fn short_length(secs: f64) -> String {
1095 match secs < 1. {
1096 true => format!("{:.1} s", secs.max(0.)),
1097 false => clock(secs as f32),
1098 }
1099}
1100
1101/// A compact ghost button with an icon and a word, for a row's own action.
1102fn ghost_link(id: (&'static str, usize), icon: Icon, text: &'static str) -> gpui::Stateful<Div> {
1103 let t = tokens();
1104 div()
1105 .id(id)
1106 .flex_none()
1107 .h(px(18.))
1108 .px(px(4.))
1109 .flex()
1110 .items_center()
1111 .gap(px(4.))
1112 .rounded(px(r::R_CLIP))
1113 .cursor_pointer()
1114 .hover(move |s| s.bg(rgb(t.e3)))
1115 .type_style(type_scale::caption_strong())
1116 .text_color(rgb(t.accent))
1117 .child(icon.el_px(px(12.), t.accent))
1118 .child(text)
1119}
1120
1121/// The length badge on a poster's bottom-right corner.
1122fn duration_badge(row: &Row, fps: f64) -> impl IntoElement {
1123 let secs = f64::from(row.frames) / fps.max(1.);
1124 div()
1125 .absolute()
1126 .right(px(3.))
1127 .bottom(px(3.))
1128 .px(px(4.))
1129 .rounded(px(2.))
1130 .bg(rgba(SUB_SHADE()))
1131 .type_style(type_scale::caption())
1132 .text_color(rgb(tokens().ink1))
1133 .child(short_length(secs))
1134}
1135
1136/// The 6px film ink dot (REDESIGN §0: one of the four places a source's ink
1137/// lives). Right-click opens the row menu, as the whole row does.
1138fn film_dot(
1139 i: usize,
1140 tint: usize,
1141 usable: bool,
1142 path: PathBuf,
1143 stream: usize,
1144 cx: &mut Context<Player>,
1145) -> impl IntoElement {
1146 div()
1147 .id(("dock-source-dot", i))
1148 .flex_none()
1149 .size(px(6.))
1150 .rounded_full()
1151 .bg(rgb(source_tint(tint)))
1152 .when(usable, |d| {
1153 d.on_mouse_down(
1154 MouseButton::Right,
1155 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
1156 cx.stop_propagation();
1157 this.selected_asset = Some((path.clone(), stream));
1158 this.library_menu = Some(LibraryMenu { path: path.clone(), stream, at: event.position, details: false });
1159 cx.notify();
1160 }),
1161 )
1162 })
1163}
1164
1165/// The picked media row's tooltip: how to add more rows to the picks.
1166const PICK_HINT: &str = "Ctrl-click to pick more";
1167
1168/// Whether a click on a source row adds the row to the picks: Ctrl, Shift or the platform key
1169/// held, and not a double click (which opens the source). Otherwise the click picks that row alone.
1170pub(crate) fn click_adds_to_picks(held: gpui::Modifiers, click_count: usize) -> bool {
1171 (held.control || held.shift || held.platform) && click_count < 2
1172}
1173
1174/// The gestures every media row/tile answers, in one place: right-click
1175/// anywhere opens the row menu (Add, Remove, Reveal, Properties -- DESIGN §9),
1176/// a click picks (ctrl/shift add to the picks, a multicam clip is made of
1177/// several), a double click opens it in the source viewer, and a drag carries the
1178/// source to a lane (the bench's `AssetDrag` drop target takes it).
1179#[allow(clippy::too_many_arguments)]
1180fn source_gestures(
1181 el: gpui::Stateful<Div>,
1182 i: usize,
1183 path: &std::path::Path,
1184 stream: usize,
1185 usable: bool,
1186 ghost: SharedString,
1187 tip: SharedString,
1188 cx: &mut Context<Player>,
1189) -> gpui::Stateful<Div> {
1190 let menu_path = path.to_path_buf();
1191 let click_path = path.to_path_buf();
1192 let drag = AssetDrag(path.to_path_buf(), stream);
1193 el.child(crate::ui::anchor::probe_row(path, stream)).on_mouse_down(
1194 MouseButton::Right,
1195 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
1196 cx.stop_propagation();
1197 this.selected_asset = Some((menu_path.clone(), stream));
1198 this.library_menu = Some(LibraryMenu { path: menu_path.clone(), stream, at: event.position, details: false });
1199 cx.notify();
1200 }),
1201 )
1202 .when(usable, |d| {
1203 d.cursor_pointer()
1204 .on_click(cx.listener(move |this, event: &ClickEvent, _, cx| {
1205 let held = crate::ui::widgets::press_modifiers(event);
1206 if click_adds_to_picks(held, event.click_count()) {
1207 this.toggle_asset_pick(click_path.clone(), stream);
1208 } else {
1209 this.pick_one_asset(click_path.clone(), stream);
1210 }
1211 if event.click_count() >= 2 {
1212 this.open_preview(&click_path, stream, cx);
1213 }
1214 cx.notify();
1215 }))
1216 .on_drag(drag, {
1217 let me = cx.entity();
1218 move |_, _, _, cx| {
1219 // A fresh gesture inherits nothing: the last live sample of
1220 // the previous drag must not land this one on its lane.
1221 me.update(cx, |this, _| {
1222 this.drag_lane = None;
1223 this.drag_x = None;
1224 });
1225 cx.new(|_| Tip(ghost.clone()))
1226 }
1227 })
1228 })
1229 .when(!tip.is_empty(), |d| d.tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()))
1230 .children(hitmap::dynamic(move || (format!("source.{i}.row"), "Source row".into()), usable))
1231}
1232
1233/// One grid tile (REDESIGN §3.8): a 16:9 poster with the length and the `+`
1234/// on it, the name under it. Same gestures as a row.
1235fn source_tile(
1236 player: &Player,
1237 i: usize,
1238 row: &Row,
1239 picked: bool,
1240 star: Option<bool>,
1241 tile_w: f32,
1242 cx: &mut Context<Player>,
1243) -> impl IntoElement {
1244 let t = tokens();
1245 let usable = row.unusable.is_none();
1246 let offline = is_offline(player, &row.path);
1247 let ok = usable && !offline;
1248 let name: SharedString = stem(&row.name).into();
1249 let can_insert = ok && player.session.is_some() && player.exporting().is_none();
1250 let (path, stream) = (row.path.clone(), row.stream);
1251 let add_path = path.clone();
1252 let tip: SharedString = match (&row.unusable, offline) {
1253 // The tile says Missing and the banner above the list offers Relink; a plate would cover the next tile.
1254 (_, true) => SharedString::default(),
1255 (Some(why), _) => refusal_sentence(why).into(),
1256 _ if picked => PICK_HINT.into(),
1257 // The name is under the poster; only a name the tile cuts needs saying whole, and a plate
1258 // over the poster would cover its length badge.
1259 _ if crate::ui::popup::text_w(&name, type_scale::CAPTION_PX + 1., false) <= tile_w - 24. => SharedString::default(),
1260 _ => name.clone(),
1261 };
1262 let thumb_h = (tile_w - 12.) * 9. / 16.;
1263 let group: SharedString = format!("dock-source-tile-{i}").into();
1264 let star_path = row.path.clone();
1265 let el = div()
1266 .id(("dock-source", i))
1267 .group(group.clone())
1268 .flex_none()
1269 .w(px(tile_w))
1270 .p(px(5.))
1271 .flex()
1272 .flex_col()
1273 .gap(px(6.))
1274 .rounded(px(r::R_CARD))
1275 .border_1()
1276 .border_color(if picked { rgba((t.accent << 8) | 0x59).into() } else { gpui::transparent_black() })
1277 .when(picked, |d| d.bg(rgba(t.accent_wash)))
1278 .when(!picked, |d| d.hover(move |s| s.bg(rgb(t.e2))));
1279 source_gestures(el, i, &row.path, row.stream, ok, name.clone(), tip, cx)
1280 .child(
1281 poster(player, &row.path, ok, r::R_CLIP)
1282 .w_full()
1283 .h(px(thumb_h))
1284 .relative()
1285 .when(!usable || offline, |d| d.child(poster_badge(Icon::TriangleAlert, if offline { t.warn } else { t.err }, true)))
1286 .when_some(star, |d, starred| {
1287 d.child(
1288 div().absolute().left(px(2.)).top(px(2.)).child(star_button(
1289 ("dock-tile-star", i),
1290 starred,
1291 picked,
1292 group.clone(),
1293 star_path,
1294 stream,
1295 cx,
1296 )),
1297 )
1298 })
1299 .when(ok, |d| {
1300 // A still has no length to show: its badge would read a made-up "10:00".
1301 d.when(!engine::is_image(&row.path), |d| d.child(duration_badge(row, player.fps)))
1302 .child(
1303 // On hover or selection only, like the list's: laid out always, so nothing shifts.
1304 div().absolute().right(px(2.)).top(px(2.))
1305 .when(!picked, |d| d.invisible().group_hover(group.clone(), |s| s.visible()))
1306 .child(
1307 Button::new("dock-tile-add-btn")
1308 .icon(Icon::Plus)
1309 .style(ButtonStyle::Secondary)
1310 .size(ButtonSize::Small)
1311 .enabled(can_insert)
1312 .build()
1313 .id(("dock-add-at-playhead", i))
1314 .when(can_insert, |d| {
1315 d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1316 cx.stop_propagation();
1317 this.append_source(&add_path, stream, cx);
1318 cx.notify();
1319 }))
1320 })
1321 .children(hitmap::dynamic(
1322 move || (format!("source.{i}.add"), "Append to timeline end".into()),
1323 can_insert,
1324 ))
1325 .tooltip(crate::ui::widgets::tip_hover("Append to timeline end", "", None)),
1326 ),
1327 )
1328 })
1329 )
1330 .child(
1331 div()
1332 .flex()
1333 .items_center()
1334 .gap(px(4.))
1335 .child(film_dot(i, row.tint, ok, path, stream, cx))
1336 .child(
1337 div()
1338 .id(("dock-tile-name", i))
1339 .flex_1()
1340 .min_w(px(0.))
1341 .truncate()
1342 .type_style(type_scale::body_strong())
1343 .text_color(rgb(if ok { t.ink1 } else { t.ink2 }))
1344 .child(fit_row_name(&name, tile_w - 30., type_scale::BODY_PX))
1345 .tooltip(crate::ui::widgets::tip_hover(&name, "", None)),
1346 ),
1347 )
1348 // The status line, always there so the tiles of a pair stay the same height: a missing
1349 // file's chip, then where the source is used.
1350 .child({
1351 let chips = usage_labels(player, row.tint);
1352 div()
1353 .h(px(18.))
1354 .flex()
1355 .items_center()
1356 .gap(px(6.))
1357 .overflow_hidden()
1358 .when(offline, |d| d.child(missing_chip()))
1359 .when(!chips.is_empty(), |d| d.child(usage_text(&chips, offline)))
1360 })
1361}
1362
1363/// One entry of the Sources list, planned before anything is drawn: either a
1364/// media row or the subtitle group of some file. Plain data so the *order* --
1365/// the branchy part -- can be tested without a window.
1366#[derive(Debug, PartialEq, Clone, Copy)]
1367pub(crate) enum Slot {
1368 /// Index into the media rows.
1369 Media(usize),
1370 /// Index into the subtitle groups.
1371 Subs(usize),
1372}
1373
1374/// Where each subtitle group belongs in the one Sources list: directly under
1375/// the source that carries it, never at the end of the list (user 2026-09-10,
1376/// "you put a video related subtitle to the end") -- a track that belongs to a
1377/// file is that file's subset and reads as one, so it follows the *last* row
1378/// naming that file, the way `library_rows` keeps a file's audio streams
1379/// together. A standalone `.srt` belongs to nobody and stays a top-level row
1380/// in arrival order, after the sources.
1381pub(crate) fn source_list_order(media: &[PathBuf], subs: &[PathBuf]) -> Vec<Slot> {
1382 let mut slots = Vec::new();
1383 for (i, path) in media.iter().enumerate() {
1384 slots.push(Slot::Media(i));
1385 if media[i + 1..].contains(path) {
1386 continue; // a later row still names this file; its subs go under that one
1387 }
1388 slots.extend(
1389 subs.iter()
1390 .enumerate()
1391 .filter(|(_, sub)| *sub == path)
1392 .map(|(j, _)| Slot::Subs(j)),
1393 );
1394 }
1395 slots.extend(
1396 subs.iter()
1397 .enumerate()
1398 .filter(|(_, sub)| !media.contains(sub))
1399 .map(|(j, _)| Slot::Subs(j)),
1400 );
1401 slots
1402}
1403
1404/// Imported subtitle tracks, grouped by their source -- the Text tab's own
1405/// rows (DESIGN.md's "text section ... not serving to anything", user
1406/// 2026-08-27: relocated off the unconditional spot under the source list
1407/// and into the tab that names them). A row selects and drags its track; its
1408/// header folds that source's rows without becoming a cycle. Styled off
1409/// [`source_row`] -- same dot, same name/detail ink and type scale, same
1410/// hover fill and selection ring -- so Text stops reading as a second
1411/// dialect from Media/Audio. Hands back the track count for the tab header's
1412/// own count line, same as `rows.len()` does for the other two tabs.
1413fn subtitle_tab_rows(
1414 player: &Player,
1415 parents: &[PathBuf],
1416 cx: &mut Context<Player>,
1417) -> (usize, Vec<(PathBuf, usize, AnyElement)>) {
1418 let mut groups = match player.session.as_ref() {
1419 Some(session) => subtitle_rows(session.subtitles()),
1420 None => Vec::new(),
1421 };
1422 // The same search box the other two tabs answer to -- a visible filter
1423 // that a whole tab ignored would be a dead control. It matches a track's
1424 // label or its file's name; a group with no surviving track leaves with
1425 // its rows.
1426 let filter = player.dock_filter.to_lowercase();
1427 if !filter.is_empty() {
1428 for group in &mut groups {
1429 if group.name.to_lowercase().contains(&filter) {
1430 continue;
1431 }
1432 group
1433 .rows
1434 .retain(|row| row.label.to_lowercase().contains(&filter));
1435 }
1436 groups.retain(|group| !group.rows.is_empty());
1437 }
1438 // Which lane(s) actually hold each track's captions right now -- the
1439 // row's second line answers "is it showing?", so it has to read the
1440 // timeline, not stay the literal "not placed" it was born saying (the
1441 // old palette's badge never updated after a drop).
1442 let placed_on = |track: usize| -> Option<String> {
1443 let session = player.session.as_ref()?;
1444 let lanes: Vec<String> = session
1445 .lanes()
1446 .into_iter()
1447 .filter(|lane| session.sub_lane(*lane).iter().any(|sub| sub.track == track))
1448 .map(|lane| lane.label())
1449 .collect();
1450 if lanes.is_empty() {
1451 None
1452 } else {
1453 Some(lanes.join(" "))
1454 }
1455 };
1456 let count: usize = groups.iter().map(|group| group.rows.len()).sum();
1457 let rows: Vec<_> = groups
1458 .into_iter()
1459 .enumerate()
1460 .map(|(group_ord, group)| {
1461 // A source already in the list is this group's parent row: its
1462 // tracks hang under it bare, with no `▸ name 1 track` row of their
1463 // own to separate them from it. Past three, the disclosure comes
1464 // back -- and arrives shut, so membership of `sub_folded` means
1465 // the editor *opened* it there.
1466 let nested = parents.contains(&group.path);
1467 let group_path = group.path.clone();
1468 let fold_path = group.path.clone();
1469 let tint = file_tint(player.sources(), &group.path);
1470 let track_count = group.rows.len();
1471 let tracks: Vec<_> = group
1472 .rows
1473 .into_iter()
1474 .map(|row| {
1475 let track = row.track;
1476 let picked = track == player.sub_track;
1477 let usable = row.refused.is_none();
1478 let title: SharedString = match track_count {
1479 1 => row.label,
1480 _ => format!("{} {}", row.label, row.number),
1481 }
1482 .into();
1483 let detail: SharedString = row
1484 .refused
1485 .or_else(|| placed_on(track))
1486 .unwrap_or_else(|| NOT_ON_TIMELINE.to_string())
1487 .into();
1488 let ghost = title.clone();
1489 let hitmap_title = title.clone();
1490 let select_title = title.clone();
1491 div()
1492 .id(("dock-subtitle-track", track))
1493 .flex_none()
1494 .flex()
1495 .items_center()
1496 .gap(px(6.))
1497 // A track is the header's subset, and the row says
1498 // so the way an outline does: stepped in under the
1499 // header's own name (user 2026-08-27, "indentation
1500 // is needed for subset").
1501 .pl(px(30.))
1502 .pr(px(8.))
1503 .py(px(4.))
1504 .rounded(px(3.))
1505 .border_1()
1506 .border_color(match picked {
1507 // The ring is always in flow -- transparent at rest, ink1 when
1508 // picked -- because a `when(picked, border_1())` added a pixel of
1509 // box on selection and shoved every row's text sideways.
1510 true => rgb(INK1()).into(),
1511 false => gpui::transparent_black(),
1512 })
1513 .when(!usable, |d| d.opacity(0.5))
1514 .when(usable, |d| {
1515 d.cursor_pointer()
1516 .hover(|s| s.bg(rgb(DARK_RAISED())))
1517 .on_drag(SubPick(track), {
1518 let me = cx.entity();
1519 move |_, _, _, cx| {
1520 // A fresh gesture inherits nothing: `Player::drag_lane`
1521 // and `Player::drag_x` are the *last live sample* of the
1522 // drag being made, and a drag whose first sample lands
1523 // outside every row would otherwise be let go onto the
1524 // lane the previous one ended over.
1525 me.update(cx, |this, _| {
1526 this.drag_lane = None;
1527 this.drag_x = None;
1528 });
1529 cx.new(|_| Tip(ghost.clone()))
1530 }
1531 })
1532 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1533 this.sub_track = track;
1534 cx.notify();
1535 }))
1536 })
1537 .tooltip(crate::ui::widgets::tip_hover(
1538 "Subtitle track",
1539 "drag to a lane",
1540 None,
1541 ))
1542 .children(hitmap::dynamic(
1543 move || {
1544 (
1545 format!("subtitle.{group_ord}.{track}.row"),
1546 hitmap_title.to_string(),
1547 )
1548 },
1549 usable,
1550 ))
1551 .children(hitmap::dynamic(
1552 move || {
1553 (
1554 format!("subtitle.{group_ord}.{track}.select"),
1555 format!("Select {select_title}"),
1556 )
1557 },
1558 usable,
1559 ))
1560 .child(
1561 // The same round dot `source_row`'s own name line
1562 // opens with, not the old vertical bar -- one dot
1563 // shape for every row this dock draws.
1564 div()
1565 .flex_none()
1566 .w(px(8.))
1567 .h(px(8.))
1568 .rounded(px(4.))
1569 .when_some(tint, |d, tint| d.bg(rgb(tint))),
1570 )
1571 .child(
1572 div()
1573 .flex_1()
1574 .min_w(px(0.))
1575 .truncate()
1576 // A step below the header's LABEL_ROW_PX --
1577 // subset smaller than superset (user
1578 // 2026-08-27), same ink so it stays a name,
1579 // not a footnote.
1580 .type_style(label_tabular(
1581 type_scale::CHORD_METADATA_MIN_PX,
1582 FontWeight::MEDIUM,
1583 ))
1584 .text_color(rgb(INK1()))
1585 .child(title),
1586 )
1587 .child(
1588 div()
1589 .flex_none()
1590 .truncate()
1591 .type_style(label_tabular(type_scale::FLOOR_PX, FontWeight::MEDIUM))
1592 .text_color(rgb(INK3()))
1593 .child(detail),
1594 )
1595 .child(
1596 div()
1597 .id(("dock-subtitle-remove", track))
1598 .flex_none()
1599 .w(px(HIT_MIN))
1600 .h(px(HIT_MIN))
1601 .flex()
1602 .items_center()
1603 .justify_center()
1604 .rounded(px(3.))
1605 .cursor_pointer()
1606 .hover(|s| s.bg(rgb(DARK_RAISED())).text_color(rgb(INK1())))
1607 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1608 cx.stop_propagation();
1609 this.remove_subtitle_track(track, cx);
1610 }))
1611 .tooltip(crate::ui::widgets::tip_hover(
1612 "Remove subtitle track",
1613 "",
1614 None,
1615 ))
1616 .children(hitmap::dynamic(
1617 move || {
1618 (
1619 format!("subtitle.{track}.remove"),
1620 "Remove subtitle".into(),
1621 )
1622 },
1623 true,
1624 ))
1625 .child("×"),
1626 )
1627 })
1628 .collect();
1629 let has_header = !nested || track_count > 3;
1630 let folded = has_header && (nested != player.sub_folded.contains(&group_path));
1631 let header = div()
1632 .id(("dock-subtitle-group", group_ord))
1633 .flex_none()
1634 .flex()
1635 .items_center()
1636 .gap(px(6.))
1637 .px(px(8.))
1638 // Stepped in under its parent when it has one, the
1639 // same outline the track rows below it read as.
1640 .when(nested, |d| d.pl(px(22.)))
1641 .py(px(4.))
1642 .rounded(px(3.))
1643 .cursor_pointer()
1644 .hover(|s| s.bg(rgb(DARK_RAISED())))
1645 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1646 if !this.sub_folded.remove(&fold_path) {
1647 this.sub_folded.insert(fold_path.clone());
1648 }
1649 cx.notify();
1650 }))
1651 .tooltip(crate::ui::widgets::tip_hover(
1652 "Fold this source",
1653 "click",
1654 None,
1655 ))
1656 .children(hitmap::dynamic(
1657 move || {
1658 (
1659 format!("subtitle-group.{group_ord}.fold"),
1660 "Toggle subtitle group".into(),
1661 )
1662 },
1663 true,
1664 ))
1665 // Bare, the glyph inherited the panel's dim ink and
1666 // vanished ("the little arrow on left side is hard
1667 // to see", user 2026-08-27) -- it reads at the same
1668 // ink as the name it folds.
1669 .child(
1670 div()
1671 .flex_none()
1672 .w(px(10.))
1673 .text_color(rgb(INK1()))
1674 .child(if folded { "▸" } else { "▾" }),
1675 )
1676 .when_some(tint, |d, tint| {
1677 d.child(
1678 div()
1679 .flex_none()
1680 .w(px(8.))
1681 .h(px(8.))
1682 .rounded(px(4.))
1683 .bg(rgb(tint)),
1684 )
1685 })
1686 .child(
1687 div()
1688 .flex_1()
1689 .min_w(px(0.))
1690 .truncate()
1691 .type_style(label_tabular(type_scale::LABEL_ROW_PX, FontWeight::MEDIUM))
1692 .text_color(rgb(INK1()))
1693 .child(group.name),
1694 )
1695 .child(
1696 div()
1697 .flex_none()
1698 .type_style(label_tabular(type_scale::CHORD_METADATA_MIN_PX, FontWeight::MEDIUM))
1699 .text_color(rgb(INK3()))
1700 .child(format!(
1701 "{track_count} track{}",
1702 if track_count == 1 { "" } else { "s" }
1703 )),
1704 );
1705 (
1706 group_path,
1707 track_count,
1708 div()
1709 .flex_none()
1710 .flex()
1711 .flex_col()
1712 .gap(px(2.))
1713 .when(has_header, |d| d.child(header))
1714 .when(!folded, |d| d.children(tracks))
1715 .into_any_element(),
1716 )
1717 })
1718 .collect();
1719 (count, rows)
1720}
1721
1722/// The dock's own menu ([`DOCK_ITEMS`]): the three ways a file gets in, on a
1723/// right-click anywhere in the Sources body a row does not claim first. It is
1724/// where `Paste path` and `Import subtitles` went when cleanse round 2 took
1725/// their footer rows, so both keep a pointer door -- including on an empty
1726/// library, which is when a pasted path is worth most.
1727fn opens_dock_menu(
1728 cx: &mut Context<Player>,
1729) -> impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static {
1730 cx.listener(|this, event: &MouseDownEvent, _, cx| {
1731 if this.modal() || this.session.is_none() {
1732 return;
1733 }
1734 cx.stop_propagation();
1735 this.context_menu = Some(ContextMenu {
1736 lane: Lane::V1,
1737 on: MenuOn::Dock,
1738 at: event.position,
1739 details: false,
1740 sub: Sub::Closed,
1741 });
1742 cx.notify();
1743 })
1744}
1745
1746/// The Sources tab, cleanse round 2 (2026-09-10, user "seems cool, let's
1747/// apply"): one filter and one list of everything this project holds --
1748/// picture, sound, and the subtitle tracks beside them -- with what a row
1749/// *is* read off its own metadata line instead of off a sub-tab the editor
1750/// had to pick first. The `MEDIA` head, the `Media / Audio / Text` strip, the
1751/// `↕ Recent` sort cycle and the `IMPORT` head are all gone with it; the row
1752/// facts are still [`library_rows`]' and [`subtitle_tab_rows`]'.
1753fn sources_tab(
1754 player: &Player,
1755 _window: &mut Window,
1756 cx: &mut Context<Player>,
1757) -> impl IntoElement {
1758 let sources = player
1759 .session
1760 .as_ref()
1761 .map_or(&[][..], PlaybackSession::sources);
1762 let all_rows: Vec<Row> = library_rows(
1763 sources,
1764 &player.streams,
1765 &player.decoders,
1766 player.timeline_audio(),
1767 |path| {
1768 player
1769 .session
1770 .as_ref()
1771 .map_or(0, |session| session.file_frames(path))
1772 },
1773 );
1774 let filter = player.dock_filter.to_lowercase();
1775 let favs_only = fav_only();
1776 let kind = KIND.get();
1777 // The source a row stands for: a file's further audio streams are rows before they are
1778 // sources, and have no bin or star.
1779 let source_of = |row: &Row| sources.iter().position(|s| s.path == row.path && s.audio_stream == row.stream);
1780 let mut rows: Vec<(Row, usize)> = all_rows
1781 .into_iter()
1782 .map(|row| {
1783 let placed = player.row_ctx(&row.path, row.stream).placed;
1784 (row, placed)
1785 })
1786 .filter(|(row, placed)| {
1787 (filter.is_empty()
1788 || row.name.to_lowercase().contains(&filter)
1789 || row.detail.to_lowercase().contains(&filter)
1790 || (NOT_ON_TIMELINE.contains(&filter) && *placed == 0))
1791 && (!favs_only || source_of(row).is_some_and(|i| sources[i].fav))
1792 && kind_matches(kind, &row.path)
1793 })
1794 .collect();
1795 // Sort: the project's own order is "date added"; the others reorder the rows (a stable sort,
1796 // so a file's streams stay together).
1797 match SORT.get() {
1798 0 => rows.sort_by_cached_key(|(row, _)| stem(&row.name).to_lowercase()),
1799 2 => rows.sort_by_key(|(row, _)| std::cmp::Reverse(row.frames)),
1800 _ => {}
1801 }
1802 // The subtitle tracks join the same list rather than hiding behind a tab
1803 // of their own: a standalone `.srt` is a source in the sense that matters
1804 // here -- something that came in and can go on a lane -- and the tracks
1805 // inside a container are drawn *under* that file's own row
1806 // ([`source_list_order`]), not after every other source.
1807 let media: Vec<PathBuf> = rows.iter().map(|(row, _)| row.path.clone()).collect();
1808 let (_, subtitles) = subtitle_tab_rows(player, &media, cx);
1809 let subs: Vec<PathBuf> = subtitles.iter().map(|(path, ..)| path.clone()).collect();
1810 // Past three tracks the group under a parent arrives shut, so the count
1811 // goes on the parent's own metadata line -- the number stays readable
1812 // while the rows it counts are folded away.
1813 for (i, (row, _)) in rows.iter_mut().enumerate() {
1814 if media[i + 1..].contains(&row.path) {
1815 continue;
1816 }
1817 if let Some((_, n, _)) = subtitles
1818 .iter()
1819 .find(|(path, n, _)| *path == row.path && *n > 3)
1820 {
1821 row.detail = join_detail(&row.detail, &format!("{n} subs"));
1822 }
1823 }
1824 let mut subtitles: Vec<Option<AnyElement>> =
1825 subtitles.into_iter().map(|(.., el)| Some(el)).collect();
1826 let mut row_elements: Vec<AnyElement> = Vec::new();
1827 let grid = grid_view();
1828 // The bins: media are listed under the bin they are filed in, bins first. A search or the
1829 // favourites filter opens every bin that still has something in it and hides the rest, so a
1830 // match is never behind a closed fold.
1831 let bins: &[engine::Bin] = player.session.as_ref().map_or(&[][..], PlaybackSession::bins);
1832 let narrowed = !filter.is_empty() || favs_only || kind != 0;
1833 let order = source_list_order(&media, &subs);
1834 let mut by_bin: std::collections::HashMap<u32, Vec<Slot>> = std::collections::HashMap::new();
1835 {
1836 let (mut here, mut last): (u32, Option<&PathBuf>) = (0, None);
1837 for slot in &order {
1838 match *slot {
1839 Slot::Media(i) => {
1840 here = source_of(&rows[i].0).map_or(0, |s| sources[s].bin);
1841 last = Some(&media[i]);
1842 by_bin.entry(here).or_default().push(*slot);
1843 }
1844 // A file's subtitle tracks stay under the file; a standalone track is top level.
1845 Slot::Subs(j) => {
1846 let bin = if last == Some(&subs[j]) { here } else { 0 };
1847 by_bin.entry(bin).or_default().push(*slot);
1848 }
1849 }
1850 }
1851 }
1852 let media_in = |bin: u32| by_bin.get(&bin).map_or(0, |v| v.iter().filter(|s| matches!(s, Slot::Media(_))).count());
1853 enum Entry {
1854 Bin(u32, usize, usize, bool),
1855 Hint(usize),
1856 Slot(Slot, usize),
1857 }
1858 let mut entries: Vec<Entry> = Vec::new();
1859 for top in bins.iter().filter(|b| b.parent == 0) {
1860 let kids: Vec<&engine::Bin> = bins.iter().filter(|b| b.parent == top.id).collect();
1861 let total = media_in(top.id) + kids.iter().map(|k| media_in(k.id)).sum::<usize>();
1862 if narrowed && total == 0 {
1863 continue;
1864 }
1865 let open = narrowed || !player.collapsed_bins.contains(&top.id);
1866 entries.push(Entry::Bin(top.id, 0, total, open));
1867 if !open {
1868 continue;
1869 }
1870 for kid in kids {
1871 let n = media_in(kid.id);
1872 if narrowed && n == 0 {
1873 continue;
1874 }
1875 let kid_open = narrowed || !player.collapsed_bins.contains(&kid.id);
1876 entries.push(Entry::Bin(kid.id, 1, n, kid_open));
1877 if kid_open {
1878 entries.extend(by_bin.get(&kid.id).into_iter().flatten().map(|s| Entry::Slot(*s, 2)));
1879 if n == 0 {
1880 entries.push(Entry::Hint(2));
1881 }
1882 }
1883 }
1884 entries.extend(by_bin.get(&top.id).into_iter().flatten().map(|s| Entry::Slot(*s, 1)));
1885 if media_in(top.id) == 0 && total == 0 {
1886 entries.push(Entry::Hint(1));
1887 }
1888 }
1889 entries.extend(by_bin.get(&0).into_iter().flatten().map(|s| Entry::Slot(*s, 0)));
1890 let dock_w = f32::from_bits(DOCK_W_BITS.load(std::sync::atomic::Ordering::Relaxed));
1891 let tile_w = ((if dock_w > 0. { dock_w } else { r::DOCK_W } - 24. - 4.) / 2.).floor();
1892 let mut tiles: Vec<AnyElement> = Vec::new();
1893 let flush = |tiles: &mut Vec<AnyElement>, out: &mut Vec<AnyElement>| {
1894 if !tiles.is_empty() {
1895 out.push(div().flex_none().flex().gap(px(4.)).children(tiles.drain(..)).into_any_element());
1896 }
1897 };
1898 for entry in entries {
1899 let (slot, depth) = match entry {
1900 Entry::Bin(id, depth, count, open) => {
1901 flush(&mut tiles, &mut row_elements);
1902 if let Some(bin) = bins.iter().find(|b| b.id == id) {
1903 row_elements.push(bin_row(player, bin, depth, count, open, cx).into_any_element());
1904 }
1905 continue;
1906 }
1907 Entry::Hint(depth) => {
1908 flush(&mut tiles, &mut row_elements);
1909 row_elements.push(
1910 div()
1911 .flex_none()
1912 .h(px(28.))
1913 .pl(px(34. + 14. * (depth - 1) as f32))
1914 .flex()
1915 .items_center()
1916 .type_style(type_scale::caption())
1917 .text_color(rgb(tokens().ink3))
1918 .child("Empty — drag media here")
1919 .into_any_element(),
1920 );
1921 continue;
1922 }
1923 Entry::Slot(slot, depth) => (slot, depth),
1924 };
1925 match slot {
1926 Slot::Media(i) => {
1927 let (row, placed) = &rows[i];
1928 let picked = player
1929 .selected_asset
1930 .as_ref()
1931 .is_some_and(|p| *p == (row.path.clone(), row.stream))
1932 || player.asset_picks.contains(&(row.path.clone(), row.stream));
1933 let star = source_of(row).map(|s| sources[s].fav);
1934 if grid {
1935 tiles.push(source_tile(player, i, row, picked, star, tile_w, cx).into_any_element());
1936 if tiles.len() == 2 {
1937 flush(&mut tiles, &mut row_elements);
1938 }
1939 } else {
1940 let el = source_row(player, i, row, *placed, picked, star, cx).into_any_element();
1941 // Rows inside a bin are indented under it.
1942 row_elements.push(match depth {
1943 0 => el,
1944 d => div().flex_none().pl(px(14. * d as f32)).child(el).into_any_element(),
1945 });
1946 }
1947 }
1948 Slot::Subs(j) => {
1949 flush(&mut tiles, &mut row_elements);
1950 if let Some(el) = subtitles[j].take() {
1951 row_elements.push(match depth {
1952 0 => el,
1953 d => div().flex_none().pl(px(14. * d as f32)).child(el).into_any_element(),
1954 });
1955 }
1956 }
1957 }
1958 }
1959 flush(&mut tiles, &mut row_elements);
1960 let filter_text: SharedString = player.dock_filter.clone().into();
1961 // One banner for every missing file, one Relink for the first (the export sheet's rule).
1962 // The Favourites view counts only the missing files it shows, so its banner is about its own rows.
1963 let missing: Vec<PathBuf> = offline_files(player)
1964 .into_iter()
1965 .filter(|p| !favs_only || sources.iter().any(|s| s.path == *p && s.fav))
1966 .collect();
1967 let banner = (!missing.is_empty()).then(|| {
1968 let t = tokens();
1969 let first = missing[0].clone();
1970 let words = match missing.len() {
1971 1 => "1 file is missing".to_string(),
1972 n => format!("{n} files are missing"),
1973 };
1974 div()
1975 .id("dock-missing-banner")
1976 .flex_none()
1977 .h(px(40.))
1978 .px(px(10.))
1979 .flex()
1980 .items_center()
1981 .gap(px(8.))
1982 .rounded(px(r::R_CONTROL))
1983 .bg(rgb(t.e2))
1984 .child(Icon::TriangleAlert.el(IconSize::Inline, t.warn))
1985 .child(div().flex_1().min_w(px(0.)).truncate().type_style(type_scale::body()).text_color(rgb(t.ink1)).child(words))
1986 .child(
1987 Button::new("dock-relink-all")
1988 .label("Relink\u{2026}")
1989 .style(ButtonStyle::Secondary)
1990 .size(ButtonSize::Small)
1991 .build()
1992 .tooltip(crate::ui::widgets::tip_hover("Point this missing file at its new place; same-named files in that folder follow", "", None))
1993 .children(hitmap::control("dock.relink", "Relink", true))
1994 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| this.relink_pick(first.clone(), cx))),
1995 )
1996 });
1997 // The sort-and-show list, hung under its button.
1998 let sort_list = SORT_OPEN.get().then(|| {
1999 let me = cx.entity();
2000 let heading = |text: &'static str| kit::section_head(text, None).h(px(24.)).px(px(8.));
2001 let mut plate = kit::plate(6.)
2002 .id("dock-sort-list")
2003 .absolute()
2004 .top(px(8. + r::CONTROL_M + 4.))
2005 .right(px(12.))
2006 .w(px(188.))
2007 .p(px(crate::layout::MENU_PAD))
2008 .flex()
2009 .flex_col()
2010 .occlude()
2011 .on_mouse_down_out(cx.listener(|_, _: &MouseDownEvent, _, cx| {
2012 SORT_OPEN.set(false);
2013 SORT_CLOSED.set(Some(std::time::Instant::now()));
2014 cx.notify();
2015 }))
2016 .child(heading("Sort by"));
2017 for (n, label) in SORTS.iter().enumerate() {
2018 let me = me.clone();
2019 plate = plate.child(kit::choice_row(("dock-sort-opt", n), *label, SORT.get() == n, move |_, cx| {
2020 SORT.set(n);
2021 me.update(cx, |_, cx| cx.notify());
2022 }));
2023 }
2024 plate = plate.child(crate::ui::popup::popup_rule()).child(heading("Show"));
2025 for (n, label) in KINDS.iter().enumerate() {
2026 let me = me.clone();
2027 plate = plate.child(kit::choice_row(("dock-kind-opt", n), *label, KIND.get() == n, move |_, cx| {
2028 KIND.set(n);
2029 me.update(cx, |_, cx| cx.notify());
2030 }));
2031 }
2032 gpui::deferred(plate)
2033 });
2034 div()
2035 .id("dock-sources")
2036 .relative()
2037 .track_focus(&player.focus_dock)
2038 .on_key_down(cx.listener(move |this, event: &KeyDownEvent, window, cx| {
2039 cycle_on_key_down(Surface::Dock)(this, event, window, cx)
2040 }))
2041 // Right-click anywhere the rows are not: the ways *in* (Add files,
2042 // Paste path, Import subtitles), which is what the dock itself can be
2043 // told -- and the door those last two kept when their rows left the
2044 // footer. A row's own right-click stops here first (`source_row`).
2045 .on_mouse_down(MouseButton::Right, opens_dock_menu(cx))
2046 // The focus ring is not painted (user 2026-09-09: "clicking through
2047 // timeline draws a white overlay around the timeline, same happens
2048 // for library section too"). The border stays in flow, transparent in
2049 // every state, so keyboard focus still moves and nothing shifts.
2050 .border_1()
2051 .border_color(gpui::transparent_black())
2052 .flex_1()
2053 .min_h(px(0.))
2054 .flex()
2055 .flex_col()
2056 .gap(px(8.))
2057 .px(px(12.))
2058 .pt(px(8.))
2059 .child({
2060 let t = tokens();
2061 let editing = player.dock_filter_edit;
2062 let has_text = !player.dock_filter.is_empty();
2063 // REDESIGN §3.8 row 36: search field, list/grid toggle, import.
2064 div()
2065 .flex_none()
2066 .flex()
2067 .items_center()
2068 .gap(px(8.))
2069 .child(
2070 div()
2071 .id("dock-filter")
2072 .flex_1()
2073 .min_w(px(0.))
2074 .cursor_text()
2075 // A box, not a bare glass: the `e2` fill says "type
2076 // here"; the border (always in flow) lights to the
2077 // accent while typing, so focusing shifts nothing.
2078 .h(px(r::CONTROL_M))
2079 .px(px(8.))
2080 .flex()
2081 .items_center()
2082 .gap(px(6.))
2083 .rounded(px(r::R_CONTROL))
2084 .border_1()
2085 .border_color(if editing { rgb(t.accent).into() } else { gpui::transparent_black() })
2086 .bg(rgb(t.e2))
2087 .type_style(type_scale::body())
2088 .text_color(rgb(if editing || has_text { t.ink1 } else { t.ink3 }))
2089 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2090 this.dock_filter_edit = true;
2091 cx.notify();
2092 }))
2093 .tooltip(crate::ui::widgets::tip_hover(
2094 "Search media",
2095 "type to narrow",
2096 None,
2097 ))
2098 .children(hitmap::control("dock.filter", "Search media", true))
2099 .child(Icon::Search.el(IconSize::Inline, t.ink3))
2100 .child(
2101 div().flex_1().min_w(px(0.)).truncate().child(match has_text {
2102 false => SEARCH_PLACEHOLDER.to_string(),
2103 true => filter_text.to_string(),
2104 }),
2105 )
2106 .when(has_text, |d| {
2107 d.child(
2108 div()
2109 .id("dock-filter-clear")
2110 .flex_none()
2111 .size(px(20.))
2112 .flex()
2113 .items_center()
2114 .justify_center()
2115 .rounded(px(r::R_CLIP))
2116 .cursor_pointer()
2117 .hover(move |s| s.bg(rgb(t.e3)))
2118 .child(Icon::X.el(IconSize::Inline, t.ink2))
2119 .tooltip(crate::ui::widgets::tip_hover("Clear search", "Esc", None))
2120 .children(hitmap::control("dock.filter.clear", "Clear search", true))
2121 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2122 cx.stop_propagation();
2123 this.dock_filter.clear();
2124 cx.notify();
2125 })),
2126 )
2127 }),
2128 )
2129 .child(
2130 Button::new("dock-sort")
2131 .icon(Icon::SlidersHorizontal)
2132 .style(if SORT.get() != 1 || kind != 0 { ButtonStyle::Secondary } else { ButtonStyle::Ghost })
2133 .build()
2134 .tooltip(crate::ui::widgets::tip_hover("Sort and show", "by name, date or length; video, audio or images", None))
2135 .children(hitmap::control("dock.sort", "Sort and show", true))
2136 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2137 // The press that closed the list (it fires outside the list) is not a second
2138 // press on the button.
2139 let just_closed = SORT_CLOSED.get().is_some_and(|at| at.elapsed().as_millis() < 300);
2140 SORT_OPEN.set(!SORT_OPEN.get() && !just_closed);
2141 this.dock_filter_edit = false;
2142 cx.notify();
2143 })),
2144 )
2145 .child(
2146 Button::new("dock-import-plus")
2147 .icon(Icon::Plus)
2148 .style(ButtonStyle::Ghost)
2149 .build()
2150 .relative()
2151 .child(crate::ui::anchor::probe("dock-add-anchor"))
2152 .tooltip(crate::ui::widgets::tip_hover("Import media or add a bin", "", None))
2153 .children(hitmap::control("dock.add", "Import media or add a bin", true))
2154 // The ways in and the new bin: the dock's own menu, under the button.
2155 .on_click(cx.listener(|this, event: &ClickEvent, _, cx| {
2156 if this.modal() || this.session.is_none() {
2157 this.pick_and_import(cx);
2158 return;
2159 }
2160 // Under the button, its right edge on the dock's (the placer keeps it
2161 // inside the window, and flips it above when there is no room below).
2162 let at = crate::ui::anchor::control_at(event.position()).map_or(event.position(), |b| {
2163 point(b.origin.x + b.size.width, b.origin.y + b.size.height + px(2.))
2164 });
2165 this.context_menu = Some(ContextMenu {
2166 lane: Lane::V1,
2167 on: MenuOn::Dock,
2168 at,
2169 details: false,
2170 sub: Sub::Closed,
2171 });
2172 cx.notify();
2173 })),
2174 )
2175 })
2176 .child(
2177 // The second row: which media to list, and how.
2178 div()
2179 .flex_none()
2180 .flex()
2181 .items_center()
2182 .justify_between()
2183 .child(
2184 div()
2185 .id("dock-which")
2186 .flex_none()
2187 .tooltip(crate::ui::widgets::tip_hover("Show all media or favourites only", "", None))
2188 .child(kit::segmented(
2189 "dock-which-seg",
2190 &[Segment::text("All"), Segment::text("Favourites")],
2191 usize::from(favs_only),
2192 true,
2193 None,
2194 {
2195 let me = cx.entity();
2196 move |pick, _, cx| {
2197 set_fav_only(pick == 1);
2198 me.update(cx, |_, cx| cx.notify());
2199 }
2200 },
2201 )),
2202 )
2203 .child(
2204 div()
2205 .id("dock-view")
2206 .flex_none()
2207 .tooltip(crate::ui::widgets::tip_hover("List or grid", "", None))
2208 .child(kit::segmented(
2209 "dock-view-seg",
2210 &[Segment::text("List"), Segment::text("Grid")],
2211 usize::from(grid),
2212 true,
2213 None,
2214 {
2215 let me = cx.entity();
2216 move |pick, _, cx| {
2217 set_grid_view(pick == 1);
2218 me.update(cx, |_, cx| cx.notify());
2219 }
2220 },
2221 )),
2222 ),
2223 )
2224 .children(banner)
2225 .child(
2226 div().relative().flex_1().min_h(px(0.)).flex().flex_col().child(
2227 div()
2228 .id("dock-source-rows")
2229 .flex_1()
2230 .min_h(px(0.))
2231 .flex()
2232 .flex_col()
2233 .gap(px(2.))
2234 .overflow_y_scroll()
2235 .track_scroll(&LIST_SCROLL.with(Clone::clone))
2236 // The list fills the dock, so the empty stretch under the last
2237 // row is *this* element and not its parent: the menu opens off
2238 // both, or a right-click below the rows finds nothing.
2239 .on_mouse_down(MouseButton::Right, opens_dock_menu(cx))
2240 .when(row_elements.is_empty(), |d| {
2241 let library_empty = sources.is_empty() && player.dock_filter.is_empty();
2242 d.child(empty_state(player, library_empty, favs_only, kind, cx))
2243 })
2244 .children(row_elements),
2245 )
2246 .child(crate::ui::widgets::more_below(LIST_SCROLL.with(Clone::clone))),
2247 )
2248 // One door in, pinned at the bottom (REDESIGN §3.8): a real secondary
2249 // button, always drawn. `Paste path` (`^l`) and `Import subtitles`
2250 // (`^i`) keep their strokes and the dock's right-click menu; `Add
2251 // files` takes a `.srt`/`.vtt` as happily as an `.mkv`.
2252 .child(
2253 div()
2254 .flex_none()
2255 .flex()
2256 .items_center()
2257 .py(px(12.))
2258 .children(import_button(player, cx)),
2259 )
2260 .children(sort_list)
2261}
2262
2263/// The list's empty face, one for every reason it can be empty: an icon, one plain line, and the
2264/// one thing that gets out of it.
2265fn empty_state(player: &Player, library_empty: bool, favs_only: bool, kind: usize, cx: &mut Context<Player>) -> impl IntoElement {
2266 let t = tokens();
2267 let typing = !player.dock_filter.is_empty();
2268 let (icon, text, id, action): (Icon, String, &'static str, &'static str) = if library_empty {
2269 (Icon::Film, EMPTY_LIBRARY_HINT.to_string(), "dock-empty-import", "Import media\u{2026}")
2270 } else if favs_only && !typing && kind == 0 {
2271 (Icon::Star, "No favourites yet. Star a file and it waits here.".to_string(), "dock-empty-all", "Show all media")
2272 } else if !typing && kind != 0 {
2273 (Icon::Film, format!("No {} in this project.", KINDS[kind].to_lowercase()), "dock-empty-types", "Show all types")
2274 } else {
2275 (Icon::Search, "Nothing matches.".to_string(), "dock-empty-clear", "Clear search")
2276 };
2277 div()
2278 .id("dock-empty")
2279 .flex_none()
2280 .flex()
2281 .flex_col()
2282 .items_center()
2283 .gap(px(10.))
2284 .px(px(12.))
2285 .py(px(28.))
2286 .child(icon.el(IconSize::Hero, t.ink3))
2287 .child(div().text_center().type_style(type_scale::body()).text_color(rgb(t.ink2)).child(text))
2288 .child(
2289 Button::new(id)
2290 .label(action)
2291 .style(ButtonStyle::Secondary)
2292 .size(ButtonSize::Small)
2293 .build()
2294 .tooltip(crate::ui::widgets::tip_hover(action, "", None))
2295 .children(hitmap::control(id, action, true))
2296 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2297 match id {
2298 "dock-empty-import" => this.pick_and_import(cx),
2299 "dock-empty-all" => set_fav_only(false),
2300 "dock-empty-types" => KIND.set(0),
2301 _ => {
2302 this.dock_filter.clear();
2303 KIND.set(0);
2304 }
2305 }
2306 cx.notify();
2307 })),
2308 )
2309}
2310
2311/// The footer's `Import media…` button: secondary, full width, the chord only
2312/// in its tooltip; dimmed with the reason when the room refuses an import.
2313fn import_button(player: &Player, cx: &mut Context<Player>) -> Option<impl IntoElement> {
2314 let action = ActionId::AddFiles;
2315 let enabled = player.enable(action, None);
2316 if !enabled.listed() {
2317 return None;
2318 }
2319 let on = enabled.yes();
2320 Some(
2321 div().flex_1().child(
2322 Button::new("dock-import-files")
2323 .label("Import media…")
2324 .icon(Icon::Download)
2325 .style(ButtonStyle::Secondary)
2326 .size(ButtonSize::Large)
2327 .enabled(on)
2328 .build()
2329 .w_full()
2330 .tooltip(crate::ui::widgets::action_hover(player, action))
2331 .children(hitmap::action(action, on))
2332 .when(on, |d| d.on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.pick_and_import(cx)))),
2333 ),
2334 )
2335}
2336
2337/// The transition a clip carries into its immediate successor, if any -- a
2338/// dissolve on a video lane ([`Clip::transition_out`]) or a crossfade on an
2339/// audio lane, told apart from a plain one-sided fade drag by
2340/// [`Project::crossfade`]'s own signature: both ends of the join set
2341/// together, not just this clip's tail. `cap` is what the pair actually
2342/// offers -- the shorter of the two clips' own lengths -- the same ceiling
2343/// [`Project::set_transition_out`]/[`Project::crossfade`] clamp to, so the
2344/// row this feeds never claims more room than a step could land in.
2345pub(crate) fn transition_of(
2346 lane_kind: LaneKind,
2347 clip: &Clip,
2348 next: Option<&Clip>,
2349) -> Option<(&'static str, u32, u32)> {
2350 let next = next.filter(|n| n.start == clip.end())?;
2351 let cap = clip.frames().min(next.frames());
2352 match lane_kind {
2353 LaneKind::Video if clip.transition_out > 0 => {
2354 Some((clip.transition_kind.title(), clip.transition_out, cap))
2355 }
2356 LaneKind::Audio if clip.fade_out > 0 && next.fade_in > 0 => {
2357 Some(("Crossfade", clip.fade_out, cap))
2358 }
2359 _ => None,
2360 }
2361}
2362
2363/// The transition block under the Clip tab's verbs, for the join the anchor
2364/// makes with its right-hand neighbour. On a video lane it always shows, so
2365/// the kind can be picked before there is a transition: `None` clears it, a
2366/// shape sets it (a fresh one is a second long), a moving shape takes its
2367/// direction, and a transition that exists shows its length. A crossfade on an
2368/// audio lane shows its length only ([`transition_of`]). Every control writes
2369/// through the same doors as the palette ([`Player::set_transition_kind`],
2370/// [`Player::set_transition_frames`]).
2371/// The Transition section's rows: Kind, its one-line description, Direction, Length,
2372/// and the cap, on one grid (a label column, then the control column). Every row is
2373/// always there, so switching kinds moves nothing: a row that does not apply to the
2374/// kind is shown dimmed, with the reason as its tooltip. Returns the section's title
2375/// and its rows; `None` when the clip has no neighbour to join.
2376fn transition_rows(player: &Player, cx: &mut Context<Player>) -> Option<(&'static str, gpui::Stateful<gpui::Div>)> {
2377 use engine::transitions::{Dir, TransitionKind};
2378 let (lane, idx) = player.selected.anchor()?;
2379 let session = player.session.as_ref()?;
2380 let clips = session.lane_clips(lane);
2381 let clip = clips.get(idx)?;
2382 let next = clips.get(idx + 1);
2383 let (frames, cap) = match lane.kind {
2384 LaneKind::Video => {
2385 let next = next.filter(|n| n.start == clip.end())?;
2386 (clip.transition_out, clip.frames().min(next.frames()))
2387 }
2388 _ => {
2389 let (_, frames, cap) = transition_of(lane.kind, clip, next)?;
2390 (frames, cap)
2391 }
2392 };
2393 let fps = player.fps.max(1.);
2394 let seconds = |f: u32| f64::from(f) / fps;
2395 let title = match lane.kind {
2396 LaneKind::Video => "Transition",
2397 _ => "Crossfade",
2398 };
2399 let current = clip.transition_kind;
2400 let me = cx.entity();
2401 // One row: a label column of the same width everywhere, then the control.
2402 let row = |id: &'static str, name: &'static str, control: gpui::AnyElement| {
2403 div()
2404 .id(id)
2405 .flex_none()
2406 .flex()
2407 .items_center()
2408 .gap(px(8.))
2409 .h(px(r::CONTROL_M))
2410 .px(px(6.))
2411 .child(div().flex_none().w(px(112.)).type_style(type_scale::body()).text_color(rgb(INK2())).child(name))
2412 .child(control)
2413 };
2414 let mut block = div().id("dock-transition").flex().flex_col().gap(px(4.));
2415 if lane.kind == LaneKind::Video {
2416 // The kind row: None, then the seven shapes. A dip's colour and a
2417 // moving shape's direction are their own rows, so a shape is one pick.
2418 let dir = current.dir().unwrap_or(Dir::Left);
2419 let shapes = [
2420 TransitionKind::Dissolve,
2421 TransitionKind::DipBlack,
2422 TransitionKind::DipWhite,
2423 TransitionKind::Wipe(dir),
2424 TransitionKind::Slide(dir),
2425 TransitionKind::Push(dir),
2426 TransitionKind::Zoom,
2427 ];
2428 // One list row per kind, each with a plain line of what it does. None
2429 // first: it removes the transition.
2430 const KINDS: [(&str, &str); 8] = [
2431 ("None", "No transition: a straight cut"),
2432 ("Dissolve", "Fades one clip into the next"),
2433 ("Dip black", "Fades out to black, then in"),
2434 ("Dip white", "Fades out to white, then in"),
2435 ("Wipe", "A line reveals the next clip"),
2436 ("Slide", "The next clip slides over"),
2437 ("Push", "Next clip pushes the old out"),
2438 ("Zoom", "Old clip zooms into the next"),
2439 ];
2440 let at = match frames {
2441 0 => 0,
2442 _ => 1 + shapes.iter().position(|k| k.shape_name() == current.shape_name()).unwrap_or(0),
2443 };
2444 let pick = move |this: &mut Player, i: usize, cx: &mut Context<Player>| {
2445 this.transition_kind_open = false;
2446 match i {
2447 0 => this.set_transition_frames(lane, idx, 0, cx),
2448 n => this.set_transition_kind(shapes[n - 1], cx),
2449 }
2450 };
2451 let open = player.transition_kind_open;
2452 let field = kit::dropdown_field("transition-kind", KINDS[at].0, true).on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2453 this.transition_kind_open = !this.transition_kind_open;
2454 cx.notify();
2455 }));
2456 let list = open.then(|| {
2457 let t = crate::ui::theme::tokens();
2458 let backdrop = div().absolute().top(px(-4000.)).left(px(-4000.)).size(px(8000.)).on_mouse_down(
2459 MouseButton::Left,
2460 cx.listener(|this, _: &MouseDownEvent, _, cx| {
2461 this.transition_kind_open = false;
2462 cx.stop_propagation();
2463 cx.notify();
2464 }),
2465 );
2466 // One line a kind: its name, then what it does. Eight of them fit under the
2467 // field on a 720-line window, so the list never runs off the bottom.
2468 let mut plate = kit::plate(6.).id("transition-kind-list").w(px(360.)).p(px(crate::layout::MENU_PAD)).flex().flex_col().occlude();
2469 for (i, &(name, why)) in KINDS.iter().enumerate() {
2470 plate = plate.child(
2471 div()
2472 .id(("transition-kind-row", i))
2473 .flex_none()
2474 .h(px(crate::layout::MENU_ROW_H))
2475 .px(px(8.))
2476 .flex()
2477 .items_center()
2478 .gap(px(8.))
2479 .rounded(px(4.))
2480 .cursor_pointer()
2481 .hover(|s| s.bg(rgba(crate::ui::theme::WASH_HOVER)))
2482 .child(div().flex_none().size(px(16.)).children((i == at).then(|| Icon::Check.el(IconSize::Inline, t.accent))))
2483 .child(div().flex_none().w(px(84.)).whitespace_nowrap().type_style(type_scale::body_strong()).text_color(rgb(t.ink1)).child(name))
2484 .child(div().flex_1().min_w(px(0.)).whitespace_nowrap().overflow_hidden().type_style(label(type_scale::LABEL_ROW_PX, FontWeight::NORMAL)).text_color(rgb(INK3())).child(why))
2485 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| pick(this, i, cx))),
2486 );
2487 }
2488 gpui::deferred(
2489 div()
2490 .absolute()
2491 .top(px(0.))
2492 .right(px(0.))
2493 .child(backdrop)
2494 .child(div().absolute().top(px(r::CONTROL_M + 2.)).right(px(0.)).child(plate)),
2495 )
2496 });
2497 block = block.child(row(
2498 "dock-transition-kind",
2499 "Kind",
2500 div().relative().flex_none().w(px(150.)).child(field).children(list).into_any_element(),
2501 ));
2502 // The kind's line sits right under its row, quiet, one line.
2503 block = block.child(
2504 div()
2505 .h(px(20.))
2506 .px(px(6.))
2507 .whitespace_nowrap()
2508 .overflow_hidden()
2509 .type_style(label(type_scale::LABEL_ROW_PX, FontWeight::NORMAL))
2510 .text_color(rgb(INK3()))
2511 .child(KINDS[at].1),
2512 );
2513 // Direction: the four sides for a moving shape; dimmed with the reason otherwise.
2514 let dir_on = frames > 0 && current.dir().is_some();
2515 let dirs = [Dir::Left, Dir::Right, Dir::Up, Dir::Down];
2516 let dir_at = dirs.iter().position(|&d| Some(d) == current.dir()).unwrap_or(usize::MAX);
2517 let me_dir = me.clone();
2518 let pick_dir = move |i: usize, _: &mut Window, app: &mut App| {
2519 me_dir.update(app, |this, cx| this.set_transition_kind(current.with_dir(dirs[i]), cx));
2520 };
2521 let dir_row = row(
2522 "dock-transition-direction",
2523 "Direction",
2524 div()
2525 .flex_none()
2526 .w(px(150.))
2527 .child(kit::segmented_equal(
2528 "transition-dirs",
2529 &["Left", "Right", "Up", "Down"].map(Segment::text),
2530 dir_at,
2531 dir_on,
2532 None,
2533 pick_dir,
2534 ))
2535 .into_any_element(),
2536 );
2537 block = block.child(match dir_on {
2538 true => dir_row,
2539 false => dir_row.tooltip(crate::ui::widgets::tip_hover("Direction", "", Some("Only for wipe, slide and push"))),
2540 });
2541 }
2542 let style = label(type_scale::LABEL_ROW_PX, FontWeight::NORMAL);
2543 let shown = format!("{:.1}", seconds(frames));
2544 let editing = player.transition_edit.as_ref();
2545 // The length is typed only once a kind is picked; before that it reads 0.0 s, dimmed.
2546 let len_on = frames > 0;
2547 let length = kit::number_field("transition-duration-field", 150., shown, Some("s"), editing, len_on);
2548 let length = match len_on {
2549 true => length
2550 .tooltip(crate::ui::widgets::tip_hover("Transition length", "click to type", None))
2551 .children(hitmap::control("transition-duration-field", "Transition length, type-in", true))
2552 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2553 if this.transition_edit.is_none() {
2554 this.edit_transition(frames);
2555 }
2556 cx.notify();
2557 }))
2558 .into_any_element(),
2559 false => length.into_any_element(),
2560 };
2561 let length_row = row("dock-transition-length", "Length", div().flex_none().child(length).into_any_element());
2562 block = block.child(match len_on {
2563 true => length_row,
2564 false => length_row.tooltip(crate::ui::widgets::tip_hover("Length", "", Some("Pick a kind to set its length"))),
2565 });
2566 // The cap sits under the box, on the control column.
2567 block = block.child(
2568 div()
2569 .h(px(20.))
2570 .pl(px(126.))
2571 .whitespace_nowrap()
2572 .type_style(style)
2573 .text_color(rgb(INK3()))
2574 .child(format!("up to {:.1} s", seconds(cap))),
2575 );
2576 Some((title, block))
2577}
2578
2579/// The Transition section in the Clip tab: a head like Speed or Colour (icon,
2580/// chevron, name), folding its rows open and shut. Only for a clip with a neighbour.
2581fn transition_section(player: &Player, cx: &mut Context<Player>) -> Option<AnyElement> {
2582 let (title, rows) = transition_rows(player, cx)?;
2583 let open = player.transition_section_open;
2584 let t = tokens();
2585 let ink = if open { t.ink1 } else { t.ink2 };
2586 let head = div()
2587 .id("dock-verb-transition")
2588 .flex_none()
2589 .h(px(r::CONTROL_L))
2590 .px(px(12.))
2591 .flex()
2592 .items_center()
2593 .gap(px(8.))
2594 .border_t_1()
2595 .border_color(rgba(t.line))
2596 .when(open, |d| d.bg(rgb(t.e2)))
2597 .cursor_pointer()
2598 .hover(move |s| s.bg(rgb(t.e2)))
2599 .tooltip(crate::ui::widgets::tip_hover(title, "", None))
2600 .children(hitmap::control("dock-verb-transition", title, true))
2601 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2602 this.transition_section_open = !this.transition_section_open;
2603 cx.notify();
2604 }))
2605 .child(if open { Icon::ChevronDown } else { Icon::ChevronRight }.el_px(px(12.), t.ink3))
2606 .child(Icon::Layers.el(IconSize::Inline, ink))
2607 .child(div().type_style(type_scale::section()).text_color(rgb(ink)).child(title));
2608 Some(
2609 div()
2610 .id("dock-transition-section")
2611 .flex_none()
2612 .flex()
2613 .flex_col()
2614 .child(head)
2615 .children(open.then(|| div().id("dock-transition-body").flex_none().px(px(12.)).pb(px(12.)).child(rows)))
2616 .into_any_element(),
2617 )
2618}
2619
2620/// The Clip tab: the four verbs DESIGN §5 names, as ghosts, over whichever
2621/// param-row card they open -- [`Player::eq_card`], [`Player::color_card`],
2622/// [`Player::transform_card`], [`Player::speed_card`] verbatim, the same
2623/// param-row rendering `inspector.rs`'s selection section already opens
2624/// these onto. Drag-while-playing and every other gesture on a row is
2625/// whatever that card already does; nothing about the gesture is reimplemented
2626/// here.
2627fn viz_style_verbs(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
2628 let clip = player.selected.anchor().and_then(|(lane, idx)| {
2629 let session = player.session.as_ref()?;
2630 let clip = session.lane_clips(lane).get(idx)?;
2631 (clip.visualizer & 1 != 0).then_some(clip.clone())
2632 });
2633 let Some(clip) = clip else {
2634 return div().id("dock-viz-styles");
2635 };
2636 let flags = clip.visualizer;
2637 // The ink the wheel draws is the one a drag is holding, when one is: the
2638 // clip still carries the sample before it until the worker lands the
2639 // holding frame (`viz_held_paint`).
2640 let paint = viz_held_paint(clip.viz_paint, player.pending_viz);
2641 let pick = |id: &'static str, label_text: &'static str, style: u8, on: bool| {
2642 let row = label(type_scale::LABEL_ROW_PX, FontWeight::MEDIUM);
2643 div()
2644 .id(id)
2645 .flex_none()
2646 .h(px(CONTROL_H))
2647 .px(px(8.))
2648 .flex()
2649 .items_center()
2650 .cursor_pointer()
2651 .text_color(rgb(if on { INK1() } else { INK3() }))
2652 .font(row.font)
2653 .text_size(row.size)
2654 .tooltip(crate::ui::widgets::tip_hover(label_text, "", None))
2655 .children(hitmap::control(id, label_text, true))
2656 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2657 this.set_viz_style(style, cx);
2658 }))
2659 .child(if on {
2660 format!("· {label_text}")
2661 } else {
2662 label_text.to_string()
2663 })
2664 .into_any_element()
2665 };
2666 let bit = |id: &'static str, label_text: &'static str, bit: u8, on: bool| {
2667 let style = label(type_scale::LABEL_ROW_PX, FontWeight::MEDIUM);
2668 div()
2669 .id(id)
2670 .flex_none()
2671 .h(px(CONTROL_H))
2672 .px(px(8.))
2673 .flex()
2674 .items_center()
2675 .cursor_pointer()
2676 .text_color(rgb(if on { INK1() } else { INK3() }))
2677 .font(style.font.clone())
2678 .text_size(style.size)
2679 .tooltip(crate::ui::widgets::tip_hover(label_text, "", None))
2680 .children(hitmap::control(id, label_text, true))
2681 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2682 this.toggle_viz_flag(bit, cx);
2683 }))
2684 .child(if on {
2685 format!("· {label_text}")
2686 } else {
2687 label_text.to_string()
2688 })
2689 .into_any_element()
2690 };
2691 div()
2692 .id("dock-viz-styles")
2693 .flex_none()
2694 .flex()
2695 .flex_col()
2696 .gap(px(2.))
2697 .child(
2698 div()
2699 .flex_none()
2700 .pt(px(4.))
2701 .px(px(8.))
2702 .child(section_head("VISUALIZER")),
2703 )
2704 .child(pick(
2705 "dock-viz-fill",
2706 "Fill",
2707 engine::decode::VIZ_STYLE_FILL,
2708 engine::decode::viz_style(flags) == engine::decode::VIZ_STYLE_FILL,
2709 ))
2710 .child(pick(
2711 "dock-viz-ribbon",
2712 "Ribbon",
2713 engine::decode::VIZ_STYLE_RIBBON,
2714 engine::decode::viz_style(flags) == engine::decode::VIZ_STYLE_RIBBON,
2715 ))
2716 .child(pick(
2717 "dock-viz-ring",
2718 "Ring",
2719 engine::decode::VIZ_STYLE_RING,
2720 engine::decode::viz_style(flags) == engine::decode::VIZ_STYLE_RING,
2721 ))
2722 .child(pick(
2723 "dock-viz-wave",
2724 "Waveform",
2725 engine::decode::VIZ_STYLE_WAVE,
2726 engine::decode::viz_style(flags) == engine::decode::VIZ_STYLE_WAVE,
2727 ))
2728 .child(bit(
2729 "dock-viz-fast",
2730 "Fast",
2731 engine::decode::VIZ_FAST,
2732 flags & engine::decode::VIZ_FAST != 0,
2733 ))
2734 .child(viz_paint_knobs(player, paint, cx))
2735}
2736
2737/// Which of the clip's two inks the wheel and the colour field are on. The
2738/// picked chip wears the solid ink and the other the quiet one -- the style
2739/// chips' own shape (`viz_style_verbs`'s `pick`, one row up the same column).
2740///
2741/// The Strand chip is dead while the clip has one strand: a strand colour is
2742/// painted on the ring's *dual* half and a one-strand ring has none, so the
2743/// chip would be wired to nothing -- and it says so on hover rather than doing
2744/// nothing in silence (`widgets::control`'s own rule for a button with no
2745/// action).
2746fn viz_slot_chips(player: &Player, paint: u64, cx: &mut Context<Player>) -> impl IntoElement {
2747 let picked = player.viz_slot.picked(paint);
2748 let strand_live = engine::decode::viz_strands_of(paint) >= 2;
2749 let chip = |id: &'static str, label_text: &'static str, slot: VizSlot, live: bool| {
2750 let row = label(type_scale::LABEL_ROW_PX, FontWeight::MEDIUM);
2751 let on = picked == slot;
2752 div()
2753 .id(id)
2754 .flex_none()
2755 .h(px(CONTROL_H))
2756 .px(px(8.))
2757 .flex()
2758 .items_center()
2759 .font(row.font)
2760 .text_size(row.size)
2761 .text_color(rgb(if on { INK1() } else { INK3() }))
2762 .tooltip(crate::ui::widgets::tip_hover(
2763 label_text,
2764 "",
2765 match live {
2766 true => None,
2767 false => Some("needs two strands"),
2768 },
2769 ))
2770 .children(hitmap::control(id, label_text, live))
2771 .when(!live, |d| d.opacity(0.4).cursor_not_allowed())
2772 .when(live, |d| {
2773 d.cursor_pointer()
2774 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2775 this.set_viz_slot(slot, cx);
2776 }))
2777 })
2778 .child(label_text.to_string())
2779 .into_any_element()
2780 };
2781 div()
2782 .id("dock-viz-slots")
2783 .flex()
2784 .items_center()
2785 .child(chip("dock-viz-colour", "Colour", VizSlot::Main, true))
2786 .child(chip(
2787 "dock-viz-strand",
2788 "Strand",
2789 VizSlot::Strand,
2790 strand_live,
2791 ))
2792}
2793
2794/// The picked slot's colour as text, and the way in: a click opens the type-in
2795/// seeded with exactly what the row is showing
2796/// ([`Player::edit_viz_hex`]). While the field is open the row is the buffer
2797/// and its refusal instead -- `transition_row`'s own rule for its own field.
2798fn viz_hex_row(player: &Player, paint: u64, cx: &mut Context<Player>) -> impl IntoElement {
2799 let (hue, sat) = player.viz_slot.picked(paint).hue_sat(paint);
2800 let hex = engine::decode::viz_color_hex(hue, sat);
2801 // The seed the click opens on is the line the row is showing, so a click
2802 // that lands while the field is open cannot seed it with something else.
2803 let seed = hex.clone();
2804 let field = player.viz_hex_edit.as_ref();
2805 let row = label(type_scale::LABEL_ROW_PX, FontWeight::MEDIUM);
2806 div()
2807 .id("dock-viz-hex-field")
2808 .h(px(CONTROL_H))
2809 .flex()
2810 .items_center()
2811 .font(row.font)
2812 .text_size(row.size)
2813 .text_color(rgb(INK2()))
2814 .cursor_pointer()
2815 .tooltip(crate::ui::widgets::tip_hover(
2816 "Colour",
2817 "click to type",
2818 None,
2819 ))
2820 .children(hitmap::control(
2821 "dock-viz-hex-field",
2822 "Colour hex, type-in",
2823 true,
2824 ))
2825 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2826 this.edit_viz_hex(&seed);
2827 cx.notify();
2828 }))
2829 .child(match field {
2830 Some(edit) => edit.detail(),
2831 None => hex,
2832 })
2833}
2834
2835fn viz_color_wheel(player: &Player, paint: u64, cx: &mut Context<Player>) -> impl IntoElement {
2836 // What the mark is on, read out here because the canvas closure paints and
2837 // so cannot borrow the player: the picked slot's ink
2838 // ([`VizSlot::hue_sat`]) -- the clip's own colour, or, for a strand the
2839 // clip has not chosen, the automatic complement, so the hand starts where
2840 // the picture already is.
2841 let (mark_hue, mark_sat) = player.viz_slot.picked(paint).hue_sat(paint);
2842 div()
2843 .id("dock-viz-hs")
2844 .w(px(112.))
2845 .h(px(112.))
2846 .relative()
2847 .cursor_pointer()
2848 .tooltip(crate::ui::widgets::tip_hover(
2849 "Colour wheel",
2850 "drag to pick",
2851 None,
2852 ))
2853 .children(hitmap::control("dock-viz-hs", "Colour wheel", true))
2854 .child(bounds_probe(player.viz_wheel.clone()))
2855 .child(
2856 canvas(
2857 |_, _, _| (),
2858 move |bounds, _, window, _| {
2859 let o = bounds.origin;
2860 let (w, h) = (f32::from(bounds.size.width), f32::from(bounds.size.height));
2861 let cx = f32::from(o.x) + w / 2.;
2862 let cy = f32::from(o.y) + h / 2.;
2863 let radius = w.min(h) / 2. - 1.;
2864 let wedges = 72;
2865 let rings = 10;
2866 for ring in 0..rings {
2867 let s0 = ring as f32 / rings as f32;
2868 let s1 = (ring + 1) as f32 / rings as f32;
2869 let sat = (s0 + s1) / 2.;
2870 for i in 0..wedges {
2871 let a0 = (i as f32 / wedges as f32) * std::f32::consts::TAU;
2872 let a1 = ((i + 1) as f32 / wedges as f32) * std::f32::consts::TAU;
2873 let hue = i as f32 / wedges as f32 * 360.;
2874 let (r, g, b) = engine::decode::viz_hsv_rgb(hue, sat, 0.84);
2875 let color = (u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b);
2876 let p00 = point(
2877 px(cx + radius * s0 * a0.sin()),
2878 px(cy - radius * s0 * a0.cos()),
2879 );
2880 let p01 = point(
2881 px(cx + radius * s0 * a1.sin()),
2882 px(cy - radius * s0 * a1.cos()),
2883 );
2884 let p11 = point(
2885 px(cx + radius * s1 * a1.sin()),
2886 px(cy - radius * s1 * a1.cos()),
2887 );
2888 let p10 = point(
2889 px(cx + radius * s1 * a0.sin()),
2890 px(cy - radius * s1 * a0.cos()),
2891 );
2892 let mut path = PathBuilder::fill();
2893 path.add_polygon(&[p00, p01, p11, p10], false);
2894 if let Ok(path) = path.build() {
2895 window.paint_path(path, rgb(color));
2896 }
2897 }
2898 }
2899 // Selection mark.
2900 let hue = f32::from(mark_hue) / 256. * std::f32::consts::TAU;
2901 let sat = f32::from(mark_sat) / 255.;
2902 let mx = cx + radius * sat * hue.sin();
2903 let my = cy - radius * sat * hue.cos();
2904 let mut mark = PathBuilder::stroke(px(2.));
2905 let r = 4.;
2906 mark.add_polygon(
2907 &[
2908 point(px(mx - r), px(my)),
2909 point(px(mx), px(my - r)),
2910 point(px(mx + r), px(my)),
2911 point(px(mx), px(my + r)),
2912 ],
2913 true,
2914 );
2915 if let Ok(path) = mark.build() {
2916 window.paint_path(path, rgb(INK1()));
2917 }
2918 },
2919 )
2920 .size_full(),
2921 )
2922 .on_mouse_down(
2923 MouseButton::Left,
2924 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
2925 this.viz_hs_dragging = true;
2926 this.drag_viz_hs(event.position, true, cx);
2927 }),
2928 )
2929}
2930
2931fn viz_paint_knobs(player: &Player, paint: u64, cx: &mut Context<Player>) -> impl IntoElement {
2932 div()
2933 .flex()
2934 .flex_col()
2935 .gap(px(4.))
2936 .px(px(8.))
2937 .child(
2938 div()
2939 .id("dock-viz-wheel")
2940 .flex()
2941 .flex_col()
2942 .gap(px(4.))
2943 .child(viz_slot_chips(player, paint, cx))
2944 .child(viz_color_wheel(player, paint, cx))
2945 .child(viz_hex_row(player, paint, cx)),
2946 )
2947 .child(viz_strands_slider(paint, cx))
2948 .child(viz_glow_slider(paint, cx))
2949}
2950
2951/// The strand count a slider share lands on: 1 at the left end, 32 at the
2952/// right, one count per step.
2953pub(crate) fn viz_strands_at(along: f32) -> u8 {
2954 1 + (along.clamp(0., 1.) * 31.).round() as u8
2955}
2956
2957/// The glow a slider share lands on: 0 at the left end, 16 at the right.
2958pub(crate) fn viz_glow_at(along: f32) -> u8 {
2959 (along.clamp(0., 1.) * 16.).round() as u8
2960}
2961
2962/// The strands slider, 1 to 32 (the engine's own clamp). A press sets the
2963/// count on the spot and the picture follows; the reset goes back to the
2964/// azure default's count.
2965fn viz_strands_slider(paint: u64, cx: &mut Context<Player>) -> impl IntoElement {
2966 let strands = engine::decode::viz_strands_of(paint);
2967 let default = engine::decode::viz_strands_of(engine::decode::VIZ_PAINT_AZURE);
2968 // The probe and the press share this box: it is recorded at paint and read
2969 // by the press that the same paint's listener was built for.
2970 let bar = Rc::new(Cell::new(Bounds::default()));
2971 let press_bar = bar.clone();
2972 let reset: SliderReset<Player> = Rc::new(move |this: &mut Player, cx: &mut Context<Player>| {
2973 this.set_viz_strands(default, cx);
2974 });
2975 div()
2976 .id("dock-viz-strands-field")
2977 .tooltip(crate::ui::widgets::tip_hover(
2978 "Strands",
2979 "",
2980 Some("Lines the visualizer draws, 1 to 32"),
2981 ))
2982 .child(slider_row(
2983 SliderRow {
2984 id: "dock-viz-strands",
2985 label: "Strands".into(),
2986 value: format!("{strands}").into(),
2987 fraction: slider_fraction(f32::from(strands), 1., 32.),
2988 changed: strands != default,
2989 bar,
2990 on_press: Box::new(
2991 move |this: &mut Player, x: Pixels, cx: &mut Context<Player>| {
2992 let along = frac_along(x, press_bar.get());
2993 this.set_viz_strands(viz_strands_at(along), cx);
2994 },
2995 ),
2996 on_reset: Some(reset),
2997 // Typed as the count the row shows, 1 to 32.
2998 typed: Some(SliderTyped {
2999 lo: 1.,
3000 hi: 32.,
3001 set: Rc::new(|this: &mut Player, v: f64, cx: &mut Context<Player>| {
3002 this.set_viz_strands(v.round() as u8, cx);
3003 }),
3004 }),
3005 },
3006 cx,
3007 ))
3008}
3009
3010/// The glow slider, 0 to 16 (the engine's own clamp). Same press and reset
3011/// rules as [`viz_strands_slider`].
3012fn viz_glow_slider(paint: u64, cx: &mut Context<Player>) -> impl IntoElement {
3013 let glow = engine::decode::viz_glow_of(paint);
3014 let default = engine::decode::viz_glow_of(engine::decode::VIZ_PAINT_AZURE);
3015 let bar = Rc::new(Cell::new(Bounds::default()));
3016 let press_bar = bar.clone();
3017 let reset: SliderReset<Player> = Rc::new(move |this: &mut Player, cx: &mut Context<Player>| {
3018 this.set_viz_glow(default, cx);
3019 });
3020 div()
3021 .id("dock-viz-glow-field")
3022 .tooltip(crate::ui::widgets::tip_hover(
3023 "Glow",
3024 "",
3025 Some("How strongly the picture glows, 0 to 16"),
3026 ))
3027 .child(slider_row(
3028 SliderRow {
3029 id: "dock-viz-glow",
3030 label: "Glow".into(),
3031 value: format!("{glow}").into(),
3032 fraction: slider_fraction(f32::from(glow), 0., 16.),
3033 changed: glow != default,
3034 bar,
3035 on_press: Box::new(
3036 move |this: &mut Player, x: Pixels, cx: &mut Context<Player>| {
3037 let along = frac_along(x, press_bar.get());
3038 this.set_viz_glow(viz_glow_at(along), cx);
3039 },
3040 ),
3041 on_reset: Some(reset),
3042 // Typed as the level the row shows, 0 to 16.
3043 typed: Some(SliderTyped {
3044 lo: 0.,
3045 hi: 16.,
3046 set: Rc::new(|this: &mut Player, v: f64, cx: &mut Context<Player>| {
3047 this.set_viz_glow(v.round() as u8, cx);
3048 }),
3049 }),
3050 },
3051 cx,
3052 ))
3053}
3054
3055fn clip_tab(
3056 player: &Player,
3057 width: f32,
3058 window_size: Size<Pixels>,
3059 _window: &mut Window,
3060 cx: &mut Context<Player>,
3061) -> impl IntoElement {
3062 // The room actually given here, not the window's: `eq_card_w`/
3063 // `card_max_w` are asked "how wide may I draw" and answered with the
3064 // *whole viewport's* width when handed `window_size` verbatim -- but this
3065 // tab is a ~280-390px strip inside the dock, not the window, so a card
3066 // capped at up to 720px overflowed past the window's own right edge.
3067 // Height stays the window's: none of the un-maximized cards' own
3068 // arithmetic uses it.
3069 let room = Size::new(px(width - 24.), window_size.height);
3070 let anchor = player.selected.anchor();
3071 let title_up = player.title_target().is_some();
3072 // A selected caption is not a clip either: the tab is its panel, then its style section.
3073 let cue_up = anchor.is_none() && !title_up && player.sel_cue_span().is_some();
3074 let empty = anchor.is_none() && !player.clip_card_open() && !title_up && !cue_up;
3075 // One inspector: a header for the clip, then a section head per card; the
3076 // open card sits right under its head (REDESIGN §3.9). The cards keep the
3077 // "one card up at a time" rule (`close_card`), so opening a section folds
3078 // the previous one; the heads and everything below them move, nothing
3079 // above does.
3080 let mut first = true;
3081 let mut head = |id: &'static str,
3082 title: &'static str,
3083 icon: Icon,
3084 action: ActionId,
3085 open: bool,
3086 on_click: fn(&mut Player, &ClickEvent, &mut Context<Player>)|
3087 -> Option<AnyElement> {
3088 let section = Section::ALL.into_iter().find(|s| s.action() == action);
3089 let changed = section.is_some_and(|s| player.section_changed(s));
3090 let el = section_verb(id, title, icon, action, open, !first, (section, changed), player, on_click, cx)?;
3091 first = false;
3092 Some(el.into_any_element())
3093 };
3094 let speed = head("dock-verb-speed", "Speed", Icon::Gauge, ActionId::Speed, player.speed_open.is_some(), |t, _, cx| t.open_speed(cx));
3095 let color = head("dock-verb-color", "Colour", Icon::Palette, ActionId::Color, player.color_open.is_some(), |t, _, cx| t.open_color(cx));
3096 let transform = head("dock-verb-transform", "Transform", Icon::Move, ActionId::Transform, player.transform_open.is_some(), |t, _, cx| t.open_transform(cx));
3097 let effects = head("dock-verb-effects", "Effects", Icon::Sparkles, ActionId::Effects, player.effects_open.is_some(), |t, _, cx| t.open_effects(cx));
3098 let eq = head("dock-verb-eq", "EQ", Icon::SlidersHorizontal, ActionId::Equalizer, player.eq_open.is_some(), |t, _, cx| t.open_eq(cx));
3099 let silence = head("dock-verb-silence", "Silence", Icon::VolumeX, ActionId::Silence, player.silence_open.is_some(), |t, _, cx| t.open_silence(cx));
3100 // Mark the beats: a sound clip's section, listed only where there is a sound to listen to.
3101 let beats = match player.beats_open.is_some() || player.beats_available() {
3102 true => head("dock-verb-beats", "Mark the beats", Icon::Timer, ActionId::MarkBeats, player.beats_open.is_some(), |t, _, cx| t.open_beats(cx)),
3103 false => None,
3104 };
3105 let mix = head("dock-verb-mix", "Mix", Icon::Volume2, ActionId::Mix, player.mix_open, |t, _, cx| t.open_mix(None, cx));
3106 let markers = head("dock-verb-markers", "Markers in this sequence", Icon::Flag, ActionId::Markers, player.markers_open, |t, _, cx| t.open_markers(cx));
3107 let history = head("dock-verb-history", "History", Icon::Undo2, ActionId::History, player.history_open, |t, _, cx| t.open_history(cx));
3108 // Tools: Normalize, Captions, Fillers and Voiceover in one card.
3109 let tools = head("dock-verb-tools", "Tools", Icon::Wrench, ActionId::Normalize, player.tools.is_some(), |t, _, cx| {
3110 t.open_tools(crate::player::tools::Tool::Normalize, cx)
3111 });
3112 // Subtitle style: the look of the cue plate, offered while a subtitle clip is selected.
3113 let on_subtitle = cue_up || anchor.is_some_and(|(lane, _)| !matches!(lane.kind, LaneKind::Video | LaneKind::Audio));
3114 let substyle = match on_subtitle {
3115 true => head("dock-verb-substyle", "Subtitle style", Icon::Captions, ActionId::SubtitleStyle, player.subtitle_style_open, |t, _, cx| {
3116 t.open_subtitle_style(cx)
3117 }),
3118 false => None,
3119 };
3120 // Fit: a list of four, not a card, so it never reads as open -- the click
3121 // opens the list (`overlays.rs`'s `Pick::Fit`, the one the clip's
3122 // right-click menu opens).
3123 let fit = head("dock-verb-fit", "Fit to frame", Icon::Scan, ActionId::Fit, false, |t, ev, cx| {
3124 t.open_fit_list(ev.position(), cx);
3125 if let Some(p) = &mut t.picker {
3126 p.floored = false;
3127 }
3128 });
3129 // The Transition section (video and audio joins alike), after the list of sections.
3130 let transition = transition_section(player, cx);
3131 let picked: PanelPick = (anchor, player.sel_cue, player.title_sel);
3132 if CLIP_PICKED.with(std::cell::Cell::get) != picked {
3133 CLIP_PICKED.with(|c| c.set(picked));
3134 CLIP_SCROLL.with(|s| s.set_offset(gpui::point(px(0.), px(0.))));
3135 }
3136 div()
3137 .id("dock-clip")
3138 .track_scroll(&CLIP_SCROLL.with(Clone::clone))
3139 .track_focus(&player.focus_inspector)
3140 .on_key_down(cx.listener(move |this, event: &KeyDownEvent, window, cx| {
3141 cycle_on_key_down(Surface::Inspector)(this, event, window, cx)
3142 }))
3143 // The focus ring is not painted (user 2026-09-09); the border stays in
3144 // flow, transparent in every state, so keyboard focus still moves and
3145 // nothing shifts.
3146 .border_1()
3147 .border_color(gpui::transparent_black())
3148 .flex_1()
3149 .min_h(px(0.))
3150 .flex()
3151 .flex_col()
3152 .overflow_y_scroll()
3153 .when(empty, |d| d.child(clip_hero()))
3154 // A title is not a clip: with one selected the tab is its section and nothing else.
3155 .when(title_up && anchor.is_none() && !player.clip_card_open(), |d| {
3156 d.children(title_header(player)).children(section_body(player.title_card(room, cx)))
3157 })
3158 .when(!empty && !(title_up && anchor.is_none() && !player.clip_card_open()), |d| {
3159 // A selected caption is its own panel and the Subtitle style section, nothing of a clip's.
3160 if cue_up {
3161 return d
3162 .children(player.caption_card(cx))
3163 .children(substyle)
3164 .children(section_body(player.subtitle_style_card(room, cx)));
3165 }
3166 d.children(clip_header(player))
3167 .children(section_body(player.generator_card(room, cx)))
3168 .children(speed)
3169 .children(section_body(player.speed_card(room, cx)))
3170 .children(color)
3171 .children(section_body(player.color_card(room, cx)))
3172 .children(transform)
3173 .children(section_body(player.transform_card(room, cx)))
3174 .children(effects)
3175 .children(section_body(player.effects_card(room, cx)))
3176 .children(eq)
3177 .children(section_body(player.eq_card(room, cx)))
3178 .children(silence)
3179 .children(section_body(player.silence_card(room, cx)))
3180 .children(beats)
3181 .children(section_body(player.beats_card(room, cx)))
3182 .children(mix)
3183 .children(section_body(player.mix_card(room, cx)))
3184 .children(markers)
3185 .children(section_body(player.markers_card(room, cx)))
3186 .children(history)
3187 .children(section_body(player.history_card(room, cx)))
3188 .children(tools)
3189 .children(section_body(player.tools_card(room, cx)))
3190 .children(fit)
3191 // The Transition section: its head joins the others, its rows fold under it.
3192 .children(transition)
3193 // Its head is listed only while a subtitle clip is selected; the card
3194 // is mounted regardless, or its chord (`y`) would open an invisible modal.
3195 .children(substyle)
3196 // The body only under its own head: a style left open by a caption stays open
3197 // (its section state persists), but it never shows headless under a clip.
3198 .children(on_subtitle.then(|| section_body(player.subtitle_style_card(room, cx))).flatten())
3199 .child(
3200 div()
3201 .id("dock-clip-verbs")
3202 .flex_none()
3203 .flex()
3204 .flex_col()
3205 .gap(px(2.))
3206 .p(px(12.))
3207 .child(viz_style_verbs(player, cx)),
3208 )
3209 })
3210}
3211
3212/// The open card, under its section head.
3213fn section_body<E: IntoElement>(card: Option<E>) -> Option<gpui::Stateful<Div>> {
3214 card.map(|c| div().id("dock-section-body").flex_none().px(px(12.)).pb(px(12.)).child(c))
3215}
3216
3217/// The Clip tab with nothing to adjust (REDESIGN §3.11): one icon, one line.
3218fn clip_hero() -> impl IntoElement {
3219 let t = tokens();
3220 div()
3221 .id("dock-clip-hero")
3222 .flex_1()
3223 .flex()
3224 .flex_col()
3225 .items_center()
3226 .justify_center()
3227 .gap(px(12.))
3228 .p(px(24.))
3229 .child(Icon::SlidersHorizontal.el(IconSize::Hero, t.ink3))
3230 .child(
3231 div()
3232 .type_style(type_scale::body())
3233 .text_color(rgb(t.ink2))
3234 .child("Select a clip to adjust its speed, colour and sound"),
3235 )
3236}
3237
3238/// The inspector's header (REDESIGN §3.9, 44px): the clip's kind icon, its
3239/// name, its length, and where it sits under the name.
3240fn clip_header(player: &Player) -> Option<impl IntoElement> {
3241 let t = tokens();
3242 let (lane, idx) = player.selected.anchor()?;
3243 let session = player.session.as_ref()?;
3244 let clip = session.lane_clips(lane).get(idx).cloned()?;
3245 // A compound clip plays a sequence, not a file: it wears that sequence's name.
3246 let name = match engine::project::sequence_id_of(clip.source) {
3247 Some(id) => session.sequence_name(id).unwrap_or_default().to_string(),
3248 None => session
3249 .sources()
3250 .get(clip.source)
3251 .map(|s| stem(&crate::file_name(&s.path)))
3252 .unwrap_or_default(),
3253 };
3254 let icon = match lane.kind {
3255 LaneKind::Video => Icon::Film,
3256 LaneKind::Audio => Icon::AudioWaveform,
3257 _ => Icon::Captions,
3258 };
3259 let secs = clip.frames() as f32 / player.fps.max(1.) as f32;
3260 Some(
3261 div()
3262 .id("dock-clip-header")
3263 .flex_none()
3264 .h(px(44.))
3265 .px(px(12.))
3266 .flex()
3267 .items_center()
3268 .gap(px(8.))
3269 .child(icon.el(IconSize::Inline, t.ink2))
3270 .child(
3271 div()
3272 .flex_1()
3273 .min_w(px(0.))
3274 .flex()
3275 .flex_col()
3276 .child(
3277 div()
3278 .truncate()
3279 .type_style(type_scale::emph())
3280 .text_color(rgb(t.ink1))
3281 .child(name),
3282 )
3283 .child(
3284 div()
3285 .type_style(type_scale::caption())
3286 .text_color(rgb(t.ink3))
3287 .child(format!("{} · clip {}", lane.label(), idx + 1)),
3288 ),
3289 )
3290 .child(
3291 div()
3292 .flex_none()
3293 .type_style(type_scale::caption())
3294 .text_color(rgb(t.ink3))
3295 .child(clock(secs)),
3296 ),
3297 )
3298}
3299
3300/// The header a selected title wears: the clip header's twin (icon, the title's own words, "Title",
3301/// length), so the inspector opens the same way on every kind of thing on the timeline.
3302fn title_header(player: &Player) -> Option<impl IntoElement> {
3303 let t = tokens();
3304 let (_, title) = player.title_target()?;
3305 let title = player.shown_title(&title);
3306 // The title's own words are its heading; an empty one has no clip number to fall back on.
3307 let name = title.text.lines().next().unwrap_or_default().trim().to_string();
3308 let name = if name.is_empty() { "Untitled title".to_string() } else { name };
3309 let secs = title.frames as f32 / player.fps.max(1.) as f32;
3310 Some(
3311 div()
3312 .id("dock-title-header")
3313 .flex_none()
3314 .h(px(44.))
3315 .px(px(12.))
3316 .flex()
3317 .items_center()
3318 .gap(px(8.))
3319 .child(Icon::Type.el(IconSize::Inline, t.ink2))
3320 .child(
3321 div()
3322 .flex_1()
3323 .min_w(px(0.))
3324 .flex()
3325 .flex_col()
3326 .child(div().truncate().type_style(type_scale::emph()).text_color(rgb(t.ink1)).child(name))
3327 .child(
3328 div()
3329 .type_style(type_scale::caption())
3330 .text_color(rgb(t.ink3))
3331 .child("Title"),
3332 ),
3333 )
3334 .child(div().flex_none().type_style(type_scale::caption()).text_color(rgb(t.ink3)).child(clock(secs))),
3335 )
3336}
3337
3338/// One section head of the Clip inspector (REDESIGN §3.9, 32px): chevron,
3339/// icon, title; a 1px `line` above all but the first. Clicking opens the card
3340/// under it, or folds it when it is the open one. A section the clip's kind
3341/// can never use ([`Enable::Hidden`]) is left out; one the state refuses
3342/// dims and says why on hover. The chord is in the tooltip, not on the row.
3343#[allow(clippy::too_many_arguments)]
3344fn section_verb(
3345 id: &'static str,
3346 title: &'static str,
3347 icon: Icon,
3348 action: ActionId,
3349 open: bool,
3350 rule: bool,
3351 (section, changed): (Option<Section>, bool),
3352 player: &Player,
3353 on_click: fn(&mut Player, &ClickEvent, &mut Context<Player>),
3354 cx: &mut Context<Player>,
3355) -> Option<impl IntoElement> {
3356 let enabled = player.enable(action, None);
3357 if !enabled.listed() {
3358 return None;
3359 }
3360 let on = enabled.yes();
3361 let t = tokens();
3362 let chord: String = match player.keymap.chord(action).as_ref() {
3363 "--" => String::new(),
3364 k => k.to_string(),
3365 };
3366 let ink = if open { t.ink1 } else { t.ink2 };
3367 Some(
3368 div()
3369 .id(id)
3370 .flex_none()
3371 .h(px(r::CONTROL_L))
3372 .px(px(12.))
3373 .flex()
3374 .items_center()
3375 .gap(px(8.))
3376 // The rule is always in flow (transparent on the first head).
3377 .border_t_1()
3378 .border_color(if rule { rgba(t.line).into() } else { gpui::transparent_black() })
3379 .when(open, |d| d.bg(rgb(t.e2)))
3380 .when(!on, |d| {
3381 d.tooltip(crate::ui::widgets::action_hover(player, action))
3382 .opacity(0.4)
3383 .cursor_not_allowed()
3384 })
3385 .when(on, |d| {
3386 d.cursor_pointer()
3387 .hover(move |s| s.bg(rgb(t.e2)))
3388 .tooltip(crate::ui::widgets::tip_hover(title, &chord, None))
3389 .on_click(cx.listener(move |this, ev: &ClickEvent, _, cx| {
3390 if open {
3391 // Folds this section alone: the others stay open.
3392 match section {
3393 Some(section) => section.close(this),
3394 None => this.close_card(),
3395 }
3396 cx.notify();
3397 } else {
3398 on_click(this, ev, cx);
3399 }
3400 }))
3401 })
3402 .children(hitmap::action(action, on))
3403 .child(
3404 if open { Icon::ChevronDown } else { Icon::ChevronRight }
3405 .el_px(px(12.), t.ink3),
3406 )
3407 .child(icon.el(IconSize::Inline, ink))
3408 .child(
3409 div()
3410 .type_style(type_scale::section())
3411 .text_color(rgb(ink))
3412 .child(title),
3413 )
3414 // A dot when this clip's values differ from the defaults. Its slot is always there
3415 // (transparent when not), so a head never changes width or height.
3416 // The hit area is 16 px square around the 6 px dot, so the hover is easy to find;
3417 // nothing is drawn in the extra room.
3418 .child(
3419 div()
3420 .id("dock-section-dot")
3421 .flex_none()
3422 .size(px(16.))
3423 .flex()
3424 .items_center()
3425 .justify_center()
3426 .when(changed, |d| {
3427 d.tooltip(crate::ui::widgets::overlay_tip_hover("Changed from default", "", None))
3428 })
3429 .child(div().flex_none().size(px(6.)).rounded(px(3.)).when(changed, |d| d.bg(rgb(t.accent)))),
3430 ),
3431 )
3432}
3433
3434/// The shortcuts sheet: every bound command, sectioned by [`keymap::Category`]
3435/// exactly as [`keys_rows`] files them (reusing that registry-driven order is
3436/// what makes an action added anywhere land here without a second list to
3437/// forget), in the shared dialog shell ([`kit::dialog`]) over the picture --
3438/// not a dock tab, so opening it moves no other tab. Each stroke is drawn as
3439/// [`kit::keycaps`]. An action the room would refuse right now is dimmed to
3440/// `ink4` and says why on hover, never hidden: the list is the full truth about
3441/// the keyboard. The root's key handler owns the filter box (typing, Esc,
3442/// backspace), so the sheet needs no focus of its own.
3443pub(crate) fn keys_sheet(player: &Player, viewport: Size<Pixels>, bottom_inset: f32, cx: &mut Context<Player>) -> impl IntoElement + use<> {
3444 let t = tokens();
3445 // A reference, not a state view: every row reads the same whether the action can run now or
3446 // not, so nothing is greyed here. An action with no stroke leaves its key cell empty.
3447 let pair = |id: usize, text: String, strokes: Vec<String>| {
3448 div()
3449 .id(("keys-row", id))
3450 .flex_none()
3451 .flex()
3452 .items_center()
3453 .justify_between()
3454 .gap(px(16.))
3455 .h(px(crate::layout::MENU_ROW_H))
3456 .px(px(4.))
3457 .child(
3458 div()
3459 .flex_1()
3460 .min_w(px(0.))
3461 .truncate()
3462 .type_style(type_scale::body())
3463 .text_color(rgb(t.ink1))
3464 .child(text),
3465 )
3466 .child(
3467 div().flex_none().flex().items_center().gap(px(6.)).children(strokes.into_iter().enumerate().flat_map(|(i, s)| {
3468 let mut parts: Vec<AnyElement> = Vec::new();
3469 if i > 0 {
3470 parts.push(div().type_style(type_scale::caption()).text_color(rgb(t.ink3)).child("or").into_any_element());
3471 }
3472 parts.push(kit::keycaps(&s).into_any_element());
3473 parts
3474 })),
3475 )
3476 .into_any_element()
3477 };
3478 let rows: Vec<AnyElement> = keys_rows_matching(&player.keys_filter, &player.keymap)
3479 .into_iter()
3480 .enumerate()
3481 .map(|(n, row)| match row {
3482 KeyRow::Head(category) => div()
3483 .flex_none()
3484 .pt(px(12.))
3485 .pb(px(2.))
3486 .px(px(4.))
3487 .type_style(type_scale::section())
3488 .text_color(rgb(t.ink2))
3489 .child(category.label())
3490 .into_any_element(),
3491 // Every stroke the action answers to, not the menu's one-key column.
3492 KeyRow::Act(action) => pair(n, action.label().to_string(), player.keymap.strokes(action)),
3493 KeyRow::Fixed(i) => {
3494 let f = &keymap::FIXED[i];
3495 pair(n, f.label.to_string(), f.chord.split(" or ").map(str::to_string).collect())
3496 }
3497 })
3498 .collect();
3499 let editing = !player.keys_filter.is_empty();
3500 let list_max = (f32::from(viewport.height) - bottom_inset - crate::layout::MENU_BAR_H - 48. - 112.).max(120.);
3501 let filter = div()
3502 .id("keys-filter")
3503 .flex_none()
3504 .h(px(r::CONTROL_M))
3505 .px(px(8.))
3506 .flex()
3507 .items_center()
3508 .gap(px(6.))
3509 .rounded(px(r::R_CONTROL))
3510 .bg(rgb(t.e2))
3511 .cursor_text()
3512 .type_style(type_scale::body())
3513 .text_color(rgb(if editing { t.ink1 } else { t.ink3 }))
3514 .tooltip(crate::ui::widgets::overlay_tip_hover("Filter shortcuts", "type to filter", None))
3515 .children(hitmap::control("dock.keys-filter", "Filter keys", true))
3516 .child(Icon::Search.el(IconSize::Inline, t.ink3))
3517 .child(match editing {
3518 false => "Search shortcuts".to_string(),
3519 true => format!("{}\u{258f}", player.keys_filter),
3520 });
3521 let list = match rows.is_empty() {
3522 true => kit::dialog_text("No shortcut matches.").into_any_element(),
3523 false => div()
3524 .id("keys-sheet-rows")
3525 .track_scroll(&player.keys_scroll)
3526 .flex()
3527 .flex_col()
3528 .max_h(px(list_max))
3529 .overflow_y_scroll()
3530 .children(rows)
3531 .into_any_element(),
3532 };
3533 kit::dialog_layer(bottom_inset)
3534 .on_mouse_down(
3535 MouseButton::Left,
3536 cx.listener(|this, _: &MouseDownEvent, _, cx| {
3537 this.keys_open = false;
3538 cx.notify();
3539 cx.stop_propagation();
3540 }),
3541 )
3542 .child(
3543 kit::dialog("keys-sheet", 560.)
3544 .child(kit::dialog_title("Keyboard shortcuts"))
3545 .child(filter)
3546 .child(list),
3547 )
3548}
3549
3550/// The dock's content, under `stance.rs::dock()`'s tab-bar-and-body frame:
3551/// the tab row, then whichever tab is showing.
3552///
3553/// Degradation (DESIGN §7): the dock is a fixed-width side panel, not a lane
3554/// bed, so it has no width ladder of its own to walk -- the panel is either
3555/// on screen at its one width or, at the narrowest floors this editor draws
3556/// to, is the first region asked to give up its width entirely (a step
3557/// `layout.rs`'s split budget already owns for the legacy inspector/library
3558/// pair). What degrades *inside* fixed width is the two tabs' own content:
3559/// Sources scrolls its own row list; Clip's param rows are whatever their
3560/// card already draws at this width.
3561pub(crate) fn render(
3562 player: &Player,
3563 width: f32,
3564 window_size: Size<Pixels>,
3565 window: &mut Window,
3566 cx: &mut Context<Player>,
3567) -> impl IntoElement {
3568 let export = player.export_open;
3569 let transcript = player.transcript_open && !export;
3570 let clip_card = player.clip_card_open();
3571 let src_active = player.dock_src_active && !export && !transcript && !clip_card;
3572 div()
3573 .id("stance-dock-body")
3574 .flex_1()
3575 .min_h(px(0.))
3576 .flex()
3577 .flex_col()
3578 .child(
3579 div()
3580 .id("stance-dock-tabs")
3581 .flex_none()
3582 .flex()
3583 .bg(rgb(tokens().e1))
3584 .border_b_1()
3585 .border_color(rgba(tokens().line))
3586 .child(dock_tab("dock-tab-src", "Media", src_active, cx))
3587 .child(dock_tab("dock-tab-clip", "Clip", !src_active && !export && !transcript, cx))
3588 .child(dock_tab("dock-tab-transcript", "Transcript", transcript, cx))
3589 .child(dock_tab("dock-tab-export", "Export", export, cx)),
3590 )
3591 .child(match (export, src_active) {
3592 (true, _) => player.export_panel(cx).into_any_element(),
3593 _ if transcript => crate::ui::transcript_panel::transcript_tab(player, cx).into_any_element(),
3594 (false, true) => sources_tab(player, window, cx).into_any_element(),
3595 (false, false) => clip_tab(player, width, window_size, window, cx).into_any_element(),
3596 })
3597}
3598
3599/// The Tab/Shift-Tab handler shared by the dock's two tabs (`sources_tab`'s
3600/// "dock/library" and `clip_tab`'s "inspector") -- only [`is_focus_cycle_key`]
3601/// is ever answered here; every other key is left un-stopped so it bubbles
3602/// to the room's root handler (`ui::stance::render`'s `on_key_down`), which
3603/// is the one every other keybind, Tab included when nothing in the ring
3604/// has focus yet, still hangs off.
3605fn cycle_on_key_down(
3606 surface: Surface,
3607) -> impl Fn(&mut Player, &KeyDownEvent, &mut Window, &mut Context<Player>) + 'static {
3608 move |this, event, window, cx| {
3609 let key = event.keystroke.key.as_str();
3610 if is_focus_cycle_key(key) {
3611 let next = next_surface(surface, event.keystroke.modifiers.shift);
3612 this.focus_surface(next, window, cx);
3613 cx.stop_propagation();
3614 } else if is_focus_exit_key(key) && !this.any_text_field() {
3615 // A dismissible overlay (context menu, library menu, picker, any
3616 // card, a live preview) opened by a click into the dock/inspector
3617 // takes this escape first -- the same door the root handler
3618 // itself closes it through (`Player::escape_closes_overlay`) --
3619 // so it does not go on sitting open just because focus happened
3620 // to be inside this ring when escape was pressed (the "esc is
3621 // not closing menus opened by clicking in the clip section"
3622 // report).
3623 if this.escape_closes_overlay(cx) {
3624 cx.stop_propagation();
3625 return;
3626 }
3627 // Leaves the ring for the root, and lets the stroke bubble on to it: the root
3628 // answers escape as Deselect (clears the clip, title or caption selection) and
3629 // routes it into an open text field. A text field open here is left to the root too.
3630 window.focus(&this.focus);
3631 cx.notify();
3632 }
3633 }
3634}
3635
3636#[cfg(test)]
3637mod tests {
3638 use super::*;
3639
3640 fn bare() -> gpui::Modifiers {
3641 gpui::Modifiers::none()
3642 }
3643
3644 #[test]
3645 fn space_and_enter_answer_a_picked_row_only_while_the_media_panel_has_focus() {
3646 // Focused with a row picked: Space previews, Enter adds (DESIGN §6.7).
3647 assert!(media_key("space", bare(), true, true) == Some(RowItem::Preview));
3648 assert!(media_key("enter", bare(), true, true) == Some(RowItem::Preview));
3649 // Not focused: Space stays Play, Enter stays whatever the keymap says.
3650 assert!(media_key("space", bare(), false, true).is_none());
3651 assert!(media_key("enter", bare(), false, true).is_none());
3652 // No row picked: fall through to Play.
3653 assert!(media_key("space", bare(), true, false).is_none());
3654 // A chord keeps its keymap meaning even with the panel focused.
3655 let shift = gpui::Modifiers {
3656 shift: true,
3657 ..bare()
3658 };
3659 assert!(media_key("space", shift, true, true).is_none());
3660 // Other keys are never routed here.
3661 assert!(media_key("j", bare(), true, true).is_none());
3662 }
3663
3664 /// One relink of one missing file also points the other missing files of the same name in its
3665 /// new folder at their copies, but only those whose length matches; a mismatched one stays
3666 /// missing, and a file of another kind is never followed.
3667 #[test]
3668 fn relinking_one_missing_file_follows_only_the_same_names_of_the_same_length() {
3669 use std::path::{Path, PathBuf};
3670 let missing = vec![
3671 (0, PathBuf::from("/old/a.mp4")),
3672 (1, PathBuf::from("/old/b.mp4")),
3673 (2, PathBuf::from("/old/c.mp4")),
3674 (3, PathBuf::from("/old/d.mp4")),
3675 ];
3676 let new = Path::new("/new/a.mp4");
3677 // b.mp4 is there with the matching length, c.mp4 is there but a different length, d.mp4 is not there.
3678 let there = |p: &Path| p == Path::new("/new/b.mp4") || p == Path::new("/new/c.mp4") || p == new;
3679 let length_ok = |_: usize, p: &Path| p == Path::new("/new/b.mp4");
3680 let followers = relink_followers(&missing, 0, Path::new("/old/a.mp4"), new, there, length_ok);
3681 assert_eq!(followers, vec![(1, PathBuf::from("/new/b.mp4"))], "matching length follows, mismatched is skipped");
3682 assert_eq!(relink_words(5, 2), "Relinked 5 files. 2 are still missing.");
3683 assert_eq!(relink_words(1, 0), "Relinked 1 file.");
3684 assert_eq!(relink_words(3, 1), "Relinked 3 files. 1 is still missing.");
3685 }
3686
3687 /// The length rule: within one frame of what the source was recorded at, and a file that
3688 /// cannot be read never matches.
3689 #[test]
3690 fn a_relinked_file_must_match_the_recorded_length_within_a_frame() {
3691 assert!(!same_length(100, Path::new("/no/such/file.mp4"), 25.));
3692 assert!(engine::is_image(Path::new("x.png")) && same_length(0, Path::new("x.png"), 25.));
3693 }
3694
3695 /// A name that does not fit is cut with an ellipsis, never mid-letter, and a short one is left whole.
3696 #[test]
3697 fn a_long_name_is_cut_with_an_ellipsis_and_a_short_one_is_whole() {
3698 assert_eq!(fit_name("clip", 500., 13.), "clip");
3699 let cut = fit_name("test_multiaudio [audio 2] long name", 60., 13.);
3700 assert!(cut.ends_with('\u{2026}'), "{cut}");
3701 assert!(crate::ui::popup::text_w(&cut, 13., false) <= 60.);
3702 }
3703
3704 /// Two names sharing a long start read apart: the cut keeps the end, so the rows differ.
3705 #[test]
3706 fn names_sharing_a_long_start_are_cut_in_the_middle_and_stay_distinct() {
3707 let short = fit_row_name("test_multiaudio_fr [audio 1]", 110., 13.);
3708 let long = fit_row_name("test_multiaudio_fr_commentary [audio 1]", 110., 13.);
3709 assert_ne!(short, long, "{short} / {long}");
3710 assert!(short.contains('\u{2026}') && long.contains('\u{2026}'), "{short} / {long}");
3711 assert!(short.ends_with("\u{00b7} audio 1") && long.ends_with("\u{00b7} audio 1"));
3712 assert!(crate::ui::popup::text_w(&long, 13., false) <= 110.);
3713 }
3714
3715 /// A stream tag stays whole when the file's name is cut, so three tracks of one file stay apart.
3716 #[test]
3717 fn a_stream_tag_is_kept_when_the_file_name_is_cut() {
3718 let cut = fit_row_name("test_multiaudio [audio 2]", 120., 13.);
3719 assert!(cut.ends_with("\u{00b7} audio 2"), "{cut}");
3720 assert!(cut.contains('\u{2026}'), "{cut}");
3721 assert!(crate::ui::popup::text_w(&cut, 13., false) <= 120.);
3722 assert_eq!(fit_row_name("clip", 500., 13.), "clip");
3723 }
3724
3725 /// Language codes read as names; an untagged track loses the word.
3726 #[test]
3727 fn a_stream_language_reads_as_a_name() {
3728 assert_eq!(language_name("fra"), Some("French"));
3729 assert_eq!(language_name("eng"), Some("English"));
3730 assert_eq!(language_name("und"), None);
3731 assert!(is_layout_refusal("the timeline is mono"));
3732 assert!(refusal_sentence("the timeline is mono").contains("mono"));
3733 assert!(LAYOUT_SHORT.len() < 40, "the row's short line must fit the panel");
3734 assert_eq!(refusal_sentence("aac is not supported"), "aac is not supported");
3735 }
3736}