Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions crates/catalog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,10 @@ pub struct Catalog {
/// Lookups derived from the above (never saved), see [`index`].
#[serde(skip)]
index: index::Indexes,
/// How many photos are procedural samples (`Source::Demo`): kept as ops change photos, and
/// counted again by [`Catalog::repair`] on load, so asking needs no scan of a large library.
#[serde(skip)]
demo_photos: usize,
}

/// What of a photo an op changed: enough to tell which tallies of the library an edit leaves as they were (a
Expand Down Expand Up @@ -399,6 +403,11 @@ impl Catalog {
pub fn is_empty(&self) -> bool {
self.photos.is_empty()
}
/// How many photos are procedural samples (`Source::Demo`), wherever they are (Recently
/// Deleted too).
pub fn sample_photos(&self) -> usize {
self.demo_photos
}
pub fn album(&self, id: AlbumId) -> Option<&Album> {
self.albums.get(&id)
}
Expand Down Expand Up @@ -623,7 +632,7 @@ impl Catalog {
}
let broad = self.changes.broad;
self.changes.torn = false;
let inv = match self.apply_inner(op) {
let inv = match self.apply_counted(op) {
Ok(inv) => inv,
Err(e) => {
let made = self.revision.saturating_add(1);
Expand Down Expand Up @@ -652,6 +661,25 @@ impl Catalog {
Ok(inv)
}

/// [`Catalog::apply_inner`], keeping the counts of sample photos: an op that changes one
/// photo (adds, removes, deletes, restores, re-sources it) changes them by what it did to it.
fn apply_counted(&mut self, op: Op) -> Result<Op> {
let id = match &op {
Op::AddPhoto { photo } => Some(photo.id),
Op::RemovePhoto { id } | Op::SetDeleted { id, .. } | Op::SetLocal { id, .. } | Op::Relink { id, .. } | Op::SetFile { id, .. } => {
Some(*id)
}
_ => None,
};
// whether that photo is a sample
let is_sample = |c: &Catalog| id.and_then(|id| c.photos.get(&id)).is_some_and(|p| matches!(p.source, Source::Demo { .. }));
let before = usize::from(is_sample(self));
let inv = self.apply_inner(op)?;
let after = usize::from(is_sample(self));
self.demo_photos = (self.demo_photos + after).saturating_sub(before);
Ok(inv)
}

fn apply_inner(&mut self, op: Op) -> Result<Op> {
// An op that changes one photo says which (`photo_mut`, and adding or removing it below). Every other kind
// can change what any photo matches or where it sorts: an album's photos or rules, a stack, a keyword's
Expand Down Expand Up @@ -987,12 +1015,12 @@ impl Catalog {
Op::Batch { ops } => {
let mut inverses = Vec::with_capacity(ops.len());
for op in ops {
match self.apply_inner(op) {
match self.apply_counted(op) {
Ok(inv) => inverses.push(inv),
Err(e) => {
// roll back what was applied
for inv in inverses.into_iter().rev() {
if self.apply_inner(inv).is_err() {
if self.apply_counted(inv).is_err() {
self.changes.torn = true;
}
}
Expand Down Expand Up @@ -1057,6 +1085,7 @@ impl Catalog {
/// missing, not a folder or inside itself moves to the top level. Returns what was changed
/// (nothing, for a catalog this build wrote).
pub fn repair(&mut self) -> Vec<String> {
self.demo_photos = self.photos.values().filter(|p| matches!(p.source, Source::Demo { .. })).count();
let mut changed = Vec::new();
for (id, p) in self.photos.iter_mut() {
if p.id != *id {
Expand Down
9 changes: 9 additions & 0 deletions crates/engine/src/cmd/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ pub use specs::specs;
#[path = "library/tests_relative_ratings.rs"]
mod relative_rating_tests;

/// `library.addSamples` is for a library without them.
fn no_samples(s: &Session) -> std::result::Result<(), String> {
if s.has_samples() { Err("the sample photos are already in this library".into()) } else { Ok(()) }
}

/// `library.removeSamples` needs sample photos to remove.
fn has_samples(s: &Session) -> std::result::Result<(), String> {
if s.has_samples() { Ok(()) } else { Err("this library has no sample photos".into()) }
}
#[cfg(test)]
#[path = "library/tests_flag_cycle.rs"]
mod flag_cycle_tests;
Expand Down
80 changes: 79 additions & 1 deletion crates/engine/src/cmd/library/specs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use super::selection::{
};
use super::{
Album, AlbumId, ColorLabel, CommandSpec, CopyrightStatus, Filter, Flag, GroupBy, LibrarySource, Op, PhotoId, Result, Selection, Sort, SortKey,
Value, always, bad, bool_or, cmd, has_active, has_library_selection, has_selection, json, ok, str_param,
Value, always, bad, bool_or, cmd, has_active, has_library_selection, has_samples, has_selection, json, no_samples, ok, str_param,
};

/// Seeds stay exactly representable as a JSON double, so web and agent clients read back what they wrote.
Expand Down Expand Up @@ -672,6 +672,84 @@ pub fn specs() -> Vec<CommandSpec> {
Ok(json!({"deleted": ids.len()}))
}
),
cmd!(
"library.addSamples",
"Add Sample Photos",
["Help"],
None,
"{folder?: name of the folder their albums go in (default \"Sample Photos\"; the interface names it in its language)} → {added, albums, folder} — adds the procedural sample photos, their keywords and their albums (in one folder) to the library, to try LightCraft on (one undo step)",
no_samples,
|s, p| {
let folder = match p.get("folder") {
None | Some(Value::Null) => crate::demo::SAMPLES_FOLDER.to_string(),
Some(Value::String(name))
if !name.trim().is_empty() && name.trim().chars().count() <= 200 && !name.trim().chars().any(char::is_control) =>
{
name.trim().to_string()
}
Some(_) => return Err(bad("library.addSamples", "`folder` must be a name of 1 to 200 characters, without control characters")),
};
let ops = crate::demo::ops_in_folder(s, &folder);
let added = ops.iter().filter(|o| matches!(o, Op::AddPhoto { .. })).count();
let albums = ops.iter().filter(|o| matches!(o, Op::AddAlbum { album } if !album.folder)).count();
let added_ids: std::collections::HashSet<PhotoId> = ops
.iter()
.filter_map(|o| match o {
Op::AddPhoto { photo } => Some(photo.id),
_ => None,
})
.collect();
s.commit("Add Sample Photos", Op::Batch { ops })?;
// (a selection the person made stays, and so does an active photo set without one)
if s.selection.ids.is_empty() && s.selection.active.is_none() {
crate::demo::select_first_of(s, &added_ids);
}
Ok(json!({"added": added, "albums": albums, "folder": folder}))
}
),
cmd!(
"library.removeSamples",
"Remove Sample Photos",
["Help"],
None,
"{} → {removed, albums} — removes every sample photo and the albums only they filled; photos of your own and their albums stay (one undo step)",
has_samples,
|s, _| {
// an open drag ends first, as its own undo step (as `photo.deletePermanently`)
s.end_interaction()?;
let before = s.visible_cloned();
let (op, removed, albums) = crate::demo::remove_ops(&s.catalog);
// as `added` counts them: albums, not the folders that held them
let album_count = albums.iter().filter(|id| s.catalog.album(**id).is_some_and(|a| !a.folder)).count();
s.commit("Remove Sample Photos", op)?;
// an album that went can't stay on screen (as `album.delete`)
if matches!(s.source, LibrarySource::Album(a) if albums.contains(&a)) {
s.source = LibrarySource::All;
}
// nor can a filter (or the one put aside) on it: the filter bar has no album chip, so it would narrow the view unseen
for f in std::iter::once(&mut s.filter).chain(s.shelved_filter.as_mut()) {
if f.album.is_some_and(|a| albums.contains(&a)) {
f.album = None;
}
}
// (an empty filter is not left put aside, as in `library.removeFolder`)
if s.shelved_filter.as_ref() == Some(&Filter::default()) {
s.shelved_filter = None;
}
// the person's own photos that were selected stay selected (as `photo.deletePermanently`)
let active_before = s.selection.active;
select_after_deletion(s, &before);
if s.selection.active.is_none() {
crate::demo::select_first(s);
}
// a mask or spot chosen on the photo that went doesn't point into the next one
if s.selection.active != active_before {
s.active_mask = None;
s.active_spot = None;
}
Ok(json!({"removed": removed, "albums": album_count}))
}
),
cmd!("photo.deletePermanently", "Delete Permanently", ["Photo"], None, "{ids?}", has_selection, |s, p| {
let before = s.visible_cloned();
let t = s.targets(p)?;
Expand Down
95 changes: 89 additions & 6 deletions crates/engine/src/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,78 @@

use std::sync::Arc;

use lightcraft_catalog::{Album, Flag, Meta, Op, Photo, Source};
use std::collections::HashSet;

use lightcraft_catalog::{Album, AlbumId, Catalog, Flag, Meta, Op, Photo, PhotoId, Source};
use lightcraft_develop::DevelopSettings;

use crate::Session;

/// Fill the session's catalog with the demo photos and albums directly (no undo step, no
/// journal entry): a new in-memory session, or a new library that asked for them.
pub fn load(s: &mut Session) {
for op in ops(s) {
let _ = s.catalog.apply(op);
}
select_first(s);
}

/// Select the first photo shown, so there is one to look at.
pub fn select_first(s: &mut Session) {
if let Some(first) = s.visible_cloned().first() {
s.selection = crate::Selection::single(*first);
}
}

/// Select the first of `ids` that is shown, so a photo just added is there to look at; nothing
/// changes when none of them is shown (another album is open, a filter hides them).
pub fn select_first_of(s: &mut Session, ids: &HashSet<PhotoId>) {
if let Some(first) = s.visible_cloned().iter().find(|id| ids.contains(id)) {
s.selection = crate::Selection::single(*first);
}
}

/// What takes the sample photos out: every demo photo (wherever it is: albums, stacks), the
/// albums they alone filled, and the folders that held only such albums. An album that also holds
/// a photo of the person's own stays, with that photo (and a cover that was a sample becomes its
/// first photo left). Returns the op, how many photos go, and the albums that go.
pub fn remove_ops(c: &Catalog) -> (Op, usize, Vec<AlbumId>) {
let samples: Vec<PhotoId> = c.photos().filter(|p| matches!(p.source, Source::Demo { .. })).map(|p| p.id).collect();
let gone: HashSet<PhotoId> = samples.iter().copied().collect();
let filled_by_samples =
|a: &Album| !a.folder && a.smart.is_none() && !a.quick && !a.photos.is_empty() && a.photos.iter().all(|p| gone.contains(p));
let mut albums: Vec<AlbumId> = c.albums().filter(|a| filled_by_samples(a)).map(|a| a.id).collect();
// a folder goes when everything in it goes: one level of folders per round, so a chain is
// taken in at most one round per album (bounded, in case the albums hold each other)
let mut changed = true;
let mut rounds = 0;
let most_rounds = c.albums().count() + 1;
while changed && rounds < most_rounds {
rounds += 1;
let emptied: Vec<AlbumId> = c
.albums()
.filter(|f| f.folder && f.photos.is_empty() && !albums.contains(&f.id))
.filter(|f| {
let mut inside = c.albums().filter(|a| a.parent == Some(f.id)).peekable();
inside.peek().is_some() && inside.all(|a| albums.contains(&a.id))
})
.map(|f| f.id)
.collect();
changed = !emptied.is_empty();
albums.extend(emptied);
}
let mut ops = vec![c.delete_photos_permanently_ops(&samples)];
// an album that stays shows one of its own photos, not a removed sample
for a in c.albums().filter(|a| !albums.contains(&a.id) && a.cover.is_some_and(|p| gone.contains(&p))) {
ops.push(Op::SetAlbumCover { id: a.id, cover: a.photos.iter().copied().find(|p| !gone.contains(p)) });
}
// inner albums before the folders that hold them
ops.extend(albums.iter().map(|id| Op::RemoveAlbum { id: *id }));
(Op::Batch { ops }, samples.len(), albums)
}

/// The ops that add the demo photos and albums (ids are taken from the catalog).
pub fn ops(s: &mut Session) -> Vec<Op> {
let scenes = lightcraft_scenes::demo_library();
let mut ids = Vec::new();
let mut ops = Vec::new();
Expand Down Expand Up @@ -99,12 +165,29 @@ pub fn load(s: &mut Session) {
album: Album { id, name: name.into(), parent, folder: false, photos, cover, smart: None, quick: false, order: None },
});
}
for op in ops {
let _ = s.catalog.apply(op);
}
if let Some(first) = s.visible_cloned().first() {
s.selection = crate::Selection::single(*first);
ops
}

/// The name of the folder [`ops_in_folder`] puts the sample albums in, unless asked for another
/// (the interface asks for it in its language).
pub const SAMPLES_FOLDER: &str = "Sample Photos";

/// [`ops`], with every album in one folder named `folder`, so the samples' albums stay together
/// and apart from the ones the person makes.
pub fn ops_in_folder(s: &mut Session, folder: &str) -> Vec<Op> {
let mut ops = ops(s);
let id = s.catalog.alloc_album_id();
for op in &mut ops {
if let Op::AddAlbum { album } = op
&& album.parent.is_none()
{
album.parent = Some(id);
}
}
let at = ops.iter().position(|op| matches!(op, Op::AddAlbum { .. })).unwrap_or(ops.len());
let album = Album { id, name: folder.into(), parent: None, folder: true, photos: vec![], cover: None, smart: None, quick: false, order: None };
ops.insert(at, Op::AddAlbum { album });
ops
}

/// Procedural scenes are deterministic but costly to evaluate: every pixel runs the scene's noise
Expand Down
6 changes: 6 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1292,6 +1292,12 @@ impl Session {
self.total.as_ref().map(|t| t.1)
}

/// The library holds sample (demo) photos, Recently Deleted included. Asked each frame (the
/// Help menu's enabled state): the catalog keeps the count, so it costs no scan.
pub fn has_samples(&self) -> bool {
self.catalog.sample_photos() > 0
}

pub fn visible_cloned(&mut self) -> Vec<PhotoId> {
self.visible().to_vec()
}
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ mod presets_scale;
mod print;
mod process;
mod recheck;
mod samples;
mod segment;
mod settings_files;
mod slide;
Expand Down
Loading
Loading