Skip to content
Closed
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ Workspace builds, including the desktop, web and CLI applications, require Rust

```sh
git clone https://github.com/storytold/lightcraft && cd lightcraft
cargo run --release -p lightcraft # opens your library (~/Pictures/LightCraft Library; a new one starts with demo photos)
cargo run --release -p lightcraft # opens your library (~/Pictures/LightCraft Library; a new one asks how to begin)
cargo run --release -p lightcraft -- ~/Pictures/trip # import your photos (folders are scanned, duplicates skipped)
cargo run --release -p lightcraft -- --memory # a throwaway in-memory demo session (writes nothing)
cargo run --release -p lightcraft -- --control 7980 # with the automation channel
Expand Down
16 changes: 9 additions & 7 deletions apps/lightcraft/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
//!
//! The library (catalog, presets, thumbnail cache) lives in `--library DIR`, else
//! `$LIGHTCRAFT_LIBRARY`, else the library last opened with Settings → Open Library…, else
//! `~/Pictures/LightCraft Library`; a new library starts with the
//! procedural demo photos unless `--no-demo` or files are given. Files and folders on the command
//! line are imported (duplicates are skipped). `--memory` runs an in-memory session that writes
//! nothing (demo photos unless files are given; used by the README showcase scripts). A library
//! `~/Pictures/LightCraft Library`; a new library starts empty, and its first screen offers to
//! import photos, a Lightroom catalog, or the procedural sample photos (`library.addSamples`).
//! Files and folders on the command line are imported (duplicates are skipped). `--memory` runs an
//! in-memory session that writes nothing (demo photos unless `--no-demo` or files are given; used
//! by the README showcase scripts). A library
//! that can't be opened is never replaced silently: the window says why and asks what to do
//! (`lightcraft_ui_egui::panels::library_problem`).
//!
Expand Down Expand Up @@ -61,7 +62,7 @@ impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(target_os = "macos")]
if let Some(m) = self.2.as_mut()
&& m.update(&mut self.0, ctx)
&& m.update(&mut self.0)
&& lightcraft_ui_egui::panels::notices::may_close(&mut self.0)
{
// Quit from the menu bar: save exactly what closing the window saves (settings and
Expand Down Expand Up @@ -744,7 +745,8 @@ fn open_library_session(in_memory: bool, dir: Option<std::path::PathBuf>, seed_d
};
let t0 = std::time::Instant::now();
let mut s = Session::new().with_fs().with_default_denoise_models().with_system_clock();
match s.open_library(&dir, seed_demo) {
// a new library starts empty: its first screen asks how to begin (sample photos are one way)
match s.open_library(&dir, false) {
Ok(r) => {
let (replayed, torn) = (r.replayed, r.torn_bytes);
log::info!(
Expand All @@ -770,7 +772,7 @@ USAGE: lightcraft [OPTIONS] [FILES/FOLDERS…] (files and folders are imported

OPTIONS:
--library DIR open (or create) this library (default: ~/Pictures/LightCraft Library; env LIGHTCRAFT_LIBRARY)
--no-demo don't seed a new library with the procedural demo photos
--no-demo with --memory, start without the procedural demo photos
--memory throwaway in-memory session (alias --demo); nothing is saved
--control PORT serve the JSON-lines control channel on 127.0.0.1:PORT (env LIGHTCRAFT_CONTROL_PORT;
see docs/control-protocol.md)
Expand Down
5 changes: 3 additions & 2 deletions apps/lightcraft/src/native_menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ impl NativeMenu {
/// accelerators with the app state. Returns whether Quit was chosen: the caller saves
/// everything and exits the process itself (closing the viewport while AppKit terminates the
/// app can crash in winit's teardown, PR #444).
pub fn update(&mut self, app: &mut LightcraftApp, ctx: &egui::Context) -> bool {
pub fn update(&mut self, app: &mut LightcraftApp) -> bool {
lightcraft_ui_egui::i18n::set_language(app.ui.language);
let mut quit = false;
while let Ok(key) = self.rx.try_recv() {
Expand Down Expand Up @@ -416,7 +416,8 @@ impl NativeMenu {
}
walk(&bar.iter().flat_map(|(_, v)| v.clone()).collect::<Vec<_>>(), &mut self.items);

let focus = ctx.egui_wants_keyboard_input();
// a text field has the keyboard (not a focused plain button, such as the welcome's Import)
let focus = app.text_focus;
let capturing = app.recording_shortcut.is_some();
if focus != self.text_focus || capturing != self.capturing {
self.text_focus = focus;
Expand Down
52 changes: 49 additions & 3 deletions crates/catalog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,13 @@ 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`), and how many of those are in the
/// library (not in Recently Deleted): 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,
#[serde(skip)]
demo_in_library: 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 @@ -396,6 +403,19 @@ impl Catalog {
pub fn is_empty(&self) -> bool {
self.photos.is_empty()
}
/// No photo was ever added (photo ids are never reused): a library as it was created.
pub fn never_held_photos(&self) -> bool {
self.next_photo <= 1
}
/// How many photos are procedural samples (`Source::Demo`), wherever they are (Recently
/// Deleted too).
pub fn sample_photos(&self) -> usize {
self.demo_photos
}
/// How many sample photos are in the library: not in Recently Deleted.
pub fn sample_photos_in_library(&self) -> usize {
self.demo_in_library
}
pub fn album(&self, id: AlbumId) -> Option<&Album> {
self.albums.get(&id)
}
Expand Down Expand Up @@ -616,12 +636,36 @@ impl Catalog {
// the revision was set from outside: what is remembered is of another past
self.changes = Changes { floor: self.revision, seen: self.revision, ..Default::default() };
}
let inv = self.apply_inner(op)?;
let inv = self.apply_counted(op)?;
self.revision += 1;
self.changes.seen = self.revision;
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,
};
// (a sample, a sample in the library) for that photo
let state = |c: &Catalog| {
let p = id.and_then(|id| c.photos.get(&id));
let demo = p.is_some_and(|p| matches!(p.source, Source::Demo { .. }));
(usize::from(demo), usize::from(demo && p.is_some_and(|p| p.in_library())))
};
let before = state(self);
let inv = self.apply_inner(op)?;
let after = state(self);
self.demo_photos = (self.demo_photos + after.0).saturating_sub(before.0);
self.demo_in_library = (self.demo_in_library + after.1).saturating_sub(before.1);
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 @@ -957,12 +1001,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() {
let _ = self.apply_inner(inv);
let _ = self.apply_counted(inv);
}
return Err(e);
}
Expand Down Expand Up @@ -1025,6 +1069,8 @@ 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> {
let demo = || self.photos.values().filter(|p| matches!(p.source, Source::Demo { .. }));
(self.demo_photos, self.demo_in_library) = (demo().count(), demo().filter(|p| p.in_library()).count());
let mut changed = Vec::new();
for (id, p) in self.photos.iter_mut() {
if p.id != *id {
Expand Down
53 changes: 53 additions & 0 deletions crates/engine/src/cmd/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,50 @@ 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.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();
s.commit("Add Sample Photos", Op::Batch { ops })?;
crate::demo::select_first(s);
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, _| {
let (op, removed, albums) = crate::demo::remove_ops(&s.catalog);
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;
}
s.selection = Selection::default();
crate::demo::select_first(s);
Ok(json!({"removed": removed, "albums": albums.len()}))
}
),
cmd!("photo.deletePermanently", "Delete Permanently", ["Photo"], None, "{ids?}", has_selection, |s, p| {
let before = s.visible_cloned();
let t = s.targets(p)?;
Expand Down Expand Up @@ -1755,6 +1799,15 @@ mod gps_tests {
#[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;
130 changes: 124 additions & 6 deletions crates/engine/src/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,92 @@

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);
}

/// The sample scenes the empty library's welcome shows, as (scene id, title): five landscapes of
/// different colours (a lake at dawn, dunes, an aurora, lavender, a beach). None of them comes
/// edited ([`ops`] edits a few others): the one opened is as its thumbnail showed it, and the
/// first slider dragged is the first change.
pub fn welcome_scenes() -> Vec<(u32, String)> {
let scenes = lightcraft_scenes::demo_library();
[1u32, 2, 14, 6, 18].iter().filter_map(|id| scenes.iter().find(|s| s.id == *id).map(|s| (s.id, s.name.clone()))).collect()
}

/// How many sample photos [`ops`] adds.
pub fn sample_count() -> usize {
lightcraft_scenes::demo_library().len()
}

/// A sample scene drawn small for the welcome (`max_edge` on its long side), as it looks before
/// any edit. About 25 ms for one at 320 px on all cores: call it off the UI thread.
pub fn scene_preview(scene: u32, max_edge: usize) -> Option<lightcraft_raster::Rgba8> {
let scenes = lightcraft_scenes::demo_library();
let s = scenes.iter().find(|s| s.id == scene)?;
Some(s.render_fit(max_edge.clamp(16, 1024)).to_srgb8())
}

/// 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);
}
}

/// 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 (bounded: a folder can't hold itself)
let mut changed = true;
let mut rounds = 0;
while changed && rounds < 64 {
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 Op::Batch { mut ops } = c.delete_photos_permanently_ops(&samples) else {
return (Op::Batch { ops: Vec::new() }, 0, Vec::new());
};
// 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 +179,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 Expand Up @@ -332,6 +429,27 @@ fn trim_scene_cache(c: &mut SceneCache, limit: usize) {
mod tests {
use super::*;

#[test]
fn the_welcome_samples_arrive_unedited() {
let mut s = Session::new();
let edited: Vec<u32> = ops(&mut s)
.iter()
.filter_map(|op| match op {
Op::AddPhoto { photo } => match photo.source {
Source::Demo { scene } if *photo.develop != DevelopSettings::default() => Some(scene),
_ => None,
},
_ => None,
})
.collect();
assert!(!edited.is_empty(), "a few samples come edited, for the grid's variety");
let welcome = welcome_scenes();
assert_eq!(welcome.len(), 5, "every scene the welcome shows exists");
for (scene, title) in welcome {
assert!(!edited.contains(&scene), "“{title}” comes edited: its thumbnail would show it otherwise");
}
}

fn small_scene() -> lightcraft_scenes::Scene {
lightcraft_scenes::demo_library().swap_remove(0)
}
Expand Down
Loading