forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

menus.rs1153 lines, 49.0 KiBHistoryRawDownload
1//! The lists the window opens over itself: the clip menu, the pickers, the key rows.
2
3use crate::*;
4
5/// What a right-click on the bench named: a clip at an index, or the empty
6/// stretch of the lane it landed in ([`engine::PlaybackSession::gap_at`]) --
7/// two different things the one menu can be about, so it stays one struct and
8/// one field to clear rather than a second `Option` beside `context_menu`
9/// that every closer would have to learn about too.
10#[derive(Clone, Copy)]
11pub(crate) enum MenuOn {
12 Clip(usize),
13 /// `(start, frames)` of the gap, in timeline frames -- what
14 /// [`Player::close_gap`] ripples shut.
15 Gap(u32, u32),
16 /// The bench itself: the ruler, or the empty stretch below the last lane.
17 /// Nothing under the pointer is a clip, so what the menu offers is what
18 /// the *timeline* can be told -- walking its cuts, its zoom, its snap and
19 /// the undo pair ([`BENCH_ITEMS`]). The lane field means nothing here and
20 /// no row reads it.
21 Bench,
22 /// An empty stretch of a lane's bed with no gap to close: Paste and the two track adds
23 /// ([`empty_items`]). The lane names the track the stretch is on.
24 Empty,
25 /// A lane head: the verbs of the track itself, on the lane the menu
26 /// already names ([`oracle::lane_items`]).
27 Head,
28 /// The dock's Sources body, anywhere its rows are not: the ways *in*
29 /// ([`DOCK_ITEMS`]). Cleanse round 2 took `Paste path` and `Import
30 /// subtitles` out of the footer, and this is the door they kept -- an
31 /// empty library included, which is exactly when a pasted path is worth
32 /// most. The lane field means nothing here and no row reads it.
33 Dock,
34 /// The viewer's picture: what the picture can be told ([`VIEWER_ITEMS`]).
35 /// The lane field means nothing here and no row reads it.
36 Viewer,
37 /// A sequence tab: the verbs of the sequence ([`SEQ_TAB_ITEMS`]); the tab was opened first,
38 /// so they act on the open sequence.
39 SeqTab,
40 /// A bin row in the media list: the verbs of the bin ([`BIN_ITEMS`]); the bin was picked
41 /// first, so they act on it.
42 Bin,
43 /// A comment marker on the ruler: its verbs ([`MARKER_ITEMS`]); the marker was selected
44 /// first, so they act on it.
45 Marker,
46}
47
48/// An open clip menu: what it was opened on, where it hangs, and whether it
49/// has been turned over to show what a clip *is* instead of what can be done
50/// to it (`details` means nothing for a gap, which has no properties side).
51/// The lane is the one the same click selected, so every item acts on
52/// exactly the box -- or the hole -- under the pointer.
53#[derive(Clone, Copy)]
54pub(crate) struct ContextMenu {
55 pub(crate) lane: Lane,
56 pub(crate) on: MenuOn,
57 pub(crate) at: Point<Pixels>,
58 pub(crate) details: bool,
59 /// The submenu out beside the plate, if any. One at a time.
60 pub(crate) sub: Sub,
61}
62
63/// Which submenu of a clip menu is out beside the plate.
64#[derive(Clone, Copy, PartialEq, Eq, Debug)]
65pub(crate) enum Sub {
66 Closed,
67 /// The card openers.
68 Adjust,
69 /// Nest, break apart, open, flatten.
70 Compound,
71 /// The colour list of the clip.
72 Label,
73 /// The fit policies of the clip.
74 Fit,
75}
76
77/// An open library menu: which row it was opened on -- the file and the stream,
78/// the pair [`Player::selected_asset`] holds, so a list rebuilt under it (a
79/// probe landing, a source going) cannot slide another row beneath the menu the
80/// way a row *index* would -- where it hangs, and whether it has been turned
81/// over to show what the file *is*.
82#[derive(Clone)]
83pub(crate) struct LibraryMenu {
84 pub(crate) path: PathBuf,
85 pub(crate) stream: usize,
86 pub(crate) at: Point<Pixels>,
87 pub(crate) details: bool,
88}
89
90/// An open choice list: which setting it offers and where it hangs. What a
91/// button that stepped one value on per click used to be -- a setting with more
92/// than two values is a list to look at, not a thing to click round. Placed by
93/// [`menu_at`] and closed by a stroke, exactly like the two menus above it.
94#[derive(Clone, Copy, PartialEq)]
95pub(crate) struct Picker {
96 pub(crate) of: Pick,
97 pub(crate) at: Point<Pixels>,
98 /// Which row the keyboard is on, from the value in force when the list
99 /// opened. The list answers ↑↓ and enter as well as a click: a setting whose
100 /// only door is a pointer is a setting half this editor's users cannot
101 /// reach, which is the rule `FIXED` already writes down for every card.
102 pub(crate) sel: usize,
103 /// Whether the list keeps off the picture and timeline (a list opened from the menu bar's
104 /// own corner or the status bar) or hangs from the foot of the dock button that opened it.
105 pub(crate) floored: bool,
106 /// For a list hung from a recorded control ([`crate::ui::anchor`]): the control's top edge,
107 /// where the plate's bottom goes when there is no room below.
108 pub(crate) above: Option<f32>,
109}
110
111/// Which setting an open list is offering. The fit policy names the clip it is
112/// about, like the clip menu it opens from -- indices move under every edit, so
113/// the list closes on the first stroke as that menu does.
114#[derive(Clone, Copy, PartialEq, Eq, Debug)]
115pub(crate) enum Pick {
116 Resolution,
117 Fps,
118 /// The rate the project's own mix runs at
119 /// ([`engine::PlaybackSession::set_sample_rate`]). Opened from the panel,
120 /// beside the resolution and rate it shares a row style with.
121 SampleRate,
122 /// The speech model the project transcribes with, or Auto ([`Choice::SpeechModel`]).
123 SpeechModel,
124 Fit(Lane, usize),
125 /// The colour label of the clip at (lane, index) ([`engine::project::LABELS`]).
126 Label(Lane, usize),
127 /// The easing of the key on the playhead, for one kind of key.
128 KeyEase(engine::project::KeyKind),
129 /// The viewer's zoom, playback quality and aspect mask: lists on the viewer header.
130 ViewZoom,
131 OutputDisplay,
132 ViewQuality,
133 ViewMask,
134 ViewGuides,
135 /// The colour of marker `n`, from the markers card's swatch.
136 MarkerColor(usize),
137 /// What the export's *sound* is coded at. Opened from the card's Sound row,
138 /// which is the only place it means anything.
139 #[allow(dead_code)] // opened from Settings now
140 AudioRate,
141 /// Which HDR-to-SDR rendition the project is watched and exported in
142 /// ([`engine::tonemap::Preset`]). Opened from the panel, beside the two
143 /// other settings that are the project's rather than the media's.
144 #[allow(dead_code)] // three chips on the settings page now
145 Tone,
146 /// Which palette the window is painted in ([`ui::theme`]). The one setting
147 /// here that is nobody's project: it is the person's, so it outlives the
148 /// timeline and every file opened in it.
149 Theme,
150 /// Which accent colour the window wears ([`ui::theme::AccentId`]); the person's, like [`Pick::Theme`].
151 Accent,
152 /// Which encoder an export writes the picture with
153 /// ([`engine::export::EncoderSeat`]). Opened from the card's Encoder row,
154 /// which is the only place it means anything.
155 #[allow(dead_code)] // opened from Settings now
156 Encoder,
157 /// Which file an export is written as -- the codec and its box in one
158 /// list ([`ui::settings_stance::picture_choices`]). Opened from the
159 /// settings page's Picture row: nine answers are too many for chips.
160 Picture,
161 /// A Details row of the Export tab (preset, container, codec, ...).
162 Export(crate::export_ui::ExportRow),
163 /// The bin the picked media are filed in; the list offers every bin and "No bin".
164 Bin,
165 /// How often the session is autosaved beside its file, from Settings ([`player::library::AUTOSAVE_CHOICES`]).
166 Autosave,
167}
168
169/// One value a list offers, carrying everything picking it needs -- so a click
170/// goes straight to the value rather than to a position in a list that was
171/// built somewhere else.
172/// `Eq` is off it for the rate: a frame rate is the `f64` the engine is told,
173/// bit for bit (23.976023976... is not 23.976), and nothing here keys a map on a
174/// choice -- comparing two is all a list row ever does.
175#[derive(Clone, Copy, PartialEq, Debug)]
176pub(crate) enum Choice {
177 Size(u32, u32),
178 Fps(f64),
179 /// `None` is "source" -- the rate derived from the sources (the highest
180 /// among them, 48 kHz when all are below 44.1 kHz),
181 /// [`engine::PlaybackSession::set_sample_rate`]'s own default.
182 SampleRate(Option<u32>),
183 Fit(Lane, usize, FitPolicy),
184 /// A label number for the clip: 0 none, else 1..=[`engine::project::LABEL_COUNT`].
185 Label(Lane, usize, u8),
186 KeyEase(engine::project::KeyKind, engine::transform::KeyEase),
187 ViewZoom(crate::viewer_view::Zoom),
188 /// An index into [`Player::output_displays`].
189 OutputDisplay(usize),
190 ViewQuality(crate::viewer_view::Quality),
191 ViewMask(crate::viewer_view::Mask),
192 ViewGuides(crate::viewer_view::Guide),
193 MarkerColor(usize, engine::project::MarkerColor),
194 AudioRate(u32),
195 Tone(Preset),
196 Theme(ui::theme::PaletteId),
197 Accent(ui::theme::AccentId),
198 Encoder(EncoderSeat),
199 Picture(Format),
200 /// A Details row of the Export tab ([`Pick::Export`]).
201 Export(crate::export_ui::ExportPick),
202 /// File the picked media in bin `n` (`0`: out of every bin) ([`Pick::Bin`]).
203 Bin(u32),
204 /// The autosave period in seconds, `None` for Off ([`Pick::Autosave`]).
205 Autosave(Option<u64>),
206 /// The speech model, `None` for Auto ([`engine::speech::MODELS`]).
207 SpeechModel(Option<&'static str>),
208}
209
210/// A status-bar item a shortcut-opened list hangs above.
211#[derive(Clone, Copy, PartialEq, Eq, Debug)]
212pub(crate) enum LedgerItem {
213 Size,
214 Clip,
215}
216
217/// One row of an open list: the value, its name, the small print beside it, and
218/// whether it is the one in force.
219pub(crate) type ChoiceRow = (Choice, SharedString, SharedString, bool);
220
221/// What a library row's menu offers, in the order it lists them. Unlike the clip
222/// menu's items only one of these ([`RowItem::Add`]) is a stroke, and that one
223/// is not a bindable [`ActionId`] but `ui/stance.rs`'s own `enter` branch, so
224/// the label and the chord are written here rather than read off the keymap.
225#[derive(Clone, Copy, PartialEq)]
226pub(crate) enum RowItem {
227 /// Point a missing file at its new place ([`Player::relink_pick`]). Listed
228 /// only on a row whose file is gone.
229 Relink,
230 /// Put the source on the end of the timeline, after the last clip on any lane
231 /// ([`Player::append_source`]). The default: the first row, and what Enter does.
232 Add,
233 /// Insert the source at the playhead, pushing the clips after it right
234 /// ([`Player::insert_source`] with no lane and no position).
235 Insert,
236 /// Play the source outside the timeline ([`Player::open_preview`]). The
237 /// row's `▷` ghost until cleanse round 2 (2026-09-10); a double-click on
238 /// the row is the other door.
239 Preview,
240 /// Make or stop the source's stand-in ([`Player::toggle_proxy`]) -- the
241 /// row's `○` ghost until the same cleanse. Settings carries the policy;
242 /// this is the one file. Reads "Stop editing copy" while one is being made.
243 Proxy,
244 /// Makes a multicam clip from the picked rows ([`Player::create_multicam_selected`]).
245 /// Refused until two or more are picked, saying how.
246 CreateMulticam,
247 /// Take the source out of the library. Refused while any clip plays it
248 /// (the engine's own rule), and destructive, so it sits below the rule.
249 Remove,
250 /// Remove that first deletes every clip playing the row. It is listed
251 /// always and refused with a reason while nothing plays the file, so the
252 /// pointer can see the way out exists; destructive, so it sits below the
253 /// rule and says how many clips it takes with it.
254 RemoveWithClips,
255 Reveal,
256 Properties,
257 /// Stars the source, or takes the star off ([`Player::toggle_favourite`]).
258 Favourite,
259 /// Opens the list of bins to file the source in ([`Pick::Bin`]).
260 MoveToBin,
261 /// Makes a bin holding this source, named in place ([`Player::new_bin`]).
262 NewBin,
263}
264
265/// Menu rows in the order the Media row menu lists them (DESIGN §6.7). The two
266/// destructive rows are last, under the rule line ([`RowItem::destructive`]).
267pub(crate) const ROW_ITEMS: [RowItem; 13] = [
268 RowItem::Relink,
269 RowItem::Add,
270 RowItem::Insert,
271 RowItem::Preview,
272 RowItem::Proxy,
273 RowItem::CreateMulticam,
274 RowItem::Favourite,
275 RowItem::MoveToBin,
276 RowItem::NewBin,
277 RowItem::Reveal,
278 RowItem::Properties,
279 RowItem::Remove,
280 RowItem::RemoveWithClips,
281];
282
283impl RowItem {
284 /// The icon the row wears in the media menu's icon column.
285 pub(crate) fn icon(self) -> crate::ui::icons::Icon {
286 use crate::ui::icons::Icon as I;
287 match self {
288 Self::Relink => I::Link,
289 Self::Add | Self::Insert => I::Plus,
290 Self::Preview => I::Play,
291 Self::Proxy => I::Gauge,
292 Self::Remove | Self::RemoveWithClips => I::Trash2,
293 Self::Reveal => I::FolderOpen,
294 Self::Properties => I::Info,
295 Self::Favourite => I::Star,
296 Self::MoveToBin | Self::NewBin => I::Folder,
297 Self::CreateMulticam => I::Layers,
298 }
299 }
300
301 pub(crate) fn label(self) -> &'static str {
302 match self {
303 Self::Relink => "Relink…",
304 Self::Add => "Append to timeline end",
305 Self::Insert => "Insert at playhead",
306 Self::CreateMulticam => "Create multicam…",
307 Self::Preview => "Open in source viewer",
308 Self::Proxy => "Make editing copy",
309 Self::Remove => "Remove from library",
310 // The consequence is in the label now rather than in the hint
311 // column beside a label identical to the plain remove's: that
312 // column carries chords ([`RowItem::hint`]), and a destructive
313 // verb whose difference from the row above it lived in dim grey
314 // prose is a verb that reads as the same verb. It fits `MENU_W`
315 // whole exactly because nothing is printed to its right.
316 Self::RemoveWithClips => "Remove with its clips",
317 Self::Reveal => "Reveal in files",
318 Self::Properties => "Properties",
319 Self::Favourite => "Favourite",
320 Self::MoveToBin => "Move to bin…",
321 Self::NewBin => "New bin",
322 }
323 }
324
325 /// The label this row wears in `ctx`: the one state-dependent label, the
326 /// proxy row's, reads "Stop editing copy" while a stand-in is being made.
327 pub(crate) fn label_in(self, ctx: RowCtx) -> &'static str {
328 match self {
329 Self::Proxy if ctx.proxy_stops => "Stop editing copy",
330 Self::Favourite if ctx.starred => "Remove from favourites",
331 _ => self.label(),
332 }
333 }
334
335 /// Whether the row takes something away -- the rows below the rule line
336 /// ([`destructive`] is the same answer for the clip menu).
337 pub(crate) fn destructive(self) -> bool {
338 matches!(self, Self::Remove | Self::RemoveWithClips)
339 }
340
341 /// The dim right-hand column: the *stroke* that does the same thing, the
342 /// one thing DESIGN §4 puts there ("every command wears its chord"), and
343 /// nothing at all where no stroke reaches the verb.
344 ///
345 /// It used to carry a prose gloss on every row -- a phrase about the whole
346 /// file, one about the desktop's file browser, one about clips -- which is
347 /// §8's instructional copy sitting in the column the sibling clip menu
348 /// spends on chords, and which the user read as the crowding it is. A
349 /// refusal still prints here in place of the chord (`oracle::row_enable`)
350 /// -- that is state, not instruction.
351 pub(crate) fn hint(self) -> &'static str {
352 match self {
353 Self::Add | Self::Insert | Self::CreateMulticam => "",
354 Self::Preview => "↵",
355 Self::Relink
356 | Self::Proxy
357 | Self::Remove
358 | Self::RemoveWithClips
359 | Self::Reveal
360 | Self::Properties
361 | Self::Favourite
362 | Self::MoveToBin
363 | Self::NewBin => "",
364 }
365 }
366}
367
368/// What the menu offers, in the order it lists them. Every one of these is an
369/// action a stroke already reaches -- the menu is a second way *to* the actions
370/// and never a second version of them -- so both the label and the hint come
371/// out of the keymap registry and the two can never disagree.
372pub(crate) const MENU_ITEMS: [ActionId; 31] = [
373 ActionId::Cut,
374 // The cut machinery (DESIGN.md §6) on the very clip it is about: the
375 // trims and the loop-trim were strokes the spine rail listed and nothing
376 // else did, and the subject cut a right-click names is exactly the one
377 // they act on. Their trim-to-playhead pair is *not* here: `^[` and `^]`
378 // are the keyboard's own version of a gesture the pointer already has --
379 // drag the edge to where you want it -- so a row for them in the menu the
380 // pointer opens is the junk drawer §9 forbids. They keep their chords and
381 // their KEYS rows.
382 ActionId::TrimIn,
383 ActionId::TrimOut,
384 ActionId::LoopTrim,
385 // The clipboard pair, which had no door but a chord: copy takes the clip
386 // the menu names, and paste is the timeline's rather than this clip's.
387 ActionId::Copy,
388 ActionId::Paste,
389 // The clip's colour label and its on/off switch (Premiere's Label and Enable).
390 ActionId::ClipLabel,
391 ActionId::ClipEnabled,
392 // The two joins, one per kind, each hidden over the other kind
393 // (`oracle::enable`, DESIGN §8's class refusal): sound crossfades, picture
394 // dissolves, and neither is ever offered over the wrong waveform.
395 ActionId::Crossfade,
396 ActionId::Dissolve,
397 // The picture cards...
398 ActionId::Color,
399 ActionId::Transform,
400 ActionId::Effects,
401 // ...and the sound ones, the same class refusal the other way round.
402 ActionId::Equalizer,
403 ActionId::Silence,
404 ActionId::MarkBeats,
405 ActionId::Visualizer,
406 ActionId::Reframe,
407 ActionId::TrackMask,
408 ActionId::Speed,
409 ActionId::Reverse,
410 ActionId::Fit,
411 // The compound clip's three verbs, folded into one "Compound" submenu like the cards.
412 ActionId::NestClips,
413 ActionId::BreakApart,
414 ActionId::OpenCompound,
415 ActionId::FlattenMulticam,
416 // The group trio used to live only on chords + ctrl-click. A right-click
417 // that cannot group is a missing pointer door (the same class Fit and
418 // Redo shipped as). Dimmed in place when the selection cannot.
419 ActionId::Group,
420 ActionId::Detach,
421 ActionId::Regroup,
422 // Last, under the rule line the render draws before the first of them
423 // (DESIGN §9): the two that take the clip off the lane.
424 ActionId::Delete,
425 ActionId::Lift,
426];
427
428// Mute stays off this list: it is the mix's, which the transport already
429// carries a button for.
430
431/// What a right-click on the bench itself offers -- the ruler and the empty
432/// stretch under the lanes. The verbs of the *timeline*: walking its cuts at
433/// either stride (DESIGN §6's odometer), what it is looked at through, and the
434/// undo pair, which is the one thing every editor expects on empty canvas.
435/// Not a junk drawer (§9): nothing here acts on a clip, and everything here
436/// acts on the thing the pointer is over.
437pub(crate) const BENCH_ITEMS: [ActionId; 22] = [
438 // The two that act on the frame the pointer named, first and in this order: a marker
439 // there, then the playhead there (the ruler's own verbs, not the playhead's).
440 ActionId::MarkerHere,
441 ActionId::PlayheadHere,
442 // Where the playhead goes, then the range it marks: the ruler is the
443 // strip a person clicks to seek, so its menu leads with the seek pair and
444 // the in/out pair that frames a range on it. Nothing here is destructive
445 // (`ClearRange` only lets go of the marks), so the list still ends on the
446 // undo pair and the rule-free tail.
447 ActionId::GoStart,
448 ActionId::GoEnd,
449 ActionId::SetIn,
450 ActionId::SetOut,
451 ActionId::ClearRange,
452 // The `all` control left the ruler's right edge (cleanse round 2): this
453 // row is where the pointer reaches "select everything" now, and `^a`
454 // still fires it.
455 ActionId::SelectAll,
456 ActionId::Paste,
457 ActionId::WalkCutPrev,
458 ActionId::WalkCutNext,
459 ActionId::WalkCutPrev10,
460 ActionId::WalkCutNext10,
461 // The comment markers: drop one at the playhead, walk to its neighbours, or open the
462 // list -- the ruler is where they are drawn, so its menu is where they are reached.
463 ActionId::PrevMarker,
464 ActionId::NextMarker,
465 ActionId::Markers,
466 ActionId::ZoomOut,
467 ActionId::ZoomIn,
468 ActionId::ZoomFit,
469 ActionId::ToggleSnap,
470 ActionId::Undo,
471 ActionId::Redo,
472];
473
474/// What a right-click on the viewer offers: the things the picture itself
475/// answers to -- play it, loop it, keep the frame, go full screen -- and the
476/// way to Settings. Every one is an [`ActionId`] the keyboard already reaches.
477pub(crate) const VIEWER_ITEMS: [ActionId; 5] = [
478 ActionId::Play,
479 ActionId::Loop,
480 ActionId::Screenshot,
481 ActionId::Fullscreen,
482 ActionId::Settings,
483];
484
485/// What a right-click on a sequence tab offers.
486pub(crate) const SEQ_TAB_ITEMS: [ActionId; 3] =
487 [ActionId::RenameSequence, ActionId::DuplicateSequence, ActionId::DeleteSequence];
488
489/// What a right-click on a comment marker on the ruler offers: the marker was selected first,
490/// so these act on it ([`Player::rename_marker_at_pick`], [`Player::delete_marker_at_pick`]).
491pub(crate) const MARKER_ITEMS: [ActionId; 2] = [ActionId::RenameMarker, ActionId::DeleteMarker];
492
493/// What a right-click on a bin row offers.
494/// The media row's own doors for `ActionId::ToggleFavourite` (Favourite) and
495/// `ActionId::MoveToBin`; the dock's All / Favourites control is the door for
496/// `ActionId::ShowFavourites` and `ActionId::ShowAllMedia`.
497pub(crate) const BIN_ITEMS: [ActionId; 3] = [ActionId::RenameBin, ActionId::NewBinInside, ActionId::RemoveBin];
498
499/// What a right-click on the dock's Sources body offers: the three ways a
500/// file gets in. Every one is an [`ActionId`] the keyboard already reaches,
501/// so the row's label and its chord come out of the registry -- the dock
502/// itself only draws one of them (`Add`) as a row of its own now.
503pub(crate) const DOCK_ITEMS: [ActionId; 13] = [
504 ActionId::AddFiles,
505 ActionId::PasteFilePath,
506 ActionId::ImportSubtitles,
507 ActionId::NewBin,
508 ActionId::CreateMulticam,
509 ActionId::NewSolid,
510 ActionId::NewGradient,
511 ActionId::NewCountdown,
512 ActionId::NewBars,
513 ActionId::NewTone,
514 ActionId::NewBarsAndTone,
515 ActionId::NewAdjustment,
516 ActionId::NewTitle,
517];
518
519/// The tracks a lane head's menu can add, in the order it lists them. Its
520/// remove is the one of the clicked lane's own kind and comes from
521/// [`oracle::lane_items`], which is what puts it under the rule line.
522/// What an empty stretch of a bed offers with no gap to close: the clipboard's paste and the
523/// two track adds, whichever track it is on.
524pub(crate) fn empty_items(_lane: Lane) -> Vec<ActionId> {
525 vec![ActionId::Paste, ActionId::AddVideoLane, ActionId::AddAudioLane]
526}
527
528pub(crate) const HEAD_ADDS: [ActionId; 3] = [
529 ActionId::AddVideoLane,
530 ActionId::AddAudioLane,
531 ActionId::AddSubtitleLane,
532];
533
534/// Whether a menu row takes something away -- what DESIGN §9 puts below a rule
535/// line, wherever the row is listed. One answer, so the clip menu and the lane
536/// head's menu cannot come to disagree about which of their rows is the
537/// dangerous one.
538/// The card openers a clip's menu folds into its one "Adjust" submenu, so the
539/// top level keeps the high-frequency rows and always fits the window.
540pub(crate) fn adjust_item(action: ActionId) -> bool {
541 matches!(
542 action,
543 ActionId::Color
544 | ActionId::Transform
545 | ActionId::Effects
546 | ActionId::Equalizer
547 | ActionId::Silence
548 | ActionId::MarkBeats
549 | ActionId::Visualizer
550 | ActionId::Reframe
551 | ActionId::TrackMask
552 | ActionId::Speed
553 )
554}
555
556/// The compound-clip verbs a clip's menu folds into its one "Compound" submenu.
557pub(crate) fn compound_item(action: ActionId) -> bool {
558 matches!(
559 action,
560 ActionId::NestClips | ActionId::BreakApart | ActionId::OpenCompound | ActionId::FlattenMulticam
561 )
562}
563
564pub(crate) fn destructive(action: ActionId) -> bool {
565 matches!(
566 action,
567 ActionId::Delete
568 | ActionId::Lift
569 | ActionId::RemoveVideoLane
570 | ActionId::RemoveAudioLane
571 | ActionId::RemoveSubtitleLane
572 | ActionId::DeleteSequence
573 | ActionId::RemoveBin
574 )
575}
576
577/// One row of the actions card, in the order it lists them: a heading, then
578/// every action the registry files under it, then the strokes the modal cards
579/// answer themselves.
580///
581/// A list rather than a loop inside the render, so the card and
582/// `every_action_is_on_the_actions_card` read the *same* order: an action that
583/// reaches no row fails a test instead of quietly becoming pointer-unreachable.
584#[derive(Clone, Copy, Debug)]
585pub(crate) enum KeyRow {
586 Head(keymap::Category),
587 /// Click its label to do it, click its stroke to change that stroke.
588 Act(ActionId),
589 /// An index into [`keymap::FIXED`]. Shown and never offered: nothing may
590 /// unbind the way out of a card.
591 Fixed(usize),
592}
593
594/// Every action, under its heading, and the card-local strokes beside them.
595/// Generated from the registry -- [`ActionId::ALL`] in its own order, under
596/// [`keymap::Category::ALL`] -- so an action added there is on the card the
597/// moment it exists and there is no second list here to forget.
598pub(crate) fn keys_rows() -> Vec<KeyRow> {
599 let mut rows = Vec::new();
600 for category in keymap::Category::ALL {
601 rows.push(KeyRow::Head(category));
602 // The nine angle keys are one row: Angle1 is labelled "angle 1–9" and
603 // the other eight are reached by the same number keys, so they stay in
604 // the registry (and keep their keys) but get no row of their own.
605 rows.extend(
606 ActionId::ALL
607 .into_iter()
608 .filter(|a| a.category() == category)
609 .filter(|a| a.angle_number().is_none_or(|n| n == 1))
610 .map(KeyRow::Act),
611 );
612 rows.extend(
613 keymap::FIXED
614 .iter()
615 .enumerate()
616 .filter(|(_, f)| f.category == category)
617 .map(|(i, _)| KeyRow::Fixed(i)),
618 );
619 }
620 rows
621}
622
623/// The KEYS tab's type-to-filter: keep a heading only when one of its rows
624/// still matches, match a row on its label or its chord.
625pub(crate) fn keys_rows_matching(query: &str, keymap: &keymap::Keymap) -> Vec<KeyRow> {
626 let q = query.trim().to_ascii_lowercase();
627 if q.is_empty() {
628 return keys_rows();
629 }
630 let rows = keys_rows();
631 let mut out = Vec::new();
632 let mut i = 0;
633 while i < rows.len() {
634 match rows[i] {
635 KeyRow::Head(cat) => {
636 let mut kids = Vec::new();
637 i += 1;
638 while i < rows.len() && !matches!(rows[i], KeyRow::Head(_)) {
639 if key_row_hits(&rows[i], &q, keymap) {
640 kids.push(rows[i]);
641 }
642 i += 1;
643 }
644 if !kids.is_empty() {
645 out.push(KeyRow::Head(cat));
646 out.extend(kids);
647 }
648 }
649 _ => i += 1,
650 }
651 }
652 out
653}
654
655fn key_row_hits(row: &KeyRow, q: &str, keymap: &keymap::Keymap) -> bool {
656 match *row {
657 KeyRow::Head(c) => c.label().to_ascii_lowercase().contains(q),
658 KeyRow::Act(a) => {
659 a.label().to_ascii_lowercase().contains(q)
660 || keymap.display(a).to_ascii_lowercase().contains(q)
661 || keymap::search_aliases(&keymap.display(a))
662 .to_ascii_lowercase()
663 .contains(q)
664 }
665 KeyRow::Fixed(i) => {
666 let f = &keymap::FIXED[i];
667 f.label.to_ascii_lowercase().contains(q)
668 || f.chord.to_ascii_lowercase().contains(q)
669 || keymap::search_aliases(&f.chord)
670 .to_ascii_lowercase()
671 .contains(q)
672 }
673 }
674}
675
676/// The character a stroke types into the actions card's search box, if it types
677/// one. gpui reports a printable key as itself and the space bar by name
678/// (platform.rs:866), and everything else -- the arrows, the function keys --
679/// is a word this must not spell into the box letter by letter.
680pub(crate) fn typed(key: &str) -> Option<char> {
681 match key {
682 "space" => Some(' '),
683 _ => key
684 .chars()
685 .next()
686 .filter(|c| c.is_ascii_graphic() && key.chars().count() == 1),
687 }
688}
689
690/// One row of the command palette (DESIGN §4.4, Ctrl+K): an action, and the
691/// reason the editor refuses it right now, if it does. A hidden action never
692/// becomes a row ([`palette_rows`]).
693#[derive(Clone, Copy, Debug, PartialEq)]
694pub(crate) struct PaletteRow {
695 pub(crate) action: ActionId,
696 /// `Some(reason)` when the row is listed but cannot run. It stays on the
697 /// list in ink4, with the reason where the key would be (DESIGN §4.8).
698 pub(crate) refused: Option<&'static str>,
699}
700
701/// The palette's rows for `query`, in the order they list.
702///
703/// An empty query lists every action under its category, in the registry's
704/// order. A query keeps the actions it matches on their label or category --
705/// case-insensitive, each word a prefix or a substring -- and lists the best
706/// matches first: a label that starts with the word beats a word inside it,
707/// which beats a substring, which beats a match on the category alone. Ties
708/// keep the registry's order. `enable` is the oracle's answer per action; its
709/// `Hidden` answers are dropped, its `No` answers stay as refused rows.
710pub(crate) fn palette_rows(
711 query: &str,
712 enable: impl Fn(ActionId) -> crate::oracle::Enable,
713) -> Vec<PaletteRow> {
714 let tokens: Vec<String> = query
715 .split_whitespace()
716 .map(str::to_lowercase)
717 .collect();
718 // (score, registry index, row): the index keeps every sort stable.
719 let mut hits: Vec<(u32, usize, PaletteRow)> = Vec::new();
720 for (i, action) in ActionId::ALL.into_iter().enumerate() {
721 let refused = match enable(action) {
722 crate::oracle::Enable::Hidden(_) => continue,
723 crate::oracle::Enable::Yes => None,
724 crate::oracle::Enable::No(why) => Some(why),
725 };
726 let Some(score) = palette_score(action, &tokens) else {
727 continue;
728 };
729 hits.push((score, i, PaletteRow { action, refused }));
730 }
731 if tokens.is_empty() {
732 hits.sort_by_key(|(_, i, row)| (category_rank(row.action.category()), *i));
733 } else {
734 hits.sort_by_key(|(score, i, _)| (*score, *i));
735 }
736 hits.into_iter().map(|(_, _, row)| row).collect()
737}
738
739/// How well `action` answers every word of the query, lower is better, or
740/// `None` when one word matches nothing. A word scores 0 for a label prefix, 1
741/// for a label word prefix, 2 for a label substring and 3 for a category match.
742fn palette_score(action: ActionId, tokens: &[String]) -> Option<u32> {
743 let label = action.label().to_lowercase();
744 let category = action.category().label().to_lowercase();
745 let mut total = 0;
746 for token in tokens {
747 let word_starts = |text: &str| {
748 text.split(|c: char| !c.is_alphanumeric())
749 .any(|w| w.starts_with(token.as_str()))
750 };
751 total += if label.starts_with(token.as_str()) {
752 0
753 } else if word_starts(&label) {
754 1
755 } else if label.contains(token.as_str()) {
756 2
757 } else if word_starts(&category) || category.contains(token.as_str()) {
758 3
759 } else {
760 return None;
761 };
762 }
763 Some(total)
764}
765
766/// Where a category sits in the registry's own order, for grouping an empty
767/// query.
768fn category_rank(category: keymap::Category) -> usize {
769 keymap::Category::ALL
770 .iter()
771 .position(|c| *c == category)
772 .unwrap_or(usize::MAX)
773}
774
775/// The list index of row `sel` as a child of the palette's list, which holds a
776/// heading before each new category when the query is empty. The scroll handle
777/// wants a child index, not a row index.
778pub(crate) fn palette_child_index(rows: &[PaletteRow], sel: usize, grouped: bool) -> usize {
779 if !grouped {
780 return sel;
781 }
782 // Every heading at or above the row: one before each category's first row.
783 let headings = (0..rows.len().min(sel + 1))
784 .filter(|&i| i == 0 || rows[i - 1].action.category() != rows[i].action.category())
785 .count();
786 sel + headings
787}
788
789/// What Enter does on a palette row: a runnable row runs and the palette
790/// closes; a refused row says why (`Player::act`'s toast) and stays open.
791pub(crate) fn palette_closes_on_run(row: PaletteRow) -> bool {
792 row.refused.is_none()
793}
794
795#[cfg(test)]
796mod palette_tests {
797 use super::*;
798 use crate::oracle::Enable;
799
800 fn all_yes(_: ActionId) -> Enable {
801 Enable::Yes
802 }
803
804 #[test]
805 fn empty_query_lists_every_action_grouped_by_category() {
806 let rows = palette_rows("", all_yes);
807 assert_eq!(rows.len(), ActionId::ALL.len());
808 let cats: Vec<usize> = rows
809 .iter()
810 .map(|r| category_rank(r.action.category()))
811 .collect();
812 assert!(cats.windows(2).all(|w| w[0] <= w[1]), "not grouped: {cats:?}");
813 }
814
815 #[test]
816 fn a_label_prefix_ranks_above_a_word_inside_a_label() {
817 let rows = palette_rows("play", all_yes);
818 let first = rows[0].action.label().to_lowercase();
819 assert!(first.starts_with("play"), "best match was {first:?}");
820 assert!(
821 rows.iter().all(|r| {
822 let l = r.action.label().to_lowercase();
823 l.contains("play") || r.action.category().label().to_lowercase().contains("play")
824 }),
825 "a row matches neither label nor category"
826 );
827 }
828
829 #[test]
830 fn matching_is_case_insensitive() {
831 assert_eq!(palette_rows("PLAY", all_yes), palette_rows("play", all_yes));
832 }
833
834 #[test]
835 fn a_category_word_lists_its_actions() {
836 let rows = palette_rows("clips", all_yes);
837 assert!(!rows.is_empty());
838 assert!(rows.iter().all(|r| r.action.category() == keymap::Category::Clips
839 || r.action.label().to_lowercase().contains("clip")));
840 }
841
842 #[test]
843 fn every_word_of_the_query_must_match() {
844 assert!(palette_rows("play xyzzy", all_yes).is_empty());
845 assert!(palette_rows("xyzzy-no-such", all_yes).is_empty());
846 }
847
848 #[test]
849 fn hidden_actions_are_omitted_and_refused_ones_stay_listed() {
850 let rows = palette_rows("", |a| match a {
851 ActionId::Cut => Enable::Hidden("no clip"),
852 ActionId::Copy => Enable::No("nothing selected"),
853 _ => Enable::Yes,
854 });
855 assert!(!rows.iter().any(|r| r.action == ActionId::Cut));
856 let copy = rows.iter().find(|r| r.action == ActionId::Copy).unwrap();
857 assert_eq!(copy.refused, Some("nothing selected"));
858 let play = rows.iter().find(|r| r.action == ActionId::Play).unwrap();
859 assert_eq!(play.refused, None);
860 }
861
862 #[test]
863 fn only_a_runnable_row_closes_the_palette() {
864 let yes = PaletteRow { action: ActionId::Play, refused: None };
865 let no = PaletteRow { action: ActionId::Copy, refused: Some("nothing selected") };
866 assert!(palette_closes_on_run(yes));
867 assert!(!palette_closes_on_run(no));
868 }
869
870 #[test]
871 fn child_index_counts_the_category_headings_above_the_row() {
872 let rows = palette_rows("", all_yes);
873 assert_eq!(palette_child_index(&rows, 0, true), 1);
874 let last = rows.len() - 1;
875 let blocks = keymap::Category::ALL
876 .iter()
877 .filter(|c| rows.iter().any(|r| r.action.category() == **c))
878 .count();
879 assert_eq!(palette_child_index(&rows, last, true), last + blocks);
880 assert_eq!(palette_child_index(&rows, 3, false), 3);
881 }
882}
883
884#[cfg(test)]
885mod keys_search_tests {
886 use super::*;
887
888 /// The KEYS search finds a fixed row by the word a person says for its
889 /// glyph, and by the glyph's own name for `Esc`.
890 #[test]
891 fn a_glyph_row_is_found_by_its_spoken_name() {
892 let keymap = keymap::Keymap::defaults();
893 let finds = |q: &str, chord: &str| {
894 keys_rows_matching(q, &keymap).iter().any(|row| match row {
895 KeyRow::Fixed(i) => keymap::FIXED[*i].chord == chord,
896 _ => false,
897 })
898 };
899 assert!(finds("enter", "↵"));
900 assert!(finds("return", "↵"));
901 assert!(finds("up", "↑"));
902 assert!(finds("left arrow", "← / →"));
903 assert!(finds("escape", "Esc"));
904 assert!(finds("esc", "Esc"));
905 }
906}
907
908/// The 16px icon a menu row wears beside its label (REDESIGN §3.1), where the
909/// verb has an obvious picture; `None` leaves the icon column blank so labels
910/// still line up. Pure decoration -- the label and the key stay the contract.
911pub(crate) fn icon(action: ActionId) -> Option<crate::ui::icons::Icon> {
912 use crate::ui::icons::Icon as I;
913 Some(match action {
914 ActionId::AddFiles => I::Plus,
915 ActionId::OpenProject => I::FolderOpen,
916 ActionId::NewProject => I::Clapperboard,
917 ActionId::ImportSubtitles => I::Captions,
918 ActionId::Save => I::Save,
919 ActionId::ReloadProject => I::RefreshCw,
920 ActionId::Export => I::Upload,
921 ActionId::Screenshot => I::Image,
922 ActionId::Settings => I::Settings,
923 ActionId::Undo => I::Undo2,
924 ActionId::Redo => I::Redo2,
925 ActionId::History => I::Undo2,
926 ActionId::Copy => I::Copy,
927 ActionId::Paste | ActionId::PasteFilePath => I::Clipboard,
928 ActionId::SelectAll => I::Layers,
929 ActionId::Cut => I::Scissors,
930 ActionId::Delete => I::Trash2,
931 ActionId::Lift => I::Eraser,
932 ActionId::Color => I::Palette,
933 ActionId::Transform => I::Move,
934 ActionId::Effects => I::Sparkles,
935 ActionId::Equalizer | ActionId::Mix => I::SlidersHorizontal,
936 ActionId::Speed => I::FastForward,
937 ActionId::Group | ActionId::NestClips => I::Layers,
938 ActionId::Detach => I::Unlink,
939 ActionId::ToggleMute => I::VolumeX,
940 ActionId::SetIn => I::SquareArrowDownRight,
941 ActionId::SetOut => I::SquareArrowDownLeft,
942 ActionId::ZoomIn => I::ZoomIn,
943 ActionId::ZoomOut => I::ZoomOut,
944 ActionId::ZoomFit | ActionId::ZoomToSelection => I::Scan,
945 ActionId::ViewZoom => I::ZoomIn,
946 ActionId::PlaybackQuality => I::Signal,
947 ActionId::GuideStyle => I::Grid3x3,
948 ActionId::GuideMask => I::Image,
949 ActionId::ToggleOutputWindow | ActionId::OutputDisplay => I::Scan,
950 ActionId::ToggleSnap => I::Magnet,
951 // A track's height: the one resize glyph the set has, for the three sizes and the two steps.
952 ActionId::TrackSmall | ActionId::TrackMedium | ActionId::TrackLarge | ActionId::TracksSmaller | ActionId::TracksLarger => I::Scaling,
953 ActionId::AddMarker | ActionId::MarkerHere => I::Flag,
954 ActionId::RenameMarker => I::Type,
955 ActionId::DeleteMarker => I::Trash2,
956 ActionId::PlayheadHere => I::SkipBack,
957 ActionId::Captions => I::Captions,
958 ActionId::Voiceover | ActionId::RecordVoiceover => I::Mic,
959 ActionId::Play => I::Play,
960 ActionId::StepBack => I::StepBack,
961 ActionId::StepForward => I::StepForward,
962 ActionId::GoStart => I::SkipBack,
963 ActionId::GoEnd => I::SkipForward,
964 ActionId::GoToTime => I::Timer,
965 ActionId::Loop => I::Repeat,
966 ActionId::PlayAround => I::Play,
967 ActionId::ToggleWaveforms => I::AudioWaveform,
968 ActionId::ToggleScrubAudio => I::Volume2,
969 ActionId::CompareOff | ActionId::CompareSplit | ActionId::CompareSide => I::Layers,
970 ActionId::AutoColour => I::WandSparkles,
971 ActionId::SaveLook => I::Save,
972 ActionId::ToggleSubtitles => I::Captions,
973 ActionId::ShowActions => I::Search,
974 ActionId::ShowKeys => I::Keyboard,
975 ActionId::About => I::Info,
976 ActionId::Normalize | ActionId::CleanVoice => I::AudioWaveform,
977 ActionId::SubtitleStyle => I::Type,
978 ActionId::Reframe => I::Scaling,
979 ActionId::TrackMask => I::Scan,
980 ActionId::TrimIn => I::ArrowLeftToLine,
981 ActionId::TrimOut => I::ArrowRightToLine,
982 ActionId::Regroup => I::Link,
983 ActionId::LoopTrim => I::Repeat,
984 ActionId::Reverse => I::RotateCcw,
985 ActionId::Dissolve | ActionId::Crossfade | ActionId::TransitionDissolve => I::Sparkles,
986 ActionId::TransitionDipBlack => I::Square,
987 ActionId::TransitionDipWhite => I::Circle,
988 ActionId::TransitionZoom => I::ZoomIn,
989 ActionId::TransitionWipeLeft => I::SquareArrowDownLeft,
990 ActionId::TransitionWipeRight => I::SquareArrowDownRight,
991 ActionId::TransitionWipeUp => I::ArrowUp,
992 ActionId::TransitionWipeDown => I::ArrowDown,
993 ActionId::TransitionSlideLeft => I::ChevronLeft,
994 ActionId::TransitionSlideRight => I::ChevronRight,
995 ActionId::TransitionSlideUp => I::ChevronUp,
996 ActionId::TransitionSlideDown => I::ChevronDown,
997 ActionId::TransitionPushLeft | ActionId::TransitionPushRight | ActionId::TransitionPushUp | ActionId::TransitionPushDown => I::Layers,
998 ActionId::ClipLabel => I::Flag,
999 ActionId::AddVideoLane | ActionId::AddAudioLane | ActionId::AddSubtitleLane | ActionId::NewSequence => I::Plus,
1000 ActionId::RemoveVideoLane | ActionId::RemoveAudioLane | ActionId::RemoveSubtitleLane => I::Minus,
1001 ActionId::RenameLane | ActionId::RenameSequence | ActionId::RenameBin | ActionId::NewTitle => I::Type,
1002 ActionId::DeleteSequence | ActionId::RemoveBin => I::Trash2,
1003 ActionId::DuplicateSequence => I::Copy,
1004 ActionId::NewBin | ActionId::NewBinInside => I::Folder,
1005 ActionId::NewSolid => I::Square,
1006 ActionId::NewGradient => I::Palette,
1007 ActionId::NewCountdown => I::Timer,
1008 ActionId::NewBars => I::Grid3x3,
1009 ActionId::NewTone => I::Volume2,
1010 ActionId::NewBarsAndTone => I::AudioWaveform,
1011 ActionId::NewAdjustment => I::SlidersHorizontal,
1012 ActionId::NewRectangle => I::Square,
1013 ActionId::NewEllipse => I::Circle,
1014 ActionId::NewLine => I::Minus,
1015 ActionId::NewArrow => I::ArrowRight,
1016 ActionId::BreakApart => I::Unlink,
1017 ActionId::CancelExport | ActionId::Deselect => I::CircleX,
1018 ActionId::ClearRange => I::Eraser,
1019 ActionId::RenderInOut => I::SquareArrowDownRight,
1020 ActionId::RenderAll => I::Film,
1021 ActionId::CancelRender => I::CircleX,
1022 ActionId::DeleteRenderFiles => I::Trash2,
1023 ActionId::ClipEnabled | ActionId::ToggleAngleMonitor | ActionId::KeyOpacity => I::Eye,
1024 ActionId::CloseCompound | ActionId::OpenCompound | ActionId::CreateMulticam | ActionId::FlattenMulticam | ActionId::Angle1 => {
1025 I::Layers
1026 }
1027 ActionId::CloseGap | ActionId::TrimInToPlayhead | ActionId::RippleTrimInToPlayhead => I::ArrowLeftToLine,
1028 ActionId::ExtendAudio | ActionId::ExtendVideo | ActionId::TrimOutToPlayhead | ActionId::RippleTrimOutToPlayhead => {
1029 I::ArrowRightToLine
1030 }
1031 ActionId::CollectMedia | ActionId::InsertSource | ActionId::OverwriteSource => I::Download,
1032 ActionId::ExportTimelineOtio | ActionId::ExportTimelineFcpxml | ActionId::ExportTimelineEdl => I::Upload,
1033 ActionId::ImportTimelineOtio => I::Plus,
1034 ActionId::Fillers | ActionId::Silence | ActionId::Visualizer => I::AudioWaveform,
1035 ActionId::CutSelectedWords => I::Trash2,
1036 ActionId::MarkBeats => I::Timer,
1037 ActionId::Fit | ActionId::Resolution => I::Scaling,
1038 ActionId::Fullscreen => I::Scan,
1039 ActionId::FocusPanels => I::Layers,
1040 ActionId::Freeze | ActionId::ShuttleStop => I::Pause,
1041 ActionId::JumpBack | ActionId::PrevSyncPoint => I::SkipBack,
1042 ActionId::JumpForward | ActionId::NextSyncPoint => I::SkipForward,
1043 ActionId::KeyColor | ActionId::Theme | ActionId::AccentColour => I::Palette,
1044 ActionId::KeyEasing => I::Spline,
1045 ActionId::SpeedRampClear => I::Eraser,
1046 ActionId::SpeedRampDown => I::TrendingDown,
1047 ActionId::SpeedRampUp => I::TrendingUp,
1048 ActionId::SpeedRampSlowFastSlow => I::Activity,
1049 ActionId::SpeedRampFastSlowFast => I::Zap,
1050 ActionId::SpeedRampKey => I::Diamond,
1051 ActionId::ToggleProxies | ActionId::ToggleAutoProxies => I::Gauge,
1052 ActionId::KeyPlacement => I::Move,
1053 ActionId::Markers | ActionId::NextMarker | ActionId::PrevMarker => I::FlagTriangleRight,
1054 ActionId::MatchFrame | ActionId::ReplaceEdit => I::Film,
1055 ActionId::NudgeBack | ActionId::NudgeBack10 | ActionId::RollBack | ActionId::SlipBack | ActionId::SlideBack | ActionId::ShuttleBack => I::StepBack,
1056 ActionId::NudgeForward | ActionId::NudgeForward10 | ActionId::RollForward | ActionId::SlipForward | ActionId::SlideForward | ActionId::ShuttleForward => I::StepForward,
1057 ActionId::PasteAttributes | ActionId::PasteAudio | ActionId::PasteColor | ActionId::PasteEffects | ActionId::PasteSpeed | ActionId::PasteTransform => I::Clipboard,
1058 ActionId::SaveVersion | ActionId::SaveTemplate | ActionId::ExportCaptions => I::Save,
1059 ActionId::Versions => I::RotateCcw,
1060 ActionId::ProjectNotes => I::Clipboard,
1061 ActionId::Select | ActionId::SelectForward | ActionId::SelectForwardAll => I::Brackets,
1062 ActionId::SelectNext | ActionId::WalkCutNext | ActionId::WalkCutNext10 => I::ChevronRight,
1063 ActionId::SelectPrev | ActionId::WalkCutPrev | ActionId::WalkCutPrev10 => I::ChevronLeft,
1064 ActionId::VoiceDynamics => I::Mic,
1065 ActionId::VolumeDown | ActionId::VolumeUp => I::Volume2,
1066 _ => return None,
1067 })
1068}
1069
1070/// The one-line plain description a menu row carries on hover, for the two
1071/// trims whose names alone do not say what they do.
1072pub(crate) fn note(action: ActionId) -> Option<&'static str> {
1073 Some(match action {
1074 ActionId::SlipBack | ActionId::SlipForward => "Slip: change which part of the footage shows, keeping the clip in place",
1075 ActionId::SlideBack | ActionId::SlideForward => "Slide: move the clip between its neighbours, keeping its footage",
1076 ActionId::Detach => "Unlink: the picture and the sound of a grouped clip edit separately",
1077 _ => return None,
1078 })
1079}
1080
1081/// The icon beside a submenu row of the bar menus (REDESIGN §3.1).
1082pub(crate) fn icon_sub(name: &str) -> Option<crate::ui::icons::Icon> {
1083 use crate::ui::icons::Icon as I;
1084 Some(match name {
1085 "Paste attributes" => I::Clipboard,
1086 "Export timeline as" => I::Upload,
1087 "New from template" => I::Layers,
1088 "Compare grade" => I::Layers,
1089 "Trim" => I::Scissors,
1090 "Speed" => I::FastForward,
1091 "Adjust" => I::SlidersHorizontal,
1092 "Transitions" => I::Sparkles,
1093 "Compound" => I::Layers,
1094 "Markers" => I::Flag,
1095 "Select" => I::Brackets,
1096 "Captions" => I::Captions,
1097 "Audio" => I::AudioWaveform,
1098 "Tracks" => I::Film,
1099 "Keyframes" => I::KeyRound,
1100 "Go to" => I::SkipForward,
1101 "Sequence" => I::Film,
1102 "Render preview" => I::Zap,
1103 "New" => I::Plus,
1104 "Multicam" => I::Layers,
1105 "Nudge" => I::StepForward,
1106 "Open recent" => I::RotateCcw,
1107 _ => return None,
1108 })
1109}
1110
1111#[cfg(test)]
1112mod icon_tests {
1113 use super::*;
1114 use crate::ui::menubar::Title;
1115
1116 /// Every verb any menu lists wears an icon, so the icon column is never half empty: the
1117 /// bar's menus and flyouts, the clip, track, bench, viewer, tab, bin and dock menus.
1118 #[test]
1119 fn every_menu_row_has_an_icon() {
1120 let mut actions: Vec<ActionId> = Vec::new();
1121 for title in Title::ALL {
1122 actions.extend(title.entries().into_iter().filter_map(|e| e.action()));
1123 }
1124 for list in [
1125 &MENU_ITEMS[..], &BENCH_ITEMS[..], &VIEWER_ITEMS[..], &SEQ_TAB_ITEMS[..], &MARKER_ITEMS[..], &BIN_ITEMS[..], &DOCK_ITEMS[..], &HEAD_ADDS[..],
1126 ] {
1127 actions.extend_from_slice(list);
1128 }
1129 for kind in [LaneKind::Video, LaneKind::Audio, LaneKind::Subtitle] {
1130 actions.extend(crate::oracle::lane_items(Lane { kind, ord: 0 }));
1131 }
1132 let mut missing: Vec<String> = actions.into_iter().filter(|a| icon(*a).is_none()).map(|a| format!("{a:?}")).collect();
1133 missing.sort();
1134 missing.dedup();
1135 assert!(missing.is_empty(), "menu rows without an icon: {missing:?}");
1136 let mut subs: Vec<&str> = Vec::new();
1137 for title in Title::ALL {
1138 fn walk<'a>(list: &'a [crate::ui::menubar::Entry], out: &mut Vec<&'a str>) {
1139 for e in list {
1140 if let crate::ui::menubar::Entry::Sub(name, inner) = e {
1141 out.push(name);
1142 walk(inner, out);
1143 }
1144 }
1145 }
1146 walk(title.layout(), &mut subs);
1147 }
1148 let bare: Vec<&&str> = subs.iter().filter(|n| icon_sub(n).is_none()).collect();
1149 assert!(bare.is_empty(), "flyout rows without an icon: {bare:?}");
1150 // The media row menu has its own verbs: all of them wear one too.
1151 let _ = ROW_ITEMS.map(RowItem::icon);
1152 }
1153}