Skip to content
Open
Show file tree
Hide file tree
Changes from 6 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: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions contributors/people.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,6 @@ sync_github_name = true
[people.Peaperfish]
real_name = "Yule Wang"
display_name = "Brian Wang"

[people.pixelpuxel]
real_name = "Gabriel Schreiber"
25 changes: 2 additions & 23 deletions crates/engine/src/cmd/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,29 +128,8 @@ pub fn specs() -> Vec<CommandSpec> {
}),
cmd!(query "photo.allMetadata", "All Metadata", [], None, "{id?} → {exif: [{group, tag, name, value}], xmp: [{name, value}]} — every EXIF / TIFF / GPS tag of the file and its XMP properties", always, |s, p| {
let id = photo_arg(s, p, "photo.allMetadata")?;
let ph = s.catalog.photo(id).ok_or_else(|| super::bad("photo.allMetadata", "no such photo"))?.clone();
let lightcraft_catalog::Source::File { path } = &ph.source else {
return Ok(json!({"exif": [], "xmp": [], "note": "a generated demo photo has no file"}));
};
let bytes = match &s.media.file_bytes {
Some(r) => r(path),
None => std::fs::read(path).map_err(|e| format!("{path}: {e}")),
}
.map_err(|e| super::bad("photo.allMetadata", e))?;
let exif: Vec<Value> = lightcraft_meta::file_tag_rows(&bytes)
.into_iter()
.map(|r| json!({"group": r.group, "tag": r.tag, "name": r.name, "value": r.value}))
.collect();
// Keep sidecar precedence; reuse the loaded bytes for embedded XMP.
let packet = match s.sidecar_lookup(ph.id).find(path) {
Some(sc) => std::fs::read_to_string(sc).ok(),
None => lightcraft_meta::embedded(&bytes).xmp,
};
let xmp: Vec<Value> = packet
.and_then(|x| lightcraft_meta::parse_xmp(&x).ok())
.map(|d| d.properties.into_iter().filter(|(k, _)| !k.starts_with("lc:")).map(|(k, v)| json!({"name": k, "value": v.join("; ")})).collect())
.unwrap_or_default();
Ok(json!({"exif": exif, "xmp": xmp}))
crate::metadata_read::Request::new(s, id).and_then(|request| request.read())
.map_err(|e| super::bad("photo.allMetadata", e))
}),
cmd!(query "albums.list", "List Albums", [], None, "{}", always, |s, _| {
let all: Vec<Album> = s.catalog.albums().cloned().collect();
Expand Down
13 changes: 13 additions & 0 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub mod logging;
pub mod media;
pub mod memory;
pub mod merge;
pub mod metadata_read;
mod model_download;
pub mod open_path;
pub mod originals;
Expand Down Expand Up @@ -1072,6 +1073,18 @@ impl Session {
self.shelved_filter.is_some()
}

/// Clear matching view rules from both the live filter and the filter put aside by Enable Filters.
pub fn clear_view_rules(&mut self, rules: &lightcraft_catalog::RuleSet) {
if self.filter.rule_set.as_ref() == Some(rules) {
self.filter.rule_set = None;
}
if let Some(filter) = &mut self.shelved_filter
&& filter.rule_set.as_ref() == Some(rules)
{
filter.rule_set = None;
}
}

/// Photos shown in the grid/filmstrip for the current source, filter and sort.
pub fn visible(&mut self) -> &[PhotoId] {
let mut key =
Expand Down
61 changes: 61 additions & 0 deletions crates/engine/src/metadata_read.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
//! A read-only metadata request that can be moved to a UI worker.

use crate::{Session, merge::ByteReader, sidecar::SidecarLookup};
use lightcraft_catalog::{PhotoId, Source};
use serde_json::{Value, json};

pub struct Request {
source: Source,
read: Option<ByteReader>,
sidecar: SidecarLookup,
}

impl Request {
pub fn new(session: &Session, id: PhotoId) -> Result<Self, String> {
let photo = session.catalog.photo(id).ok_or("no such photo")?;
Ok(Self { source: photo.source.clone(), read: session.media.file_bytes.clone(), sidecar: session.sidecar_lookup(id) })
}

pub fn read(self) -> Result<Value, String> {
let (mut value, warning) = self.read_with_diagnostics()?;
if let Some(warning) = warning
&& let Some(fields) = value.as_object_mut()
{
fields.insert("warning".into(), Value::String(warning));
}
Ok(value)
}

pub fn read_with_diagnostics(self) -> Result<(Value, Option<String>), String> {
let Source::File { path } = self.source else {
return Ok((json!({"exif": [], "xmp": [], "note": "a generated demo photo has no file"}), None));
};
let bytes = match self.read {
Some(read) => read(&path),
None => std::fs::read(&path).map_err(|e| format!("{path}: {e}")),
}?;
let exif: Vec<Value> = lightcraft_meta::file_tag_rows(&bytes)
.into_iter()
.map(|row| json!({"group": row.group, "tag": row.tag, "name": row.name, "value": row.value}))
.collect();
let packet = match self.sidecar.find(&path) {
Some(sidecar) => std::fs::read_to_string(&sidecar).map(Some).map_err(|error| format!("{}: {error}", sidecar.display())),
None => Ok(lightcraft_meta::embedded(&bytes).xmp),
};
let parsed =
packet.and_then(|packet| packet.map(|xmp| lightcraft_meta::parse_xmp(&xmp).map_err(|error| format!("XMP: {error}"))).transpose());
let warning = parsed.as_ref().err().cloned();
let xmp: Vec<Value> = parsed
.ok()
.flatten()
.map(|d| {
d.properties
.into_iter()
.filter(|(key, _)| !key.starts_with("lc:"))
.map(|(key, values)| json!({"name": key, "value": values.join("; ")}))
.collect()
})
.unwrap_or_default();
Ok((json!({"exif": exif, "xmp": xmp}), warning))
}
}
2 changes: 2 additions & 0 deletions crates/ui-egui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ egui = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
chrono = { workspace = true }
sys-locale = { version = "0.3", features = ["js"] }

[dev-dependencies]
# tests record why they skip (`cargo xtask ci` lists the skips)
Expand Down
10 changes: 10 additions & 0 deletions crates/ui-egui/locales/de.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
{
"Waiting for an earlier metadata read to finish…": "Warte auf einen vorherigen Metadatenzugriff…",
"Metadata read timed out. Try Refresh.": "Zeitlimit beim Lesen der Metadaten erreicht. Versuche es mit Aktualisieren.",
"Refresh": "Aktualisieren",
"Keys": "Keys",
"Combine Albums": "Sammlungen verknüpfen",
"OR: any album": "ODER: beliebige Sammlung",
"AND: every album": "UND: jede Sammlung",
"First minus others": "Erste minus weitere",
"Only one album": "Nur in einer Sammlung",
"Cmd/Ctrl-click albums to combine. A plain click shows one album.": "Sammlungen mit Cmd/Strg-Klick verknüpfen. Ein einfacher Klick zeigt eine Sammlung.",
" (library default)": " (Bibliotheksstandard)",
" (inverted)": " (umgekehrt)",
" · best of its burst": " · bestes Foto der Serie",
Expand Down
139 changes: 139 additions & 0 deletions crates/ui-egui/src/album_combination.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
//! Live set operations over albums, expressed as the catalog's existing smart-album rules.
//! Membership updates are reflected immediately, without duplicating or moving photos.

use crate::LightcraftApp;
use lightcraft_catalog::rules::Match;
use lightcraft_catalog::{AlbumId, Rule, RuleSet};
use lightcraft_engine::LibrarySource;
use serde_json::{Value, json};

pub const OPERATIONS: &[(&str, &str)] =
&[("union", "OR: any album"), ("intersection", "AND: every album"), ("difference", "First minus others"), ("exclusive", "Only one album")];

fn field(id: u64, included: bool) -> Rule {
Rule::Field { field: "album".into(), op: if included { "is" } else { "isNot" }.into(), value: json!(id) }
}

fn rules(ids: &[u64], operation: &str) -> Result<RuleSet, String> {
let (mode, rules) = match operation {
"union" => (Match::Any, ids.iter().map(|id| field(*id, true)).collect()),
"intersection" => (Match::All, ids.iter().map(|id| field(*id, true)).collect()),
"difference" => (Match::All, ids.iter().enumerate().map(|(i, id)| field(*id, i == 0)).collect()),
// For two albums this is XOR. With more albums, keep photos belonging to exactly one.
"exclusive" => (
Match::Any,
ids.iter()
.map(|id| Rule::Group { group: RuleSet { mode: Match::All, rules: ids.iter().map(|other| field(*other, id == other)).collect() } })
.collect(),
),
_ => return Err("view.combineAlbums: unknown operation (union|intersection|difference|exclusive)".into()),
};
Ok(RuleSet { mode, rules })
}

/// Remove only the rules installed by this view, preserving unrelated filters.
pub fn clear(app: &mut LightcraftApp) {
if let Some((ids, operation)) = app.ui.album_combination.take()
&& let Ok(set) = rules(&ids, &operation)
{
app.session.clear_view_rules(&set);
}
}

pub fn active(app: &LightcraftApp) -> bool {
app.ui.album_combination.as_ref().is_some_and(|(ids, op)| {
(2..=8).contains(&ids.len())
&& app.session.source == LibrarySource::All
&& rules(ids, op).is_ok_and(|set| app.session.filter.rule_set.as_ref() == Some(&set))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
})
}

pub fn command(app: &mut LightcraftApp, params: &Value) -> Result<Value, String> {
let values = params.get("ids").and_then(Value::as_array).ok_or("view.combineAlbums: ids must be an array")?;
if !(2..=8).contains(&values.len()) {
return Err("view.combineAlbums: choose 2 to 8 albums".into());
}
let mut ids = Vec::new();
for value in values {
let id = value.as_u64().ok_or("view.combineAlbums: invalid album id")?;
if app.session.catalog.album(AlbumId(id)).is_none_or(|a| a.folder) {
return Err(format!("view.combineAlbums: no album {id}"));
}
if !ids.contains(&id) {
ids.push(id);
}
}
if ids.len() < 2 {
return Err("view.combineAlbums: choose two distinct albums".into());
}
let operation = match params.get("operation") {
None => "union",
Some(value) => value.as_str().ok_or("view.combineAlbums: operation must be a string")?,
};
let set = rules(&ids, operation)?;
let problems = set.check(&app.session.catalog);
if !problems.is_empty() {
return Err(problems.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "));
}
// A source choice starts a fresh view; ordinary filters can be applied to the result next.
let filter = lightcraft_catalog::Filter { rule_set: Some(set), ..Default::default() };
let filter = serde_json::to_value(filter).map_err(|e| e.to_string())?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
app.session.source = LibrarySource::All;
app.session.execute("library.filter", &filter).map_err(|e| e.to_string())?;
app.ui.search.clear();
app.ui.album_combination = Some((ids, operation.into()));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
app.session.keep_active_in_view();
Ok(json!({"count": app.session.visible().len(), "operation": operation}))
}

/// A modifier-click adds or removes an album; a plain click still shows just that album.
pub fn toggle(app: &mut LightcraftApp, id: u64) {
let (mut ids, operation) = if active(app) {
app.ui.album_combination.clone().unwrap_or_default()
} else {
let ids = match app.session.source {
LibrarySource::Album(a) => vec![a.0],
_ => Vec::new(),
};
(ids, "union".into())
};
if ids.contains(&id) {
ids.retain(|a| *a != id);
} else {
ids.push(id);
}
let result = if ids.len() >= 2 {
app.run("view.combineAlbums", json!({"ids": ids, "operation": operation}))
} else if let Some(id) = ids.first() {
app.run("library.source", json!({"kind": "album", "id": id}))
} else {
app.run("library.source", json!({"kind": "all"}))
};
if let Err(e) = result {
app.toast(&app.tasks.repaint.clone().unwrap_or_default(), e);
}
}

pub fn controls(app: &mut LightcraftApp, ui: &mut egui::Ui) {
if !active(app) {
return;
}
let Some((ids, mut operation)) = app.ui.album_combination.clone() else { return };
let before = operation.clone();
ui.label(crate::i18n::tr("Combine Albums"));
ui.horizontal_wrapped(|ui| {
for (id, label) in OPERATIONS {
let response = ui.selectable_value(&mut operation, (*id).into(), crate::i18n::tr(label));
crate::widgets::register(ui, format!("albumOperation:{id}"), response.rect);
}
});
let names: Vec<_> = ids.iter().filter_map(|id| app.session.catalog.album(AlbumId(*id))).map(|a| a.name.as_str()).collect();
ui.label(names.join(" → "));
ui.label(crate::i18n::tr("Cmd/Ctrl-click albums to combine. A plain click shows one album."));
if before != operation
&& let Err(e) = app.run("view.combineAlbums", json!({"ids": ids, "operation": operation}))
{
app.toast(ui.ctx(), e);
}
ui.separator();
}
19 changes: 18 additions & 1 deletion crates/ui-egui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ impl LightcraftApp {
native_menu: false,
native_shortcuts: Default::default(),
recording_shortcut: None,
metadata_panel: Default::default(),
text_focus: false,
headless_host: false,
notices: vec![],
Expand Down Expand Up @@ -212,7 +213,23 @@ impl LightcraftApp {
} else {
params
};
let r = self.session.execute(id, &params).map_err(CommandError::from);
let combined = self.ui.album_combination.is_some();
let mut r = self.session.execute(id, &params).map_err(CommandError::from);
let member_removed = combined
&& self
.ui
.album_combination
.as_ref()
.is_some_and(|(ids, _)| ids.iter().any(|id| self.session.catalog.album(lightcraft_catalog::AlbumId(*id)).is_none()));
if r.is_ok() && combined && (id == "library.source" || member_removed) {
crate::album_combination::clear(self);
self.session.keep_active_in_view();
if id == "library.source"
&& let Ok(result) = &mut r
{
*result = serde_json::json!({"count": self.session.visible().len()});
}
}
if r.is_ok() && matches!(id, "crop.aspect" | "crop.rotateAspect") {
self.ui.crop_default_aspect = if id == "crop.aspect" && params.get("aspect").and_then(Value::as_str) == Some("original") {
Some(serde_json::json!("original"))
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/dialogs/import/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ pub fn browse(app: &mut LightcraftApp, path: &str, subfolders: Option<bool>) ->
if app.scan.as_ref().is_some_and(|t| !t.browse) || app.import.as_ref().is_some_and(|t| !t.browse) {
return Err("an import is running".into());
}
crate::album_combination::clear(app);
let dir_s = dir.to_string_lossy().trim_end_matches(['/', '\\']).to_string();
let subfolders = subfolders.unwrap_or_else(|| app.session.browse.as_ref().is_some_and(|b| b.subfolders));
let running = app.scan.as_ref().is_some_and(|t| t.browse) || app.import.as_ref().is_some_and(|t| t.browse);
Expand Down
31 changes: 18 additions & 13 deletions crates/ui-egui/src/dialogs/keymap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,10 @@ const SHOW_ALL: &str = "shortcuts-show-all";
pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
let mac = ui.ctx().os() == egui::os::OperatingSystem::Mac;
capture(app, ui.ctx());
ui.set_min_width(560.0);
let (search_id, all_id) = (egui::Id::unique(SEARCH), egui::Id::unique(SHOW_ALL));
let mut search: String = ui.data(|d| d.get_temp(search_id)).unwrap_or_default();
let mut show_all: bool = ui.data(|d| d.get_temp(all_id)).unwrap_or(false);
ui.horizontal(|ui| {
ui.horizontal_wrapped(|ui| {
let r = ui.add(egui::TextEdit::singleline(&mut search).hint_text(crate::i18n::tr("Search commands or keys")).desired_width(220.0));
register(ui, "field:shortcutsSearch", r.rect);
let r = ui.checkbox(&mut show_all, crate::i18n::tr("Show commands without a shortcut"));
Expand Down Expand Up @@ -63,18 +62,24 @@ pub fn body(app: &mut LightcraftApp, ui: &mut egui::Ui, t: &Tokens) {
// a fixed height, so the dialog doesn't jump around while the search narrows the list
// (shorter on a short window, so the dialog fits it)
let h = crate::panels::dialogs::list_height(ui, 400.0);
egui::ScrollArea::vertical().max_height(h).min_scrolled_height(h).auto_shrink([false, false]).id_salt("shortcuts-list").show(ui, |ui| {
egui::Grid::new("shortcuts").striped(true).num_columns(4).spacing([12.0, 4.0]).show(ui, |ui| {
for (b, sc) in &rows {
row(app, ui, t, b, sc.as_deref(), mac);
}
if rows.is_empty() {
ui.label(RichText::new(crate::i18n::tr("No matching commands")).color(t.text_dim));
ui.end_row();
}
egui::ScrollArea::both()
.max_width(ui.available_width())
.max_height(h)
.min_scrolled_height(h)
.auto_shrink([false, false])
.id_salt("shortcuts-list")
.show(ui, |ui| {
egui::Grid::new("shortcuts").striped(true).num_columns(4).spacing([12.0, 4.0]).show(ui, |ui| {
for (b, sc) in &rows {
row(app, ui, t, b, sc.as_deref(), mac);
}
if rows.is_empty() {
ui.label(RichText::new(crate::i18n::tr("No matching commands")).color(t.text_dim));
ui.end_row();
}
});
fixed_keys(app, ui, t, mac, &needle);
});
fixed_keys(app, ui, t, mac, &needle);
});
}

/// `Cmd+Shift+Z` as menus show it (`⇧⌘Z` on macOS).
Expand Down
Loading