Skip to main content

egui_pop_views/library/
plugin.rs

1//! The library's steps (ADR 0011), its commands (the agent surface), the
2//! registry of the libraries drawn with an application, and
3//! [`LibraryPlugin`] declaring them.
4//!
5//! | Step | Arguments | Default |
6//! |---|---|---|
7//! | `library.select` | `library`, `keys`, `cursor` | sets the selection |
8//! | `library.rate` | `library`, `keys`, `rating` (0 to 5) | nothing: the application rates its images (the `Rate` signal) |
9//! | `library.label` | `library`, `keys`, `label` (`red`, `yellow`, `green`, `blue`, `purple`), `on` | nothing: the application labels them (`Label`) |
10//! | `library.flag` | `library`, `keys`, `flag` (`pick`, `reject`, `none`) | nothing: the application flags them (`Flag`) |
11//! | `library.tag` | `library`, `keys`, `add`, `remove` (tag lists) | nothing: the application tags them (`Tag`) |
12//! | `library.stack` | `library`, `stack` (its top image's key), `expanded` | expands or collapses the stack in the view |
13//! | `library.filter` | `library`, `filter` (a [`Filter`](super::filter::Filter)) | sets the search field's filter |
14//!
15//! The application owns the marks, the tags and the filtering: a mark's
16//! default does nothing but report it (the view's output signal, and the
17//! journal); the application applies it from the signal or from an
18//! after-hook. A before-hook vetoes a mark (`Veto`) or rewrites it
19//! (`Redirect`, a rating capped, a label swapped, other keys).
20//!
21//! Commands (keys, palette, agents), each acting on `library` (else the
22//! library that last had the focus) and on `keys` (else its selection):
23//! `library.select` (`keys`, `cursor`), `library.rate` (`rating`),
24//! `library.label` (`label`, `on`: else toggled from the cursor's image),
25//! `library.flag` (`flag`), `library.tag` (`add`, `remove`),
26//! `library.filter` (`filter`). A command queues its step for the view,
27//! which runs it at its next pass as if the user had asked. The
28//! `libraries` debug collector lists the libraries drawn, their
29//! selection and filter.
30
31use std::collections::{BTreeMap, VecDeque};
32use std::sync::Mutex;
33
34#[cfg(feature = "api")]
35use egui_pop_api::services::ServiceToken;
36#[cfg(feature = "api")]
37use egui_pop_api::steps::StepSpec;
38#[cfg(feature = "api")]
39use egui_pop_api::{Call, Ctx, Plugin, PluginError};
40
41use crate::app_link::{AppHandle, Outcome};
42#[cfg(feature = "api")]
43use egui_pop_core::debug::FnCollector;
44use egui_pop_core::lock;
45#[cfg(feature = "api")]
46use egui_pop_model::commands::CommandSpec;
47use egui_pop_model::ids::{CommandId, PluginId, StepId};
48use serde::de::DeserializeOwned;
49use serde_json::{Value as Json, json};
50
51#[cfg(feature = "api")]
52use super::marks::{ColorLabel, Flag, MAX_RATING};
53
54pub const LIBRARY_SELECT: StepId = StepId::from_static("library.select");
55pub const LIBRARY_RATE: StepId = StepId::from_static("library.rate");
56pub const LIBRARY_LABEL: StepId = StepId::from_static("library.label");
57pub const LIBRARY_FLAG: StepId = StepId::from_static("library.flag");
58pub const LIBRARY_TAG: StepId = StepId::from_static("library.tag");
59pub const LIBRARY_STACK: StepId = StepId::from_static("library.stack");
60pub const LIBRARY_FILTER: StepId = StepId::from_static("library.filter");
61
62pub const CMD_SELECT: CommandId = CommandId::from_static("library.select");
63pub const CMD_RATE: CommandId = CommandId::from_static("library.rate");
64pub const CMD_LABEL: CommandId = CommandId::from_static("library.label");
65pub const CMD_FLAG: CommandId = CommandId::from_static("library.flag");
66pub const CMD_TAG: CommandId = CommandId::from_static("library.tag");
67pub const CMD_FILTER: CommandId = CommandId::from_static("library.filter");
68
69/// The plugin's id.
70pub const LIBRARY: PluginId = PluginId::from_static("egui_pop.library");
71
72/// How many requests a library keeps waiting for its view: a view its
73/// host no longer draws keeps the latest, the older ones dropped and
74/// counted (`dropped` in the collector).
75pub const INBOX: usize = 64;
76
77/// A step a command asked a library's view to run.
78#[derive(Clone, Debug, PartialEq)]
79pub(crate) struct Request {
80    pub step: StepId,
81    pub args: Json,
82}
83
84#[derive(Debug, Default)]
85struct Entry {
86    count: usize,
87    selection: Vec<Json>,
88    cursor: Json,
89    filter: Json,
90    inbox: VecDeque<Request>,
91    filter_inbox: Option<Json>,
92    /// Requests dropped from a full inbox.
93    dropped: u64,
94}
95
96#[derive(Debug, Default)]
97struct Inner {
98    entries: BTreeMap<String, Entry>,
99    focused: Option<String>,
100}
101
102/// The libraries drawn with an application, by id: what commands and
103/// the collector reach. A grid, a filmstrip or a search field registers
104/// its library when drawn with `.app(...)`.
105#[derive(Debug, Default)]
106pub struct Libraries {
107    inner: Mutex<Inner>,
108}
109
110/// The registry, a service of [`LibraryPlugin`].
111#[cfg(feature = "api")]
112pub const LIBRARIES: ServiceToken<Libraries> = ServiceToken::new("egui_pop.library");
113
114impl Libraries {
115    /// The libraries' ids.
116    pub fn ids(&self) -> Vec<String> {
117        lock(&self.inner).entries.keys().cloned().collect()
118    }
119
120    /// The library that last had the focus.
121    pub fn focused(&self) -> Option<String> {
122        lock(&self.inner).focused.clone()
123    }
124
125    /// What the collector shows: each library's count, selection (the
126    /// first hundred keys), cursor and filter, the requests waiting for
127    /// its view and those dropped (past [`INBOX`]).
128    pub fn describe(&self) -> Json {
129        let i = lock(&self.inner);
130        let all: serde_json::Map<String, Json> = i
131            .entries
132            .iter()
133            .map(|(id, e)| {
134                (
135                    id.clone(),
136                    json!({
137                        "count": e.count,
138                        "selected": e.selection.len(),
139                        "selection": e.selection.iter().take(100).collect::<Vec<_>>(),
140                        "cursor": e.cursor,
141                        "filter": e.filter,
142                        "waiting": e.inbox.len(),
143                        "dropped": e.dropped,
144                    }),
145                )
146            })
147            .collect();
148        json!({ "libraries": all, "focused": i.focused })
149    }
150
151    pub(crate) fn publish(&self, id: &str, count: usize, selection: Vec<Json>, cursor: Json) {
152        let mut i = lock(&self.inner);
153        let e = i.entries.entry(id.to_string()).or_default();
154        e.count = count;
155        e.selection = selection;
156        e.cursor = cursor;
157    }
158
159    /// Registers a library (a view drawn for the first time).
160    pub(crate) fn touch(&self, id: &str) {
161        lock(&self.inner).entries.entry(id.to_string()).or_default();
162    }
163
164    pub(crate) fn publish_filter(&self, id: &str, filter: Json) {
165        lock(&self.inner)
166            .entries
167            .entry(id.to_string())
168            .or_default()
169            .filter = filter;
170    }
171
172    pub(crate) fn set_focused(&self, id: &str) {
173        let mut i = lock(&self.inner);
174        if i.focused.as_deref() != Some(id) {
175            i.focused = Some(id.to_string());
176        }
177    }
178
179    pub(crate) fn take(&self, id: &str) -> Vec<Request> {
180        lock(&self.inner)
181            .entries
182            .get_mut(id)
183            .map(|e| e.inbox.drain(..).collect())
184            .unwrap_or_default()
185    }
186
187    pub(crate) fn take_filter(&self, id: &str) -> Option<Json> {
188        lock(&self.inner)
189            .entries
190            .get_mut(id)
191            .and_then(|e| e.filter_inbox.take())
192    }
193
194    /// The selection published for a library.
195    pub fn selection(&self, id: &str) -> Option<Vec<Json>> {
196        lock(&self.inner)
197            .entries
198            .get(id)
199            .map(|e| e.selection.clone())
200    }
201
202    /// The cursor published for a library (the image the keyboard is on),
203    /// if it has one: what a preview in another panel usually follows.
204    pub fn cursor(&self, id: &str) -> Option<Json> {
205        lock(&self.inner)
206            .entries
207            .get(id)
208            .map(|e| e.cursor.clone())
209            .filter(|c| !c.is_null())
210    }
211
212    /// The library a command acts on.
213    #[cfg(feature = "api")]
214    fn target(&self, args: &Json) -> Result<String, String> {
215        let i = lock(&self.inner);
216        match args.get("library").and_then(Json::as_str) {
217            Some(id) if i.entries.contains_key(id) => Ok(id.to_string()),
218            Some(id) => Err(format!("no library `{id}`")),
219            None => i
220                .focused
221                .clone()
222                .ok_or_else(|| "no library has had the focus; name one with `library`".to_string()),
223        }
224    }
225
226    #[cfg(feature = "api")]
227    fn push(&self, id: &str, request: Request) {
228        let mut i = lock(&self.inner);
229        let e = i.entries.entry(id.to_string()).or_default();
230        if request.step == LIBRARY_FILTER {
231            e.filter_inbox = Some(request.args["filter"].clone());
232            return;
233        }
234        e.inbox.push_back(request);
235        while e.inbox.len() > INBOX {
236            e.inbox.pop_front();
237            e.dropped += 1;
238        }
239    }
240}
241
242/// Declares the library's steps, its commands and its collector, and
243/// provides the [`Libraries`] registry. Connect it when library views
244/// run with an application.
245#[cfg(feature = "api")]
246#[derive(Debug, Default)]
247pub struct LibraryPlugin;
248
249/// Every step the library declares.
250#[cfg(feature = "api")]
251pub fn specs() -> Vec<StepSpec> {
252    vec![
253        StepSpec::new(LIBRARY_SELECT, "A library's selection changes (a click, the keyboard, a rubber band, a command).")
254            .args(json!({ "library": "shoot", "keys": [12, 13], "cursor": 13 })),
255        StepSpec::new(LIBRARY_RATE, "Images are rated (0 to 5 stars); the application rates them. A veto keeps the rating, a redirect changes it.")
256            .args(json!({ "library": "shoot", "keys": [12], "rating": 3 })),
257        StepSpec::new(LIBRARY_LABEL, "A colour label is put on images or taken off; the application labels them.")
258            .args(json!({ "library": "shoot", "keys": [12], "label": "red", "on": true })),
259        StepSpec::new(LIBRARY_FLAG, "Images are picked, rejected or unflagged; the application flags them.")
260            .args(json!({ "library": "shoot", "keys": [12], "flag": "pick" })),
261        StepSpec::new(LIBRARY_TAG, "Tags are added to images or taken off; the application tags them.")
262            .args(json!({ "library": "shoot", "keys": [12], "add": ["beach"], "remove": [] })),
263        StepSpec::new(LIBRARY_STACK, "A stack is expanded or collapsed in a library's views.")
264            .args(json!({ "library": "shoot", "stack": 40, "expanded": true })),
265        StepSpec::new(LIBRARY_FILTER, "A library's filter changes (the search field, its chips, a command); the application filters its images.")
266            .args(json!({ "library": "shoot", "filter": { "text": "beach", "min_rating": 3, "labels": ["red"] } })),
267    ]
268}
269
270#[cfg(feature = "api")]
271impl Plugin for LibraryPlugin {
272    fn id(&self) -> PluginId {
273        LIBRARY
274    }
275
276    fn title(&self) -> String {
277        "Photo library".into()
278    }
279
280    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
281        for spec in specs() {
282            ctx.step(spec)?;
283        }
284        ctx.service(&LIBRARIES, Libraries::default())?;
285        commands(ctx)?;
286        let reg = ctx.app().service(&LIBRARIES).expect("just provided");
287        ctx.collector(
288            FnCollector::new(
289                "libraries",
290                "The photo libraries drawn: their count, selection, cursor, filter, and the requests waiting for their view and dropped from a full inbox.",
291            )
292            .snapshot(move |_| reg.describe()),
293        )?;
294        Ok(())
295    }
296}
297
298/// Queues `step` for the library a command names; `fill` checks and
299/// completes the arguments.
300#[cfg(feature = "api")]
301fn queue(
302    call: &Call<'_>,
303    step: StepId,
304    fill: impl FnOnce(&Json) -> Result<Json, String>,
305) -> Result<Json, String> {
306    let reg = call
307        .app
308        .service(&LIBRARIES)
309        .ok_or("the library plugin is not connected")?;
310    let id = reg.target(call.args)?;
311    let mut args = fill(call.args)?;
312    args["library"] = json!(id);
313    reg.push(
314        &id,
315        Request {
316            step: step.clone(),
317            args: args.clone(),
318        },
319    );
320    Ok(json!({ "library": id, "queued": step.to_string(), "args": args }))
321}
322
323/// Copies `keys` when given.
324#[cfg(feature = "api")]
325fn with_keys(args: &Json, mut out: Json) -> Json {
326    if let Some(k) = args.get("keys") {
327        out["keys"] = k.clone();
328    }
329    out
330}
331
332#[cfg(feature = "api")]
333fn commands(ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
334    const CAT: &str = "Library";
335    ctx.command(
336        CommandSpec::new(CMD_SELECT, "Select images", CAT)
337            .description("Selects images of a library by key (`keys`, the cursor on `cursor` or the last key), through its `library.select` step.")
338            .args(json!({ "library": "shoot (optional: the library that last had the focus)", "keys": [12, 13], "cursor": 13 })),
339        |call| {
340            queue(call, LIBRARY_SELECT, |a| {
341                let keys = a.get("keys").filter(|k| k.is_array()).ok_or("`keys` is a list")?;
342                let cursor = a
343                    .get("cursor")
344                    .cloned()
345                    .or_else(|| keys.as_array().and_then(|k| k.last().cloned()))
346                    .unwrap_or(Json::Null);
347                Ok(json!({ "keys": keys, "cursor": cursor }))
348            })
349        },
350    )?;
351    ctx.command(
352        CommandSpec::new(CMD_RATE, "Rate images", CAT)
353            .description("Rates images (`rating`, 0 to 5) of a library: `keys`, else its selection; through its `library.rate` step.")
354            .args(json!({ "library": "shoot", "keys": [12], "rating": 3 })),
355        |call| {
356            queue(call, LIBRARY_RATE, |a| {
357                let rating = a
358                    .get("rating")
359                    .and_then(Json::as_u64)
360                    .filter(|r| *r <= u64::from(MAX_RATING))
361                    .ok_or("`rating` is 0 to 5")?;
362                Ok(with_keys(a, json!({ "rating": rating })))
363            })
364        },
365    )?;
366    ctx.command(
367        CommandSpec::new(CMD_LABEL, "Label images", CAT)
368            .description("Puts a colour label (`label`: red, yellow, green, blue, purple) on images or takes it off (`on`; else toggled from the cursor's image): `keys`, else the selection; through `library.label`.")
369            .args(json!({ "library": "shoot", "keys": [12], "label": "red", "on": true })),
370        |call| {
371            queue(call, LIBRARY_LABEL, |a| {
372                let label = a
373                    .get("label")
374                    .and_then(Json::as_str)
375                    .and_then(ColorLabel::parse)
376                    .ok_or("`label` is red, yellow, green, blue or purple")?;
377                let mut out = with_keys(a, json!({ "label": label.name() }));
378                if let Some(on) = a.get("on").and_then(Json::as_bool) {
379                    out["on"] = json!(on);
380                }
381                Ok(out)
382            })
383        },
384    )?;
385    ctx.command(
386        CommandSpec::new(CMD_FLAG, "Flag images", CAT)
387            .description("Picks, rejects or unflags images (`flag`: pick, reject, none): `keys`, else the selection; through `library.flag`.")
388            .args(json!({ "library": "shoot", "keys": [12], "flag": "pick" })),
389        |call| {
390            queue(call, LIBRARY_FLAG, |a| {
391                let flag = a
392                    .get("flag")
393                    .and_then(Json::as_str)
394                    .and_then(Flag::parse)
395                    .ok_or("`flag` is pick, reject or none")?;
396                Ok(with_keys(a, json!({ "flag": flag.name() })))
397            })
398        },
399    )?;
400    ctx.command(
401        CommandSpec::new(CMD_TAG, "Tag images", CAT)
402            .description("Adds tags (`add`) to images and takes others off (`remove`): `keys`, else the selection; through `library.tag`.")
403            .args(json!({ "library": "shoot", "keys": [12], "add": ["beach"], "remove": [] })),
404        |call| {
405            queue(call, LIBRARY_TAG, |a| {
406                let list = |k: &str| -> Result<Vec<String>, String> {
407                    match a.get(k) {
408                        None => Ok(Vec::new()),
409                        Some(v) => parse(v, k),
410                    }
411                };
412                let (add, remove) = (list("add")?, list("remove")?);
413                if add.is_empty() && remove.is_empty() {
414                    return Err("nothing to add (`add`) or remove (`remove`)".into());
415                }
416                Ok(with_keys(a, json!({ "add": add, "remove": remove })))
417            })
418        },
419    )?;
420    ctx.command(
421        CommandSpec::new(CMD_FILTER, "Filter images", CAT)
422            .description("Sets a library's filter (`filter`: `text`, `min_rating`, `labels`, `flags`, `tags`, `from`, `to`; `{}` clears it), through its search field's `library.filter` step.")
423            .args(json!({ "library": "shoot", "filter": { "text": "beach", "min_rating": 3, "labels": ["red"], "flags": ["pick"], "tags": ["sea"], "from": "2024-06-01", "to": "2024-06-30" } })),
424        |call| {
425            queue(call, LIBRARY_FILTER, |a| {
426                let filter = a.get("filter").ok_or("`filter` is missing")?;
427                let parsed: super::filter::Filter = parse(filter, "filter")?;
428                Ok(json!({ "filter": parsed }))
429            })
430        },
431    )?;
432    Ok(())
433}
434
435/// The [`Libraries`] registry of the application, when there is one
436/// and it connected [`LibraryPlugin`].
437pub(crate) fn registry(app: Option<&AppHandle>) -> Option<std::sync::Arc<Libraries>> {
438    #[cfg(feature = "api")]
439    return app.and_then(|a| a.service(&LIBRARIES));
440    #[cfg(not(feature = "api"))]
441    {
442        let _ = app;
443        None
444    }
445}
446
447/// A field of step arguments, typed.
448pub(crate) fn parse<T: DeserializeOwned>(v: &Json, what: &str) -> Result<T, String> {
449    serde_json::from_value(v.clone()).map_err(|e| format!("{what}: {e}"))
450}
451
452/// Runs a step whose default only reports it: the arguments it ran
453/// with (a before-hook may have redirected them), or why it did not.
454pub(crate) fn report(app: Option<&AppHandle>, step: &StepId, args: Json) -> Result<Json, String> {
455    let mut ran = None;
456    let outcome = crate::steps::run(app, step, args.clone(), |a| {
457        ran = Some(a.clone());
458        Ok(a.clone())
459    });
460    match outcome {
461        Outcome::Done(Ok(result)) => {
462            Ok(ran.unwrap_or(if result.is_object() { result } else { args }))
463        }
464        Outcome::Done(Err(reason)) | Outcome::Vetoed { reason, .. } => Err(reason),
465    }
466}