forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

library.rs270 lines, 12.4 KiBHistoryRawDownload
1//! The media library: the left panel's rows and the menu over them.
2
3use crate::ui::popup::{popup_plate, popup_row, popup_row_icon, popup_rule, popup_w};
4use crate::ui::widgets::*;
5use crate::*;
6
7impl Player {
8 /// The menu a right-click on a library row opens: what can be done with the
9 /// *file* rather than with a clip of it, and a turn-over side saying what
10 /// that file is. Built like [`Player::context_card`] down to the scrim, the
11 /// row height and the clamp, because it is the same menu on the other panel
12 /// -- a click away or any stroke closes it.
13 pub(crate) fn library_card(
14 &self,
15 viewport: Size<Pixels>,
16 cx: &mut Context<Self>,
17 ) -> Option<impl IntoElement> {
18 let menu = self.library_menu.clone()?;
19 let path = menu.path.clone();
20 let mut measure: Vec<(String, String)> = Vec::new();
21 let mut rows: Vec<AnyElement> = Vec::new();
22 // What every item of this menu is answered from, read once.
23 let ctx = self.row_ctx(&path, menu.stream);
24 if menu.details {
25 // What the library knows about this file: its header, read once at
26 // import, and the frames for the length line. Every track of the
27 // file is listed, not only this row's -- a plate describes the file.
28 let frames = self
29 .session
30 .as_ref()
31 .map_or(0, |session| session.file_frames(&path));
32 // How many clips play from this exact row -- the number that
33 // decides whether Remove is refused, so the card answers the
34 // question the refusal would otherwise raise.
35 let placed = ctx.placed;
36 // A still is described by what it has -- a picture, a size, and a
37 // longest it may be held for -- where a media file is described by
38 // its streams and its length. Same card, the rows that mean
39 // something for this kind of source.
40 let image = engine::is_image(&path);
41 let kind = match self.sizes.get(&path).copied().flatten() {
42 Some((w, h)) => format!("still image · {w}x{h}"),
43 None => "still image".to_string(),
44 };
45 let streams = self.streams.get(&path).map_or(&[][..], Vec::as_slice);
46 let mut lines = file_properties(
47 &path,
48 self.facts.get(&path).and_then(Option::as_ref),
49 streams,
50 self.bitrates.get(&path).copied().flatten(),
51 );
52 if image {
53 lines.push(("Picture".to_string(), kind));
54 }
55 // The path is cut in the middle (both ends say where it is and what it is);
56 // the whole of it is the plate's tooltip and the Copy button.
57 for (label, value) in &mut lines {
58 if label == "Path" {
59 *value = crate::recent::middle(value, 38);
60 }
61 if label == "Container" {
62 *value = container_name(value);
63 }
64 }
65 let secs = f64::from(frames) / self.fps;
66 lines.push(match image {
67 // A still has no length of its own: how long it may be held, in words.
68 true => ("Longest hold".to_string(), hold_words(secs)),
69 false => ("Length".to_string(), timecode(secs, self.fps)),
70 });
71 lines.push((
72 "On the timeline".to_string(),
73 format!("{placed} clip{}", if placed == 1 { "" } else { "s" }),
74 ));
75 for (label, value) in lines {
76 measure.push((label.clone(), value.clone()));
77 rows.push(
78 popup_row(("library-menu", rows.len()), label, value, None, None)
79 .cursor_default()
80 .into_any_element(),
81 );
82 }
83 let text = path.display().to_string();
84 rows.push(
85 div()
86 .flex_none()
87 .p(px(4.))
88 .child(
89 crate::ui::kit::Button::new("properties-copy-path")
90 .label("Copy path")
91 .icon(crate::ui::icons::Icon::Copy)
92 .style(crate::ui::kit::ButtonStyle::Secondary)
93 .size(crate::ui::kit::ButtonSize::Small)
94 .build()
95 .w_full()
96 .tooltip(crate::ui::widgets::tip_hover("Copy the full path of this file", "", None))
97 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
98 cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.clone()));
99 this.notify_user("Path copied".into());
100 cx.notify();
101 })),
102 )
103 .into_any_element(),
104 );
105 } else {
106 // The oracle's list, exactly as the clip menu takes its rows from
107 // `menu_items`: an item that means nothing for the file that was
108 // right-clicked is not a row, and one this moment refuses is drawn
109 // dimmed and says why in place of its hint.
110 // Whether the rule line above the destructive rows has been drawn.
111 let mut ruled = false;
112 for item in row_items(ctx) {
113 // DESIGN §9: destructive verbs sit below a rule line, drawn once
114 // before the first of them -- the same seam the clip menu draws
115 // (`DARK_SEAM`), so the two menus cannot disagree about it.
116 if item.destructive() && !rows.is_empty() && !ruled {
117 ruled = true;
118 rows.push(popup_rule());
119 }
120 let refusal = row_enable(item, ctx);
121 let enabled = refusal.yes();
122 let hint = match refusal.why() {
123 Some(_) => String::new(),
124 None => item.hint().to_string(),
125 };
126 measure.push((item.label_in(ctx).to_string(), hint.clone()));
127 rows.push(
128 popup_row_icon(
129 ("library-menu", rows.len()),
130 item.label_in(ctx),
131 hint,
132 Some(false),
133 Some(item.icon()),
134 refusal.why(),
135 )
136 // A destructive row answers a hover in the error token.
137 .when(!enabled && item.destructive(), |d| {
138 d.hover(|s| s.text_color(rgb(STATUS_ERROR())))
139 })
140 .when(enabled, |d| {
141 let destructive = item.destructive();
142 d.cursor_pointer()
143 .hover(move |s| {
144 let s = s.bg(rgb(BG_HOVER()));
145 if destructive {
146 s.text_color(rgb(STATUS_ERROR()))
147 } else {
148 s
149 }
150 })
151 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
152 this.act_on_row(item, cx);
153 }))
154 })
155 .into_any_element(),
156 );
157 }
158 }
159 // Opens at the pointer, top-left on it, like every context menu. When
160 // the plate would not fit whole below the pointer it flips up so its
161 // bottom edge sits on the pointer; `menu_at_w` then keeps it inside
162 // all four window edges.
163 let list_h = menu_rows_h(rows.len(), viewport);
164 let h = MENU_PAD * 2. + list_h;
165 // The item rows reserve the icon column, so the plate is measured with it.
166 let pw = popup_w(measure.iter().map(|(l, h)| (l.as_str(), h.as_str())), !menu.details);
167 // Properties sits beside the row it describes, top-aligned with it: right of the row,
168 // or left of it when the window has no room on the right.
169 let beside = menu.details.then(|| crate::ui::anchor::row_of(&path, menu.stream)).flatten().map(|row| {
170 let right = f32::from(row.origin.x + row.size.width) + 4.;
171 let x = if right + pw + MENU_EDGE > f32::from(viewport.width) {
172 (f32::from(row.origin.x) - pw - 4.).max(0.)
173 } else {
174 right
175 };
176 point(px(x), row.origin.y)
177 });
178 let at = if let Some(beside) = beside {
179 beside
180 } else if f32::from(menu.at.y) + h + MENU_EDGE > f32::from(viewport.height) {
181 point(menu.at.x, px((f32::from(menu.at.y) - h).max(0.)))
182 } else {
183 menu.at
184 };
185 let (x, y) = menu_at_w(at, viewport, pw, h);
186 let full: SharedString = path.display().to_string().into();
187 Some(
188 scrim()
189 .on_mouse_down(
190 MouseButton::Left,
191 cx.listener(|this, _: &MouseDownEvent, _, cx| {
192 this.library_menu = None;
193 cx.notify();
194 cx.stop_propagation();
195 }),
196 )
197 .on_mouse_down(
198 MouseButton::Right,
199 cx.listener(|this, _: &MouseDownEvent, _, cx| {
200 this.library_menu = None;
201 cx.notify();
202 cx.stop_propagation();
203 }),
204 )
205 .child(
206 popup_plate("library-menu-card", x, y, pw)
207 // Painted after the scrim, so this listener runs first
208 // and a press meant for an item never closes the menu
209 // out from under its own click (`context_card`).
210 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
211 cx.stop_propagation()
212 })
213 .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| {
214 cx.stop_propagation()
215 })
216 .when(menu.details, |d| {
217 d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into())
218 })
219 // Scrolls where the window has no room for the list,
220 // like the clip menu's -- an item hanging off the bottom
221 // edge is an item nobody can click.
222 .child(
223 div()
224 .id("library-menu-rows")
225 .flex()
226 .flex_col()
227 .max_h(px(list_h))
228 .overflow_y_scroll()
229 .children(rows),
230 ),
231 ),
232 )
233 }
234}
235
236/// A container as its name reads: `mp4` is "MP4", `mov` is "QuickTime". A name this
237/// table does not know is shown with its first letter capitalised.
238fn container_name(raw: &str) -> String {
239 match raw.to_ascii_lowercase().as_str() {
240 "mp4" => "MP4".to_string(),
241 "mov" | "quicktime" => "QuickTime".to_string(),
242 "m4a" => "M4A".to_string(),
243 "m4v" => "M4V".to_string(),
244 "3gp" => "3GP".to_string(),
245 "mkv" | "matroska" => "Matroska".to_string(),
246 "webm" => "WebM".to_string(),
247 "ogg" | "ogv" => "Ogg".to_string(),
248 "wav" => "WAV".to_string(),
249 "avi" => "AVI".to_string(),
250 "flac" => "FLAC".to_string(),
251 "mp3" => "MP3".to_string(),
252 other => {
253 let mut chars = other.chars();
254 match chars.next() {
255 Some(first) => first.to_uppercase().chain(chars).collect(),
256 None => String::new(),
257 }
258 }
259 }
260}
261
262/// A duration in plain words: "10 s", "10 min", "1 min 30 s".
263fn hold_words(secs: f64) -> String {
264 let secs = secs.max(0.).round() as u64;
265 match (secs / 60, secs % 60) {
266 (0, s) => format!("{s} s"),
267 (m, 0) => format!("{m} min"),
268 (m, s) => format!("{m} min {s} s"),
269 }
270}