1use std::fmt;
40use std::path::PathBuf;
41use std::sync::{Arc, Mutex};
42
43use egui::{Modifiers, Rect, Ui, vec2};
44use egui_pop_api::files::browser::{
45 EntryDrawer, ModeContext, ModeInfo, ModeKey, ModeNeeds, ModeOutput, ModeSettings, PlainDrawer,
46 SourceEntry, ThumbState, ThumbnailsMode, ViewMode, ViewModes,
47};
48use egui_pop_core::kit::{self, Kit, KitCx, Part, State};
49use egui_pop_core::rating::RatingStars;
50use egui_pop_core::strings::tr_with;
51use egui_pop_core::theme::Tokens;
52
53use super::grid::{OVERLAY_MIN, Signal, overlay};
54use super::marks::{CullAction, CullKeymap, EmptyStars, Flag, Marks};
55use super::paint::LibraryTokens;
56use crate::strings as s;
57
58pub const MODE_LIBRARY: &str = "library";
60
61pub type EntryLibraryMarks = dyn Fn(&SourceEntry) -> Marks + Send + Sync;
63
64#[derive(Clone, Default)]
68pub struct LibrarySignals(Arc<Mutex<Vec<Signal<PathBuf>>>>);
69
70impl fmt::Debug for LibrarySignals {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.debug_tuple("LibrarySignals").field(&self.len()).finish()
73 }
74}
75
76impl LibrarySignals {
77 fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Signal<PathBuf>>> {
78 self.0.lock().unwrap_or_else(|e| e.into_inner())
79 }
80
81 pub fn drain(&self) -> Vec<Signal<PathBuf>> {
83 std::mem::take(&mut *self.lock())
84 }
85
86 pub fn len(&self) -> usize {
88 self.lock().len()
89 }
90
91 pub fn is_empty(&self) -> bool {
92 self.len() == 0
93 }
94
95 fn push(&self, signal: Signal<PathBuf>) {
96 self.lock().push(signal);
97 }
98}
99
100#[derive(Clone)]
104pub struct LibraryGridMode {
105 marks: Arc<EntryLibraryMarks>,
106 keymap: CullKeymap,
107 signals: LibrarySignals,
108 grid: ThumbnailsMode,
109 pending: Vec<(Option<usize>, CullAction)>,
113}
114
115impl fmt::Debug for LibraryGridMode {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.debug_struct("LibraryGridMode")
118 .field("keymap", &self.keymap)
119 .field("signals", &self.signals)
120 .finish_non_exhaustive()
121 }
122}
123
124impl LibraryGridMode {
125 pub fn new(marks: impl Fn(&SourceEntry) -> Marks + Send + Sync + 'static) -> Self {
128 LibraryGridMode {
129 marks: Arc::new(marks),
130 keymap: CullKeymap::lightroom(),
131 signals: LibrarySignals::default(),
132 grid: ThumbnailsMode::default(),
133 pending: Vec::new(),
134 }
135 }
136
137 #[must_use]
140 pub fn keymap(mut self, keymap: CullKeymap) -> Self {
141 self.keymap = keymap;
142 self
143 }
144
145 #[must_use]
147 pub fn signals(mut self, signals: LibrarySignals) -> Self {
148 self.signals = signals;
149 self
150 }
151
152 pub fn register(self, modes: &ViewModes) -> Result<(), String> {
156 modes.register(
157 MODE_LIBRARY,
158 Arc::new(move || Box::new(self.clone()) as Box<dyn ViewMode>),
159 )
160 }
161
162 fn takes(&self, key: egui::Key, modifiers: Modifiers) -> Option<CullAction> {
164 if !(modifiers.is_none() || modifiers == Modifiers::SHIFT) {
165 return None;
166 }
167 self.keymap.action(key).filter(|a| {
168 matches!(
169 a,
170 CullAction::Rate(_) | CullAction::Flag(_) | CullAction::Label(_)
171 )
172 })
173 }
174
175 fn cull(&mut self, cx: &ModeContext<'_>) -> Option<usize> {
178 let mut advance = None;
179 for (focus, action) in std::mem::take(&mut self.pending) {
180 let focus = focus.filter(|&f| f < cx.entries.len());
181 let keys: Vec<PathBuf> = if cx.selection.is_empty() {
183 focus
184 .map(|f| cx.entries[f].path.clone())
185 .into_iter()
186 .collect()
187 } else {
188 cx.entries
189 .iter()
190 .filter(|e| cx.selection.contains(&e.path))
191 .map(|e| e.path.clone())
192 .collect()
193 };
194 if keys.is_empty() {
195 continue;
196 }
197 let signal = match action {
198 CullAction::Rate(r) => Signal::Rate {
199 keys,
200 rating: r.min(super::marks::MAX_RATING),
201 },
202 CullAction::Flag(flag) => Signal::Flag { keys, flag },
203 CullAction::Label(label) => {
204 let on = focus.is_none_or(|f| !(self.marks)(&cx.entries[f]).labels.has(label));
206 Signal::Label { keys, label, on }
207 }
208 _ => continue,
209 };
210 self.signals.push(signal);
211 if self.keymap.auto_advance
212 && let Some(f) = focus
213 && f + 1 < cx.entries.len()
214 {
215 advance = Some(f + 1);
216 }
217 }
218 advance
219 }
220}
221
222impl ViewMode for LibraryGridMode {
223 fn describe(&self) -> ModeInfo {
224 let mut info = self.grid.describe();
225 info.id = MODE_LIBRARY.into();
226 info.label = "Library grid".into();
227 info.icon = "phosphor:images".into();
228 info.persist = MODE_LIBRARY.into();
229 info.keys.extend([
230 ("0 to 5".into(), "Rate".into()),
231 ("P, X, U".into(), "Pick, reject, unflag".into()),
232 ("6 to 9".into(), "Toggle a colour label".into()),
233 ]);
234 info.gestures.push("Drag: select with a band".into());
235 info.needs = ModeNeeds {
236 thumbnails: true,
237 ..ModeNeeds::default()
238 };
239 info
240 }
241
242 fn show(&mut self, ui: &mut Ui, cx: ModeContext<'_>) -> ModeOutput {
243 let advance = self.cull(&cx);
244 if advance.is_some() {
245 ui.ctx().request_repaint();
246 }
247 let ModeContext {
248 entries,
249 selection,
250 focus,
251 thumbnails,
252 settings,
253 id,
254 reveal_focus,
255 max_height,
256 drawer,
257 name,
258 many,
259 place,
260 ancestors,
261 peek,
262 loading,
263 generation,
264 marks,
265 } = cx;
266 let mut plain = PlainDrawer {
267 entries,
268 selection,
269 focus,
270 marks,
271 };
272 let inner: &mut dyn EntryDrawer = match drawer {
273 Some(d) => d,
274 None => &mut plain,
275 };
276 let mut drawer = MarksDrawer {
277 inner,
278 entries,
279 marks: &*self.marks,
280 id,
281 };
282 let mut out = self.grid.show(
283 ui,
284 ModeContext {
285 entries,
286 selection,
287 focus,
288 thumbnails,
289 settings,
290 id,
291 reveal_focus,
292 max_height,
293 drawer: Some(&mut drawer),
294 name,
295 many,
296 place,
297 ancestors,
298 peek,
299 loading,
300 generation,
301 marks,
302 },
303 );
304 if let Some(next) = advance {
307 out.clicked = Some((next, Modifiers::NONE));
308 }
309 out
310 }
311
312 fn step(&self, from: usize, count: usize, key: ModeKey) -> usize {
313 self.grid.step(from, count, key)
314 }
315
316 fn own_key(
317 &mut self,
318 key: egui::Key,
319 modifiers: Modifiers,
320 focus: Option<usize>,
321 _settings: &mut ModeSettings,
322 ) -> bool {
323 match self.takes(key, modifiers) {
324 Some(action) => {
325 self.pending.push((focus, action));
326 true
327 }
328 None => false,
329 }
330 }
331}
332
333struct MarksDrawer<'a> {
336 inner: &'a mut dyn EntryDrawer,
337 entries: &'a [SourceEntry],
338 marks: &'a EntryLibraryMarks,
339 id: egui::Id,
340}
341
342impl EntryDrawer for MarksDrawer<'_> {
343 fn headers(&mut self, ui: &mut Ui, width: f32) {
344 self.inner.headers(ui, width);
345 }
346
347 fn empty(&mut self, ui: &mut Ui) {
348 self.inner.empty(ui);
349 }
350
351 fn row_size(&self, ui: &Ui, width: f32) -> egui::Vec2 {
352 self.inner.row_size(ui, width)
353 }
354
355 fn row(&mut self, ui: &mut Ui, n: usize, size: egui::Vec2) -> egui::Response {
356 self.inner.row(ui, n, size)
357 }
358
359 fn cell_size(&self, ui: &Ui, side: f32) -> egui::Vec2 {
360 self.inner.cell_size(ui, side)
361 }
362
363 fn cell(
364 &mut self,
365 ui: &mut Ui,
366 n: usize,
367 size: egui::Vec2,
368 thumbnail: ThumbState,
369 ) -> egui::Response {
370 let r = self.inner.cell(ui, n, size, thumbnail);
371 let Some(e) = self.entries.get(n) else {
372 return r;
373 };
374 if e.is_dir() {
375 return r;
376 }
377 let marks = (self.marks)(e);
378 if marks == Marks::default() {
379 return r;
380 }
381 if let Some(said) = spoken(ui.ctx(), &marks) {
382 ui.ctx()
383 .accesskit_node_builder(r.id, |node| node.set_description(said));
384 }
385 let side = size.x.min(r.rect.width());
386 if side >= OVERLAY_MIN {
387 let t = Tokens::of(ui.ctx());
388 let image = Rect::from_min_size(r.rect.min, vec2(side, side)).shrink(t.space.xs);
389 paint_marks(ui, image, &marks, self.id.with(("library.stars", &e.path)));
390 }
391 r
392 }
393}
394
395fn paint_marks(ui: &mut Ui, image: Rect, marks: &Marks, id: egui::Id) {
399 let t = Tokens::of(ui.ctx());
400 let lt = LibraryTokens::of(ui.ctx());
401 let kit = Kit::of(ui.ctx());
402 let painter = ui.painter().clone();
403 let cx = KitCx {
404 painter: &painter,
405 ppp: ui.ctx().pixels_per_point(),
406 };
407 if marks.flag == Flag::Reject {
408 kit.thumb_layer.paint(
409 &cx,
410 &Part {
411 rect: image,
412 room: image,
413 state: State::REST.toned(kit::Tone::Muted),
414 label: None,
415 },
416 );
417 }
418 let star = (image.width() / 10.0).clamp(10.0, 16.0);
419 overlay(&cx, &kit, <, &t, image, marks, false, star);
420 if marks.rating > 0 {
421 let stars = Rect::from_min_size(
422 egui::pos2(image.left() + star * 0.25, image.bottom() - star * 1.25),
423 RatingStars::size_for(star),
424 );
425 let _ = RatingStars::new(marks.rating)
426 .id(id)
427 .focusable(false)
428 .read_only(true)
429 .empty(EmptyStars::OnHover)
430 .item_hovered(false)
431 .show_at(ui, stars);
432 }
433}
434
435pub fn spoken(ctx: &egui::Context, marks: &Marks) -> Option<String> {
438 let mut parts = Vec::new();
439 if marks.rating > 0 {
440 parts.push(tr_with(
441 ctx,
442 &s::LIBRARY_RATED,
443 &[("stars", i64::from(marks.rating).into())],
444 ));
445 }
446 if marks.flag != Flag::None {
447 parts.push(marks.flag.title(ctx));
448 }
449 parts.extend(marks.labels.iter().map(|l| l.title(ctx)));
450 (!parts.is_empty()).then(|| parts.join(", "))
451}