forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

settings_stance.rs2270 lines, 91.3 KiBHistoryRawDownload
1//! The settings page (user complaint: "we should have a settings page that
2//! we can edit project and editor settings"). Sections, per the split
3//! rule a rubric pass settled -- but never columns at once: they are
4//! tabs of one strip since 2026-09-19 (user: the three-column row asked the
5//! eye to find three anchors in one glance and then to read a column that
6//! began mid-screen). One section shows under the strip; the strip wears the
7//! dock's own tab look ([`crate::ui::dock_stance`]'s `dock_tab`, reproduced
8//! here because that fn is private to its module) and each tab's hover plate
9//! carries the one-line explanation the column head used to trail:
10//!
11//! Four tabs (DESIGN §9.2), each ending on a line that says where its values
12//! are kept:
13//!
14//! - PROJECT: anything that changes the rendered output or is stored in the
15//! `.edith` file -- resolution, fps, sample-rate, the HDR tonemap, the mix,
16//! and the proxy switches. The window's own default answers before a project
17//! is open ([`crate::player::library::load_proxies_pref`]).
18//! - EDITOR: this machine and this window -- the palette and the subtitle font,
19//! kept in `~/.config/edith` like the theme beside them, and the monitoring
20//! level, which is session-only.
21//! - EXPORT: what a delivery is written as. The picture and the sound are this
22//! computer's default ([`load_export_defaults`]); the encoder is the project's.
23//! - KEYS: every shortcut, rebindable, saved in the keybindings file. See
24//! [`keys_section`].
25//!
26//! A row with five answers or fewer shows all of them as chips
27//! ([`crate::ui::choice`]): the tonemap, the two proxy switches, the sound
28//! rate and the encoder seat -- what used to be "press to cycle" rows, where
29//! only the current value showed (UX audit D-1). A longer list (the project's
30//! size and rate, the palette, the export's file) is a dropdown off the row,
31//! which wears a caret so it reads as one. The arrows walk the chip rows and
32//! step them ([`settings_arrow`]); the focused row wears a 1px `ink2` top rule.
33//!
34//! Every row here reuses an opener or a picker this editor already has
35//! ([`Player::open_picker`], [`Player::open_mix`], [`Player::open_subtitle_style`],
36//! [`Player::toggle_proxies`], [`Player::toggle_auto_proxies`]) -- no new card
37//! body, no second source of truth for what a value is or how it is set.
38//! Values apply live through those same doors; there is no Apply button here
39//! to be inconsistent with the rest of the room.
40//!
41//! Seams left for other builders (this task's scope boundary): a finer
42//! fps/sample-rate/tone picker is the same builder's to extend; this page
43//! only ever asks for [`Pick::Fps`]/[`Pick::SampleRate`]/[`Pick::Tone`]
44//! exactly as `inspector.rs`'s legacy panel already does.
45//!
46//! The HDR reference numbers beside the tonemap row (`HDR reference` and
47//! `Content light`) are the *file's* declared light level
48//! ([`engine::colorspace::ContentLight`]), not a monitor fact -- read-only,
49//! since nothing in [`engine::project::Project`] holds a place to persist an
50//! override into.
51
52use crate::keymap::{self, Binding, Chord, Keymap};
53use crate::ui::choice;
54use crate::ui::hitmap;
55use crate::ui::type_scale;
56use crate::*;
57use engine::speech::{self, DeviceChoice};
58use gpui::{AnyElement, KeyDownEvent, SharedString};
59
60/// Which of the page's four sections is showing. Kept on [`Player`] beside
61/// [`Player::settings_open`] rather than in the leaf, so a close and a reopen
62/// return to the section a hand left instead of snapping back to the first --
63/// the dock keeps its own tab pick the same way ([`Player::dock_src_active`]).
64/// Display state and nothing else: no row reads it, and picking a tab writes
65/// no project value, so the pick never lights the ledger.
66#[derive(Clone, Copy, PartialEq, Eq, Debug)]
67pub(crate) enum SettingsTab {
68 Project,
69 Editor,
70 Keys,
71}
72
73/// What the KEYS tab is waiting on. Held on [`Player`] so a capture survives a
74/// repaint and the tab's own key listener can read it. `None` (the field) is
75/// the page at rest: keys the tab does not take fall through to the room, so
76/// escape still closes the page.
77#[derive(Clone, PartialEq, Eq, Debug)]
78pub(crate) enum KeyEdit {
79 /// The filter field was clicked: typed letters go to it.
80 Filtering,
81 /// Row `usize` (an index into [`Keymap::entries`]) takes the next key.
82 Capturing(usize),
83 /// `chord`, typed for row `row`, is already `holder`'s. The row asks,
84 /// inline, before it moves the stroke.
85 Conflict {
86 row: usize,
87 chord: Chord,
88 holder: usize,
89 },
90}
91
92/// One tab of the page's strip (PROJECT/EDITOR/EXPORT), wearing the dock's
93/// own tab look -- [`crate::ui::dock_stance`]'s `dock_tab` verbatim: no pill,
94/// no fill, no rounded button, a 1px `ink1` top rule and `ink1` text mark the
95/// showing tab, the resting one is `ink3`, and the whole row is a
96/// [`hitmap::control`] so the harness can press it. The section's one-line
97/// explanation -- what used to run on after a column head as ambient prose --
98/// is the tab's hover plate (DESIGN §8: a distinction that matters is a plate,
99/// not ambient text).
100fn settings_tab(
101 id: &'static str,
102 label_text: &'static str,
103 explanation: &'static str,
104 tab: SettingsTab,
105 active: bool,
106 cx: &mut Context<Player>,
107) -> impl IntoElement {
108 let style = type_scale::body();
109 crate::ui::kit::kbd_stop(div().id(id))
110 .flex_1()
111 .flex()
112 .items_center()
113 .justify_center()
114 .gap(px(4.))
115 .h(px(36.))
116 .border_b_2()
117 .border_color(rgba(0))
118 .when(active, |d| d.border_color(rgb(crate::ui::theme::tokens().accent)))
119 .cursor_pointer()
120 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| this.set_settings_tab(tab, cx)))
121 .tooltip(crate::ui::widgets::tip_hover(
122 &format!("Show {}", label_text.to_lowercase()),
123 explanation,
124 None,
125 ))
126 .children(hitmap::control(id, label_text, true))
127 .child(
128 div()
129 .font(style.font.clone())
130 .text_size(style.size)
131 .text_color(rgb(if active { crate::ui::theme::tokens().ink1 } else { crate::ui::theme::tokens().ink2 }))
132 .child(label_text),
133 )
134}
135
136/// The shortcut column every settings row ends on: the stroke that also
137/// reaches the setting, dim and right-aligned in a column of its own after the
138/// value (the menus' shortcut column), never glued before it -- "M 100%" read
139/// as one value. A row with no stroke keeps the column empty so the values
140/// above and below it stay on one edge, and an unbound action shows nothing,
141/// never a dash.
142fn chord_col(chord: Option<SharedString>) -> impl IntoElement {
143 div()
144 .flex_none()
145 // No stroke, no column: every row's value then ends on the same edge.
146 .when(chord.is_some(), |d| d.min_w(px(SETTINGS_CHORD_W)))
147 .flex()
148 .items_center()
149 .justify_end()
150 .gap(px(3.))
151 // Each key of the stroke is its own keycap ("Ctrl" "M"), as in menus and tooltips.
152 .children(chord.map(|text| {
153 let parts: Vec<String> = match text.as_ref() {
154 "+" => vec!["+".to_string()],
155 t => t.split('+').filter(|p| !p.is_empty()).map(str::to_string).collect(),
156 };
157 parts.into_iter().map(crate::ui::kit::keycap).collect::<Vec<_>>()
158 }).into_iter().flatten())
159}
160
161/// The least width of [`chord_col`]: one short stroke, so single-letter keys
162/// line up and a longer one (`Ctrl+M`) grows the column rather than wrapping.
163const SETTINGS_CHORD_W: f32 = 52.;
164
165/// `action`'s first stroke, compact, or `None` when it has none: an unbound
166/// action wears no badge (the keymap's own [`Keymap::chord`] answers `--`).
167fn chord_of(player: &Player, action: ActionId) -> Option<SharedString> {
168 player
169 .keymap
170 .entries()
171 .iter()
172 .any(|b| b.action == action)
173 .then(|| player.keymap.chord(action).into())
174}
175
176/// The short plain sentence a value slot carries instead of a bare dash when
177/// there is nothing to show: no project yet, or (`hdr_only`) a project whose
178/// source declares nothing for this row.
179pub(crate) fn no_value_reason(has_project: bool, hdr_only: bool) -> &'static str {
180 match (has_project, hdr_only) {
181 (false, _) => "Open a project first",
182 (true, true) => "Only for HDR sources",
183 (true, false) => "Add a clip first",
184 }
185}
186
187/// A row for a setting with more answers than a row of chips holds: a
188/// click opens its list ([`Pick`]), and the value wears a caret so the row
189/// reads as a dropdown rather than a button that steps. `chord` is the
190/// stroke that also reaches the setting, in the mono chord ink every other
191/// darkroom surface wears it in (DESIGN §4 -- "every command wears its chord,
192/// everywhere it appears"): the palette came here off the spine with its
193/// badge, and keeps it.
194#[allow(clippy::too_many_arguments)]
195fn list_row(
196 id: &'static str,
197 label_text: &'static str,
198 value: impl Into<SharedString>,
199 hint: &'static str,
200 chord: Option<SharedString>,
201 player: &Player,
202 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
203 value_ink: u32,
204) -> impl IntoElement {
205 row_full(
206 id, label_text, value, hint, chord, None, true, player, on_click, value_ink,
207 )
208}
209
210/// The one row body the wrappers share. `chord` is the stroke that also
211/// reaches this setting, drawn in mono `ink3` *beside* the value rather than
212/// over it -- three settings came here off the spine and each one keeps the
213/// badge it wore there (DESIGN §4). `caret` trails the value with `▾` for a
214/// row whose click opens a list, the dock's own fold glyph, so a dropdown
215/// and a door read differently before either is pressed.
216#[allow(clippy::too_many_arguments)]
217fn row_full(
218 id: &'static str,
219 label_text: &'static str,
220 value: impl Into<SharedString>,
221 hint: &'static str,
222 chord: Option<SharedString>,
223 tail: Option<(SharedString, u32)>,
224 caret: bool,
225 player: &Player,
226 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
227 value_ink: u32,
228) -> impl IntoElement {
229 let value: SharedString = value.into();
230 let hint: SharedString = hint.into();
231 let label_style = type_scale::body();
232 let value_style = type_scale::body();
233 let exporting = player.exporting().is_some();
234 crate::ui::kit::kbd_stop(div().id(id))
235 .flex_none()
236 .flex()
237 .items_center()
238 .justify_between()
239 .h(px(CONTROL_H))
240 .px(px(8.))
241 .rounded(px(3.))
242 .tooltip(move |_, cx| cx.new(|_| Tip(hint.clone())).into())
243 .when(exporting, |d| d.opacity(0.4).cursor_not_allowed())
244 .when(!exporting, |d| {
245 d.cursor_pointer()
246 .hover(|s| s.bg(rgb(DARK_RAISED())))
247 .on_click(on_click)
248 })
249 .children(hitmap::control(id, label_text, !exporting))
250 .child(
251 div()
252 .font(label_style.font)
253 .text_size(label_style.size)
254 .text_color(rgb(INK2()))
255 .child(label_text),
256 )
257 .child(
258 div()
259 .flex_none()
260 .flex()
261 .items_baseline()
262 .gap(px(8.))
263 .children(tail.map(|(tail, ink)| {
264 let tail_style = type_scale::caption();
265 div()
266 .font(tail_style.font)
267 .text_size(tail_style.size)
268 .text_color(rgb(ink))
269 .child(tail)
270 }))
271 .child(
272 div()
273 .font(value_style.font.clone())
274 .text_size(value_style.size)
275 .text_color(rgb(value_ink))
276 .child(value),
277 )
278 .children(caret.then(|| {
279 crate::ui::icons::Icon::ChevronDown
280 .el(crate::ui::icons::IconSize::Inline, crate::ui::theme::tokens().ink3)
281 }))
282 .child(chord_col(chord)),
283 )
284}
285
286/// A setting with five answers or fewer, shown as a row of chips rather
287/// than a value that steps on a press: every answer visible, the one in
288/// force lit, any other one click away. Listed in the order the keyboard
289/// walks them ([`choice_rows`]).
290#[derive(Clone, Copy, PartialEq, Eq, Debug)]
291pub(crate) enum ChoiceRow {
292 /// Which rendition HDR media is watched in ([`Preset::ALL`]).
293 Tone,
294 /// The two stand-in switches, Off/On.
295 Proxies,
296 AutoProxies,
297 /// What the speech model runs on ([`device_choices`]).
298 Device,
299}
300
301/// The devices the picker offers: the GPU only when edith-stt has one.
302pub(crate) fn device_choices() -> Vec<DeviceChoice> {
303 match speech::gpu_available() {
304 true => vec![DeviceChoice::Auto, DeviceChoice::Cpu, DeviceChoice::Gpu],
305 false => vec![DeviceChoice::Auto, DeviceChoice::Cpu],
306 }
307}
308
309fn device_label(device: DeviceChoice) -> &'static str {
310 match device {
311 DeviceChoice::Auto => "Auto",
312 DeviceChoice::Cpu => "CPU",
313 DeviceChoice::Gpu => "GPU",
314 }
315}
316
317/// The two words a switch answers with, and the index each one sits at.
318const SWITCH: [&str; 2] = ["Off", "On"];
319
320/// Where a switch's chip is: `Off` first, `On` second.
321pub(crate) fn switch_index(on: bool) -> usize {
322 usize::from(on)
323}
324
325/// The switch a chip index means ([`switch_index`]'s inverse).
326pub(crate) fn switch_on(at: usize) -> bool {
327 at == 1
328}
329
330/// Where `value` sits in `all` -- the chip to light.
331pub(crate) fn index_of<T: PartialEq>(all: &[T], value: T) -> Option<usize> {
332 all.iter().position(|v| *v == value)
333}
334
335impl ChoiceRow {
336 /// Every choice row there is, for the guards below.
337 #[cfg(test)]
338 pub(crate) const ALL: [ChoiceRow; 4] = [
339 ChoiceRow::Tone,
340 ChoiceRow::Proxies,
341 ChoiceRow::AutoProxies,
342 ChoiceRow::Device,
343 ];
344
345 /// The row's chips, in order, each a word read off the same table the
346 /// value is picked from -- so a chip cannot name a value the setter
347 /// does not take.
348 pub(crate) fn labels(self) -> Vec<String> {
349 match self {
350 ChoiceRow::Tone => Preset::ALL
351 .iter()
352 .map(|&p| tone_label(p).to_string())
353 .collect(),
354 ChoiceRow::Proxies | ChoiceRow::AutoProxies => {
355 SWITCH.iter().map(|w| w.to_string()).collect()
356 }
357 ChoiceRow::Device => device_choices().into_iter().map(|d| device_label(d).to_string()).collect(),
358 }
359 }
360
361 /// Whether the row can take a pick right now: the tonemap and the seat
362 /// are the project's, so they need one open; the rest answer always.
363 fn enabled(self, player: &Player) -> bool {
364 match self {
365 ChoiceRow::Tone => player.session.is_some(),
366 ChoiceRow::Proxies | ChoiceRow::AutoProxies => true,
367 ChoiceRow::Device => player.session.is_some(),
368 }
369 }
370}
371
372/// The choice rows a tab shows, top to bottom -- what the arrows walk. The
373/// EXPORT tab's depend on the file: a codec with no rate has no Sound row,
374/// and a song has no Encoder row ([`export_section`]'s own two gates).
375pub(crate) fn choice_rows(tab: SettingsTab, _format: Format) -> Vec<ChoiceRow> {
376 match tab {
377 SettingsTab::Project => vec![ChoiceRow::Device, ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies],
378 SettingsTab::Editor | SettingsTab::Keys => Vec::new(),
379 }
380}
381
382/// Which chip of `row` is in force: `None` where nothing is behind it yet.
383pub(crate) fn current_choice(player: &Player, row: ChoiceRow) -> Option<usize> {
384 match row {
385 ChoiceRow::Tone => player
386 .session
387 .as_ref()
388 .and_then(|session| index_of(&Preset::ALL, session.tone())),
389 ChoiceRow::Device => player
390 .session
391 .as_ref()
392 .and_then(|session| index_of(&device_choices(), session.speech_device())),
393 ChoiceRow::Proxies => Some(switch_index(player.proxies_on)),
394 // The import switch waits on editing copies: while they are off it shows off, and its own
395 // value is kept, so it comes back on when they are turned on again.
396 ChoiceRow::AutoProxies => Some(switch_index(player.auto_proxies_on && player.proxies_on)),
397 }
398}
399
400/// The arrows while the page is up ([`Player::param_card_key`]'s settings
401/// branch): `↑`/`↓` move the focus between the showing tab's choice rows,
402/// `←`/`→` step the focused row's value -- and, with no row focused yet,
403/// only put the focus on the first one, so the first stroke shows where the
404/// keyboard is before anything changes. `false` for any other key, and for
405/// a tab with no choice rows, so those strokes fall through as before.
406pub(crate) fn settings_arrow(player: &mut Player, key: &str, cx: &mut Context<Player>) -> bool {
407 let rows = choice_rows(player.settings_tab, player.format);
408 if rows.is_empty() {
409 return false;
410 }
411 match key {
412 "up" | "down" => {
413 player.settings_focus =
414 choice::move_focus(rows.len(), player.settings_focus, key == "down");
415 }
416 "left" | "right" => {
417 let Some(at) = player.settings_focus.filter(|&at| at < rows.len()) else {
418 player.settings_focus = choice::move_focus(rows.len(), None, true);
419 cx.notify();
420 return true;
421 };
422 let row = rows[at];
423 if let Some(current) = current_choice(player, row) {
424 let next = choice::step(row.labels().len(), current, key == "right");
425 pick_choice(player, row, next, cx);
426 }
427 }
428 _ => return false,
429 }
430 cx.notify();
431 true
432}
433
434/// A choice row: the label, then the chord and the tail where the row has
435/// them, then the chips ([`choice::segmented`]) in the value's slot. No
436/// click on the row itself -- the chips are the controls -- and the row
437/// the keyboard is on wears DESIGN §4.10's 1px `ink2` top rule.
438#[allow(clippy::too_many_arguments)]
439fn choice_row(
440 id: &'static str,
441 label_text: &'static str,
442 hint: &'static str,
443 chord: Option<SharedString>,
444 tail: Option<(SharedString, u32)>,
445 dependent: bool,
446 row: ChoiceRow,
447 player: &Player,
448 cx: &mut Context<Player>,
449) -> impl IntoElement {
450 // The key is told in the tooltip only, never as a chip on the row.
451 // A dependent row (the import switch) waits on the editing-copies switch.
452 let waiting = dependent && !player.proxies_on;
453 let tip: SharedString = match (&chord, waiting) {
454 (_, true) => format!("{hint} (turn on editing copies first)").into(),
455 (Some(key), false) => format!("{hint} ({key})").into(),
456 (None, false) => hint.into(),
457 };
458 let label_style = type_scale::body();
459 let badge_style = type_scale::caption();
460 let exporting = player.exporting().is_some();
461 let enabled = !exporting && !waiting && row.enabled(player);
462 let focused = player.settings_focus.is_some()
463 && index_of(&choice_rows(player.settings_tab, player.format), row) == player.settings_focus;
464 let labels = row.labels();
465 let chips = choice::chips(&labels, current_choice(player, row));
466 let is_switch = labels == SWITCH;
467 // A label too long to share a line with its chips takes a line of its own.
468 let stacked = label_text.chars().count() > 26;
469 let id_sw: &'static str = match row {
470 ChoiceRow::Proxies => "settings-switch-proxies",
471 _ => "settings-switch-auto-proxies",
472 };
473 div()
474 .id(id)
475 .flex_none()
476 .flex()
477 .items_center()
478 .justify_between()
479 .h(px(CONTROL_H))
480 .px(px(8.))
481 .when(dependent, |d| d.pl(px(28.)))
482 .when(stacked, |d| d.flex_col().items_end().h_auto().min_h(px(CONTROL_H)).py(px(4.)).gap(px(4.)))
483 .rounded(px(3.))
484 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
485 .when(focused, |d| d.border_t_1().border_color(rgb(INK2())))
486 .when(exporting || waiting, |d| d.opacity(0.4))
487 .child(
488 div()
489 .when(stacked, |d| d.w_full())
490 .font(label_style.font)
491 .text_size(label_style.size)
492 .text_color(rgb(INK2()))
493 .child(label_text),
494 )
495 .child(
496 div()
497 .flex_none()
498 .flex()
499 .items_center()
500 .gap(px(8.))
501 .children(tail.map(|(tail, ink)| {
502 div()
503 .font(badge_style.font.clone())
504 .text_size(badge_style.size)
505 .text_color(rgb(ink))
506 .child(tail)
507 }))
508 .child(match is_switch {
509 true => {
510 let on = chips.get(1).is_some_and(|c| c.active);
511 let sw = crate::ui::kit::switch(id_sw, on, enabled, None)
512 .children(hitmap::dynamic(
513 move || (format!("{id}-{}", usize::from(!on)), "toggle".to_string()),
514 enabled,
515 ));
516 match enabled {
517 true => sw
518 .cursor_pointer()
519 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
520 cx.stop_propagation();
521 pick_choice(this, row, usize::from(!on), cx)
522 }))
523 .into_any_element(),
524 false => sw.into_any_element(),
525 }
526 }
527 false => choice::segmented(
528 id,
529 chips,
530 enabled,
531 hint,
532 cx,
533 move |this, at, cx| pick_choice(this, row, at, cx),
534 )
535 .into_any_element(),
536 })
537 // The empty key column keeps every row's value on one edge.
538 .child(chord_col(None)),
539 )
540}
541
542/// A size as a person says it: `1920×1080 (1080p)`, `3840×2160 (2160p, 4K)`;
543/// a size with no common name is just its two numbers.
544pub(crate) fn resolution_words(w: u32, h: u32) -> String {
545 // A tall or square frame names its shape, not a height the list has no word for.
546 if w <= h {
547 return crate::export_ui::size_row_label(w, h);
548 }
549 let name = match h {
550 720 => Some("720p"),
551 1080 => Some("1080p"),
552 1440 => Some("1440p"),
553 2160 => Some("2160p (4K)"),
554 _ => None,
555 };
556 match name {
557 Some(name) => format!("{w}\u{d7}{h} ({name})"),
558 None => format!("{w}\u{d7}{h}"),
559 }
560}
561
562/// One quiet, wrapping line under a row: what its choices mean.
563fn hint_line(id: &'static str, text: &'static str) -> impl IntoElement {
564 let style = type_scale::caption();
565 div()
566 .id(id)
567 .flex_none()
568 .px(px(8.))
569 .pb(px(4.))
570 .font(style.font)
571 .text_size(style.size)
572 .text_color(rgb(INK3()))
573 .child(text)
574}
575
576/// PROJECT: the canvas every clip is composed onto, the rate it is cut at,
577/// how HDR looks on a normal screen (only when the project has HDR in it), and
578/// the editing-copies switches. The mix is a live panel (Clip tab), not a row.
579fn project_section(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
580 // corner-cut: no genuine default resolution or fps exists before either
581 // a project opens or a pick is made, so the empty state is a bare dash
582 // in INK3 -- quieter than a real value (INK1), never a noun that reads as one.
583 let resolution = player.session.as_ref().map(PlaybackSession::resolution);
584 let (res_val, res_ink) = match resolution.or(player.pending_settings.0) {
585 Some((w, h)) => (resolution_words(w, h), INK1()),
586 None => (no_value_reason(false, false).to_string(), INK3()),
587 };
588 let (fps_val, fps_ink) = match (player.session.is_some(), player.pending_settings.1) {
589 (true, _) => (format!("{} fps", fps_label(player.fps)), INK1()),
590 (false, Some(fps)) => (format!("{} fps", fps_label(fps)), INK1()),
591 (false, None) => (no_value_reason(false, false).to_string(), INK3()),
592 };
593 // The rate keeps a "Match source" fallback: unlike resolution/fps it
594 // states a real behaviour (derived from the sources) rather than standing
595 // in for a value with nothing behind it.
596 let rate_val = match player
597 .session
598 .as_ref()
599 .map_or(player.pending_settings.2, |s| s.sample_rate())
600 {
601 Some(rate) => format!("{} kHz", f64::from(rate) / 1000.),
602 None => "Match source".to_string(),
603 };
604 // The file's own declared light level is the sign of an HDR source.
605 let has_hdr = player
606 .session
607 .as_ref()
608 .is_some_and(|s| s.content_light().peak().is_some());
609 div()
610 .flex_none()
611 .flex()
612 .flex_col()
613 .gap(px(2.))
614 .child(list_row(
615 "settings-resolution",
616 "Resolution",
617 res_val,
618 "the canvas every clip is composed onto, and the size the export comes out at; click for the list",
619 None,
620 player,
621 cx.listener(|this, event: &ClickEvent, _, cx| this.open_picker(Pick::Resolution, event.position(), cx)),
622 res_ink,
623 ))
624 .child(list_row(
625 "settings-fps",
626 "Frame rate",
627 fps_val,
628 "the rate the whole timeline is cut and written at; click for the list",
629 None,
630 player,
631 cx.listener(|this, event: &ClickEvent, _, cx| this.open_picker(Pick::Fps, event.position(), cx)),
632 fps_ink,
633 ))
634 .child(list_row(
635 "settings-sample-rate",
636 "Audio sample rate",
637 rate_val,
638 "the rate the project's own sound mix is run at; Match source follows the highest rate among the sources, 48 kHz if all are below 44.1 kHz",
639 None,
640 player,
641 cx.listener(|this, event: &ClickEvent, _, cx| this.open_picker(Pick::SampleRate, event.position(), cx)),
642 INK1(),
643 ))
644 .child(still_row(player, cx))
645 .child(speech_model_row(player, cx))
646 .child(choice_row(
647 "settings-speech-device",
648 "Speech device",
649 "where the speech model runs; Auto takes the GPU when this computer has one",
650 None,
651 None,
652 false,
653 ChoiceRow::Device,
654 player,
655 cx,
656 ))
657 // Only a project with HDR in it has anything to choose here.
658 .children(has_hdr.then(|| {
659 choice_row(
660 "settings-tonemap",
661 "When HDR plays on a normal screen",
662 "which look HDR video gets on a normal (SDR) screen; SDR video is untouched",
663 None,
664 None,
665 false,
666 ChoiceRow::Tone,
667 player,
668 cx,
669 )
670 }))
671 .children(has_hdr.then(|| {
672 hint_line(
673 "settings-tonemap-hint",
674 "Faithful stays true to the standard; Balanced looks like a normal player; Bright is the richest colour.",
675 )
676 }))
677 // The proxy switches are the project's once one is open (they are
678 // written into its .edith); the window's default answers before that.
679 // The progress of a copy being made rides as the first switch's tail
680 // ([`Player::proxy_tail`], its own separator dropped).
681 .child(choice_row(
682 "settings-proxies",
683 "Editing copies (proxies)",
684 "Lighter copies for smooth playback; export always uses the originals",
685 chord_of(player, ActionId::ToggleProxies),
686 {
687 let making = player.proxy_tail();
688 let making = making.trim_start_matches([' ', '\u{b7}']).trim();
689 (player.proxies_on && !making.is_empty()).then(|| (making.to_string().into(), INK3()))
690 },
691 false,
692 ChoiceRow::Proxies,
693 player,
694 cx,
695 ))
696 .child(choice_row(
697 "settings-auto-proxies",
698 "Make them on import",
699 "makes a lighter copy of every big video as it is imported",
700 chord_of(player, ActionId::ToggleAutoProxies),
701 None,
702 true,
703 ChoiceRow::AutoProxies,
704 player,
705 cx,
706 ))
707 .child(saved_line("Saved in this project"))
708}
709
710/// The still image length: a typed number of seconds, the number field's own look. A click opens
711/// it for typing; Enter keeps it, Escape drops it. Off until a project is open, since the length
712/// is the project's.
713fn still_row(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
714 let secs = player.session.as_ref().map(PlaybackSession::still_secs);
715 let enabled = secs.is_some();
716 let shown = secs.map_or_else(|| "\u{2013}".to_string(), |s| format!("{s:.1}"));
717 let typing = player.still_num.as_ref();
718 let field = crate::ui::kit::number_field("settings-still-secs", 96., shown, enabled.then_some("s"), typing, enabled);
719 let label_style = type_scale::body();
720 let field = match enabled {
721 false => field.cursor_not_allowed(),
722 true => field.on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.begin_still_num(cx))),
723 };
724 div()
725 .id("settings-still")
726 .flex_none()
727 .flex()
728 .items_center()
729 .justify_between()
730 .h(px(CONTROL_H))
731 .px(px(8.))
732 .tooltip(crate::ui::widgets::tip_hover(
733 "Still image length",
734 "",
735 Some("How long a picture or title card lasts when it is dropped on the timeline; clips already placed keep theirs"),
736 ))
737 .child(
738 div()
739 .font(label_style.font.clone())
740 .text_size(label_style.size)
741 .text_color(rgb(INK2()))
742 .child("Still image length"),
743 )
744 .child(field)
745}
746
747/// The speech model the project transcribes with: Auto, or one of [`speech::MODELS`] from a list.
748/// Models not installed for the device are dimmed in the list.
749fn speech_model_row(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
750 let value = match player.session.as_ref().and_then(|s| s.speech_model()) {
751 Some(model) => crate::creator::model_label(model),
752 None => "Auto".to_string(),
753 };
754 list_row(
755 "settings-speech-model",
756 "Speech model",
757 value,
758 "the model that hears the timeline for captions, fillers and the transcript; Auto takes the best one installed",
759 None,
760 player,
761 cx.listener(|this, event: &ClickEvent, _, cx| this.open_picker(Pick::SpeechModel, event.position(), cx)),
762 INK1(),
763 )
764}
765
766/// A chip of `row` was picked (by a click, or by an arrow through
767/// [`settings_arrow`]): the value at `at`, through the same door the row's
768/// old cycle press and the keymap's own action go through -- the switches
769/// toggle only when the chip differs from the state, so a click on the lit
770/// chip is not a flip. Beside the PROJECT section because three of the five
771/// rows are its, and the doors it opens are the project's.
772fn pick_choice(player: &mut Player, row: ChoiceRow, at: usize, cx: &mut Context<Player>) {
773 match row {
774 ChoiceRow::Tone => {
775 if let Some(&preset) = Preset::ALL.get(at) {
776 player.apply_tone(preset, cx);
777 }
778 }
779 ChoiceRow::Proxies => {
780 if switch_on(at) != player.proxies_on {
781 player.toggle_proxies(cx);
782 }
783 }
784 ChoiceRow::AutoProxies => {
785 if switch_on(at) != player.auto_proxies_on {
786 player.toggle_auto_proxies(cx);
787 }
788 }
789 ChoiceRow::Device => {
790 if let Some(&device) = device_choices().get(at) {
791 player.apply_speech_device(device, cx);
792 }
793 }
794 }
795}
796
797/// The line a section ends on, saying where its values are kept (DESIGN §9.2).
798/// Quiet `ink3` text on the row's own height, so it reads as a note, not a row.
799fn saved_line(text: &'static str) -> impl IntoElement {
800 let style = type_scale::caption();
801 div()
802 .flex_none()
803 .flex()
804 .items_center()
805 .h(px(CONTROL_H))
806 .px(px(8.))
807 .font(style.font)
808 .text_size(style.size)
809 .text_color(rgb(INK3()))
810 .child(text)
811}
812
813/// EDITOR: this machine and this person's own reading preferences. Nothing
814/// here touches the `.edith` file.
815fn editor_section(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
816 div()
817 .flex_none()
818 .flex()
819 .flex_col()
820 .gap(px(2.))
821 // The room's own palette, moved off the spine (user 2026-08-21: the
822 // rail was too crowded to fit its own rows) -- a preference kept in
823 // ~/.config/edith, so the EDITOR section is where it belongs; the
824 // same `Pick::Theme` list `ActionId::Theme` has always opened.
825 .child(list_row(
826 "settings-theme",
827 "Theme",
828 crate::ui::theme::active().label(),
829 "the editor's colours; kept for every project; click for the list",
830 chord_of(player, ActionId::Theme),
831 player,
832 cx.listener(|this, event: &ClickEvent, _, cx| {
833 this.open_picker(Pick::Theme, event.position(), cx)
834 }),
835 INK1(),
836 ))
837 .child(accent_row(player, cx))
838 .child(vivid_row(player, cx))
839 .child(custom_block(player, cx))
840 // The family in force, said (user: "Subtitle font Font…" -- the
841 // value slot carried the door's noun, elided, never the pick). With
842 // nothing picked the window draws its own, which is one word.
843 .child(list_row(
844 "settings-subtitle-style",
845 "Subtitle font",
846 player
847 .sub_family
848 .clone()
849 .unwrap_or_else(|| "Default".to_string()),
850 "the cue plate's own font and size -- kept in ~/.config/edith, never in a project",
851 None,
852 player,
853 cx.listener(|this, _: &ClickEvent, _, cx| this.open_subtitle_style(cx)),
854 INK1(),
855 ))
856 .child(list_row(
857 "settings-autosave",
858 "Autosave",
859 crate::player::library::autosave_label(player.autosave_secs),
860 "how often unsaved work is written beside the project; click for the list",
861 None,
862 player,
863 cx.listener(|this, event: &ClickEvent, _, cx| this.open_picker(Pick::Autosave, event.position(), cx)),
864 INK1(),
865 ))
866 .child(saved_line("Saved on this computer."))
867}
868
869/// "Accent colour": six round swatches, one click picks, the pick is in force
870/// and kept at once. Every swatch has the same 22px box with a 2px border that
871/// is transparent until it is the picked one, so picking never moves a neighbour.
872fn accent_row(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
873 use crate::ui::theme::{self, AccentId};
874 let label_style = type_scale::body();
875 let picked = theme::accent();
876 let exporting = player.exporting().is_some();
877 let mut swatches = div().flex_none().flex().items_center().gap(px(4.));
878 for a in AccentId::ALL {
879 let on = a == picked;
880 let hint = SharedString::from(a.label());
881 swatches = swatches.child(
882 crate::ui::kit::kbd_stop(div().id(("settings-accent", a as usize)))
883 .flex_none()
884 .size(px(22.))
885 .flex()
886 .items_center()
887 .justify_center()
888 .rounded_full()
889 .border_2()
890 .border_color(match on {
891 true => gpui::Hsla::from(rgb(INK1())),
892 false => gpui::transparent_black(),
893 })
894 .cursor_pointer()
895 .tooltip(move |_, cx| cx.new(|_| Tip(hint.clone())).into())
896 .children(hitmap::dynamic(move || ("settings-accent".to_string(), format!("Accent colour {}", a.label())), !exporting))
897 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
898 theme::set_accent(a);
899 this.keep_accent();
900 cx.notify();
901 }))
902 .child(match a == AccentId::Custom && theme::custom_colour().is_none() {
903 // Nothing of its own yet: a plus says "make one".
904 true => div()
905 .size(px(12.))
906 .flex()
907 .items_center()
908 .justify_center()
909 .text_color(rgb(INK2()))
910 .child("+")
911 .into_any_element(),
912 false => div().size(px(12.)).rounded_full().bg(rgb(theme::swatch(a))).into_any_element(),
913 }),
914 );
915 }
916 div()
917 .id("settings-accent-row")
918 .flex_none()
919 .flex()
920 .items_center()
921 .justify_between()
922 .h(px(CONTROL_H))
923 .px(px(8.))
924 .child(
925 div()
926 .font(label_style.font)
927 .text_size(label_style.size)
928 .text_color(rgb(INK2()))
929 .child("Accent colour"),
930 )
931 .child(swatches)
932}
933
934/// The Custom colour and Hue rows while Custom is the accent in force; otherwise one quiet line in
935/// the same space, so picking an accent never moves the rows below.
936fn custom_block(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
937 let live = crate::ui::theme::accent() == crate::ui::theme::AccentId::Custom;
938 let hint = type_scale::caption();
939 div()
940 .flex_none()
941 .h(px(2. * CONTROL_H + 2.))
942 .flex()
943 .flex_col()
944 .gap(px(2.))
945 .when(live, |d| d.child(custom_row(player, cx)).child(hue_row(player, cx)))
946 .when(!live, |d| {
947 d.justify_center().child(
948 div()
949 .px(px(8.))
950 .font(hint.font)
951 .text_size(hint.size)
952 .text_color(rgb(INK3()))
953 .child("Use + to pick any colour"),
954 )
955 })
956}
957
958/// Wraps one of the Custom rows: always on the page so nothing moves, dim and untouchable while
959/// the accent in force is not Custom.
960fn custom_only(live: bool, row: impl IntoElement) -> Div {
961 let wrap = div().relative().flex_none().child(row);
962 match live {
963 true => wrap,
964 false => wrap
965 .opacity(0.4)
966 .child(div().absolute().size_full().top_0().left_0().occlude()),
967 }
968}
969
970/// "Vivid": how strong the accent is, 0 a faint tint, 50 the colours as designed, 100 bold.
971fn vivid_row(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
972 use crate::player::accent::AccentSlider;
973 use crate::ui::widgets::{SliderRow, SliderTyped, slider_fraction, slider_row_inline};
974 let vivid = crate::ui::theme::vivid();
975 let reset: crate::ui::widgets::SliderReset<Player> = Rc::new(|this: &mut Player, _| {
976 crate::ui::theme::set_vivid(crate::ui::theme::VIVID_DEFAULT);
977 this.keep_accent();
978 });
979 div()
980 .id("settings-vivid")
981 .flex_none()
982 .h(px(CONTROL_H))
983 .px(px(8.))
984 .flex()
985 .items_center()
986 .tooltip(crate::ui::widgets::overlay_tip_hover(
987 "Vivid",
988 "",
989 Some("How strong the accent colour is: 0 is a faint tint, 50 keeps the colours as designed, 100 bold."),
990 ))
991 .child(slider_row_inline(
992 SliderRow {
993 id: "settings-vivid-bar",
994 label: "Vivid".into(),
995 value: format!("{vivid} %").into(),
996 fraction: slider_fraction(f32::from(vivid), 0., 100.),
997 changed: vivid != crate::ui::theme::VIVID_DEFAULT,
998 bar: player.accent_vivid_bar.clone(),
999 on_press: Box::new(|this: &mut Player, x: Pixels, cx: &mut Context<Player>| {
1000 this.accent_drag = Some(AccentSlider::Vivid);
1001 this.drag_accent(AccentSlider::Vivid, x, cx);
1002 }),
1003 on_reset: Some(reset),
1004 // Typed as the number the row shows, 0 to 100.
1005 typed: Some(SliderTyped {
1006 lo: 0.,
1007 hi: 100.,
1008 set: Rc::new(|this: &mut Player, v: f64, cx: &mut Context<Player>| {
1009 crate::ui::theme::set_vivid(v.round() as u8);
1010 this.keep_accent();
1011 cx.notify();
1012 }),
1013 }),
1014 },
1015 cx,
1016 ))
1017}
1018
1019/// "Custom colour": the hex of the colour behind the Custom swatch. A valid edit is in force at
1020/// once; an invalid one keeps the last good colour and says what a colour looks like.
1021fn custom_row(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
1022 use crate::ui::kit::{self, ScrubLook};
1023 use crate::ui::theme::{self, AccentId};
1024 let label_style = type_scale::body();
1025 let live = theme::accent() == AccentId::Custom;
1026 let editing = player.accent_hex.as_ref();
1027 let value = match editing {
1028 Some(f) => f.text.clone(),
1029 None => theme::custom_colour().map_or("#______".to_string(), |c| format!("#{c:06x}")),
1030 };
1031 let invalid = editing.is_some_and(|f| !f.text.is_empty() && theme::parse_hex(&f.text).is_none());
1032 let hint_style = type_scale::caption();
1033 let field = kit::scrub_field(
1034 "settings-accent-hex",
1035 76.,
1036 value,
1037 None,
1038 live,
1039 editing.map(|_| ScrubLook::Typing),
1040 )
1041 .cursor(CursorStyle::IBeam)
1042 .tooltip(crate::ui::widgets::tip_hover("Custom colour", "type hex", Some("Six hex digits such as 3ddc97; enter to keep")))
1043 .on_mouse_down(
1044 MouseButton::Left,
1045 cx.listener(|this, _: &MouseDownEvent, _, cx| {
1046 cx.stop_propagation();
1047 this.begin_accent_hex(cx);
1048 }),
1049 );
1050 custom_only(
1051 live,
1052 div()
1053 .id("settings-accent-custom-row")
1054 .flex_none()
1055 .flex()
1056 .items_center()
1057 .justify_between()
1058 .h(px(CONTROL_H))
1059 .px(px(8.))
1060 .child(
1061 div()
1062 .font(label_style.font)
1063 .text_size(label_style.size)
1064 .text_color(rgb(INK2()))
1065 .child("Custom colour"),
1066 )
1067 .child(
1068 div()
1069 .flex()
1070 .items_center()
1071 .gap(px(8.))
1072 .child(
1073 div()
1074 .font(hint_style.font)
1075 .text_size(hint_style.size)
1076 .text_color(rgb(INK3()))
1077 .child(match invalid {
1078 true => "Use six digits, like #3ddc97",
1079 false => "",
1080 }),
1081 )
1082 .child(field),
1083 ),
1084 )
1085}
1086
1087/// The hue of the Custom colour, 0..360, on a rainbow track drawn at the Vivid in force. The
1088/// knob is white over it; the whole row is dim while Custom is not the accent.
1089fn hue_row(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
1090 use crate::player::accent::AccentSlider;
1091 use crate::ui::theme::{self, AccentId};
1092 const THUMB: f32 = 14.;
1093 const STEPS: usize = 24;
1094 let t = theme::tokens();
1095 let live = theme::accent() == AccentId::Custom;
1096 let hue = theme::custom_colour().map_or(0., |c| theme::to_oklch(c).2) as f32;
1097 let fraction = (hue / 360.).clamp(0., 1.);
1098 let vivid = theme::vivid();
1099 // One canvas, stripes from cumulative rounded edges: each stripe ends exactly where the next
1100 // begins, so no fractional width leaves a seam and no overlap doubles up under the dim.
1101 let colours: Vec<u32> = (0..STEPS)
1102 .map(|i| {
1103 let h = (i as f64 + 0.5) / STEPS as f64 * 360.;
1104 theme::vivid_adjust(theme::from_oklch(0.75, 0.14, h), vivid)
1105 })
1106 .collect();
1107 let track = div().relative().w_full().h(px(8.)).rounded(px(4.)).overflow_hidden().child(
1108 gpui::canvas(
1109 |_, _, _| (),
1110 move |bounds, _, window, _| {
1111 let (x0, w) = (f32::from(bounds.origin.x), f32::from(bounds.size.width));
1112 let edge = |i: usize| (x0 + (i as f32 * w / STEPS as f32)).round();
1113 for (i, colour) in colours.iter().enumerate() {
1114 let (l, r) = (edge(i), if i + 1 == STEPS { x0 + w } else { edge(i + 1) });
1115 window.paint_quad(gpui::fill(
1116 gpui::Bounds::new(point(px(l), bounds.origin.y), size(px(r - l), bounds.size.height)),
1117 rgb(*colour),
1118 ));
1119 }
1120 },
1121 )
1122 .size_full(),
1123 );
1124 let label_style = type_scale::body();
1125 let value_style = type_scale::caption();
1126 custom_only(
1127 live,
1128 div()
1129 .id("settings-hue")
1130 .flex_none()
1131 .h(px(CONTROL_H))
1132 .px(px(8.))
1133 .flex()
1134 .items_center()
1135 .gap(px(12.))
1136 .child(
1137 div()
1138 .flex_none()
1139 .w(px(96.))
1140 .font(label_style.font)
1141 .text_size(label_style.size)
1142 .text_color(rgb(t.ink2))
1143 .child("Hue"),
1144 )
1145 .child(
1146 div()
1147 .id("settings-hue-bar")
1148 .relative()
1149 .flex_1()
1150 .min_w(px(0.))
1151 .h(px(HIT_MIN))
1152 .flex()
1153 .items_center()
1154 .cursor_pointer()
1155 .on_mouse_down(
1156 MouseButton::Left,
1157 cx.listener(|this, event: &MouseDownEvent, _, cx| {
1158 this.accent_drag = Some(AccentSlider::Hue);
1159 this.drag_accent(AccentSlider::Hue, event.position.x, cx);
1160 }),
1161 )
1162 .child(crate::timeline_math::bounds_probe(player.accent_hue_bar.clone()))
1163 .child(track)
1164 .child(
1165 div()
1166 .absolute()
1167 .top(px((HIT_MIN - THUMB) / 2.))
1168 .left(relative(fraction))
1169 .ml(px(-THUMB / 2.))
1170 .size(px(THUMB))
1171 .rounded_full()
1172 .border_2()
1173 .border_color(rgb(t.e0))
1174 .bg(rgb(t.ink1)),
1175 ),
1176 )
1177 .child(
1178 div()
1179 .flex_none()
1180 .h(px(crate::layout::redesign::CONTROL_S))
1181 .px(px(8.))
1182 .flex()
1183 .items_center()
1184 .rounded(px(4.))
1185 .bg(rgb(t.e2))
1186 .font(value_style.font)
1187 .text_size(value_style.size)
1188 .text_color(rgb(t.ink2))
1189 .child(format!("{}°", hue.round() as u32)),
1190 ),
1191 )
1192}
1193
1194/// The nine files this editor writes, in the order the Picture row cycles
1195/// them: a codec's two boxes side by side (the container question the export
1196/// card asked in a row of its own, folded into this one), and the sound-only
1197/// formats after the pictures.
1198pub(crate) const PICTURE_CYCLE: [Format; 10] = [
1199 Format::Mp4,
1200 Format::Av1Mp4,
1201 Format::Av1,
1202 Format::Hevc,
1203 Format::HevcMp4,
1204 Format::Wav,
1205 Format::Flac,
1206 Format::Mp3,
1207 Format::Ogg,
1208 Format::Opus,
1209];
1210
1211/// `H.264 · MP4`: the codec by the name it is picked under ([`format_label`])
1212/// and the box it lands in. An audio-only format names itself once -- `WAV ·
1213/// WAV` would be the one field on the line that says nothing.
1214pub(crate) fn picture_label(format: Format) -> String {
1215 match format.has_video() {
1216 true => format!("{} · {}", format_label(format), format.ext().to_uppercase()),
1217 false => format_label(format).to_string(),
1218 }
1219}
1220
1221/// The Picture row's list ([`Pick::Picture`]): the nine files in the order
1222/// of [`PICTURE_CYCLE`], the one in force marked, and beside each one what this
1223/// machine says about it -- a refusal in six words where there is one
1224/// ([`short_reason`]), else the box or `sound only`. Refused rows are still
1225/// listed, since a reason a person can read is what tells them why the pick
1226/// is not theirs to make (DESIGN §8: never hidden).
1227pub(crate) fn picture_choices(
1228 current: Format,
1229 refusal: impl Fn(Format) -> Option<String>,
1230) -> Vec<crate::menus::ChoiceRow> {
1231 PICTURE_CYCLE
1232 .into_iter()
1233 .map(|format| {
1234 let detail: SharedString = match refusal(format) {
1235 Some(why) => short_reason(&why).into(),
1236 None if format.has_video() => "picture and sound".into(),
1237 None => "sound only".into(),
1238 };
1239 (
1240 Choice::Picture(format),
1241 picture_label(format).into(),
1242 detail,
1243 format == current,
1244 )
1245 })
1246 .collect()
1247}
1248
1249/// A refusal in six words, which is what fits beside a value on one row --
1250/// the whole sentence is still said where the pick is actually refused
1251/// ([`Player::set_format`]'s own banner).
1252pub(crate) fn short_reason(why: &str) -> String {
1253 why.split_whitespace().take(6).collect::<Vec<_>>().join(" ")
1254}
1255
1256/// Saves the keybindings file after a change. As with the export pick, a
1257/// failed write is said once and the new keys still work this session.
1258fn persist_keys(player: &mut Player) {
1259 if player.keymap.save().is_err() {
1260 player
1261 .notify_user("Could not save the keys. Check that ~/.config/edith is writable.".into());
1262 }
1263}
1264
1265/// Whether a key name is a modifier alone. A capture waits through these: the
1266/// stroke is the key pressed with them, not the shift on its own.
1267fn is_modifier_key(key: &str) -> bool {
1268 matches!(
1269 key,
1270 "shift" | "control" | "alt" | "platform" | "function" | "capslock"
1271 )
1272}
1273
1274/// Takes `chord` for row `row`. A stroke the file cannot spell is refused and
1275/// the row keeps waiting; a stroke another row holds is offered as a swap, never
1276/// taken silently; any other stroke is simply the row's now.
1277fn capture_key(player: &mut Player, row: usize, chord: Chord) {
1278 if !chord.bindable() {
1279 player.notify_user("That key cannot be bound, so the shortcut is unchanged.".into());
1280 return;
1281 }
1282 match player.keymap.holder(&chord, row) {
1283 Some(holder) => {
1284 player.settings_key_edit = Some(KeyEdit::Conflict { row, chord, holder });
1285 }
1286 None => apply_key(player, row, chord),
1287 }
1288}
1289
1290/// Puts `chord` on row `row`, handing the holder's stroke over when there is
1291/// one, and saves.
1292fn apply_key(player: &mut Player, row: usize, chord: Chord) {
1293 player.keymap.swap_in(row, chord);
1294 player.settings_key_edit = None;
1295 persist_keys(player);
1296}
1297
1298/// Puts one action back to its shipped keys. Any action that lost one of them
1299/// to this is named, so the change is never silent.
1300fn reset_action_keys(player: &mut Player, action: ActionId) {
1301 let displaced = player.keymap.reset_action(action);
1302 player.settings_key_edit = None;
1303 persist_keys(player);
1304 if !displaced.is_empty() {
1305 let names: Vec<&str> = displaced.iter().map(|a| a.label()).collect();
1306 player.notify_user(
1307 format!(
1308 "{} is back to its keys. {} lost the one it took.",
1309 action.label(),
1310 names.join(", ")
1311 )
1312 .into(),
1313 );
1314 }
1315}
1316
1317/// The KEYS tab's keyboard, asked first while its list holds focus (a click on
1318/// the filter or a row gives it focus). A capture takes every key but the
1319/// modifiers alone; the filter takes the letters typed into it. Anything it
1320/// does not take falls through to the room, so escape still closes the page
1321/// and the room's chords still work. `true` when the key was taken.
1322fn settings_key_down(player: &mut Player, event: &KeyDownEvent) -> bool {
1323 let key = event.keystroke.key.as_str();
1324 let mods = &event.keystroke.modifiers;
1325 match player.settings_key_edit.clone() {
1326 Some(KeyEdit::Capturing(row)) => {
1327 if key == "escape" {
1328 player.settings_key_edit = None;
1329 } else if !is_modifier_key(key) {
1330 let chord = Chord {
1331 key: key.to_string(),
1332 ctrl: mods.control,
1333 shift: mods.shift,
1334 alt: mods.alt,
1335 };
1336 capture_key(player, row, chord);
1337 }
1338 true
1339 }
1340 Some(KeyEdit::Conflict { row, chord, .. }) => {
1341 match key {
1342 "escape" => player.settings_key_edit = None,
1343 "enter" => apply_key(player, row, chord),
1344 // Tab and Shift+Tab fall through to the room, which moves the focus ring
1345 // between Swap and Cancel.
1346 _ => return false,
1347 }
1348 true
1349 }
1350 Some(KeyEdit::Filtering) => {
1351 // A chord is the room's, not the filter's.
1352 if mods.control || mods.alt {
1353 return false;
1354 }
1355 match key {
1356 "escape" => {
1357 player.settings_key_edit = None;
1358 player.settings_keys_filter.clear();
1359 }
1360 "enter" => player.settings_key_edit = None,
1361 "backspace" => {
1362 player.settings_keys_filter.pop();
1363 }
1364 _ => {
1365 if let Some(c) = crate::menus::typed(key) {
1366 player.settings_keys_filter.push(c);
1367 }
1368 }
1369 }
1370 true
1371 }
1372 None => false,
1373 }
1374}
1375
1376/// A text button on a KEYS row or its footer: a hit area of its own, the label
1377/// in `ink1`, and `hint` as its tooltip. `key` names it for the harness, and
1378/// the click stops there so the row it sits in does not also take it.
1379fn text_button(
1380 key: String,
1381 label: &'static str,
1382 hint: &'static str,
1383 tab: bool,
1384 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1385) -> impl IntoElement {
1386 let style = type_scale::body();
1387 let hit_key = key.clone();
1388 div()
1389 .id(SharedString::from(key))
1390 .when(tab, crate::ui::kit::kbd_stop)
1391 .flex_none()
1392 .flex()
1393 .items_center()
1394 .h(px(CONTROL_H))
1395 .px(px(8.))
1396 .rounded(px(3.))
1397 .cursor_pointer()
1398 .hover(|s| s.bg(rgb(DARK_RAISED())))
1399 .tooltip(crate::ui::widgets::tip_hover(label, hint, None))
1400 .on_click(move |event, window, cx| {
1401 cx.stop_propagation();
1402 on_click(event, window, cx)
1403 })
1404 .children(hitmap::dynamic(move || (hit_key, label.to_string()), true))
1405 .font(style.font)
1406 .text_size(style.size)
1407 .text_color(rgb(INK1()))
1408 .child(label)
1409}
1410
1411/// One value on a KEYS row, in mono, its ink the caller's: `ink1` for a stroke
1412/// the user changed or a prompt, `ink3` for the shipped one.
1413/// The strokes of one Keys row as keycaps ("Ctrl" "M"), words such as "hold" or
1414/// "drag" plain beside them; an action with no key shows a calm dash.
1415fn keys_cell(text: &str) -> AnyElement {
1416 let t = crate::ui::theme::tokens();
1417 let style = type_scale::caption();
1418 let word = |w: &str| {
1419 div()
1420 .flex_none()
1421 .font(style.font.clone())
1422 .text_size(style.size)
1423 .text_color(rgb(t.ink3))
1424 .child(w.to_string())
1425 .into_any_element()
1426 };
1427 let text = text.trim();
1428 if text.is_empty() || text == "unbound" || text == "--" {
1429 return div()
1430 .flex_none()
1431 .text_color(rgb(t.ink3))
1432 .child("\u{2014}")
1433 .into_any_element();
1434 }
1435 let mut parts: Vec<AnyElement> = Vec::new();
1436 for group in text.split(" or ") {
1437 if !parts.is_empty() {
1438 parts.push(word("or"));
1439 }
1440 for token in group.split_whitespace() {
1441 if token == "/" {
1442 parts.push(word("/"));
1443 continue;
1444 }
1445 let (token, comma) = match token.strip_suffix(',') {
1446 Some(t) if !t.is_empty() => (t, true),
1447 _ => (token, false),
1448 };
1449 for cap in cap_parts(token) {
1450 let plain = cap.len() >= 3 && cap.chars().all(|c| c.is_ascii_lowercase());
1451 parts.push(match plain {
1452 true => word(&cap),
1453 false => crate::ui::kit::keycap(cap).into_any_element(),
1454 });
1455 }
1456 if comma {
1457 parts.push(word(","));
1458 }
1459 }
1460 }
1461 div().flex_none().flex().items_center().gap(px(3.)).children(parts).into_any_element()
1462}
1463
1464/// One stroke split into its keys: `Ctrl+Shift+M` is three, `Ctrl++` is
1465/// "Ctrl" and "+".
1466fn cap_parts(stroke: &str) -> Vec<String> {
1467 let chars: Vec<char> = stroke.chars().collect();
1468 let (mut out, mut cur) = (Vec::new(), String::new());
1469 for (i, c) in chars.iter().enumerate() {
1470 if *c == '+' && !cur.is_empty() && i + 1 < chars.len() {
1471 out.push(std::mem::take(&mut cur));
1472 } else {
1473 cur.push(*c);
1474 }
1475 }
1476 if !cur.is_empty() {
1477 out.push(cur);
1478 }
1479 out
1480}
1481
1482fn key_value(text: String, ink: u32) -> AnyElement {
1483 let style = type_scale::body();
1484 div()
1485 .flex_none()
1486 .font(style.font)
1487 .text_size(style.size)
1488 .text_color(rgb(ink))
1489 .child(text)
1490 .into_any_element()
1491}
1492
1493/// The filter field above the list: a click gives it the keyboard, and typed
1494/// letters then narrow the rows.
1495fn filter_row(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
1496 let t = crate::ui::theme::tokens();
1497 let style = type_scale::body();
1498 let empty = player.settings_keys_filter.is_empty();
1499 let filtering = matches!(player.settings_key_edit, Some(KeyEdit::Filtering));
1500 let shown = match (empty, filtering) {
1501 (true, false) => "Search shortcuts".to_string(),
1502 (_, true) => format!("{}\u{258f}", player.settings_keys_filter),
1503 _ => player.settings_keys_filter.clone(),
1504 };
1505 div()
1506 .id("settings-keys-filter")
1507 .flex_none()
1508 .flex()
1509 .items_center()
1510 .gap(px(6.))
1511 .h(px(28.))
1512 .mb(px(4.))
1513 .px(px(8.))
1514 .rounded(px(4.))
1515 .border_1()
1516 .border_color(match filtering {
1517 true => rgb(t.accent).into(),
1518 false => gpui::hsla(0., 0., 0., 0.),
1519 })
1520 .bg(rgb(t.e2))
1521 .cursor_text()
1522 .tooltip(crate::ui::widgets::tip_hover(
1523 "Search shortcuts",
1524 "click to type",
1525 None,
1526 ))
1527 .on_click(cx.listener(|this, _: &ClickEvent, window, cx| {
1528 this.settings_key_edit = Some(KeyEdit::Filtering);
1529 window.focus(&this.focus_settings);
1530 cx.notify();
1531 }))
1532 .children(hitmap::control("settings-keys-filter", "Filter keys", true))
1533 .font(style.font)
1534 .text_size(style.size)
1535 .text_color(rgb(match empty && !filtering {
1536 true => t.ink3,
1537 false => t.ink1,
1538 }))
1539 .child(crate::ui::icons::Icon::Search.el(crate::ui::icons::IconSize::Inline, t.ink3))
1540 .child(shown)
1541}
1542
1543/// A read-only line on the KEYS list: the label, and the stroke in the dim
1544/// right-aligned key column (empty for an action with none).
1545fn key_static(label: &'static str, chord: String, why: &'static str) -> impl IntoElement {
1546 let label_style = type_scale::body();
1547 div()
1548 .id(SharedString::from(format!("settings-keys-static-{label}")))
1549 .tooltip(crate::ui::widgets::tip_hover(label, "", Some(why)))
1550 .flex_none()
1551 .flex()
1552 .items_center()
1553 .justify_between()
1554 .gap(px(12.))
1555 .min_h(px(CONTROL_H))
1556 .py(px(4.))
1557 .px(px(8.))
1558 .child(
1559 div()
1560 .flex_1()
1561 .min_w(px(0.))
1562 .font(label_style.font)
1563 .text_size(label_style.size)
1564 .text_color(rgb(INK2()))
1565 .child(label),
1566 )
1567 .child(keys_cell(&chord))
1568}
1569
1570/// One stroke on the KEYS list. A click takes the next key for it; while it
1571/// waits the row says so, and a stroke another row holds offers Swap and Cancel
1572/// in place. A changed action carries its own Reset. The value is `ink1` when
1573/// the stroke differs from the shipped one, `ink3` at the shipped one.
1574fn key_row(
1575 row: usize,
1576 binding: &Binding,
1577 edit: Option<&KeyEdit>,
1578 shipped: &Keymap,
1579 player: &Player,
1580 cx: &mut Context<Player>,
1581) -> impl IntoElement {
1582 let action = binding.action;
1583 let label = action.label();
1584 let chord = player.keymap.display(action);
1585 let changed = !player.keymap.is_default(action, shipped);
1586 let label_style = type_scale::body();
1587 let mut right: Vec<AnyElement> = Vec::new();
1588 match edit {
1589 Some(KeyEdit::Capturing(at)) if *at == row => {
1590 right.push(key_value("Press a key, Esc cancels".to_string(), INK1()));
1591 }
1592 Some(KeyEdit::Conflict {
1593 row: at, holder, ..
1594 }) if *at == row => {
1595 let holder_label = player.keymap.entries()[*holder].action.label();
1596 right.push(
1597 div()
1598 .flex_none()
1599 .font(label_style.font.clone())
1600 .text_size(label_style.size)
1601 .text_color(rgb(INK2()))
1602 .child(format!("Used by {holder_label}"))
1603 .into_any_element(),
1604 );
1605 right.push(
1606 text_button(
1607 format!("settings-key-{row}-swap"),
1608 "Swap",
1609 "give this key to this action, and this action's old key to the other",
1610 true,
1611 cx.listener(move |this, _: &ClickEvent, _, cx| {
1612 if let Some(KeyEdit::Conflict { row, chord, .. }) =
1613 this.settings_key_edit.clone()
1614 {
1615 apply_key(this, row, chord);
1616 }
1617 cx.notify();
1618 }),
1619 )
1620 .into_any_element(),
1621 );
1622 right.push(
1623 text_button(
1624 format!("settings-key-{row}-cancel"),
1625 "Cancel",
1626 "keep both keys as they are",
1627 true,
1628 cx.listener(|this, _: &ClickEvent, _, cx| {
1629 this.settings_key_edit = None;
1630 cx.notify();
1631 }),
1632 )
1633 .into_any_element(),
1634 );
1635 }
1636 _ => {
1637 right.push(keys_cell(&chord));
1638 if changed {
1639 right.push(
1640 text_button(
1641 format!("settings-key-{row}-reset"),
1642 "Reset",
1643 "back to the key this action shipped with",
1644 false,
1645 cx.listener(move |this, _: &ClickEvent, _, cx| {
1646 reset_action_keys(this, action);
1647 cx.notify();
1648 }),
1649 )
1650 .into_any_element(),
1651 );
1652 }
1653 }
1654 }
1655 crate::ui::kit::kbd_stop(div().id(("settings-key", row)))
1656 .flex_none()
1657 .flex()
1658 .items_center()
1659 .justify_between()
1660 .gap(px(12.))
1661 .min_h(px(CONTROL_H))
1662 .py(px(4.))
1663 .px(px(8.))
1664 .rounded(px(3.))
1665 .cursor_pointer()
1666 .hover(|s| s.bg(rgb(DARK_RAISED())))
1667 .tooltip(crate::ui::widgets::tip_hover(
1668 label,
1669 &chord,
1670 Some("click, then press the new key"),
1671 ))
1672 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
1673 this.settings_key_edit = Some(KeyEdit::Capturing(row));
1674 window.focus(&this.focus_settings);
1675 cx.notify();
1676 }))
1677 // Enter on the focused row takes the next key, as a click does. Only an idle row
1678 // starts: while a capture or a conflict is up, Enter is that edit's own key (the
1679 // list's listener reads it), and a focused Swap or Cancel never reaches here as Enter.
1680 .on_key_down(cx.listener(move |this, event: &KeyDownEvent, _, cx| {
1681 let mods = &event.keystroke.modifiers;
1682 if event.keystroke.key == "enter" && !mods.control && !mods.alt && this.settings_key_edit.is_none() {
1683 this.settings_key_edit = Some(KeyEdit::Capturing(row));
1684 cx.stop_propagation();
1685 cx.notify();
1686 }
1687 }))
1688 .children(hitmap::dynamic(
1689 move || (format!("settings-key-{row}"), label.to_string()),
1690 true,
1691 ))
1692 .child(
1693 div()
1694 .flex_1()
1695 .min_w(px(0.))
1696 .font(label_style.font)
1697 .text_size(label_style.size)
1698 .text_color(rgb(INK2()))
1699 .child(label),
1700 )
1701 .child(
1702 div()
1703 .flex_none()
1704 .flex()
1705 .items_center()
1706 .gap(px(8.))
1707 .children(right),
1708 )
1709}
1710
1711/// KEYS: every shortcut the keymap holds, one row per action, filterable. A
1712/// click on a row (or Enter on the focused row) takes the next key as its
1713/// stroke; escape cancels. A stroke another row holds is offered as a swap:
1714/// Enter swaps, escape cancels, Tab reaches the two buttons. The footer resets
1715/// every key.
1716///
1717/// The list takes the keyboard through `track_focus`, so its own key listener
1718/// sees each stroke before the room's keymap does. It takes only what the page
1719/// is waiting for ([`settings_key_down`]).
1720fn keys_section(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
1721 let shipped = Keymap::defaults();
1722 let query = player.settings_keys_filter.trim().to_ascii_lowercase();
1723 let edit = player.settings_key_edit.clone();
1724 // The shortcuts sheet's own rows, in its order ([`crate::menus::keys_rows`]):
1725 // a heading per category, then one row per action -- not per stroke, so an
1726 // action with two keys ("? or F1") is listed once -- then the strokes the
1727 // cards answer themselves. A row whose action has a stroke the file can
1728 // spell takes a click to rebind; the rest are read-only, and an action
1729 // with no stroke shows an empty key column, never the word unbound.
1730 let rows: Vec<AnyElement> = crate::menus::keys_rows_matching(&query, &player.keymap)
1731 .into_iter()
1732 .map(|r| match r {
1733 crate::menus::KeyRow::Head(category) => {
1734 let head = type_scale::section();
1735 div()
1736 .flex_none()
1737 .px(px(8.))
1738 .pt(px(10.))
1739 .font(head.font)
1740 .text_size(head.size)
1741 .text_color(rgb(INK3()))
1742 .child(category.label())
1743 .into_any_element()
1744 }
1745 crate::menus::KeyRow::Act(action) => {
1746 let at = player
1747 .keymap
1748 .entries()
1749 .iter()
1750 .position(|b| b.action == action && b.chord.bindable());
1751 match at {
1752 Some(row) => key_row(row, &player.keymap.entries()[row], edit.as_ref(), &shipped, player, cx)
1753 .into_any_element(),
1754 None => key_static(action.label(), String::new(), "No key is set for this. Use it from the menu").into_any_element(),
1755 }
1756 }
1757 crate::menus::KeyRow::Fixed(i) => {
1758 let f = &keymap::FIXED[i];
1759 key_static(f.label, f.chord.to_string(), "A fixed key: it cannot be changed").into_any_element()
1760 }
1761 })
1762 .collect();
1763 div()
1764 .id("settings-keys")
1765 .track_focus(&player.focus_settings)
1766 .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
1767 if settings_key_down(this, event) {
1768 cx.stop_propagation();
1769 cx.notify();
1770 }
1771 }))
1772 .flex_none()
1773 .flex()
1774 .flex_col()
1775 .gap(px(2.))
1776 .child(filter_row(player, cx))
1777 .child(hint_line("settings-keys-hint", "Click a shortcut, then press the new key"))
1778 .children(match rows.is_empty() {
1779 true => vec![crate::ui::kit::dialog_text("No shortcut matches.").px(px(8.)).into_any_element()],
1780 false => rows,
1781 })
1782 .child(
1783 div()
1784 .flex_none()
1785 .flex()
1786 .justify_between()
1787 .items_center()
1788 .child(saved_line("Saved on this computer"))
1789 .child(text_button(
1790 "settings-keys-reset-all".to_string(),
1791 "Reset all",
1792 "every key back to the one it shipped with",
1793 false,
1794 cx.listener(|this, _: &ClickEvent, _, cx| {
1795 this.keymap = Keymap::defaults();
1796 this.settings_key_edit = None;
1797 persist_keys(this);
1798 cx.notify();
1799 }),
1800 )),
1801 )
1802}
1803
1804/// The scroll fade at the foot of the rows, in the plate's own colour (the
1805/// shared fade is the dock's, a different surface).
1806fn plate_more_below(scroll: gpui::ScrollHandle) -> impl IntoElement {
1807 gpui::canvas(
1808 |_, _, _| (),
1809 move |bounds, _, window, _| {
1810 if !crate::export_ui::more_below_shows(f32::from(scroll.offset().y), f32::from(scroll.max_offset().height)) {
1811 return;
1812 }
1813 let plate = rgb(crate::ui::theme::tokens().e3);
1814 let clear = gpui::Rgba { a: 0., ..plate };
1815 window.paint_quad(gpui::fill(
1816 bounds,
1817 gpui::linear_gradient(
1818 180.,
1819 gpui::linear_color_stop(clear, 0.),
1820 gpui::linear_color_stop(plate, 0.7),
1821 ),
1822 ));
1823 },
1824 )
1825 .absolute()
1826 .left_0()
1827 .right_0()
1828 .bottom_0()
1829 .h(px(28.))
1830}
1831
1832/// The centred modal's plate width: one tabbed column's own measure, wide
1833/// enough for the longest row a section carries (the EXPORT range's marks
1834/// line, its chords and all) beside its label -- and no wider. The sheet this
1835/// replaces was `w_full()`, which read every row as a line stretched across
1836/// the room with its value a window away from the label it belongs to.
1837/// [`KEYS_W`]'s class, and a step past its number: these rows carry the same
1838/// label-left/stroke-right anatomy with a value where that card has none.
1839const SETTINGS_W: f32 = 480.;
1840
1841/// The gap the plate keeps to the menu bar above it and the time band below.
1842const SETTINGS_GAP: f32 = 8.;
1843
1844/// The rows' one measure, spent by every tab alike: the tallest section's own
1845/// height (PROJECT's nine rows and its storage line at [`CONTROL_H`], the
1846/// sections' 2px gaps between them), so a tab switch swaps the rows and never resizes the plate
1847/// under the hand (user 2026-09-20: "switching between them feels weird"). A
1848/// shorter section leaves air below its last row; a short window still
1849/// scrolls, the plate's `max_h` cap shrinking this from `min_h(0)`.
1850pub(crate) const SETTINGS_ROWS_H: f32 = 9. * CONTROL_H + 36. + 9. * 2.;
1851
1852/// The plate's height that is not its rows: the dialog's padding and gaps, the title and the tab
1853/// strip. The plate's top is set from it, so the tab strip sits on one line for every tab.
1854const SETTINGS_CHROME_H: f32 = 40. + 28. + CONTROL_H + 12.;
1855
1856/// The Keys list's share of the window's height, and the most it may take: the list is the one
1857/// place a whole shortcut sheet is read, so it gets more room than PROJECT's rows.
1858const KEYS_SHARE: f32 = 0.6;
1859const KEYS_ROWS_MAX: f32 = 560.;
1860
1861/// The dialog layer's own top and bottom padding ([`kit::dialog_layer`]).
1862const LAYER_PAD: f32 = 8.;
1863
1864/// The page itself: a centred modal card, closed by a click away or `esc`
1865/// through [`Player::close_card`] like every other card here.
1866///
1867/// It held to [`crate::ui::stance::below_picture_floor`] from 2026-08-21
1868/// until 2026-09-19: a centred sheet then drew the whole page -- and every
1869/// picker opened off one of its rows -- over the picture (DESIGN §11 check
1870/// 6's occlusion rule, half of the user's own report about menus "not
1871/// aligning with our design"), so the page was anchored over the bench and
1872/// ledger at the window's full width. The user 2026-09-19 retired that read
1873/// -- "this settings section should be a modal instead of covering the
1874/// timeline" -- so the plate is centred again, at one tabbed column's own
1875/// measure: it floats over the room's middle, the timeline beneath is not
1876/// laid under a full-width sheet, and a short window scrolls the rows under
1877/// the strip rather than clipping them. The catcher still paints nothing
1878/// rather than tinting the frame, the same rule the menus it opens follow.
1879///
1880/// Centred on the whole window it still stood over the ruler and the V1/A1
1881/// lanes (its top near y=375 of 1080), so since 2026-10-19 the plate is
1882/// centred in [`settings_area`] -- the band over the viewer that ends above
1883/// the time band, where the export sheet sits -- and capped to it.
1884pub(crate) fn render(
1885 player: &Player,
1886 window_size: Size<Pixels>,
1887 cx: &mut Context<Player>,
1888) -> impl IntoElement {
1889 // The plate's top is one line for every tab: it is centred as PROJECT's rows (the tallest of
1890 // the other tabs) would centre it, and the tab strip stays on that line. Only the Keys tab
1891 // is taller, so its plate grows downward from there -- the strip never moves on a switch.
1892 let wh = f32::from(window_size.height);
1893 let proj_rows = SETTINGS_ROWS_H.min(wh - 2. * SETTINGS_GAP - 150.).max(120.);
1894 let top = LAYER_PAD + ((wh - 2. * LAYER_PAD - (SETTINGS_CHROME_H + proj_rows)) / 2.).max(0.);
1895 let rows_h = match player.settings_tab {
1896 SettingsTab::Keys => {
1897 // A third of the window is the list's, capped; what is left under the plate's
1898 // bottom edge is the most it may take, so the plate stays on screen.
1899 let want = (KEYS_SHARE * wh - SETTINGS_CHROME_H).min(KEYS_ROWS_MAX);
1900 let room = wh - LAYER_PAD - top - SETTINGS_CHROME_H;
1901 want.min(room).max(proj_rows)
1902 }
1903 _ => proj_rows,
1904 };
1905 crate::ui::kit::dialog_layer(0.)
1906 .items_start()
1907 .pt(px(top))
1908 .on_mouse_move(cx.listener(Player::drag_move))
1909 .on_mouse_up(MouseButton::Left, cx.listener(Player::drag_release))
1910 .on_mouse_down(
1911 MouseButton::Left,
1912 cx.listener(|this, _: &MouseDownEvent, window, cx| {
1913 if this.any_text_field() {
1914 this.blur_text_fields(window, cx);
1915 }
1916 // A capture or a filter is the page's own; a click away ends it
1917 // with the page, so the next opening starts at rest.
1918 this.settings_key_edit = None;
1919 this.settings_open = false;
1920 cx.notify();
1921 cx.stop_propagation();
1922 }),
1923 )
1924 .child(
1925 crate::ui::kit::dialog("settings-card", SETTINGS_W)
1926 .max_w(relative(1.))
1927 // The card sits over the room's own capture, so a press in it leaves
1928 // a field (the accent's hex) itself; the field's click then reopens it.
1929 .capture_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, cx| {
1930 if this.any_text_field() {
1931 this.blur_text_fields(window, cx);
1932 }
1933 }))
1934 .gap(px(6.))
1935 .child(crate::ui::kit::dialog_title("Settings"))
1936 .child(
1937 div()
1938 .id("settings-tabs")
1939 .flex_none()
1940 .flex()
1941 .child(settings_tab(
1942 "settings-tab-project",
1943 "Project",
1944 "stored in the .edith file",
1945 SettingsTab::Project,
1946 player.settings_tab == SettingsTab::Project,
1947 cx,
1948 ))
1949 .child(settings_tab(
1950 "settings-tab-editor",
1951 "Editor",
1952 "this machine, this window",
1953 SettingsTab::Editor,
1954 player.settings_tab == SettingsTab::Editor,
1955 cx,
1956 ))
1957 .child(settings_tab(
1958 "settings-tab-keys",
1959 "Keys",
1960 "every shortcut, and how to rebind it",
1961 SettingsTab::Keys,
1962 player.settings_tab == SettingsTab::Keys,
1963 cx,
1964 )),
1965 )
1966 // The showing section alone, on the plate's whole width: the
1967 // three columns this row used to hold side by side -- each
1968 // with its own head and a hairline down its left edge -- asked
1969 // the eye to find three anchors at once and then to read a
1970 // column that began mid-screen. The strip above is the way
1971 // between them; there is one section in the tree at a time, so
1972 // a row that is not showing cannot be reached by a tab stroke
1973 // or by the pointer either. The area's height is the tallest
1974 // section's own ([`SETTINGS_ROWS_H`]), so a tab switch swaps
1975 // the rows and never resizes the plate under the hand.
1976 // A short window shortens the rows (the plate's
1977 // `max_h`); the export sheet's fade says when more
1978 // of them is below.
1979 .child(
1980 div()
1981 .relative()
1982 .h(px(rows_h))
1983 .min_h(px(0.))
1984 .flex()
1985 .flex_col()
1986 .child(
1987 div()
1988 .id("settings-rows")
1989 .flex_1()
1990 .min_h(px(0.))
1991 .overflow_y_scroll()
1992 .track_scroll(&player.settings_rows_scroll)
1993 .child(match player.settings_tab {
1994 SettingsTab::Project => project_section(player, cx).into_any_element(),
1995 SettingsTab::Editor => editor_section(player, cx).into_any_element(),
1996 SettingsTab::Keys => keys_section(player, cx).into_any_element(),
1997 }),
1998 )
1999 .child(plate_more_below(player.settings_rows_scroll.clone())),
2000 ),
2001 )
2002}
2003
2004#[cfg(test)]
2005mod tests {
2006 use super::*;
2007
2008 /// The chip rows, their words and their tabs.
2009 #[test]
2010 fn every_choice_row_is_five_answers_or_fewer_each_a_plain_word() {
2011 for row in ChoiceRow::ALL {
2012 let labels = row.labels();
2013 assert!(
2014 (2..=5).contains(&labels.len()),
2015 "{row:?} has {} answers -- chips are for five or fewer",
2016 labels.len()
2017 );
2018 for label in &labels {
2019 assert!(
2020 !label.is_empty() && !label.contains('?'),
2021 "{row:?}: {label:?}"
2022 );
2023 assert!(
2024 label.chars().count() <= 9,
2025 "{row:?}: {label:?} is not a chip's word"
2026 );
2027 }
2028 }
2029 }
2030
2031 /// Picking a chip sets the value it names: the index into the row is the
2032 /// index into the table the setter reads, both ways.
2033 #[test]
2034 fn a_chip_index_names_the_value_it_sets_and_back() {
2035 // The renditions, by the names every other surface calls them.
2036 assert_eq!(ChoiceRow::Tone.labels(), ["Faithful", "Balanced", "Bright"]);
2037 assert_eq!(index_of(&Preset::ALL, Preset::Vivid), Some(2));
2038 // A switch: Off is the first chip, On the second, and back.
2039 assert_eq!(ChoiceRow::Proxies.labels(), ["Off", "On"]);
2040 for on in [false, true] {
2041 assert_eq!(switch_on(switch_index(on)), on);
2042 }
2043 // A value no table holds lights nothing rather than a wrong chip.
2044 assert_eq!(index_of(&Preset::ALL, Preset::Vivid), Some(2));
2045 assert_eq!(index_of(&[1, 2], 9), None);
2046 }
2047
2048 /// The current value is the lit chip -- exactly one, and the right one.
2049 #[test]
2050 fn the_chip_in_force_is_the_one_lit() {
2051 let chips = choice::chips(&ChoiceRow::Tone.labels(), index_of(&Preset::ALL, Preset::Standard));
2052 let lit: Vec<&str> = chips
2053 .iter()
2054 .filter(|c| c.active)
2055 .map(|c| c.label.as_ref())
2056 .collect();
2057 assert_eq!(lit, ["Balanced"]);
2058 // Nothing behind the setting (no project for the tonemap): no chip lit.
2059 let chips = choice::chips(&ChoiceRow::Tone.labels(), None);
2060 assert!(chips.iter().all(|c| !c.active));
2061 }
2062
2063 /// `→` off the last chip is the first, `←` off the first is the last: the
2064 /// arrows cycle a row the way the press it replaces did.
2065 #[test]
2066 fn the_arrows_cycle_a_row_round() {
2067 for row in ChoiceRow::ALL {
2068 let n = row.labels().len();
2069 let mut at = 0;
2070 for _ in 0..n {
2071 at = choice::step(n, at, true);
2072 }
2073 assert_eq!(at, 0, "{row:?}: a full walk is a wrap");
2074 assert_eq!(choice::step(n, 0, false), n - 1, "{row:?}: ← wraps");
2075 }
2076 }
2077
2078 /// Each tab's chip rows, in the order the keyboard walks them; the EXPORT
2079 /// tab's follow the file the way its rows are mounted.
2080 #[test]
2081 fn the_choice_rows_sit_in_the_tabs_they_belong_to() {
2082 assert_eq!(
2083 choice_rows(SettingsTab::Project, Format::Mp4),
2084 [ChoiceRow::Device, ChoiceRow::Tone, ChoiceRow::Proxies, ChoiceRow::AutoProxies]
2085 );
2086 assert!(choice_rows(SettingsTab::Editor, Format::Mp4).is_empty());
2087 assert!(choice_rows(SettingsTab::Keys, Format::Mp4).is_empty());
2088 // The focus walks whatever the tab has, and nothing on an empty tab.
2089 assert_eq!(choice::move_focus(3, None, true), Some(0));
2090 assert_eq!(choice::move_focus(0, None, true), None);
2091 }
2092
2093 /// The page fits a 1280x720 window with every chip row on one line: the
2094 /// plate's height under the cap, and each row's label, badge, tail and
2095 /// chips inside [`SETTINGS_W`] at a generous per-glyph measure.
2096 #[test]
2097 fn the_panel_and_its_chip_rows_fit_at_1280_by_720() {
2098 // PROJECT at its tallest (HDR row and its hint, both switches, the
2099 // storage line) still fits the rows area.
2100 let project_tallest = 9. * CONTROL_H + 36. + 9. * 2.;
2101 assert!(project_tallest <= SETTINGS_ROWS_H);
2102 // Width: a generous measure per glyph, so a real font only has room
2103 // to spare. (label, chord, tail, row)
2104 let keys = Keymap::defaults();
2105 let label_w = |text: &str| text.chars().count() as f32 * 9.;
2106 let mono_w = |text: &str| text.chars().count() as f32 * 8.;
2107 let _ = keys;
2108 // (label, tail, row); the key lives in the tooltip, the column is empty.
2109 let rows: [(&str, &str, ChoiceRow); 4] = [
2110 ("Speech device", "", ChoiceRow::Device),
2111 ("When HDR plays on a normal screen", "", ChoiceRow::Tone),
2112 ("Editing copies (proxies)", "100%", ChoiceRow::Proxies),
2113 (" Make them on import", "", ChoiceRow::AutoProxies),
2114 ];
2115 for (label, tail, row) in rows {
2116 let chord = String::new();
2117 let parts = 1 + usize::from(!chord.is_empty()) + usize::from(!tail.is_empty());
2118 let label = if label.chars().count() > 26 { "" } else { label };
2119 let w = 16.
2120 + label_w(label)
2121 + mono_w(&chord)
2122 + mono_w(tail)
2123 + parts as f32 * 8.
2124 + choice::row_w(&row.labels());
2125 assert!(
2126 w <= SETTINGS_W,
2127 "{row:?} asks {w}px of a {SETTINGS_W}px plate -- its chips wrap"
2128 );
2129 }
2130 }
2131
2132 /// The chips drive the same doors the keys and the old press did, the
2133 /// arrows reach the page, and the focused row is drawn.
2134 #[test]
2135 fn the_chip_rows_drive_the_same_setters_and_the_arrows_reach_them() {
2136 let page = include_str!("settings_stance.rs");
2137 let start = page.find("fn pick_choice(").expect("the chip dispatcher");
2138 let body = &page[start..start + page[start..].find("\n}\n").expect("its end")];
2139 for door in [
2140 "apply_tone(",
2141 "toggle_proxies(",
2142 "toggle_auto_proxies(",
2143 ] {
2144 assert!(body.contains(door), "a chip row no longer opens {door}");
2145 }
2146 // No settings row cycles on a press any more: the rows with few
2147 // answers are chips, the rest open their list.
2148 let rows = &page[..page.find("#[cfg(test)]\nmod tests").expect("the tests")];
2149 for press in [
2150 "cycle_export_picture()",
2151 "cycle_audio_kbps()",
2152 "cycle_encoder(",
2153 ] {
2154 assert!(
2155 !rows.contains(press),
2156 "a settings row still cycles on a press: {press}"
2157 );
2158 }
2159 // The focused row wears the 1px ink2 top rule (DESIGN §4.10).
2160 let start = page.find("fn choice_row(").expect("the chip row");
2161 let body = &page[start..start + page[start..].find("\n}\n").expect("its end")];
2162 assert!(body.contains(".when(focused, |d| d.border_t_1().border_color(rgb(INK2())))"));
2163 assert!(body.contains("choice::segmented("));
2164 // The room's key branch hands the arrows to the page.
2165 let cards = include_str!("../player/cards.rs");
2166 assert!(
2167 cards.contains("settings_arrow(self, key, cx)"),
2168 "the arrows never reach the page"
2169 );
2170 }
2171
2172 /// The Picture list: the nine files in `c`'s order, one marked, a refused
2173 /// one carrying its reason rather than vanishing.
2174 #[test]
2175 fn the_picture_list_is_the_cycle_with_its_refusals_said() {
2176 let rows = picture_choices(Format::Av1, |f| {
2177 (f == Format::Hevc).then(|| {
2178 "HEVC needs the VA-API plugin, which this machine has not built".to_string()
2179 })
2180 });
2181 assert_eq!(rows.len(), PICTURE_CYCLE.len());
2182 let picked: Vec<&SharedString> = rows.iter().filter(|r| r.3).map(|r| &r.1).collect();
2183 assert_eq!(picked.len(), 1);
2184 assert_eq!(picked[0].as_ref(), "AV1 · MKV");
2185 let hevc = rows
2186 .iter()
2187 .find(|r| r.0 == Choice::Picture(Format::Hevc))
2188 .expect("HEVC");
2189 assert_eq!(hevc.2.as_ref(), "HEVC needs the VA-API plugin, which");
2190 let wav = rows
2191 .iter()
2192 .find(|r| r.0 == Choice::Picture(Format::Wav))
2193 .expect("WAV");
2194 assert_eq!(wav.2.as_ref(), "sound only");
2195 }
2196
2197 #[test]
2198 fn a_modifier_alone_is_not_a_stroke() {
2199 for key in ["shift", "control", "alt", "platform", "function"] {
2200 assert!(is_modifier_key(key), "{key}");
2201 }
2202 assert!(!is_modifier_key("s"));
2203 assert!(!is_modifier_key("escape"));
2204 }
2205
2206 #[test]
2207 fn the_keys_filter_matches_a_label_or_a_chord_and_nothing_else() {
2208 let keys = Keymap::defaults();
2209 let has = |q: &str| {
2210 crate::menus::keys_rows_matching(q, &keys)
2211 .iter()
2212 .any(|r| matches!(r, crate::menus::KeyRow::Act(ActionId::Save)))
2213 };
2214 assert!(has("save"));
2215 assert!(has("ctrl+s"));
2216 assert!(!has("zzz"));
2217 }
2218
2219 /// The Keys tab is the shortcuts sheet's rows: one row per action, so
2220 /// "Keyboard shortcuts" (`?` and F1) is listed once, and the key column
2221 /// never says "unbound".
2222 #[test]
2223 fn the_keys_tab_lists_each_action_once_and_never_says_unbound() {
2224 let keys = Keymap::defaults();
2225 let rows = crate::menus::keys_rows_matching("", &keys);
2226 let shows = rows
2227 .iter()
2228 .filter(|r| matches!(r, crate::menus::KeyRow::Act(ActionId::ShowKeys)))
2229 .count();
2230 assert_eq!(shows, 1);
2231 let page = include_str!("settings_stance.rs");
2232 let body = &page[..page.find("#[cfg(test)]\nmod tests").unwrap()];
2233 // Only the key cell may name the absence (it draws a dash for it).
2234 let at = body.find("fn keys_cell(").unwrap();
2235 let body = format!("{}{}", &body[..at], &body[body[at..].find("\n}\n").unwrap() + at..]);
2236 assert!(!body.contains("\"unbound\""));
2237 }
2238
2239 /// No value slot carries a bare dash: an empty row gives a plain reason.
2240 /// And a stroke is drawn after the value it belongs to, never before it
2241 /// ("M 100%", "c H.264" read as one value).
2242 #[test]
2243 fn no_value_is_a_bare_dash_and_no_stroke_leads_a_value() {
2244 let page = include_str!("settings_stance.rs");
2245 let body = &page[..page.find("#[cfg(test)]\nmod tests").unwrap()];
2246 // The key cell is the one place a dash is the answer: an action with no key.
2247 let at = body.find("fn keys_cell(").unwrap();
2248 let body = format!("{}{}", &body[..at], &body[body[at..].find("\n}\n").unwrap() + at..]);
2249 assert!(!body.contains("(\"\u{2014}\".to_string()"));
2250 assert!(!body.contains("(\"\u{2014}\""));
2251 assert!(!body.contains("\"--\""));
2252 for (project, hdr) in [(false, false), (false, true), (true, true), (true, false)] {
2253 let why = no_value_reason(project, hdr);
2254 assert!(why.split_whitespace().count() >= 3, "{why}");
2255 assert!(!why.starts_with(|c: char| c.is_ascii_alphabetic() && why.chars().nth(1) == Some(' ')));
2256 }
2257 // chord_col is the last child of each row body, after the value.
2258 for f in ["fn row_full(", "fn choice_row("] {
2259 let at = page.find(f).unwrap();
2260 let end = page[at..].find("\n}\n").unwrap() + at;
2261 let src = &page[at..end];
2262 let call = src.find("chord_col(chord)").or_else(|| src.find("chord_col(None)")).unwrap_or_else(|| panic!("{f} lacks the chord column"));
2263 let value = src.rfind(".child(value)").or_else(|| src.find("choice::segmented(")).unwrap();
2264 assert!(call > value, "{f}: the stroke comes before the value");
2265 }
2266 // An unbound action wears no badge.
2267 let keys = Keymap::defaults();
2268 assert!(keys.entries().iter().any(|b| b.action == ActionId::ToggleMute));
2269 }
2270}