forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

popup.rs489 lines, 21.1 KiBHistoryRawDownload
1//! The one popup look: the menu bar's dropdowns, the clip and media
2//! right-click menus and every other hanging list draw their plate, rows and
3//! rule lines through here, so surface, border, radius, padding, row height,
4//! type, hover and the right-aligned shortcut column cannot drift apart.
5//!
6//! The plate fits its content: [`popup_w`] measures the widest label beside
7//! the widest shortcut, so nothing is ever cut off.
8
9use crate::layout::{MENU_PAD, MENU_ROW_H, MENU_W};
10use crate::ui::type_scale::{self, Typeset};
11use crate::ui::widgets::overlay_tip_hover;
12use crate::*;
13
14/// The widest a plate grows. A longer value (a file path in a details side)
15/// truncates in its own column; the label never does.
16pub(crate) const POPUP_MAX_W: f32 = 460.;
17/// The gap between the label and the shortcut column.
18const COL_GAP: f32 = 24.;
19/// Each row's side padding.
20const ROW_PX: f32 = 8.;
21/// The column a check mark takes on a plate whose rows can be switches.
22pub(crate) const CHECK_W: f32 = 16.;
23
24/// An upper bound on the width of `text` set at `size_px`. Archivo averages
25/// about 0.55 em a glyph and the mono face 0.6 em; the factors here sit a
26/// little above both, so a plate sized by this never cuts a word.
27pub(crate) fn text_w(text: &str, size_px: f32, mono: bool) -> f32 {
28 let em = if mono { 0.62 } else { 0.58 };
29 text.chars().count() as f32 * size_px * em
30}
31
32/// The plate width for rows of `(label, shortcut)`: the widest label (measured
33/// at the row's `body_strong`), the gap, the widest shortcut, the paddings, plus
34/// the icon / check column (16px and its gap) when `checks`. Pass `checks: true`
35/// whenever any row is built with `checked: Some(..)` ([`popup_row_icon`]) -- an
36/// icon row counts -- or its label would be squeezed into a wrap.
37pub(crate) fn popup_w<'a>(rows: impl IntoIterator<Item = (&'a str, &'a str)>, checks: bool) -> f32 {
38 let (mut label, mut hint) = (0f32, 0f32);
39 for (l, h) in rows {
40 // Rows set the label in `body_strong` (medium weight), a touch wider than regular.
41 label = label.max(text_w(l, type_scale::BODY_PX, false) * 1.06);
42 hint = hint.max(text_w(h, type_scale::CAPTION_PX, false));
43 }
44 let gap = if hint > 0. { COL_GAP } else { 0. };
45 let check = if checks { CHECK_W + 8. } else { 0. };
46 // 2 for the plate's border.
47 let w = MENU_PAD * 2. + 2. + ROW_PX * 2. + check + label + gap + hint;
48 w.clamp(MENU_W * 0.75, POPUP_MAX_W)
49}
50
51/// The plate: absolute at `(x, y)`, `w` wide.
52pub(crate) fn popup_plate(id: &'static str, x: f32, y: f32, w: f32) -> Stateful<Div> {
53 // Occluding: without it the click-away backdrop under a dropdown counted as
54 // hovered too and closed the menu on the press, before a row's click landed.
55 crate::interact::menu_plate(id, x, y).w(px(w)).occlude()
56}
57
58/// The rule line between groups, the same everywhere.
59pub(crate) fn popup_rule() -> AnyElement {
60 div()
61 .flex_none()
62 .my(px(4.))
63 .h(px(1.))
64 .bg(rgba(crate::ui::theme::tokens().line))
65 .into_any_element()
66}
67
68/// One row: the label left, the shortcut right-aligned in mono `ink3`, and
69/// nothing at all where there is no shortcut. `checked` is `Some` on a plate
70/// that has switches (the check column is then reserved on every row, so the
71/// labels line up). A disabled row is dimmed and says why on hover, never as
72/// text in the row. The caller adds the click and the hover colour of an
73/// enabled row ([`popup_hover`]).
74pub(crate) fn popup_row(
75 id: impl Into<gpui::ElementId>,
76 label: impl Into<SharedString>,
77 hint: impl Into<SharedString>,
78 checked: Option<bool>,
79 why: Option<&str>,
80) -> Stateful<Div> {
81 popup_row_icon(id, label, hint, checked, None, why)
82}
83
84/// [`popup_row`] with the 16px icon column (REDESIGN §3.1): `checked` opens the
85/// column (a tick when `Some(true)`), and `icon` fills it for rows that are not
86/// switches. Rows with neither leave the column blank so labels line up.
87pub(crate) fn popup_row_icon(
88 id: impl Into<gpui::ElementId>,
89 label: impl Into<SharedString>,
90 hint: impl Into<SharedString>,
91 checked: Option<bool>,
92 icon: Option<crate::ui::icons::Icon>,
93 why: Option<&str>,
94) -> Stateful<Div> {
95 use crate::ui::icons::{Icon, IconSize};
96 let t = crate::ui::theme::tokens();
97 let label: SharedString = label.into();
98 let hint: SharedString = hint.into();
99 let disabled = why.is_some();
100 let ink = if disabled { t.ink4 } else { t.ink1 };
101 let mut row = div()
102 .id(id)
103 .flex()
104 .flex_none()
105 .items_center()
106 .justify_between()
107 .gap(px(COL_GAP))
108 .h(px(MENU_ROW_H))
109 .px(px(ROW_PX))
110 .rounded(px(4.))
111 .type_style(type_scale::body_strong())
112 .text_color(rgb(ink))
113 .child(
114 div()
115 .flex()
116 .items_center()
117 .gap(px(8.))
118 .min_w(px(0.))
119 .flex_none()
120 .whitespace_nowrap()
121 .when_some(checked, |d, on| {
122 d.child(
123 div().flex_none().w(px(CHECK_W)).h(px(CHECK_W)).children(
124 match (on, icon) {
125 (true, _) => Some(Icon::Check.el(IconSize::Inline, t.accent)),
126 (false, Some(i)) => {
127 Some(i.el(IconSize::Inline, if disabled { t.ink4 } else { t.ink2 }))
128 }
129 (false, None) => None,
130 },
131 ),
132 )
133 })
134 .child(div().min_w(px(0.)).whitespace_nowrap().child(label.clone())),
135 );
136 if !hint.is_empty() {
137 row = row.child(
138 div()
139 .flex_none()
140 .max_w(px(300.))
141 .truncate()
142 .type_style(type_scale::caption())
143 .text_color(rgb(if disabled { t.ink4 } else { t.ink3 }))
144 .child(hint),
145 );
146 }
147 match why {
148 Some(why) => row
149 .cursor_not_allowed()
150 .tooltip(overlay_tip_hover(&label, "", Some(why))),
151 None => row.cursor_pointer().when(!disabled, popup_hover),
152 }
153}
154
155pub(crate) fn shortcut(keymap: &crate::keymap::Keymap, action: ActionId) -> String {
156 match keymap.display(action) {
157 s if s == "unbound" || s == "--" => String::new(),
158 // The column is narrow; the long spelling is in the shortcuts list.
159 s if s == "Delete or Backspace" => "Del".into(),
160 // A menu column has room for one key; the sheet lists every stroke.
161 s => s.split(" or ").next().unwrap_or(&s).to_string(),
162 }
163}
164
165/// The hover colour of a live row.
166pub(crate) fn popup_hover(row: Stateful<Div>) -> Stateful<Div> {
167 row.hover(|s| s.bg(rgb(BG_HOVER())))
168}
169
170/// The About box's width. Its height hugs its content.
171pub(crate) const ABOUT_W: f32 = 360.;
172
173impl Player {
174 /// The modal sheet that is up, if any, in the shared dialog shell: Help,
175 /// About edith (the app mark, the name, the version and the licence line,
176 /// centred), or the shortcuts sheet. Click away, Esc or Close shuts it.
177 pub(crate) fn about_card(
178 &self,
179 viewport: Size<Pixels>,
180 cx: &mut Context<Self>,
181 ) -> Option<AnyElement> {
182 let area_h = crate::ui::stance::below_picture_floor(
183 f32::from(viewport.height),
184 self.split_px(Split::Bench, viewport),
185 );
186 let bottom = (f32::from(viewport.height) - area_h).max(0.);
187 if self.quit_ask {
188 return Some(self.unsaved_dialog(bottom, cx));
189 }
190 if let Some(why) = self.recovery_failure.clone() {
191 return Some(self.recovery_failed_dialog(&why, bottom, cx));
192 }
193 if self.save_ask {
194 return Some(self.overwrite_dialog(bottom, cx));
195 }
196 if self.keys_open && !self.about_open {
197 return Some(crate::ui::dock_stance::keys_sheet(self, viewport, 0., cx).into_any_element());
198 }
199 if !self.about_open {
200 return None;
201 }
202 use crate::ui::kit;
203 let t = crate::ui::theme::tokens();
204 Some(
205 kit::dialog_layer(bottom)
206 .on_mouse_down(
207 MouseButton::Left,
208 cx.listener(|this, _: &MouseDownEvent, _, cx| {
209 this.about_open = false;
210 cx.notify();
211 cx.stop_propagation();
212 }),
213 )
214 .child(
215 kit::dialog("about-card", ABOUT_W)
216 .items_center()
217 .gap(px(6.))
218 .child(
219 // The app mark: the menu bar's "E" on the accent square.
220 div()
221 .flex_none()
222 .size(px(56.))
223 .mb(px(6.))
224 .flex()
225 .items_center()
226 .justify_center()
227 .rounded(px(12.))
228 .bg(rgb(t.accent_fill))
229 .type_style(type_scale::label(28., gpui::FontWeight::SEMIBOLD))
230 .text_color(rgb(t.on_accent))
231 .child("E"),
232 )
233 .child(div().type_style(type_scale::title()).text_color(rgb(t.ink1)).child("edith"))
234 .child(
235 div()
236 .type_style(type_scale::caption())
237 .text_color(rgb(t.ink3))
238 .child(format!("Version {}", env!("CARGO_PKG_VERSION"))),
239 )
240 .child(
241 div()
242 .mt(px(6.))
243 .type_style(type_scale::body())
244 .text_color(rgb(t.ink2))
245 .child("A keyboard-first video editor."),
246 )
247 .child(
248 div()
249 .flex()
250 .flex_col()
251 .items_center()
252 .type_style(type_scale::caption())
253 .text_color(rgb(t.ink3))
254 .child("Icons from Lucide (ISC).")
255 .child("Fonts under the SIL Open Font License."),
256 )
257 ,
258 )
259 .into_any_element(),
260 )
261 }
262}
263
264impl Player {
265 /// The window's close request over unsaved work, in the dialog shell. The
266 /// title and the body are read off the state as it is drawn: a question
267 /// about edits says so, a question about exports says so, and a question
268 /// about neither (an export finished while the dialog was up) names nothing
269 /// it does not have. Save (primary, `Enter`), Don't save (`D`), Stay (`Esc`).
270 /// The keys are the root handler's (`quit_ask` owns the keyboard); the
271 /// buttons are the pointer's door to the same answers.
272 fn unsaved_dialog(&self, bottom: f32, cx: &mut Context<Self>) -> AnyElement {
273 use crate::ui::kit::{self, Button, ButtonStyle};
274 let edits = self.close_dirty();
275 let exports = self.queue.unfinished();
276 let queue = self.queue_quit_note();
277 let name = crate::files::file_name(&self.project_path);
278 let (title, text) = match (edits, exports > 0) {
279 (true, _) => {
280 let title = match name.is_empty() {
281 true => "Save changes before closing?".to_string(),
282 false => format!("Save changes to {name}?"),
283 };
284 let body = match name.is_empty() {
285 true => "This project has changes that are not saved yet.".to_string(),
286 false => format!("{name} has changes that are not saved yet."),
287 };
288 (title, [Some(body), queue].into_iter().flatten().collect::<Vec<_>>().join(" "))
289 }
290 (false, true) => ("Close with exports unfinished?".to_string(), queue.unwrap_or_default()),
291 (false, false) => ("Close edith?".to_string(), "Nothing here is unsaved.".to_string()),
292 };
293 let actions = kit::dialog_actions()
294 .child(
295 Button::new("quit-stay")
296 .label("Stay")
297 .build()
298 .tooltip(crate::ui::widgets::overlay_tip_hover("Keep editing", "Esc", None))
299 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
300 this.quit_ask = false;
301 cx.notify();
302 })),
303 )
304 .child(
305 Button::new("quit-discard")
306 .label(if edits { "Don't save" } else { "Close anyway" })
307 .build()
308 .tooltip(crate::ui::widgets::overlay_tip_hover(
309 if edits { "Close without saving" } else { "Close and stop the exports" },
310 "D",
311 None,
312 ))
313 .on_click(cx.listener(|this, _: &ClickEvent, window, _| {
314 // Only the edits are let go. Exports and a pending recovery
315 // are not answered by Don't save.
316 if this.close_dirty() {
317 this.discard_unsaved_edits();
318 }
319 this.queue.cancel_all();
320 window.remove_window();
321 })),
322 )
323 .children(edits.then(|| {
324 Button::new("quit-save")
325 .label("Save")
326 .style(ButtonStyle::Primary)
327 .build()
328 .tooltip(crate::ui::widgets::overlay_tip_hover("Save and close", "Enter", None))
329 .on_click(cx.listener(|this, _: &ClickEvent, window, cx| {
330 // A save that failed keeps the window open: the notice says why.
331 if this.save_project(cx) {
332 window.remove_window();
333 }
334 }))
335 }));
336 kit::dialog_layer(bottom)
337 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| cx.stop_propagation())
338 .child(
339 kit::dialog("unsaved-dialog", 400.)
340 .child(kit::dialog_title(title))
341 .child(kit::dialog_text(text))
342 .child(actions),
343 )
344 .into_any_element()
345 }
346
347 /// Recover could not bring the unsaved edits back: the plain reason, and that the
348 /// saved version is open. OK closes it; the autosave is still on disk.
349 fn recovery_failed_dialog(&self, why: &str, bottom: f32, cx: &mut Context<Self>) -> AnyElement {
350 use crate::ui::kit::{self, Button, ButtonStyle};
351 kit::dialog_layer(bottom)
352 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| cx.stop_propagation())
353 .child(
354 kit::dialog("recovery-failed-dialog", 440.)
355 .child(kit::dialog_title("Couldn't bring back the unsaved edits"))
356 .child(kit::dialog_text(why.to_string()))
357 .child(
358 kit::dialog_actions().child(
359 Button::new("recovery-failed-ok")
360 .label("OK")
361 .style(ButtonStyle::Primary)
362 .build()
363 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
364 this.recovery_failure = None;
365 cx.notify();
366 })),
367 ),
368 ),
369 )
370 .into_any_element()
371 }
372
373 /// Saving over a project file this window never opened or wrote: Overwrite
374 /// (`Enter`) or Keep the file (`Esc`).
375 fn overwrite_dialog(&self, bottom: f32, cx: &mut Context<Self>) -> AnyElement {
376 use crate::ui::kit::{self, Button, ButtonStyle};
377 kit::dialog_layer(bottom)
378 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| cx.stop_propagation())
379 .child(
380 kit::dialog("overwrite-dialog", 400.)
381 .child(kit::dialog_title("Replace the existing file?"))
382 .child(kit::dialog_text(format!(
383 "A file named {} already exists in this folder. Replace it?",
384 crate::files::file_name(&self.project_path)
385 )))
386 .child(
387 kit::dialog_actions()
388 .child(
389 Button::new("overwrite-keep")
390 .label("Keep the file")
391 .build()
392 .tooltip(crate::ui::widgets::overlay_tip_hover("Do not save", "Esc", None))
393 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
394 this.save_ask = false;
395 cx.notify();
396 })),
397 )
398 .child(
399 Button::new("overwrite-go")
400 .label("Replace")
401 .style(ButtonStyle::Primary)
402 .build()
403 .tooltip(crate::ui::widgets::overlay_tip_hover("Replace the file", "Enter", None))
404 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
405 this.save_project(cx);
406 this.save_ask = false;
407 cx.notify();
408 })),
409 ),
410 ),
411 )
412 .into_any_element()
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419
420 #[test]
421 fn the_plate_is_at_least_as_wide_as_its_widest_row() {
422 let rows = [
423 ("Reload project from disk", "Ctrl+Shift+R"),
424 ("Paste (global)", "Ctrl+V"),
425 ("Regroup", ""),
426 ];
427 let w = popup_w(rows, false);
428 for (l, h) in rows {
429 let need = text_w(l, type_scale::LABEL_ROW_PX, false)
430 + text_w(h, type_scale::CHORD_METADATA_MIN_PX, true);
431 assert!(w >= need + MENU_PAD * 2., "{l}: {w} < {need}");
432 }
433 }
434
435 #[test]
436 fn a_short_menu_keeps_a_floor_width_and_a_long_one_a_ceiling() {
437 assert!(popup_w([("Cut", "X")], false) >= MENU_W * 0.75);
438 assert_eq!(popup_w([(&"x".repeat(200)[..], "")], false), POPUP_MAX_W);
439 }
440
441 #[test]
442 fn a_context_menu_opens_with_its_corner_on_the_pointer_clamped_to_the_window() {
443 let view = size(px(1000.), px(700.));
444 let (x, y) = crate::oracle::menu_at_w(point(px(300.), px(200.)), view, 240., 150.);
445 assert_eq!((x, y), (300., 200.));
446 let (x, y) = crate::oracle::menu_at_w(point(px(990.), px(690.)), view, 240., 150.);
447 assert!(x + 240. <= 1000. && y + 150. <= 700.);
448 }
449
450 #[test]
451 fn no_menu_row_prints_unbound_and_help_has_about() {
452 let keymap = crate::keymap::Keymap::defaults();
453 for title in crate::ui::menubar::Title::ALL {
454 for entry in title.entries() {
455 use crate::ui::menubar::Entry::*;
456 if let Act(a) | Switch(a) = entry {
457 let hint = shortcut(&keymap, a);
458 assert!(!hint.contains("unbound"), "{a:?}");
459 }
460 }
461 }
462 let help = crate::ui::menubar::Title::Help.entries();
463 assert!(help.contains(&crate::ui::menubar::Entry::Act(ActionId::About)));
464 assert_eq!(ActionId::About.label(), "About edith…");
465 }
466
467 /// The clip menu's top level is short (the card openers live in the Adjust
468 /// submenu) and, placed the way `context_card` places it, fits a 1280x720
469 /// window whatever y the click was at.
470 #[test]
471 fn the_clip_menu_fits_a_720_window_at_any_click_y() {
472 let all: Vec<ActionId> = crate::menus::MENU_ITEMS.to_vec();
473 let top = all
474 .iter()
475 .filter(|a| !crate::menus::adjust_item(**a) && !crate::menus::compound_item(**a))
476 .count()
477 + 3; // Adjust, Compound and Properties
478 assert!(top <= 20, "{top} rows");
479 let view = size(px(1280.), px(720.));
480 let list_h = crate::oracle::menu_rows_h(top + 1, view);
481 let h = MENU_PAD * 2. + list_h;
482 for y in (0..=720).step_by(10) {
483 let at = point(px(300.), px(y as f32));
484 let at = crate::ui::stance::menu_above(at, view, 0., h);
485 let (_, top_y) = crate::oracle::menu_at_w(at, view, 260., h);
486 assert!(top_y >= 0. && top_y + h <= 720., "y {y}: {top_y} + {h}");
487 }
488 }
489}