Merge storytold/main into fix/2575-geocode-dataset-params

This commit is contained in:
insideTheFlux committed 2026-10-28 08:17:49 -07:00
commit 1b28224afd
656 files changed
+121623 -69343

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
<!--
Title: start with the checklist id or the issue, as the commits do:
`LR-IMP-FORMATS: folder import finds Sony SR2 and SRF files`, or `Issue #123: …` when there is no checklist row.
One change per pull request. Unrelated fixes and clean-ups (clippy, formatting, a second feature) go in their own:
small ones land fast, bundles get sent back to be split. The rules are in AGENTS.md.
Delete the sections and lines that don't apply, and these comments. A translation or a one-line fix needs only the
first three sections.
-->
Fixes #
<!-- `Part of #123` when this does only part of the issue. Built on another open pull request? Say so here
(`Stacked on #123`) and name the commits that are this one's own. -->
## Problem
<!-- What is wrong or missing, as a person using the app meets it. For a bug: the cause. -->
## Change
<!-- What you changed and where. -->
**Not in this PR:** <!-- what you left out on purpose, and known limits -->
## How it was checked
- [ ] `cargo xtask ci` passes on this branch, rebased on current `main`
- [ ] A test that fails without this change (for a crash fix: a regression test that panicked before it)
- [ ] User-visible change: ran the app and looked at the result
<!-- Numbers, when it changes rendering, decoding or speed: before and after, on more than one photo or camera
(ΔE against the reference, `cargo xtask bench`, `/usr/bin/time`, memory). Name the files or corpus entries used. -->
## Screenshots
<!-- For a visible change: before and after, labelled. Never a screenshot of an Adobe app. -->
## Merging
<!-- Pull requests land in batches, merged together. This is what the person merging can't see in the diff. -->
- **Overlap:** <!-- open pull requests that fix the same issue or change the same functions, by number, and how
this one differs. Search the open pull requests for the issue number and checklist id first. "none found" is fine. -->
- **Existing edits and libraries:** <!-- does any photo already edited render differently, or any saved setting,
preset, sort order or default change? Then it goes behind a new process version (docs/process-versions.md) or is a
setting that is off by default, with a line in docs/whats-new.md. "unchanged" is fine. -->
- **Shared numbers taken:** <!-- catalog format `VERSION` (crates/catalog/src/journal.rs), `RENDER_CACHE_VERSION`,
`LOOK_VERSION`, process version: the number this takes. If another pull request lands with it first, take one
past main's when you rebase. -->
- **Where it came from:** <!-- for a decoder, camera or lens data, or fitted constants: the public spec, your own
measurements, or observed output, and the files measured. Never GPL / LGPL code (dcraw, LibRaw, rawspeed, darktable,
RawTherapee, lensfun …), text derived from it, or Adobe profiles. -->
- **New dependencies, `unsafe`, build scripts, network access, spawned processes, deleted files, CI or `xtask` gate
changes:** <!-- each with its reason, or "none". Dependencies are pure Rust and use `workspace = true`; actions are
pinned by SHA; downloads are checked against a sha256; nothing leaves the machine unless the person asked. -->
## Checklist
- [ ] No new panic path in non-test code: no `unwrap` / `expect` / `panic!`, no indexing or unchecked arithmetic on a
number from a file, a person or an agent (`get`, `checked_mul`, NaN and char boundaries handled)
- [ ] New text on screen goes through `tr()` and has its key in `crates/ui-egui/locales/*.json`; a new shortcut is
free in `docs/library-shortcuts.md`
- [ ] The feature's rows in `docs/parity-checklist.md` and its entry in `docs/gaps.md` are updated, honestly (🟡 when
it is partial), in the same commit
- [ ] New code has a caller: no command, module or setting that nothing reaches yet
- [ ] Every new image, icon or other asset has its entry in `assets/ATTRIBUTION.md`; no font or media files added
- [ ] Ready to merge (otherwise open it as a draft)
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
# Same craft-fonts commit as release.yml.
craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
timeout-minutes: 90
# xtask ci runs cargo test: the demo scene cache is per process, so nextest is slower here.
tools: ""
+1 -1
View File
@@ -28,4 +28,4 @@ jobs:
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
with:
require-craft-fonts: true
craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
+24
View File
@@ -37,3 +37,27 @@ jobs:
run: |
./packaging/windows/test-install-folder.ps1 -Arch x64
./packaging/windows/test-install-folder.ps1 -Arch x86
windows-install-policy:
timeout-minutes: 10
name: Windows installation policy (no app build)
runs-on: windows-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install the pinned packaging toolchain
shell: pwsh
run: |
$tools = Join-Path $env:RUNNER_TEMP 'craft-install-policy-wix'
dotnet tool install --tool-path $tools wix --version 5.0.2
if ($LASTEXITCODE -ne 0) { throw 'WiX installation failed.' }
$tools >> $env:GITHUB_PATH
$policy = Get-Content -Raw -LiteralPath packaging/windows/install-policy.json | ConvertFrom-Json
foreach ($extension in @($policy.extensions)) {
& (Join-Path $tools 'wix.exe') extension add -g "WixToolset.$extension.wixext/5.0.2"
if ($LASTEXITCODE -ne 0) { throw "WiX extension $extension installation failed." }
}
- name: Build and check non-executable installer fixtures
shell: pwsh
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
+1 -1
View File
@@ -66,7 +66,7 @@ jobs:
with:
app-name: lightcraft
app-title: LightCraft
craft-fonts-ref: a71c20e30af613287c504f7e685ca8fad77752bc
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
web-craft-fonts: true
version: ${{ inputs.version }}
secrets:
+7 -1
View File
@@ -16,6 +16,12 @@ concurrency:
jobs:
sonarcloud:
# Tracked at @main so org-wide CI improvements propagate without PR churn.
# Track shared CI improvements on main.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
with:
shards: 8
python-coverage-source: packaging/linux/flatpak
python-coverage-script: packaging/linux/flatpak/test_generate_cargo_sources.py
timeout-minutes: 120
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
secrets: inherit
+4 -2
View File
@@ -27,8 +27,10 @@ permissions:
jobs:
windows-arm64:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@main
# Immutable supporting workflow revision until the new install contract lands upstream.
uses: storytold/craft-common-actions/.github/workflows/windows-arm64.yml@8bb4e5ab95443171104ad88113fe1ef9b0e5ce3f
with:
app-name: lightcraft
app-dir: LightCraft
install-relative-path: Programs/ArtCraft/LightCraft
install-scope: perUser
+1 -1
View File
@@ -51,7 +51,7 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
- **Last-resort guard:** a panic hook plus `catch_unwind` around command dispatch and import/export turns an escaped
panic into an error dialog and keeps the document. It's a safety net, not a licence; keep `panic = "unwind"` on native.
- **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix.
- Enforced by clippy: root `clippy.toml` allows unwrap/expect/panic/indexing in tests only, and every production crate
- Enforced by clippy: root `clippy.toml` allows unwrap/expect/panic in tests only; indexing is not denied. Every production crate
root (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Not `[workspace.lints]`: those would also hit
integration tests, examples and benches. New crates start with the attribute.
+11 -5
View File
@@ -52,10 +52,13 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
- **Last-resort guard:** a panic hook plus `catch_unwind` around command dispatch and import/export turns an escaped
panic into an error dialog and keeps the document. It's a safety net, not a licence; keep `panic = "unwind"` on native.
- **Prove it:** every crash fix lands with a small synthetic regression test that panicked before the fix.
- Enforced by clippy: root `clippy.toml` allows unwrap/expect/panic/indexing in tests only, and every production crate
root (`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Not `[workspace.lints]`: those would also hit
integration tests, examples and benches. New crates start with the attribute.
- Enforced by clippy: root `clippy.toml` keeps unwrap/expect/panic allowances scoped to tests; indexing is not denied. The workspace
denies `cognitive_complexity`, `too_many_arguments` and `wildcard_imports`; members inherit them with
`[lints] workspace = true`, and `sysmem` repeats those denies in its local lint table. Every production crate root
(`lib.rs`, each binary's `main.rs`) carries `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic,
clippy::unimplemented, clippy::todo, clippy::unreachable)]`. Every new workspace crate must include
`[lints] workspace = true` in `Cargo.toml` to inherit `[workspace.lints]`, and new production crate roots include
the attribute before modules or other crate items; crate-level `//!` documentation may precede it.
## Non-negotiables
- **Clean-room.** Never read/disassemble anything inside Adobe app bundles (names/listings only). Never copy Adobe icons, presets, profiles (DCP), lens profiles (LCP), camera matrices, fonts. Observation of the installed Lightroom is read-only (it syncs the user's personal library: never import/edit/rate/delete there). Never copy GPL/LGPL/AGPL code (darktable, RawTherapee, ART, LibRaw, rawspeed, rawloader, rawler, lensfun, dcraw-derived GPL code…).
@@ -68,7 +71,10 @@ of it. Full standard: `../craftrules/standards/never-crash.md`
`Cancel::No` when the job can't stop. No progress window, panel or progress toast of its own; its tests assert the row.
- **Resolution independence:** settings use normalized image coordinates and relative radii; previews and exports must match.
- **Time goes through `chrono`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a crate owns only its output format string. The one exception is range extension: past the years chrono can represent, shift the date by whole 400-year Gregorian cycles (146,097 days, after which the calendar repeats), let chrono compute the month and day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is plain arithmetic).
- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm).
- **Quality gates** before every commit: `cargo xtask ci --quick` (fmt, clippy -D warnings, the changed packages'
tests, layers, assets, and heif / parity / wasm when touched). GitHub runs the full `cargo xtask ci` on every PR
(`.github/workflows/ci.yml`); run the full one locally before merging branches (below) or when `--quick` can't see
the risk. One `ci` runs at a time per machine; others wait their turn (`xtask/src/ci_lock.rs`).
- **Commits:** one task id per commit (`M2.3: local Laplacian highlights/shadows`). Only green states. End messages with the attribution line required by the environment.
## Assets: icons, images, fonts (ABSOLUTE RULE — never violate)
Generated
+1195 -307
View File
File diff suppressed because it is too large. Load diff
+37 -11
View File
@@ -3,15 +3,17 @@ resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
[workspace.package]
version = "0.13.0"
version = "0.14.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.90"
rust-version = "1.95"
repository = "https://github.com/storytold/lightcraft"
[workspace.dependencies]
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "5c874d51eeb3de70e735c8ce87a59a7dedd47675", features = ["serde"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
# internal
lightcraft-denoise-core = { path = "crates/denoise-core" }
lightcraft-denoise = { path = "crates/denoise", default-features = false }
@@ -52,6 +54,7 @@ log = "0.4"
# All date/time conversion goes through chrono (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md).
chrono = { version = "0.4.45", default-features = false, features = ["std"] }
rayon = "1"
winapi-util = "0.1" # lightcraft-catalog reads a file's volume serial number and file index with it on Windows
proptest = "1"
bytemuck = { version = "1", features = ["derive"] }
crc32fast = "1"
@@ -60,8 +63,8 @@ libc = "0.2" # dev-only: process CPU time in benches
dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and heap tests; never in product builds
# formats
quick-xml = "0.38"
miniz_oxide = "0.8"
quick-xml = "0.41"
miniz_oxide = "0.9"
# codecs
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "webp"] }
@@ -91,10 +94,13 @@ wgpu = { version = "30", default-features = false, features = ["std", "parking_l
pollster = "1"
# ui
egui = "0.36"
egui_extras = { version = "0.36", default-features = false }
eframe = { version = "0.36", default-features = false }
egui_kittest = "0.36"
# 0.37: `default_fonts` is no longer an egui default and the monochrome emoji faces moved behind
# `monochrome_emoji_fonts`. Every resolution root (native, CLI/headless, kittest, wasm) needs both:
# kittest's own dev-dependencies do not propagate to its consumers.
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
egui_extras = { version = "0.37", default-features = false }
eframe = { version = "0.37", default-features = false }
egui_kittest = "0.37"
rfd = "0.17"
muda = { version = "0.21", default-features = false } # native menu bar (macOS: objc2/AppKit, pure Rust; no GTK)
# macOS: the profile of the screen showing the window (safe AppKit bindings; muda and wgpu use the same)
@@ -116,9 +122,11 @@ web-sys = "0.3"
unsafe_code = "deny"
[workspace.lints.clippy]
cognitive_complexity = "deny"
too_many_arguments = "deny"
wildcard_imports = "deny"
dbg_macro = "warn"
todo = "warn"
too_many_arguments = "allow"
needless_range_loop = "allow"
type_complexity = "allow"
excessive_precision = "allow"
@@ -169,3 +177,21 @@ jpeg-decoder = { opt-level = 3 }
jpeg-encoder = { opt-level = 3 }
png = { opt-level = 3 }
miniz_oxide = { opt-level = 3 }
# Keep the complete egui family and native event bridge on reviewed fork commits.
[patch.crates-io]
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+279 -6
View File
@@ -12,7 +12,9 @@ Third-party material
This product bundles third-party material under its own licenses, listed below. The per-file
list (author, source, license) is in assets/ATTRIBUTION.md.
Inter (assets/fonts/Inter-*.ttf) — SIL Open Font License 1.1. See assets/fonts/OFL-Inter.txt.
Inter (assets/fonts/Inter-*.ttf) — SIL Open Font License 1.1. The licence text is
assets/fonts/OFL-Inter.txt in the source tree; release packages ship it beside NOTICE as
OFL-Inter.txt (Windows installers include it in FONT-LICENCES.txt).
Showcase photographs by Ansel Adams, Dorothea Lange and NASA (docs/images/) — public domain. See assets/ATTRIBUTION.md.
crates/raw/src/spectral_table.rs (lightcraft-raw) holds camera colour matrices derived from the
@@ -50,11 +52,15 @@ maintainer decision. The ONNX reader and CPU/GPU executor are our Rust implement
no darktable, RawSpeed, LibRaw or other GPL decoder/runtime code is included.
Builds made with craft-fonts (the optional CRAFT_FONTS_DIR build input; all official releases)
also embed the fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md
(BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic and Noto Sans
Thai), under the SIL Open Font License 1.1. The web build embeds BIZ UDPGothic Regular and Noto
Sans Thai Regular, and loads Noto Sans CJK SC separately. Release packages include each font's
licence as OFL-<family>.txt; Windows installers include their texts in FONT-LICENCES.txt.
also embed the default fonts listed in
https://github.com/storytold/craft-fonts/blob/b076417b5880bd4154bd22f00695b1d28c6bea83/ATTRIBUTION.md (BIZ UDPGothic, BIZ UDMincho,
Shippori Mincho, Noto Sans CJK SC, Noto Sans Arabic, Noto Sans Thai, Noto Sans Georgian,
NanumGothic, Noto Sans Symbols, Noto Sans Symbols 2, Noto Sans Hebrew and
Noto Sans Devanagari), under the SIL Open Font License 1.1. The opt-in LXGW WenKai Lite face
(fonts/simplified-chinese-manifest.txt in craft-fonts) is not embedded. The web build embeds
BIZ UDPGothic Regular, Noto Sans Thai Regular and Noto Sans Georgian Regular, and loads Noto Sans
CJK SC separately. Release packages include each font's licence as OFL-<family>.txt; Windows
installers include their texts in FONT-LICENCES.txt.
Place names for reverse geocoding (Photo > Fill Location from GPS) are not part of LightCraft and
are never distributed with it. On the user's request (Photo > Download Place Names) the app
@@ -62,3 +68,270 @@ downloads cities15000.zip, admin1CodesASCII.txt and countryInfo.txt from GeoName
(https://download.geonames.org/export/dump/) into the settings folder. GeoNames data is licensed
under Creative Commons Attribution 4.0 (https://creativecommons.org/licenses/by/4.0/);
attribution: "GeoNames, geonames.org". The lookup code (crates/geocode) is our own.
epaint_default_fonts, the egui default-font crate LightCraft builds with, also bundles Hack Regular
and Ubuntu Light, and Noto Emoji Regular when egui's `monochrome_emoji_fonts` feature is on (the
LightCraft workspace enables both `default_fonts` and `monochrome_emoji_fonts` on egui 0.37). The
LightCraft binaries embed these faces unmodified, registered through egui's default font definitions.
Source for all of them (the same pin as the icon fonts below):
https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts
Hack Regular (Hack-Regular.ttf) is Copyright (c) 2018 Source Foundry Authors and
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. It is licensed under the MIT License, and
the Bitstream Vera parts under the Bitstream Vera License with Reserved Font Names "Bitstream" and
"Vera": the font as a whole is MIT AND Bitstream Vera License. The work in the DejaVu project it
derives from was committed to the public domain.
The following text is reproduced verbatim from Hack-Regular.txt:
The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License
The work in the DejaVu project was committed to the public domain.
Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera"
MIT License
Copyright (c) 2018 Source Foundry Authors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
BITSTREAM VERA LICENSE
Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions:
The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces.
The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera".
This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names.
The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself.
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org.
Ubuntu Light (Ubuntu-Light.ttf) is Copyright 2011 Canonical Ltd., was designed by Dalton Maag Ltd,
and is licensed under the Ubuntu Font Licence 1.0 (not the SIL Open Font License).
The following text is reproduced verbatim from UFL.txt; that file carries no copyright line, so the
copyright notice above is taken from the font's own name table:
-------------------------------
UBUNTU FONT LICENCE Version 1.0
-------------------------------
PREAMBLE
This licence allows the licensed fonts to be used, studied, modified and
redistributed freely. The fonts, including any derivative works, can be
bundled, embedded, and redistributed provided the terms of this licence
are met. The fonts and derivatives, however, cannot be released under
any other licence. The requirement for fonts to remain under this
licence does not require any document created using the fonts or their
derivatives to be published under this licence, as long as the primary
purpose of the document is not to be a vehicle for the distribution of
the fonts.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this licence and clearly marked as such. This may
include source files, build scripts and documentation.
"Original Version" refers to the collection of Font Software components
as received under this licence.
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to
a new environment.
"Copyright Holder(s)" refers to all individuals and companies who have a
copyright ownership of the Font Software.
"Substantially Changed" refers to Modified Versions which can be easily
identified as dissimilar to the Font Software by users of the Font
Software comparing the Original Version with the Modified Version.
To "Propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification and with or without charging
a redistribution fee), making available to the public, and in some
countries other activities as well.
PERMISSION & CONDITIONS
This licence does not grant any rights under trademark law and all such
rights are reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of the Font Software, to propagate the Font Software, subject to
the below conditions:
1) Each copy of the Font Software must contain the above copyright
notice and this licence. These can be included either as stand-alone
text files, human-readable headers or in the appropriate machine-
readable metadata fields within text or binary files as long as those
fields can be easily viewed by the user.
2) The font name complies with the following:
(a) The Original Version must retain its name, unmodified.
(b) Modified Versions which are Substantially Changed must be renamed to
avoid use of the name of the Original Version or similar names entirely.
(c) Modified Versions which are not Substantially Changed must be
renamed to both (i) retain the name of the Original Version and (ii) add
additional naming elements to distinguish the Modified Version from the
Original Version. The name of such Modified Versions must be the name of
the Original Version, with "derivative X" where X represents the name of
the new work, appended to that name.
3) The name(s) of the Copyright Holder(s) and any contributor to the
Font Software shall not be used to promote, endorse or advertise any
Modified Version, except (i) as required by this licence, (ii) to
acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with
their explicit written permission.
4) The Font Software, modified or unmodified, in part or in whole, must
be distributed entirely under this licence, and must not be distributed
under any other licence. The requirement for fonts to remain under this
licence does not affect any document created using the Font Software,
except any version of the Font Software extracted from a document
created using the Font Software may only be distributed under this
licence.
TERMINATION
This licence becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
DEALINGS IN THE FONT SOFTWARE.
Noto Emoji Regular (NotoEmoji-Regular.ttf) is Copyright 2013 Google Inc. All Rights Reserved. It was
designed by the Monotype Design Team and is licensed under the SIL Open Font License 1.1.
The following text is reproduced verbatim from OFL.txt; that file carries no copyright line, so the
copyright notice above is taken from the font's own name table:
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to
provide a free and open framework in which fonts may be shared and
improved in partnership with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software
components as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to,
deleting, or substituting -- in part or in whole -- any of the
components of the Original Version, by changing formats or by porting
the Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed,
modify, redistribute, and sell modified and unmodified copies of the
Font Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components, in
Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created using
the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
The UI's egui-icons.ttf subset and emoji-icon-font.ttf fallback are provided by epaint_default_fonts
and registered through egui's default font definitions. They derive from emoji-icon-font by
John Slegers, under the MIT License. The subset and full face share the following upstream notice.
Source: https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts
Original: https://github.com/jslegers/emoji-icon-font
The following text is reproduced verbatim from emoji-icon-font-mit-license.txt:
MIT License
Copyright (c) 2014 John Slegers
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+15 -3
View File
@@ -348,7 +348,7 @@ LightCraft is young and moving fast: **alpha**. **Where we honestly stand** (det
casual use.** It's great for JPEG/DNG and most Sony / Panasonic /
Fujifilm / Nikon / older-Canon raws on one machine; see [docs/raw-parity.md](docs/raw-parity.md) for your camera.
- **The biggest gaps:**
- **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 raws have guarded estimates from their camera JPEGs, with built-in ILCA-99M2, ILCE-7CR, ILCE-7M4, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration is missing, and other raws or rejected fits retain a neutral matrix;
- **camera colour calibration:** Sony, Nikon, Panasonic, Fujifilm and Canon CR3 raws have guarded estimates from their camera JPEGs, with built-in ILCA-99M2, ILCE-7CR, ILCE-7M4, ILCE-7RM5, X-H2S, X-T4, Nikon Z 6II, Z 8 and D5300 profiles; measured calibration is missing, and other raws or rejected fits retain a neutral matrix;
- **compressed Olympus raws and unsupported CR3 variants:** these use embedded JPEG previews when present. Fujifilm lossless/lossy compressed RAF now decodes sensor data; [verification and existing-library reload instructions](docs/raf-compression.md);
- **AI quality and model setup:** Subject and Sky selection are classical heuristics; Object/Describe use an
optional SAM 3 model. AI Denoise supports Bayer RAW with separately installed weights, while X-Trans and
@@ -405,8 +405,17 @@ cargo run --release -p lightcraft -- --control 7980 # with the automation ch
cargo xtask web --serve # the same app in the browser: http://127.0.0.1:8080/
cargo run --release -p lightcraft-cli -- render photo.jpg -o out.jpg --set light.exposure=0.5
cargo xtask ci # fmt, clippy, HEIF, tests, parity, layers, assets, WASM
cargo xtask ci --quick # only what your branch's changes can break (minutes)
```
`cargo xtask ci --quick` compares with the merge base of `origin/main` (`--base REF` for another)
and runs fmt, clippy, the tests of the changed packages, layers and assets, plus HEIF, parity and
the wasm check when the changes touch them; a change to `Cargo.toml`, `Cargo.lock` or the lint
config tests everything. GitHub runs the full `cargo xtask ci` on every pull request
(`.github/workflows/ci.yml`). Only one `ci` runs at a time per machine: a second one, from another
worktree say, waits for the first and names it, since several at once take longer in total than in
turn. `LIGHTCRAFT_CI_SLOTS=2` allows two; `LIGHTCRAFT_CI_LOCK=off` skips the lock.
CI defaults to line-table debug information and one build job per 1.5 GB of RAM
available when it starts (at most one per CPU; 4 if memory can't be read), so an
8 GB machine with 6 GB free builds with 4, and a busy machine with little free
@@ -554,9 +563,12 @@ Questions, ideas or a bug you'd like to talk through first? Bring them to [Disco
| arm64 (Snapdragon and other ARM PCs) | `lightcraft-<ver>-windows-arm64.msi` | `lightcraft-<ver>-windows-arm64-portable.zip` |
| x86 (32-bit) | `lightcraft-<ver>-windows-x86.msi` | `lightcraft-<ver>-windows-x86-portable.zip` |
Installers and executables are code-signed. The installer asks where to install (`C:\Program Files\LightCraft` by
default; upgrades stay in the folder you chose) and ends on a page confirming LightCraft was installed, with an
Installers and executables are code-signed. The installer asks who to install for and where (for your account only, in
`%LOCALAPPDATA%\Programs\ArtCraft\LightCraft`, by default; "Everyone on this computer" uses
`C:\Program Files\ArtCraft\LightCraft` (`Program Files (x86)` for the 32-bit build); upgrades stay in the folder you chose) and ends on a page confirming LightCraft was installed, with an
option to start it. For unattended installs: `msiexec /i lightcraft-<ver>-windows-x64.msi /qn INSTALLFOLDER="D:\Apps\LightCraft\"`.
A silent install is per-user by default. `INSTALLFOLDER` chooses the folder, not who it is installed for;
add `ALLUSERS=1`, from an elevated terminal or deployment tool, for an all-users install.
### macOS
+9 -7
View File
@@ -298,18 +298,18 @@ lightcraft --control 7980 ~/Pictures/trip
## Feature status
LightCraft 很年轻,而且进展很快。**我们如实所处的位置**(细节见[路线图](ROADMAP.md#where-we-stand)):
LightCraft 很年轻,而且进展很快。**我们如实所处的位置**(细节见[路线图](ROADMAP.md)):
- **按功能数量算,我们达到了约 79%**(核心功能 98%),逐行记录在
[docs/parity.md](docs/parity.md)。
[docs/parity-checklist.md](docs/parity-checklist.md)。
- **作为日常使用的工具,我们更接近 60–70%。** 在单台机器上处理 JPEG/DNG 以及大多数尼康/索尼/
较老佳能的 raw 都很出色。
- **最大的缺口:**
- **相机色彩校准:** 索尼、尼康、松下、富士和佳能 CR3 的 raw 会从各自的相机 JPEG 得到受保护的估计值,内置 ILCA-99M2、ILCE-7CR、ILCE-7M4、X-H2S、X-T4、尼康 Z 6II、Z 8 和 D5300 配置文件;实测校准仍然缺失,其他 raw 或被拒绝的拟合会保留中性矩阵;
- **相机色彩校准:** 索尼、尼康、松下、富士和佳能 CR3 的 raw 会从各自的相机 JPEG 得到受保护的估计值,内置 ILCA-99M2、ILCE-7CR、ILCE-7M4、ILCE-7RM5、X-H2S、X-T4、尼康 Z 6II、Z 8 和 D5300 配置文件;实测校准仍然缺失,其他 raw 或被拒绝的拟合会保留中性矩阵;
- **压缩的奥林巴斯 raw 和不受支持的 CR3 变体:** 这些在有内嵌 JPEG 预览时使用预览。富士无损/有损压缩 RAF 现在能解码传感器数据;[验证与已有图库重新加载说明](docs/raf-compression.md);
- **AI 蒙版与降噪:** 主体和天空选择目前是经典启发式算法;
- **屏幕上的 HDR 显示、视频,以及经典版式中的打印/画册/地图模块。**
- **接下来做什么:** 见[我们要去往哪里](ROADMAP.md#where-were-going)。
- **接下来做什么:** 见[我们要去往哪里](ROADMAP.md#upcoming)。
| 领域 | 状态 |
|---|---|
@@ -333,7 +333,7 @@ LightCraft 很年轻,而且进展很快。**我们如实所处的位置**(
| 镜头校正(畸变、暗角、自动 + 手动色差、去边、DNG 文件内嵌的镜头校正以及松下/徕卡 RW2/RWL 畸变数据)、几何(变换、限制裁剪)、垂直校正(自动/水平/垂直/完整/引导式) | ✅ · 相机镜头配置文件(我们自己的)⬜ |
| 照片合并:HDR(自动对齐、去重影)、全景(球面/圆柱/透视、边界变形、自动裁剪)、HDR 全景 → DNG | ✅ |
| GPU 管线(wgpu 计算,与 CPU 一致到 1/255 以内)、设备限制/出错时回退到 CPU | ✅ · 浏览器中的 WebGPU 🚧 |
| AI:分割蒙版、AI 降噪、超分辨率、人脸;视频 | ⬜(见[路线图](ROADMAP.md#where-were-going)) |
| AI:分割蒙版、AI 降噪、超分辨率、人脸;视频 | ⬜(见[路线图](ROADMAP.md#upcoming)) |
| 网页版(通过 WASM 在浏览器中使用同一界面):图库持久化在 OPFS/IndexedDB、Web Worker 渲染、导出下载 | ✅ · WebGPU、Safari/Firefox 测试 🚧 |
<sub>✅ 现已可用 · 🚧 进行中 · ⬜ 尚未开始</sub>
@@ -484,9 +484,11 @@ egui 前端是一个可替换的 crate;它下面没有任何东西知道 UI
| arm64(骁龙及其他 ARM PC) | `lightcraft-<ver>-windows-arm64.msi` | `lightcraft-<ver>-windows-arm64-portable.zip` |
| x86(32 位) | `lightcraft-<ver>-windows-x86.msi` | `lightcraft-<ver>-windows-x86-portable.zip` |
安装程序和可执行文件都有代码签名。安装程序会询问安装位置(默认
`C:\Program Files\LightCraft`;升级会留在你选择的文件夹),结束时有一页确认 LightCraft 已安装,
安装程序和可执行文件都有代码签名。安装程序会询问为谁安装以及安装位置(默认仅为当前账户,安装到
`%LOCALAPPDATA%\Programs\ArtCraft\LightCraft`;选择“这台计算机上的所有人”则安装到
`C:\Program Files\ArtCraft\LightCraft`(32 位版本为 `Program Files (x86)`);升级会留在你选择的文件夹),结束时有一页确认 LightCraft 已安装,
并可选择启动它。无人值守安装:`msiexec /i lightcraft-<ver>-windows-x64.msi /qn INSTALLFOLDER="D:\Apps\LightCraft\"`。
静默安装默认仅为当前用户安装。`INSTALLFOLDER` 只决定安装文件夹,不决定为谁安装;若要为所有用户安装,请在提升权限的终端或部署工具中加上 `ALLUSERS=1`。
### macOS
+5 -3
View File
@@ -320,7 +320,7 @@ LightCraft 還很年輕,而且進展飛快:**Alpha 階段**。**老實說,
在單機上處理 JPEG/DNG,以及大多數 Sony/Panasonic/
Fujifilm/Nikon/較舊款 Canon 的 raw 都很出色;各機型詳情見 [docs/raw-parity.md](docs/raw-parity.md)。
- **最大的缺口:**
- **相機色彩校正:** Sony、Nikon、Panasonic、Fujifilm 和 Canon CR3 的 raw 會從各自的相機 JPEG 得到受保護的估計值,內建 ILCA-99M2、ILCE-7CR、ILCE-7M4、X-H2S、X-T4、Nikon Z 6II、Z 8 和 D5300 描述檔;仍缺少實測校正,其他 raw 或被拒絕的擬合會保留中性矩陣;
- **相機色彩校正:** Sony、Nikon、Panasonic、Fujifilm 和 Canon CR3 的 raw 會從各自的相機 JPEG 得到受保護的估計值,內建 ILCA-99M2、ILCE-7CR、ILCE-7M4、ILCE-7RM5、X-H2S、X-T4、Nikon Z 6II、Z 8 和 D5300 描述檔;仍缺少實測校正,其他 raw 或被拒絕的擬合會保留中性矩陣;
- **壓縮的 Olympus raw 與不受支援的 CR3 變體:** 這些在有內嵌 JPEG 預覽時會改用預覽畫面。Fujifilm 無損/有損壓縮 RAF 現在能解碼感光元件資料;[驗證與現有照片庫重新載入說明](docs/raf-compression.md);
- **AI 遮色片與降噪:** 主體與天空選取目前是傳統啟發式演算法;
- **網路照片庫:** 預覽只讀取 raw 的標頭 — 或者,對於 CR3 或預覽標籤位於其後的 TIFF raw,只讀取稀疏規劃器指定的範圍 — 以及其內嵌的 JPEG(56.5 MB → 5.9 MB,10 秒 → 1 秒,測得於測試用的網路共用資料夾),但*顯影後*的畫面仍需要透過網路傳輸感光元件資料;詳見 [docs/raw-preview-reads.md](docs/raw-preview-reads.md);
@@ -514,9 +514,11 @@ egui 前端是一個可替換的 crate;它之下沒有任何東西知道 UI
| arm64(Snapdragon 及其他 ARM PC) | `lightcraft-<ver>-windows-arm64.msi` | `lightcraft-<ver>-windows-arm64-portable.zip` |
| x86(32 位元) | `lightcraft-<ver>-windows-x86.msi` | `lightcraft-<ver>-windows-x86-portable.zip` |
安裝程式與執行檔都有程式碼簽章。安裝程式會詢問安裝位置(預設為
`C:\Program Files\LightCraft`;升級時會留在你選擇的資料夾),結束時會有一頁確認 LightCraft 已安裝,
安裝程式與執行檔都有程式碼簽章。安裝程式會詢問為誰安裝以及安裝位置(預設僅為目前帳戶,安裝到
`%LOCALAPPDATA%\Programs\ArtCraft\LightCraft`;選擇「這台電腦上的所有人」則安裝到
`C:\Program Files\ArtCraft\LightCraft`(32 位元版本為 `Program Files (x86)`);升級時會留在你選擇的資料夾),結束時會有一頁確認 LightCraft 已安裝,
並可選擇立即啟動。無訊息安裝:`msiexec /i lightcraft-<ver>-windows-x64.msi /qn INSTALLFOLDER="D:\Apps\LightCraft\"`。
無訊息安裝預設僅為目前使用者安裝。`INSTALLFOLDER` 只決定安裝資料夾,不決定為誰安裝;若要為所有使用者安裝,請在提升權限的終端機或部署工具中加上 `ALLUSERS=1`。
### macOS
+7 -1
View File
@@ -2,7 +2,7 @@
**Stage: alpha** · next: beta, ~14 points and ~340–600 h away
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (Print: Japanese photo and postcard paper sizes — L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺; Minolta MRW decoded, 6 bodies verified; RAW: 83% of Adobe's models decode, 38% verified after the camera-coverage sweep #1327; German catalog 91% → 97%: interface strings and What's New lines translated) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6
One-page summary of how close LightCraft is to Adobe Lightroom. Agents: read this, then pick work
from [docs/gaps.md](docs/gaps.md). The full assessment, method and evidence are in
@@ -114,6 +114,11 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
## Progress log
- 2026-10-22: Print page setup and PDF output gain the Japanese photo and postcard papers — L判
(89 × 127 mm), 2L判 (127 × 178), KG判 (102 × 152), はがき (100 × 148), 往復はがき (148 × 200),
六切 (203 × 254), 四切 (254 × 305) and 名刺 (55 × 91) — at their exact metric sizes. The Print dialog
and `print.set` take their customary names, and names are matched case-, space- and
punctuation-insensitively (`L判`, `l`, `L-size` are one paper).
- 2026-10-14: Camera-coverage sweep verifies 30 more models on 40 CC0 files, with file and sensor
hashes pinned (`docs/raw/coverage.py`: 515 → 545 verified). Eleven candidates excluded after rechecking
identity, provenance and camera-image agreement. Phone and drone DNG tone differences remain tracked in #1277.
@@ -186,6 +191,7 @@ Ranked toward beta; detail in [docs/roadmap.md](docs/roadmap.md), gaps in [docs/
| Date | Change | Summary |
|---|---|---|
| 2026-10-22 | minor | Print: Japanese photo and postcard paper sizes (L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺) in the page setup, Print dialog and PDF output; headline numbers unchanged |
| 2026-10-19 | minor | Indonesian interface (`id`): every plain and formats message, plus 69 command labels, locale, menu command and tests; What's New left in English; Localization ~55% → ~64% (mean of the 12 key languages), 8 of 12 present |
| 2026-10-12 | minor | Italian interface (`it`, #1192): 2,201 of 2,398 messages, locale, menu command and tests; headline numbers unchanged |
| 2026-10-13 | minor | Sony ILCA-99M2 camera colour profile in the log; numbers unchanged |
+1
View File
@@ -819,6 +819,7 @@ fn snapshot(args: &[String]) -> Result<(), String> {
let services = lightcraft_ui_egui::Services {
write_shared: Some(std::sync::Arc::new(lightcraft_engine::export::write_file)),
write: Some(Box::new(lightcraft_engine::export::write_file)),
write_new: Some(Box::new(lightcraft_engine::export::write_file_new)),
png: Some(Box::new(|img: &lightcraft_raster::Rgba8| {
lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(img), &lightcraft_codecs::EncodeMeta::default()).unwrap_or_default()
})),
+49 -37
View File
@@ -5,7 +5,7 @@ use std::process::{Command, Stdio};
use serde_json::{Value, json};
const BIN: &str = env!("CARGO_BIN_EXE_lightcraft-cli");
use super::binary;
#[test]
fn contact_sheet_exports_pdf_and_protects_originals() {
@@ -106,7 +106,7 @@ fn calibrate_reads_raf_inputs_and_reports_bad_files() {
let input = tmp("invalid.RAF");
std::fs::write(&input, b"FUJIFILMCCD-RAW").unwrap();
let out = tmp("raf-profiles");
let result = Command::new(BIN).args(["calibrate", "--out"]).arg(&out).arg(&input).output().unwrap();
let result = Command::new(binary()).args(["calibrate", "--out"]).arg(&out).arg(&input).output().unwrap();
assert!(!result.status.success());
let stderr = String::from_utf8_lossy(&result.stderr);
assert!(stderr.contains("1 of 1 raw files"), "RAF was silently ignored: {stderr}");
@@ -124,8 +124,13 @@ fn mean(path: &std::path::Path) -> f64 {
fn mcp_over_stdio_sets_exposure_and_renders() {
let input = tmp("in.png");
gradient_png(&input);
let mut child =
Command::new(BIN).args(["mcp", input.to_str().unwrap()]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
let mut child = Command::new(binary())
.args(["mcp", input.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
let mut stdout = BufReader::new(child.stdout.take().unwrap());
let mut rpc = |id: u64, method: &str, params: Value| -> Value {
@@ -163,9 +168,9 @@ fn render_subcommand() {
gradient_png(&input);
let plain = tmp("r-plain.png");
let out = tmp("r-out.jpg");
let st = Command::new(BIN).args(["render", input.to_str().unwrap(), "-o", plain.to_str().unwrap()]).status().unwrap();
let st = Command::new(binary()).args(["render", input.to_str().unwrap(), "-o", plain.to_str().unwrap()]).status().unwrap();
assert!(st.success());
let st = Command::new(BIN)
let st = Command::new(binary())
.args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--set", "light.exposure=1", "--size", "60"])
.status()
.unwrap();
@@ -176,7 +181,7 @@ fn render_subcommand() {
assert_eq!((d.width, d.height), (120, 80));
assert!(mean(&out) > mean(&plain) + 10.0);
// Bad control id fails cleanly.
let o = Command::new(BIN).args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--set", "nope=1"]).output().unwrap();
let o = Command::new(binary()).args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--set", "nope=1"]).output().unwrap();
assert!(!o.status.success());
assert!(String::from_utf8_lossy(&o.stderr).contains("unknown control"));
}
@@ -204,10 +209,10 @@ fn render_settings_applies_an_lcpreset_and_refuses_unknown_files() {
);
assert!(ok, "{err}: {lines:?}");
let plain = tmp("lcpreset-plain.png");
let st = Command::new(BIN).args(["render", input.to_str().unwrap(), "-o", plain.to_str().unwrap()]).status().unwrap();
let st = Command::new(binary()).args(["render", input.to_str().unwrap(), "-o", plain.to_str().unwrap()]).status().unwrap();
assert!(st.success());
let bright = tmp("lcpreset-bright.png");
let o = Command::new(BIN)
let o = Command::new(binary())
.args(["render", input.to_str().unwrap(), "-o", bright.to_str().unwrap(), "--settings", preset.to_str().unwrap()])
.output()
.unwrap();
@@ -217,7 +222,7 @@ fn render_settings_applies_an_lcpreset_and_refuses_unknown_files() {
let other = tmp("other.lcpreset");
std::fs::write(&other, r#"{"format": "other", "version": 1, "presets": []}"#).unwrap();
let out = tmp("lcpreset-other.png");
let o = Command::new(BIN)
let o = Command::new(binary())
.args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--settings", other.to_str().unwrap()])
.output()
.unwrap();
@@ -236,8 +241,10 @@ fn render_refuses_to_overwrite_its_input() {
std::fs::create_dir_all(dir.join("sub")).unwrap();
let other_spelling = dir.join("sub/../self-in.png");
for out in [&input, &other_spelling] {
let o =
Command::new(BIN).args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--set", "light.exposure=1"]).output().unwrap();
let o = Command::new(binary())
.args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--set", "light.exposure=1"])
.output()
.unwrap();
assert!(!o.status.success());
assert!(String::from_utf8_lossy(&o.stderr).contains("never writes over an original"), "{}", String::from_utf8_lossy(&o.stderr));
}
@@ -249,7 +256,7 @@ fn render_export_options() {
let input = tmp("o-in.png");
gradient_png(&input);
let out = tmp("o-out.tif");
let st = Command::new(BIN)
let st = Command::new(binary())
.args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap()])
.args(["--opt", "shortEdge=40", "--opt", "colorSpace=displayP3", "--opt", "bitDepth=16"])
.status()
@@ -260,7 +267,7 @@ fn render_export_options() {
assert_eq!(d.space.named, Some(lightcraft_codecs::NamedSpace::DisplayP3));
// original + sidecar named after the output
let out = tmp("o-copy.png");
let st = Command::new(BIN)
let st = Command::new(binary())
.args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap(), "--set", "light.exposure=1", "--opt", "format=original"])
.status()
.unwrap();
@@ -269,26 +276,26 @@ fn render_export_options() {
let xmp = std::fs::read_to_string(out.with_extension("xmp")).unwrap();
assert!(xmp.contains("exposure"), "{xmp}");
// unknown extension fails with a hint
let o = Command::new(BIN).args(["render", input.to_str().unwrap(), "-o", tmp("x.bmp").to_str().unwrap()]).output().unwrap();
let o = Command::new(binary()).args(["render", input.to_str().unwrap(), "-o", tmp("x.bmp").to_str().unwrap()]).output().unwrap();
assert!(!o.status.success() && String::from_utf8_lossy(&o.stderr).contains("unknown extension"));
}
#[test]
fn commands_subcommand_lists_registry() {
let o = Command::new(BIN).args(["commands", "--json"]).output().unwrap();
let o = Command::new(binary()).args(["commands", "--json"]).output().unwrap();
assert!(o.status.success());
let v: Value = serde_json::from_slice(&o.stdout).unwrap();
let ids: Vec<&str> = v.as_array().unwrap().iter().filter_map(|c| c["id"].as_str()).collect();
for id in ["develop.set", "photo.rate", "library.import", "edit.undo", "app.export"] {
assert!(ids.contains(&id), "{id}");
}
let o = Command::new(BIN).arg("controls").output().unwrap();
let o = Command::new(binary()).arg("controls").output().unwrap();
assert!(String::from_utf8_lossy(&o.stdout).contains("light.exposure"));
}
#[test]
fn commands_subcommand_lists_commands_sorted_by_id() {
let o = Command::new(BIN).args(["commands", "--json"]).output().unwrap();
let o = Command::new(binary()).args(["commands", "--json"]).output().unwrap();
assert!(o.status.success());
let v: Value = serde_json::from_slice(&o.stdout).unwrap();
let cmds = v.as_array().unwrap();
@@ -302,7 +309,7 @@ fn commands_subcommand_lists_commands_sorted_by_id() {
let unsorted = ids.windows(2).find(|w| w[0] >= w[1]);
assert!(unsorted.is_none(), "--json should list commands sorted by id, but {unsorted:?} are out of order");
let o = Command::new(BIN).arg("commands").output().unwrap();
let o = Command::new(binary()).arg("commands").output().unwrap();
assert!(o.status.success());
let text = String::from_utf8_lossy(&o.stdout);
let lines: Vec<&str> = text.lines().collect();
@@ -338,7 +345,7 @@ fn snapshot_subcommand_renders_the_ui_headlessly() {
),
)
.unwrap();
let o = Command::new(BIN)
let o = Command::new(binary())
.args(["snapshot", "--demo", "--script", script.to_str().unwrap(), "-o", a.to_str().unwrap(), "--size", "640x400"])
.output()
.unwrap();
@@ -353,7 +360,7 @@ fn snapshot_subcommand_renders_the_ui_headlessly() {
assert_eq!(mean(p) < mean(&a) - 2.0, dimmed, "{}", p.display());
}
// no script: one settled screenshot, at 2× scale
let o = Command::new(BIN).args(["snapshot", "-o", a.to_str().unwrap(), "--size", "320x240", "--scale", "2"]).output().unwrap();
let o = Command::new(binary()).args(["snapshot", "-o", a.to_str().unwrap(), "--size", "320x240", "--scale", "2"]).output().unwrap();
assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
let d = lightcraft_codecs::decode(&std::fs::read(&a).unwrap(), Default::default()).unwrap();
assert_eq!((d.width, d.height), (640, 480));
@@ -375,7 +382,7 @@ fn snapshot_script_failure_exits_non_zero() {
)
.unwrap();
let _ = std::fs::remove_file(&out);
let o = Command::new(BIN)
let o = Command::new(binary())
.args(["snapshot", "--demo", "--script", script.to_str().unwrap(), "-o", out.to_str().unwrap(), "--size", "320x200"])
.output()
.unwrap();
@@ -400,7 +407,7 @@ fn snapshot_script_with_non_object_params_is_an_error() {
let script = tmp("snap-bad-params.jsonl");
let out = tmp("snap-bad-params.png");
std::fs::write(&script, format!("{}\n", json!({"method": "ui.screenshot", "params": [1]}))).unwrap();
let o = Command::new(BIN)
let o = Command::new(binary())
.args(["snapshot", "--demo", "--script", script.to_str().unwrap(), "-o", out.to_str().unwrap(), "--size", "320x200"])
.output()
.unwrap();
@@ -417,7 +424,7 @@ fn snapshot_ui_zoom_keeps_requested_pixel_dimensions() {
.unwrap();
for (size, scale, expected) in [("400x240", "1", (400, 240)), ("345x200", "0.9", (311, 180))] {
let out = tmp(&format!("snap-ui-zoom-{scale}.png"));
let o = Command::new(BIN)
let o = Command::new(binary())
.args(["snapshot", "--script", script.to_str().unwrap(), "-o", out.to_str().unwrap(), "--size", size, "--scale", scale])
.output()
.unwrap();
@@ -440,7 +447,7 @@ fn snapshot_defaults_to_cpu_without_gpu_environment_overrides() {
)
.unwrap();
let image = tmp("default-cpu.png");
let output = Command::new(BIN)
let output = Command::new(binary())
.env_remove("LIGHTCRAFT_GPU")
.env_remove("LIGHTCRAFT_GPU_BACKEND")
.env_remove("WGPU_BACKEND")
@@ -476,7 +483,7 @@ fn snapshot_starts_without_a_gpu() {
.unwrap();
for (var, value, reason) in [("LIGHTCRAFT_GPU", "0", "LIGHTCRAFT_GPU=0"), ("LIGHTCRAFT_GPU_BACKEND", "off", "LIGHTCRAFT_GPU_BACKEND=off")] {
let out = tmp(&format!("nogpu-{var}.png"));
let o = Command::new(BIN)
let o = Command::new(binary())
.env_remove("LIGHTCRAFT_GPU")
.env_remove("LIGHTCRAFT_GPU_BACKEND")
.env(var, value)
@@ -496,7 +503,7 @@ fn snapshot_starts_without_a_gpu() {
}
fn run_cli(args: &[&str], stdin: Option<&str>) -> (bool, Vec<Value>, String) {
let mut child = Command::new(BIN).arg("run").args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
let mut child = Command::new(binary()).arg("run").args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
if let Some(text) = stdin {
child.stdin.take().unwrap().write_all(text.as_bytes()).unwrap();
}
@@ -561,7 +568,7 @@ fn devices_are_listed_and_imported_from() {
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("CARD/DCIM/100TEST")).unwrap();
gradient_png(&base.join("CARD/DCIM/100TEST/IMG_0001.png"));
let o = Command::new(BIN).env("LIGHTCRAFT_DEVICE_ROOTS", &base).args(["run", "--demo", "library.devices"]).output().unwrap();
let o = Command::new(binary()).env("LIGHTCRAFT_DEVICE_ROOTS", &base).args(["run", "--demo", "library.devices"]).output().unwrap();
assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
let line: Value = serde_json::from_slice(o.stdout.split(|b| *b == b'\n').next().unwrap()).unwrap();
let dev = &line["result"][0];
@@ -570,7 +577,7 @@ fn devices_are_listed_and_imported_from() {
let dcim = dev["path"].as_str().unwrap().to_string();
// JSON-escaped: a Windows path has backslashes
let paths = serde_json::to_string(&[&dcim]).unwrap();
let o = Command::new(BIN).args(["run", "library.importPreview", &format!("paths={paths}")]).output().unwrap();
let o = Command::new(binary()).args(["run", "library.importPreview", &format!("paths={paths}")]).output().unwrap();
let line: Value = serde_json::from_slice(o.stdout.split(|b| *b == b'\n').next().unwrap()).unwrap();
assert_eq!(line["result"]["candidates"].as_array().map(Vec::len), Some(1), "{line}");
}
@@ -583,7 +590,7 @@ fn a_library_open_in_another_process_is_refused() {
let _ = std::fs::remove_dir_all(&lib);
let lib_s = lib.to_str().unwrap();
let mut holder =
Command::new(BIN).args(["mcp", "--library", lib_s]).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped()).spawn().unwrap();
Command::new(binary()).args(["mcp", "--library", lib_s]).stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped()).spawn().unwrap();
let mut err = BufReader::new(holder.stderr.take().unwrap());
let mut line = String::new();
while !line.contains("opened library") {
@@ -643,7 +650,7 @@ fn warnings_are_logged_on_stderr() {
gradient_png(&input);
let out = tmp("log-out.jpg");
let run = |level: &str| {
let o = Command::new(BIN)
let o = Command::new(binary())
.args(["render", input.to_str().unwrap(), "-o", out.to_str().unwrap()])
.env("LIGHTCRAFT_GPU_BACKEND", "bogus")
.env("RUST_LOG", level)
@@ -667,7 +674,7 @@ fn snapshot_rejects_invalid_dimensions_before_creating_an_image() {
[("NaNx100", "1"), ("100x100", "inf"), ("9000x9000", "1"), ("9000x100", "2"), ("100x100", "0.001")].into_iter().enumerate()
{
let image = tmp(&format!("invalid-viewport-{index}.png"));
let output = Command::new(BIN).args(["snapshot", "--size", size, "--scale", scale, "-o"]).arg(&image).output().unwrap();
let output = Command::new(binary()).args(["snapshot", "--size", size, "--scale", scale, "-o"]).arg(&image).output().unwrap();
assert!(!output.status.success());
assert!(String::from_utf8_lossy(&output.stderr).contains("snapshot: bad --size/--scale"), "{}", String::from_utf8_lossy(&output.stderr));
assert!(!image.exists());
@@ -677,8 +684,12 @@ fn snapshot_rejects_invalid_dimensions_before_creating_an_image() {
#[test]
fn snapshot_preserves_fractional_scale_rounding() {
let image = tmp("fractional-scale-rounding.png");
let output =
Command::new(BIN).env("LIGHTCRAFT_GPU", "0").args(["snapshot", "--size", "345x200", "--scale", "0.9", "-o"]).arg(&image).output().unwrap();
let output = Command::new(binary())
.env("LIGHTCRAFT_GPU", "0")
.args(["snapshot", "--size", "345x200", "--scale", "0.9", "-o"])
.arg(&image)
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
let decoded = lightcraft_codecs::decode(&std::fs::read(image).unwrap(), Default::default()).unwrap();
assert_eq!((decoded.width, decoded.height), (311, 180));
@@ -709,7 +720,7 @@ fn snapshot_leaves_desktop_gpu_preferences_untouched() {
.unwrap();
for gpu_environment in [None, Some("1")] {
let image = dir.join(format!("{}.png", gpu_environment.unwrap_or("default")));
let mut cmd = Command::new(BIN);
let mut cmd = Command::new(binary());
cmd.env("XDG_CONFIG_HOME", &config).env_remove("LIGHTCRAFT_GPU").env_remove("LIGHTCRAFT_GPU_BACKEND").env_remove("WGPU_BACKEND");
if let Some(value) = gpu_environment {
cmd.env("LIGHTCRAFT_GPU", value);
@@ -770,13 +781,14 @@ fn denoise_serve_runs_tiles_for_another_computer() {
let sha = lightcraft_denoise::hash::sha256_file(&onnx).unwrap();
// without its token the server doesn't start
let o = Command::new(BIN).args(["denoise-serve", "--models", models.to_str().unwrap(), "--token-env", "LC_TEST_NO_SUCH_VAR"]).output().unwrap();
let o =
Command::new(binary()).args(["denoise-serve", "--models", models.to_str().unwrap(), "--token-env", "LC_TEST_NO_SUCH_VAR"]).output().unwrap();
assert!(!o.status.success() && String::from_utf8_lossy(&o.stderr).contains("LC_TEST_NO_SUCH_VAR"));
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let addr = format!("127.0.0.1:{port}");
let token = "cli-test-token-0123456789";
let mut child = Command::new(BIN)
let mut child = Command::new(binary())
.args(["denoise-serve", "--models", models.to_str().unwrap(), "--listen", &addr, "--run-on", "cpu"])
.env("LIGHTCRAFT_DENOISE_TOKEN", token)
.stderr(Stdio::piped())
+5
View File
@@ -2,3 +2,8 @@
mod cli;
mod mcp_shutdown;
/// Nextest archives relocate the executable; plain Cargo uses its compile-time path.
fn binary() -> std::ffi::OsString {
std::env::var_os("NEXTEST_BIN_EXE_lightcraft_cli").unwrap_or_else(|| env!("CARGO_BIN_EXE_lightcraft-cli").into())
}
+1 -7
View File
@@ -6,13 +6,7 @@ use std::time::{Duration, Instant};
#[test]
fn broken_stdout_exits_with_stdin_still_open() {
let mut child = Command::new(env!("CARGO_BIN_EXE_lightcraft-cli"))
.arg("mcp")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut child = Command::new(super::binary()).arg("mcp").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
let mut input = child.stdin.take().unwrap();
drop(child.stdout.take());
input.write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\"}\n{\"jsonrpc\":").unwrap();
+3
View File
@@ -77,3 +77,6 @@ web-sys = { workspace = true, features = [
# it (HEVC patents); build with `--features heif` to include it. On wasm32 panics abort, so
# heic-rs's `catch_unwind` guard does not apply there.
heif = ["lightcraft-codecs/heif"]
[dev-dependencies]
egui = { workspace = true }
+48
View File
@@ -0,0 +1,48 @@
//! The page's automation entry point, `lightcraft.command(id, params)` (see `web.rs`): what the
//! params text means. Plain Rust, so it is tested natively.
use serde_json::Value;
/// The command parameters in `text`: a JSON object, or `{}` when the text is empty or blank (or
/// `null`). Anything else is an error, never `{}`: a command run without its params acts on the
/// selection or with defaults, so a typo such as `{ids: [3]}` must not delete or reset the
/// selected photos. The control channel and MCP refuse such params the same way.
pub fn params(text: &str) -> Result<Value, String> {
let text = text.trim();
if text.is_empty() {
return Ok(Value::Object(Default::default()));
}
match serde_json::from_str::<Value>(text) {
Ok(Value::Null) => Ok(Value::Object(Default::default())),
Ok(v @ Value::Object(_)) => Ok(v),
Ok(_) => Err("params must be a JSON object, e.g. {\"ids\": [3]}".into()),
Err(e) => Err(format!("params are not valid JSON ({e}); nothing was run")),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn blank_or_null_params_are_an_empty_object() {
for text in ["", " ", "\n", "null", " null "] {
assert_eq!(params(text), Ok(json!({})), "{text:?}");
}
}
#[test]
fn an_object_is_passed_through() {
assert_eq!(params(r#"{"ids": [3], "rating": 5}"#), Ok(json!({"ids": [3], "rating": 5})));
}
/// Before, any of these ran the command with `{}`: `photo.delete` then removed the selection.
#[test]
fn invalid_json_or_a_non_object_is_refused() {
for text in ["{ids: [3]}", "{\"ids\": [3]", "ids=3", "[3]", "3", "\"{}\"", "true"] {
assert!(params(text).is_err(), "{text:?} must not run the command");
}
assert!(params("{ids: [3]}").unwrap_err().contains("nothing was run"));
}
}
+6 -3
View File
@@ -39,7 +39,7 @@ pub struct Bench {
}
impl Bench {
/// `start_ms`: the page's time origin in the same clock as [`lightcraft_ui_egui::now_ms`].
/// `start_ms`: an origin on the same monotonic clock as [`lightcraft_ui_egui::monotonic_ms`].
pub fn new(start_ms: f64) -> Self {
Bench {
phase: Phase::Idle,
@@ -54,13 +54,16 @@ impl Bench {
}
}
/// The render key of the main preview texture, or `None` while that slot holds no texture.
/// A changed key means the benchmark's requested main-image render has arrived.
fn main_key(app: &LightcraftApp) -> Option<u64> {
app.renderer.textures.get(&Slot::Main).map(|t| t.key)
}
/// Call once per frame after `LightcraftApp::logic`. Returns the report when finished.
/// Call once per root UI pass after `LightcraftApp::ui` (a UI-phase step, never a hidden tick).
/// Returns the report when finished.
pub fn step(&mut self, app: &mut LightcraftApp) -> Option<Value> {
let now = lightcraft_ui_egui::now_ms();
let now = lightcraft_ui_egui::monotonic_ms();
self.frames += 1;
if self.first_frame_ms.is_none() && self.frames > 1 {
self.first_frame_ms = Some(now - self.start_ms);
+391
View File
@@ -0,0 +1,391 @@
//! When the browser host may consume queued drops. Kept out of the wasm-only `web` module so the
//! rule that keeps stored drops out of a library behind a foreground window is testable natively.
use lightcraft_ui_egui::LightcraftApp;
/// The browser host's two drop queues: file handles not yet read, and originals whose asynchronous
/// storage has finished and that wait to be imported. Taking either only through this trait keeps
/// the gate and the drain together.
pub trait QueuedDrops {
type Dropped;
type Pending;
/// Whether a prompt or the blocking library window owns input right now.
fn drops_wait(&self) -> bool;
/// Record that all currently unread handles are held by this foreground barrier.
fn defer_dropped(&mut self);
fn take_dropped(&mut self) -> Vec<Self::Dropped>;
/// Take fresh arrivals only, retaining handles protected by an earlier foreground barrier.
fn take_unprotected_dropped(&mut self) -> Vec<Self::Dropped>;
fn take_pending(&mut self) -> Vec<Self::Pending>;
}
/// A prompt or the blocking library window (over an already open library, or its own New Library
/// name prompt or asynchronous folder picker) owns input: leaves the dropped-file queue and the
/// originals still being stored for a later UI pass, instead of importing them behind the window.
/// With no library open and no dialog in front, the existing drop path is unchanged.
pub fn drops_wait(app: &LightcraftApp) -> bool {
lightcraft_ui_egui::panels::notices::blocks_input(app) || lightcraft_ui_egui::panels::library_problem::blocks_file_drops(app)
}
/// One UI pass's queues, drained by [`drain_ready`].
pub struct Drained<D, P> {
pub dropped: Vec<D>,
/// `None` when new file handles were refused behind a dialog: the originals already stored
/// stay queued for a later pass (as before), rather than importing behind that dialog.
pub pending: Option<Vec<P>>,
}
/// The actual queue drain `WebApp` runs each UI pass: while [`drops_wait`] holds, neither queue is
/// touched. With an ordinary dialog open, only fresh handles are taken for refusal; earlier
/// barrier-held handles remain queued. If fresh handles are refused, stored originals are left
/// queued as well. Otherwise the existing stored-original drain policy is unchanged.
pub fn drain_ready<Q: QueuedDrops>(queues: &mut Q, dialog_open: bool) -> Option<Drained<Q::Dropped, Q::Pending>> {
if queues.drops_wait() {
queues.defer_dropped();
return None;
}
let dropped = if dialog_open { queues.take_unprotected_dropped() } else { queues.take_dropped() };
let pending = if !dropped.is_empty() && dialog_open { None } else { Some(queues.take_pending()) };
Some(Drained { dropped, pending })
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::{QueuedDrops, drain_ready, drops_wait};
use lightcraft_engine::Session;
use lightcraft_ui_egui::panels::library_problem::LibraryProblem;
use lightcraft_ui_egui::state::Dialog;
use lightcraft_ui_egui::{LightcraftApp, Services};
struct Scratch(std::path::PathBuf);
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
type Asked = std::sync::Arc<std::sync::Mutex<Vec<std::sync::mpsc::Sender<Vec<String>>>>>;
fn app_with_library(tag: &str) -> Result<(Scratch, LightcraftApp), String> {
let dir = std::env::temp_dir().join(format!("lc-web-drop-gate-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).map_err(|error| error.to_string())?;
let scratch = Scratch(dir);
let mut session = Session::new().with_fs();
session.open_library(&scratch.0, false).map_err(|error| error.to_string())?;
Ok((scratch, LightcraftApp::new(session, Services::default())))
}
/// Stands in for `WebApp`: the same shared orchestration over two real queues, so a test sees
/// that a held window leaves both queues untouched, that the ready path drains both, and that
/// a refused new drop keeps the already stored originals queued.
struct FakeQueues {
app: LightcraftApp,
dropped: Vec<String>,
protected: usize,
pending: Vec<String>,
}
impl FakeQueues {
fn new(app: LightcraftApp) -> Self {
Self { app, dropped: vec!["dropped-photo".into()], protected: 0, pending: vec!["web/hash/photo.png".into()] }
}
}
impl QueuedDrops for FakeQueues {
type Dropped = String;
type Pending = String;
fn drops_wait(&self) -> bool {
drops_wait(&self.app)
}
fn defer_dropped(&mut self) {
self.protected = self.dropped.len();
}
fn take_dropped(&mut self) -> Vec<Self::Dropped> {
self.protected = 0;
std::mem::take(&mut self.dropped)
}
fn take_unprotected_dropped(&mut self) -> Vec<Self::Dropped> {
self.dropped.split_off(self.protected.min(self.dropped.len()))
}
fn take_pending(&mut self) -> Vec<Self::Pending> {
std::mem::take(&mut self.pending)
}
}
#[test]
fn stored_drops_wait_through_the_choosers_new_library_prompt_and_drain_after_it() {
let (_dir, mut app) = app_with_library("chooser").expect("create chooser test library");
let mut problem = LibraryProblem::choose_later(&app.ui.settings);
if let Some(c) = problem.chooser.as_mut() {
c.over = Some(app.session.library_generation());
}
app.library_problem = Some(problem);
let mut queues = FakeQueues::new(app);
// The list's own New Library name prompt hides the list but still owns the library.
queues.app.ui.dialog = Some(Dialog::TextPrompt {
title: "New Library".into(),
hint: "Library name".into(),
value: String::new(),
command: "app.newLibrary".into(),
params: serde_json::json!({}),
key: "name".into(),
});
assert!(drain_ready(&mut queues, false).is_none(), "the name prompt holds both queues");
assert_eq!((queues.dropped.len(), queues.pending.len()), (1, 1), "the queued drop survived the prompt");
// Cancelling the prompt brings the list back; it still owns the drop until it goes.
queues.app.ui.dialog = None;
assert!(drain_ready(&mut queues, false).is_none(), "the list is back and still holds the queue");
queues.app.library_problem = None;
let got = drain_ready(&mut queues, false).expect("the queues should be ready");
assert_eq!(got.dropped, vec!["dropped-photo".to_string()]);
assert_eq!(got.pending, Some(vec!["web/hash/photo.png".to_string()]));
assert!(queues.dropped.is_empty() && queues.pending.is_empty(), "both queues drained once the window was gone");
}
#[test]
fn a_refused_new_drop_behind_a_dialog_keeps_stored_originals_queued() {
let (_dir, app) = app_with_library("refused").expect("create refused-drop test library");
// not held by the gate: the dialog alone refuses the newly dropped handles
let mut queues = FakeQueues::new(app);
let got = drain_ready(&mut queues, true).expect("the queues should be ready");
assert_eq!(got.dropped, vec!["dropped-photo".to_string()]);
assert_eq!(got.pending, None, "the refused drop must not drain originals behind the dialog");
assert_eq!(queues.pending.len(), 1, "the earlier originals stayed queued");
// Nothing new was dropped: originals read from an earlier drop still finish, as before.
let got = drain_ready(&mut queues, true).expect("the queues should be ready");
assert!(got.dropped.is_empty());
assert_eq!(got.pending, Some(vec!["web/hash/photo.png".to_string()]));
assert!(queues.pending.is_empty());
}
#[test]
fn a_no_library_library_picker_holds_both_queues() {
let mut app = LightcraftApp::new(Session::new().with_fs(), Services::default());
let asked: Asked = Default::default();
app.services.picker = Some(Box::new(move |_| {
let (tx, rx) = std::sync::mpsc::channel();
asked.lock().unwrap().push(tx);
Ok(rx)
}));
// New Library's name prompt was confirmed; the asynchronous place picker is still open.
assert_eq!(app.run("app.newLibrary", serde_json::json!({"name": "Queued"})).unwrap(), serde_json::Value::Null);
assert!(app.session.library.is_none());
app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings));
let mut queues = FakeQueues::new(app);
assert!(drain_ready(&mut queues, false).is_none(), "a library picker that will open one holds both queues");
assert_eq!((queues.dropped.len(), queues.pending.len()), (1, 1), "nothing was drained while the picker is up");
}
#[test]
fn a_no_library_window_lets_the_existing_drop_path_consume_the_queues() {
let mut app = LightcraftApp::new(Session::with_demo(), Services::default());
app.library_problem = Some(LibraryProblem::new("/no/such/library", "missing"));
let mut queues = FakeQueues::new(app);
assert!(!drops_wait(&queues.app), "with no library open the existing drop path is unchanged");
let got = drain_ready(&mut queues, false).expect("the queues should be ready");
assert_eq!(got.dropped, vec!["dropped-photo".to_string()]);
assert_eq!(got.pending, Some(vec!["web/hash/photo.png".to_string()]));
assert!(queues.dropped.is_empty() && queues.pending.is_empty(), "the host consumed both queues");
queues.app.notices.push("The settings file could not be read and was reset.".into());
queues.dropped.push("late-drop".into());
queues.pending.push("web/hash/late.png".into());
assert!(drain_ready(&mut queues, false).is_none(), "a prompt still owns input");
assert_eq!((queues.dropped.len(), queues.pending.len()), (1, 1), "the prompt left both queues alone");
}
/// Uses the product's actual raw-handle queue and provenance APIs. Only the stored-original
/// vector is host-owned; there is no test copy of protected-prefix bookkeeping or policy.
struct RealAppQueues {
h: lightcraft_ui_egui::headless::Headless,
pending: Vec<String>,
pending_takes: usize,
}
impl QueuedDrops for RealAppQueues {
type Dropped = egui::DroppedFileHandle;
type Pending = String;
fn drops_wait(&self) -> bool {
drops_wait(&self.h.app)
}
fn defer_dropped(&mut self) {
self.h.app.defer_dropped_files();
}
fn take_dropped(&mut self) -> Vec<Self::Dropped> {
self.h.app.take_dropped_files()
}
fn take_unprotected_dropped(&mut self) -> Vec<Self::Dropped> {
self.h.app.take_unprotected_dropped_files()
}
fn take_pending(&mut self) -> Vec<Self::Pending> {
self.pending_takes += 1;
std::mem::take(&mut self.pending)
}
}
#[derive(Debug)]
struct UnreadDrop {
path: std::path::PathBuf,
reads: std::sync::Arc<std::sync::atomic::AtomicUsize>,
}
impl egui::DroppedFile for UnreadDrop {
fn path(&self) -> &std::path::Path {
&self.path
}
fn bytes(&self) -> Result<Vec<u8>, String> {
self.reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Err("the queue gate must not read dropped bytes".into())
}
}
fn unread(path: &str) -> (egui::DroppedFileHandle, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
let reads = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let handle = std::sync::Arc::new(UnreadDrop { path: path.into(), reads: reads.clone() });
(handle, reads)
}
fn queue_raw(queues: &mut RealAppQueues, handles: &[egui::DroppedFileHandle]) {
let mut raw = egui::RawInput { dropped_files: handles.to_vec(), ..Default::default() };
queues.h.app.raw_input_hook(&queues.h.view.ctx, &mut raw);
assert!(raw.dropped_files.is_empty(), "the product takes raw ownership once");
}
fn hold_library(queues: &mut RealAppQueues) -> Result<(), String> {
let mut problem = LibraryProblem::choose_later(&queues.h.app.ui.settings);
problem.chooser.as_mut().ok_or("the launch list has no chooser")?.over = Some(queues.h.app.session.library_generation());
queues.h.app.library_problem = Some(problem);
Ok(())
}
fn real_queues(tag: &str) -> Result<(Scratch, RealAppQueues), String> {
let (dir, app) = app_with_library(tag)?;
let h = lightcraft_ui_egui::headless::Headless::new(app, [1300.0, 900.0], 1.0);
Ok((dir, RealAppQueues { h, pending: vec!["web/hash/stored.png".into()], pending_takes: 0 }))
}
fn protect(queues: &mut RealAppQueues, handle: &egui::DroppedFileHandle) -> Result<(), String> {
hold_library(queues)?;
queue_raw(queues, std::slice::from_ref(handle));
// WebApp's gate runs before App.ui, including the cold first frame. The gate
// itself must establish provenance; a warmed native UI pass cannot stand in for it.
assert_eq!(queues.h.frames(), 0, "this starts before the first native UI pass");
assert!(drops_wait(&queues.h.app));
assert!(drain_ready(queues, false).is_none());
assert_eq!(queues.h.frames(), 0, "the host gate protects ownership without drawing");
assert_eq!(queues.pending_takes, 0);
assert!(queues.h.app.scan.is_none() && queues.h.app.import.is_none());
assert_eq!(queues.h.app.session.catalog.len(), 0);
Ok(())
}
#[test]
fn real_unread_barrier_drop_survives_a_dialog_while_stored_originals_finish() {
let (_dir, mut queues) = real_queues("real-held-dialog").expect("create real-queue library");
let (a, reads) = unread("A.png");
protect(&mut queues, &a).expect("hold the library barrier");
queues.h.app.library_problem = None;
queues.h.app.ui.dialog = Some(Dialog::WhatsNew);
// WebApp drains BEFORE App.ui. A native UI pass here would conceal the host-order bug.
let got = drain_ready(&mut queues, true).expect("only the ordinary dialog remains");
assert!(got.dropped.is_empty(), "the earlier unread A must not be drained for dialog refusal");
assert_eq!(
got.pending,
Some(vec!["web/hash/stored.png".into()]),
"with no fresh refusal, earlier stored originals retain their existing completion policy"
);
assert_eq!(queues.pending_takes, 1);
let again = drain_ready(&mut queues, true).unwrap();
assert!(again.dropped.is_empty(), "A stays protected across another host pass");
queues.h.app.ui.dialog = None;
let released = drain_ready(&mut queues, false).unwrap();
assert_eq!(released.dropped.len(), 1);
assert!(std::sync::Arc::ptr_eq(&released.dropped[0], &a), "the original A handle is released");
assert!(drain_ready(&mut queues, false).unwrap().dropped.is_empty(), "A transfers exactly once");
assert!(queues.h.app.take_dropped_files().is_empty());
assert_eq!(reads.load(std::sync::atomic::Ordering::SeqCst), 0);
}
#[test]
fn real_fresh_dialog_drop_is_refused_without_consuming_protected_or_stored_files() {
let (_dir, mut queues) = real_queues("real-mixed-dialog").expect("create real-queue library");
let (a, reads_a) = unread("A.png");
let (b, reads_b) = unread("B.png");
protect(&mut queues, &a).expect("hold the library barrier");
queues.h.app.library_problem = None;
queues.h.app.ui.dialog = Some(Dialog::WhatsNew);
queue_raw(&mut queues, std::slice::from_ref(&b));
let got = drain_ready(&mut queues, true).unwrap();
assert_eq!(got.dropped.len(), 1, "only fresh B is offered to the browser's existing refusal branch");
assert!(std::sync::Arc::ptr_eq(&got.dropped[0], &b));
assert_eq!(got.pending, None, "refusing B must not consume stored originals");
assert_eq!(queues.pending_takes, 0);
assert_eq!(queues.pending, vec!["web/hash/stored.png".to_string()]);
assert!(matches!(queues.h.app.ui.dialog, Some(Dialog::WhatsNew)));
queues.h.app.ui.dialog = None;
let released = drain_ready(&mut queues, false).unwrap();
assert_eq!(released.dropped.len(), 1, "protected A survived B's refusal");
assert!(std::sync::Arc::ptr_eq(&released.dropped[0], &a));
assert_eq!(released.pending, Some(vec!["web/hash/stored.png".into()]));
let empty = drain_ready(&mut queues, false).unwrap();
assert!(empty.dropped.is_empty());
assert_eq!(empty.pending, Some(Vec::<String>::new()));
assert_eq!(reads_a.load(std::sync::atomic::Ordering::SeqCst), 0);
assert_eq!(reads_b.load(std::sync::atomic::Ordering::SeqCst), 0);
// Consuming A clears its protection: a later ordinary drop is still fresh.
let (c, reads_c) = unread("C.png");
queues.h.app.ui.dialog = Some(Dialog::WhatsNew);
queue_raw(&mut queues, std::slice::from_ref(&c));
let fresh = drain_ready(&mut queues, true).unwrap();
assert_eq!(fresh.dropped.len(), 1);
assert!(std::sync::Arc::ptr_eq(&fresh.dropped[0], &c));
assert_eq!(fresh.pending, None);
queues.h.app.ui.dialog = None;
assert!(drain_ready(&mut queues, false).unwrap().dropped.is_empty());
assert_eq!(reads_c.load(std::sync::atomic::Ordering::SeqCst), 0);
}
#[test]
fn real_protected_drops_keep_order_through_barrier_reentry_and_transfer_once() {
let (_dir, mut queues) = real_queues("real-reentered").expect("create real-queue library");
let (a, reads_a) = unread("A.png");
let (b, reads_b) = unread("B.png");
protect(&mut queues, &a).expect("hold the library barrier");
queues.h.app.library_problem = None;
queues.h.app.ui.dialog = Some(Dialog::WhatsNew);
assert!(drain_ready(&mut queues, true).unwrap().dropped.is_empty());
queues.h.app.ui.dialog = None;
hold_library(&mut queues).expect("reenter the library barrier"); // Before a pass can consume A.
queue_raw(&mut queues, std::slice::from_ref(&b));
assert!(drain_ready(&mut queues, false).is_none(), "the reentered host gate protects B before native UI");
assert_eq!(queues.h.frames(), 0, "neither protected arrival depends on font readiness or a completed UI pass");
queues.h.app.library_problem = None;
queues.h.app.ui.dialog = Some(Dialog::WhatsNew);
assert!(drain_ready(&mut queues, true).unwrap().dropped.is_empty(), "both real barrier arrivals remain protected");
queues.h.app.ui.dialog = None;
let released = drain_ready(&mut queues, false).unwrap();
assert_eq!(released.dropped.len(), 2);
assert!(std::sync::Arc::ptr_eq(&released.dropped[0], &a));
assert!(std::sync::Arc::ptr_eq(&released.dropped[1], &b));
assert!(drain_ready(&mut queues, false).unwrap().dropped.is_empty());
assert!(queues.h.app.take_dropped_files().is_empty());
assert_eq!(reads_a.load(std::sync::atomic::Ordering::SeqCst), 0);
assert_eq!(reads_b.load(std::sync::atomic::Ordering::SeqCst), 0);
}
}
+5
View File
@@ -16,8 +16,13 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod automation;
pub mod backup;
pub mod bench;
// The web host's drop gate, also compiled natively so its queue handling has tests (the module is
// unused in a native, non-test library build and would otherwise be dead code there).
#[cfg(any(test, target_arch = "wasm32"))]
mod drop_gate;
pub mod files;
pub mod store;
pub mod wire;
+132 -34
View File
@@ -23,7 +23,11 @@ use crate::store::{Originals, content_hash, download_name, storage_key};
use crate::wire::ThumbIndex;
use crate::workers::{THUMB_INDEX, Workers};
const ACCEPT: &str = ".jpg,.jpeg,.png,.tif,.tiff,.webp,.dng,.cr2,.nef,.arw,.psd,.jxl,.gif,.bmp";
/// The web picker's accept list, derived from the engine's import extensions (both
/// cases) so no format the engine can import is silently filtered out of the dialog.
fn accept_list() -> String {
lightcraft_engine::import::accept_list()
}
/// After a failed save, wait this long before trying again (ms).
const SAVE_RETRY_MS: f64 = 2000.0;
@@ -123,7 +127,7 @@ fn open_picker(originals: Originals, backend: Option<Backend>, ctx: egui::Contex
let Ok(input) = doc.create_element("input").map(|e| e.unchecked_into::<web_sys::HtmlInputElement>()) else { return };
input.set_type("file");
input.set_multiple(true);
input.set_accept(ACCEPT);
input.set_accept(&accept_list());
let inp = input.clone();
let on_change = Closure::<dyn FnMut()>::new(move || {
if let Some(files) = inp.files() {
@@ -164,10 +168,14 @@ fn download(path: &str, bytes: &[u8]) -> Result<(), String> {
Ok(())
}
/// Build the browser host's `Services`: library backup/restore through browser storage and a
/// download, asynchronous file picking, downloads for writes, and PNG encoding. Desktop-only
/// services (native pickers, reveal, model folders) stay unset.
fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen: Rc<Cell<bool>>, ctx: egui::Context) -> Services {
let (backup_backend, backup_files) = (backend.clone(), files);
let restore_backend = backend.clone();
Services {
local_places: None,
picker: None,
pick_display_profile: None,
screen_profile: None,
@@ -224,7 +232,12 @@ fn services(originals: Originals, backend: Option<Backend>, files: Files, frozen
save_curve_preset_file: None,
pick_slideshow_templates: None,
save_slideshow_template: None,
pick_print_templates: None,
save_print_template: None,
write: Some(Box::new(download)),
// the browser download path has no meaningful create-new file write; the control channel
// (and therefore screenshot paths) is not available on the web
write_new: None,
// downloads happen on the main thread: exports run in the foreground on the web
write_shared: None,
png: Some(Box::new(|img: &lightcraft_raster::Rgba8| {
@@ -267,12 +280,14 @@ async fn flush(files: Files, backend: Backend, dir: String, flushing: Rc<Cell<bo
log::error!("saving {} failed: {e}", op.name());
files.failed(&ops[i..]);
files.set_error(Some(e));
failed_at.set(perf_now());
failed_at.set(lightcraft_ui_egui::monotonic_ms());
break 'outer;
}
}
}
flushing.set(false);
// the page title drops its unsaved • now, even when nothing else wakes the page
request_repaint();
}
/// Everything loaded before the UI starts.
@@ -402,11 +417,43 @@ struct WebApp {
lib_dir: String,
bench: Option<Bench>,
first_frame_logged: bool,
/// The page title last set (`document.title`), so it is written only when it changes.
title: String,
last_save: f64,
ui_written: Vec<u8>,
}
/// The browser host's drop queues, taken only through the shared gate: a prompt or blocking
/// library window leaves both untouched for a later UI pass.
impl crate::drop_gate::QueuedDrops for WebApp {
type Dropped = egui::DroppedFileHandle;
type Pending = String;
fn drops_wait(&self) -> bool {
crate::drop_gate::drops_wait(&self.app)
}
fn defer_dropped(&mut self) {
self.app.defer_dropped_files();
}
fn take_dropped(&mut self) -> Vec<Self::Dropped> {
self.app.take_dropped_files()
}
fn take_unprotected_dropped(&mut self) -> Vec<Self::Dropped> {
self.app.take_unprotected_dropped_files()
}
fn take_pending(&mut self) -> Vec<Self::Pending> {
self.originals.take_pending()
}
}
impl WebApp {
/// Construct the web app from the boot options: install originals and open the library from
/// browser storage (a read failure starts an empty session and a blocking `LibraryProblem`),
/// load the stored UI state, start render workers and the optional benchmark.
fn new(cc: &eframe::CreationContext<'_>, boot: Boot, chinese_font: Vec<u8>) -> Self {
let Boot { opts, backend, files, index, lib_dir, load_error } = boot;
let originals = Originals::default();
@@ -462,7 +509,12 @@ impl WebApp {
let mut app = LightcraftApp::new(session, services(originals.clone(), backend.clone(), files.clone(), frozen.clone(), cc.egui_ctx.clone()))
.with_chinese_font(chinese_font);
let ui_written = files.get("ui.json").unwrap_or_default();
if let Ok(ui) = serde_json::from_slice::<UiState>(&ui_written) {
// an arrangement from an older docking version starts again from the default
let mut saved = serde_json::from_slice::<serde_json::Value>(&ui_written).unwrap_or_default();
if let Some(fields) = saved.as_object_mut() {
lightcraft_ui_egui::docking::drop_outdated(fields);
}
if let Ok(ui) = serde_json::from_value::<UiState>(saved) {
app.ui = ui;
}
app.ui = app.ui.sanitized();
@@ -488,7 +540,7 @@ impl WebApp {
}
log::info!("lightcraft: {n} render workers");
CTX.with(|c| *c.borrow_mut() = Some(cc.egui_ctx.clone()));
let origin = lightcraft_ui_egui::now_ms() - perf_now();
let origin = lightcraft_ui_egui::monotonic_ms();
WebApp {
app,
originals,
@@ -501,29 +553,51 @@ impl WebApp {
lib_dir,
bench: opts.bench.then(|| Bench::new(origin)),
first_frame_logged: false,
title: String::new(),
last_save: 0.0,
ui_written,
}
}
/// Consume the drops the raw-input hook queued once (never re-read `raw.dropped_files` in a
/// hidden logic tick), and add originals whose bytes have arrived.
fn import_dropped(&mut self, ctx: &egui::Context) {
let dropped = ctx.input(|i| i.raw.dropped_files.clone());
for f in dropped {
// A prompt or the blocking library window (including the chooser's own New Library name
// prompt or asynchronous folder picker) holds both queues for a later UI pass: nothing is
// read or imported behind it. `drain_ready` is the same orchestration the native tests run.
let dialog_open = self.app.ui.dialog.is_some();
let Some(drained) = crate::drop_gate::drain_ready(self, dialog_open) else { return };
// a dialog is on screen (the card said so while the files hovered): nothing is read or imported
// (files read from an earlier drop still finish below)
if !drained.dropped.is_empty() && dialog_open {
self.app.toast(ctx, lightcraft_ui_egui::i18n::tr("Close the open dialog, then drop the files again"));
return;
}
for f in drained.dropped {
let (originals, backend, ctx) = (self.originals.clone(), self.backend.clone(), ctx.clone());
wasm_bindgen_futures::spawn_local(async move {
let name = f.path().to_string_lossy().to_string();
match f.bytes_async().await {
let name = egui::DroppedFile::path(f.as_ref()).to_string_lossy().to_string();
match egui::DroppedFile::bytes_async(f.as_ref()).await {
Ok(bytes) => store_file(originals, backend, name, bytes, ctx).await,
Err(e) => log::warn!("reading dropped {name}: {e}"),
Err(e) => notice(lightcraft_ui_egui::i18n::dropped_file_unreadable(&name, &e.to_string())),
}
});
}
let paths = self.originals.take_pending();
let Some(paths) = drained.pending else { return };
if !paths.is_empty() {
let n = paths.len();
match self.app.run("library.import", json!({"paths": paths})) {
Ok(_) => self.app.toast(ctx, format!("Added {n} photo{}", if n == 1 { "" } else { "s" })),
Err(e) => log::warn!("import: {e}"),
// what the import did, not what was submitted: duplicates and unsupported files add nothing,
// a drop that only finds duplicates says nothing (as the desktop import's toast does when it
// shows where they are), and one whose files could not be read says so
Ok(report) => {
if let Some(notice) = lightcraft_ui_egui::i18n::dropped_photos_outcome(&report) {
self.app.toast(ctx, notice);
}
}
Err(e) => {
log::warn!("import: {e}");
self.app.toast(ctx, lightcraft_ui_egui::i18n::dropped_import_failed(&e));
}
}
}
}
@@ -563,7 +637,7 @@ impl WebApp {
if self.frozen.get() {
return;
}
let now = perf_now();
let now = lightcraft_ui_egui::monotonic_ms();
if now - self.last_save >= SAVE_EVERY_MS {
self.last_save = now;
self.app.session.save_view();
@@ -639,8 +713,11 @@ impl WebApp {
fn run_inbox(&mut self) {
let inbox = INBOX.with(|q| std::mem::take(&mut *q.borrow_mut()));
for (id, params, (resolve, reject)) in inbox {
let params: serde_json::Value = serde_json::from_str(&params).unwrap_or(json!({}));
let r = if id == "web.stats" { Ok(self.web_stats()) } else { self.app.run(&id, params) };
let r = match crate::automation::params(&params) {
Err(e) => Err(format!("{id}: {e}")),
Ok(_) if id == "web.stats" => Ok(self.web_stats()),
Ok(params) => self.app.run(&id, params),
};
let _ = match r {
Ok(v) => resolve.call1(&JsValue::NULL, &v.to_string().into()),
Err(e) => reject.call1(&JsValue::NULL, &e.into()),
@@ -650,13 +727,14 @@ impl WebApp {
}
impl eframe::App for WebApp {
/// eframe's non-drawing pass for the browser host: drain safety notices and queued inbox work,
/// load originals the UI requested, apply the cache budget, run the app's logic, then save.
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
for text in safety::take_notices() {
let now = ctx.input(|i| i.time);
let now = self.app.tick_now();
self.app.ui.toast = Some((text, now + NOTICE_SECS, None));
}
self.run_inbox();
self.import_dropped(ctx);
self.load_originals(ctx);
if let Some(w) = &self.workers {
// `library.preferences ▸ cacheMb` is read by the session; the worker index prunes on
@@ -665,27 +743,47 @@ impl eframe::App for WebApp {
}
self.app.logic(ctx);
self.save();
if let Some(b) = self.bench.as_mut()
&& let Some(report) = b.step(&mut self.app)
{
log::info!("lightcraft-bench {report}");
if let Some((alive, ready, remote, inline)) = self.workers.as_ref().map(Workers::stats) {
log::info!("lightcraft-workers {{\"alive\":{alive},\"ready\":{ready},\"remote_jobs\":{remote},\"inline_jobs\":{inline}}}");
}
set_status(&format!("bench: {report}"));
self.bench = None;
}
if self.bench.is_some() {
ctx.request_repaint();
}
}
fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(raw);
/// Pass the browser's raw input to the app hook before egui processes it, so prompt barriers
/// and synthetic or dropped input are applied consistently with the desktop host.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
self.app.raw_input_hook(ctx, raw);
}
/// eframe's UI pass: import queued drops unless a prompt blocks input, draw the app, update the
/// page title, and advance the benchmark once per root pass.
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
// Drops are the UI phase's: a hidden `logic`/`run_logic` tick must not import them twice.
// `import_dropped` itself takes both queues only through the gate, so a prompt or the
// blocking library window (over an already open library) keeps a stored drop queued.
let ctx = ui.ctx().clone();
self.import_dropped(&ctx);
self.app.ui(ui);
// eframe's web runner ignores `ViewportCommand::Title`: name the open photo in the page title
let title = self.app.page_title(self.files.is_dirty() || self.flushing.get());
if title != self.title
&& let Some(doc) = window().and_then(|w| w.document())
{
doc.set_title(&title);
self.title = title;
}
// The benchmark is a UI-phase step: a second layout pass or a hidden tick must not count a frame.
if ui.ctx().current_pass_index() == 0 {
if let Some(b) = self.bench.as_mut()
&& let Some(report) = b.step(&mut self.app)
{
log::info!("lightcraft-bench {report}");
if let Some((alive, ready, remote, inline)) = self.workers.as_ref().map(Workers::stats) {
log::info!("lightcraft-workers {{\"alive\":{alive},\"ready\":{ready},\"remote_jobs\":{remote},\"inline_jobs\":{inline}}}");
}
set_status(&format!("bench: {report}"));
self.bench = None;
}
if self.bench.is_some() {
ctx.request_repaint();
}
}
if !self.first_frame_logged && !self.app.widgets.is_empty() {
self.first_frame_logged = true;
log::info!("lightcraft first UI frame at {:.0} ms after navigation start", perf_now());
+1 -1
View File
@@ -522,7 +522,7 @@ mod tests {
}
};
frame(&mut watch, &mut index); // an empty filtered view: no render request yet
cache.clear(); // File ▸ Clear Preview Cache
cache.clear(); // File ▸ Discard Preview Cache
frame(&mut watch, &mut index);
// the filter is removed: the first thumbnail request (`Workers::try_start`)
gone.extend(watch.observe(&cache, cache.generation(), &mut index));
+6 -1
View File
@@ -23,7 +23,9 @@ lightcraft-sysmem = { workspace = true }
lightcraft-ui-egui = { workspace = true }
lightcraft-codecs = { workspace = true }
lightcraft-raster = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "glow", "accesskit", "wayland", "x11"] }
# `clipboard` is a separate eframe feature in 0.37: without it egui-winit simulates an in-process
# clipboard and cut/copy/paste, RequestPaste and the Wayland PRIMARY path are unavailable.
eframe = { workspace = true, features = ["default_fonts", "clipboard", "wgpu", "glow", "accesskit", "wayland", "x11"] }
egui = { workspace = true }
serde_json = { workspace = true }
chrono = { workspace = true }
@@ -53,3 +55,6 @@ objc2-foundation = { workspace = true }
[dev-dependencies]
# tests record why they skip (`cargo xtask ci` lists the skips)
lightcraft-testkit = { workspace = true }
[target.'cfg(windows)'.dependencies]
craft-update = { workspace = true }
+7
View File
@@ -247,6 +247,9 @@ mod tests {
let mut client = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
client.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
let (stream, _) = listener.accept().unwrap();
// Small test messages must not wait for Nagle's algorithm or a delayed ACK.
client.set_nodelay(true).unwrap();
stream.set_nodelay(true).unwrap();
before(&mut client);
let (tx, requests) = channel();
let worker = spawn_connection(stream, tx, egui::Context::default(), Arc::clone(open), idle).unwrap();
@@ -316,6 +319,10 @@ mod tests {
// A dispatched command waits for its reply, not for socket input.
std::thread::sleep(Duration::from_millis(250));
req.reply.send(json!({"ok": true, "result": id})).unwrap();
if id == 2 {
// The worker must reach EOF even before the client reads its final reply.
connection.join();
}
let mut reply = String::new();
connection.client.read_line(&mut reply).unwrap();
let reply: Value = serde_json::from_str(&reply).unwrap();
+14 -4
View File
@@ -133,13 +133,23 @@ mod tests {
}
}
/// Every dialog filter goes through the helper: `main.rs` must not call rfd's own
/// Every dialog filter goes through the helper: no source file in `src/` calls rfd's own
/// `add_filter`.
#[test]
fn no_dialog_bypasses_the_helper() {
for (file, src) in [("main.rs", include_str!("main.rs")), ("control_server.rs", include_str!("control_server.rs"))] {
assert!(!src.contains(".add_filter("), "{file} calls rfd's add_filter; use add_filter_nocase");
let mut dirs = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src")];
let mut helper_used = false;
while let Some(dir) = dirs.pop() {
for path in std::fs::read_dir(&dir).unwrap().map(|entry| entry.unwrap().path()) {
if path.is_dir() {
dirs.push(path);
} else if path.extension().is_some_and(|ext| ext == "rs") && !path.ends_with("dialog_filter.rs") {
let src = std::fs::read_to_string(&path).unwrap();
assert!(!src.contains(".add_filter("), "{} calls rfd's add_filter; use add_filter_nocase", path.display());
helper_used |= src.contains(".add_filter_nocase(");
}
}
}
assert!(include_str!("main.rs").contains(".add_filter_nocase("));
assert!(helper_used);
}
}
+134 -23
View File
@@ -31,22 +31,14 @@ pub fn check(app: &str) -> Result<(), String> {
/// Open `path` in `app` (see [`check`]). Spawned, never waited for: the editor runs alongside.
pub fn open_with(path: &str, app: &str) -> Result<(), String> {
let mut c = match launcher(app)? {
Launcher::Default if cfg!(target_os = "macos") => {
let mut c = Command::new("open");
c.arg(path);
c
}
Launcher::Default if cfg!(target_os = "macos") => return run_open(&[path]),
Launcher::Default if cfg!(target_os = "windows") => windows_default_command(path),
Launcher::Default => {
let mut c = Command::new("xdg-open");
c.arg(path);
c
}
Launcher::MacApp(app) => {
let mut c = Command::new("open");
c.args(["-a", &app, path]);
c
}
Launcher::MacApp(app) => return run_open(&["-a", &app, path]),
Launcher::Program(p) => {
let mut c = Command::new(p);
c.arg(path);
@@ -61,6 +53,22 @@ pub fn open_with(path: &str, app: &str) -> Result<(), String> {
c.spawn().map(|_| ()).map_err(|e| e.to_string())
}
/// macOS: run `open` and wait for it (it returns as soon as LaunchServices has handed the file
/// over), so an application it can't find or start is reported instead of silently doing nothing.
fn run_open(args: &[&str]) -> Result<(), String> {
let out = Command::new("open").args(args).output().map_err(|e| e.to_string())?;
open_result(out.status.success(), &String::from_utf8_lossy(&out.stderr))
}
/// What `open` said, as a result: its own message when it failed.
fn open_result(ok: bool, stderr: &str) -> Result<(), String> {
if ok {
return Ok(());
}
let msg = stderr.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("the application couldn't be started");
Err(msg.to_string())
}
/// Open every file in `paths` with one start of `app`, as a file manager hands over a selection:
/// an editor that keeps a single window (DxO PhotoLab) loses the files that arrive while it is
/// still starting when it is started once per file. The system default opens them one by one
@@ -119,10 +127,15 @@ fn launcher(app: &str) -> Result<Launcher, String> {
fn find_photocraft() -> Option<Launcher> {
let env = |k: &str| std::env::var_os(k).map(|v| v.to_string_lossy().to_string());
if cfg!(target_os = "macos") {
// LaunchServices finds the app wherever it is; these are only the usual places
// the usual places, then wherever Spotlight knows it (by bundle id or bundle name)
let home = env("HOME").map(|h| Path::new(&h).join("Applications/PhotoCraft.app"));
let found = [Some(PathBuf::from("/Applications/PhotoCraft.app")), home].into_iter().flatten().find(|p| p.is_dir());
return Some(Launcher::MacApp(found.map_or_else(|| PHOTOCRAFT.to_string(), |p| p.to_string_lossy().to_string())));
let usual = [Some(PathBuf::from("/Applications/PhotoCraft.app")), home].into_iter().flatten().find(|p| p.is_dir());
let spotlight = || {
let query = format!("kMDItemCFBundleIdentifier == '{PHOTOCRAFT_ID}' || kMDItemFSName == 'PhotoCraft.app'");
let out = Command::new("mdfind").arg(query).output().ok().filter(|o| o.status.success())?;
mdfind_app(&String::from_utf8_lossy(&out.stdout))
};
return usual.or_else(spotlight).map(|p| Launcher::MacApp(p.to_string_lossy().to_string()));
}
if cfg!(target_os = "windows") {
let install_dir = reg_query(r"HKLM\Software\PhotoCraft", Some("InstallDir"));
@@ -130,16 +143,34 @@ fn find_photocraft() -> Option<Launcher> {
return windows_candidates(install_dir, app_path, env).into_iter().find(|p| p.is_file()).map(Launcher::Program);
}
// Linux, FreeBSD: on the PATH (.deb, .rpm, tarball), a desktop entry (AppImage, which
// registers one on first run), else the Flatpak
let on_path =
env("PATH").into_iter().flat_map(|p| std::env::split_paths(&p).collect::<Vec<_>>()).map(|d| d.join("photocraft")).find(|p| p.is_file());
// registers one on first run; its Exec a path or a name on the PATH), an AppImage where people
// keep them, else the Flatpak
let path_dirs: Vec<PathBuf> = env("PATH").into_iter().flat_map(|p| std::env::split_paths(&p).collect::<Vec<_>>()).collect();
let on_path = |name: &Path| resolve_program(name, &path_dirs);
let from_entry = || {
desktop_entry_dirs(env).into_iter().find_map(|d| {
let text = std::fs::read_to_string(d.join(format!("{PHOTOCRAFT_ID}.desktop"))).ok()?;
desktop_exec(&text).filter(|p| p.is_file())
desktop_exec(&text)
// a wrapper (`Exec=env VAR=1 /opt/PhotoCraft/photocraft %F`) would be started with the photo only:
// skip it and look further
.filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().to_lowercase().contains("photocraft")))
.and_then(|p| on_path(&p))
})
};
if let Some(p) = on_path.or_else(from_entry) {
let appimage = || {
let home = env("HOME")?;
let dirs = [Path::new(&home).join("Applications"), Path::new(&home).join(".local/bin")];
// both folders, so the newest version wins whichever it is in
let mut found: Vec<PathBuf> = dirs
.iter()
.filter_map(|d| std::fs::read_dir(d).ok())
.flat_map(|rd| rd.flatten().map(|e| e.path()).filter(|p| is_photocraft_appimage(p) && p.is_file()).collect::<Vec<_>>())
.collect();
// the newest version by name (1.10 after 1.9)
found.sort_by_key(|p| version_key(&p.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default()));
found.pop()
};
if let Some(p) = on_path(Path::new("photocraft")).or_else(from_entry).or_else(appimage) {
return Some(Launcher::Program(p));
}
let flatpak = Command::new("flatpak").args(["info", PHOTOCRAFT_ID]).output().is_ok_and(|o| o.status.success());
@@ -205,10 +236,44 @@ fn desktop_exec(entry: &str) -> Option<PathBuf> {
Some(rest) => rest.split('"').next()?,
None => exec.split_whitespace().next()?,
};
// a bare name (`photocraft %F`) was already looked for on the PATH. Desktop entries are a
// freedesktop (POSIX) format: absolute means a leading `/` on every platform the parser runs on
// (`Path::is_absolute` wants a drive letter on Windows, where the tests run too)
program.starts_with('/').then(|| PathBuf::from(program))
// a path, or a bare name (`photocraft %F`) the caller looks for on the PATH
(!program.is_empty()).then(|| PathBuf::from(program))
}
/// A program from a desktop entry or the PATH: a path as it is (if it is a file), a bare name
/// looked for in `dirs`. A leading `/` counts as absolute on every platform (desktop entries are
/// a POSIX format; `Path::is_absolute` wants a drive letter on Windows, where the tests run too).
fn resolve_program(name: &Path, dirs: &[PathBuf]) -> Option<PathBuf> {
if name.is_absolute() || name.starts_with("/") {
return Some(name.to_path_buf()).filter(|p| p.is_file());
}
dirs.iter().map(|d| d.join(name)).find(|p| p.is_file())
}
/// A sort key that orders the digit runs in a name by value (`1.9` before `1.10`).
fn version_key(name: &str) -> Vec<(u64, String)> {
let mut out = Vec::new();
let mut rest = name;
while !rest.is_empty() {
let digits = rest.len() - rest.trim_start_matches(|c: char| c.is_ascii_digit()).len();
let (num, tail) = rest.split_at(digits);
let text_len = tail.find(|c: char| c.is_ascii_digit()).unwrap_or(tail.len());
let (text, next) = tail.split_at(text_len);
out.push((num.parse().unwrap_or(u64::MAX), text.to_string()));
rest = next;
}
out
}
/// An AppImage of PhotoCraft by its file name (`PhotoCraft-1.2-x86_64.AppImage`, any case).
fn is_photocraft_appimage(p: &Path) -> bool {
let name = p.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
name.contains("photocraft") && name.ends_with(".appimage")
}
/// The first application bundle in `mdfind` output (one path per line).
fn mdfind_app(output: &str) -> Option<PathBuf> {
output.lines().map(str::trim).find(|l| l.ends_with(".app")).map(PathBuf::from)
}
#[cfg(test)]
@@ -275,13 +340,59 @@ mod tests {
let appimage = "[Desktop Entry]\nName=PhotoCraft\nExec=\"/home/simon/Apps/photocraft-1.2-linux-x86_64.AppImage\" %F\n";
assert_eq!(desktop_exec(appimage), Some(PathBuf::from("/home/simon/Apps/photocraft-1.2-linux-x86_64.AppImage")));
assert_eq!(desktop_exec("Exec=/opt/photocraft/photocraft %F\n"), Some(PathBuf::from("/opt/photocraft/photocraft")));
assert_eq!(desktop_exec("Exec=photocraft %F\nTryExec=photocraft\n"), None, "a bare name is a PATH lookup");
assert_eq!(desktop_exec("Exec=photocraft %F\nTryExec=photocraft\n"), Some(PathBuf::from("photocraft")), "a bare name, for a PATH lookup");
assert_eq!(desktop_exec("[Desktop Entry]\n"), None);
let dirs = desktop_entry_dirs(|k| (k == "HOME").then(|| "/home/simon".to_string()));
assert_eq!(dirs[0], PathBuf::from("/home/simon/.local/share/applications"));
assert!(dirs.contains(&PathBuf::from("/usr/share/applications")));
}
#[test]
fn a_bare_exec_name_is_found_on_the_path() {
let a = std::env::temp_dir().join(format!("lc-editors-a-{}", std::process::id()));
let b = std::env::temp_dir().join(format!("lc-editors-b-{}", std::process::id()));
std::fs::create_dir_all(&a).unwrap();
std::fs::create_dir_all(&b).unwrap();
std::fs::write(b.join("photocraft"), b"").unwrap();
let dirs = vec![a.clone(), b.clone()];
assert_eq!(resolve_program(Path::new("photocraft"), &dirs), Some(b.join("photocraft")));
assert_eq!(resolve_program(Path::new("nothere"), &dirs), None);
let abs = b.join("photocraft");
assert_eq!(resolve_program(&abs, &[]), Some(abs.clone()), "a path needs no PATH");
assert_eq!(resolve_program(&b.join("missing"), &dirs), None);
let _ = std::fs::remove_dir_all(&a);
let _ = std::fs::remove_dir_all(&b);
}
#[test]
fn appimage_versions_sort_numerically() {
let mut names = ["photocraft-1.10-x86_64.appimage", "photocraft-1.9-x86_64.appimage", "photocraft-1.2-x86_64.appimage"];
names.sort_by_key(|n| version_key(n));
assert_eq!(names[2], "photocraft-1.10-x86_64.appimage");
assert_eq!(names[0], "photocraft-1.2-x86_64.appimage");
}
#[test]
fn a_failed_open_is_an_error() {
assert!(open_result(true, "").is_ok());
assert!(open_result(false, "Unable to find application\n").is_err());
assert!(open_result(false, "").is_err(), "even when it says nothing");
}
#[test]
fn odd_detection_input_does_not_panic() {
for text in ["", "Exec=", "Exec=\"", "Exec=\"\"", "\u{0}\u{fffd}", "Exec= %F", "[Desktop Entry]\nExec=\u{e9}\u{301}"] {
let _ = desktop_exec(text);
let _ = mdfind_app(text);
let _ = reg_value(text);
}
for p in ["", "/", ".AppImage", "\u{e9}.appimage", "a/../b"] {
let _ = is_photocraft_appimage(Path::new(p));
}
let _ = desktop_entry_dirs(|_| None);
let _ = windows_candidates(None, Some("\"".into()), |_| None);
}
#[test]
fn other_editors_are_used_as_named() {
assert_eq!(launcher("").unwrap(), Launcher::Default);
+97
View File
@@ -0,0 +1,97 @@
use super::prefs::config_dir;
use super::window_gpu;
/// The window's renderer (egui-wgpu): eframe's defaults, with LightCraft's backend choice — DX12
/// alone on Windows unless `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND` say otherwise (issue #136:
/// with Vulkan in the set, wgpu loads the Vulkan driver even when it then picks DX12) — and DX12
/// shaders compiled with FXC, never a stray `dxcompiler.dll` (issue #471).
/// The fallback chain on top of it (DX12 → Vulkan → GL → glow) is in `window_gpu`.
#[cfg(test)]
pub(crate) fn window_wgpu_options() -> eframe::egui_wgpu::WgpuConfiguration {
window_gpu::base_options()
}
/// Where the window's renderer files live (`window_gpu::Files`): nothing for `--memory` sessions
/// and `LIGHTCRAFT_NO_PREFS`.
pub(crate) fn window_files(in_memory: bool) -> window_gpu::Files {
window_gpu::Files::new(config_dir().filter(|_| !in_memory && std::env::var_os("LIGHTCRAFT_NO_PREFS").is_none()))
}
/// Written while the GPU compute device is created, removed once that returned
/// (`lightcraft_gpu::backend::set_init_marker`). Not with `LIGHTCRAFT_NO_PREFS` (tests, scripts).
fn gpu_marker_path() -> Option<std::path::PathBuf> {
if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() {
return None;
}
config_dir().map(|d| d.join("gpu-init.marker"))
}
/// Arm the GPU crash sentinel; if the previous launch left it behind (it died inside the GPU
/// driver while creating the device), the notice to show — GPU rendering then starts off.
///
/// A `--memory` session writes nothing (issue #169): it neither arms the sentinel — which would
/// create the settings folder — nor removes a marker it finds. It still honours one, so the GPU
/// starts off there too, and the next ordinary launch reports and clears it.
pub(crate) fn gpu_crash_check(in_memory: bool) -> Option<String> {
gpu_crash_check_at(gpu_marker_path(), in_memory)
}
pub(crate) fn gpu_crash_check_at(marker: Option<std::path::PathBuf>, in_memory: bool) -> Option<String> {
use lightcraft_engine::gpu::backend;
let left = if in_memory {
marker.as_deref().and_then(backend::read_init_marker)
} else {
let left = marker.as_deref().and_then(backend::take_init_marker);
backend::set_init_marker(marker);
left
};
left.map(|what| gpu_crash_notice(&what))
}
pub(crate) fn gpu_crash_notice(what: &str) -> String {
format!(
"LightCraft closed unexpectedly while starting the GPU last time ({what}), so GPU rendering is now off and photos render on the CPU. \
To try the GPU again, turn on Settings ▸ Performance ▸ Use the GPU for rendering; to try another graphics backend, start LightCraft with \
LIGHTCRAFT_GPU_BACKEND=dx12, vulkan or off (see docs/gpu-pipeline.md → Troubleshooting)."
)
}
/// Written when the window stopped drawing after the GPU device was lost (issue #1337): the next
/// launch renders on the CPU and says why.
pub(crate) fn gpu_lost_marker_path() -> Option<std::path::PathBuf> {
gpu_marker_path().map(|p| p.with_file_name("gpu-lost.marker"))
}
/// Why the GPU was lost, when the GPU pipeline stopped after a device failure in this process (a
/// driver reset, a hang, the Windows watchdog): `None` for other reasons it is off, or when it
/// never failed.
pub(crate) fn gpu_lost_reason() -> Option<String> {
lightcraft_engine::gpu::unavailable_reason().and_then(|r| r.strip_prefix("stopped after a GPU failure: ").map(str::to_string))
}
/// Record that LightCraft stopped after the GPU was lost, for the next launch.
pub(crate) fn record_gpu_lost(marker: Option<&std::path::Path>, reason: &str) {
let Some(m) = marker else { return };
if let Some(d) = m.parent() {
let _ = std::fs::create_dir_all(d);
}
if let Err(e) = std::fs::write(m, format!("{reason}\n")) {
log::warn!("could not write {}: {e}", m.display());
}
}
/// A GPU loss the last launch stopped on: its notice, once (the marker is removed, except by a
/// `--memory` session, which leaves the disk as it found it).
pub(crate) fn gpu_lost_check_at(marker: Option<&std::path::Path>, in_memory: bool) -> Option<String> {
let m = marker?;
let reason = std::fs::read_to_string(m).ok()?;
if !in_memory {
let _ = std::fs::remove_file(m);
}
Some(format!(
"LightCraft stopped last time after the graphics driver reset the GPU ({}) while photos rendered on it, so GPU rendering \
is now off and photos render on the CPU. To try the GPU again, turn on Settings ▸ Performance ▸ Use the GPU for rendering; \
an up-to-date graphics driver may help.",
reason.trim()
))
}
+138
View File
@@ -0,0 +1,138 @@
use super::prefs::config_dir;
pub(crate) const HELP: &str = "\
lightcraft — photo library + raw developer
USAGE: lightcraft [OPTIONS] [FILES/FOLDERS…] (files and folders are imported)
OPTIONS:
--library DIR open (or create) this library (env LIGHTCRAFT_LIBRARY; default: the last library opened, or
a list of the recent ones with Settings > General > At launch: Ask me or Alt/Option held,
else ~/Pictures/LightCraft Library)
--no-demo don't seed a new library with 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)
--version, --help
ENVIRONMENT:
LIGHTCRAFT_CONFIG_DIR=DIR use this settings folder instead of the platform default (empty = no settings folder).
Without it, a portable.txt file next to the program puts the folder beside it (LightCraftData)
LIGHTCRAFT_GPU_BACKEND=dx12|vulkan|metal|auto|off graphics backend (default: DX12 on Windows, Metal on macOS,
Vulkan on Linux; off = render on the CPU); else WGPU_BACKEND. LIGHTCRAFT_GPU=0: CPU rendering.
LIGHTCRAFT_SAM3_DIR=DIR the SAM 3 model for Object / Describe masks (default: <settings folder>/models/sam3;
optional: LightCraft offers to download it when first needed)
LIGHTCRAFT_SAM3_MIRRORS=URL,… where to download the SAM 3 model from (base URLs, tried in order)
LIGHTCRAFT_LOG=info|debug more log detail from LightCraft itself (default: info from LightCraft, warnings
from other crates); else RUST_LOG=<env_logger directives>. Records go to stderr and to
<settings folder>/logs/lightcraft.log (previous runs: lightcraft.1.log, lightcraft.2.log)
";
/// The launch arguments' files and folders to import (absolute), and a notice for each one that
/// is not imported (see [`lightcraft_engine::import::launch_path`]; issue #374).
pub(crate) fn launch_imports(args: &[String]) -> (Vec<String>, Vec<String>) {
let cwd = std::env::current_dir().ok();
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
launch_imports_in(args, cwd.as_deref(), home.as_deref())
}
pub(crate) fn launch_imports_in(args: &[String], cwd: Option<&std::path::Path>, home: Option<&std::path::Path>) -> (Vec<String>, Vec<String>) {
use lightcraft_engine::import::{LaunchPath, launch_path};
let (mut files, mut notices) = (Vec::new(), Vec::new());
for a in args {
match launch_path(a, cwd, home, lightcraft_engine::devices::dcim_in) {
Some(LaunchPath::Import(p)) => files.push(p),
Some(LaunchPath::Refused { path, why }) => {
log::warn!("not importing {path} given at launch: {why}");
notices
.push(format!("{path} was not imported: it is {why}. To import from it, choose a folder inside it with File ▸ Import Photos…"));
}
None => {}
}
}
(files, notices)
}
/// Where the log files live: `logs` in the settings folder, next to `ui.json` (see `logging`).
/// None with `LIGHTCRAFT_NO_PREFS` (tests, scripts), so those runs don't rotate away the user's logs.
pub(crate) fn log_dir() -> Option<std::path::PathBuf> {
if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() {
return None;
}
config_dir().map(|d| d.join("logs"))
}
/// The control port `value` names; a value that isn't a port is logged and ignored (`what` is
/// the option or variable it came from). Logged before the log file opens, so it is kept for it.
pub(crate) fn control_port_from(what: &str, value: Option<String>) -> Option<u16> {
let value = value?;
let port = value.trim().parse().ok();
if port.is_none() {
log::warn!("{what} {value:?} is not a port number; no control server");
}
port
}
/// An isolated profile keeps the emergency crash log with its other app data. With no
/// override (or an empty override), retain the historical system-temp location.
pub(crate) fn panic_log_path_with(env: impl Fn(&str) -> Option<std::ffi::OsString>, temp: std::path::PathBuf) -> std::path::PathBuf {
env("LIGHTCRAFT_CONFIG_DIR").filter(|value| !value.is_empty()).map(std::path::PathBuf::from).unwrap_or(temp).join("lightcraft-panics.log")
}
/// What to tell the user when LightCraft stopped while running (`error`), and why when the GPU
/// was lost (`lost`): GPU rendering is off from the next start.
pub(crate) fn stopped_text(error: &str, lost: Option<&str>) -> String {
match lost {
Some(reason) => format!(
"{error}. The graphics driver reset the GPU ({reason}). LightCraft renders on the CPU from its next start; \
Settings ▸ Performance ▸ Use the GPU for rendering turns the GPU back on"
),
None => error.to_string(),
}
}
/// LightCraft stopped while its window was up: say so in the log and in a native message box
/// naming the log file (as [`startup_failed`] does for a start that failed).
pub(crate) fn stopped_while_running(text: &str, log_file: Option<&std::path::Path>) {
log::error!("LightCraft stopped: {text}");
if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() {
return; // tests and scripts: no dialog to click away
}
let (title, text) = lightcraft_ui_egui::i18n::stopped_message(text, log_file.map(|p| p.display().to_string()).as_deref());
let _ = rfd::MessageDialog::new()
.set_level(rfd::MessageLevel::Error)
.set_title(title)
.set_description(text)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
/// The window could not start (e.g. no usable graphics device): say so in the log and in a native
/// message box naming the log file, instead of exiting without a trace — the release builds have
/// no console on Windows, and an app started from Finder shows no standard error (issue #260).
pub(crate) fn startup_failed(error: &str, log_file: Option<&std::path::Path>) {
log::error!("LightCraft could not open its window: {error}");
if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() {
return; // tests and scripts: no dialog to click away
}
let (title, text) = lightcraft_ui_egui::i18n::startup_failed_message(error, log_file.map(|p| p.display().to_string()).as_deref());
let _ = rfd::MessageDialog::new()
.set_level(rfd::MessageLevel::Error)
.set_title(title)
.set_description(text)
.set_buttons(rfd::MessageButtons::Ok)
.show();
}
#[cfg(test)]
mod config_path_tests {
use super::*;
#[test]
fn config_override_keeps_panic_log_in_isolated_profile() {
let temp = std::path::PathBuf::from("temp");
assert_eq!(panic_log_path_with(|_| Some("isolated".into()), temp.clone()), std::path::PathBuf::from("isolated/lightcraft-panics.log"));
assert_eq!(panic_log_path_with(|_| None, temp.clone()), temp.join("lightcraft-panics.log"));
assert_eq!(panic_log_path_with(|_| Some("".into()), temp.clone()), temp.join("lightcraft-panics.log"));
}
}
+1 -366
View File
@@ -343,369 +343,4 @@ pub fn record_panics(logger: &'static AppLogger) {
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, UNIX_EPOCH};
fn temp_dir(tag: &str) -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let d = std::env::temp_dir().join(format!("lightcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&d);
d
}
fn read(path: &Path) -> String {
std::fs::read_to_string(path).expect("read log")
}
fn record(logger: &AppLogger, level: log::Level, target: &str, msg: &str) {
use log::Log;
logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build());
}
/// The logger this replaced (`StderrLog`): warnings and errors from every target, `info` and
/// `debug` only from LightCraft's own crates, and only when `LIGHTCRAFT_LOG` asked for them.
fn old_stderr_log_enabled(lightcraft_log: &str, level: log::Level, target: &str) -> bool {
let max = match lightcraft_log {
"debug" => LevelFilter::Debug,
"info" => LevelFilter::Info,
_ => LevelFilter::Warn,
};
level <= max && (level <= log::Level::Warn || target.starts_with("lightcraft"))
}
#[test]
fn the_default_filter_shows_lightcraft_info_and_other_crates_warnings() {
let f = Filter::parse(DEFAULT_FILTER);
assert_eq!(f.level_for("lightcraft"), LevelFilter::Info);
assert_eq!(f.level_for("lightcraft::control_server"), LevelFilter::Info);
assert_eq!(f.level_for("lightcraft_engine::guard"), LevelFilter::Info);
assert_eq!(f.level_for("lightcraft_ui_egui::render"), LevelFilter::Info);
assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn);
assert_eq!(f.level_for("naga"), LevelFilter::Warn);
assert_eq!(f.max(), LevelFilter::Info);
assert_eq!(filter_spec(None, None), DEFAULT_FILTER);
// An empty variable is the same as an unset one.
assert_eq!(filter_spec(Some(""), Some(" ")), DEFAULT_FILTER);
}
/// `LIGHTCRAFT_LOG` keeps working exactly as it did with the old stderr-only logger.
#[test]
fn lightcraft_log_keeps_its_meaning() {
let targets =
["lightcraft", "lightcraft::control_server", "lightcraft_engine::segment", "lightcraft_gpu", "wgpu_core::device", "naga", "eframe"];
let levels = [log::Level::Error, log::Level::Warn, log::Level::Info, log::Level::Debug, log::Level::Trace];
for value in ["info", "debug", "warn", "error", "verbose", "INFO"] {
let f = Filter::parse(&filter_spec(Some(value), None));
for target in targets {
for level in levels {
assert_eq!(level <= f.level_for(target), old_stderr_log_enabled(value, level, target), "LIGHTCRAFT_LOG={value} {level} {target}");
}
}
}
assert_eq!(Filter::parse(&filter_spec(Some("debug"), None)).max(), LevelFilter::Debug);
assert_eq!(Filter::parse(&filter_spec(Some("warn"), None)).max(), LevelFilter::Warn);
}
#[test]
fn rust_log_replaces_the_default_and_lightcraft_log_wins_over_it() {
assert_eq!(filter_spec(None, Some("warn,wgpu_core=info")), "warn,wgpu_core=info");
let f = Filter::parse(&filter_spec(None, Some("debug")));
assert_eq!(f.level_for("eframe"), LevelFilter::Debug);
// The app's own variable is the more specific choice.
let f = Filter::parse(&filter_spec(Some("info"), Some("trace")));
assert_eq!(f.level_for("eframe"), LevelFilter::Warn);
assert_eq!(f.level_for("lightcraft_engine"), LevelFilter::Info);
}
#[test]
fn directives_follow_env_logger_and_the_most_specific_one_wins() {
let f = Filter::parse("info,wgpu_core=error,lightcraft_pipeline=trace,lightcraft_pipeline::tiles=off");
assert_eq!(f.level_for("eframe"), LevelFilter::Info);
assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error);
assert_eq!(f.level_for("lightcraft_pipeline::stage"), LevelFilter::Trace);
assert_eq!(f.level_for("lightcraft_pipeline::tiles"), LevelFilter::Off);
assert_eq!(f.max(), LevelFilter::Trace);
// A module name is matched at `::` boundaries, not as a bare prefix.
assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info);
// A trailing `*` is a prefix.
assert_eq!(Filter::parse("lightcraft*=debug").level_for("lightcraft_raw::cr2"), LevelFilter::Debug);
assert_eq!(Filter::parse("lightcraft*=debug").level_for("eframe"), LevelFilter::Error);
// A bare target name sets that target to the most verbose level, as env_logger does.
assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace);
assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error);
// Levels are case-insensitive and surrounding blanks are ignored.
assert_eq!(Filter::parse(" WARN , lightcraft = Debug ").level_for("lightcraft"), LevelFilter::Debug);
assert_eq!(Filter::parse(" WARN , lightcraft = Debug ").level_for("eframe"), LevelFilter::Warn);
}
#[test]
fn hostile_specs_never_panic_and_fall_back_sensibly() {
let long = "x".repeat(100_000);
let many = "a=info,".repeat(10_000);
for spec in [
"",
",,,",
"=",
"==",
"=debug",
"lightcraft=",
"nonsense=loud",
"🦀=info",
"*",
"*=",
"=*",
"a=b=c",
"warn,,lightcraft=DEBUG",
"\0",
"é::ü=trace",
&long,
&many,
] {
let f = Filter::parse(spec);
for target in ["", "lightcraft", "🦀", "a::b", "*"] {
let _ = f.level_for(target);
}
let _ = f.max();
let _ = filter_spec(Some(spec), Some(spec));
}
assert_eq!(Filter::parse("warn,,lightcraft=DEBUG").level_for("lightcraft"), LevelFilter::Debug);
// An unknown level is skipped: that target keeps the default.
assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error);
assert_eq!(Filter::parse("lightcraft=").level_for("lightcraft"), LevelFilter::Error);
assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error);
assert_eq!(Filter::parse("🦀=info").level_for("🦀::claw"), LevelFilter::Info);
}
#[test]
fn timestamps_are_utc_with_milliseconds() {
assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z");
// Leap day, and the day after it.
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z");
// 2000 is a leap year (divisible by 400), 2100 is not.
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z");
// Before the epoch (a clock set wrong) clamps instead of panicking.
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
// Past chrono's year range still converts via the 400-year cycle (the old code did too,
// through `civil_from_days`): never a silent reset to the epoch. Platform-safe: Windows'
// SystemTime can't hold this instant, so it is only checked where it exists.
// `u64::MAX / 2` seconds == `i64::MAX` seconds → year 292277026596 (old output).
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) {
assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z");
}
// Years past 9999 keep the plain zero-padded year (no `+`).
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z");
// 10_000_000_000_000 s is far beyond chrono's range; old output is year 318857.
// Windows' SystemTime holds only up to about year 30828, so this is checked where it fits.
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) {
assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z");
}
}
#[test]
fn a_line_carries_time_level_thread_target_and_message() {
assert_eq!(
format_line("2026-10-08T07:59:17.728Z", log::Level::Info, "main", "lightcraft", "library /photos: 12 photos"),
"2026-10-08T07:59:17.728Z INFO [main] lightcraft: library /photos: 12 photos\n"
);
// A multi-line message keeps its lines; the record still ends in one newline.
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
}
#[test]
fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() {
let dir = temp_dir("rotate");
for run in 1..=4 {
let (path, _file) = rotate(&dir).expect("rotate");
assert_eq!(path, dir.join(LOG_FILE));
assert_eq!(read(&path), "");
std::fs::write(&path, format!("run {run}")).expect("write");
}
assert_eq!(read(&dir.join(LOG_FILE)), "run 4");
assert_eq!(read(&dir.join("lightcraft.1.log")), "run 3");
assert_eq!(read(&dir.join("lightcraft.2.log")), "run 2");
assert!(!dir.join("lightcraft.3.log").exists(), "only {KEEP} old logs are kept");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() {
let dir = temp_dir("blocked");
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
std::fs::write(&dir, "a file where the directory should be").expect("block");
assert!(rotate(&dir).is_err());
let _ = std::fs::remove_file(&dir);
}
#[test]
fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() {
let dir = temp_dir("pending");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(MAX_FILE_BYTES);
sink.write("early 1\n");
sink.write("early 2\n");
sink.attach(file);
sink.write("late\n");
assert_eq!(read(&path), "early 1\nearly 2\nlate\n");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() {
let dir = temp_dir("bounded");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(MAX_FILE_BYTES);
for i in 0..MAX_PENDING + 5 {
sink.write(&format!("line {i}\n"));
}
sink.attach(file);
let text = read(&path);
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING);
assert!(text.contains("5 earlier log lines were dropped"), "{text}");
assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n")));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn exactly_a_full_pending_buffer_drops_nothing() {
let dir = temp_dir("full");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(MAX_FILE_BYTES);
for i in 0..MAX_PENDING {
sink.write(&format!("line {i}\n"));
}
sink.attach(file);
let text = read(&path);
assert_eq!(text.lines().count(), MAX_PENDING);
assert!(!text.contains("dropped"), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn without_a_file_nothing_is_kept_in_memory() {
let mut sink = Sink::new(MAX_FILE_BYTES);
sink.write("early\n");
sink.no_file();
sink.write("late\n");
assert!(sink.pending.is_empty() && sink.dropped == 0);
}
#[test]
fn the_file_stops_at_its_size_cap_with_one_note() {
let dir = temp_dir("cap");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(100);
sink.attach(file);
for i in 0..50 {
sink.write(&format!("line {i:02} with some padding\n"));
}
let text = read(&path);
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}");
assert_eq!(text.matches("log file reached").count(), 1, "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_logger_filters_records_and_writes_them_to_the_attached_file() {
use log::Log;
let dir = temp_dir("logger");
let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false);
record(&logger, log::Level::Info, "lightcraft", "before the settings directory");
record(&logger, log::Level::Info, "wgpu_core::device", "too chatty");
let path = logger.attach_dir(&dir).expect("attach");
assert_eq!(path, dir.join(LOG_FILE));
record(&logger, log::Level::Warn, "wgpu_hal::vulkan", "a real warning");
record(&logger, log::Level::Error, "lightcraft_engine::guard", "`develop.reset` failed unexpectedly: boom");
record(&logger, log::Level::Debug, "lightcraft", "below info");
let text = read(&path);
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 3, "{text}");
assert!(lines[0].contains(" INFO [") && lines[0].ends_with("lightcraft: before the settings directory"), "{text}");
assert!(lines[1].ends_with("wgpu_hal::vulkan: a real warning"), "{text}");
assert!(lines[2].contains(" ERROR [") && lines[2].ends_with("lightcraft_engine::guard: `develop.reset` failed unexpectedly: boom"), "{text}");
assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("lightcraft_ui_egui").build()));
assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build()));
// Attaching again rotates: the first log becomes `.1`.
logger.attach_dir(&dir).expect("attach again");
assert_eq!(read(&dir.join("lightcraft.1.log")), text);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn records_from_many_threads_are_whole_lines() {
let dir = temp_dir("threads");
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
let path = logger.attach_dir(&dir).expect("attach");
let workers: Vec<_> = (0..8)
.map(|t| {
let l = std::sync::Arc::clone(&logger);
std::thread::spawn(move || {
for i in 0..100 {
record(&l, log::Level::Info, "lightcraft", &format!("thread {t} record {i}"));
}
})
})
.collect();
for w in workers {
w.join().expect("worker");
}
let text = read(&path);
assert_eq!(text.lines().count(), 800);
assert!(text.lines().all(|l| l.contains(" lightcraft: thread ")), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() {
let dir = temp_dir("unusable");
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
std::fs::write(&dir, "not a directory").expect("block");
let logger = AppLogger::new(Filter::parse("info"), false);
record(&logger, log::Level::Info, "lightcraft", "early");
assert!(logger.attach_dir(&dir).is_err());
record(&logger, log::Level::Error, "x", "still fine");
// Nothing waits in memory for a file that won't come.
assert!(logger.sink.lock().expect("sink").pending.is_empty());
let _ = std::fs::remove_file(&dir);
}
#[test]
fn a_poisoned_sink_still_logs() {
let dir = temp_dir("poison");
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
let l = std::sync::Arc::clone(&logger);
let _ = std::thread::spawn(move || {
let _guard = l.sink.lock().expect("lock");
panic!("poison the sink");
})
.join();
assert!(logger.sink.is_poisoned());
let path = logger.attach_dir(&dir).expect("attach");
record(&logger, log::Level::Warn, "lightcraft", "after the poison");
assert!(read(&path).contains("lightcraft: after the poison"));
let _ = std::fs::remove_dir_all(&dir);
}
/// The panic hook's report lands in the file, and never deadlocks when the panic happened
/// while this thread held the sink.
#[test]
fn a_panic_report_goes_to_the_file_and_never_deadlocks() {
let dir = temp_dir("panic");
let logger = AppLogger::new(Filter::parse("off"), false);
let path = logger.attach_dir(&dir).expect("attach");
logger.record_panic("render", "panicked at crates/x/src/lib.rs:3:5:\nboom");
{
let _held = logger.sink.lock().expect("lock");
logger.record_panic("main", "while the sink is held");
}
let text = read(&path);
assert!(text.contains(" ERROR [render] lightcraft: panicked at crates/x/src/lib.rs:3:5:\nboom\n"), "{text}");
assert!(!text.contains("while the sink is held"), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
}
mod tests;
+363
View File
@@ -0,0 +1,363 @@
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, UNIX_EPOCH};
fn temp_dir(tag: &str) -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
let d = std::env::temp_dir().join(format!("lightcraft-logging-{tag}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
let _ = std::fs::remove_dir_all(&d);
d
}
fn read(path: &Path) -> String {
std::fs::read_to_string(path).expect("read log")
}
fn record(logger: &AppLogger, level: log::Level, target: &str, msg: &str) {
use log::Log;
logger.log(&log::Record::builder().level(level).target(target).args(format_args!("{msg}")).build());
}
/// The logger this replaced (`StderrLog`): warnings and errors from every target, `info` and
/// `debug` only from LightCraft's own crates, and only when `LIGHTCRAFT_LOG` asked for them.
fn old_stderr_log_enabled(lightcraft_log: &str, level: log::Level, target: &str) -> bool {
let max = match lightcraft_log {
"debug" => LevelFilter::Debug,
"info" => LevelFilter::Info,
_ => LevelFilter::Warn,
};
level <= max && (level <= log::Level::Warn || target.starts_with("lightcraft"))
}
#[test]
fn the_default_filter_shows_lightcraft_info_and_other_crates_warnings() {
let f = Filter::parse(DEFAULT_FILTER);
assert_eq!(f.level_for("lightcraft"), LevelFilter::Info);
assert_eq!(f.level_for("lightcraft::control_server"), LevelFilter::Info);
assert_eq!(f.level_for("lightcraft_engine::guard"), LevelFilter::Info);
assert_eq!(f.level_for("lightcraft_ui_egui::render"), LevelFilter::Info);
assert_eq!(f.level_for("wgpu_core::device"), LevelFilter::Warn);
assert_eq!(f.level_for("naga"), LevelFilter::Warn);
assert_eq!(f.max(), LevelFilter::Info);
assert_eq!(filter_spec(None, None), DEFAULT_FILTER);
// An empty variable is the same as an unset one.
assert_eq!(filter_spec(Some(""), Some(" ")), DEFAULT_FILTER);
}
/// `LIGHTCRAFT_LOG` keeps working exactly as it did with the old stderr-only logger.
#[test]
fn lightcraft_log_keeps_its_meaning() {
let targets = ["lightcraft", "lightcraft::control_server", "lightcraft_engine::segment", "lightcraft_gpu", "wgpu_core::device", "naga", "eframe"];
let levels = [log::Level::Error, log::Level::Warn, log::Level::Info, log::Level::Debug, log::Level::Trace];
for value in ["info", "debug", "warn", "error", "verbose", "INFO"] {
let f = Filter::parse(&filter_spec(Some(value), None));
for target in targets {
for level in levels {
assert_eq!(level <= f.level_for(target), old_stderr_log_enabled(value, level, target), "LIGHTCRAFT_LOG={value} {level} {target}");
}
}
}
assert_eq!(Filter::parse(&filter_spec(Some("debug"), None)).max(), LevelFilter::Debug);
assert_eq!(Filter::parse(&filter_spec(Some("warn"), None)).max(), LevelFilter::Warn);
}
#[test]
fn rust_log_replaces_the_default_and_lightcraft_log_wins_over_it() {
assert_eq!(filter_spec(None, Some("warn,wgpu_core=info")), "warn,wgpu_core=info");
let f = Filter::parse(&filter_spec(None, Some("debug")));
assert_eq!(f.level_for("eframe"), LevelFilter::Debug);
// The app's own variable is the more specific choice.
let f = Filter::parse(&filter_spec(Some("info"), Some("trace")));
assert_eq!(f.level_for("eframe"), LevelFilter::Warn);
assert_eq!(f.level_for("lightcraft_engine"), LevelFilter::Info);
}
#[test]
fn directives_follow_env_logger_and_the_most_specific_one_wins() {
let f = Filter::parse("info,wgpu_core=error,lightcraft_pipeline=trace,lightcraft_pipeline::tiles=off");
assert_eq!(f.level_for("eframe"), LevelFilter::Info);
assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error);
assert_eq!(f.level_for("lightcraft_pipeline::stage"), LevelFilter::Trace);
assert_eq!(f.level_for("lightcraft_pipeline::tiles"), LevelFilter::Off);
assert_eq!(f.max(), LevelFilter::Trace);
// A module name is matched at `::` boundaries, not as a bare prefix.
assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info);
// A trailing `*` is a prefix.
assert_eq!(Filter::parse("lightcraft*=debug").level_for("lightcraft_raw::cr2"), LevelFilter::Debug);
assert_eq!(Filter::parse("lightcraft*=debug").level_for("eframe"), LevelFilter::Error);
// A bare target name sets that target to the most verbose level, as env_logger does.
assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace);
assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error);
// Levels are case-insensitive and surrounding blanks are ignored.
assert_eq!(Filter::parse(" WARN , lightcraft = Debug ").level_for("lightcraft"), LevelFilter::Debug);
assert_eq!(Filter::parse(" WARN , lightcraft = Debug ").level_for("eframe"), LevelFilter::Warn);
}
#[test]
fn hostile_specs_never_panic_and_fall_back_sensibly() {
let long = "x".repeat(100_000);
let many = "a=info,".repeat(10_000);
for spec in [
"",
",,,",
"=",
"==",
"=debug",
"lightcraft=",
"nonsense=loud",
"🦀=info",
"*",
"*=",
"=*",
"a=b=c",
"warn,,lightcraft=DEBUG",
"\0",
"é::ü=trace",
&long,
&many,
] {
let f = Filter::parse(spec);
for target in ["", "lightcraft", "🦀", "a::b", "*"] {
let _ = f.level_for(target);
}
let _ = f.max();
let _ = filter_spec(Some(spec), Some(spec));
}
assert_eq!(Filter::parse("warn,,lightcraft=DEBUG").level_for("lightcraft"), LevelFilter::Debug);
// An unknown level is skipped: that target keeps the default.
assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error);
assert_eq!(Filter::parse("lightcraft=").level_for("lightcraft"), LevelFilter::Error);
assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error);
assert_eq!(Filter::parse("🦀=info").level_for("🦀::claw"), LevelFilter::Info);
}
#[test]
fn timestamps_are_utc_with_milliseconds() {
assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z");
// Leap day, and the day after it.
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z");
// 2000 is a leap year (divisible by 400), 2100 is not.
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z");
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z");
// Before the epoch (a clock set wrong) clamps instead of panicking.
assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z");
// Past chrono's year range still converts via the 400-year cycle (the old code did too,
// through `civil_from_days`): never a silent reset to the epoch. Platform-safe: Windows'
// SystemTime can't hold this instant, so it is only checked where it exists.
// `u64::MAX / 2` seconds == `i64::MAX` seconds → year 292277026596 (old output).
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(u64::MAX / 2)) {
assert_eq!(timestamp(far), "292277026596-12-04T15:30:07.000Z");
}
// Years past 9999 keep the plain zero-padded year (no `+`).
assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z");
// 10_000_000_000_000 s is far beyond chrono's range; old output is year 318857.
// Windows' SystemTime holds only up to about year 30828, so this is checked where it fits.
if let Some(far) = UNIX_EPOCH.checked_add(Duration::from_secs(10_000_000_000_000)) {
assert_eq!(timestamp(far), "318857-05-20T17:46:40.000Z");
}
}
#[test]
fn a_line_carries_time_level_thread_target_and_message() {
assert_eq!(
format_line("2026-10-08T07:59:17.728Z", log::Level::Info, "main", "lightcraft", "library /photos: 12 photos"),
"2026-10-08T07:59:17.728Z INFO [main] lightcraft: library /photos: 12 photos\n"
);
// A multi-line message keeps its lines; the record still ends in one newline.
assert!(format_line("t", log::Level::Error, "w", "x", "a\nb\n").ends_with("x: a\nb\n"));
}
#[test]
fn rotation_keeps_the_previous_logs_and_starts_an_empty_file() {
let dir = temp_dir("rotate");
for run in 1..=4 {
let (path, _file) = rotate(&dir).expect("rotate");
assert_eq!(path, dir.join(LOG_FILE));
assert_eq!(read(&path), "");
std::fs::write(&path, format!("run {run}")).expect("write");
}
assert_eq!(read(&dir.join(LOG_FILE)), "run 4");
assert_eq!(read(&dir.join("lightcraft.1.log")), "run 3");
assert_eq!(read(&dir.join("lightcraft.2.log")), "run 2");
assert!(!dir.join("lightcraft.3.log").exists(), "only {KEEP} old logs are kept");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn rotation_into_an_unusable_directory_is_an_error_not_a_panic() {
let dir = temp_dir("blocked");
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
std::fs::write(&dir, "a file where the directory should be").expect("block");
assert!(rotate(&dir).is_err());
let _ = std::fs::remove_file(&dir);
}
#[test]
fn lines_logged_before_the_file_exists_are_written_when_it_is_attached() {
let dir = temp_dir("pending");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(MAX_FILE_BYTES);
sink.write("early 1\n");
sink.write("early 2\n");
sink.attach(file);
sink.write("late\n");
assert_eq!(read(&path), "early 1\nearly 2\nlate\n");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() {
let dir = temp_dir("bounded");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(MAX_FILE_BYTES);
for i in 0..MAX_PENDING + 5 {
sink.write(&format!("line {i}\n"));
}
sink.attach(file);
let text = read(&path);
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING);
assert!(text.contains("5 earlier log lines were dropped"), "{text}");
assert!(text.contains("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n")));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn exactly_a_full_pending_buffer_drops_nothing() {
let dir = temp_dir("full");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(MAX_FILE_BYTES);
for i in 0..MAX_PENDING {
sink.write(&format!("line {i}\n"));
}
sink.attach(file);
let text = read(&path);
assert_eq!(text.lines().count(), MAX_PENDING);
assert!(!text.contains("dropped"), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn without_a_file_nothing_is_kept_in_memory() {
let mut sink = Sink::new(MAX_FILE_BYTES);
sink.write("early\n");
sink.no_file();
sink.write("late\n");
assert!(sink.pending.is_empty() && sink.dropped == 0);
}
#[test]
fn the_file_stops_at_its_size_cap_with_one_note() {
let dir = temp_dir("cap");
let (path, file) = rotate(&dir).expect("rotate");
let mut sink = Sink::new(100);
sink.attach(file);
for i in 0..50 {
sink.write(&format!("line {i:02} with some padding\n"));
}
let text = read(&path);
assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), 3, "{text}");
assert_eq!(text.matches("log file reached").count(), 1, "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn the_logger_filters_records_and_writes_them_to_the_attached_file() {
use log::Log;
let dir = temp_dir("logger");
let logger = AppLogger::new(Filter::parse(DEFAULT_FILTER), false);
record(&logger, log::Level::Info, "lightcraft", "before the settings directory");
record(&logger, log::Level::Info, "wgpu_core::device", "too chatty");
let path = logger.attach_dir(&dir).expect("attach");
assert_eq!(path, dir.join(LOG_FILE));
record(&logger, log::Level::Warn, "wgpu_hal::vulkan", "a real warning");
record(&logger, log::Level::Error, "lightcraft_engine::guard", "`develop.reset` failed unexpectedly: boom");
record(&logger, log::Level::Debug, "lightcraft", "below info");
let text = read(&path);
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 3, "{text}");
assert!(lines[0].contains(" INFO [") && lines[0].ends_with("lightcraft: before the settings directory"), "{text}");
assert!(lines[1].ends_with("wgpu_hal::vulkan: a real warning"), "{text}");
assert!(lines[2].contains(" ERROR [") && lines[2].ends_with("lightcraft_engine::guard: `develop.reset` failed unexpectedly: boom"), "{text}");
assert!(logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("lightcraft_ui_egui").build()));
assert!(!logger.enabled(&log::Metadata::builder().level(log::Level::Info).target("naga").build()));
// Attaching again rotates: the first log becomes `.1`.
logger.attach_dir(&dir).expect("attach again");
assert_eq!(read(&dir.join("lightcraft.1.log")), text);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn records_from_many_threads_are_whole_lines() {
let dir = temp_dir("threads");
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
let path = logger.attach_dir(&dir).expect("attach");
let workers: Vec<_> = (0..8)
.map(|t| {
let l = std::sync::Arc::clone(&logger);
std::thread::spawn(move || {
for i in 0..100 {
record(&l, log::Level::Info, "lightcraft", &format!("thread {t} record {i}"));
}
})
})
.collect();
for w in workers {
w.join().expect("worker");
}
let text = read(&path);
assert_eq!(text.lines().count(), 800);
assert!(text.lines().all(|l| l.contains(" lightcraft: thread ")), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn attaching_to_an_unusable_directory_reports_an_error_and_keeps_logging() {
let dir = temp_dir("unusable");
std::fs::create_dir_all(dir.parent().expect("parent")).expect("tmp");
std::fs::write(&dir, "not a directory").expect("block");
let logger = AppLogger::new(Filter::parse("info"), false);
record(&logger, log::Level::Info, "lightcraft", "early");
assert!(logger.attach_dir(&dir).is_err());
record(&logger, log::Level::Error, "x", "still fine");
// Nothing waits in memory for a file that won't come.
assert!(logger.sink.lock().expect("sink").pending.is_empty());
let _ = std::fs::remove_file(&dir);
}
#[test]
fn a_poisoned_sink_still_logs() {
let dir = temp_dir("poison");
let logger = std::sync::Arc::new(AppLogger::new(Filter::parse("info"), false));
let l = std::sync::Arc::clone(&logger);
let _ = std::thread::spawn(move || {
let _guard = l.sink.lock().expect("lock");
panic!("poison the sink");
})
.join();
assert!(logger.sink.is_poisoned());
let path = logger.attach_dir(&dir).expect("attach");
record(&logger, log::Level::Warn, "lightcraft", "after the poison");
assert!(read(&path).contains("lightcraft: after the poison"));
let _ = std::fs::remove_dir_all(&dir);
}
/// The panic hook's report lands in the file, and never deadlocks when the panic happened
/// while this thread held the sink.
#[test]
fn a_panic_report_goes_to_the_file_and_never_deadlocks() {
let dir = temp_dir("panic");
let logger = AppLogger::new(Filter::parse("off"), false);
let path = logger.attach_dir(&dir).expect("attach");
logger.record_panic("render", "panicked at crates/x/src/lib.rs:3:5:\nboom");
{
let _held = logger.sink.lock().expect("lock");
logger.record_panic("main", "while the sink is held");
}
let text = read(&path);
assert!(text.contains(" ERROR [render] lightcraft: panicked at crates/x/src/lib.rs:3:5:\nboom\n"), "{text}");
assert!(!text.contains("while the sink is held"), "{text}");
let _ = std::fs::remove_dir_all(&dir);
}
File diff suppressed because it is too large. Load diff
+49 -77
View File
@@ -11,12 +11,19 @@
//! - while a text field has keyboard focus, accelerators without ⌘ (`G`, `1`, `Delete`…) and the
//! text-editing ones (⌘A/⌘C/⌘V/⌘X/⌘Z) are removed, so typing and text editing work; they come
//! back when the field loses focus.
//!
//! Menu events never pass through the egui shortcut handler. [`NativeMenu::update`] therefore runs
//! every queued command through [`lightcraft_ui_egui::menubar::run_native_command`]: while the
//! blocking library window or a quit/settings notice owns input it drops the command (Settings…
//! and About included), and only Quit stays available for the host's existing confirmation.
use std::collections::{HashMap, HashSet};
use std::sync::mpsc::{Receiver, channel};
use lightcraft_ui_egui::LightcraftApp;
use lightcraft_ui_egui::menubar::{MenuNode, menu_bar};
use lightcraft_ui_egui::menubar::{
MenuNode, menu_bar, native_item_presentation, native_menu_delivers as menu_delivers, native_menu_structure as structure_of,
};
use muda::accelerator::{Accelerator, Code, Modifiers};
use muda::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem, Submenu};
use serde_json::Value;
@@ -57,8 +64,10 @@ struct Item {
}
impl Item {
/// The row's text as installed: `label` is already what the row shows (translated, with a
/// borrowed key's hint, `native_item_presentation`).
fn native_label(&self) -> String {
lightcraft_ui_egui::menubar::display_item_label(&self.cmd, &self.params, &self.label).replace('&', "&&")
self.label.replace('&', "&&")
}
/// Puts `want` on the native item. muda's `set_accelerator(None)` does nothing on macOS (the
@@ -276,13 +285,6 @@ fn yields_to_text(sc: &str) -> bool {
!sc.contains("Cmd") && !sc.contains("Ctrl") || TEXT_EDIT.contains(&sc)
}
/// Whether AppKit hands this shortcut to the menu bar: only key presses with ⌘ or ⌃, and function
/// keys. A plain `C` or `⇧P` never reaches it (the window's view takes the key), so egui has to run
/// those even though their menu item shows the key.
fn menu_delivers(sc: &str) -> bool {
sc.split('+').any(|part| matches!(part, "Cmd" | "Ctrl") || part.strip_prefix('F').is_some_and(|n| n.parse::<u8>().is_ok()))
}
/// The shortcuts the menu bar runs itself, for `LightcraftApp::native_shortcuts`.
fn owned_by_menu<'a>(installed: impl Iterator<Item = &'a str>, text_focus: bool) -> HashSet<String> {
installed.filter(|sc| menu_delivers(sc) && !(text_focus && yields_to_text(sc))).map(str::to_string).collect()
@@ -293,34 +295,6 @@ fn label_text(s: &str) -> String {
lightcraft_ui_egui::i18n::tr(s).replace('&', "&&")
}
fn structure_of(bar: &[(String, Vec<MenuNode>)]) -> String {
fn walk(n: &[MenuNode], out: &mut String) {
for x in n {
match x {
MenuNode::Item { id, params, checked, shortcut, .. } => {
out.push_str(&MenuNode::key(id, params));
out.push(if checked.is_some() { 'c' } else { 'i' });
out.push_str(shortcut.as_deref().unwrap_or(""));
}
MenuNode::Separator => out.push('-'),
MenuNode::Submenu { label, children } => {
out.push('[');
out.push_str(label);
walk(children, out);
out.push(']');
}
}
out.push(';');
}
}
let mut s = format!("{};", lightcraft_ui_egui::i18n::language().code());
for (t, items) in bar {
s.push_str(t);
walk(items, &mut s);
}
s
}
/// Drop a trailing separator (left behind when an item moved to the app menu).
fn tidy_separators(mut nodes: Vec<MenuNode>) -> Vec<MenuNode> {
while matches!(nodes.last(), Some(MenuNode::Separator)) {
@@ -353,9 +327,10 @@ impl NativeMenu {
m
}
/// Recreate native handles and shortcut ownership from the current shared menu model.
fn rebuild(&mut self, app: &mut LightcraftApp) {
let bar = menu_bar(app);
self.structure = structure_of(&bar);
self.structure = structure_of(&bar, &app.ui.settings.keymap);
self.menu = Menu::new();
self.items.clear();
self.app_items.clear();
@@ -389,7 +364,7 @@ impl NativeMenu {
shortcut: Some(shortcut.to_string()),
accel,
current: accel,
label: text.to_string(),
label: lightcraft_ui_egui::menubar::display_item_label(cmd, &Value::Null, text).to_string(),
enabled: true,
checked: None,
});
@@ -414,7 +389,7 @@ impl NativeMenu {
let nodes = tidy_separators(nodes);
// Swapping an item in the Help menu leaves the old row in place and adds a second one
// (measured on macOS 27 with muda 0.21): the Help menu is not addressed row for row.
self.append_nodes(&sub, &nodes, title != "Help");
self.append_nodes(&sub, &nodes, &app.ui.settings.keymap, title != "Help");
if title == "File" {
// ⌘W, the system's own item
let _ = sub.append_items(&[
@@ -441,8 +416,9 @@ impl NativeMenu {
self.publish_shortcuts(app);
}
/// Install translated rows with their effective accelerators, preserving hint-only keys.
/// `swappable`: whether its items may be replaced to drop their key (see `Item::swappable`).
fn append_nodes(&mut self, sub: &Submenu, nodes: &[MenuNode], swappable: bool) {
fn append_nodes(&mut self, sub: &Submenu, nodes: &[MenuNode], keymap: &lightcraft_ui_egui::shortcuts::Keymap, swappable: bool) {
for n in nodes {
match n {
MenuNode::Separator => {
@@ -450,7 +426,7 @@ impl NativeMenu {
}
MenuNode::Submenu { label, children } => {
let s = Submenu::new(label_text(label), true);
self.append_nodes(&s, children, swappable);
self.append_nodes(&s, children, keymap, swappable);
let _ = sub.append(&s);
}
MenuNode::Item { id, params, label, shortcut, enabled, checked } => {
@@ -458,26 +434,16 @@ impl NativeMenu {
if self.items.contains_key(&key) {
continue; // muda ids must be unique
}
let accel = shortcut.as_deref().filter(|s| !CONTEXTUAL.contains(s)).and_then(accelerator);
let (native_label, native_key) = native_item_presentation(keymap, id, params, label, shortcut.as_deref());
let accel = native_key.filter(|s| !CONTEXTUAL.contains(s)).and_then(accelerator);
let handle = match checked {
Some(c) => {
let it = CheckMenuItem::with_id(
key.clone(),
lightcraft_ui_egui::menubar::display_item_label(id, params, label).replace('&', "&&"),
*enabled,
*c,
accel,
);
let it = CheckMenuItem::with_id(key.clone(), native_label.replace('&', "&&"), *enabled, *c, accel);
let _ = sub.append(&it);
Handle::Check(it)
}
None => {
let it = MenuItem::with_id(
key.clone(),
lightcraft_ui_egui::menubar::display_item_label(id, params, label).replace('&', "&&"),
*enabled,
accel,
);
let it = MenuItem::with_id(key.clone(), native_label.replace('&', "&&"), *enabled, accel);
let _ = sub.append(&it);
Handle::Plain(it)
}
@@ -493,7 +459,7 @@ impl NativeMenu {
shortcut: shortcut.clone(),
accel,
current: accel,
label: label.clone(),
label: native_label,
enabled: *enabled,
checked: *checked,
},
@@ -519,37 +485,43 @@ impl NativeMenu {
lightcraft_ui_egui::i18n::set_language(app.ui.language);
let mut quit = false;
while let Ok(key) = self.rx.try_recv() {
if key == QUIT {
// Resolve the native id to its command, then let the shared policy decide. Native menu
// events never reach `shortcuts::handle`, so this is the one guard for AppKit's
// accelerators and clicks: while the blocking library window or a quit/settings notice
// owns input, a queued command is dropped (Quit stays for the existing confirmation).
let (cmd, params) = if key == QUIT {
(key, serde_json::json!({}))
} else if key == "app.about" || key == SETTINGS {
(key, serde_json::json!({}))
} else if let Some(it) = self.items.get(&key) {
(it.cmd.clone(), it.params.clone())
} else {
continue;
};
if lightcraft_ui_egui::menubar::run_native_command(app, &cmd, params) == lightcraft_ui_egui::menubar::NativeCommand::Quit {
quit = true;
continue;
}
if key == "app.about" || key == SETTINGS {
let _ = app.run(&key, serde_json::json!({}));
continue;
}
if let Some(it) = self.items.get(&key) {
let (cmd, params) = (it.cmd.clone(), it.params.clone());
let _ = lightcraft_ui_egui::menubar::run_item(app, &cmd, params);
}
}
let bar = menu_bar(app);
if structure_of(&bar) != self.structure {
if structure_of(&bar, &app.ui.settings.keymap) != self.structure {
// (no early return: a rebuild installs every accelerator and resets the state they were synced
// to, so the sync below runs in this same frame and no key reaches the menu in between)
self.rebuild(app);
}
fn walk(nodes: &[MenuNode], items: &mut HashMap<String, Item>) {
/// Synchronize live labels and states; accelerator ownership changes already triggered a rebuild.
fn walk(nodes: &[MenuNode], items: &mut HashMap<String, Item>, keymap: &lightcraft_ui_egui::shortcuts::Keymap) {
for n in nodes {
match n {
MenuNode::Submenu { children, .. } => walk(children, items),
MenuNode::Item { id, params, label, enabled, checked, .. } => {
MenuNode::Submenu { children, .. } => walk(children, items, keymap),
MenuNode::Item { id, params, label, shortcut, enabled, checked } => {
let Some(it) = items.get_mut(&MenuNode::key(id, params)) else { continue };
if it.label != *label {
let (native_label, _) = native_item_presentation(keymap, id, params, label, shortcut.as_deref());
if it.label != native_label {
match &it.handle {
Handle::Plain(h) => h.set_text(lightcraft_ui_egui::menubar::display_item_label(id, params, label).replace('&', "&&")),
Handle::Check(h) => h.set_text(lightcraft_ui_egui::menubar::display_item_label(id, params, label).replace('&', "&&")),
Handle::Plain(h) => h.set_text(native_label.replace('&', "&&")),
Handle::Check(h) => h.set_text(native_label.replace('&', "&&")),
}
it.label = label.clone();
it.label = native_label;
}
if it.enabled != *enabled {
match &it.handle {
@@ -570,7 +542,7 @@ impl NativeMenu {
}
}
}
walk(&bar.iter().flat_map(|(_, v)| v.clone()).collect::<Vec<_>>(), &mut self.items);
walk(&bar.iter().flat_map(|(_, v)| v.clone()).collect::<Vec<_>>(), &mut self.items, &app.ui.settings.keymap);
let focus = ctx.egui_wants_keyboard_input();
let capturing = app.recording_shortcut.is_some();
@@ -610,7 +582,7 @@ mod tests {
let mut seen = std::collections::BTreeSet::new();
for language in Locale::ALL {
set_language(*language);
assert!(seen.insert(structure_of(&bar)), "{language:?} shares another language's menu structure key");
assert!(seen.insert(structure_of(&bar, &app.ui.settings.keymap)), "{language:?} shares another language's menu structure key");
}
set_language(Locale::En);
}
+57
View File
@@ -0,0 +1,57 @@
/// The Windows command that opens `url` in the default browser. `explorer <url>` opened File
/// Explorer instead for links with a query or fragment, like the Map button's OpenStreetMap link
/// (issue #234). The URL protocol handler hands the URL to the browser as is; no shell runs, so
/// `?`, `&` and `#` need no escaping.
pub(crate) fn windows_open_url_command(url: &str) -> std::process::Command {
let mut c = std::process::Command::new("rundll32");
c.args(["url.dll,FileProtocolHandler", url]);
c
}
/// Explorer's `/select,<path>` switch (issue #272). Explorer parses its own command line and only
/// selects the file when the path after the comma is quoted (`/select,"C:\My Photos\a.jpg"`),
/// spelled with backslashes and free of the verbatim prefix (`\\?\`, `\\?\UNC\`) that
/// `canonicalize` adds; given anything else it opens Documents. Windows file names can't contain
/// `"`; a path that does anyway (a hostile catalog) has them dropped, so the raw command line
/// always holds exactly this one argument.
pub(crate) fn explorer_select_arg(path: &str) -> String {
let path = path.replace('/', "\\").replace('"', "");
let path = match path.strip_prefix(r"\\?\UNC\") {
Some(unc) => format!(r"\\{unc}"),
None => path.strip_prefix(r"\\?\").unwrap_or(path.as_str()).to_string(),
};
format!("/select,\"{path}\"")
}
/// `explorer /select,"<path>"`. Rust's own argument quoting wraps the whole switch in quotes
/// (`"/select,C:\My Photos\a.jpg"`) whenever the path has a space, which Explorer doesn't
/// recognise, so on Windows the switch goes on the command line exactly as built.
pub(crate) fn explorer_select_command(path: &str) -> std::process::Command {
let mut c = std::process::Command::new("explorer");
let arg = explorer_select_arg(path);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
c.raw_arg(arg);
}
#[cfg(not(windows))]
{
c.arg(arg);
}
c
}
/// The file dialogs' parent, set once the window exists (`services`). A dialog with a parent is
/// a child of the app's window; without one, the xdg-desktop-portal picker on Wayland is a stray
/// top-level ("Failed to associate portal window with parent window" in the portal's log): a
/// tiling compositor puts it beside the app, and a fullscreen window hides it entirely, so
/// Import Photos… looks like a hang. rfd exports the Wayland surface through xdg_foreign itself;
/// `FileDialog` is `Clone` and `Send`, so one parented template serves every picker, including
/// the one on its own thread (#191). Only set on Linux and FreeBSD: on macOS a parented dialog
/// becomes a sheet and on Windows a modal, a behaviour change this does not make.
pub(crate) static DIALOG_PARENT: std::sync::OnceLock<rfd::FileDialog> = std::sync::OnceLock::new();
/// A file dialog owned by the app's window, or a plain one before the window exists.
pub(crate) fn file_dialog() -> rfd::FileDialog {
DIALOG_PARENT.get().cloned().unwrap_or_default()
}
+245
View File
@@ -0,0 +1,245 @@
use super::{LibraryProblem, LightcraftApp, UiState};
/// Where the system keeps monitor profiles, for the Choose Profile dialog to start in: the user's
/// own profiles first (Linux: colord / DisplayCAL; macOS: ColorSync), then the system's.
pub(crate) fn display_profile_dir() -> Option<std::path::PathBuf> {
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).filter(|h| !h.is_empty()).map(std::path::PathBuf::from);
let user = |rel: &str| home.as_ref().map(|h| h.join(rel));
let candidates: Vec<Option<std::path::PathBuf>> = if cfg!(target_os = "macos") {
vec![user("Library/ColorSync/Profiles"), Some("/Library/ColorSync/Profiles".into())]
} else if cfg!(windows) {
let root = std::env::var_os("SystemRoot").map(std::path::PathBuf::from).unwrap_or_else(|| "C:\\Windows".into());
vec![Some(root.join("System32").join("spool").join("drivers").join("color"))]
} else {
let data = std::env::var_os("XDG_DATA_HOME").filter(|d| !d.is_empty()).map(std::path::PathBuf::from).or_else(|| user(".local/share"));
vec![data.map(|d| d.join("icc")), user(".color/icc"), Some("/usr/share/color/icc".into())]
};
candidates.into_iter().flatten().find(|d| d.is_dir())
}
pub(crate) fn config_dir() -> Option<std::path::PathBuf> {
lightcraft_engine::config::config_dir()
}
/// The window at the size it was last used at, zoomed if it was (`window`), or at the usual size
/// when nothing is remembered. A zoomed window is given the size it goes back to. Where it
/// opens is the system's to say.
pub(crate) fn as_remembered(builder: egui::ViewportBuilder, window: Option<lightcraft_ui_egui::window_place::WindowPlace>) -> egui::ViewportBuilder {
let builder = builder.with_inner_size(window.map_or(lightcraft_ui_egui::window_place::DEFAULT_SIZE, |w| w.size));
// (only ever asked to zoom: asked not to, macOS un-zooms a window whose size fills the screen
// to a size of its own choosing)
if window.is_some_and(|w| w.zoomed) { builder.with_maximized(true) } else { builder }
}
/// `<config>/ui.json`, the saved UI state and app settings — `None` when nothing is read or
/// written: `LIGHTCRAFT_NO_PREFS` (tests, scripts) or no home folder.
pub(crate) fn prefs_path() -> Option<std::path::PathBuf> {
if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() {
return None;
}
config_dir().map(|d| d.join("ui.json"))
}
/// The saved UI state and app settings (`<config>/ui.json`), if any, and a warning for the user
/// when the file exists but can't be used (issue #103): a damaged file is kept as
/// `ui.json.corrupt-<unix time>` first, so the next save can't lose the library location in it;
/// one that can't be read at all is not written this session (`keep_file`).
///
/// A `--memory` session reads the settings (so it looks like the user's app) but writes nothing
/// (issue #164), so a damaged file is left as it is there, not set aside.
pub(crate) fn load_prefs(in_memory: bool) -> (Option<UiState>, Option<String>, bool) {
let Some(path) = prefs_path() else { return (None, None, false) };
load_prefs_at(&path, !in_memory)
}
/// Compatibility recovery is limited to persisted docking, not runtime UiState commands. An
/// arrangement from an older docking version starts again from the default without a warning.
fn decode_saved_ui(bytes: &[u8]) -> Result<(UiState, bool), String> {
let mut saved: serde_json::Value = serde_json::from_slice(bytes).map_err(|error| error.to_string())?;
let fields = saved.as_object_mut().ok_or("settings must be an object")?;
lightcraft_ui_egui::docking::drop_outdated(fields);
let recovered =
fields.get("docking").is_some_and(|value| match serde_json::from_value::<Option<lightcraft_ui_egui::docking::Workspace>>(value.clone()) {
Ok(Some(workspace)) => lightcraft_ui_egui::docking::validate(&workspace).is_err(),
Ok(None) => false,
Err(_) => true,
});
if recovered {
fields.remove("docking");
}
let ui = serde_json::from_value(saved).map_err(|error| error.to_string())?;
Ok((ui, recovered))
}
pub(crate) fn load_prefs_at(path: &std::path::Path, set_aside_damaged: bool) -> (Option<UiState>, Option<String>, bool) {
let bytes = match std::fs::read(path) {
Ok(b) => b,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (None, None, false),
Err(e) => {
let msg = format!("The app settings ({}) couldn't be read: {e}. Defaults are used, and the file isn't overwritten.", path.display());
return (None, Some(msg), true);
}
};
match decode_saved_ui(&bytes) {
Ok((ui, false)) => (Some(ui.sanitized()), None, false),
Ok((ui, true)) => {
let msg = format!(
"The saved panel layout in {} couldn't be restored. Other settings were loaded; the original file is preserved and settings won't be saved this session.",
path.display()
);
(Some(ui.sanitized()), Some(msg), true)
}
Err(e) if !set_aside_damaged => {
let msg = format!("The app settings ({}) are damaged ({e}). Defaults are used; nothing is saved in this session.", path.display());
(None, Some(msg), true)
}
Err(e) => {
let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
let keep = path.with_file_name(format!("ui.json.corrupt-{secs}"));
let kept = std::fs::rename(path, &keep);
let what = match &kept {
Ok(()) => format!("it was kept as {}", keep.display()),
Err(r) => format!("it couldn't be set aside ({r})"),
};
let msg = format!(
"The app settings ({}) are damaged ({e}); {what}. Defaults are used — reopen your library with Settings → Open Library… if it isn't shown.",
path.display()
);
(None, Some(msg), kept.is_err())
}
}
}
/// Write `bytes` to `path` atomically: a temp file, fsynced, renamed over it (a crash or a full
/// disk leaves the old file or the new one, never a truncated one).
pub(crate) fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write;
let tmp = path.with_extension("json.tmp");
let written = (|| {
let mut f = std::fs::File::create(&tmp)?;
f.write_all(bytes)?;
f.sync_all()
})();
if let Err(e) = written {
let _ = std::fs::remove_file(&tmp);
return Err(e);
}
std::fs::rename(&tmp, path)?;
if let Some(dir) = path.parent()
&& let Ok(d) = std::fs::File::open(dir)
{
let _ = d.sync_all();
}
Ok(())
}
/// Saves `ui.json` (app settings, incl. the library to open at launch): as soon as the library
/// changes, every few seconds when anything else changed, and at exit.
///
/// Nothing is written while the session is one that promises to save nothing: `--memory`
/// (`path` is `None`; issue #164), or the one running because the library couldn't be opened — the
/// question window and Continue Without Saving (issue #100; `app.openLibrary` ends it, and the
/// library it opened is saved then).
#[derive(Default)]
pub(crate) struct PrefsWriter {
/// Where to write; `None` writes nothing (`--memory`, `LIGHTCRAFT_NO_PREFS`, no home folder).
pub(crate) path: Option<std::path::PathBuf>,
pub(crate) written: Vec<u8>,
pub(crate) library: String,
pub(crate) checked: f64,
/// The last write failed (reported once until a write works).
pub(crate) failing: bool,
/// `ui.json` couldn't be read at launch: never overwrite it this session.
pub(crate) keep_file: bool,
/// Follows the window, to remember the size it rests at (`UiState::window`).
pub(crate) window: lightcraft_ui_egui::window_place::WindowWatch,
/// When the window was first looked at: its watch goes by the clock from then on, not by
/// the interface's time, which stands still while the window is hidden.
pub(crate) window_since: Option<std::time::Instant>,
}
impl PrefsWriter {
pub(crate) fn save(&mut self, app: &LightcraftApp) -> Result<(), String> {
self.save_ui(&app.ui, app.library_problem.as_ref().is_some_and(LibraryProblem::saves_nothing))
}
/// Write `ui` if it changed since the last write; `temporary` (the library couldn't be
/// opened) saves nothing.
pub(crate) fn save_ui(&mut self, ui: &UiState, temporary: bool) -> Result<(), String> {
if self.keep_file || temporary {
return Ok(());
}
let Some(path) = self.path.clone() else { return Ok(()) };
if let Some(workspace) = &ui.docking {
lightcraft_ui_egui::docking::validate(workspace)?;
}
let bytes = serde_json::to_vec_pretty(ui).map_err(|e| e.to_string())?;
if bytes == self.written {
return Ok(());
}
path.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| write_atomic(&path, &bytes))
.map_err(|e| format!("saving the app settings failed: {e}"))?;
self.written = bytes;
self.library = ui.settings.library_path.clone();
Ok(())
}
/// What to remember of the window as the app quits ([`WindowWatch::at_exit`]).
///
/// [`WindowWatch::at_exit`]: lightcraft_ui_egui::window_place::WindowWatch::at_exit
pub(crate) fn window_at_exit(
&mut self,
remembered: Option<lightcraft_ui_egui::window_place::WindowPlace>,
) -> Option<lightcraft_ui_egui::window_place::WindowPlace> {
match self.window_since {
Some(since) => self.window.at_exit(remembered, since.elapsed().as_secs_f64()),
None => remembered,
}
}
/// Per-frame host tick: records the window's placement while visible, asks for a repaint when
/// a remembered size is due, and saves settings/library at most every three seconds or
/// immediately after the library path changes; a failed save is reported once and retried.
pub(crate) fn tick(&mut self, app: &mut LightcraftApp, ctx: &egui::Context) {
// (asked for before the input is read: the context is not asked from inside its own lock)
let zoom = ctx.zoom_factor();
// The monotonic app clock: `i.time` stands still while the window is hidden.
let now = app.tick_now();
let (hidden, seen) = ctx.input(|i| {
let hidden = i.viewport().visible() == Some(false);
(hidden, lightcraft_ui_egui::window_place::Seen::of(i.viewport(), i.content_rect(), zoom))
});
// how the window is, to open like that next time (written with the settings below). What
// the settings hold is checked first: a script may have set it (`ui.set`). A hidden
// `run_logic` pass has no fresh content rect: keep the last known placement.
let remembered = app.ui.window.and_then(lightcraft_ui_egui::window_place::WindowPlace::checked);
let at = self.window_since.get_or_insert_with(std::time::Instant::now).elapsed().as_secs_f64();
if !hidden {
app.ui.window = self.window.note(remembered, &seen, at);
}
if let Some(wait) = self.window.waits(at) {
// (a size is only remembered once the window has rested at it: look again then, though
// nothing else asks for a frame)
ctx.request_repaint_after(wait);
}
let moved = app.ui.settings.library_path != self.library;
if !moved && now - self.checked < 3.0 {
return;
}
self.checked = now;
match self.save(app) {
Ok(()) => self.failing = false,
Err(e) => {
if !self.failing {
log::warn!("{e}");
app.notices.push(format!("{e}. LightCraft keeps trying."));
}
self.failing = true;
// don't retry every frame
self.library = app.ui.settings.library_path.clone();
}
}
}
}
+298
View File
@@ -0,0 +1,298 @@
#[cfg(any(target_os = "freebsd", target_os = "linux"))]
use super::platform::DIALOG_PARENT;
use super::platform::{explorer_select_command, file_dialog, windows_open_url_command};
use super::prefs::display_profile_dir;
use super::*;
/// The platform services; `cc` is the window the file dialogs belong to (its `egui_ctx` repaints
/// when a dialog closes), and `log_file` is for Help ▸ Open Log Folder.
pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std::path::Path>) -> Services {
let ctx = cc.egui_ctx.clone();
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
let _ = DIALOG_PARENT.set(rfd::FileDialog::new().set_parent(cc));
Services {
local_places: None,
// Commands' file dialogs run on their own thread (#191): a dialog on the UI thread
// stopped the window answering the compositor, which then reported the app as hung.
picker: Some(Box::new(move |req: lightcraft_ui_egui::pick::PickRequest| {
use lightcraft_ui_egui::pick::PickKind;
let (tx, rx) = std::sync::mpsc::channel();
let repaint = ctx.clone();
std::thread::Builder::new()
.name("file-dialog".into())
.spawn(move || {
let mut d = file_dialog();
if let Some(t) = &req.title {
d = d.set_title(t);
}
if let Some((name, exts)) = &req.filter {
d = d.add_filter_nocase(name.clone(), exts);
}
if let Some(n) = &req.file_name {
d = d.set_file_name(n);
}
let s = |p: std::path::PathBuf| p.to_string_lossy().to_string();
let paths: Vec<String> = match req.kind {
PickKind::Files => d.pick_files().unwrap_or_default().into_iter().map(s).collect(),
PickKind::File => d.pick_file().map(s).into_iter().collect(),
PickKind::Folder => d.pick_folder().map(s).into_iter().collect(),
PickKind::Save => d.save_file().map(s).into_iter().collect(),
};
// the app may have quit meanwhile: nobody to tell
let _ = tx.send(paths);
repaint.request_repaint();
})
.map_err(|e| format!("could not start the file dialog: {e}"))?;
Ok(rx)
})),
log_file: log_file.map(|p| p.display().to_string()),
pick_lightroom_catalog: Some(Box::new(|| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Import Lightroom Catalog"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Lightroom Classic Catalog"), &["lrcat"])
.pick_file()
.map(|p| p.to_string_lossy().to_string())
})),
pick_folder: Some(Box::new(|| {
file_dialog().set_title(lightcraft_ui_egui::i18n::tr("Open Library")).pick_folder().map(|p| p.to_string_lossy().to_string())
})),
#[cfg(target_os = "linux")]
open_model_folder: Some(std::sync::Arc::new(|path: &str| {
std::process::Command::new("xdg-open")
.arg(path)
.status()
.map_err(|e| e.to_string())
.and_then(|s| if s.success() { Ok(()) } else { Err(format!("opening folder failed: {s}")) })
})),
open_with: Some(Box::new(editors::open_with)),
open_all_with: Some(Box::new(editors::open_all_with)),
check_editor: Some(Box::new(editors::check)),
open_url: Some(Box::new(|url: &str| {
if !url.starts_with("https://") {
return Err("only https links are opened".into());
}
let status = if cfg!(target_os = "macos") {
std::process::Command::new("open").arg(url).status()
} else if cfg!(target_os = "windows") {
windows_open_url_command(url).status()
} else {
std::process::Command::new("xdg-open").arg(url).status()
};
status.map(|_| ()).map_err(|e| e.to_string())
})),
reveal: Some(Box::new(|path: &str| {
let status = if cfg!(target_os = "macos") {
std::process::Command::new("open").args(["-R", path]).status()
} else if cfg!(target_os = "windows") {
explorer_select_command(path).status()
} else {
let dir = std::path::Path::new(path).parent().map(|d| d.to_string_lossy().to_string()).unwrap_or_else(|| ".".into());
std::process::Command::new("xdg-open").arg(dir).status()
};
status
.map_err(|e| e.to_string())
.and_then(|s| if s.success() || cfg!(target_os = "windows") { Ok(()) } else { Err(format!("reveal failed: {s}")) })
})),
pick_files: Some(Box::new(|| {
file_dialog()
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Photos"), lightcraft_engine::import::EXTENSIONS)
.pick_files()
.unwrap_or_default()
.into_iter()
.map(|p| p.to_string_lossy().to_string())
.collect()
})),
pick_denoise_model: Some(Box::new(|| {
file_dialog()
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("ONNX model"), &["onnx"])
.pick_file()
.map(|p| vec![p.to_string_lossy().into_owned()])
.unwrap_or_default()
})),
pick_preset_files: Some(Box::new(|| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Import Presets"))
.add_filter_nocase(
lightcraft_ui_egui::i18n::tr("Presets & Profiles"),
&["lcpreset", "xmp", "lrtemplate", "zip", "dng", "lmp", "mplumpack", "cube"],
)
.pick_files()
.unwrap_or_default()
.into_iter()
.map(|p| p.to_string_lossy().to_string())
.collect()
})),
pick_model_file: Some(Box::new(|| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Add a Face Recognition Model"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Face models (ONNX)"), &["onnx"])
.pick_file()
.map(|p| vec![p.to_string_lossy().to_string()])
.unwrap_or_default()
})),
pick_tracklog: Some(Box::new(|| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Auto-Tag from Tracklog"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("GPS Track Log"), &["gpx"])
.pick_file()
.map(|p| vec![p.to_string_lossy().to_string()])
.unwrap_or_default()
})),
// macOS doesn't colour-manage the window: previews follow the screen's profile (#787)
#[cfg(target_os = "macos")]
screen_profile: Some(Box::new(screen_profile::icc)),
// Linux: the profile the desktop assigns in colord, read off the UI thread
#[cfg(target_os = "linux")]
screen_profile: Some(colord::service()),
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
screen_profile: None,
pick_display_profile: Some(Box::new(|| {
let mut d = file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Choose Monitor Profile"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("ICC Profiles"), &["icc", "icm"]);
if let Some(dir) = display_profile_dir() {
d = d.set_directory(dir);
}
d.pick_file().map(|p| vec![p.to_string_lossy().to_string()]).unwrap_or_default()
})),
save_preset_file: Some(Box::new(|name: &str| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Export Presets"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("LightCraft Preset"), &["lcpreset"])
.set_file_name(name)
.save_file()
.map(|p| p.to_string_lossy().to_string())
})),
pick_keyword_list: Some(Box::new(|| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Import Keywords"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Keyword Lists"), &["txt", "utf8"])
.pick_file()
.map(|p| vec![p.to_string_lossy().to_string()])
.unwrap_or_default()
})),
save_keyword_list: Some(Box::new(|name: &str| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Export Keywords"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Keyword Lists"), &["txt"])
.set_file_name(name)
.save_file()
.map(|p| p.to_string_lossy().to_string())
})),
pick_curve_preset_files: Some(Box::new(|| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Import Point Curve Presets"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Point Curve Presets"), &["lccurve", "json"])
.pick_files()
.unwrap_or_default()
.into_iter()
.map(|p| p.to_string_lossy().to_string())
.collect()
})),
save_curve_preset_file: Some(Box::new(|name: &str| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Export Point Curve Presets"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Point Curve Presets"), &["lccurve"])
.set_file_name(name)
.save_file()
.map(|p| p.to_string_lossy().to_string())
})),
pick_slideshow_templates: Some(Box::new(|| {
rfd::FileDialog::new()
.set_title(lightcraft_ui_egui::i18n::tr("Import Slideshow Templates"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Slideshow Templates"), &["json"])
.pick_files()
.unwrap_or_default()
.into_iter()
.map(|p| p.to_string_lossy().to_string())
.collect()
})),
save_slideshow_template: Some(Box::new(|name: &str| {
rfd::FileDialog::new()
.set_title(lightcraft_ui_egui::i18n::tr("Export Slideshow Template"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Slideshow Templates"), &["json"])
.set_file_name(name)
.save_file()
.map(|p| p.to_string_lossy().to_string())
})),
pick_print_templates: Some(Box::new(|| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Import Print Templates"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Print Templates"), &[lightcraft_engine::print::template::FILE_EXT])
.pick_files()
.unwrap_or_default()
.into_iter()
.map(|p| p.to_string_lossy().to_string())
.collect()
})),
save_print_template: Some(Box::new(|name: &str| {
file_dialog()
.set_title(lightcraft_ui_egui::i18n::tr("Export Print Template"))
.add_filter_nocase(lightcraft_ui_egui::i18n::tr("Print Templates"), &[lightcraft_engine::print::template::FILE_EXT])
.set_file_name(name)
.save_file()
.map(|p| p.to_string_lossy().to_string())
})),
// atomic (temp file + sync + rename): a failed write never leaves a truncated file
write_shared: Some(std::sync::Arc::new(lightcraft_engine::export::write_file)),
write: Some(Box::new(lightcraft_engine::export::write_file)),
write_new: Some(Box::new(lightcraft_engine::export::write_file_new)),
png: Some(Box::new(|img: &lightcraft_raster::Rgba8| {
lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(img), &lightcraft_codecs::EncodeMeta::default()).unwrap_or_default()
})),
// the library is a folder on disk: backed up with the user's other files
backup_library: None,
restore_library: None,
system_theme: appearance::service(),
}
}
/// The library session with the folders face models (`<config>/models`) and slideshow templates
/// (`<config>/slideshow-templates`) are kept in. With [`Launch::Ask`] no library is opened yet:
/// the window lists the recent ones.
pub(crate) fn open_session(in_memory: bool, launch: &Launch, seed_demo: bool) -> (Session, Option<LibraryProblem>) {
let (mut s, problem) = match launch {
Launch::Ask => (Session::new().with_fs().with_default_denoise_models().with_system_clock(), None),
Launch::Open { dir, .. } => open_library_session(in_memory, dir.clone(), seed_demo),
};
s.face_models_dir = lightcraft_engine::config::default_face_models_dir();
s.slide_templates_dir = lightcraft_engine::config::config_dir().map(|d| d.join(lightcraft_engine::slide_template::DIR_NAME));
// Control requests are answered on the UI thread: Add to Apple Photos must not wait there
s.apple_photos_background = true;
(s, problem)
}
/// The persistent library session, or with `--memory` an in-memory one (demo photos).
///
/// If the library can't be opened the session is empty and in memory — never seeded with the
/// demo photos, never written anywhere — and the problem is returned: the window then says so
/// and offers Try Again / Choose Another Library… / Continue Without Saving / Quit (issue #100).
fn open_library_session(in_memory: bool, dir: Option<std::path::PathBuf>, seed_demo: bool) -> (Session, Option<LibraryProblem>) {
if in_memory {
return (if seed_demo { Session::with_demo() } else { Session::new() }.with_fs().with_default_denoise_models().with_system_clock(), None);
}
let unopened = || Session::new().with_fs().with_default_denoise_models().with_system_clock();
let Some(dir) = dir else {
log::warn!("no library location (set --library or LIGHTCRAFT_LIBRARY)");
return (unopened(), Some(LibraryProblem::new("", "There is no home folder to keep the library in. Choose a folder for it.")));
};
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) {
Ok(r) => {
let (replayed, torn) = (r.replayed, r.torn_bytes);
log::info!(
"library {}: {} photos, {replayed} log records replayed{} ({:.1} ms)",
dir.display(),
s.catalog.len(),
if torn > 0 { ", torn tail repaired" } else { "" },
t0.elapsed().as_secs_f64() * 1000.0
);
(s, None)
}
Err(e) => {
log::error!("can't open library {}: {e}", dir.display());
(unopened(), Some(LibraryProblem::new(dir.to_string_lossy(), e.to_string())))
}
}
}
+464
View File
@@ -0,0 +1,464 @@
use super::*;
fn dir(tag: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("lc-app-prefs-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
/// Issue #374: launch arguments that would walk a whole drive or home folder are reported,
/// not imported; empty ones are ignored; the rest are imported as absolute paths.
#[test]
fn launch_arguments_never_walk_a_drive_or_the_home_folder() {
let home = dir("launch");
std::fs::create_dir_all(home.join("Trip")).unwrap();
let args: Vec<String> = ["", " ", ".", "Trip", &home.to_string_lossy()].iter().map(|s| s.to_string()).collect();
let (files, notices) = launch_imports_in(&args, Some(&home), Some(&home));
assert_eq!(files, [home.join("Trip").to_string_lossy().to_string()]);
assert_eq!(notices.len(), 2, "{notices:?}");
assert!(notices.iter().all(|n| n.contains("was not imported")), "{notices:?}");
// the working folder is a drive root (a launcher's choice): `.` is never the whole drive
let root = home.ancestors().last().unwrap().to_path_buf();
let (files, notices) = launch_imports_in(&[".".to_string()], Some(&root), None);
assert!(files.iter().all(|f| f.ends_with("DCIM")) && files.len() + notices.len() == 1, "{files:?} {notices:?}");
let _ = std::fs::remove_dir_all(&home);
}
/// Issue #236: the window answers control requests on its UI thread, so the desktop session
/// adds to Apple Photos on a worker (headless sessions wait instead).
#[test]
fn the_desktop_session_adds_to_apple_photos_in_the_background() {
let (s, problem) = open_session(true, &Launch::Open { dir: None, alt_asks: false }, false);
assert!(problem.is_none());
assert!(s.apple_photos_background);
assert!(!lightcraft_engine::Session::new().apple_photos_background);
}
/// Issue #1290: with Settings ▸ At launch ▸ Ask me nothing is opened (nor seeded with demo
/// photos) before the user chooses, and the settings are still saved while the list shows (a
/// removed entry is kept), unlike the failed-library window's temporary session.
#[test]
fn asking_at_launch_opens_nothing_and_still_saves_the_settings() {
let (s, problem) = open_session(false, &Launch::Ask, true);
assert!(problem.is_none() && s.library.is_none() && s.catalog.is_empty());
assert!(s.apple_photos_background, "the same desktop session as an opened one");
let d = dir("writer-ask");
let path = d.join("ui.json");
let mut app = LightcraftApp::new(s, Services::default());
app.ui.settings.recent_libraries = vec!["/gone/a".into(), "/gone/b".into()];
app.library_problem = Some(LibraryProblem::choose_later(&app.ui.settings));
let mut w = PrefsWriter { path: Some(path.clone()), ..Default::default() };
app.ui.settings.recent_libraries.remove(0);
w.save(&app).unwrap();
let saved: UiState = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(saved.settings.recent_libraries, ["/gone/b"]);
// the failed-library window still writes nothing
app.library_problem = Some(LibraryProblem::new("/gone/b", "not there"));
app.ui.settings.recent_libraries.clear();
w.save(&app).unwrap();
let saved: UiState = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(saved.settings.recent_libraries, ["/gone/b"]);
let _ = std::fs::remove_dir_all(&d);
}
/// Issue #103: a damaged ui.json (which holds the library location) is kept aside and
/// reported, not silently replaced by the defaults.
#[test]
fn damaged_ui_json_is_kept_and_reported() {
let d = dir("damaged");
let path = d.join("ui.json");
std::fs::write(&path, br#"{"settings": {"library_path": "/Volumes/Photos/Lib"#).unwrap();
let (ui, warning, keep) = load_prefs_at(&path, true);
assert!(ui.is_none() && !keep);
let warning = warning.unwrap();
assert!(warning.contains("damaged") && warning.contains("ui.json.corrupt-"), "{warning}");
assert!(!path.exists());
let kept: Vec<_> = std::fs::read_dir(&d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).collect();
assert!(kept.len() == 1 && kept[0].starts_with("ui.json.corrupt-"), "{kept:?}");
// a missing file is just "no settings yet"
assert_eq!(load_prefs_at(&path, true).1, None);
let _ = std::fs::remove_dir_all(&d);
}
/// Issue #164: a `--memory` session reads the settings but writes nothing — a damaged file is
/// reported and left where it is, not set aside.
#[test]
fn memory_session_leaves_a_damaged_ui_json_alone() {
let d = dir("damaged-memory");
let path = d.join("ui.json");
let bytes = br#"{"settings": {"library_path": "/Volumes/Photos/Lib"#;
std::fs::write(&path, bytes).unwrap();
let (ui, warning, keep) = load_prefs_at(&path, false);
assert!(ui.is_none() && keep);
let warning = warning.unwrap();
assert!(warning.contains("damaged") && warning.contains("nothing is saved"), "{warning}");
assert_eq!(std::fs::read(&path).unwrap(), bytes);
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn docking_survives_native_settings_file_reload() {
use lightcraft_ui_egui::docking::Panel;
let d = dir("docking-reload");
let path = d.join("ui.json");
let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default());
app.run("ui.dock", serde_json::json!({"operation":"float", "panel":"tools", "rect":[70,80,310,500]})).unwrap();
app.run("ui.dock", serde_json::json!({"operation":"close", "panel":"tools"})).unwrap();
let mut writer = PrefsWriter { path: Some(path.clone()), ..Default::default() };
writer.save_ui(&app.ui, false).unwrap();
let (restored, warning, keep) = load_prefs_at(&path, false);
assert!(warning.is_none());
assert!(!keep);
let mut restored_app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default());
restored_app.ui = restored.unwrap();
restored_app.run("ui.dock", serde_json::json!({"operation":"open", "panel":"tools"})).unwrap();
assert_eq!(
restored_app.ui.docking.as_ref().unwrap().layout.floating.iter().find(|g| g.contains(&Panel::Tools)).unwrap().rect,
[70.0, 80.0, 310.0, 500.0]
);
std::fs::remove_dir_all(d).unwrap();
}
#[test]
fn future_docking_preserves_library_settings_and_the_original_preferences_file() {
let d = dir("future-docking");
let path = d.join("ui.json");
let mut ui = UiState { thumb_size: 210.0, filmstrip: false, ..Default::default() };
ui.settings.library_path = "/Volumes/Photos/Synthetic Library".into();
for docking in [serde_json::json!({"layout":{"root":{"FutureLayout":{}}}}), serde_json::json!(false)] {
let mut saved = serde_json::to_value(&ui).unwrap();
saved["docking"] = docking;
assert!(serde_json::from_value::<UiState>(saved.clone()).is_err(), "runtime state parsing stays strict");
let bytes = serde_json::to_vec(&saved).unwrap();
for set_aside in [false, true] {
std::fs::write(&path, &bytes).unwrap();
let (loaded, warning, keep) = load_prefs_at(&path, set_aside);
let loaded = loaded.unwrap();
assert_eq!(loaded.settings.library_path, ui.settings.library_path);
assert_eq!(loaded.thumb_size, ui.thumb_size);
assert!(!loaded.filmstrip);
assert!(loaded.docking.is_none());
assert!(warning.unwrap().contains("Other settings were loaded"));
assert!(keep);
let mut writer = PrefsWriter { path: Some(path.clone()), keep_file: keep, ..Default::default() };
writer.save_ui(&loaded, false).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), bytes);
assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1, "a future layout does not rename or replace the settings file");
}
}
std::fs::remove_dir_all(d).unwrap();
}
/// Issue #164: the writer saves changed settings to its file — and nothing at all without one
/// (`--memory`) or while the session is the temporary one offered when the library can't open.
#[test]
fn prefs_writer_writes_nothing_in_a_memory_or_temporary_session() {
let d = dir("writer");
let path = d.join("sub").join("ui.json");
let mut ui = UiState::default();
// an ordinary session: a change is written, the folder created on the way
let mut w = PrefsWriter { path: Some(path.clone()), ..Default::default() };
ui.thumb_size += 50.0;
w.save_ui(&ui, false).unwrap();
let saved = std::fs::read(&path).unwrap();
assert!(String::from_utf8_lossy(&saved).contains("thumbSize"), "{}", String::from_utf8_lossy(&saved));
// the temporary session (library problem): a further change is not written…
ui.thumb_size += 50.0;
w.save_ui(&ui, true).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), saved);
// …until a library opens
w.save_ui(&ui, false).unwrap();
assert_ne!(std::fs::read(&path).unwrap(), saved);
// --memory: no path, so no file and no folder, whatever changes
let d2 = dir("writer-memory");
let _ = std::fs::remove_dir_all(&d2);
let mut w = PrefsWriter { path: None, ..Default::default() };
ui.thumb_size += 50.0;
w.save_ui(&ui, false).unwrap();
assert!(w.written.is_empty() && !d2.exists());
let _ = std::fs::remove_dir_all(&d);
}
/// Issue #169: a `--memory` session neither arms the GPU crash sentinel (which would create
/// the settings folder) nor removes a marker a crashed launch left; it still reports it, and
/// the next ordinary launch finds it, reports it and clears it.
#[test]
fn memory_session_leaves_the_gpu_marker_and_folder_alone() {
let d = dir("gpu-marker-memory");
let _ = std::fs::remove_dir_all(&d);
let m = d.join("gpu-init.marker");
// nothing left behind: no notice, and the folder is not created
assert_eq!(gpu_crash_check_at(Some(m.clone()), true), None);
assert!(!d.exists(), "a --memory session must not create the settings folder");
// a marker left by a crashed launch: reported, kept
std::fs::create_dir_all(&d).unwrap();
std::fs::write(&m, "GPU device creation started (backends METAL)").unwrap();
let notice = gpu_crash_check_at(Some(m.clone()), true).unwrap();
assert!(notice.contains("GPU rendering is now off"), "{notice}");
assert!(m.exists(), "the marker stays for the next ordinary launch");
// the next ordinary launch reports it once and removes it
assert!(gpu_crash_check_at(Some(m.clone()), false).is_some());
lightcraft_engine::gpu::backend::set_init_marker(None);
assert!(!m.exists());
assert_eq!(gpu_crash_check_at(Some(m.clone()), false), None);
lightcraft_engine::gpu::backend::set_init_marker(None);
let _ = std::fs::remove_dir_all(&d);
}
/// Issue #1337: the window stopped drawing after the graphics driver reset the GPU during an
/// export, and the dialog said the window "could not open". The stop is recorded; the next
/// launch says why once and renders on the CPU (a `--memory` session leaves the record).
#[test]
fn a_gpu_lost_while_running_turns_the_gpu_off_next_time() {
let d = dir("gpu-lost");
let m = d.join("gpu-lost.marker");
assert_eq!(gpu_lost_check_at(Some(&m), false), None, "nothing recorded");
assert_eq!(gpu_lost_check_at(None, false), None, "no settings folder");
record_gpu_lost(Some(&m), "device lost (Unknown): Device is lost");
let notice = gpu_lost_check_at(Some(&m), true).unwrap();
assert!(
notice.contains("(device lost (Unknown): Device is lost)")
&& notice.contains("GPU rendering is now off")
&& notice.contains("Use the GPU for rendering"),
"{notice}"
);
assert!(m.exists(), "a --memory session leaves it");
assert!(gpu_lost_check_at(Some(&m), false).is_some());
assert!(!m.exists());
assert_eq!(gpu_lost_check_at(Some(&m), false), None, "said once");
// the message box: LightCraft stopped (not "could not open its window"), and why
let text = stopped_text("its window stopped drawing (the renderer panicked)", Some("device lost (Unknown): Device is lost"));
assert!(text.contains("reset the GPU (device lost (Unknown)") && text.contains("renders on the CPU from its next start"), "{text}");
assert_eq!(stopped_text("its window stopped drawing", None), "its window stopped drawing");
let (title, body) = lightcraft_ui_egui::i18n::stopped_message(&text, Some("/logs/lightcraft.log"));
assert_eq!(title, "LightCraft stopped");
assert!(body.starts_with("LightCraft stopped unexpectedly: its window stopped drawing") && body.ends_with("/logs/lightcraft.log"), "{body}");
let _ = std::fs::remove_dir_all(&d);
}
/// Issue #136: a GPU init marker left by a crashed launch is reported once and removed.
#[test]
fn gpu_crash_marker_is_reported_once() {
let d = dir("gpu-marker");
let m = d.join("gpu-init.marker");
assert_eq!(lightcraft_engine::gpu::backend::take_init_marker(&m), None);
std::fs::write(&m, "GPU device creation started (backends VULKAN | DX12)").unwrap();
let what = lightcraft_engine::gpu::backend::take_init_marker(&m).unwrap();
let notice = gpu_crash_notice(&what);
assert!(notice.contains("GPU rendering is now off") && notice.contains("Use the GPU for rendering"), "{notice}");
assert!(!m.exists());
let _ = std::fs::remove_dir_all(&d);
}
/// Issue #136: Windows windows render with DX12 alone (no Vulkan driver loaded) by default.
#[test]
fn window_backends_follow_the_platform_default() {
let eframe::egui_wgpu::WgpuSetup::CreateNew(n) = window_wgpu_options().wgpu_setup else { panic!("expected CreateNew") };
let b = n.instance_descriptor.backends;
if std::env::var_os("LIGHTCRAFT_GPU_BACKEND").is_none() && std::env::var_os("WGPU_BACKEND").is_none() {
if cfg!(windows) {
assert_eq!(b, eframe::wgpu::Backends::DX12);
} else if cfg!(target_os = "macos") {
assert_eq!(b, eframe::wgpu::Backends::METAL);
}
}
assert!(!b.is_empty());
}
/// Issue #471: the window's DX12 shaders compile with FXC — wgpu's default loaded any
/// `dxcompiler.dll` on the search path, and one without `dxil.dll` kept the window from opening.
#[test]
fn window_compiles_dx12_shaders_with_fxc() {
let eframe::egui_wgpu::WgpuSetup::CreateNew(n) = window_wgpu_options().wgpu_setup else { panic!("expected CreateNew") };
if std::env::var_os("WGPU_DX12_COMPILER").is_none() {
assert!(matches!(n.instance_descriptor.backend_options.dx12.shader_compiler, eframe::wgpu::Dx12Compiler::Fxc));
}
}
/// Issue #250: the window's device is created without wgpu's indirect-call validation pipeline,
/// which Intel Macs' Metal compiler fails to build (the device was lost, the window never opened).
#[test]
fn window_has_no_indirect_call_validation_pipeline() {
let eframe::egui_wgpu::WgpuSetup::CreateNew(n) = window_wgpu_options().wgpu_setup else { panic!("expected CreateNew") };
if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() {
assert!(!n.instance_descriptor.flags.contains(eframe::wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL));
}
}
/// Issue #234: Windows opens links with the URL protocol handler (the default browser), not
/// File Explorer, and passes the whole map link, `?`, `&` and `#` included, as one argument.
#[test]
fn windows_links_open_in_the_browser() {
let url = "https://www.openstreetmap.org/?mlat=48.856600&mlon=2.352200#map=15/48.856600/2.352200";
let c = windows_open_url_command(url);
assert_eq!(c.get_program(), "rundll32");
let args: Vec<&std::ffi::OsStr> = c.get_args().collect();
assert_eq!(args, ["url.dll,FileProtocolHandler", url]);
}
/// Issue #272: Explorer gets the file to select quoted after `/select,`, with backslashes and
/// without the verbatim prefix, even when the path has spaces (else it opens Documents).
#[test]
fn explorer_select_quotes_the_path() {
assert_eq!(explorer_select_arg(r"C:\Users\Me\My Photos\IMG 1.jpg"), r#"/select,"C:\Users\Me\My Photos\IMG 1.jpg""#);
assert_eq!(explorer_select_arg("D:/Example/Photos/IMG_0001.CR3"), r#"/select,"D:\Example\Photos\IMG_0001.CR3""#);
assert_eq!(explorer_select_arg(r"\\server\share\My Photos\a.jpg"), r#"/select,"\\server\share\My Photos\a.jpg""#);
assert_eq!(explorer_select_arg(r"\\?\D:\My Photos\a.jpg"), r#"/select,"D:\My Photos\a.jpg""#);
assert_eq!(explorer_select_arg(r"\\?\UNC\server\share\a.jpg"), r#"/select,"\\server\share\a.jpg""#);
// a `"` can't end the quoted path and add arguments to the raw command line
assert_eq!(explorer_select_arg(r#"C:\a" "C:\b.jpg"#), r#"/select,"C:\a C:\b.jpg""#);
let c = explorer_select_command(r"C:\My Photos\a.jpg");
assert_eq!(c.get_program(), "explorer");
let args: Vec<&std::ffi::OsStr> = c.get_args().collect();
assert_eq!(args, [r#"/select,"C:\My Photos\a.jpg""#]);
}
#[test]
fn a_control_port_that_is_not_a_number_is_ignored() {
assert_eq!(control_port_from("--control", Some("7980".into())), Some(7980));
assert_eq!(control_port_from("--control", Some(" 18001 ".into())), Some(18001));
assert_eq!(control_port_from("--control", Some("nope".into())), None);
assert_eq!(control_port_from("--control", Some(String::new())), None);
assert_eq!(control_port_from("--control", Some("70000".into())), None);
assert_eq!(control_port_from("LIGHTCRAFT_CONTROL_PORT", None), None);
}
#[test]
fn ui_json_is_written_atomically() {
let d = dir("atomic");
let path = d.join("ui.json");
std::fs::write(&path, b"old").unwrap();
write_atomic(&path, b"{\"new\": true}").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"{\"new\": true}");
assert!(!d.join("ui.json.tmp").exists());
// a failed write leaves the old file
let missing = d.join("gone").join("ui.json");
assert!(write_atomic(&missing, b"x").is_err());
assert_eq!(std::fs::read(&path).unwrap(), b"{\"new\": true}");
let ui = UiState::default();
write_atomic(&path, &serde_json::to_vec_pretty(&ui).unwrap()).unwrap();
let (loaded, warning, _) = load_prefs_at(&path, true);
assert!(loaded.is_some() && warning.is_none());
let _ = std::fs::remove_dir_all(&d);
}
/// Given what the settings remember of the window, when the app's window is built, then it
/// opens at that size, zoomed if it was, where the system puts it; with nothing remembered it
/// opens at the usual size.
#[test]
fn the_window_opens_as_it_was() {
use lightcraft_ui_egui::window_place::{DEFAULT_SIZE, WindowPlace};
let fresh = as_remembered(egui::ViewportBuilder::default(), None);
assert_eq!((fresh.inner_size, fresh.position, fresh.maximized), (Some(egui::Vec2::from(DEFAULT_SIZE)), None, None));
let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: true }));
assert_eq!((b.inner_size, b.position, b.maximized), (Some(egui::vec2(1300.0, 800.0)), None, Some(true)));
// (not asked to un-zoom: macOS would then resize a window that fills its screen)
let b = as_remembered(egui::ViewportBuilder::default(), Some(WindowPlace { size: [1300.0, 800.0], zoomed: false }));
assert_eq!((b.inner_size, b.position, b.maximized), (Some(egui::vec2(1300.0, 800.0)), None, None));
}
/// Given a window that rests at a size, when the settings are written and read again, then
/// they hold how it was. A window in the file that is not one (a hand edit, another version's)
/// reads as nothing remembered and costs no other setting; and a window resized just before
/// the app quits is remembered at that size.
#[test]
fn the_settings_keep_how_the_window_was() {
use lightcraft_ui_egui::window_place::{Seen, WindowPlace};
let d = dir("window");
let path = d.join("ui.json");
let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default());
app.ui.settings.library_path = "/pictures/library".into();
let mut writer = PrefsWriter { path: Some(path.clone()), ..Default::default() };
writer.save(&app).unwrap();
assert!(!std::fs::read_to_string(&path).unwrap().contains("\"window\""), "nothing to remember yet");
let window = WindowPlace { size: [1300.0, 800.0], zoomed: true };
app.ui.window = Some(window);
writer.save(&app).unwrap();
let (restored, warning, _) = load_prefs_at(&path, false);
assert_eq!((restored.unwrap().window, warning), (Some(window), None));
// a window that is no window: the file is read all the same, with its other settings
let text = std::fs::read_to_string(&path).unwrap();
for odd in [r#""window": {}"#, r#""window": "wide""#, r#""window": {"size": [1, 2, 3]}"#, r#""window": {"size": [null, 800.0]}"#] {
let start = text.find("\"window\"").unwrap();
let end = start + text[start..].find('}').unwrap() + 1;
std::fs::write(&path, format!("{}{odd}{}", &text[..start], &text[end..])).unwrap();
let (restored, warning, keep) = load_prefs_at(&path, true);
let restored = restored.unwrap_or_else(|| panic!("{odd}: {warning:?}"));
assert_eq!((restored.window, restored.settings.library_path.as_str(), warning, keep), (None, "/pictures/library", None, false), "{odd}");
}
// resized, and the app quits a moment later: the new size is what is written
let mut writer = PrefsWriter { path: Some(path.clone()), ..Default::default() };
let rest = Some(WindowPlace { size: [1300.0, 800.0], zoomed: false });
writer.window.note(rest, &Seen { size: Some([1500.0, 900.0]), ..Default::default() }, 0.0);
writer.window_since = std::time::Instant::now().checked_sub(std::time::Duration::from_millis(400));
assert!(writer.window_since.is_some());
assert_eq!(writer.window_at_exit(rest), Some(WindowPlace { size: [1500.0, 900.0], zoomed: false }));
assert_eq!(PrefsWriter::default().window_at_exit(rest), rest, "a window that was never seen");
let _ = std::fs::remove_dir_all(&d);
}
/// Given the app's window at a size, when the settings writer looks at it frame after frame,
/// then it asks to be woken while the size has still to rest, remembers the size once it has,
/// and asks for nothing more. A window in the settings that is not one (a script set it) is
/// put right before it is gone by.
#[test]
fn the_writer_follows_the_window_from_frame_to_frame() {
use lightcraft_ui_egui::window_place::WindowPlace;
let mut app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services::default());
let mut writer = PrefsWriter::default();
let ctx = egui::Context::default();
let pass = |look: &mut dyn FnMut(&egui::Context)| {
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1300.0, 800.0))), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| look(ui.ctx()));
out.textures_delta.clear();
out.viewport_output.get(&egui::ViewportId::ROOT).map(|v| v.repaint_delay)
};
// (egui's own first frames ask for another: let them pass)
for _ in 0..3 {
pass(&mut |_| {});
}
app.ui.window = Some(WindowPlace { size: [f32::NAN, 800.0], zoomed: true });
let asked = pass(&mut |ctx| writer.tick(&mut app, ctx));
assert_eq!(app.ui.window, None, "no window, and not yet at rest");
assert!(asked.is_some_and(|wait| wait <= std::time::Duration::from_secs(1)), "{asked:?}");
// a second later
writer.window_since = writer.window_since.and_then(|since| since.checked_sub(std::time::Duration::from_secs(1)));
pass(&mut |ctx| writer.tick(&mut app, ctx));
assert_eq!(app.ui.window, Some(WindowPlace { size: [1300.0, 800.0], zoomed: false }));
let asked = pass(&mut |ctx| writer.tick(&mut app, ctx));
assert!(asked.is_none_or(|wait| wait > std::time::Duration::from_secs(3600)), "at rest and remembered: {asked:?}");
}
/// #1331: on macOS the process ends inside `on_exit`, before eframe would tear the window down.
/// The check runs in a child (this test binary again), since on macOS it ends the process.
#[test]
fn on_exit_ends_the_process_on_macos() {
if std::env::var_os("LIGHTCRAFT_TEST_ON_EXIT").is_some() {
let app = LightcraftApp::new(lightcraft_engine::Session::new(), Services::default());
let mut app = App(
app,
PrefsWriter::default(),
#[cfg(target_os = "macos")]
None,
);
println!("calling on_exit");
eframe::App::on_exit(&mut app, None);
println!("on_exit returned");
return;
}
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["--exact", "tests::on_exit_ends_the_process_on_macos", "--nocapture"])
.env("LIGHTCRAFT_TEST_ON_EXIT", "1")
.env("LIGHTCRAFT_NO_PREFS", "1")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{stdout}");
assert!(stdout.contains("calling on_exit"), "the child didn't run the test: {stdout}");
assert_eq!(stdout.contains("on_exit returned"), !cfg!(target_os = "macos"), "{stdout}");
}
+34 -13
View File
@@ -93,7 +93,6 @@ pub fn choose(files: &Files) -> Chosen {
let compiled = wgpu::Instance::enabled_backend_features();
let os = std::env::consts::OS;
let order = backend::window_renderer_order(forced, remembered, failed, os, compiled, true);
let mut notice = failed.map(|f| format!("The window could not start with its {} renderer last time.", f.name()));
let mut problems = Vec::new();
let chosen = if cfg!(windows) {
pick_probed(&order, &mut problems)
@@ -104,18 +103,7 @@ pub fn choose(files: &Files) -> Chosen {
Some((WindowRenderer::Wgpu(backend::window_backends()), None))
};
let (which, existing) = chosen.unwrap_or((WindowRenderer::Glow, None));
if !problems.is_empty() {
notice = Some(format!("{} {}", notice.unwrap_or_default(), problems.join(" ")).trim().to_string());
}
let notice = notice.map(|n| {
format!(
"{n} {app} now draws its window with {}. To choose another, start {app} with {var}=dx12, vulkan, gl or glow \
(see docs/gpu-pipeline.md → Troubleshooting).",
which.name(),
app = "LightCraft",
var = "LIGHTCRAFT_GPU_BACKEND",
)
});
let notice = user_notice(failed, forced, &problems, which);
log::info!("window: renderer {} (order {:?})", which.name(), order.iter().map(|r| r.name()).collect::<Vec<_>>());
let mut wgpu_options = base_options();
let renderer = match (which, existing) {
@@ -134,6 +122,25 @@ pub fn choose(files: &Files) -> Chosen {
Chosen { renderer, wgpu_options, which, notice }
}
/// What to tell the user about the window's renderer. A renderer that failed its probe is skipped
/// silently (it is logged, and the one that worked is remembered): the app works, so a pop-up with
/// wgpu's error only alarms (#1624). Shown: the last start died, or the forced renderer failed.
fn user_notice(failed: Option<WindowRenderer>, forced: Option<WindowRenderer>, problems: &[String], which: WindowRenderer) -> Option<String> {
let mut notice = failed.map(|f| format!("The window could not start with its {} renderer last time.", f.name()));
if forced.is_some() && !problems.is_empty() {
notice = Some(format!("{} {}", notice.unwrap_or_default(), problems.join(" ")).trim().to_string());
}
notice.map(|n| {
format!(
"{n} {app} now draws its window with {}. To choose another, start {app} with {var}=dx12, vulkan, gl or glow \
(see docs/gpu-pipeline.md → Troubleshooting).",
which.name(),
app = "LightCraft",
var = "LIGHTCRAFT_GPU_BACKEND",
)
})
}
/// eframe's defaults with the app's backends and DX12 shader compiler (issues #136, #471).
pub fn base_options() -> WgpuConfiguration {
let mut c = WgpuConfiguration::default();
@@ -269,6 +276,20 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// #1624: a renderer skipped by the probe (DX12 → Vulkan) is no pop-up; a died start or a
/// failed forced renderer still is.
#[test]
fn probe_fallback_is_silent() {
let (dx, vk) = (WindowRenderer::Wgpu(Backends::DX12), WindowRenderer::Wgpu(Backends::VULKAN));
let problems = vec!["The dx12 renderer failed (Validation Error).".to_string()];
assert_eq!(user_notice(None, None, &problems, vk), None);
assert_eq!(user_notice(None, None, &[], vk), None);
let forced = user_notice(None, Some(dx), &problems, vk).unwrap();
assert!(forced.starts_with("The dx12 renderer failed") && forced.contains("now draws its window with vulkan"), "{forced}");
let died = user_notice(Some(dx), None, &problems, vk).unwrap();
assert!(died.contains("last time") && !died.contains("Validation Error"), "{died}");
}
/// The crash report: a pipeline that fails validation must come back as an error, never as
/// wgpu's default panic. Needs an adapter; skipped where there is none (CI without a GPU).
#[test]
+9 -1
View File
@@ -8,6 +8,10 @@ covers a whole directory), or if a licence file referenced in the Licence column
| Path | Asset | Creator | Source | Licence | Added | Modifications |
|---|---|---|---|---|---|---|
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | egui icon subset and monochrome fallback | John Slegers | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | 2026-10-24 (notice audit) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full fallback. Registered by production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
| `epaint_default_fonts::HACK_REGULAR` (dependency font input) | Hack Regular (the monospace default) | Source Foundry Authors (built on the DejaVu project, which was committed to the public domain) and Bitstream Inc. | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts) | MIT AND Bitstream Vera License (Copyright (c) 2018 Source Foundry Authors; Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved.; full upstream texts in `NOTICE`) | 2026-10-25 (notice audit) | unmodified egui default font embedded in the binary and registered by the production default font definitions (egui's `default_fonts`); no font file copied into this repository |
| `epaint_default_fonts::UBUNTU_LIGHT` (dependency font input) | Ubuntu Light (the proportional default) | Canonical Ltd.; designed by Dalton Maag Ltd | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts) | Ubuntu Font Licence 1.0, not the SIL Open Font License (Copyright 2011 Canonical Ltd.; full upstream text in `NOTICE`) | 2026-10-25 (notice audit) | unmodified egui default font embedded in the binary and registered by the production default font definitions (egui's `default_fonts`); no font file copied into this repository |
| `epaint_default_fonts::NOTO_EMOJI_REGULAR` (dependency font input) | Noto Emoji Regular | Google Inc.; designed by the Monotype Design Team | [egui 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts) | SIL Open Font License 1.1 (Copyright 2013 Google Inc. All Rights Reserved.; full upstream text in `NOTICE`) | 2026-10-25 (notice audit) | unmodified egui default font embedded in the binary and registered by the production default font definitions (egui's `default_fonts` and `monochrome_emoji_fonts`); no font file copied into this repository |
| `assets/fonts/Inter-*.ttf` (Regular, Medium, SemiBold) | Inter | Rasmus Andersson | https://github.com/rsms/inter | SIL Open Font License 1.1 (`assets/fonts/OFL-Inter.txt`) | 2026-09-30 | none |
| `assets/app-icon/` (`lightcraft.svg` and the PNG/ICNS/ICO/SVG files derived from it) | LightCraft app icon (lynx) | LightCraft project owner (drawn in ArtCraft) | original work (vectorised from the owner's drawing; see `assets/app-icon/README.md`) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | 2026-10-02 | vectorised to SVG; rendered to PNG/ICNS/ICO by `packaging/icons.sh` |
| `assets/camera-profiles/*.json` | Camera colour profiles (matrix + hue/saturation/value table), built into LightCraft | ILCE-7M4: Harald Hoyer | original work: fitted by `lightcraft-cli calibrate` to the contributor's own raw photos and their in-camera JPEGs (597 ILCE-7M4 photos, 2026); aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-07 | none |
@@ -18,6 +22,7 @@ covers a whole directory), or if a licence file referenced in the Licence column
| `assets/camera-profiles/NIKON_Z_6_2.json` | Nikon Z 6II camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 296 usable Z 6II NEFs of my own (of 299, 2024 to 2026, Standard and Auto picture controls; NIKKOR Z 20mm f/1.8 S, Z 24-70mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/NIKON_Z_8.json` | Nikon Z 8 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 261 usable Z 8 NEFs of my own (of 278, 2023 and 2026, nearly all Standard picture control, lossless 14-bit; NIKKOR Z 24-120mm f/4 S and AF-S 70-200mm f/2.8G on the FTZ) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/NIKON_D5300.json` | Nikon D5300 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Michael Anderson (@endthestart) | original work: fitted by `lightcraft-cli calibrate` to 264 usable D5300 NEFs of my own (of 273, 2014 to 2017, mostly Standard picture control, lossy 12-bit, mostly the AF-S DX 35mm f/1.8G) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-13 | none |
| `assets/camera-profiles/ILCE-7RM5.json` | Sony ILCE-7RM5 camera colour profile (matrix + hue/saturation/value table), built into LightCraft | Yule (Brian) Wang (@peaperfish) | original work: fitted by `lightcraft-cli calibrate` to 220 usable ILCE-7RM5 ARWs of my own (of 241, 2025 to 2026, Standard creative style; Sigma 24-70mm F2.8 DG DN II Art and Sony FE 200-600mm F5.6-6.3 G OSS) and their in-camera JPEGs; aggregate colour statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 | 2026-10-26 | none |
| `crates/raw/src/spectral_table.rs` | Camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D65) for 52 camera models, and the model alias list | Derived by LightCraft contributors from rawtoaces-data (Academy Software Foundation): camera spectral sensitivities measured by Weta Digital (44 cameras), scitech (7) and Jonathon Irons at the National Physical Laboratory (Nikon D5100); training reflectances; CIE 1931 colour-matching functions (CIE, CC-BY-4.0, as shipped in rawtoaces-data) | https://github.com/AcademySoftwareFoundation/rawtoaces-data, tag v1.1.0, commit 5cfa53707b053594b2d0d48e8019fb56e6582d6c | Apache-2.0 (`LICENSE-APACHE`); the colour-matching functions CC-BY-4.0 | 2026-10-08 | generated by `tools/spectral_camera_table.py`: a 3×3 matrix per illuminant fitted to the spectral data (no measurement copied verbatim); aliases copied from `data/aliases.json`; no Adobe or third-party camera matrix |
| `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none |
| `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a |
@@ -29,7 +34,7 @@ covers a whole directory), or if a licence file referenced in the Licence column
| `docs/images/*-blue-marble.jpg`, `docs/images/grid-pd.jpg` | "The Blue Marble" (AS17-148-22727) | NASA, Apollo 17 crew (1972) | https://commons.wikimedia.org/wiki/File:The_Earth_seen_from_Apollo_17.jpg | Public domain (NASA) | 2026-09-30 | developed in LightCraft; shown inside app screenshots |
| `docs/images/*.jpg` (UI) | LightCraft application screenshots | LightCraft contributors | original work (captured with `docs/showcase/`) | MIT OR Apache-2.0 | 2026-09-30 | n/a |
| `docs/brand/` (artcraft-logo and artcraft-mark, SVG and PNG) | ArtCraft wordmark and mark | ArtCraft Team | original work (https://getartcraft.com/) | ArtCraft trademark, see `docs/brand/LICENSE-brand.txt` (not open source) | 2026-10-01 | none |
| craft-fonts: optional build input, not files in this repository | BIZ UDPGothic (Regular, Bold), BIZ UDMincho Regular, Shippori Mincho Regular, Noto Sans CJK SC Regular, Noto Sans Arabic Regular, Noto Sans Thai Regular | The Noto Project Authors (Arabic and Thai); Morisawa Inc. / The BIZ UDGothic and BIZ UDMincho Project Authors; The Shippori Mincho Project Authors; Google and Adobe (Noto Sans CJK, maintainer-approved exception; see AGENTS.md) (per craft-fonts' attribution) | https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md | SIL Open Font License 1.1 (each font's OFL.txt in craft-fonts; release packages ship it as OFL-<family>.txt) | 2026-10-06 | none; native builds made with `CRAFT_FONTS_DIR` embed the manifest fonts (all official releases); the web build embeds BIZ UDPGothic Regular and Noto Sans Thai Regular and ships Noto Sans CJK SC Regular as a separate font file |
| craft-fonts: optional build input, not files in this repository | BIZ UDPGothic (Regular, Bold), BIZ UDMincho Regular, Shippori Mincho Regular, Noto Sans CJK SC Regular, Noto Sans Arabic Regular, Noto Sans Thai Regular, Noto Sans Georgian Regular, NanumGothic Regular, Noto Sans Symbols Regular, Noto Sans Symbols 2 Regular, Noto Sans Hebrew Regular, Noto Sans Devanagari Regular | The Noto Project Authors (Arabic, Thai, Georgian, Symbols, Symbols 2, Hebrew and Devanagari); Morisawa Inc. / The BIZ UDGothic and BIZ UDMincho Project Authors; The Shippori Mincho Project Authors; NHN Corporation and Sandoll Communications (NanumGothic); Google and Adobe (Noto Sans CJK, maintainer-approved exception; see AGENTS.md) (per craft-fonts' attribution) | https://github.com/storytold/craft-fonts/blob/b076417b5880bd4154bd22f00695b1d28c6bea83/ATTRIBUTION.md | SIL Open Font License 1.1 (each font's OFL.txt in craft-fonts; release packages ship it as OFL-<family>.txt) | 2026-10-06 | none; native builds made with `CRAFT_FONTS_DIR` embed the default `fonts/manifest.txt` set (all official releases; the opt-in LXGW WenKai Lite face in `fonts/simplified-chinese-manifest.txt` is not embedded); the web build embeds BIZ UDPGothic Regular, Noto Sans Thai Regular and Noto Sans Georgian Regular and ships Noto Sans CJK SC Regular as a separate font file |
| `crates/ui-egui/locales/uk.json`, `crates/ui-egui/locales/uk-formats.json` | Ukrainian interface catalogs | @dmatviichuk with Codex; PhotoCraft, FilmCraft and VectorCraft translation contributors for reused labels | original translations from English source; 337 initial English-key matches reviewed from [PhotoCraft 69c41f3](https://github.com/storytold/photocraft/blob/69c41f3523e147eb215da8c7b4c29b18b35d1c63/crates/ui-egui/src/i18n/uk.tsv), [FilmCraft 4854c27](https://github.com/storytold/filmcraft/blob/4854c277536fe8118257362304b6a7d82d8e704b/crates/ui-egui/src/i18n/uk.tsv), [VectorCraft 4b44265](https://github.com/storytold/vectorcraft/blob/4b44265965fdd6ffedfd6182a892c1a6c360d344/crates/ui-egui/src/i18n/uk.tsv) | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, also the source repositories' licences) | 2026-10-09 | adapted to LightCraft photo-development context, completed catalogs, reviewed spelling and placeholders |
| `crates/ui-egui/locales/cs.json`, `crates/ui-egui/locales/cs-formats.json` | Czech interface catalogs | @Losminek with AI assistance (Codex) | original work: translations of English source phrases, reviewed against the app UI conventions; no external translation material | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-11 | catalog coverage, Czech dates and count-neutral wording; independent scope/terminology review; native-speaker proofreading pending |
| `crates/ui-egui/locales/it.json`, `crates/ui-egui/locales/it-formats.json` | Italian interface catalogs | @GabrielePecchioli with Claude Code; PhotoCraft, VectorCraft, PdfCraft and WordCraft translation contributors for reused labels | original translations from English source; 410 initial English-key matches reviewed from [PhotoCraft da3da09](https://github.com/storytold/photocraft/blob/da3da0942c14c1159f40c652afcf33584332c733/crates/ui-egui/src/i18n/it.tsv), [VectorCraft 5432821](https://github.com/storytold/vectorcraft/blob/543282148007bcb5633c493a5374cd26b0339c8d/crates/ui-egui/src/i18n/it.tsv), [PdfCraft e8e275c](https://github.com/storytold/pdfcraft/blob/e8e275cbd40ccd0dc6b56f82b16a575571043702/crates/ui-egui/src/i18n/it.tsv) and the Italian WordCraft catalog ([storytold/wordcraft#598](https://github.com/storytold/wordcraft/pull/598)); 46 of them retranslated where the sibling's meaning didn't fit a photo app | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`, also the source repositories' licences) | 2026-10-12 | adapted to LightCraft photo-development context, count-neutral labels for Italian plural agreement, reviewed placeholders |
@@ -40,6 +45,9 @@ covers a whole directory), or if a licence file referenced in the Licence column
| `crates/ui-egui/locales/vi.json`, `crates/ui-egui/locales/vi-formats.json` | Vietnamese interface catalogs | @duydev (DUY Tran Nhat) with AI assistance (Cursor) | original work: translations of English source phrases; no external translation material | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-10-13 | plural-neutral counts, Vietnamese dates and weekdays, reviewed placeholders |
Notes
- egui's default fonts (Hack, Ubuntu Light, Noto Emoji, egui-icons and emoji-icon-font) come from the
`epaint_default_fonts` dependency, not from files in this repository; their creators, licences and the full
upstream texts are recorded in the rows above and in `NOTICE`.
- Fonts authored or published by Adobe (Source Sans/Serif/Code, Source Han, …) are not used, even though some are
OFL-licensed: the asset rule excludes anything from Adobe. Source Sans 3 was removed on 2026-09-30 and replaced by Inter.
- CJK fonts (BIZ UDPGothic, BIZ UDMincho, Shippori Mincho, Noto Sans CJK SC) are not in this repository. They live in
File diff suppressed because it is too large. Load diff
+4
View File
@@ -2,3 +2,7 @@ allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
]
cognitive-complexity-threshold = 30
+7
View File
@@ -61,9 +61,16 @@ sync_github_name = false
real_name = "Ege Gursel"
sync_github_name = true
[people.valenfys]
sync_github_name = true
[people.mahmatias]
display_name = "Márcio Matias de Andrade"
sync_github_name = true
[people.ronibalthazar]
sync_github_name = true
[people.dotCooCoo]
real_name = "Robert Lee"
sync_github_name = true
+4
View File
@@ -20,6 +20,10 @@ log = { workspace = true }
chrono = { workspace = true }
web-time = { workspace = true }
[target.'cfg(windows)'.dependencies]
winapi-util = { workspace = true }
[dev-dependencies]
lightcraft-geom = { workspace = true }
lightcraft-testkit = { workspace = true }
proptest = { workspace = true }
+1 -1
View File
@@ -14,7 +14,7 @@
use std::sync::Arc;
use std::time::Instant;
use lightcraft_catalog::*;
use lightcraft_catalog::{Catalog, DEFAULT_FORGET_DAYS, FsStore, HistoryStep, Journal, MediaKind, Op, Photo, PhotoId, Source, folder_of};
use lightcraft_develop::DevelopSettings;
fn ms(t: Instant) -> f64 {
+107 -4
View File
@@ -43,19 +43,63 @@ pub fn weekday(iso: &str) -> Option<&'static str> {
/// Shift an ISO time by `secs`, keeping anything after the seconds (fractions, zone) as it was.
/// A date without a time gets one. `None` if it doesn't parse, or if the result leaves years
/// 0000–9999 (an ISO date here has four year digits, so it couldn't be read back); `secs` may be
/// anything, it never overflows.
/// anything, it never overflows. Stricter than [`iso_seconds`], which reads what it can for sorting:
/// a time cut short, seconds that aren't digits or anything after the zone is `None` here, not
/// written back as a clean-looking time.
pub fn shift_iso(iso: &str, secs: i64) -> Option<String> {
let iso = iso.trim();
let tail = iso.get(tail_start(iso)?..)?;
let t = iso_seconds(iso)?.checked_add(secs)?;
let (first, last) = (iso_seconds("0000-01-01T00:00:00")?, iso_seconds("9999-12-31T23:59:59")?);
if !(first..=last).contains(&t) {
return None;
}
let iso = iso.trim();
// the seconds are optional (`10:00+02:00`): without them the tail starts right after the minutes
let tail = iso.get(if iso.get(16..17) == Some(":") { 19 } else { 16 }..).unwrap_or("");
Some(format!("{}{tail}", civil(t)))
}
/// Where the part of an ISO time that [`shift_iso`] keeps as it was (fraction, zone) starts, or
/// `None` unless `iso` is a date alone (`2026-01-01`) or a date and `HH:MM`, optional `:SS` with
/// an optional fraction (`.5`), and an optional zone (`Z`, `+02:00`, `-0500`, `+02`), and nothing after.
fn tail_start(iso: &str) -> Option<usize> {
let b = iso.as_bytes();
let digits = |x: &[u8]| !x.is_empty() && x.iter().all(u8::is_ascii_digit);
let digits_at = |a: usize, z: usize| b.get(a..z).is_some_and(digits);
let at = |i: usize, c: u8| b.get(i) == Some(&c);
if !(digits_at(0, 4) && at(4, b'-') && digits_at(5, 7) && at(7, b'-') && digits_at(8, 10)) {
return None;
}
if b.len() == 10 {
return Some(10);
}
if !((at(10, b'T') || at(10, b' ')) && digits_at(11, 13) && at(13, b':') && digits_at(14, 16)) {
return None;
}
// the seconds are optional (`10:00+02:00`): without them the tail starts right after the minutes
let start = if !at(16, b':') {
16
} else if digits_at(17, 19) {
19
} else {
return None;
};
let mut zone = b.get(start..)?;
// a fraction only after the seconds: `10:00.5` is half a minute, not half a second
if let ([b'.', rest @ ..], 19) = (zone, start) {
let n = rest.iter().take_while(|c| c.is_ascii_digit()).count();
zone = rest.get(n..)?;
if n == 0 {
return None;
}
}
let ok = match zone {
[] | [b'Z'] => true,
[b'+' | b'-', h1, h2, b':', m1, m2] => digits(&[*h1, *h2, *m1, *m2]),
[b'+' | b'-', hm @ ..] => matches!(hm.len(), 2 | 4) && digits(hm),
_ => false,
};
ok.then_some(start)
}
/// Normalize user input to `YYYY-MM-DDTHH:MM:SS` (accepts a space instead of `T`, missing
/// seconds or time). `None` if it isn't a valid date.
pub fn normalize_iso(s: &str) -> Option<String> {
@@ -260,6 +304,65 @@ mod tests {
assert_eq!(iso_seconds("2026-01-01T10:00+02:00"), iso_seconds("2026-01-01T10:00"));
}
#[test]
fn shift_refuses_a_time_it_cant_fully_read() {
for bad in [
"2026-01-01T10:0",
"2026-01-01T10",
"2026-01-01T",
"2026-01-01T10:00:xx",
"2026-01-01T10:00:0",
"2026-01-01T10:00:00+",
"2026-01-01T10:00:00+2",
"2026-01-01T10:00:00+02:0",
"2026-01-01T10:00:00.",
"2026-01-01T10:00:00.5.5",
"2026-01-01T10:00.5",
"2026-01-01T10:00:00ZZ",
"2026-01-01T10:00:00 and more",
"2026-01-01T10:00 and more",
"2026-01-01x10:00:00",
"2026/01/01T10:00:00",
] {
assert_eq!(shift_iso(bad, 3600), None, "{bad} doesn't fully read, so it must not be written back");
}
// multi-byte characters where the time, the seconds and the zone start never panic
for at in [11, 16, 18, 21] {
let mut s = String::from("2026-01-01T10:00:00+02:00");
s.replace_range(at..at + 1, "é");
assert_eq!(shift_iso(&s, 3600), None, "{s}");
assert_eq!(shift_iso(s.get(..at + 2).unwrap(), 3600), None, "{s}");
}
}
#[test]
fn shift_keeps_a_fraction_and_zone_and_reads_back() {
for (from, to) in [
("2026-01-01", "2026-01-01T01:00:00"),
(" 2026-01-01T10:00 ", "2026-01-01T11:00:00"),
("2026-01-01 10:00:30", "2026-01-01T11:00:30"),
("2026-01-01T10:00:30.5", "2026-01-01T11:00:30.5"),
("2026-01-01T10:00:30Z", "2026-01-01T11:00:30Z"),
("2026-01-01T10:00:30+02:00", "2026-01-01T11:00:30+02:00"),
("2026-01-01T10:00:30-0500", "2026-01-01T11:00:30-0500"),
("2026-01-01T10:00:30+02", "2026-01-01T11:00:30+02"),
("2026-01-01T10:00:30.125+02:00", "2026-01-01T11:00:30.125+02:00"),
] {
assert_eq!(shift_iso(from, 3600).as_deref(), Some(to), "{from}");
assert_eq!(shift_iso(to, 0).as_deref(), Some(to), "{to} reads back");
}
}
/// Sorting, grouping and date rules read with `iso_seconds`, which stays lenient: only the
/// write path refuses what it can't fully read.
#[test]
fn reading_stays_lenient_for_sorting() {
let at_ten = iso_seconds("2026-01-01T10:00:00");
assert_eq!(iso_seconds("2026-01-01T10:00:00 and more"), at_ten);
assert_eq!(iso_seconds("2026-01-01T10:00:xx"), at_ten);
assert_eq!(iso_seconds("2026-01-01T10:0"), iso_seconds("2026-01-01"));
}
#[test]
fn impossible_times_are_rejected_not_rolled_over() {
for bad in ["2026-04-01T10:75:00", "2026-04-01 10:00:75", "2026-04-01T10:60", "2026-04-01T24:00:00", "2026-04-01T10:59:60"] {
+19 -2
View File
@@ -207,14 +207,31 @@ impl Catalog {
/// folder that is no longer there and are dropped (undo restores them). Empty when there is
/// nothing to carry or drop.
pub fn folder_records_follow(&self, from: &str, to: &str) -> Vec<Op> {
self.folder_records_carried(from, to, true)
}
/// [`Catalog::folder_records_follow`] for a folder located where it already is on disk
/// (`folder.updateLocation`): nothing arrived at `to`, the library only learned that the
/// folder is there. So what it knows about folders at or below `to` (other folders of the
/// library there) stays; a record carried over replaces the one at the same place.
pub fn folder_records_located(&self, from: &str, to: &str) -> Vec<Op> {
self.folder_records_carried(from, to, false)
}
fn folder_records_carried(&self, from: &str, to: &str, clear_destination: bool) -> Vec<Op> {
let (Some(root), Some(dest)) = (record_key(from), record_key(to)) else { return Vec::new() };
if root == dest {
return Vec::new();
}
// a folder located below itself: what is already at or below `to` belongs to the folders
// of the library there, not to the folder located, so it is neither carried nor cleared
// (the record of `from` itself still lands at `to`, replacing the one there)
let nested = !clear_destination && key_within(&dest, &root);
let carried = |k: &str| key_within(k, &root) && !(nested && key_within(k, &dest));
let moved: Vec<(String, FolderRecord)> = self
.folder_records
.iter()
.filter(|(k, _)| key_within(k, &root))
.filter(|(k, _)| carried(k))
.filter_map(|(k, r)| {
let rest = folder_rest(k, &root)?;
let base = dest.trim_end_matches('/');
@@ -224,7 +241,7 @@ impl Catalog {
.collect();
// what was known at the old place goes, and so does what is left at the new one (also
// when the moved folder carries nothing: the folder now there is not the one it was about)
let stale = self.folder_records.keys().filter(|k| key_within(k, &root) || key_within(k, &dest));
let stale = self.folder_records.keys().filter(|k| carried(k) || (clear_destination && key_within(k, &dest)));
let mut ops: Vec<Op> = stale.map(|k| Op::SetFolderRecord { folder: k.clone(), record: None }).collect();
ops.extend(moved.into_iter().map(|(k, r)| Op::SetFolderRecord { folder: k, record: Some(r) }));
ops
+48 -1
View File
@@ -263,14 +263,36 @@ fn newer(what: String) -> CatalogError {
CatalogError::Newer(format!("{what}; this version reads catalog format v{VERSION} and older"))
}
/// The most `resync` spends re-validating the suffixes of one line whose whole bytes are not valid
/// UTF-8 (a real fragment ends at any byte): one line of a modest malformed log that holds a start
/// of a record in every few bytes used to re-validate the whole remaining suffix at every attempt
/// (CWE-407). Past the budget the rest of the line stays a torn tail, which the damaged path keeps
/// and reports, same state as before, minus the CPU.
const RESYNC_BUDGET_BYTES: usize = 64 << 20; // 64 MiB
/// A line that doesn't decode but ends with a whole record: a fragment of a failed append followed
/// by the record that retried it (the retry re-encodes the same ops with the same `seq`s). Returns
/// the fragment's length and the record, if that record continues the log (`seq <= last + 1`).
/// The record's CRC must match, so damage is never mistaken for it.
fn resync(line: &[u8], last: u64) -> Option<(usize, (u64, Op))> {
const START: &[u8] = b"{\"seq\":";
// One record per line, so a line of valid UTF-8 holds a valid suffix at every record start and
// one validation covers every candidate; only a line that is not wholly valid re-checks, and
// then up to the budget rather than the suffix length times the candidate count.
let whole = std::str::from_utf8(line).ok();
let mut spent = 0usize;
(1..line.len().saturating_sub(START.len() - 1)).filter(|&i| line[i..].starts_with(START)).find_map(|i| {
let rec = std::str::from_utf8(&line[i..]).ok().map(|l| l.trim_end_matches('\r')).and_then(decode_record)?;
let text = match &whole {
Some(t) => &t[i..],
None => {
if spent >= RESYNC_BUDGET_BYTES {
return None;
}
spent = spent.saturating_add(line.len() - i);
std::str::from_utf8(&line[i..]).ok()?
}
};
let rec = decode_record(text.trim_end_matches('\r'))?;
(rec.0 <= last.saturating_add(1)).then_some((i, rec))
})
}
@@ -714,3 +736,28 @@ impl Drop for Journal {
}
}
}
#[cfg(test)]
mod tests_resync {
use super::*;
/// A torn first line may end at any byte and a failed append's retried records may follow its
/// own start `{"seq":` more than once: `resync` finds the CRC-valid record after a fragment of
/// many record starts. UTF-8 is validated once for a valid line, and for a line that isn't
/// wholly valid only up to the budget instead of the suffix length per candidate (CWE-407).
#[test]
fn resync_finds_the_retried_record_after_a_fragment_of_many_starts() {
let op = Op::Batch { ops: vec![] };
let record = encode_record(5, &op);
let mut line = Vec::from(b"\xf2" as &[u8]); // an invalid byte, so the whole line is not UTF-8
for i in 0..1024 {
line.extend_from_slice(format!("{{\"seq\":{},\"crc\":{{", i).as_bytes());
}
let fragment = line.len();
line.extend_from_slice(record.as_bytes());
assert_eq!(resync(&line, 4).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
// a retry is still recognised past `last`: the fragment logs nothing valid, but the CRC
// matches, so the double `Some` is only reached with `last >= 4`
assert_eq!(resync(&line, 100).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5)));
}
}
+37 -685
View File
@@ -48,7 +48,11 @@ pub fn reparent(k: &str, from: &str, to: &str) -> String {
/// name, its parents' and synonyms flat besides its path). Each once, cleaned.
pub fn from_file(flat: &[String], hierarchical: &[String]) -> Vec<String> {
let mut out: Vec<String> = hierarchical.iter().map(|k| clean(k)).collect();
out.extend(flat.iter().map(|k| clean(k)).filter(|k| !hierarchical.iter().any(|h| h.split(SEP).any(|level| same(level.trim(), k)))));
// One lowered set of every hierarchical level, not a search of `hierarchical` for each flat
// keyword: disjoint lists from sidecars made the old approach quadratic in both (CWE-407), and
// `same` allocates two lower-cased strings per comparison.
let levels: std::collections::HashSet<String> = hierarchical.iter().flat_map(|h| h.split(SEP).map(|l| l.trim().to_lowercase())).collect();
out.extend(flat.iter().map(|k| clean(k)).filter(|k| !levels.contains(&k.to_lowercase())));
dedupe(&mut out);
out
}
@@ -78,6 +82,9 @@ pub fn parse_keyword_list(text: &str) -> Result<Vec<(String, KeywordInfo)>> {
let mut out: Vec<(String, KeywordInfo)> = Vec::new();
// where each keyword is in `out`, by lower-case path (a search of `out` per line was quadratic)
let mut index: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
// synonyms already accepted, by keyword (a search of each keyword's growing synonym list per
// line was quadratic and re-allocated both spellings every comparison — CWE-407)
let mut synonyms: std::collections::HashMap<usize, std::collections::HashSet<String>> = std::collections::HashMap::new();
// the keyword at each level above the line: its path and where it is in `out`
let mut above: Vec<(String, usize)> = Vec::new();
for (i, line) in text.split('\n').enumerate() {
@@ -103,9 +110,9 @@ pub fn parse_keyword_list(text: &str) -> Result<Vec<(String, KeywordInfo)>> {
if synonym.contains(SEP) {
return Err(bad(n, "“|” separates a keyword's levels: a synonym can't hold one"));
}
if let Some((_, info)) = out.get_mut(at)
&& !synonym.is_empty()
&& !info.synonyms.iter().any(|s| same(s, synonym))
if !synonym.is_empty()
&& synonyms.entry(at).or_default().insert(synonym.to_lowercase())
&& let Some((_, info)) = out.get_mut(at)
{
info.synonyms.push(synonym.to_string());
}
@@ -264,7 +271,14 @@ impl Catalog {
let mut chain: Vec<usize> = Vec::new();
let mut path = String::new();
let mut lower = String::new();
for part in k.split(SEP).map(str::trim).filter(|s| !s.is_empty()) {
// Level paths hold their every prefix (`path` and `lower` both), so a photo's XMP
// keyword split far more levels than a list file accepts (`MAX_LEVELS`) made the
// stored prefixes quadratic in the level count: a keyword nests [MAX_LEVELS]
// levels here, as a list file would, and what lies below is left out (CWE-400).
for (part_n, part) in (1..).zip(k.split(SEP).map(str::trim).filter(|s| !s.is_empty())) {
if part_n > MAX_LEVELS {
break;
}
if !path.is_empty() {
path.push(SEP);
lower.push(SEP);
@@ -505,7 +519,24 @@ impl Catalog {
}
}
let mut file = KeywordListFile::default();
// The tree is capped at [`MAX_LEVELS`] (its level rows hold every level's prefix twice, so a
// synthetic keyword past that depth made the stored bytes quadratic); whatever lies deeper
// comes from the photos' and list's own spellings instead, named unwritable as before.
let mut over_deep: std::collections::HashSet<String> = Default::default();
for k in self.listed_keywords().map(|k| &k.path) {
if k.split(SEP).count() > MAX_LEVELS {
over_deep.insert(k.clone());
}
}
for p in self.photos().filter(|p| p.in_library()) {
for k in &p.meta.keywords {
if clean(k).split(SEP).count() > MAX_LEVELS {
over_deep.insert(k.clone());
}
}
}
write(self, &self.keyword_tree(), 0, &mut file);
file.unwritable.extend(over_deep);
file
}
@@ -791,683 +822,4 @@ impl Catalog {
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Filter, Photo, PhotoId, Source};
fn lib(kws: &[&[&str]]) -> (Catalog, Vec<PhotoId>) {
let mut c = Catalog::new();
let mut ids = Vec::new();
for k in kws {
let id = c.alloc_photo_id();
let mut p = Photo::new(id, Source::Demo { scene: 1 }, "a.jpg", "JPEG", 3, 2, "2026-01-01");
p.meta.keywords = k.iter().map(|s| s.to_string()).collect();
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
ids.push(id);
}
(c, ids)
}
fn kws(c: &Catalog, id: PhotoId) -> Vec<String> {
c.photo(id).unwrap().meta.keywords.clone()
}
#[test]
fn tree_counts_photos_per_level() {
let (c, _) = lib(&[&["travel|Italy|Rome", "beach"], &["Travel|italy"], &["travel|France", "travel|italy|rome"], &["beach"]]);
let t = c.keyword_tree();
assert_eq!(t.iter().map(|n| (n.name.as_str(), n.count)).collect::<Vec<_>>(), vec![("beach", 2), ("travel", 3)]);
let travel = &t[1];
assert_eq!(travel.children.iter().map(|n| (n.path.as_str(), n.count)).collect::<Vec<_>>(), vec![("travel|France", 1), ("travel|Italy", 3)]);
assert_eq!(travel.children[1].children[0].path, "travel|Italy|Rome");
assert_eq!(travel.children[1].children[0].count, 2);
// filtering by a parent finds its children
let f = Filter { keyword: Some("travel|italy".into()), ..Default::default() };
assert_eq!(c.query(&f, &Default::default()).len(), 3);
}
/// A keyword written twice on a photo, or in two spellings, counts the photo once; the next
/// photo with it counts again.
#[test]
fn tree_counts_a_repeated_keyword_once_per_photo() {
let (c, _) = lib(&[&["sea|Baltic", "sea|Baltic", "Sea|baltic"], &["sea|baltic"], &[]]);
let t = c.keyword_tree();
assert_eq!(tree_paths(&t), [("sea".to_string(), 2), ("sea|Baltic".to_string(), 2)]);
}
#[test]
fn rename_delete_merge_are_single_undoable_batches() {
let (mut c, ids) = lib(&[&["travel|italy|rome", "beach"], &["Travel|Italy"], &["italia", "travel|italy"], &["sea"]]);
let before = c.to_snapshot();
let op = c.rename_keyword_ops("travel|italy", "Europe|Italy").unwrap();
let Op::Batch { ops } = &op else { panic!() };
assert_eq!(ops.len(), 3, "only photos that change");
let inv = c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Europe|Italy|rome", "beach"]);
assert_eq!(kws(&c, ids[1]), ["Europe|Italy"]);
c.apply(inv).unwrap();
assert_eq!(c.to_snapshot(), before);
// merge `italia` into the existing hierarchical keyword: duplicates collapse
let op = c.merge_keywords_ops(&["italia".into()], "travel|italy").unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[2]), ["travel|italy"]);
// delete removes the keyword and its children everywhere
let op = c.delete_keyword_ops("TRAVEL").unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["beach"]);
assert!(kws(&c, ids[1]).is_empty());
assert_eq!(c.keywords(), vec![("beach".to_string(), 1), ("sea".to_string(), 1)]);
// invalid requests
assert!(c.rename_keyword_ops("beach", " ").is_err());
assert!(c.rename_keyword_ops("a", "a|b").is_err());
assert!(c.merge_keywords_ops(&["a".into()], "a|b").is_err());
assert_eq!(clean(" a | |b "), "a|b");
}
fn tree_paths(nodes: &[KeywordNode]) -> Vec<(String, usize)> {
let mut out = Vec::new();
for n in nodes {
out.push((n.path.clone(), n.count));
out.extend(tree_paths(&n.children));
}
out
}
/// A keyword can be listed before any photo has it (Lightroom Classic's Create Keyword Tag):
/// it is in the tree with no photos, its parents too, and undo takes it away.
#[test]
fn a_keyword_listed_with_no_photos_is_in_the_tree() {
let (mut c, _) = lib(&[&["travel|France"]]);
let undo = c.apply(Op::SetKeyword { path: " travel | Italy ".into(), info: Some(KeywordInfo::default()) }).unwrap();
assert_eq!(tree_paths(&c.keyword_tree()), [("travel".to_string(), 1), ("travel|France".to_string(), 1), ("travel|Italy".to_string(), 0)]);
assert_eq!(c.keyword_info("TRAVEL|italy"), Some(&KeywordInfo::default()), "found whatever the case");
c.apply(undo).unwrap();
assert_eq!(tree_paths(&c.keyword_tree()), [("travel".to_string(), 1), ("travel|France".to_string(), 1)]);
assert_eq!(c.keyword_info("travel|Italy"), None);
}
/// A listed keyword needs a name, and its attributes start as Lightroom Classic's do: exported,
/// with the keywords containing it and its synonyms; not a person.
#[test]
fn a_listed_keyword_needs_a_name_and_starts_exported() {
let mut c = Catalog::new();
assert!(c.apply(Op::SetKeyword { path: " | ".into(), info: Some(KeywordInfo::default()) }).is_err());
let info = KeywordInfo::default();
assert!(info.include_on_export && info.export_containing && info.export_synonyms && !info.person && info.synonyms.is_empty());
}
/// Changing a listed keyword's attributes is undone to the attributes it had, under the name as
/// it was written.
#[test]
fn changing_a_listed_keyword_is_undone_to_what_it_was() {
let mut c = Catalog::new();
c.apply(Op::SetKeyword { path: "Weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
let person = KeywordInfo { person: true, synonyms: vec!["Marriage".into()], ..KeywordInfo::default() };
let undo = c.apply(Op::SetKeyword { path: "weddings".into(), info: Some(person.clone()) }).unwrap();
assert_eq!(c.keyword_info("Weddings"), Some(&person));
assert_eq!(undo, Op::SetKeyword { path: "Weddings".into(), info: Some(KeywordInfo::default()) });
c.apply(undo).unwrap();
assert_eq!(c.keyword_info("weddings"), Some(&KeywordInfo::default()));
}
fn listed(c: &Catalog) -> Vec<(String, KeywordInfo)> {
let mut v: Vec<(String, KeywordInfo)> = c.listed_keywords().map(|k| (k.path.clone(), k.info.clone())).collect();
v.sort_by_key(|(p, _)| p.to_lowercase());
v
}
fn with_synonyms(words: &[&str]) -> KeywordInfo {
KeywordInfo { synonyms: words.iter().map(|w| w.to_string()).collect(), ..KeywordInfo::default() }
}
/// Renaming (or moving) a keyword takes its attributes and its listed children along, photos
/// or not, in the same undo step.
#[test]
fn renaming_a_keyword_carries_its_listing_along() {
let (mut c, ids) = lib(&[&["travel|italy"]]);
c.apply(Op::SetKeyword { path: "travel".into(), info: Some(with_synonyms(&["trip"])) }).unwrap();
c.apply(Op::SetKeyword { path: "travel|Spain".into(), info: Some(KeywordInfo::default()) }).unwrap();
let before = c.to_snapshot();
let op = c.rename_keyword_ops("Travel", "Places|Europe").unwrap();
let undo = c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Places|Europe|italy"]);
assert_eq!(
listed(&c),
[("Places|Europe".to_string(), with_synonyms(&["trip"])), ("Places|Europe|Spain".to_string(), KeywordInfo::default())]
);
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
}
/// A keyword only the list holds (no photos) can be renamed too.
#[test]
fn a_keyword_without_photos_can_be_renamed() {
let mut c = Catalog::new();
c.apply(Op::SetKeyword { path: "weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
let op = c.rename_keyword_ops("weddings", "Events|Weddings").unwrap();
c.apply(op).unwrap();
assert_eq!(listed(&c), [("Events|Weddings".to_string(), KeywordInfo::default())]);
}
/// Merging keeps the target's attributes and adds the merged keyword's synonyms to them; a target
/// not listed yet takes the merged keyword's attributes.
#[test]
fn merging_keeps_the_targets_attributes_and_gathers_synonyms() {
let (mut c, _) = lib(&[&["holiday"], &["travel"]]);
let person = KeywordInfo { person: true, ..with_synonyms(&["trip"]) };
c.apply(Op::SetKeyword { path: "travel".into(), info: Some(person.clone()) }).unwrap();
c.apply(Op::SetKeyword {
path: "holiday".into(),
info: Some(KeywordInfo { include_on_export: false, ..with_synonyms(&["vacation", "Trip"]) }),
})
.unwrap();
let op = c.merge_keywords_ops(&["holiday".into()], "travel").unwrap();
c.apply(op).unwrap();
assert_eq!(listed(&c), [("travel".to_string(), KeywordInfo { person: true, ..with_synonyms(&["trip", "vacation"]) })]);
// onto a keyword that isn't listed: it takes the merged one's attributes
let mut c = Catalog::new();
c.apply(Op::SetKeyword { path: "holiday".into(), info: Some(with_synonyms(&["vacation"])) }).unwrap();
let op = c.merge_keywords_ops(&["holiday".into()], "Travel").unwrap();
c.apply(op).unwrap();
assert_eq!(listed(&c), [("Travel".to_string(), with_synonyms(&["vacation"]))]);
}
/// Deleting a keyword takes it, and the keywords below it, off the list as well as off photos.
#[test]
fn deleting_a_keyword_takes_it_off_the_list() {
let (mut c, _) = lib(&[&["travel|italy"], &["beach"]]);
for path in ["travel", "travel|spain", "beach"] {
c.apply(Op::SetKeyword { path: path.into(), info: Some(KeywordInfo::default()) }).unwrap();
}
let before = c.to_snapshot();
let op = c.delete_keyword_ops("travel").unwrap();
let undo = c.apply(op).unwrap();
assert_eq!(listed(&c), [("beach".to_string(), KeywordInfo::default())]);
assert_eq!(tree_paths(&c.keyword_tree()), [("beach".to_string(), 1)]);
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
}
/// Creating a keyword lists it with its attributes, and can tag photos with it in the same undo
/// step. A keyword that exists already (listed, or on a photo) isn't created again.
#[test]
fn creating_a_keyword_lists_it_and_can_tag_photos() {
let (mut c, ids) = lib(&[&["beach"], &[]]);
let before = c.to_snapshot();
let op = c.create_keyword_ops("Events | Weddings", with_synonyms(&["marriage"]), &[ids[1]]).unwrap();
let undo = c.apply(op).unwrap();
assert_eq!(listed(&c), [("Events|Weddings".to_string(), with_synonyms(&["marriage"]))]);
assert_eq!(kws(&c, ids[1]), ["Events|Weddings"]);
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
for exists in ["BEACH", "events|weddings"] {
if exists == "events|weddings" {
let op = c.create_keyword_ops("Events|Weddings", KeywordInfo::default(), &[]).unwrap();
c.apply(op).unwrap();
}
assert!(c.create_keyword_ops(exists, KeywordInfo::default(), &[]).is_err(), "{exists}");
}
assert!(c.create_keyword_ops(" | ", KeywordInfo::default(), &[]).is_err());
}
/// Moving a keyword nests it inside another (or takes it to the top level), with its children,
/// on photos and in the list. It can't go inside itself or one of its children, and moving it
/// where it already is changes nothing.
#[test]
fn moving_a_keyword_nests_it_inside_another() {
let (mut c, ids) = lib(&[&["Italy|Rome"], &["Europe"]]);
// typed in any case, the keywords keep the spelling the library has
let op = c.move_keyword_ops("italy", Some("EUROPE"), false).unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Europe|Italy|Rome"]);
let op = c.move_keyword_ops("europe|italy", None, false).unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Italy|Rome"], "back at the top level");
assert!(c.move_keyword_ops("italy", Some("italy|rome"), false).is_err(), "inside its own child");
assert!(c.move_keyword_ops("italy", Some("Italy"), false).is_err(), "inside itself");
assert_eq!(c.move_keyword_ops("italy|rome", Some("italy"), false).unwrap(), Op::Batch { ops: vec![] }, "already there");
assert!(c.move_keyword_ops("lisbon", Some("europe"), false).is_err(), "no such keyword");
}
/// Moving onto a name that is taken (Europe already has a Rome) merges the two, so the move
/// asks first: refused unless merging is allowed.
#[test]
fn moving_onto_a_taken_name_merges_only_when_allowed() {
let (mut c, ids) = lib(&[&["rome"], &["europe|rome"]]);
let err = c.move_keyword_ops("rome", Some("europe"), false).unwrap_err();
assert!(matches!(err, CatalogError::KeywordExists(ref k) if k == "europe|rome"), "{err:?}");
let op = c.move_keyword_ops("rome", Some("europe"), true).unwrap();
c.apply(op).unwrap();
assert_eq!((kws(&c, ids[0]), kws(&c, ids[1])), (vec!["europe|rome".to_string()], vec!["europe|rome".to_string()]));
}
/// Editing a keyword renames it (its last level: it stays where it is) and sets its attributes,
/// in one undo step. A name that is taken is refused: merging is its own action.
#[test]
fn editing_a_keyword_renames_it_and_sets_its_attributes() {
let (mut c, ids) = lib(&[&["travel|italy"], &["travel|spain"]]);
let before = c.to_snapshot();
let person = KeywordInfo { person: true, ..KeywordInfo::default() };
let op = c.edit_keyword_ops("travel|italy", "Italia", person.clone()).unwrap();
let undo = c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["travel|Italia"]);
assert_eq!(c.keyword_info("travel|italia"), Some(&person));
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
// attributes alone
let op = c.edit_keyword_ops("travel", "travel", with_synonyms(&["trip"])).unwrap();
c.apply(op).unwrap();
assert_eq!(listed(&c), [("travel".to_string(), with_synonyms(&["trip"]))]);
assert!(matches!(c.edit_keyword_ops("travel|italy", "Spain", KeywordInfo::default()), Err(CatalogError::KeywordExists(_))));
assert!(c.edit_keyword_ops("travel|italy", "a|b", KeywordInfo::default()).is_err(), "a name, not a path");
assert!(c.edit_keyword_ops("travel|italy", " ", KeywordInfo::default()).is_err());
}
/// Purging takes off the list the keywords no photo has (nor any keyword below them), in one
/// undo step; keywords photos carry stay.
#[test]
fn purging_takes_unused_keywords_off_the_list() {
let (mut c, _) = lib(&[&["travel|italy"]]);
for path in ["travel", "travel|italy", "travel|spain", "weddings"] {
c.apply(Op::SetKeyword { path: path.into(), info: Some(KeywordInfo::default()) }).unwrap();
}
let op = c.purge_unused_keywords_ops();
c.apply(op).unwrap();
assert_eq!(listed(&c).iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(), ["travel", "travel|italy"]);
assert_eq!(tree_paths(&c.keyword_tree()), [("travel".to_string(), 1), ("travel|italy".to_string(), 1)]);
}
/// Renaming matches names whatever their case, also where a letter's case changes its length
/// (ẞ is three bytes, ß two): the levels below are kept whole, never cut mid-letter.
#[test]
fn renaming_keeps_the_levels_below_whatever_the_case() {
let (mut c, ids) = lib(&[&["straße|nord"], &["ßa|ü"]]);
let op = c.rename_keyword_ops("STRAẞE", "Road").unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Road|nord"]);
let op = c.rename_keyword_ops("ẞA", "Weg").unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[1]), ["Weg|ü"]);
}
fn exported(c: &Catalog, keywords: &[&str]) -> (Vec<String>, Vec<String>) {
let e = c.export_keywords(&keywords.iter().map(|k| k.to_string()).collect::<Vec<_>>());
(e.flat, e.hierarchical)
}
/// By default a keyword is exported as its name together with the keywords containing it (flat,
/// `dc:subject`), and as its full path (`lr:hierarchicalSubject`); each name once.
#[test]
fn a_keyword_exports_its_name_its_parents_and_its_path() {
let c = Catalog::new();
let (flat, paths) = exported(&c, &["travel|Italy|Rome", "Travel|Spain", "beach"]);
assert_eq!(flat, ["Rome", "Italy", "travel", "Spain", "beach"]);
assert_eq!(paths, ["travel|Italy|Rome", "Travel|Spain", "beach"]);
}
/// A keyword not included on export is left out, path and all; a parent left out (a keyword that
/// only organizes others) isn't exported as a containing keyword, but its children are.
#[test]
fn keywords_left_out_of_export_stay_out() {
let mut c = Catalog::new();
let out = KeywordInfo { include_on_export: false, ..KeywordInfo::default() };
c.apply(Op::SetKeyword { path: "Places".into(), info: Some(out.clone()) }).unwrap();
c.apply(Op::SetKeyword { path: "draft".into(), info: Some(out) }).unwrap();
let (flat, paths) = exported(&c, &["Places|Lisbon", "draft"]);
assert_eq!(flat, ["Lisbon"]);
assert_eq!(paths, ["Places|Lisbon"]);
}
/// Without "export containing keywords" only the keyword's own name goes out flat; synonyms go
/// out with it unless "export synonyms" is off.
#[test]
fn containing_keywords_and_synonyms_follow_their_options() {
let mut c = Catalog::new();
let alone = KeywordInfo { export_containing: false, ..with_synonyms(&["Lisboa"]) };
c.apply(Op::SetKeyword { path: "Places|Lisbon".into(), info: Some(alone) }).unwrap();
let quiet = KeywordInfo { export_synonyms: false, ..with_synonyms(&["marriage"]) };
c.apply(Op::SetKeyword { path: "Events|Weddings".into(), info: Some(quiet) }).unwrap();
let (flat, _) = exported(&c, &["Places|Lisbon", "Events|Weddings"]);
assert_eq!(flat, ["Lisbon", "Lisboa", "Weddings", "Events"]);
}
/// Names match whatever the case of any letter, not only ASCII ones: changing only the case of
/// "Ärzte" is a rename, not a clash with itself, and moving it where it is changes nothing.
#[test]
fn names_match_whatever_the_case_of_any_letter() {
let (mut c, ids) = lib(&[&["Ärzte|Wien"]]);
let op = c.edit_keyword_ops("ärzte", "ÄRZTE", KeywordInfo::default()).unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["ÄRZTE|Wien"]);
assert_eq!(c.move_keyword_ops("ärzte|wien", Some("ärzte"), false).unwrap(), Op::Batch { ops: vec![] });
let op = c.rename_keyword_ops("ärzte", "Ärzte").unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Ärzte|Wien"]);
assert!(c.create_keyword_ops("ärzte", KeywordInfo::default(), &[]).is_err(), "exists");
}
/// A keyword that is only the parent of a listed one ("Events" of "Events|Weddings") is a
/// keyword like any other: it is in the tree, so it can be found, moved and renamed.
#[test]
fn the_parent_of_a_listed_keyword_is_a_keyword() {
let mut c = Catalog::new();
c.apply(Op::SetKeyword { path: "Events|Weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
assert!(c.has_keyword("events"));
assert_eq!(c.keyword_path("EVENTS").as_deref(), Some("Events"));
let op = c.edit_keyword_ops("events", "Occasions", KeywordInfo::default()).unwrap();
c.apply(op).unwrap();
assert_eq!(tree_paths(&c.keyword_tree()), [("Occasions".to_string(), 0), ("Occasions|Weddings".to_string(), 0)]);
}
/// Photos in Recently Deleted don't count: a keyword only they have isn't in the tree, so it
/// can be created again and is purged as unused, and its spelling there isn't the library's.
#[test]
fn deleted_photos_dont_hold_keywords() {
let (mut c, ids) = lib(&[&["Weddings"], &["travel"]]);
c.apply(Op::SetDeleted { id: ids[0], deleted: true }).unwrap();
assert!(!c.has_keyword("weddings"));
assert!(c.create_keyword_ops("weddings", KeywordInfo::default(), &[]).is_ok());
c.apply(Op::SetKeyword { path: "Weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
let op = c.purge_unused_keywords_ops();
c.apply(op).unwrap();
assert!(listed(&c).is_empty(), "only a deleted photo has it: unused");
}
/// Merging several keywords moves each keyword under them by the closest one, whatever the
/// order they are given in, and every listing lands where its keyword does: one landing where
/// another is about to leave isn't merged into it.
#[test]
fn merging_overlapping_keywords_keeps_every_listing() {
let (mut c, ids) = lib(&[&["a|b|c"], &["a|c"]]);
let person = KeywordInfo { person: true, ..KeywordInfo::default() };
c.apply(Op::SetKeyword { path: "a|b|c".into(), info: Some(person.clone()) }).unwrap();
c.apply(Op::SetKeyword { path: "a|c".into(), info: Some(with_synonyms(&["sea"])) }).unwrap();
let op = c.merge_keywords_ops(&["a|b".into(), "a|c".into()], "a").unwrap();
c.apply(op).unwrap();
assert_eq!((kws(&c, ids[0]), kws(&c, ids[1])), (vec!["a|c".to_string()], vec!["a".to_string()]));
assert_eq!(listed(&c), [("a".to_string(), with_synonyms(&["sea"])), ("a|c".to_string(), person)]);
// the order of the keywords merged doesn't matter
let merged = |from: [&str; 2]| {
let (mut c, ids) = lib(&[&["a|b|c", "a|d"]]);
let op = c.merge_keywords_ops(&from.map(String::from), "x").unwrap();
c.apply(op).unwrap();
kws(&c, ids[0])
};
assert_eq!(merged(["a", "a|b"]), merged(["a|b", "a"]));
assert_eq!(merged(["a", "a|b"]), ["x|c", "x|d"]);
}
/// One keyword at most is where new keywords go (Put New Keywords Inside This Keyword). Making
/// another one so is one undo step; the mark moves with its keyword (also into a merge) and
/// goes with it.
#[test]
fn one_keyword_is_where_new_keywords_go() {
let (mut c, _) = lib(&[&["Events|Weddings"], &["Travel"]]);
let op = c.set_default_parent_ops(Some("events")).unwrap();
let undo = c.apply(op).unwrap();
assert_eq!(c.default_keyword_parent().as_deref(), Some("Events"));
let op = c.set_default_parent_ops(Some("travel")).unwrap();
c.apply(op).unwrap();
assert_eq!(c.default_keyword_parent().as_deref(), Some("Travel"), "only one");
assert!(c.set_default_parent_ops(Some("lisbon")).is_err());
let op = c.rename_keyword_ops("travel", "Trips").unwrap();
c.apply(op).unwrap();
assert_eq!(c.default_keyword_parent().as_deref(), Some("Trips"));
let op = c.merge_keywords_ops(&["trips".into()], "Events").unwrap();
c.apply(op).unwrap();
assert_eq!(c.default_keyword_parent().as_deref(), Some("Events"), "into the merge");
let op = c.delete_keyword_ops("events").unwrap();
c.apply(op).unwrap();
assert_eq!(c.default_keyword_parent(), None);
let op = c.set_default_parent_ops(None).unwrap();
assert_eq!(op, Op::Batch { ops: vec![] }, "none to clear");
c.apply(undo).unwrap();
assert_eq!(c.default_keyword_parent(), None, "undo of the first: none was");
}
/// A file's keywords as a photo carries them: the paths of `lr:hierarchicalSubject`, and the
/// names of `dc:subject` that aren't levels of those paths (an exported `travel|Italy` comes
/// back as one keyword, not three). Without paths, the names as they are.
#[test]
fn a_files_keywords_keep_their_hierarchy() {
let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(from_file(&v(&["Rome", "Italy", "travel", "beach"]), &v(&["travel|Italy|Rome"])), ["travel|Italy|Rome", "beach"]);
assert_eq!(from_file(&v(&["ROME"]), &v(&["travel|Rome", " travel | rome "])), ["travel|Rome"], "each once, cleaned");
assert_eq!(from_file(&v(&["beach", " sea "]), &[]), ["beach", "sea"]);
assert_eq!(from_file(&v(&["a|b"]), &[]), ["a|b"], "LightCraft's own sidecars write paths flat");
}
/// A new keyword inside one the library has takes the library's spelling of it: creating
/// "TRAVEL|rome" next to "travel|italy" doesn't respell "travel".
#[test]
fn a_new_keyword_keeps_the_spelling_of_its_parents() {
let (mut c, _) = lib(&[&["travel|italy"]]);
let op = c.create_keyword_ops("TRAVEL|Rome", KeywordInfo::default(), &[]).unwrap();
c.apply(op).unwrap();
assert_eq!(listed(&c).iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(), ["travel|Rome"]);
assert_eq!(tree_paths(&c.keyword_tree())[0].0, "travel");
}
/// An edit that changes nothing is nothing: no listing, no undo step.
#[test]
fn an_edit_that_changes_nothing_is_nothing() {
let (mut c, _) = lib(&[&["beach"]]);
assert_eq!(c.edit_keyword_ops("beach", "beach", KeywordInfo::default()).unwrap(), Op::Batch { ops: vec![] });
c.apply(Op::SetKeyword { path: "beach".into(), info: Some(with_synonyms(&["shore"])) }).unwrap();
assert_eq!(c.edit_keyword_ops("BEACH", "beach", with_synonyms(&["shore"])).unwrap(), Op::Batch { ops: vec![] });
// renamed with the default attributes: the photos change, nothing is listed
let (mut c, _) = lib(&[&["beach"]]);
let op = c.edit_keyword_ops("beach", "Shore", KeywordInfo::default()).unwrap();
c.apply(op).unwrap();
assert!(listed(&c).is_empty());
}
/// Typing suggests keywords no photo has yet too (created in the Keyword List).
#[test]
fn suggestions_include_keywords_without_photos() {
let (mut c, _) = lib(&[&["beach"]]);
c.apply(Op::SetKeyword { path: "Events|Weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
assert_eq!(c.keyword_suggestions(&[], "wed", 5), ["Events|Weddings"]);
assert!(!c.keyword_suggestions(&["events|weddings".into()], "wed", 5).contains(&"Events|Weddings".to_string()), "not one it has");
}
/// A new name typed for a photo goes inside the default parent; a keyword the library has, and
/// a path typed whole, don't.
#[test]
fn typed_new_keywords_go_inside_the_default_parent() {
let (mut c, _) = lib(&[&["beach"], &["Events"]]);
assert_eq!(c.typed_keyword(" Weddings "), "Weddings", "no default parent");
let op = c.set_default_parent_ops(Some("events")).unwrap();
c.apply(op).unwrap();
assert_eq!(c.typed_keyword("Weddings"), "Events|Weddings");
assert_eq!(c.typed_keyword("BEACH"), "BEACH", "the library has it");
assert_eq!(c.typed_keyword("Places|Lisbon"), "Places|Lisbon");
}
/// The keyword list as a text file, as Lightroom Classic writes one: a keyword a line, the
/// keywords inside it indented one tab more, a synonym in braces on a line of its own under its
/// keyword, a keyword left out of export in square brackets; by name.
#[test]
fn the_keyword_list_is_written_as_tab_indented_text() {
let (mut c, _) = lib(&[&["Places|Lisbon", "beach"]]);
c.apply(Op::SetKeyword { path: "Places".into(), info: Some(KeywordInfo { include_on_export: false, ..KeywordInfo::default() }) }).unwrap();
c.apply(Op::SetKeyword { path: "Places|Lisbon".into(), info: Some(with_synonyms(&["Lisboa"])) }).unwrap();
c.apply(Op::SetKeyword { path: "Events|Weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
assert_eq!(c.keyword_list_text().text, "beach\nEvents\n\tWeddings\n[Places]\n\tLisbon\n\t\t{Lisboa}\n");
}
/// Reading a list gives each keyword's path and attributes: what was written comes back, and a
/// file from elsewhere (Windows line ends, a byte-order mark, blank lines) reads too.
#[test]
fn a_keyword_list_reads_back() {
let read = parse_keyword_list("\u{feff}beach\r\n\r\nEvents\r\n\tWeddings\r\n\t\t{marriage}\r\n[Places]\r\n\tLisbon\r\n").unwrap();
let out = KeywordInfo { include_on_export: false, ..KeywordInfo::default() };
assert_eq!(
read,
[
("beach".to_string(), KeywordInfo::default()),
("Events".to_string(), KeywordInfo::default()),
("Events|Weddings".to_string(), with_synonyms(&["marriage"])),
("Places".to_string(), out),
("Places|Lisbon".to_string(), KeywordInfo::default()),
]
);
}
/// Photo Supreme's Formatted Vocabulary File is the same format: plain text with Windows line
/// ends and no byte-order mark, a top-level category in square brackets (an organizing keyword,
/// left out of export), keywords a tab further in at each level.
#[test]
fn a_photo_supreme_vocabulary_file_reads() {
let file = "[Places]\r\n\tPortugal\r\n\t\tLisbon\r\n\t\t\tAlfama\r\n\t\tPorto\r\n\tSpain\r\n\t\tSeville\r\n";
let read = parse_keyword_list(file).unwrap();
let paths: Vec<&str> = read.iter().map(|(p, _)| p.as_str()).collect();
assert_eq!(
paths,
["Places", "Portugal", "Portugal|Lisbon", "Portugal|Lisbon|Alfama", "Portugal|Porto", "Spain", "Spain|Seville"]
.map(|p| if p == "Places" { p.to_string() } else { format!("Places|{p}") })
);
assert!(!read[0].1.include_on_export, "the category organizes: it isn't exported");
assert!(read[1..].iter().all(|(_, i)| i.include_on_export));
}
/// A list that can't be read says which line and why, and nothing of it is taken.
#[test]
fn a_bad_keyword_list_says_which_line() {
let err = |text: &str| parse_keyword_list(text).unwrap_err().to_string();
assert!(err("Events\n\t\tWeddings\n").contains("line 2"), "two levels down at once");
assert!(err("{marriage}\n").contains("line 1"), "a synonym of nothing");
assert!(err("Events\nTravel|Lisbon\n").contains("line 2"), "“|” separates levels here");
let deep: String = (0..70).map(|i| format!("{}k{i}\n", "\t".repeat(i))).collect();
assert!(err(&deep).contains("line 65"), "a file is input: 64 levels at most");
}
/// Files from elsewhere read as they were meant or say why not: classic Mac line ends (a lone
/// carriage return) are lines; indenting with spaces, which would flatten the hierarchy, is
/// refused at its line; so are control characters in a name and "|" in a synonym.
#[test]
fn a_keyword_list_from_elsewhere_reads_or_says_why_not() {
let paths = |text: &str| parse_keyword_list(text).unwrap().into_iter().map(|(p, _)| p).collect::<Vec<_>>();
assert_eq!(paths("Events\r\tWeddings\rPlaces\r"), ["Events", "Events|Weddings", "Places"]);
let err = |text: &str| parse_keyword_list(text).unwrap_err().to_string();
assert!(err("Events\n Weddings\n").contains("line 2"), "space indentation");
assert!(err("Events\n\t Weddings\n").contains("line 2"), "a space after the tabs");
assert!(err("Events\nx\u{0}y\n").contains("line 2"), "a control character");
assert!(err("Events\n\t{sea|shore}\n").contains("line 2"), "“|” in a synonym");
}
/// A keyword repeated in another case is one keyword, and the keywords inside either take the
/// first spelling.
#[test]
fn a_repeated_keyword_keeps_its_first_spelling() {
let read = parse_keyword_list("Events\n\tWeddings\nevents\n\tBirthdays\n").unwrap();
assert_eq!(read.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(), ["Events", "Events|Weddings", "Events|Birthdays"]);
}
/// What the list can't hold is left out and named, so the file always reads back: a name the
/// format would read as something else (in brackets or braces), one with a line break, a
/// synonym with one, a keyword nested deeper than a list goes; and the keywords inside one left
/// out go with it.
#[test]
fn an_exported_keyword_list_always_reads_back() {
let deep = (0..=MAX_LEVELS).map(|i| format!("level {i}")).collect::<Vec<_>>().join("|");
let (mut c, _) = lib(&[&["Travel|[draft]", "{todo}|Lisbon", "Weddings", "Line\nbreak", deep.as_str()]]);
c.apply(Op::SetKeyword { path: "Weddings".into(), info: Some(with_synonyms(&["marriage", "two\nlines"])) }).unwrap();
let KeywordListFile { text, unwritable, .. } = c.keyword_list_text();
let read = parse_keyword_list(&text).unwrap_or_else(|e| panic!("{e}\n{text}"));
assert!(read.iter().any(|(p, _)| p == "Travel"));
assert!(read.iter().all(|(p, _)| !p.contains("draft") && !p.contains("todo") && !p.contains("Line")), "{text}");
let weddings = read.iter().find(|(p, _)| p == "Weddings").map(|(_, i)| i.synonyms.clone());
assert_eq!(weddings, Some(vec!["marriage".to_string()]));
let deepest = read.iter().map(|(p, _)| p.split(SEP).count()).max();
assert_eq!(deepest, Some(MAX_LEVELS));
assert!(unwritable.contains(&"Travel|[draft]".to_string()), "{unwritable:?}");
assert!(unwritable.contains(&"{todo}".to_string()), "{unwritable:?}");
assert!(unwritable.contains(&"Line\nbreak".to_string()), "{unwritable:?}");
assert!(unwritable.contains(&"Weddings {two\nlines}".to_string()), "{unwritable:?}");
assert!(unwritable.iter().any(|u| u.ends_with(&format!("level {MAX_LEVELS}"))), "{unwritable:?}");
}
/// The list leaves out only what it must, and names only what's lost: a name starting with a
/// byte-order mark would lose it, but a synonym in braces reads back, and a synonym that's empty
/// or another's in a different case is no loss. It also says which keywords it wrote.
#[test]
fn an_exported_keyword_list_names_only_what_it_loses() {
let (mut c, _) = lib(&[&["\u{feff}Albums", "{draft", "Weddings"]]);
c.apply(Op::SetKeyword { path: "Weddings".into(), info: Some(with_synonyms(&["Marriage", "marriage", " ", "{vows}"])) }).unwrap();
let out = c.keyword_list_text();
let read = parse_keyword_list(&out.text).unwrap_or_else(|e| panic!("{e}\n{}", out.text));
assert_eq!(out.unwritable, ["\u{feff}Albums"]);
assert_eq!(out.written, ["Weddings", "{draft"]);
assert_eq!(read.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(), ["Weddings", "{draft"]);
let weddings = read.iter().find(|(p, _)| p == "Weddings").map(|(_, i)| i.synonyms.clone());
assert_eq!(weddings, Some(vec!["Marriage".to_string(), "{vows}".to_string()]));
}
/// A big list reads and imports at once, against a big library too: 40,000 keywords used to take
/// half a minute to read, and checking 5,000 new ones against 20,000 photos over a minute, with
/// the app frozen.
#[test]
fn a_big_keyword_list_imports_quickly() {
let mut text = String::new();
for g in 0..400 {
text.push_str(&format!("group {g}\n"));
for k in 0..99 {
text.push_str(&format!("\tkeyword {g}-{k}\n"));
}
}
let t0 = std::time::Instant::now();
let read = parse_keyword_list(&text).unwrap();
assert_eq!(read.len(), 40_000);
let mut c = Catalog::new();
let mut ops = Vec::new();
for i in 0..20_000u32 {
let id = c.alloc_photo_id();
let mut p = Photo::new(id, Source::Demo { scene: 1 }, "a.jpg", "JPEG", 3, 2, "2026-01-01");
p.meta.keywords = (0..5).map(|k| format!("library {}|tag {}", k, (i + k) % 3000)).collect();
ops.push(Op::AddPhoto { photo: Box::new(p) });
}
c.apply(Op::Batch { ops }).unwrap();
let (op, added, _) = c.import_keywords_ops(&read[..5_000]);
c.apply(op).unwrap();
assert_eq!(added, 5_000);
let took = t0.elapsed();
assert!(took < std::time::Duration::from_secs(10), "{took:?}");
}
/// Importing a list adds the keywords the library doesn't have, with their attributes, and gives
/// those it has the list's synonyms (their own attributes stay), in one undo step.
#[test]
fn importing_a_keyword_list_adds_what_is_missing() {
let (mut c, _) = lib(&[&["Events|Weddings"]]);
c.apply(Op::SetKeyword { path: "Events|Weddings".into(), info: Some(KeywordInfo { person: true, ..with_synonyms(&["marriage"]) }) }).unwrap();
let before = c.to_snapshot();
let read = parse_keyword_list("events\n\tweddings\n\t\t{nuptials}\n\tBirthdays\n[Drafts]\n").unwrap();
let (op, added, updated) = c.import_keywords_ops(&read);
assert_eq!((added, updated), (2, 1));
let undo = c.apply(op).unwrap();
assert_eq!(c.keyword_info("Events|Weddings"), Some(&KeywordInfo { person: true, ..with_synonyms(&["marriage", "nuptials"]) }));
assert!(c.has_keyword("Events|Birthdays"));
assert_eq!(
listed(&c).iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(),
["Drafts", "Events|Birthdays", "Events|Weddings"],
"in the library's spelling"
);
assert!(!c.keyword_info("Drafts").unwrap().include_on_export);
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
}
#[test]
fn suggestions_rank_co_occurrence_and_prefixes() {
let (c, _) = lib(&[&["dog", "park"], &["dog", "park", "ball"], &["dog", "beach"], &["cat"], &["cat"], &["cat"], &["parade"], &["eagle"]]);
// co-occurring with `dog` first (park twice), then the most used
let s = c.keyword_suggestions(&["dog".into()], "", 3);
assert_eq!(s, ["park", "ball", "beach"]);
let s = c.keyword_suggestions(&[], "", 2);
assert_eq!(s, ["cat", "dog"]);
let s = c.keyword_suggestions(&["park".into()], "pa", 5);
assert_eq!(s, ["parade"]);
let s = c.keyword_suggestions(&[], "E", 5);
assert_eq!(s, ["eagle", "beach", "parade"], "prefix matches before substring matches");
}
}
mod tests;
+706
View File
@@ -0,0 +1,706 @@
use super::*;
use crate::{Filter, Photo, PhotoId, Source};
fn lib(kws: &[&[&str]]) -> (Catalog, Vec<PhotoId>) {
let mut c = Catalog::new();
let mut ids = Vec::new();
for k in kws {
let id = c.alloc_photo_id();
let mut p = Photo::new(id, Source::Demo { scene: 1 }, "a.jpg", "JPEG", 3, 2, "2026-01-01");
p.meta.keywords = k.iter().map(|s| s.to_string()).collect();
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
ids.push(id);
}
(c, ids)
}
fn kws(c: &Catalog, id: PhotoId) -> Vec<String> {
c.photo(id).unwrap().meta.keywords.clone()
}
#[test]
fn tree_counts_photos_per_level() {
let (c, _) = lib(&[&["travel|Italy|Rome", "beach"], &["Travel|italy"], &["travel|France", "travel|italy|rome"], &["beach"]]);
let t = c.keyword_tree();
assert_eq!(t.iter().map(|n| (n.name.as_str(), n.count)).collect::<Vec<_>>(), vec![("beach", 2), ("travel", 3)]);
let travel = &t[1];
assert_eq!(travel.children.iter().map(|n| (n.path.as_str(), n.count)).collect::<Vec<_>>(), vec![("travel|France", 1), ("travel|Italy", 3)]);
assert_eq!(travel.children[1].children[0].path, "travel|Italy|Rome");
assert_eq!(travel.children[1].children[0].count, 2);
// filtering by a parent finds its children
let f = Filter { keyword: Some("travel|italy".into()), ..Default::default() };
assert_eq!(c.query(&f, &Default::default()).len(), 3);
}
/// A keyword written twice on a photo, or in two spellings, counts the photo once; the next
/// photo with it counts again.
#[test]
fn tree_counts_a_repeated_keyword_once_per_photo() {
let (c, _) = lib(&[&["sea|Baltic", "sea|Baltic", "Sea|baltic"], &["sea|baltic"], &[]]);
let t = c.keyword_tree();
assert_eq!(tree_paths(&t), [("sea".to_string(), 2), ("sea|Baltic".to_string(), 2)]);
}
#[test]
fn rename_delete_merge_are_single_undoable_batches() {
let (mut c, ids) = lib(&[&["travel|italy|rome", "beach"], &["Travel|Italy"], &["italia", "travel|italy"], &["sea"]]);
let before = c.to_snapshot();
let op = c.rename_keyword_ops("travel|italy", "Europe|Italy").unwrap();
let Op::Batch { ops } = &op else { panic!() };
assert_eq!(ops.len(), 3, "only photos that change");
let inv = c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Europe|Italy|rome", "beach"]);
assert_eq!(kws(&c, ids[1]), ["Europe|Italy"]);
c.apply(inv).unwrap();
assert_eq!(c.to_snapshot(), before);
// merge `italia` into the existing hierarchical keyword: duplicates collapse
let op = c.merge_keywords_ops(&["italia".into()], "travel|italy").unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[2]), ["travel|italy"]);
// delete removes the keyword and its children everywhere
let op = c.delete_keyword_ops("TRAVEL").unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["beach"]);
assert!(kws(&c, ids[1]).is_empty());
assert_eq!(c.keywords(), vec![("beach".to_string(), 1), ("sea".to_string(), 1)]);
// invalid requests
assert!(c.rename_keyword_ops("beach", " ").is_err());
assert!(c.rename_keyword_ops("a", "a|b").is_err());
assert!(c.merge_keywords_ops(&["a".into()], "a|b").is_err());
assert_eq!(clean(" a | |b "), "a|b");
}
fn tree_paths(nodes: &[KeywordNode]) -> Vec<(String, usize)> {
let mut out = Vec::new();
for n in nodes {
out.push((n.path.clone(), n.count));
out.extend(tree_paths(&n.children));
}
out
}
/// A keyword can be listed before any photo has it (Lightroom Classic's Create Keyword Tag):
/// it is in the tree with no photos, its parents too, and undo takes it away.
#[test]
fn a_keyword_listed_with_no_photos_is_in_the_tree() {
let (mut c, _) = lib(&[&["travel|France"]]);
let undo = c.apply(Op::SetKeyword { path: " travel | Italy ".into(), info: Some(KeywordInfo::default()) }).unwrap();
assert_eq!(tree_paths(&c.keyword_tree()), [("travel".to_string(), 1), ("travel|France".to_string(), 1), ("travel|Italy".to_string(), 0)]);
assert_eq!(c.keyword_info("TRAVEL|italy"), Some(&KeywordInfo::default()), "found whatever the case");
c.apply(undo).unwrap();
assert_eq!(tree_paths(&c.keyword_tree()), [("travel".to_string(), 1), ("travel|France".to_string(), 1)]);
assert_eq!(c.keyword_info("travel|Italy"), None);
}
/// A listed keyword needs a name, and its attributes start as Lightroom Classic's do: exported,
/// with the keywords containing it and its synonyms; not a person.
#[test]
fn a_listed_keyword_needs_a_name_and_starts_exported() {
let mut c = Catalog::new();
assert!(c.apply(Op::SetKeyword { path: " | ".into(), info: Some(KeywordInfo::default()) }).is_err());
let info = KeywordInfo::default();
assert!(info.include_on_export && info.export_containing && info.export_synonyms && !info.person && info.synonyms.is_empty());
}
/// Changing a listed keyword's attributes is undone to the attributes it had, under the name as
/// it was written.
#[test]
fn changing_a_listed_keyword_is_undone_to_what_it_was() {
let mut c = Catalog::new();
c.apply(Op::SetKeyword { path: "Weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
let person = KeywordInfo { person: true, synonyms: vec!["Marriage".into()], ..KeywordInfo::default() };
let undo = c.apply(Op::SetKeyword { path: "weddings".into(), info: Some(person.clone()) }).unwrap();
assert_eq!(c.keyword_info("Weddings"), Some(&person));
assert_eq!(undo, Op::SetKeyword { path: "Weddings".into(), info: Some(KeywordInfo::default()) });
c.apply(undo).unwrap();
assert_eq!(c.keyword_info("weddings"), Some(&KeywordInfo::default()));
}
fn listed(c: &Catalog) -> Vec<(String, KeywordInfo)> {
let mut v: Vec<(String, KeywordInfo)> = c.listed_keywords().map(|k| (k.path.clone(), k.info.clone())).collect();
v.sort_by_key(|(p, _)| p.to_lowercase());
v
}
fn with_synonyms(words: &[&str]) -> KeywordInfo {
KeywordInfo { synonyms: words.iter().map(|w| w.to_string()).collect(), ..KeywordInfo::default() }
}
/// Renaming (or moving) a keyword takes its attributes and its listed children along, photos
/// or not, in the same undo step.
#[test]
fn renaming_a_keyword_carries_its_listing_along() {
let (mut c, ids) = lib(&[&["travel|italy"]]);
c.apply(Op::SetKeyword { path: "travel".into(), info: Some(with_synonyms(&["trip"])) }).unwrap();
c.apply(Op::SetKeyword { path: "travel|Spain".into(), info: Some(KeywordInfo::default()) }).unwrap();
let before = c.to_snapshot();
let op = c.rename_keyword_ops("Travel", "Places|Europe").unwrap();
let undo = c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Places|Europe|italy"]);
assert_eq!(listed(&c), [("Places|Europe".to_string(), with_synonyms(&["trip"])), ("Places|Europe|Spain".to_string(), KeywordInfo::default())]);
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
}
/// A keyword only the list holds (no photos) can be renamed too.
#[test]
fn a_keyword_without_photos_can_be_renamed() {
let mut c = Catalog::new();
c.apply(Op::SetKeyword { path: "weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
let op = c.rename_keyword_ops("weddings", "Events|Weddings").unwrap();
c.apply(op).unwrap();
assert_eq!(listed(&c), [("Events|Weddings".to_string(), KeywordInfo::default())]);
}
/// Merging keeps the target's attributes and adds the merged keyword's synonyms to them; a target
/// not listed yet takes the merged keyword's attributes.
#[test]
fn merging_keeps_the_targets_attributes_and_gathers_synonyms() {
let (mut c, _) = lib(&[&["holiday"], &["travel"]]);
let person = KeywordInfo { person: true, ..with_synonyms(&["trip"]) };
c.apply(Op::SetKeyword { path: "travel".into(), info: Some(person.clone()) }).unwrap();
c.apply(Op::SetKeyword { path: "holiday".into(), info: Some(KeywordInfo { include_on_export: false, ..with_synonyms(&["vacation", "Trip"]) }) })
.unwrap();
let op = c.merge_keywords_ops(&["holiday".into()], "travel").unwrap();
c.apply(op).unwrap();
assert_eq!(listed(&c), [("travel".to_string(), KeywordInfo { person: true, ..with_synonyms(&["trip", "vacation"]) })]);
// onto a keyword that isn't listed: it takes the merged one's attributes
let mut c = Catalog::new();
c.apply(Op::SetKeyword { path: "holiday".into(), info: Some(with_synonyms(&["vacation"])) }).unwrap();
let op = c.merge_keywords_ops(&["holiday".into()], "Travel").unwrap();
c.apply(op).unwrap();
assert_eq!(listed(&c), [("Travel".to_string(), with_synonyms(&["vacation"]))]);
}
/// Deleting a keyword takes it, and the keywords below it, off the list as well as off photos.
#[test]
fn deleting_a_keyword_takes_it_off_the_list() {
let (mut c, _) = lib(&[&["travel|italy"], &["beach"]]);
for path in ["travel", "travel|spain", "beach"] {
c.apply(Op::SetKeyword { path: path.into(), info: Some(KeywordInfo::default()) }).unwrap();
}
let before = c.to_snapshot();
let op = c.delete_keyword_ops("travel").unwrap();
let undo = c.apply(op).unwrap();
assert_eq!(listed(&c), [("beach".to_string(), KeywordInfo::default())]);
assert_eq!(tree_paths(&c.keyword_tree()), [("beach".to_string(), 1)]);
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
}
/// Creating a keyword lists it with its attributes, and can tag photos with it in the same undo
/// step. A keyword that exists already (listed, or on a photo) isn't created again.
#[test]
fn creating_a_keyword_lists_it_and_can_tag_photos() {
let (mut c, ids) = lib(&[&["beach"], &[]]);
let before = c.to_snapshot();
let op = c.create_keyword_ops("Events | Weddings", with_synonyms(&["marriage"]), &[ids[1]]).unwrap();
let undo = c.apply(op).unwrap();
assert_eq!(listed(&c), [("Events|Weddings".to_string(), with_synonyms(&["marriage"]))]);
assert_eq!(kws(&c, ids[1]), ["Events|Weddings"]);
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
for exists in ["BEACH", "events|weddings"] {
if exists == "events|weddings" {
let op = c.create_keyword_ops("Events|Weddings", KeywordInfo::default(), &[]).unwrap();
c.apply(op).unwrap();
}
assert!(c.create_keyword_ops(exists, KeywordInfo::default(), &[]).is_err(), "{exists}");
}
assert!(c.create_keyword_ops(" | ", KeywordInfo::default(), &[]).is_err());
}
/// Moving a keyword nests it inside another (or takes it to the top level), with its children,
/// on photos and in the list. It can't go inside itself or one of its children, and moving it
/// where it already is changes nothing.
#[test]
fn moving_a_keyword_nests_it_inside_another() {
let (mut c, ids) = lib(&[&["Italy|Rome"], &["Europe"]]);
// typed in any case, the keywords keep the spelling the library has
let op = c.move_keyword_ops("italy", Some("EUROPE"), false).unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Europe|Italy|Rome"]);
let op = c.move_keyword_ops("europe|italy", None, false).unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Italy|Rome"], "back at the top level");
assert!(c.move_keyword_ops("italy", Some("italy|rome"), false).is_err(), "inside its own child");
assert!(c.move_keyword_ops("italy", Some("Italy"), false).is_err(), "inside itself");
assert_eq!(c.move_keyword_ops("italy|rome", Some("italy"), false).unwrap(), Op::Batch { ops: vec![] }, "already there");
assert!(c.move_keyword_ops("lisbon", Some("europe"), false).is_err(), "no such keyword");
}
/// Moving onto a name that is taken (Europe already has a Rome) merges the two, so the move
/// asks first: refused unless merging is allowed.
#[test]
fn moving_onto_a_taken_name_merges_only_when_allowed() {
let (mut c, ids) = lib(&[&["rome"], &["europe|rome"]]);
let err = c.move_keyword_ops("rome", Some("europe"), false).unwrap_err();
assert!(matches!(err, CatalogError::KeywordExists(ref k) if k == "europe|rome"), "{err:?}");
let op = c.move_keyword_ops("rome", Some("europe"), true).unwrap();
c.apply(op).unwrap();
assert_eq!((kws(&c, ids[0]), kws(&c, ids[1])), (vec!["europe|rome".to_string()], vec!["europe|rome".to_string()]));
}
/// Editing a keyword renames it (its last level: it stays where it is) and sets its attributes,
/// in one undo step. A name that is taken is refused: merging is its own action.
#[test]
fn editing_a_keyword_renames_it_and_sets_its_attributes() {
let (mut c, ids) = lib(&[&["travel|italy"], &["travel|spain"]]);
let before = c.to_snapshot();
let person = KeywordInfo { person: true, ..KeywordInfo::default() };
let op = c.edit_keyword_ops("travel|italy", "Italia", person.clone()).unwrap();
let undo = c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["travel|Italia"]);
assert_eq!(c.keyword_info("travel|italia"), Some(&person));
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
// attributes alone
let op = c.edit_keyword_ops("travel", "travel", with_synonyms(&["trip"])).unwrap();
c.apply(op).unwrap();
assert_eq!(listed(&c), [("travel".to_string(), with_synonyms(&["trip"]))]);
assert!(matches!(c.edit_keyword_ops("travel|italy", "Spain", KeywordInfo::default()), Err(CatalogError::KeywordExists(_))));
assert!(c.edit_keyword_ops("travel|italy", "a|b", KeywordInfo::default()).is_err(), "a name, not a path");
assert!(c.edit_keyword_ops("travel|italy", " ", KeywordInfo::default()).is_err());
}
/// Purging takes off the list the keywords no photo has (nor any keyword below them), in one
/// undo step; keywords photos carry stay.
#[test]
fn purging_takes_unused_keywords_off_the_list() {
let (mut c, _) = lib(&[&["travel|italy"]]);
for path in ["travel", "travel|italy", "travel|spain", "weddings"] {
c.apply(Op::SetKeyword { path: path.into(), info: Some(KeywordInfo::default()) }).unwrap();
}
let op = c.purge_unused_keywords_ops();
c.apply(op).unwrap();
assert_eq!(listed(&c).iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(), ["travel", "travel|italy"]);
assert_eq!(tree_paths(&c.keyword_tree()), [("travel".to_string(), 1), ("travel|italy".to_string(), 1)]);
}
/// Renaming matches names whatever their case, also where a letter's case changes its length
/// (ẞ is three bytes, ß two): the levels below are kept whole, never cut mid-letter.
#[test]
fn renaming_keeps_the_levels_below_whatever_the_case() {
let (mut c, ids) = lib(&[&["straße|nord"], &["ßa|ü"]]);
let op = c.rename_keyword_ops("STRAẞE", "Road").unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Road|nord"]);
let op = c.rename_keyword_ops("ẞA", "Weg").unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[1]), ["Weg|ü"]);
}
fn exported(c: &Catalog, keywords: &[&str]) -> (Vec<String>, Vec<String>) {
let e = c.export_keywords(&keywords.iter().map(|k| k.to_string()).collect::<Vec<_>>());
(e.flat, e.hierarchical)
}
/// By default a keyword is exported as its name together with the keywords containing it (flat,
/// `dc:subject`), and as its full path (`lr:hierarchicalSubject`); each name once.
#[test]
fn a_keyword_exports_its_name_its_parents_and_its_path() {
let c = Catalog::new();
let (flat, paths) = exported(&c, &["travel|Italy|Rome", "Travel|Spain", "beach"]);
assert_eq!(flat, ["Rome", "Italy", "travel", "Spain", "beach"]);
assert_eq!(paths, ["travel|Italy|Rome", "Travel|Spain", "beach"]);
}
/// A keyword not included on export is left out, path and all; a parent left out (a keyword that
/// only organizes others) isn't exported as a containing keyword, but its children are.
#[test]
fn keywords_left_out_of_export_stay_out() {
let mut c = Catalog::new();
let out = KeywordInfo { include_on_export: false, ..KeywordInfo::default() };
c.apply(Op::SetKeyword { path: "Places".into(), info: Some(out.clone()) }).unwrap();
c.apply(Op::SetKeyword { path: "draft".into(), info: Some(out) }).unwrap();
let (flat, paths) = exported(&c, &["Places|Lisbon", "draft"]);
assert_eq!(flat, ["Lisbon"]);
assert_eq!(paths, ["Places|Lisbon"]);
}
/// Without "export containing keywords" only the keyword's own name goes out flat; synonyms go
/// out with it unless "export synonyms" is off.
#[test]
fn containing_keywords_and_synonyms_follow_their_options() {
let mut c = Catalog::new();
let alone = KeywordInfo { export_containing: false, ..with_synonyms(&["Lisboa"]) };
c.apply(Op::SetKeyword { path: "Places|Lisbon".into(), info: Some(alone) }).unwrap();
let quiet = KeywordInfo { export_synonyms: false, ..with_synonyms(&["marriage"]) };
c.apply(Op::SetKeyword { path: "Events|Weddings".into(), info: Some(quiet) }).unwrap();
let (flat, _) = exported(&c, &["Places|Lisbon", "Events|Weddings"]);
assert_eq!(flat, ["Lisbon", "Lisboa", "Weddings", "Events"]);
}
/// Names match whatever the case of any letter, not only ASCII ones: changing only the case of
/// "Ärzte" is a rename, not a clash with itself, and moving it where it is changes nothing.
#[test]
fn names_match_whatever_the_case_of_any_letter() {
let (mut c, ids) = lib(&[&["Ärzte|Wien"]]);
let op = c.edit_keyword_ops("ärzte", "ÄRZTE", KeywordInfo::default()).unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["ÄRZTE|Wien"]);
assert_eq!(c.move_keyword_ops("ärzte|wien", Some("ärzte"), false).unwrap(), Op::Batch { ops: vec![] });
let op = c.rename_keyword_ops("ärzte", "Ärzte").unwrap();
c.apply(op).unwrap();
assert_eq!(kws(&c, ids[0]), ["Ärzte|Wien"]);
assert!(c.create_keyword_ops("ärzte", KeywordInfo::default(), &[]).is_err(), "exists");
}
/// A keyword that is only the parent of a listed one ("Events" of "Events|Weddings") is a
/// keyword like any other: it is in the tree, so it can be found, moved and renamed.
#[test]
fn the_parent_of_a_listed_keyword_is_a_keyword() {
let mut c = Catalog::new();
c.apply(Op::SetKeyword { path: "Events|Weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
assert!(c.has_keyword("events"));
assert_eq!(c.keyword_path("EVENTS").as_deref(), Some("Events"));
let op = c.edit_keyword_ops("events", "Occasions", KeywordInfo::default()).unwrap();
c.apply(op).unwrap();
assert_eq!(tree_paths(&c.keyword_tree()), [("Occasions".to_string(), 0), ("Occasions|Weddings".to_string(), 0)]);
}
/// Photos in Recently Deleted don't count: a keyword only they have isn't in the tree, so it
/// can be created again and is purged as unused, and its spelling there isn't the library's.
#[test]
fn deleted_photos_dont_hold_keywords() {
let (mut c, ids) = lib(&[&["Weddings"], &["travel"]]);
c.apply(Op::SetDeleted { id: ids[0], deleted: true }).unwrap();
assert!(!c.has_keyword("weddings"));
assert!(c.create_keyword_ops("weddings", KeywordInfo::default(), &[]).is_ok());
c.apply(Op::SetKeyword { path: "Weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
let op = c.purge_unused_keywords_ops();
c.apply(op).unwrap();
assert!(listed(&c).is_empty(), "only a deleted photo has it: unused");
}
/// Merging several keywords moves each keyword under them by the closest one, whatever the
/// order they are given in, and every listing lands where its keyword does: one landing where
/// another is about to leave isn't merged into it.
#[test]
fn merging_overlapping_keywords_keeps_every_listing() {
let (mut c, ids) = lib(&[&["a|b|c"], &["a|c"]]);
let person = KeywordInfo { person: true, ..KeywordInfo::default() };
c.apply(Op::SetKeyword { path: "a|b|c".into(), info: Some(person.clone()) }).unwrap();
c.apply(Op::SetKeyword { path: "a|c".into(), info: Some(with_synonyms(&["sea"])) }).unwrap();
let op = c.merge_keywords_ops(&["a|b".into(), "a|c".into()], "a").unwrap();
c.apply(op).unwrap();
assert_eq!((kws(&c, ids[0]), kws(&c, ids[1])), (vec!["a|c".to_string()], vec!["a".to_string()]));
assert_eq!(listed(&c), [("a".to_string(), with_synonyms(&["sea"])), ("a|c".to_string(), person)]);
// the order of the keywords merged doesn't matter
let merged = |from: [&str; 2]| {
let (mut c, ids) = lib(&[&["a|b|c", "a|d"]]);
let op = c.merge_keywords_ops(&from.map(String::from), "x").unwrap();
c.apply(op).unwrap();
kws(&c, ids[0])
};
assert_eq!(merged(["a", "a|b"]), merged(["a|b", "a"]));
assert_eq!(merged(["a", "a|b"]), ["x|c", "x|d"]);
}
/// One keyword at most is where new keywords go (Put New Keywords Inside This Keyword). Making
/// another one so is one undo step; the mark moves with its keyword (also into a merge) and
/// goes with it.
#[test]
fn one_keyword_is_where_new_keywords_go() {
let (mut c, _) = lib(&[&["Events|Weddings"], &["Travel"]]);
let op = c.set_default_parent_ops(Some("events")).unwrap();
let undo = c.apply(op).unwrap();
assert_eq!(c.default_keyword_parent().as_deref(), Some("Events"));
let op = c.set_default_parent_ops(Some("travel")).unwrap();
c.apply(op).unwrap();
assert_eq!(c.default_keyword_parent().as_deref(), Some("Travel"), "only one");
assert!(c.set_default_parent_ops(Some("lisbon")).is_err());
let op = c.rename_keyword_ops("travel", "Trips").unwrap();
c.apply(op).unwrap();
assert_eq!(c.default_keyword_parent().as_deref(), Some("Trips"));
let op = c.merge_keywords_ops(&["trips".into()], "Events").unwrap();
c.apply(op).unwrap();
assert_eq!(c.default_keyword_parent().as_deref(), Some("Events"), "into the merge");
let op = c.delete_keyword_ops("events").unwrap();
c.apply(op).unwrap();
assert_eq!(c.default_keyword_parent(), None);
let op = c.set_default_parent_ops(None).unwrap();
assert_eq!(op, Op::Batch { ops: vec![] }, "none to clear");
c.apply(undo).unwrap();
assert_eq!(c.default_keyword_parent(), None, "undo of the first: none was");
}
/// A file's keywords as a photo carries them: the paths of `lr:hierarchicalSubject`, and the
/// names of `dc:subject` that aren't levels of those paths (an exported `travel|Italy` comes
/// back as one keyword, not three). Without paths, the names as they are.
#[test]
fn a_files_keywords_keep_their_hierarchy() {
let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(from_file(&v(&["Rome", "Italy", "travel", "beach"]), &v(&["travel|Italy|Rome"])), ["travel|Italy|Rome", "beach"]);
assert_eq!(from_file(&v(&["ROME"]), &v(&["travel|Rome", " travel | rome "])), ["travel|Rome"], "each once, cleaned");
assert_eq!(from_file(&v(&["beach", " sea "]), &[]), ["beach", "sea"]);
assert_eq!(from_file(&v(&["a|b"]), &[]), ["a|b"], "LightCraft's own sidecars write paths flat");
}
/// A new keyword inside one the library has takes the library's spelling of it: creating
/// "TRAVEL|rome" next to "travel|italy" doesn't respell "travel".
#[test]
fn a_new_keyword_keeps_the_spelling_of_its_parents() {
let (mut c, _) = lib(&[&["travel|italy"]]);
let op = c.create_keyword_ops("TRAVEL|Rome", KeywordInfo::default(), &[]).unwrap();
c.apply(op).unwrap();
assert_eq!(listed(&c).iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(), ["travel|Rome"]);
assert_eq!(tree_paths(&c.keyword_tree())[0].0, "travel");
}
/// An edit that changes nothing is nothing: no listing, no undo step.
#[test]
fn an_edit_that_changes_nothing_is_nothing() {
let (mut c, _) = lib(&[&["beach"]]);
assert_eq!(c.edit_keyword_ops("beach", "beach", KeywordInfo::default()).unwrap(), Op::Batch { ops: vec![] });
c.apply(Op::SetKeyword { path: "beach".into(), info: Some(with_synonyms(&["shore"])) }).unwrap();
assert_eq!(c.edit_keyword_ops("BEACH", "beach", with_synonyms(&["shore"])).unwrap(), Op::Batch { ops: vec![] });
// renamed with the default attributes: the photos change, nothing is listed
let (mut c, _) = lib(&[&["beach"]]);
let op = c.edit_keyword_ops("beach", "Shore", KeywordInfo::default()).unwrap();
c.apply(op).unwrap();
assert!(listed(&c).is_empty());
}
/// Typing suggests keywords no photo has yet too (created in the Keyword List).
#[test]
fn suggestions_include_keywords_without_photos() {
let (mut c, _) = lib(&[&["beach"]]);
c.apply(Op::SetKeyword { path: "Events|Weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
assert_eq!(c.keyword_suggestions(&[], "wed", 5), ["Events|Weddings"]);
assert!(!c.keyword_suggestions(&["events|weddings".into()], "wed", 5).contains(&"Events|Weddings".to_string()), "not one it has");
}
/// A new name typed for a photo goes inside the default parent; a keyword the library has, and
/// a path typed whole, don't.
#[test]
fn typed_new_keywords_go_inside_the_default_parent() {
let (mut c, _) = lib(&[&["beach"], &["Events"]]);
assert_eq!(c.typed_keyword(" Weddings "), "Weddings", "no default parent");
let op = c.set_default_parent_ops(Some("events")).unwrap();
c.apply(op).unwrap();
assert_eq!(c.typed_keyword("Weddings"), "Events|Weddings");
assert_eq!(c.typed_keyword("BEACH"), "BEACH", "the library has it");
assert_eq!(c.typed_keyword("Places|Lisbon"), "Places|Lisbon");
}
/// The keyword list as a text file, as Lightroom Classic writes one: a keyword a line, the
/// keywords inside it indented one tab more, a synonym in braces on a line of its own under its
/// keyword, a keyword left out of export in square brackets; by name.
#[test]
fn the_keyword_list_is_written_as_tab_indented_text() {
let (mut c, _) = lib(&[&["Places|Lisbon", "beach"]]);
c.apply(Op::SetKeyword { path: "Places".into(), info: Some(KeywordInfo { include_on_export: false, ..KeywordInfo::default() }) }).unwrap();
c.apply(Op::SetKeyword { path: "Places|Lisbon".into(), info: Some(with_synonyms(&["Lisboa"])) }).unwrap();
c.apply(Op::SetKeyword { path: "Events|Weddings".into(), info: Some(KeywordInfo::default()) }).unwrap();
assert_eq!(c.keyword_list_text().text, "beach\nEvents\n\tWeddings\n[Places]\n\tLisbon\n\t\t{Lisboa}\n");
}
/// Reading a list gives each keyword's path and attributes: what was written comes back, and a
/// file from elsewhere (Windows line ends, a byte-order mark, blank lines) reads too.
#[test]
fn a_keyword_list_reads_back() {
let read = parse_keyword_list("\u{feff}beach\r\n\r\nEvents\r\n\tWeddings\r\n\t\t{marriage}\r\n[Places]\r\n\tLisbon\r\n").unwrap();
let out = KeywordInfo { include_on_export: false, ..KeywordInfo::default() };
assert_eq!(
read,
[
("beach".to_string(), KeywordInfo::default()),
("Events".to_string(), KeywordInfo::default()),
("Events|Weddings".to_string(), with_synonyms(&["marriage"])),
("Places".to_string(), out),
("Places|Lisbon".to_string(), KeywordInfo::default()),
]
);
}
/// Photo Supreme's Formatted Vocabulary File is the same format: plain text with Windows line
/// ends and no byte-order mark, a top-level category in square brackets (an organizing keyword,
/// left out of export), keywords a tab further in at each level.
#[test]
fn a_photo_supreme_vocabulary_file_reads() {
let file = "[Places]\r\n\tPortugal\r\n\t\tLisbon\r\n\t\t\tAlfama\r\n\t\tPorto\r\n\tSpain\r\n\t\tSeville\r\n";
let read = parse_keyword_list(file).unwrap();
let paths: Vec<&str> = read.iter().map(|(p, _)| p.as_str()).collect();
assert_eq!(
paths,
["Places", "Portugal", "Portugal|Lisbon", "Portugal|Lisbon|Alfama", "Portugal|Porto", "Spain", "Spain|Seville"].map(|p| if p == "Places" {
p.to_string()
} else {
format!("Places|{p}")
})
);
assert!(!read[0].1.include_on_export, "the category organizes: it isn't exported");
assert!(read[1..].iter().all(|(_, i)| i.include_on_export));
}
/// A list that can't be read says which line and why, and nothing of it is taken.
#[test]
fn a_bad_keyword_list_says_which_line() {
let err = |text: &str| parse_keyword_list(text).unwrap_err().to_string();
assert!(err("Events\n\t\tWeddings\n").contains("line 2"), "two levels down at once");
assert!(err("{marriage}\n").contains("line 1"), "a synonym of nothing");
assert!(err("Events\nTravel|Lisbon\n").contains("line 2"), "“|” separates levels here");
let deep: String = (0..70).map(|i| format!("{}k{i}\n", "\t".repeat(i))).collect();
assert!(err(&deep).contains("line 65"), "a file is input: 64 levels at most");
}
/// Files from elsewhere read as they were meant or say why not: classic Mac line ends (a lone
/// carriage return) are lines; indenting with spaces, which would flatten the hierarchy, is
/// refused at its line; so are control characters in a name and "|" in a synonym.
#[test]
fn a_keyword_list_from_elsewhere_reads_or_says_why_not() {
let paths = |text: &str| parse_keyword_list(text).unwrap().into_iter().map(|(p, _)| p).collect::<Vec<_>>();
assert_eq!(paths("Events\r\tWeddings\rPlaces\r"), ["Events", "Events|Weddings", "Places"]);
let err = |text: &str| parse_keyword_list(text).unwrap_err().to_string();
assert!(err("Events\n Weddings\n").contains("line 2"), "space indentation");
assert!(err("Events\n\t Weddings\n").contains("line 2"), "a space after the tabs");
assert!(err("Events\nx\u{0}y\n").contains("line 2"), "a control character");
assert!(err("Events\n\t{sea|shore}\n").contains("line 2"), "“|” in a synonym");
}
/// A keyword repeated in another case is one keyword, and the keywords inside either take the
/// first spelling.
#[test]
fn a_repeated_keyword_keeps_its_first_spelling() {
let read = parse_keyword_list("Events\n\tWeddings\nevents\n\tBirthdays\n").unwrap();
assert_eq!(read.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(), ["Events", "Events|Weddings", "Events|Birthdays"]);
}
/// What the list can't hold is left out and named, so the file always reads back: a name the
/// format would read as something else (in brackets or braces), one with a line break, a
/// synonym with one, a keyword nested deeper than a list goes; and the keywords inside one left
/// out go with it.
#[test]
fn an_exported_keyword_list_always_reads_back() {
let deep = (0..=MAX_LEVELS).map(|i| format!("level {i}")).collect::<Vec<_>>().join("|");
let (mut c, _) = lib(&[&["Travel|[draft]", "{todo}|Lisbon", "Weddings", "Line\nbreak", deep.as_str()]]);
c.apply(Op::SetKeyword { path: "Weddings".into(), info: Some(with_synonyms(&["marriage", "two\nlines"])) }).unwrap();
let KeywordListFile { text, unwritable, .. } = c.keyword_list_text();
let read = parse_keyword_list(&text).unwrap_or_else(|e| panic!("{e}\n{text}"));
assert!(read.iter().any(|(p, _)| p == "Travel"));
assert!(read.iter().all(|(p, _)| !p.contains("draft") && !p.contains("todo") && !p.contains("Line")), "{text}");
let weddings = read.iter().find(|(p, _)| p == "Weddings").map(|(_, i)| i.synonyms.clone());
assert_eq!(weddings, Some(vec!["marriage".to_string()]));
let deepest = read.iter().map(|(p, _)| p.split(SEP).count()).max();
assert_eq!(deepest, Some(MAX_LEVELS));
assert!(unwritable.contains(&"Travel|[draft]".to_string()), "{unwritable:?}");
assert!(unwritable.contains(&"{todo}".to_string()), "{unwritable:?}");
assert!(unwritable.contains(&"Line\nbreak".to_string()), "{unwritable:?}");
assert!(unwritable.contains(&"Weddings {two\nlines}".to_string()), "{unwritable:?}");
assert!(unwritable.iter().any(|u| u.ends_with(&format!("level {MAX_LEVELS}"))), "{unwritable:?}");
}
/// The list leaves out only what it must, and names only what's lost: a name starting with a
/// byte-order mark would lose it, but a synonym in braces reads back, and a synonym that's empty
/// or another's in a different case is no loss. It also says which keywords it wrote.
#[test]
fn an_exported_keyword_list_names_only_what_it_loses() {
let (mut c, _) = lib(&[&["\u{feff}Albums", "{draft", "Weddings"]]);
c.apply(Op::SetKeyword { path: "Weddings".into(), info: Some(with_synonyms(&["Marriage", "marriage", " ", "{vows}"])) }).unwrap();
let out = c.keyword_list_text();
let read = parse_keyword_list(&out.text).unwrap_or_else(|e| panic!("{e}\n{}", out.text));
assert_eq!(out.unwritable, ["\u{feff}Albums"]);
assert_eq!(out.written, ["Weddings", "{draft"]);
assert_eq!(read.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(), ["Weddings", "{draft"]);
let weddings = read.iter().find(|(p, _)| p == "Weddings").map(|(_, i)| i.synonyms.clone());
assert_eq!(weddings, Some(vec!["Marriage".to_string(), "{vows}".to_string()]));
}
/// A big list reads and imports at once, against a big library too: 40,000 keywords used to take
/// half a minute to read, and checking 5,000 new ones against 20,000 photos over a minute, with
/// the app frozen.
#[test]
fn a_big_keyword_list_imports_quickly() {
let mut text = String::new();
for g in 0..400 {
text.push_str(&format!("group {g}\n"));
for k in 0..99 {
text.push_str(&format!("\tkeyword {g}-{k}\n"));
}
}
let t0 = std::time::Instant::now();
let read = parse_keyword_list(&text).unwrap();
assert_eq!(read.len(), 40_000);
let mut c = Catalog::new();
let mut ops = Vec::new();
for i in 0..20_000u32 {
let id = c.alloc_photo_id();
let mut p = Photo::new(id, Source::Demo { scene: 1 }, "a.jpg", "JPEG", 3, 2, "2026-01-01");
p.meta.keywords = (0..5).map(|k| format!("library {}|tag {}", k, (i + k) % 3000)).collect();
ops.push(Op::AddPhoto { photo: Box::new(p) });
}
c.apply(Op::Batch { ops }).unwrap();
let (op, added, _) = c.import_keywords_ops(&read[..5_000]);
c.apply(op).unwrap();
assert_eq!(added, 5_000);
let took = t0.elapsed();
assert!(took < std::time::Duration::from_secs(10), "{took:?}");
}
/// Importing a list adds the keywords the library doesn't have, with their attributes, and gives
/// those it has the list's synonyms (their own attributes stay), in one undo step.
#[test]
fn importing_a_keyword_list_adds_what_is_missing() {
let (mut c, _) = lib(&[&["Events|Weddings"]]);
c.apply(Op::SetKeyword { path: "Events|Weddings".into(), info: Some(KeywordInfo { person: true, ..with_synonyms(&["marriage"]) }) }).unwrap();
let before = c.to_snapshot();
let read = parse_keyword_list("events\n\tweddings\n\t\t{nuptials}\n\tBirthdays\n[Drafts]\n").unwrap();
let (op, added, updated) = c.import_keywords_ops(&read);
assert_eq!((added, updated), (2, 1));
let undo = c.apply(op).unwrap();
assert_eq!(c.keyword_info("Events|Weddings"), Some(&KeywordInfo { person: true, ..with_synonyms(&["marriage", "nuptials"]) }));
assert!(c.has_keyword("Events|Birthdays"));
assert_eq!(
listed(&c).iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(),
["Drafts", "Events|Birthdays", "Events|Weddings"],
"in the library's spelling"
);
assert!(!c.keyword_info("Drafts").unwrap().include_on_export);
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
}
#[test]
fn suggestions_rank_co_occurrence_and_prefixes() {
let (c, _) = lib(&[&["dog", "park"], &["dog", "park", "ball"], &["dog", "beach"], &["cat"], &["cat"], &["cat"], &["parade"], &["eagle"]]);
// co-occurring with `dog` first (park twice), then the most used
let s = c.keyword_suggestions(&["dog".into()], "", 3);
assert_eq!(s, ["park", "ball", "beach"]);
let s = c.keyword_suggestions(&[], "", 2);
assert_eq!(s, ["cat", "dog"]);
let s = c.keyword_suggestions(&["park".into()], "pa", 5);
assert_eq!(s, ["parade"]);
let s = c.keyword_suggestions(&[], "E", 5);
assert_eq!(s, ["eagle", "beach", "parade"], "prefix matches before substring matches");
}
/// A flat keyword already covered by a hierarchical level only in another spelling is not kept
/// again, whatever the size of either list (the per-flat-keyword search of every level, twice
/// lower-cased per comparison, was quadratic: CWE-407).
#[test]
fn from_file_matches_levels_in_any_case() {
let flat = ["Rome".to_string(), "Seaside".to_string()];
let hierarchical = ["travel|ITALY|rome".to_string()];
assert_eq!(from_file(&flat, &hierarchical), ["travel|ITALY|rome", "Seaside"]);
}
/// The same synonym, in any spelling, is kept once (the search of each keyword's growing
/// synonym list per line was quadratic, with lower-cased copies made per comparison).(CWE-407)
#[test]
fn parse_keyword_list_keeps_a_synonym_once() {
let read = parse_keyword_list("Travel\n\t{Trip}\n\t{journey}\n\t{TRIP}\n").unwrap();
assert_eq!(read.len(), 1);
assert_eq!(read[0].1.synonyms, ["Trip", "journey"]);
}
/// A keyword split into far more levels than a list file accepts is cut at [`MAX_LEVELS`] in the
/// tree, whose level rows hold every prefix twice: unbounded it made the stored bytes quadratic
/// in the level count of one short keyword (CWE-400).
#[test]
fn keyword_tree_caps_a_keyword_at_the_list_depth() {
let deep: Vec<String> = (0..4096).map(|i| format!("k{i}")).collect();
let joined = deep.join("|");
let (c, _) = lib(&[&[joined.as_str()]]);
let deepest = tree_paths(&c.keyword_tree()).iter().map(|(p, _)| p.split(SEP).count()).max().unwrap_or(0);
assert_eq!(deepest, MAX_LEVELS);
}
+69 -20
View File
@@ -36,7 +36,7 @@ pub use folders::{FolderNode, FolderRecord};
pub use journal::{Journal, LoadReport, PersistStats, SnapshotPolicy, SnapshotTiming};
pub use keywords::KeywordNode;
use lightcraft_develop::DevelopSettings;
pub use local::{DEFAULT_FORGET_DAYS, ForgetPlan, folder_of};
pub use local::{DEFAULT_FORGET_DAYS, ForgetPlan, LocalRecords, folder_of};
pub use lock::{LibraryLock, LockError, LockOwner};
pub use model::*;
pub use query::{DateGroup, Filter, Person, RatingOp, Sort, SortKey, mix64};
@@ -284,7 +284,8 @@ pub struct Catalog {
/// What the library keeps about its folders (folder identity → record), see [`folders`].
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
folder_records: BTreeMap<String, FolderRecord>,
/// Increments on every applied op.
/// Increments on every applied op, and when a batch fails and its rollback cannot undo it whole (the catalog
/// changed, so what is keyed by the revision is out of date).
#[serde(skip)]
pub revision: u64,
/// Which photos the latest ops touched ([`Catalog::touched_since`]).
@@ -348,6 +349,8 @@ struct Changes {
/// outside (a library just loaded takes a range of its own, so that nothing kept from another library is
/// taken for this one's): nothing is known of how the catalog got to where it is.
seen: u64,
/// A batch that failed could not be rolled back whole: what it changed stays, so what it noted must too.
torn: bool,
}
impl PartialEq for Changes {
@@ -610,13 +613,40 @@ impl Catalog {
self.albums.get_mut(&id).ok_or(CatalogError::NoAlbum(id))
}
/// Apply an op; returns its inverse. On error nothing changes.
/// Apply an op; returns its inverse. On error the catalog is as it was, the revision included, and nothing is
/// remembered of the op in what the latest ops touched. The one exception is a batch whose rollback fails: the
/// catalog did change, so the revision advances and anything may be taken to have changed.
pub fn apply(&mut self, op: Op) -> Result<Op> {
if self.changes.seen != self.revision {
// 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 broad = self.changes.broad;
self.changes.torn = false;
let inv = match self.apply_inner(op) {
Ok(inv) => inv,
Err(e) => {
let made = self.revision.saturating_add(1);
if self.changes.torn {
// (a batch the rollback of which failed changed something and says not what: it makes a
// revision, so what is kept for the one before is dropped, and anything may have changed, as
// after an op of a wider reach)
self.changes.torn = false;
self.changes.broad = made;
self.revision = made;
self.changes.seen = made;
} else {
// (everything the failed op, or the rollback of a batch, noted was made for the revision it
// would have made: nothing earlier has that one. A note the cap already dropped stays
// dropped, which only says less than is known, as the cap does.)
while self.changes.touched.back().is_some_and(|(r, _, _)| *r == made) {
self.changes.touched.pop_back();
}
self.changes.broad = broad;
}
return Err(e);
}
};
self.revision += 1;
self.changes.seen = self.revision;
Ok(inv)
@@ -962,7 +992,9 @@ impl Catalog {
Err(e) => {
// roll back what was applied
for inv in inverses.into_iter().rev() {
let _ = self.apply_inner(inv);
if self.apply_inner(inv).is_err() {
self.changes.torn = true;
}
}
return Err(e);
}
@@ -1066,26 +1098,41 @@ impl Catalog {
}
st.photos.len() >= 2
});
let parents: Vec<(AlbumId, Option<AlbumId>)> = self.albums.values().map(|a| (a.id, a.parent)).collect();
for (id, parent) in parents {
let Some(p) = parent else { continue };
let mut cur = Some(p);
let mut steps = 0usize;
let ok = loop {
match cur {
None => break true,
Some(c) if c == id || steps > self.albums.len() => break false,
Some(c) => match self.albums.get(&c) {
Some(a) if a.folder => cur = a.parent,
_ => break false,
},
let albums: Vec<AlbumId> = self.albums.keys().copied().collect();
// Validate each parent link once (CWE-407), caching only chains that now reach a root.
// A cached bad verdict is not enough: skipping its ancestors would leave their broken
// links/cycle intact when a lower-id child was the first to walk into that chain.
let mut valid: std::collections::HashSet<AlbumId> = std::collections::HashSet::new();
for id in albums {
let mut walked: Vec<AlbumId> = Vec::new();
let broken = {
let mut cur = id;
let mut on: std::collections::HashSet<AlbumId> = std::collections::HashSet::new();
loop {
if valid.contains(&cur) {
break None;
}
if !on.insert(cur) {
// Detach one actual cycle node, not the child that first reached it.
break self.albums.get(&cur).and_then(|a| a.parent).map(|parent| (cur, parent));
}
walked.push(cur);
let Some(parent) = self.albums.get(&cur).and_then(|a| a.parent) else { break None };
if !self.albums.get(&parent).is_some_and(|a| a.folder) {
break Some((cur, parent));
}
cur = parent;
}
steps += 1;
};
if !ok && let Some(a) = self.albums.get_mut(&id) {
if let Some((id, p)) = broken
&& let Some(a) = self.albums.get_mut(&id)
{
changed.push(format!("album {}: its folder {} is missing, not a folder or inside it: moved to the top level", id.0, p.0));
a.parent = None;
}
// Only visited nodes are cached, after every one can reach the repaired root or a
// previously validated chain. Unvisited ancestors never inherit a guessed verdict.
valid.extend(walked);
}
let past = |last: Option<u64>| last.map_or(1, |v| v.saturating_add(1));
let (photo, album, stack) = (
@@ -1164,4 +1211,6 @@ mod tests_repair;
#[cfg(test)]
mod tests_scale;
#[cfg(test)]
mod tests_tally;
#[cfg(test)]
mod tests_torn_append;
+39 -1
View File
@@ -34,6 +34,15 @@ use serde::Serialize;
use crate::{Catalog, Op, Photo, PhotoId, Source};
/// The Local records of some files ([`Catalog::local_records_of`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LocalRecords {
/// Only a record of having looked: nothing was changed on them and nothing refers to them.
pub untouched: Vec<PhotoId>,
/// Holding something of the person's, with their files.
pub kept: Vec<(PhotoId, String)>,
}
/// Default for how long a Local folder may go unbrowsed before its untouched records are
/// forgotten (days).
pub const DEFAULT_FORGET_DAYS: u32 = 30;
@@ -64,7 +73,8 @@ pub fn folder_of(p: &Photo) -> Option<String> {
// `/` and `\` are both separators whatever the platform (a catalog can move between them)
Source::File { path } => {
let key = crate::query::folder_key(path);
key.rsplit_once('/').map(|(dir, _)| if dir.is_empty() { "/".to_string() } else { dir.to_string() })
// a drive or share root keeps its trailing `/` in its key (`c:/`, `//srv/share/`)
key.rsplit_once('/').map(|(dir, _)| if dir.is_empty() { "/".to_string() } else { crate::query::folder_key(&format!("{dir}/")) })
}
Source::Demo { .. } => None,
}
@@ -176,6 +186,34 @@ impl Catalog {
&self.browsed
}
/// The Local records of `files` (paths as stored), for library photos about to point at
/// those files (a folder located where it was browsed, `folder.updateLocation`): a file has one
/// record, so the Local one gives way. Told apart: those that are only a record of having
/// looked (untouched, see the module docs, and nothing refers to them), which can go, and
/// those that hold something of the person's (a rating, an edit, a place in an album), with
/// their files. Records in Recently Deleted are not Local records to this.
pub fn local_records_of(&self, files: &HashSet<String>) -> LocalRecords {
let mut out = LocalRecords::default();
if files.is_empty() {
return out;
}
let referenced = self.referenced();
for p in self.photos.values().filter(|p| p.local && !p.deleted) {
let Source::File { path } = &p.source else { continue };
if !files.contains(path) {
continue;
}
if p.untouched_local() && !referenced.contains(&p.id) {
out.untouched.push(p.id);
} else {
out.kept.push((p.id, path.clone()));
}
}
out.untouched.sort_unstable();
out.kept.sort_unstable();
out
}
/// Plan forgetting untouched Local records whose folder wasn't browsed for `days` days (as of
/// `now`, ISO 8601). `in_use` keeps records the caller still needs. `days == 0` (never) or an
/// unreadable `now` forgets nothing. See the module docs.
+11
View File
@@ -240,6 +240,17 @@ fn has_person(p: &Photo, name: &str) -> bool {
}
impl Filter {
/// The labels that `label` and `labels` let through together (they AND), in `labels`' order;
/// `None` when neither is set, empty when they exclude each other. The chip and the filter
/// bar's buttons show this, so they match what is filtered.
pub fn labels_shown(&self) -> Option<Vec<ColorLabel>> {
match (self.label, self.labels.is_empty()) {
(None, true) => None,
(Some(l), true) => Some(vec![l]),
(l, false) => Some(self.labels.iter().copied().filter(|x| l.is_none_or(|l| l == *x)).collect()),
}
}
/// Human-readable summary of the active rules (smart album tooltips, `album.list`).
pub fn describe(&self) -> String {
self.describe_in(None)
+69 -787
View File
@@ -432,12 +432,79 @@ thread_local! {
std::cell::RefCell::new(std::collections::HashMap::new());
}
thread_local! {
/// While [`AlbumPass`] is alive on this thread: the photos of each smart album that was counted whole, with
/// the longest chain of smart albums (itself included) its rules lead through.
static PASS: std::cell::RefCell<Option<std::collections::HashMap<crate::AlbumId, (usize, crate::tally::Members)>>> =
const { std::cell::RefCell::new(None) };
}
/// One pass over one catalog state that counts every smart album whole. Each album put in with `remember`
/// answers [`smart_album_holds`] from its photos, not from its rules, until the pass is dropped (it can't outlive
/// the state it was made of: it exists only inside the counting function).
///
/// Only an album whose rules lead to no loop may be remembered, and only with the height of its chain: its answer
/// then doesn't depend on which albums are being evaluated around it, as long as the chain still fits under
/// [`MAX_ALBUM_DEPTH`] from where it is asked (checked on every use; otherwise the rules are evaluated as before).
pub(crate) struct AlbumPass {
outer: Option<std::collections::HashMap<crate::AlbumId, (usize, crate::tally::Members)>>,
}
impl AlbumPass {
pub(crate) fn begin() -> AlbumPass {
AlbumPass { outer: PASS.with_borrow_mut(|p| p.replace(std::collections::HashMap::new())) }
}
/// `id` holds exactly `members`, and its rules lead through a chain of `height` smart albums (itself included),
/// none of them in a loop.
pub(crate) fn remember(&self, id: crate::AlbumId, height: usize, members: crate::tally::Members) {
PASS.with_borrow_mut(|p| {
if let Some(p) = p {
p.insert(id, (height, members));
}
});
}
/// Ends the pass, giving back what was remembered.
pub(crate) fn finish(self) -> std::collections::HashMap<crate::AlbumId, crate::tally::Members> {
PASS.with_borrow_mut(Option::take).unwrap_or_default().into_iter().map(|(id, (_, members))| (id, members)).collect()
}
}
impl Drop for AlbumPass {
fn drop(&mut self) {
let outer = self.outer.take();
PASS.with_borrow_mut(|p| *p = outer);
}
}
/// What a counting pass knows of smart album `id` for `photo`, when asking now can't give another answer than
/// evaluating its rules would: the chain below it fits under [`MAX_ALBUM_DEPTH`] from the albums being evaluated.
fn pass_answer(id: crate::AlbumId, photo: crate::PhotoId) -> Option<bool> {
PASS.with_borrow(|p| {
let (height, members) = p.as_ref()?.get(&id)?;
let depth = EVALUATING.with_borrow(Vec::len);
(depth + height <= MAX_ALBUM_DEPTH).then(|| members.holds(photo))
})
}
#[cfg(test)]
thread_local! {
/// How many times a smart album's rules were worked out on this thread (tests count them).
pub(crate) static EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Whether `photo` is in smart album `id`, by `matches` (its rules), remembered for the rest of the
/// outermost question and guarded by [`evaluating`] (a loop or a chain too deep holds nothing).
pub(crate) fn smart_album_holds(id: crate::AlbumId, photo: crate::PhotoId, matches: impl FnOnce() -> bool) -> bool {
if let Some(known) = pass_answer(id, photo) {
return known;
}
if let Some(known) = ANSWERS.with_borrow(|a| a.get(&(id, photo)).copied()) {
return known;
}
#[cfg(test)]
EVALUATED.with(|n| n.set(n.get() + 1));
// the outermost question forgets the answers when it ends, however it ends
struct Forget(bool);
impl Drop for Forget {
@@ -456,7 +523,7 @@ pub(crate) fn smart_album_holds(id: crate::AlbumId, photo: crate::PhotoId, match
}
/// How deep smart albums may test smart albums before the innermost counts as holding nothing.
const MAX_ALBUM_DEPTH: usize = 32;
pub(crate) const MAX_ALBUM_DEPTH: usize = 32;
/// Run `f` as the evaluation of smart album `id`'s rules: `None` (so it holds nothing) when `id`
/// is already being evaluated (a loop the check would refuse, saved anyway) or the chain is
@@ -1112,789 +1179,4 @@ impl RuleSet {
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ColorLabel, Flag, PhotoId, Source};
use serde_json::json;
fn photo(id: u64) -> Photo {
let mut p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, "IMG_0042.CR2", "CR2", 6000, 4000, "2026-09-20T10:00:00");
p.rating = 4;
p.flag = Flag::Pick;
p.label = Some(ColorLabel::Red);
p.captured = Some("2026-08-14T18:30:00".into());
p.meta.keywords = vec!["travel|italy|rome".into(), "food".into()];
p.meta.camera = "Model X2".into();
p.meta.iso = Some(1600);
p.meta.aperture = Some(2.8);
p
}
fn rs(v: serde_json::Value) -> RuleSet {
serde_json::from_value(v).unwrap()
}
#[test]
fn f32_boundary_values_match_gte_lte() {
let cat = Catalog::new();
let matches =
|p: &Photo, field: &str, op: &str, value: f64| rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat);
for v in [1.4f32, 1.8, 2.8, 5.6, 0.95] {
let mut p = photo(1);
p.meta.aperture = Some(v);
p.meta.focal_mm = Some(v);
let w = v.to_string().parse::<f64>().unwrap();
for field in ["aperture", "focalLength"] {
assert!(matches(&p, field, "gte", w), "{field} gte {w}");
assert!(matches(&p, field, "lte", w), "{field} lte {w}");
assert!(!matches(&p, field, "gt", w), "{field} gt {w}");
assert!(!matches(&p, field, "lt", w), "{field} lt {w}");
}
}
}
#[test]
fn fields_ops_and_groups() {
let cat = Catalog::new();
let p = photo(1);
let yes = |v: serde_json::Value| assert!(rs(v.clone()).matches(&p, &cat), "{v}");
let no = |v: serde_json::Value| assert!(!rs(v.clone()).matches(&p, &cat), "{v}");
yes(json!({"rules": [{"field": "rating", "op": "gte", "value": 3}, {"field": "flag", "op": "is", "value": "pick"}]}));
no(json!({"rules": [{"field": "rating", "op": "gt", "value": 4}]}));
yes(json!({"match": "any", "rules": [{"field": "rating", "op": "is", "value": 1}, {"field": "label", "op": "is", "value": "red"}]}));
no(json!({"match": "none", "rules": [{"field": "label", "op": "is", "value": "red"}]}));
yes(json!({"rules": [{"field": "keywords", "op": "is", "value": "italy"}]}));
yes(
json!({"rules": [{"field": "keywords", "op": "contains", "value": "ROME"}, {"field": "keywords", "op": "notContains", "value": "beach"}]}),
);
no(json!({"rules": [{"field": "keywords", "op": "isEmpty"}]}));
yes(json!({"rules": [{"field": "fileName", "op": "startsWith", "value": "img_"}, {"field": "fileName", "op": "endsWith", "value": ".cr2"}]}));
// file path: the whole string (spaces included), either separator, case-insensitive
let mut fp = photo(3);
fp.source = Source::File { path: "D:\\Photos\\Lake Como Wedding-Day\\2026\\IMG_0042.CR2".into() };
let fpm = |v: serde_json::Value| rs(v).matches(&fp, &cat);
assert!(fpm(json!({"rules": [{"field": "filePath", "op": "contains", "value": "/Lake Como Wedding-Day/"}]})));
assert!(!fpm(json!({"rules": [{"field": "filePath", "op": "contains", "value": "/Como Lake/"}]})));
assert!(!fpm(json!({"rules": [{"field": "filePath", "op": "contains", "value": "Wedding Day"}]})));
assert!(fpm(json!({"rules": [{"field": "filePath", "op": "notContains", "value": "/Other/"}]})));
assert!(fpm(json!({"rules": [{"field": "filePath", "op": "startsWith", "value": "d:/photos/"}]})));
no(json!({"rules": [{"field": "filePath", "op": "contains", "value": "/Lake/"}]})); // demo photo has no path
yes(json!({"rules": [{"field": "filePath", "op": "isEmpty"}]}));
yes(json!({"rules": [{"field": "camera", "op": "contains", "value": "x2"}, {"field": "title", "op": "isEmpty"}]}));
yes(json!({"rules": [{"field": "iso", "op": "between", "value": [800, 3200]}, {"field": "aperture", "op": "lte", "value": "f/4"}]}));
yes(json!({"rules": [{"field": "megapixels", "op": "gte", "value": 24}]}));
yes(
json!({"rules": [{"field": "captureDate", "op": "is", "value": "2026-08"}, {"field": "captureDate", "op": "before", "value": "2026-09-01"}]}),
);
yes(json!({"rules": [{"field": "captureDate", "op": "between", "value": ["2026-08-01", "2026-08"]}]}));
no(json!({"rules": [{"field": "captureDate", "op": "after", "value": "2026-08"}]}));
yes(json!({"rules": [{"field": "kind", "op": "isNot", "value": "video"}, {"field": "edited", "op": "is", "value": false}]}));
// copyright status (unknown until set)
yes(json!({"rules": [{"field": "copyrightStatus", "op": "is", "value": "unknown"}]}));
no(json!({"rules": [{"field": "copyrightStatus", "op": "is", "value": "copyrighted"}]}));
let mut pd = photo(2);
pd.meta.copyright_status = crate::CopyrightStatus::PublicDomain;
assert!(rs(json!({"rules": [{"field": "copyrightStatus", "op": "is", "value": "publicDomain"}]})).matches(&pd, &cat));
assert!(rs(json!({"rules": [{"field": "copyrightStatus", "op": "isNot", "value": "copyrighted"}]})).matches(&pd, &cat));
// nested: rating ≥ 4 and (label is blue or keywords contain food)
yes(json!({"rules": [{"field": "rating", "op": "gte", "value": 4}, {"group": {"match": "any", "rules": [
{"field": "label", "op": "is", "value": "blue"}, {"field": "keywords", "op": "contains", "value": "food"}]}}]}));
// in the last N days, relative to now
set_now(Some("2026-09-01T00:00:00".into()));
yes(json!({"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 30, "unit": "days"}}]}));
no(json!({"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "weeks"}}]}));
yes(json!({"rules": [{"field": "captureDate", "op": "notInLast", "value": 7}]}));
set_now(None);
// an empty rule list: all → everything, any → nothing
yes(json!({"rules": []}));
no(json!({"match": "any", "rules": []}));
}
#[test]
fn problems_and_description() {
let r = rs(json!({"rules": [{"field": "rating", "op": "contains", "value": 1}, {"group": {"rules": [{"field": "nope", "op": "is"}]}}]}));
let messages: Vec<String> = r.check(&Catalog::new()).into_iter().map(|p| p.message).collect();
assert_eq!(messages, vec!["`rating` has no operator `contains`".to_string(), "unknown field `nope`".to_string()]);
let r = rs(
json!({"match": "any", "rules": [{"field": "rating", "op": "gte", "value": 3}, {"field": "captureDate", "op": "inLast", "value": {"n": 2, "unit": "weeks"}}]}),
);
assert_eq!(r.describe(), "rating is ≥ 3 or capture date is in the last 2 weeks");
// every field has a kind with operators
for (f, _, k) in FIELDS {
assert!(!ops_for(*k).is_empty(), "{f}");
}
}
/// Keyword Count: a photo with 2 keywords is in "≥ 2", "≤ 2" and "is 2"; a hierarchical path
/// (travel|italy|rome) is one keyword, and the same keyword twice in different case is one.
#[test]
fn keyword_count_rules() {
let cat = Catalog::new();
let mut p = photo(1); // travel|italy|rome, food
let m = |p: &Photo, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": "keywordCount", "op": op, "value": value}]})).matches(p, &cat)
};
assert!(m(&p, "gte", json!(2)) && m(&p, "lte", json!(2)) && m(&p, "is", json!(2)));
assert!(!m(&p, "gte", json!(3)) && !m(&p, "lt", json!(2)) && m(&p, "between", json!([1, 2])));
p.meta.keywords.push("Food".into());
assert!(m(&p, "is", json!(2)), "Food and food are one keyword");
p.meta.keywords.clear();
assert!(m(&p, "is", json!(0)) && m(&p, "lte", json!(2)));
assert_eq!(field_group("keywordCount"), Some("Keywords & People"));
}
/// People: the names on face regions. "People contains ana" finds Ana Lima; pets and unnamed
/// faces are not people; People Count counts each person once.
#[test]
fn people_rules() {
use lightcraft_meta::{Rect, Region, RegionKind};
let cat = Catalog::new();
let region = |name: Option<&str>, kind: RegionKind| Region {
rect: Rect { x0: 0.4, y0: 0.4, x1: 0.6, y1: 0.6 },
kind,
name: name.map(str::to_string),
description: None,
};
let mut p = photo(1);
let m = |p: &Photo, field: &str, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat)
};
assert!(m(&p, "person", "isEmpty", json!(null)) && m(&p, "personCount", "is", json!(0)));
p.meta.regions = vec![
region(Some("Ana Lima"), RegionKind::Face),
region(Some(" ana lima "), RegionKind::Face),
region(Some("Rex"), RegionKind::Pet),
region(None, RegionKind::Face),
region(Some("Bo"), RegionKind::Face),
];
assert!(m(&p, "person", "contains", json!("ana")));
assert!(m(&p, "person", "is", json!("ANA LIMA")));
assert!(!m(&p, "person", "is", json!("rex")), "a pet isn't a person");
assert!(m(&p, "person", "notContains", json!("rex")));
assert!(m(&p, "person", "isNotEmpty", json!(null)));
assert!(m(&p, "personCount", "is", json!(2)), "Ana Lima once, Bo; not the pet or the unnamed face");
assert_eq!(field_group("person"), Some("Keywords & People"));
}
/// Shutter Speed compares exposure times in seconds, written as the camera shows them: a
/// photo at 1/250 is in "≤ 1/60" (faster) and not in "≥ 1/60"; "between 1/1000 and 1/125".
#[test]
fn shutter_speed_rules() {
let cat = Catalog::new();
let mut p = photo(1);
let m = |p: &Photo, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": "shutterSpeed", "op": op, "value": value}]})).matches(p, &cat)
};
assert!(!m(&p, "gte", json!(0)), "no shutter speed recorded");
p.meta.shutter = "1/250".into();
assert!(m(&p, "is", json!("1/250")) && m(&p, "lte", json!("1/60")) && !m(&p, "gte", json!("1/60")));
assert!(m(&p, "between", json!(["1/1000", "1/125"])) && m(&p, "lt", json!(0.01)));
assert!(!m(&p, "is", json!("1/0")) && !m(&p, "is", json!("fast")), "a value that isn't a time matches nothing");
p.meta.shutter = "2\"".into();
assert!(m(&p, "gte", json!("1")) && m(&p, "is", json!(2)));
assert_eq!(field_group("shutterSpeed"), Some("Camera Info"));
}
#[test]
fn shutter_seconds_parses_camera_notation() {
for (s, want) in [("1/250", Some(0.004)), (" 1/250 s", Some(0.004)), ("0.5", Some(0.5)), ("2\"", Some(2.0)), ("30s", Some(30.0))] {
assert_eq!(crate::parse_shutter_seconds(s), want, "{s}");
}
for s in ["", "1/0", "0", "-1/250", "fast", "inf", "NaN", "1/x"] {
assert_eq!(crate::parse_shutter_seconds(s), None, "{s}");
}
}
/// File Extension ignores case and a leading dot; Copy Name, Alt Text, City, State /
/// Province and Country are text fields of their own (Location still matches all of them).
#[test]
fn file_source_description_and_location_rules() {
let cat = Catalog::new();
let mut p = photo(1); // IMG_0042.CR2
let m = |p: &Photo, field: &str, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat)
};
assert!(m(&p, "extension", "is", json!("cr2")) && m(&p, "extension", "is", json!(".CR2")));
assert!(!m(&p, "extension", "is", json!("jpg")));
p.file_name = "README".into();
assert!(m(&p, "extension", "isEmpty", json!(null)), "no dot, no extension");
p.file_name = "archive.tar.gz".into();
assert!(m(&p, "extension", "is", json!("gz")));
p.file_name = ".hidden".into();
assert!(m(&p, "extension", "isEmpty", json!(null)), "a dot file has no extension");
assert!(m(&p, "copyName", "isEmpty", json!(null)));
p.copy_name = Some("Black and white".into());
assert!(m(&p, "copyName", "contains", json!("black")));
p.meta.alt_text = "A red kite over a hill".into();
assert!(m(&p, "altText", "contains", json!("kite")));
p.meta.city = "Porto".into();
p.meta.state = "Porto District".into();
p.meta.country = "Portugal".into();
assert!(m(&p, "city", "is", json!("porto")) && m(&p, "state", "startsWith", json!("porto")) && m(&p, "country", "is", json!("portugal")));
assert!(!m(&p, "city", "is", json!("portugal")), "City tests only the city");
assert!(m(&p, "location", "contains", json!("portugal")), "Location still covers the country");
}
/// In a Stack, Video Duration (seconds; photos have none), Cropped and Treatment.
#[test]
fn source_file_and_develop_rules() {
use crate::{Op, Stack, StackId};
let mut cat = Catalog::new();
let a = photo(1);
let b = photo(2);
let c = photo(3);
for p in [&a, &b, &c] {
cat.apply(Op::AddPhoto { photo: Box::new(p.clone()) }).unwrap();
}
cat.apply(Op::AddStack { stack: Stack { id: StackId(1), photos: vec![a.id, b.id], collapsed: false } }).unwrap();
let m = |p: &Photo, field: &str, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat)
};
assert!(m(&a, "stacked", "is", json!(true)) && m(&b, "stacked", "is", json!(true)));
assert!(m(&c, "stacked", "is", json!(false)));
let mut v = photo(4);
assert!(!m(&v, "duration", "gte", json!(0)), "a photo has no duration");
v.duration = Some(95.0);
assert!(m(&v, "duration", "gt", json!(60)) && m(&v, "duration", "between", json!([90, 120])));
let mut d = photo(5);
assert!(m(&d, "cropped", "is", json!(false)) && m(&d, "treatment", "is", json!("color")));
let mut s = (*d.develop).clone();
s.crop.geometry.rect = lightcraft_geom::Rect::new(0.1, 0.0, 0.9, 1.0);
s.treatment = lightcraft_develop::Treatment::Bw;
d.develop = std::sync::Arc::new(s);
assert!(m(&d, "cropped", "is", json!(true)) && m(&d, "treatment", "is", json!("monochrome")));
assert!(m(&d, "treatment", "isNot", json!("color")));
let mut s = (*d.develop).clone();
s.crop = Default::default();
s.crop.geometry.angle = 2.0;
d.develop = std::sync::Arc::new(s);
assert!(m(&d, "cropped", "is", json!(true)), "straightening counts as a crop");
}
/// Size follows the photo as shown: rotated a quarter turn a landscape frame is a portrait, and
/// a crop changes its edges and its megapixels. Long / Short Edge are in pixels.
#[test]
fn size_rules_follow_orientation_and_crop() {
let cat = Catalog::new();
let mut p = photo(1); // 6000 × 4000
let m = |p: &Photo, field: &str, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat)
};
assert!(m(&p, "aspect", "is", json!("landscape")) && m(&p, "longEdge", "is", json!(6000)) && m(&p, "shortEdge", "is", json!(4000)));
assert!(m(&p, "megapixels", "is", json!(24)));
let mut s = (*p.develop).clone();
s.orientation = lightcraft_geom::Orientation::Rotate90;
p.develop = std::sync::Arc::new(s.clone());
assert!(m(&p, "aspect", "is", json!("portrait")) && m(&p, "longEdge", "is", json!(6000)));
// a square crop of the rotated frame: 4000 wide, 4000 of its 6000 tall
s.crop.geometry.rect = lightcraft_geom::Rect::new(0.0, 1.0 / 6.0, 1.0, 5.0 / 6.0);
p.develop = std::sync::Arc::new(s);
assert!(m(&p, "aspect", "is", json!("square")) && m(&p, "longEdge", "is", json!(4000)));
assert!(m(&p, "megapixels", "is", json!(16)), "a 4000 × 4000 crop is 16 MP, not the sensor's 24");
assert!(m(&p, "megapixels", "lt", json!(20)) && !m(&p, "megapixels", "gte", json!(24)));
assert!(m(&p, "aspect", "isNot", json!("portrait")));
let empty = Photo::new(PhotoId(9), Source::Demo { scene: 0 }, "x.jpg", "JPEG", 0, 0, "2026-09-20T10:00:00");
assert!(
!m(&empty, "aspect", "is", json!("landscape")) && !m(&empty, "aspect", "is", json!("square")) && m(&empty, "longEdge", "is", json!(0))
);
assert!(m(&empty, "megapixels", "is", json!(0)));
}
/// Any Searchable Text also finds the state / province, the alt text, a person on a face and
/// a virtual copy's name, as it already finds the city and country.
#[test]
fn any_searchable_text_covers_new_fields() {
let cat = Catalog::new();
let mut p = photo(1);
let m = |p: &Photo, value: &str| rs(json!({"rules": [{"field": "text", "op": "contains", "value": value}]})).matches(p, &cat);
for word in ["oregon", "kite", "ana", "bluish"] {
assert!(!m(&p, word), "{word}");
}
p.meta.state = "Oregon".into();
p.meta.alt_text = "A kite".into();
p.meta.regions = vec![lightcraft_meta::Region {
rect: lightcraft_meta::Rect { x0: 0.4, y0: 0.4, x1: 0.6, y1: 0.6 },
kind: lightcraft_meta::RegionKind::Face,
name: Some("Ana".into()),
description: None,
}];
p.copy_name = Some("Bluish".into());
for word in ["oregon", "kite", "ana", "bluish"] {
assert!(m(&p, word), "{word}");
}
}
/// Choice values have readable labels: the editor and summaries show "Public Domain" and
/// "Black & White", never ids like `publicDomain`; rules still store and accept the ids.
#[test]
fn choices_have_readable_labels() {
assert_eq!(choice_label("copyrightStatus", "publicDomain"), Some("Public Domain"));
assert_eq!(choice_label("treatment", "monochrome"), Some("Black & White"));
// own labels where a shared word would translate wrongly: "Color" is the colour noun (the
// Color panel) and "None" agrees with other nouns in gendered languages
assert_eq!(choice_label("treatment", "color"), Some("In Color"));
assert_eq!(choice_label("label", "none"), Some("No Label"));
assert_eq!(choice_label("flag", "pick"), Some("Picked"));
assert_eq!(choice_label("aspect", "landscape"), Some("Landscape (wide)"));
assert_eq!(choice_label("flag", "nope"), None);
assert_eq!(choice_label("rating", "pick"), None, "not a choice field");
for (field, _, kind) in FIELDS {
let Kind::Choice(choices) = kind else { continue };
for (id, label) in *choices {
assert!(!label.is_empty() && label != id, "{field}: {id} has no label of its own");
assert!(label.starts_with(|c: char| c.is_uppercase()), "{field}: {label}");
}
}
let r = rs(
json!({"rules": [{"field": "copyrightStatus", "op": "is", "value": "publicDomain"}, {"field": "flag", "op": "isNot", "value": "reject"}]}),
);
assert_eq!(r.describe(), "copyright status is public domain and pick flag isn't rejected");
let mut p = photo(1);
p.meta.copyright_status = crate::CopyrightStatus::PublicDomain;
assert!(r.matches(&p, &Catalog::new()), "ids still match");
}
/// Yes/no fields read "Yes" / "No", and a value means the same to matching and to every
/// summary: `false`, `"false"`, `"no"` and `0` are no; `true`, `"yes"`, `1` and a missing value
/// are yes. Anything else is reported, not silently taken as yes.
#[test]
fn yes_no_values() {
for v in [json!(true), json!("true"), json!("Yes"), json!(1), json!(1.0), json!(null)] {
assert_eq!(bool_value(&v), Some(true), "{v}");
}
for v in [json!(false), json!("false"), json!(" NO "), json!(0), json!(0.0)] {
assert_eq!(bool_value(&v), Some(false), "{v}");
}
for v in [json!("maybe"), json!(2), json!(0.5), json!(-1), json!([true]), json!({"x": 1})] {
assert_eq!(bool_value(&v), None, "{v}");
}
assert_eq!((bool_label(true), bool_label(false)), ("Yes", "No"));
let cat = Catalog::new();
let p = photo(1); // unedited
assert!(rs(json!({"rules": [{"field": "edited", "op": "is", "value": "false"}]})).matches(&p, &cat), "\"false\" means no");
assert!(
!rs(json!({"rules": [{"field": "edited", "op": "is", "value": "false"}, {"field": "hasGps", "op": "is", "value": "yes"}]}))
.matches(&p, &cat)
);
assert!(!rs(json!({"rules": [{"field": "edited", "op": "is", "value": "maybe"}]})).matches(&p, &cat), "an unreadable value matches nothing");
let r = rs(json!({"rules": [{"field": "edited", "op": "is", "value": true}, {"field": "cropped", "op": "is", "value": "false"}]}));
assert_eq!(r.describe(), "has edits is yes and cropped is no");
let bad = rs(json!({"rules": [{"field": "edited", "op": "is", "value": "maybe"}]}));
let messages: Vec<String> = bad.check(&cat).into_iter().map(|p| p.message).collect();
assert_eq!(messages, vec!["`edited` is yes or no, not \"maybe\"".to_string()]);
}
/// "In the last N" never overflows, whatever N an agent or a saved file holds: a zero,
/// negative or unreadable N matches nothing (either way round); an N beyond 10,000 years means
/// "ever", so every dated photo is in it and none is outside it.
#[test]
fn in_the_last_survives_hostile_counts() {
set_now(Some("2026-09-01T00:00:00".into()));
let cat = Catalog::new();
let p = photo(1); // captured 2026-08-14
let m = |op: &str, n: serde_json::Value, unit: &str| {
rs(json!({"rules": [{"field": "captureDate", "op": op, "value": {"n": n, "unit": unit}}]})).matches(&p, &cat)
};
for n in [json!(0), json!(-5), json!(-1e30), json!(-9.3e18), json!("soon")] {
for op in ["inLast", "notInLast"] {
assert!(!m(op, n.clone(), "years"), "{op} {n}");
}
}
for n in [json!(1e30), json!(9.3e18), json!(u64::MAX), json!(20_000)] {
assert!(m("inLast", n.clone(), "years"), "{n} years is ever");
assert!(!m("notInLast", n.clone(), "years"), "{n}");
}
assert!(m("inLast", json!(1e30), "hours") && m("inLast", json!(30), "days"));
set_now(None);
}
/// Every rule's value is checked against its field, so a rule that can't mean anything is
/// reported instead of quietly matching nothing (or everything). Each problem says which rule
/// it is about: "rule 2", or "rule 2.1" inside a group.
#[test]
fn values_are_checked_against_their_field() {
use crate::{Album, AlbumId, Op};
let mut cat = Catalog::new();
cat.apply(Op::AddAlbum { album: Album::new(AlbumId(1), "Trip") }).unwrap();
let smart = Album { smart: Some(Box::default()), ..Album::new(AlbumId(2), "Best") };
cat.apply(Op::AddAlbum { album: smart }).unwrap();
cat.apply(Op::SetLabelName { label: crate::ColorLabel::Red, name: Some("Client".into()) }).unwrap();
let check = |rule: serde_json::Value| rs(json!({"rules": [rule]})).check(&cat);
let ok = |rule: serde_json::Value| assert!(check(rule.clone()).is_empty(), "{rule}: {:?}", check(rule.clone()));
let bad = |rule: serde_json::Value, want: &str| {
let p = check(rule.clone());
assert!(p.iter().any(|p| p.message.contains(want)), "{rule}: wanted {want:?}, got {p:?}");
};
let r = |field: &str, op: &str, value: serde_json::Value| json!({"field": field, "op": op, "value": value});
// numbers
ok(r("rating", "gte", json!(3)));
ok(r("rating", "gte", json!("4")));
ok(r("rating", "between", json!([1, 5])));
ok(r("aperture", "lte", json!("f/4")));
ok(r("focalLength", "is", json!("50mm")));
bad(r("rating", "gte", json!("abc")), "needs a number");
bad(r("rating", "gte", json!(7)), "no rating 0–5 is ≥ 7");
bad(r("iso", "between", json!([100])), "two");
bad(r("iso", "between", json!("100")), "two");
ok(r("shutterSpeed", "lte", json!("1/60")));
bad(r("shutterSpeed", "lte", json!("fast")), "1/250");
// dates
for d in ["2026", "2026-08", "2026-08-14", "2026-08-14T10:00:00"] {
ok(r("captureDate", "is", json!(d)));
}
ok(r("captureDate", "between", json!(["2026-01", "2026-12"])));
for d in [json!("banana"), json!("2026-13"), json!("2026-02-30"), json!(""), json!(2026)] {
bad(r("captureDate", "after", d), "needs a date");
}
bad(r("captureDate", "between", json!(["2026-12", "2026-01"])), "after the second");
bad(r("captureDate", "between", json!(["", "2026"])), "needs a date");
ok(r("captureDate", "inLast", json!({"n": 2, "unit": "weeks"})));
ok(r("captureDate", "inLast", json!(7)));
bad(r("captureDate", "inLast", json!({"n": 0, "unit": "days"})), "more than 0");
bad(r("captureDate", "notInLast", json!({"n": 3, "unit": "fortnights"})), "fortnights");
ok(r("captureDate", "isEmpty", json!(null)));
// choices: the ids, the flag's aliases and a colour label's custom name
ok(r("kind", "is", json!("raw")));
ok(r("flag", "is", json!("picked")));
ok(r("label", "is", json!("client")));
bad(r("label", "is", json!("pink")), "pink");
bad(r("kind", "isNot", json!("photo")), "photo");
// text needs something to look for
ok(r("title", "contains", json!("kite")));
ok(r("title", "isEmpty", json!(null)));
bad(r("title", "contains", json!(" ")), "something to look for");
bad(r("keywords", "startsWith", json!("")), "something to look for");
// albums: one that exists, plain or smart
ok(r("album", "is", json!(1)));
bad(r("album", "is", json!(999)), "no album 999");
ok(r("album", "is", json!(2)));
// groups: an empty one is a mistake; problems inside one say where they are
let p = rs(json!({"rules": [r("rating", "gte", json!(3)), {"group": {"match": "any", "rules": []}}]})).check(&cat);
assert_eq!(p.iter().map(ToString::to_string).collect::<Vec<_>>(), vec!["rule 2: an empty group".to_string()]);
let p = rs(json!({"rules": [r("rating", "gte", json!(3)), {"group": {"rules": [r("iso", "is", json!(100)), r("rating", "is", json!(9))]}}]}))
.check(&cat);
assert_eq!(p.len(), 1);
assert_eq!(p[0].path, vec![1, 1]);
assert_eq!(p[0].to_string(), "rule 2.2: no rating 0–5 is 9");
// an empty rule list at the top is "all photos" (or none, for any), not a mistake
assert!(rs(json!({"rules": []})).check(&cat).is_empty());
}
/// The check and the matcher agree. Units are any case, singular or plural, and missing means
/// days; an unknown unit is refused and matches nothing (it used to count as days, so "week" was
/// one day). A rating rule is refused only when no rating 0–5 could meet it. A colour label's
/// custom name matches in any case, accents included. Empty text hints at the right operator.
#[test]
fn check_and_matcher_agree() {
use crate::Op;
set_now(Some("2026-09-01T00:00:00".into()));
let mut cat = Catalog::new();
cat.apply(Op::SetLabelName { label: crate::ColorLabel::Red, name: Some("Été".into()) }).unwrap();
let p = photo(1); // captured 2026-08-14 (18 days before now), red label, rating 4
let rule = |field: &str, op: &str, value: serde_json::Value| rs(json!({"rules": [{"field": field, "op": op, "value": value}]}));
let valid = |r: &RuleSet| r.check(&cat).is_empty();
for unit in [json!("Days"), json!("DAY"), json!("days"), json!(null)] {
let r = rule("captureDate", "inLast", json!({"n": 30, "unit": unit}));
assert!(valid(&r) && r.matches(&p, &cat), "{unit}");
}
let r = rule("captureDate", "inLast", json!({"n": 30}));
assert!(valid(&r) && r.matches(&p, &cat), "no unit is days");
let week = rule("captureDate", "inLast", json!({"n": 1, "unit": "week"}));
assert!(valid(&week) && !week.matches(&p, &cat), "a week, not a day: 18 days ago is outside it");
assert!(rule("captureDate", "inLast", json!({"n": 3, "unit": "Weeks"})).matches(&p, &cat));
let odd = rule("captureDate", "inLast", json!({"n": 30, "unit": "fortnights"}));
assert!(!valid(&odd) && !odd.matches(&p, &cat), "an unknown unit is refused and matches nothing");
// rating: only a rule no rating could meet
for (op, v) in [("lt", json!(6)), ("gt", json!(-1)), ("isNot", json!(9)), ("between", json!([3, 8]))] {
assert!(valid(&rule("rating", op, v.clone())), "{op} {v}");
}
for (op, v) in [("is", json!(9)), ("gte", json!(7)), ("gt", json!(5)), ("lt", json!(0)), ("between", json!([6, 9]))] {
assert!(!valid(&rule("rating", op, v.clone())), "{op} {v}");
}
// a custom label name, any case, accents too
let r = rule("label", "is", json!("été"));
assert!(valid(&r) && r.matches(&p, &cat));
// "isn't" with nothing points at "isn't empty", the others at "is empty"
let hint = |op: &str| rule("title", op, json!("")).check(&cat).first().map(|p| p.message.clone()).unwrap_or_default();
assert!(hint("isNot").contains("isn't empty"), "{}", hint("isNot"));
assert!(hint("contains").contains("“is empty”"), "{}", hint("contains"));
set_now(None);
}
/// An album is in it or not: Album offers "is" and "isn't", never "≥" or "between".
#[test]
fn album_rules_are_is_or_isnt() {
assert_eq!(field_kind("album"), Some(Kind::Album));
let ops: Vec<&str> = ops_for(Kind::Album).iter().map(|o| o.0).collect();
assert_eq!(ops, ["is", "isNot"]);
let r = rs(json!({"rules": [{"field": "album", "op": "gte", "value": 1}]}));
assert_eq!(r.check(&Catalog::new()).first().map(|p| p.message.as_str()), Some("`album` has no operator `gte`"));
}
/// An Album rule names its album by id, written as a number or a numeric string, the same way
/// for the check, the matcher and the editor. A folder holds albums, not photos, so it can't be
/// tested.
#[test]
fn album_rule_ids() {
use crate::{Album, AlbumId, Op};
assert_eq!(album_rule_id(&json!(3)), Some(AlbumId(3)));
assert_eq!(album_rule_id(&json!("3")), Some(AlbumId(3)));
assert_eq!(album_rule_id(&json!(3.0)), Some(AlbumId(3)));
for v in [json!(1.5), json!(-1), json!("x"), json!(null)] {
assert_eq!(album_rule_id(&v), None, "{v}");
}
let mut cat = Catalog::new();
cat.apply(Op::AddAlbum { album: Album { folder: true, ..Album::new(AlbumId(4), "Trips") } }).unwrap();
let p = rs(json!({"rules": [{"field": "album", "op": "is", "value": 4}]})).check(&cat);
assert!(p.first().is_some_and(|p| p.message.contains("folder")), "{p:?}");
}
/// Album rules saved before Album offered only "is" / "isn't" (≥, between… from when it was a
/// number field) always meant "isn't" to the matcher; upgrading says so, so they check again.
#[test]
fn old_album_operators_upgrade_to_isnt() {
let mut r = rs(json!({"rules": [
{"field": "album", "op": "gte", "value": 1},
{"field": "album", "op": "is", "value": 1},
{"field": "rating", "op": "gte", "value": 3},
{"group": {"rules": [{"field": "album", "op": "between", "value": [1, 2]}]}}
]}));
r.upgrade();
let ops = serde_json::to_value(&r).unwrap().to_string();
assert!(ops.contains(r#""field":"album","op":"isNot","value":1"#), "{ops}");
assert!(ops.contains(r#""field":"album","op":"is","value":1"#), "{ops}");
assert!(ops.contains(r#""field":"rating","op":"gte""#), "other fields keep theirs: {ops}");
assert!(ops.contains(r#""field":"album","op":"isNot","value":[1,2]"#), "inside groups too: {ops}");
}
/// Besides its English message (for agents), a problem names its field and the kind of issue,
/// so the editor can show "Title: needs something to look for" in any language. Every issue
/// has its own short text.
#[test]
fn problems_name_their_field_and_issue() {
let cat = Catalog::new();
let check = |rules: serde_json::Value| rs(json!({"rules": rules})).check(&cat);
let p = check(json!([{"field": "title", "op": "contains", "value": ""}]));
assert_eq!((p[0].field.as_deref(), p[0].issue), (Some("title"), Issue::NeedsTextOrEmpty));
let p = check(json!([{"field": "title", "op": "isNot", "value": ""}]));
assert_eq!(p[0].issue, Issue::NeedsTextOrNotEmpty);
// keywords and people say "are empty", and so does their hint
let p = check(json!([{"field": "keywords", "op": "contains", "value": ""}, {"field": "person", "op": "notContains", "value": " "}]));
assert_eq!((p[0].issue, p[1].issue), (Issue::NeedsNamesOrEmpty, Issue::NeedsNamesOrNotEmpty));
assert!(p[0].issue.text().contains("“are empty”") && p[0].message.contains("“are empty”"));
let p = check(json!([{"field": "rating", "op": "is", "value": 9}, {"group": {"rules": []}}]));
assert_eq!((p[0].field.as_deref(), p[0].issue), (Some("rating"), Issue::NoRatingMatches));
assert_eq!((p[1].field.as_deref(), p[1].issue), (None, Issue::EmptyGroup));
let p = check(json!([{"field": "captureDate", "op": "between", "value": ["2026-12", "2026-01"]}]));
assert_eq!(p[0].issue, Issue::DatesReversed);
let p = check(json!([{"field": "album", "op": "is", "value": null}]));
assert_eq!(p[0].issue, Issue::ChooseAlbum);
let mut texts: Vec<&str> = Issue::ALL.iter().map(|i| i.text()).collect();
assert!(texts.iter().all(|t| !t.is_empty()));
texts.sort_unstable();
texts.dedup();
assert_eq!(texts.len(), Issue::ALL.len(), "each issue reads differently");
}
/// A rule date reads one way for the check and the matcher: a space works as the "T"
/// ("2026-10-01 10:00" matches a photo taken then). Imported capture times can carry fractions
/// of a second and a time zone (EXIF SubSecTime / OffsetTime: "…T10:00:00.250+02:00"), so a
/// rule may too, after the seconds; anywhere else they are no date.
#[test]
fn rule_dates_have_one_reading() {
let cat = Catalog::new();
let mut p = photo(1);
p.captured = Some("2026-10-01T10:00:00".into());
let rule = |op: &str, v: serde_json::Value| rs(json!({"rules": [{"field": "captureDate", "op": op, "value": v}]}));
for (op, v) in [
("is", json!("2026-10-01 10:00")),
("is", json!(" 2026-10-01T10 ")),
("between", json!(["2026-10-01 09:00", "2026-10-01 11:00"])),
("after", json!("2026-10-01 09:59")),
] {
let r = rule(op, v.clone());
assert!(r.check(&cat).is_empty() && r.matches(&p, &cat), "{op} {v}");
}
// a capture time with a fraction and a zone, as imports write it
let mut zoned = photo(2);
zoned.captured = Some("2026-08-14T10:00:00.250+02:00".into());
for v in ["2026-08-14T10:00:00.250", "2026-08-14T10:00:00.250+02:00", "2026-08-14T10:00:00"] {
let r = rule("is", json!(v));
assert!(r.check(&cat).is_empty() && r.matches(&zoned, &cat), "{v}");
}
assert!(rule("is", json!("2026-08-14T10:00:00Z")).check(&cat).is_empty());
for v in [
"2026-8-14",
"2026-08-14T1",
"2026-08-14X10",
"26-08-14",
"2026-08-14T25:00",
"2026-08-14Z",
"2026-08-14 10:00-05:00",
"2026-08-14T10:00:00.",
"2026-08-14T10:00:00+2",
] {
let p = rule("is", json!(v)).check(&cat);
assert_eq!(p.first().map(|p| p.issue), Some(Issue::NeedsDate), "{v}");
}
assert_eq!(rule_date("2026-10-01 10:00"), Ok("2026-10-01T10:00".to_string()));
assert_eq!(rule_date("2026"), Ok("2026".to_string()));
}
/// The field menu shows every rule field once: at the top level or in exactly one group,
/// and [`FIELDS`] lists them in menu order.
#[test]
fn every_field_is_in_the_menu_exactly_once() {
let menu: Vec<&str> = TOP_LEVEL_FIELDS.iter().chain(FIELD_GROUPS.iter().flat_map(|g| g.1.iter())).copied().collect();
let fields: Vec<&str> = FIELDS.iter().map(|f| f.0).collect();
assert_eq!(menu, fields, "the menu and FIELDS list the same fields in the same order");
for (label, group) in FIELD_GROUPS {
assert!(!group.is_empty(), "group {label} is empty");
}
let mut labels: Vec<&str> = FIELD_GROUPS.iter().map(|g| g.0).collect();
labels.dedup();
assert_eq!(labels.len(), FIELD_GROUPS.len(), "group labels are unique");
}
/// Related fields sit together: all the file fields, all the camera (EXIF) fields, all the
/// dates, all the keyword fields.
#[test]
fn related_fields_share_a_group() {
let same = |fields: &[&str], group: &str| {
for f in fields {
assert_eq!(field_group(f), Some(group), "{f}");
}
};
same(&["fileName", "extension", "filePath", "kind", "format", "duration"], "File");
same(&["album", "virtualCopy", "copyName", "stacked"], "Source");
same(&["longEdge", "shortEdge", "aspect", "megapixels"], "Size");
same(&["edited", "cropped", "treatment"], "Develop");
same(&["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso"], "Camera Info");
same(&["captureDate", "importDate", "editDate"], "Date");
same(&["keywords", "keywordCount", "person", "personCount"], "Keywords & People");
same(&["title", "caption", "altText", "creator", "copyright", "copyrightStatus"], "Description");
same(&["location", "city", "state", "country", "hasGps"], "Location");
for f in ["rating", "flag", "label", "text"] {
assert_eq!(field_group(f), None, "{f} stays at the top level");
}
assert_eq!(field_group("nope"), None);
assert_eq!(field_label("filePath"), Some("File Path"));
assert_eq!(field_label("nope"), None);
}
/// The `filePath` rule exactly as it was before the in-place ASCII path: new strings per photo.
fn file_path_old(op: &str, source: &Source, value: &serde_json::Value) -> bool {
let want = lower(value);
let path = match source {
Source::File { path } => path.replace('\\', "/"),
Source::Demo { .. } => String::new(),
};
let want = want.replace('\\', "/");
match op {
"contains" => !want.trim().is_empty() && path.to_lowercase().contains(want.trim()),
"notContains" => want.trim().is_empty() || !path.to_lowercase().contains(want.trim()),
_ => text_op(op, &path, &want),
}
}
#[test]
fn file_path_rules_match_the_old_strings_for_any_path() {
let paths = [
"",
" ",
" /a/b.jpg \t",
"/Volumes/share/photos/Trip/IMG_0001.jpg",
"/Volumes/share/PHOTOS/trip/img_0001.JPG",
r"D:\Photos\Lake Como\IMG_0001.JPG",
r"d:/photos/lake como/img_0001.jpg",
r"\\nas\share\x.jpg",
"/photos/Straße/a.jpg",
"/photos/STRASSE/a.jpg",
"/photos/İstanbul/a.jpg",
"/photos/i̇stanbul/a.jpg",
"/photos/ΟΔΟΣ/a.jpg",
"/photos/οδος/a.jpg",
"/photos/ΟΔΌΣ/a.jpg",
"/photos/日本/東京.jpg",
"/p/\u{0B}x\u{0B}",
"/p/\u{85}x\u{85}",
"a",
];
let wants = [
"",
" ",
"a",
"A",
"/",
r"\",
r"\photos\",
"/photos/",
"photos",
"PHOTOS",
"Lake Como",
" lake como ",
"lake como",
r"d:\photos\lake",
"IMG_0001.JPG",
".jpg",
"straße",
"STRASSE",
"strasse",
"İstanbul",
"i̇stanbul",
"istanbul",
"ΟΔΟΣ",
"οδος",
"οδοσ",
"ΟΔΌΣ",
"東京",
"日本",
"x",
"\u{0B}x",
"/a/b.jpg",
"/a/b.jpg \t",
"\u{85}x",
];
let ops = ["contains", "notContains", "is", "isNot", "startsWith", "endsWith", "isEmpty", "isNotEmpty", "bogus"];
let mut values: Vec<serde_json::Value> = wants.iter().map(|w| json!(w)).collect();
values.extend([json!(null), json!(5), json!(true), json!(["a", "b"])]);
let mut sources: Vec<Source> = paths.iter().map(|p| Source::File { path: (*p).into() }).collect();
sources.push(Source::Demo { scene: 0 });
for source in &sources {
for op in ops {
for value in &values {
assert_eq!(file_path_matches(op, source, value), file_path_old(op, source, value), "{source:?} {op} {value}");
}
}
}
}
#[test]
fn file_path_rule_through_a_rule_set_ignores_case_and_slash_direction() {
let mut p = photo(1);
p.source = Source::File { path: r"D:\Photos\Lake Como\IMG_0001.JPG".into() };
let r = rs(json!({"rules": [{"field": "filePath", "op": "contains", "value": "/LAKE como/"}]}));
assert!(r.matches(&p, &Catalog::default()));
}
/// Every piece of a long path, in both cases and both slash directions, wherever it starts
/// (the search skips eight bytes at a time, so starts and ends at every offset matter).
#[test]
fn file_path_contains_finds_every_piece_of_a_long_path() {
let path = r"D:\Photos\Lake Como\Wedding-Day_2026\IMG_0001 (copy).JPG";
let source = Source::File { path: path.into() };
let shout = |s: &str| s.to_uppercase();
let swap = |s: &str| s.replace('\\', "/");
for from in 0..path.len() {
for to in from + 1..=path.len() {
let piece = &path[from..to];
for want in [piece.to_string(), shout(piece), swap(piece), piece.replace('/', r"\"), format!("{piece}x"), format!("x{piece}")] {
let value = json!(want);
for op in ["contains", "notContains"] {
assert_eq!(file_path_matches(op, &source, &value), file_path_old(op, &source, &value), "{op} {want:?}");
}
}
}
}
}
}
mod tests;
+776
View File
@@ -0,0 +1,776 @@
use super::*;
use crate::{ColorLabel, Flag, PhotoId, Source};
use serde_json::json;
fn photo(id: u64) -> Photo {
let mut p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, "IMG_0042.CR2", "CR2", 6000, 4000, "2026-09-20T10:00:00");
p.rating = 4;
p.flag = Flag::Pick;
p.label = Some(ColorLabel::Red);
p.captured = Some("2026-08-14T18:30:00".into());
p.meta.keywords = vec!["travel|italy|rome".into(), "food".into()];
p.meta.camera = "Model X2".into();
p.meta.iso = Some(1600);
p.meta.aperture = Some(2.8);
p
}
fn rs(v: serde_json::Value) -> RuleSet {
serde_json::from_value(v).unwrap()
}
#[test]
fn f32_boundary_values_match_gte_lte() {
let cat = Catalog::new();
let matches = |p: &Photo, field: &str, op: &str, value: f64| rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat);
for v in [1.4f32, 1.8, 2.8, 5.6, 0.95] {
let mut p = photo(1);
p.meta.aperture = Some(v);
p.meta.focal_mm = Some(v);
let w = v.to_string().parse::<f64>().unwrap();
for field in ["aperture", "focalLength"] {
assert!(matches(&p, field, "gte", w), "{field} gte {w}");
assert!(matches(&p, field, "lte", w), "{field} lte {w}");
assert!(!matches(&p, field, "gt", w), "{field} gt {w}");
assert!(!matches(&p, field, "lt", w), "{field} lt {w}");
}
}
}
#[test]
fn fields_ops_and_groups() {
let cat = Catalog::new();
let p = photo(1);
let yes = |v: serde_json::Value| assert!(rs(v.clone()).matches(&p, &cat), "{v}");
let no = |v: serde_json::Value| assert!(!rs(v.clone()).matches(&p, &cat), "{v}");
yes(json!({"rules": [{"field": "rating", "op": "gte", "value": 3}, {"field": "flag", "op": "is", "value": "pick"}]}));
no(json!({"rules": [{"field": "rating", "op": "gt", "value": 4}]}));
yes(json!({"match": "any", "rules": [{"field": "rating", "op": "is", "value": 1}, {"field": "label", "op": "is", "value": "red"}]}));
no(json!({"match": "none", "rules": [{"field": "label", "op": "is", "value": "red"}]}));
yes(json!({"rules": [{"field": "keywords", "op": "is", "value": "italy"}]}));
yes(json!({"rules": [{"field": "keywords", "op": "contains", "value": "ROME"}, {"field": "keywords", "op": "notContains", "value": "beach"}]}));
no(json!({"rules": [{"field": "keywords", "op": "isEmpty"}]}));
yes(json!({"rules": [{"field": "fileName", "op": "startsWith", "value": "img_"}, {"field": "fileName", "op": "endsWith", "value": ".cr2"}]}));
// file path: the whole string (spaces included), either separator, case-insensitive
let mut fp = photo(3);
fp.source = Source::File { path: "D:\\Photos\\Lake Como Wedding-Day\\2026\\IMG_0042.CR2".into() };
let fpm = |v: serde_json::Value| rs(v).matches(&fp, &cat);
assert!(fpm(json!({"rules": [{"field": "filePath", "op": "contains", "value": "/Lake Como Wedding-Day/"}]})));
assert!(!fpm(json!({"rules": [{"field": "filePath", "op": "contains", "value": "/Como Lake/"}]})));
assert!(!fpm(json!({"rules": [{"field": "filePath", "op": "contains", "value": "Wedding Day"}]})));
assert!(fpm(json!({"rules": [{"field": "filePath", "op": "notContains", "value": "/Other/"}]})));
assert!(fpm(json!({"rules": [{"field": "filePath", "op": "startsWith", "value": "d:/photos/"}]})));
no(json!({"rules": [{"field": "filePath", "op": "contains", "value": "/Lake/"}]})); // demo photo has no path
yes(json!({"rules": [{"field": "filePath", "op": "isEmpty"}]}));
yes(json!({"rules": [{"field": "camera", "op": "contains", "value": "x2"}, {"field": "title", "op": "isEmpty"}]}));
yes(json!({"rules": [{"field": "iso", "op": "between", "value": [800, 3200]}, {"field": "aperture", "op": "lte", "value": "f/4"}]}));
yes(json!({"rules": [{"field": "megapixels", "op": "gte", "value": 24}]}));
yes(
json!({"rules": [{"field": "captureDate", "op": "is", "value": "2026-08"}, {"field": "captureDate", "op": "before", "value": "2026-09-01"}]}),
);
yes(json!({"rules": [{"field": "captureDate", "op": "between", "value": ["2026-08-01", "2026-08"]}]}));
no(json!({"rules": [{"field": "captureDate", "op": "after", "value": "2026-08"}]}));
yes(json!({"rules": [{"field": "kind", "op": "isNot", "value": "video"}, {"field": "edited", "op": "is", "value": false}]}));
// copyright status (unknown until set)
yes(json!({"rules": [{"field": "copyrightStatus", "op": "is", "value": "unknown"}]}));
no(json!({"rules": [{"field": "copyrightStatus", "op": "is", "value": "copyrighted"}]}));
let mut pd = photo(2);
pd.meta.copyright_status = crate::CopyrightStatus::PublicDomain;
assert!(rs(json!({"rules": [{"field": "copyrightStatus", "op": "is", "value": "publicDomain"}]})).matches(&pd, &cat));
assert!(rs(json!({"rules": [{"field": "copyrightStatus", "op": "isNot", "value": "copyrighted"}]})).matches(&pd, &cat));
// nested: rating ≥ 4 and (label is blue or keywords contain food)
yes(json!({"rules": [{"field": "rating", "op": "gte", "value": 4}, {"group": {"match": "any", "rules": [
{"field": "label", "op": "is", "value": "blue"}, {"field": "keywords", "op": "contains", "value": "food"}]}}]}));
// in the last N days, relative to now
set_now(Some("2026-09-01T00:00:00".into()));
yes(json!({"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 30, "unit": "days"}}]}));
no(json!({"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "weeks"}}]}));
yes(json!({"rules": [{"field": "captureDate", "op": "notInLast", "value": 7}]}));
set_now(None);
// an empty rule list: all → everything, any → nothing
yes(json!({"rules": []}));
no(json!({"match": "any", "rules": []}));
}
#[test]
fn problems_and_description() {
let r = rs(json!({"rules": [{"field": "rating", "op": "contains", "value": 1}, {"group": {"rules": [{"field": "nope", "op": "is"}]}}]}));
let messages: Vec<String> = r.check(&Catalog::new()).into_iter().map(|p| p.message).collect();
assert_eq!(messages, vec!["`rating` has no operator `contains`".to_string(), "unknown field `nope`".to_string()]);
let r = rs(
json!({"match": "any", "rules": [{"field": "rating", "op": "gte", "value": 3}, {"field": "captureDate", "op": "inLast", "value": {"n": 2, "unit": "weeks"}}]}),
);
assert_eq!(r.describe(), "rating is ≥ 3 or capture date is in the last 2 weeks");
// every field has a kind with operators
for (f, _, k) in FIELDS {
assert!(!ops_for(*k).is_empty(), "{f}");
}
}
/// Keyword Count: a photo with 2 keywords is in "≥ 2", "≤ 2" and "is 2"; a hierarchical path
/// (travel|italy|rome) is one keyword, and the same keyword twice in different case is one.
#[test]
fn keyword_count_rules() {
let cat = Catalog::new();
let mut p = photo(1); // travel|italy|rome, food
let m =
|p: &Photo, op: &str, value: serde_json::Value| rs(json!({"rules": [{"field": "keywordCount", "op": op, "value": value}]})).matches(p, &cat);
assert!(m(&p, "gte", json!(2)) && m(&p, "lte", json!(2)) && m(&p, "is", json!(2)));
assert!(!m(&p, "gte", json!(3)) && !m(&p, "lt", json!(2)) && m(&p, "between", json!([1, 2])));
p.meta.keywords.push("Food".into());
assert!(m(&p, "is", json!(2)), "Food and food are one keyword");
p.meta.keywords.clear();
assert!(m(&p, "is", json!(0)) && m(&p, "lte", json!(2)));
assert_eq!(field_group("keywordCount"), Some("Keywords & People"));
}
/// People: the names on face regions. "People contains ana" finds Ana Lima; pets and unnamed
/// faces are not people; People Count counts each person once.
#[test]
fn people_rules() {
use lightcraft_meta::{Rect, Region, RegionKind};
let cat = Catalog::new();
let region = |name: Option<&str>, kind: RegionKind| Region {
rect: Rect { x0: 0.4, y0: 0.4, x1: 0.6, y1: 0.6 },
kind,
name: name.map(str::to_string),
description: None,
};
let mut p = photo(1);
let m = |p: &Photo, field: &str, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat)
};
assert!(m(&p, "person", "isEmpty", json!(null)) && m(&p, "personCount", "is", json!(0)));
p.meta.regions = vec![
region(Some("Ana Lima"), RegionKind::Face),
region(Some(" ana lima "), RegionKind::Face),
region(Some("Rex"), RegionKind::Pet),
region(None, RegionKind::Face),
region(Some("Bo"), RegionKind::Face),
];
assert!(m(&p, "person", "contains", json!("ana")));
assert!(m(&p, "person", "is", json!("ANA LIMA")));
assert!(!m(&p, "person", "is", json!("rex")), "a pet isn't a person");
assert!(m(&p, "person", "notContains", json!("rex")));
assert!(m(&p, "person", "isNotEmpty", json!(null)));
assert!(m(&p, "personCount", "is", json!(2)), "Ana Lima once, Bo; not the pet or the unnamed face");
assert_eq!(field_group("person"), Some("Keywords & People"));
}
/// Shutter Speed compares exposure times in seconds, written as the camera shows them: a
/// photo at 1/250 is in "≤ 1/60" (faster) and not in "≥ 1/60"; "between 1/1000 and 1/125".
#[test]
fn shutter_speed_rules() {
let cat = Catalog::new();
let mut p = photo(1);
let m =
|p: &Photo, op: &str, value: serde_json::Value| rs(json!({"rules": [{"field": "shutterSpeed", "op": op, "value": value}]})).matches(p, &cat);
assert!(!m(&p, "gte", json!(0)), "no shutter speed recorded");
p.meta.shutter = "1/250".into();
assert!(m(&p, "is", json!("1/250")) && m(&p, "lte", json!("1/60")) && !m(&p, "gte", json!("1/60")));
assert!(m(&p, "between", json!(["1/1000", "1/125"])) && m(&p, "lt", json!(0.01)));
assert!(!m(&p, "is", json!("1/0")) && !m(&p, "is", json!("fast")), "a value that isn't a time matches nothing");
p.meta.shutter = "2\"".into();
assert!(m(&p, "gte", json!("1")) && m(&p, "is", json!(2)));
assert_eq!(field_group("shutterSpeed"), Some("Camera Info"));
}
#[test]
fn shutter_seconds_parses_camera_notation() {
for (s, want) in [("1/250", Some(0.004)), (" 1/250 s", Some(0.004)), ("0.5", Some(0.5)), ("2\"", Some(2.0)), ("30s", Some(30.0))] {
assert_eq!(crate::parse_shutter_seconds(s), want, "{s}");
}
for s in ["", "1/0", "0", "-1/250", "fast", "inf", "NaN", "1/x"] {
assert_eq!(crate::parse_shutter_seconds(s), None, "{s}");
}
}
/// File Extension ignores case and a leading dot; Copy Name, Alt Text, City, State /
/// Province and Country are text fields of their own (Location still matches all of them).
#[test]
fn file_source_description_and_location_rules() {
let cat = Catalog::new();
let mut p = photo(1); // IMG_0042.CR2
let m = |p: &Photo, field: &str, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat)
};
assert!(m(&p, "extension", "is", json!("cr2")) && m(&p, "extension", "is", json!(".CR2")));
assert!(!m(&p, "extension", "is", json!("jpg")));
p.file_name = "README".into();
assert!(m(&p, "extension", "isEmpty", json!(null)), "no dot, no extension");
p.file_name = "archive.tar.gz".into();
assert!(m(&p, "extension", "is", json!("gz")));
p.file_name = ".hidden".into();
assert!(m(&p, "extension", "isEmpty", json!(null)), "a dot file has no extension");
assert!(m(&p, "copyName", "isEmpty", json!(null)));
p.copy_name = Some("Black and white".into());
assert!(m(&p, "copyName", "contains", json!("black")));
p.meta.alt_text = "A red kite over a hill".into();
assert!(m(&p, "altText", "contains", json!("kite")));
p.meta.city = "Porto".into();
p.meta.state = "Porto District".into();
p.meta.country = "Portugal".into();
assert!(m(&p, "city", "is", json!("porto")) && m(&p, "state", "startsWith", json!("porto")) && m(&p, "country", "is", json!("portugal")));
assert!(!m(&p, "city", "is", json!("portugal")), "City tests only the city");
assert!(m(&p, "location", "contains", json!("portugal")), "Location still covers the country");
}
/// In a Stack, Video Duration (seconds; photos have none), Cropped and Treatment.
#[test]
fn source_file_and_develop_rules() {
use crate::{Op, Stack, StackId};
let mut cat = Catalog::new();
let a = photo(1);
let b = photo(2);
let c = photo(3);
for p in [&a, &b, &c] {
cat.apply(Op::AddPhoto { photo: Box::new(p.clone()) }).unwrap();
}
cat.apply(Op::AddStack { stack: Stack { id: StackId(1), photos: vec![a.id, b.id], collapsed: false } }).unwrap();
let m = |p: &Photo, field: &str, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat)
};
assert!(m(&a, "stacked", "is", json!(true)) && m(&b, "stacked", "is", json!(true)));
assert!(m(&c, "stacked", "is", json!(false)));
let mut v = photo(4);
assert!(!m(&v, "duration", "gte", json!(0)), "a photo has no duration");
v.duration = Some(95.0);
assert!(m(&v, "duration", "gt", json!(60)) && m(&v, "duration", "between", json!([90, 120])));
let mut d = photo(5);
assert!(m(&d, "cropped", "is", json!(false)) && m(&d, "treatment", "is", json!("color")));
let mut s = (*d.develop).clone();
s.crop.geometry.rect = lightcraft_geom::Rect::new(0.1, 0.0, 0.9, 1.0);
s.treatment = lightcraft_develop::Treatment::Bw;
d.develop = std::sync::Arc::new(s);
assert!(m(&d, "cropped", "is", json!(true)) && m(&d, "treatment", "is", json!("monochrome")));
assert!(m(&d, "treatment", "isNot", json!("color")));
let mut s = (*d.develop).clone();
s.crop = Default::default();
s.crop.geometry.angle = 2.0;
d.develop = std::sync::Arc::new(s);
assert!(m(&d, "cropped", "is", json!(true)), "straightening counts as a crop");
}
/// Size follows the photo as shown: rotated a quarter turn a landscape frame is a portrait, and
/// a crop changes its edges and its megapixels. Long / Short Edge are in pixels.
#[test]
fn size_rules_follow_orientation_and_crop() {
let cat = Catalog::new();
let mut p = photo(1); // 6000 × 4000
let m = |p: &Photo, field: &str, op: &str, value: serde_json::Value| {
rs(json!({"rules": [{"field": field, "op": op, "value": value}]})).matches(p, &cat)
};
assert!(m(&p, "aspect", "is", json!("landscape")) && m(&p, "longEdge", "is", json!(6000)) && m(&p, "shortEdge", "is", json!(4000)));
assert!(m(&p, "megapixels", "is", json!(24)));
let mut s = (*p.develop).clone();
s.orientation = lightcraft_geom::Orientation::Rotate90;
p.develop = std::sync::Arc::new(s.clone());
assert!(m(&p, "aspect", "is", json!("portrait")) && m(&p, "longEdge", "is", json!(6000)));
// a square crop of the rotated frame: 4000 wide, 4000 of its 6000 tall
s.crop.geometry.rect = lightcraft_geom::Rect::new(0.0, 1.0 / 6.0, 1.0, 5.0 / 6.0);
p.develop = std::sync::Arc::new(s);
assert!(m(&p, "aspect", "is", json!("square")) && m(&p, "longEdge", "is", json!(4000)));
assert!(m(&p, "megapixels", "is", json!(16)), "a 4000 × 4000 crop is 16 MP, not the sensor's 24");
assert!(m(&p, "megapixels", "lt", json!(20)) && !m(&p, "megapixels", "gte", json!(24)));
assert!(m(&p, "aspect", "isNot", json!("portrait")));
let empty = Photo::new(PhotoId(9), Source::Demo { scene: 0 }, "x.jpg", "JPEG", 0, 0, "2026-09-20T10:00:00");
assert!(!m(&empty, "aspect", "is", json!("landscape")) && !m(&empty, "aspect", "is", json!("square")) && m(&empty, "longEdge", "is", json!(0)));
assert!(m(&empty, "megapixels", "is", json!(0)));
}
/// Any Searchable Text also finds the state / province, the alt text, a person on a face and
/// a virtual copy's name, as it already finds the city and country.
#[test]
fn any_searchable_text_covers_new_fields() {
let cat = Catalog::new();
let mut p = photo(1);
let m = |p: &Photo, value: &str| rs(json!({"rules": [{"field": "text", "op": "contains", "value": value}]})).matches(p, &cat);
for word in ["oregon", "kite", "ana", "bluish"] {
assert!(!m(&p, word), "{word}");
}
p.meta.state = "Oregon".into();
p.meta.alt_text = "A kite".into();
p.meta.regions = vec![lightcraft_meta::Region {
rect: lightcraft_meta::Rect { x0: 0.4, y0: 0.4, x1: 0.6, y1: 0.6 },
kind: lightcraft_meta::RegionKind::Face,
name: Some("Ana".into()),
description: None,
}];
p.copy_name = Some("Bluish".into());
for word in ["oregon", "kite", "ana", "bluish"] {
assert!(m(&p, word), "{word}");
}
}
/// Choice values have readable labels: the editor and summaries show "Public Domain" and
/// "Black & White", never ids like `publicDomain`; rules still store and accept the ids.
#[test]
fn choices_have_readable_labels() {
assert_eq!(choice_label("copyrightStatus", "publicDomain"), Some("Public Domain"));
assert_eq!(choice_label("treatment", "monochrome"), Some("Black & White"));
// own labels where a shared word would translate wrongly: "Color" is the colour noun (the
// Color panel) and "None" agrees with other nouns in gendered languages
assert_eq!(choice_label("treatment", "color"), Some("In Color"));
assert_eq!(choice_label("label", "none"), Some("No Label"));
assert_eq!(choice_label("flag", "pick"), Some("Picked"));
assert_eq!(choice_label("aspect", "landscape"), Some("Landscape (wide)"));
assert_eq!(choice_label("flag", "nope"), None);
assert_eq!(choice_label("rating", "pick"), None, "not a choice field");
for (field, _, kind) in FIELDS {
let Kind::Choice(choices) = kind else { continue };
for (id, label) in *choices {
assert!(!label.is_empty() && label != id, "{field}: {id} has no label of its own");
assert!(label.starts_with(|c: char| c.is_uppercase()), "{field}: {label}");
}
}
let r = rs(
json!({"rules": [{"field": "copyrightStatus", "op": "is", "value": "publicDomain"}, {"field": "flag", "op": "isNot", "value": "reject"}]}),
);
assert_eq!(r.describe(), "copyright status is public domain and pick flag isn't rejected");
let mut p = photo(1);
p.meta.copyright_status = crate::CopyrightStatus::PublicDomain;
assert!(r.matches(&p, &Catalog::new()), "ids still match");
}
/// Yes/no fields read "Yes" / "No", and a value means the same to matching and to every
/// summary: `false`, `"false"`, `"no"` and `0` are no; `true`, `"yes"`, `1` and a missing value
/// are yes. Anything else is reported, not silently taken as yes.
#[test]
fn yes_no_values() {
for v in [json!(true), json!("true"), json!("Yes"), json!(1), json!(1.0), json!(null)] {
assert_eq!(bool_value(&v), Some(true), "{v}");
}
for v in [json!(false), json!("false"), json!(" NO "), json!(0), json!(0.0)] {
assert_eq!(bool_value(&v), Some(false), "{v}");
}
for v in [json!("maybe"), json!(2), json!(0.5), json!(-1), json!([true]), json!({"x": 1})] {
assert_eq!(bool_value(&v), None, "{v}");
}
assert_eq!((bool_label(true), bool_label(false)), ("Yes", "No"));
let cat = Catalog::new();
let p = photo(1); // unedited
assert!(rs(json!({"rules": [{"field": "edited", "op": "is", "value": "false"}]})).matches(&p, &cat), "\"false\" means no");
assert!(
!rs(json!({"rules": [{"field": "edited", "op": "is", "value": "false"}, {"field": "hasGps", "op": "is", "value": "yes"}]})).matches(&p, &cat)
);
assert!(!rs(json!({"rules": [{"field": "edited", "op": "is", "value": "maybe"}]})).matches(&p, &cat), "an unreadable value matches nothing");
let r = rs(json!({"rules": [{"field": "edited", "op": "is", "value": true}, {"field": "cropped", "op": "is", "value": "false"}]}));
assert_eq!(r.describe(), "has edits is yes and cropped is no");
let bad = rs(json!({"rules": [{"field": "edited", "op": "is", "value": "maybe"}]}));
let messages: Vec<String> = bad.check(&cat).into_iter().map(|p| p.message).collect();
assert_eq!(messages, vec!["`edited` is yes or no, not \"maybe\"".to_string()]);
}
/// "In the last N" never overflows, whatever N an agent or a saved file holds: a zero,
/// negative or unreadable N matches nothing (either way round); an N beyond 10,000 years means
/// "ever", so every dated photo is in it and none is outside it.
#[test]
fn in_the_last_survives_hostile_counts() {
set_now(Some("2026-09-01T00:00:00".into()));
let cat = Catalog::new();
let p = photo(1); // captured 2026-08-14
let m = |op: &str, n: serde_json::Value, unit: &str| {
rs(json!({"rules": [{"field": "captureDate", "op": op, "value": {"n": n, "unit": unit}}]})).matches(&p, &cat)
};
for n in [json!(0), json!(-5), json!(-1e30), json!(-9.3e18), json!("soon")] {
for op in ["inLast", "notInLast"] {
assert!(!m(op, n.clone(), "years"), "{op} {n}");
}
}
for n in [json!(1e30), json!(9.3e18), json!(u64::MAX), json!(20_000)] {
assert!(m("inLast", n.clone(), "years"), "{n} years is ever");
assert!(!m("notInLast", n.clone(), "years"), "{n}");
}
assert!(m("inLast", json!(1e30), "hours") && m("inLast", json!(30), "days"));
set_now(None);
}
/// Every rule's value is checked against its field, so a rule that can't mean anything is
/// reported instead of quietly matching nothing (or everything). Each problem says which rule
/// it is about: "rule 2", or "rule 2.1" inside a group.
#[test]
fn values_are_checked_against_their_field() {
use crate::{Album, AlbumId, Op};
let mut cat = Catalog::new();
cat.apply(Op::AddAlbum { album: Album::new(AlbumId(1), "Trip") }).unwrap();
let smart = Album { smart: Some(Box::default()), ..Album::new(AlbumId(2), "Best") };
cat.apply(Op::AddAlbum { album: smart }).unwrap();
cat.apply(Op::SetLabelName { label: crate::ColorLabel::Red, name: Some("Client".into()) }).unwrap();
let check = |rule: serde_json::Value| rs(json!({"rules": [rule]})).check(&cat);
let ok = |rule: serde_json::Value| assert!(check(rule.clone()).is_empty(), "{rule}: {:?}", check(rule.clone()));
let bad = |rule: serde_json::Value, want: &str| {
let p = check(rule.clone());
assert!(p.iter().any(|p| p.message.contains(want)), "{rule}: wanted {want:?}, got {p:?}");
};
let r = |field: &str, op: &str, value: serde_json::Value| json!({"field": field, "op": op, "value": value});
// numbers
ok(r("rating", "gte", json!(3)));
ok(r("rating", "gte", json!("4")));
ok(r("rating", "between", json!([1, 5])));
ok(r("aperture", "lte", json!("f/4")));
ok(r("focalLength", "is", json!("50mm")));
bad(r("rating", "gte", json!("abc")), "needs a number");
bad(r("rating", "gte", json!(7)), "no rating 0–5 is ≥ 7");
bad(r("iso", "between", json!([100])), "two");
bad(r("iso", "between", json!("100")), "two");
ok(r("shutterSpeed", "lte", json!("1/60")));
bad(r("shutterSpeed", "lte", json!("fast")), "1/250");
// dates
for d in ["2026", "2026-08", "2026-08-14", "2026-08-14T10:00:00"] {
ok(r("captureDate", "is", json!(d)));
}
ok(r("captureDate", "between", json!(["2026-01", "2026-12"])));
for d in [json!("banana"), json!("2026-13"), json!("2026-02-30"), json!(""), json!(2026)] {
bad(r("captureDate", "after", d), "needs a date");
}
bad(r("captureDate", "between", json!(["2026-12", "2026-01"])), "after the second");
bad(r("captureDate", "between", json!(["", "2026"])), "needs a date");
ok(r("captureDate", "inLast", json!({"n": 2, "unit": "weeks"})));
ok(r("captureDate", "inLast", json!(7)));
bad(r("captureDate", "inLast", json!({"n": 0, "unit": "days"})), "more than 0");
bad(r("captureDate", "notInLast", json!({"n": 3, "unit": "fortnights"})), "fortnights");
ok(r("captureDate", "isEmpty", json!(null)));
// choices: the ids, the flag's aliases and a colour label's custom name
ok(r("kind", "is", json!("raw")));
ok(r("flag", "is", json!("picked")));
ok(r("label", "is", json!("client")));
bad(r("label", "is", json!("pink")), "pink");
bad(r("kind", "isNot", json!("photo")), "photo");
// text needs something to look for
ok(r("title", "contains", json!("kite")));
ok(r("title", "isEmpty", json!(null)));
bad(r("title", "contains", json!(" ")), "something to look for");
bad(r("keywords", "startsWith", json!("")), "something to look for");
// albums: one that exists, plain or smart
ok(r("album", "is", json!(1)));
bad(r("album", "is", json!(999)), "no album 999");
ok(r("album", "is", json!(2)));
// groups: an empty one is a mistake; problems inside one say where they are
let p = rs(json!({"rules": [r("rating", "gte", json!(3)), {"group": {"match": "any", "rules": []}}]})).check(&cat);
assert_eq!(p.iter().map(ToString::to_string).collect::<Vec<_>>(), vec!["rule 2: an empty group".to_string()]);
let p = rs(json!({"rules": [r("rating", "gte", json!(3)), {"group": {"rules": [r("iso", "is", json!(100)), r("rating", "is", json!(9))]}}]}))
.check(&cat);
assert_eq!(p.len(), 1);
assert_eq!(p[0].path, vec![1, 1]);
assert_eq!(p[0].to_string(), "rule 2.2: no rating 0–5 is 9");
// an empty rule list at the top is "all photos" (or none, for any), not a mistake
assert!(rs(json!({"rules": []})).check(&cat).is_empty());
}
/// The check and the matcher agree. Units are any case, singular or plural, and missing means
/// days; an unknown unit is refused and matches nothing (it used to count as days, so "week" was
/// one day). A rating rule is refused only when no rating 0–5 could meet it. A colour label's
/// custom name matches in any case, accents included. Empty text hints at the right operator.
#[test]
fn check_and_matcher_agree() {
use crate::Op;
set_now(Some("2026-09-01T00:00:00".into()));
let mut cat = Catalog::new();
cat.apply(Op::SetLabelName { label: crate::ColorLabel::Red, name: Some("Été".into()) }).unwrap();
let p = photo(1); // captured 2026-08-14 (18 days before now), red label, rating 4
let rule = |field: &str, op: &str, value: serde_json::Value| rs(json!({"rules": [{"field": field, "op": op, "value": value}]}));
let valid = |r: &RuleSet| r.check(&cat).is_empty();
for unit in [json!("Days"), json!("DAY"), json!("days"), json!(null)] {
let r = rule("captureDate", "inLast", json!({"n": 30, "unit": unit}));
assert!(valid(&r) && r.matches(&p, &cat), "{unit}");
}
let r = rule("captureDate", "inLast", json!({"n": 30}));
assert!(valid(&r) && r.matches(&p, &cat), "no unit is days");
let week = rule("captureDate", "inLast", json!({"n": 1, "unit": "week"}));
assert!(valid(&week) && !week.matches(&p, &cat), "a week, not a day: 18 days ago is outside it");
assert!(rule("captureDate", "inLast", json!({"n": 3, "unit": "Weeks"})).matches(&p, &cat));
let odd = rule("captureDate", "inLast", json!({"n": 30, "unit": "fortnights"}));
assert!(!valid(&odd) && !odd.matches(&p, &cat), "an unknown unit is refused and matches nothing");
// rating: only a rule no rating could meet
for (op, v) in [("lt", json!(6)), ("gt", json!(-1)), ("isNot", json!(9)), ("between", json!([3, 8]))] {
assert!(valid(&rule("rating", op, v.clone())), "{op} {v}");
}
for (op, v) in [("is", json!(9)), ("gte", json!(7)), ("gt", json!(5)), ("lt", json!(0)), ("between", json!([6, 9]))] {
assert!(!valid(&rule("rating", op, v.clone())), "{op} {v}");
}
// a custom label name, any case, accents too
let r = rule("label", "is", json!("été"));
assert!(valid(&r) && r.matches(&p, &cat));
// "isn't" with nothing points at "isn't empty", the others at "is empty"
let hint = |op: &str| rule("title", op, json!("")).check(&cat).first().map(|p| p.message.clone()).unwrap_or_default();
assert!(hint("isNot").contains("isn't empty"), "{}", hint("isNot"));
assert!(hint("contains").contains("“is empty”"), "{}", hint("contains"));
set_now(None);
}
/// An album is in it or not: Album offers "is" and "isn't", never "≥" or "between".
#[test]
fn album_rules_are_is_or_isnt() {
assert_eq!(field_kind("album"), Some(Kind::Album));
let ops: Vec<&str> = ops_for(Kind::Album).iter().map(|o| o.0).collect();
assert_eq!(ops, ["is", "isNot"]);
let r = rs(json!({"rules": [{"field": "album", "op": "gte", "value": 1}]}));
assert_eq!(r.check(&Catalog::new()).first().map(|p| p.message.as_str()), Some("`album` has no operator `gte`"));
}
/// An Album rule names its album by id, written as a number or a numeric string, the same way
/// for the check, the matcher and the editor. A folder holds albums, not photos, so it can't be
/// tested.
#[test]
fn album_rule_ids() {
use crate::{Album, AlbumId, Op};
assert_eq!(album_rule_id(&json!(3)), Some(AlbumId(3)));
assert_eq!(album_rule_id(&json!("3")), Some(AlbumId(3)));
assert_eq!(album_rule_id(&json!(3.0)), Some(AlbumId(3)));
for v in [json!(1.5), json!(-1), json!("x"), json!(null)] {
assert_eq!(album_rule_id(&v), None, "{v}");
}
let mut cat = Catalog::new();
cat.apply(Op::AddAlbum { album: Album { folder: true, ..Album::new(AlbumId(4), "Trips") } }).unwrap();
let p = rs(json!({"rules": [{"field": "album", "op": "is", "value": 4}]})).check(&cat);
assert!(p.first().is_some_and(|p| p.message.contains("folder")), "{p:?}");
}
/// Album rules saved before Album offered only "is" / "isn't" (≥, between… from when it was a
/// number field) always meant "isn't" to the matcher; upgrading says so, so they check again.
#[test]
fn old_album_operators_upgrade_to_isnt() {
let mut r = rs(json!({"rules": [
{"field": "album", "op": "gte", "value": 1},
{"field": "album", "op": "is", "value": 1},
{"field": "rating", "op": "gte", "value": 3},
{"group": {"rules": [{"field": "album", "op": "between", "value": [1, 2]}]}}
]}));
r.upgrade();
let ops = serde_json::to_value(&r).unwrap().to_string();
assert!(ops.contains(r#""field":"album","op":"isNot","value":1"#), "{ops}");
assert!(ops.contains(r#""field":"album","op":"is","value":1"#), "{ops}");
assert!(ops.contains(r#""field":"rating","op":"gte""#), "other fields keep theirs: {ops}");
assert!(ops.contains(r#""field":"album","op":"isNot","value":[1,2]"#), "inside groups too: {ops}");
}
/// Besides its English message (for agents), a problem names its field and the kind of issue,
/// so the editor can show "Title: needs something to look for" in any language. Every issue
/// has its own short text.
#[test]
fn problems_name_their_field_and_issue() {
let cat = Catalog::new();
let check = |rules: serde_json::Value| rs(json!({"rules": rules})).check(&cat);
let p = check(json!([{"field": "title", "op": "contains", "value": ""}]));
assert_eq!((p[0].field.as_deref(), p[0].issue), (Some("title"), Issue::NeedsTextOrEmpty));
let p = check(json!([{"field": "title", "op": "isNot", "value": ""}]));
assert_eq!(p[0].issue, Issue::NeedsTextOrNotEmpty);
// keywords and people say "are empty", and so does their hint
let p = check(json!([{"field": "keywords", "op": "contains", "value": ""}, {"field": "person", "op": "notContains", "value": " "}]));
assert_eq!((p[0].issue, p[1].issue), (Issue::NeedsNamesOrEmpty, Issue::NeedsNamesOrNotEmpty));
assert!(p[0].issue.text().contains("“are empty”") && p[0].message.contains("“are empty”"));
let p = check(json!([{"field": "rating", "op": "is", "value": 9}, {"group": {"rules": []}}]));
assert_eq!((p[0].field.as_deref(), p[0].issue), (Some("rating"), Issue::NoRatingMatches));
assert_eq!((p[1].field.as_deref(), p[1].issue), (None, Issue::EmptyGroup));
let p = check(json!([{"field": "captureDate", "op": "between", "value": ["2026-12", "2026-01"]}]));
assert_eq!(p[0].issue, Issue::DatesReversed);
let p = check(json!([{"field": "album", "op": "is", "value": null}]));
assert_eq!(p[0].issue, Issue::ChooseAlbum);
let mut texts: Vec<&str> = Issue::ALL.iter().map(|i| i.text()).collect();
assert!(texts.iter().all(|t| !t.is_empty()));
texts.sort_unstable();
texts.dedup();
assert_eq!(texts.len(), Issue::ALL.len(), "each issue reads differently");
}
/// A rule date reads one way for the check and the matcher: a space works as the "T"
/// ("2026-10-01 10:00" matches a photo taken then). Imported capture times can carry fractions
/// of a second and a time zone (EXIF SubSecTime / OffsetTime: "…T10:00:00.250+02:00"), so a
/// rule may too, after the seconds; anywhere else they are no date.
#[test]
fn rule_dates_have_one_reading() {
let cat = Catalog::new();
let mut p = photo(1);
p.captured = Some("2026-10-01T10:00:00".into());
let rule = |op: &str, v: serde_json::Value| rs(json!({"rules": [{"field": "captureDate", "op": op, "value": v}]}));
for (op, v) in [
("is", json!("2026-10-01 10:00")),
("is", json!(" 2026-10-01T10 ")),
("between", json!(["2026-10-01 09:00", "2026-10-01 11:00"])),
("after", json!("2026-10-01 09:59")),
] {
let r = rule(op, v.clone());
assert!(r.check(&cat).is_empty() && r.matches(&p, &cat), "{op} {v}");
}
// a capture time with a fraction and a zone, as imports write it
let mut zoned = photo(2);
zoned.captured = Some("2026-08-14T10:00:00.250+02:00".into());
for v in ["2026-08-14T10:00:00.250", "2026-08-14T10:00:00.250+02:00", "2026-08-14T10:00:00"] {
let r = rule("is", json!(v));
assert!(r.check(&cat).is_empty() && r.matches(&zoned, &cat), "{v}");
}
assert!(rule("is", json!("2026-08-14T10:00:00Z")).check(&cat).is_empty());
for v in [
"2026-8-14",
"2026-08-14T1",
"2026-08-14X10",
"26-08-14",
"2026-08-14T25:00",
"2026-08-14Z",
"2026-08-14 10:00-05:00",
"2026-08-14T10:00:00.",
"2026-08-14T10:00:00+2",
] {
let p = rule("is", json!(v)).check(&cat);
assert_eq!(p.first().map(|p| p.issue), Some(Issue::NeedsDate), "{v}");
}
assert_eq!(rule_date("2026-10-01 10:00"), Ok("2026-10-01T10:00".to_string()));
assert_eq!(rule_date("2026"), Ok("2026".to_string()));
}
/// The field menu shows every rule field once: at the top level or in exactly one group,
/// and [`FIELDS`] lists them in menu order.
#[test]
fn every_field_is_in_the_menu_exactly_once() {
let menu: Vec<&str> = TOP_LEVEL_FIELDS.iter().chain(FIELD_GROUPS.iter().flat_map(|g| g.1.iter())).copied().collect();
let fields: Vec<&str> = FIELDS.iter().map(|f| f.0).collect();
assert_eq!(menu, fields, "the menu and FIELDS list the same fields in the same order");
for (label, group) in FIELD_GROUPS {
assert!(!group.is_empty(), "group {label} is empty");
}
let mut labels: Vec<&str> = FIELD_GROUPS.iter().map(|g| g.0).collect();
labels.dedup();
assert_eq!(labels.len(), FIELD_GROUPS.len(), "group labels are unique");
}
/// Related fields sit together: all the file fields, all the camera (EXIF) fields, all the
/// dates, all the keyword fields.
#[test]
fn related_fields_share_a_group() {
let same = |fields: &[&str], group: &str| {
for f in fields {
assert_eq!(field_group(f), Some(group), "{f}");
}
};
same(&["fileName", "extension", "filePath", "kind", "format", "duration"], "File");
same(&["album", "virtualCopy", "copyName", "stacked"], "Source");
same(&["longEdge", "shortEdge", "aspect", "megapixels"], "Size");
same(&["edited", "cropped", "treatment"], "Develop");
same(&["camera", "lens", "focalLength", "aperture", "shutterSpeed", "iso"], "Camera Info");
same(&["captureDate", "importDate", "editDate"], "Date");
same(&["keywords", "keywordCount", "person", "personCount"], "Keywords & People");
same(&["title", "caption", "altText", "creator", "copyright", "copyrightStatus"], "Description");
same(&["location", "city", "state", "country", "hasGps"], "Location");
for f in ["rating", "flag", "label", "text"] {
assert_eq!(field_group(f), None, "{f} stays at the top level");
}
assert_eq!(field_group("nope"), None);
assert_eq!(field_label("filePath"), Some("File Path"));
assert_eq!(field_label("nope"), None);
}
/// The `filePath` rule exactly as it was before the in-place ASCII path: new strings per photo.
fn file_path_old(op: &str, source: &Source, value: &serde_json::Value) -> bool {
let want = lower(value);
let path = match source {
Source::File { path } => path.replace('\\', "/"),
Source::Demo { .. } => String::new(),
};
let want = want.replace('\\', "/");
match op {
"contains" => !want.trim().is_empty() && path.to_lowercase().contains(want.trim()),
"notContains" => want.trim().is_empty() || !path.to_lowercase().contains(want.trim()),
_ => text_op(op, &path, &want),
}
}
#[test]
fn file_path_rules_match_the_old_strings_for_any_path() {
let paths = [
"",
" ",
" /a/b.jpg \t",
"/Volumes/share/photos/Trip/IMG_0001.jpg",
"/Volumes/share/PHOTOS/trip/img_0001.JPG",
r"D:\Photos\Lake Como\IMG_0001.JPG",
r"d:/photos/lake como/img_0001.jpg",
r"\\nas\share\x.jpg",
"/photos/Straße/a.jpg",
"/photos/STRASSE/a.jpg",
"/photos/İstanbul/a.jpg",
"/photos/i̇stanbul/a.jpg",
"/photos/ΟΔΟΣ/a.jpg",
"/photos/οδος/a.jpg",
"/photos/ΟΔΌΣ/a.jpg",
"/photos/日本/東京.jpg",
"/p/\u{0B}x\u{0B}",
"/p/\u{85}x\u{85}",
"a",
];
let wants = [
"",
" ",
"a",
"A",
"/",
r"\",
r"\photos\",
"/photos/",
"photos",
"PHOTOS",
"Lake Como",
" lake como ",
"lake como",
r"d:\photos\lake",
"IMG_0001.JPG",
".jpg",
"straße",
"STRASSE",
"strasse",
"İstanbul",
"i̇stanbul",
"istanbul",
"ΟΔΟΣ",
"οδος",
"οδοσ",
"ΟΔΌΣ",
"東京",
"日本",
"x",
"\u{0B}x",
"/a/b.jpg",
"/a/b.jpg \t",
"\u{85}x",
];
let ops = ["contains", "notContains", "is", "isNot", "startsWith", "endsWith", "isEmpty", "isNotEmpty", "bogus"];
let mut values: Vec<serde_json::Value> = wants.iter().map(|w| json!(w)).collect();
values.extend([json!(null), json!(5), json!(true), json!(["a", "b"])]);
let mut sources: Vec<Source> = paths.iter().map(|p| Source::File { path: (*p).into() }).collect();
sources.push(Source::Demo { scene: 0 });
for source in &sources {
for op in ops {
for value in &values {
assert_eq!(file_path_matches(op, source, value), file_path_old(op, source, value), "{source:?} {op} {value}");
}
}
}
}
#[test]
fn file_path_rule_through_a_rule_set_ignores_case_and_slash_direction() {
let mut p = photo(1);
p.source = Source::File { path: r"D:\Photos\Lake Como\IMG_0001.JPG".into() };
let r = rs(json!({"rules": [{"field": "filePath", "op": "contains", "value": "/LAKE como/"}]}));
assert!(r.matches(&p, &Catalog::default()));
}
/// Every piece of a long path, in both cases and both slash directions, wherever it starts
/// (the search skips eight bytes at a time, so starts and ends at every offset matter).
#[test]
fn file_path_contains_finds_every_piece_of_a_long_path() {
let path = r"D:\Photos\Lake Como\Wedding-Day_2026\IMG_0001 (copy).JPG";
let source = Source::File { path: path.into() };
let shout = |s: &str| s.to_uppercase();
let swap = |s: &str| s.replace('\\', "/");
for from in 0..path.len() {
for to in from + 1..=path.len() {
let piece = &path[from..to];
for want in [piece.to_string(), shout(piece), swap(piece), piece.replace('/', r"\"), format!("{piece}x"), format!("x{piece}")] {
let value = json!(want);
for op in ["contains", "notContains"] {
assert_eq!(file_path_matches(op, &source, &value), file_path_old(op, &source, &value), "{op} {want:?}");
}
}
}
}
}
+108 -6
View File
@@ -23,6 +23,7 @@
//! replacing anything** (a hard link, which fails on a taken name; where the volume has no hard
//! links, an exclusive create that claims the name, then a rename over that placeholder).
//! - [`same_file`] tells whether two paths name the same file on disk (device + inode on Unix,
//! volume serial number + file index on Windows,
//! resolved paths elsewhere), for "is this target an original?" checks.
use std::cell::Cell;
@@ -267,26 +268,75 @@ fn same_content(path: &Path, data: &[u8]) -> io::Result<bool> {
}
}
/// Do `a` and `b` name the same existing file (through links, `..`, case-insensitive names)?
/// Do `a` and `b` name the same existing file (through hard links, symlinks, `..`,
/// case-insensitive names)?
pub fn same_file(a: &Path, b: &Path) -> bool {
let (Ok(ma), Ok(mb)) = (fs::metadata(a), fs::metadata(b)) else { return false };
compare_files(a, b, false).unwrap_or(false)
}
/// [`same_file`] for a check that must not let an unknown identity pass: `Err` when the metadata
/// of either path cannot be read for a reason other than the path not existing (for example a
/// folder it cannot enter), or when both paths exist with the same length but the file identity
/// of either cannot be read (on Windows, when either file cannot be opened or reports file index 0). A path that does not
/// exist is still `Ok(false)`.
pub fn same_file_strict(a: &Path, b: &Path) -> io::Result<bool> {
compare_files(a, b, true)
}
fn compare_files(a: &Path, b: &Path, strict: bool) -> io::Result<bool> {
let missing = |e: &io::Error| matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::NotADirectory);
let (ma, mb) = match (fs::metadata(a), fs::metadata(b)) {
(Ok(ma), Ok(mb)) => (ma, mb),
(Err(e), _) | (_, Err(e)) if strict && !missing(&e) => return Err(e),
_ => return Ok(false),
};
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
ma.dev() == mb.dev() && ma.ino() == mb.ino()
Ok(ma.dev() == mb.dev() && ma.ino() == mb.ino())
}
#[cfg(not(unix))]
{
if ma.len() != mb.len() {
return false;
return Ok(false);
}
match (fs::canonicalize(a), fs::canonicalize(b)) {
// A hard link has its own path but shares the volume serial number and file index with
// its original. A file index of 0 produces an error in strict mode. Lenient mode compares resolved paths.
// On ReFS two files can share the 64-bit file index, so the lengths are compared first.
#[cfg(windows)]
{
match file_ids(a, b).and_then(|(ia, ib)| same_file_id(ia, ib, strict)) {
Ok(true) => return Ok(true),
Ok(_) => {}
Err(e) if strict => return Err(e),
Err(_) => {}
}
}
Ok(match (fs::canonicalize(a), fs::canonicalize(b)) {
(Ok(x), Ok(y)) => x == y || x.to_string_lossy().to_lowercase() == y.to_string_lossy().to_lowercase(),
_ => false,
}
})
}
}
/// The volume serial number and file index of `a` and `b`, read while both files are open.
#[cfg(windows)]
fn file_ids(a: &Path, b: &Path) -> io::Result<((u64, u64), (u64, u64))> {
use winapi_util::{Handle, file::information};
let (ha, hb) = (Handle::from_path_any(a)?, Handle::from_path_any(b)?);
let (ia, ib) = (information(&ha)?, information(&hb)?);
Ok(((ia.volume_serial_number(), ia.file_index()), (ib.volume_serial_number(), ib.file_index())))
}
/// The comparison uses each file's volume serial number and file index. Strict mode returns an error for file index 0.
#[cfg(any(windows, test))]
fn same_file_id(a: (u64, u64), b: (u64, u64), strict: bool) -> io::Result<bool> {
if strict && (a.1 == 0 || b.1 == 0) {
return Err(io::Error::other("file identity is unavailable"));
}
Ok(a.1 != 0 && b.1 != 0 && a == b)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -397,6 +447,29 @@ mod tests {
let _ = fs::remove_dir_all(&d);
}
#[test]
fn same_file_sees_a_hard_link_under_another_name() {
let d = temp("same-link");
let p = d.join("IMG_1.jpg");
fs::write(&p, b"original").unwrap();
let linked = d.join("linked.png");
match fs::hard_link(&p, &linked) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => panic!("{}: {e}", linked.display()),
// no hard links on this volume (FAT/exFAT, some shares), as in `publish_new`
Err(e) => {
let _ = fs::remove_dir_all(&d);
lightcraft_testkit::skip!(System, "no hard links in {}: {e}", d.display());
return;
}
}
fs::write(d.join("copy.png"), b"original").unwrap();
assert!(same_file(&p, &linked), "a hard link is the same file");
assert!(same_file(&linked, &p));
assert!(!same_file(&p, &d.join("copy.png")), "a copy with the same content and length is another file");
let _ = fs::remove_dir_all(&d);
}
#[test]
fn same_file_sees_through_other_spellings() {
let d = temp("same");
@@ -409,4 +482,33 @@ mod tests {
assert!(!same_file(&p, &d.join("missing.jpg")));
let _ = fs::remove_dir_all(&d);
}
#[test]
fn strict_comparison_reports_a_path_it_cannot_query() {
let d = temp("strict-query");
let p = d.join("x.jpg");
fs::write(&p, b"x").unwrap();
// A NUL byte makes the metadata lookup fail with an error other than "not found" on
// every platform, as a folder the process cannot enter does.
let unreadable = Path::new("IMG_1\0.jpg");
assert!(same_file_strict(unreadable, &p).is_err());
assert!(same_file_strict(&p, unreadable).is_err());
assert!(!same_file(unreadable, &p), "the lenient comparison still answers false");
assert!(!same_file_strict(&d.join("missing.jpg"), &p).unwrap(), "a missing original is another file");
assert!(!same_file_strict(&p.join("under-a-file.jpg"), &p).unwrap());
let _ = fs::remove_dir_all(&d);
}
#[test]
fn a_zero_file_index_is_not_a_file_identity() {
for strict in [false, true] {
assert!(same_file_id((7, 42), (7, 42), strict).unwrap());
assert!(!same_file_id((7, 42), (7, 43), strict).unwrap());
assert!(!same_file_id((7, 42), (8, 42), strict).unwrap());
}
for (a, b) in [((7, 0), (7, 0)), ((0, 0), (0, 0)), ((7, 42), (7, 0)), ((7, 0), (7, 42))] {
assert!(same_file_id(a, b, true).is_err(), "strict comparison must reject an unavailable identity: {a:?}, {b:?}");
assert!(!same_file_id(a, b, false).unwrap(), "lenient comparison can fall back to resolved paths");
}
}
}
+38
View File
@@ -45,6 +45,18 @@ pub trait Store: Send {
}
}
/// Appends and truncates open the name's own file, so anything else at the name is the library's
/// problem: a link planted there redirects the write outside the directory (CWE-59), and a device
/// hangs the open. Refused with an error the open can show, before anything is written through.
fn check_regular_directory_entry(path: &Path) -> io::Result<()> {
match std::fs::symlink_metadata(path) {
Ok(md) if md.is_file() => Ok(()),
Ok(md) => Err(io::Error::other(format!("{} is a {:?}, not a regular file", path.display(), md.file_type()))),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
/// Files in a directory.
pub struct FsStore {
dir: PathBuf,
@@ -137,6 +149,7 @@ impl Store for FsStore {
fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> {
use std::io::Write;
if self.appender.as_ref().is_none_or(|(n, _)| n != name) {
check_regular_directory_entry(&self.path(name))?;
let existed = self.path(name).exists();
let f = std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?;
if !existed {
@@ -159,6 +172,7 @@ impl Store for FsStore {
if self.appender.as_ref().is_some_and(|(n, _)| n == name) {
self.appender = None;
}
check_regular_directory_entry(&self.path(name))?;
let f = match std::fs::OpenOptions::new().write(true).open(self.path(name)) {
Ok(f) => f,
// nothing to cut (an append that failed before creating the file)
@@ -266,4 +280,28 @@ mod tests_staging {
assert_eq!(std::fs::read(dir.join("catalog.log")).unwrap(), b"[1]");
let _ = std::fs::remove_dir_all(&dir);
}
/// The journal's append and truncate (which recovery uses) refuse a non-regular file at the
/// name instead of following it, so a link planted at `catalog.log` never receives library
/// bytes (CWE-59, Audit row 107); the snapshot write already removes such a link (#1502).
#[test]
fn append_and_truncate_refuse_a_link_at_the_name() {
let dir = std::env::temp_dir().join(format!("lc-log-link-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let victim = dir.join("victim.txt");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(&victim, b"keep").unwrap();
std::os::unix::fs::symlink(&victim, dir.join("catalog.log")).unwrap();
let mut store = FsStore::open(&dir).unwrap();
assert!(store.append("catalog.log", b"appended").is_err());
assert!(store.truncate("catalog.log", 0).is_err());
assert_eq!(std::fs::read(&victim).unwrap(), b"keep");
assert!(std::fs::symlink_metadata(dir.join("catalog.log")).unwrap().file_type().is_symlink());
// A regular file keeps working.
std::fs::remove_file(dir.join("catalog.log")).unwrap();
std::fs::write(dir.join("catalog.log"), b"abc").unwrap();
store.truncate("catalog.log", 1).unwrap();
assert_eq!(std::fs::read(dir.join("catalog.log")).unwrap(), b"a");
let _ = std::fs::remove_dir_all(&dir);
}
}
+91 -14
View File
@@ -8,7 +8,9 @@
use std::collections::{HashMap, HashSet};
use crate::{AlbumId, Aspects, Catalog, PhotoId};
use crate::query::Filter;
use crate::rules::{AlbumPass, MAX_ALBUM_DEPTH};
use crate::{Album, AlbumId, Aspects, Catalog, PhotoId};
/// The most photos an edit may touch for the counts to follow it photo by photo.
const MAX_FOLLOWED: usize = 256;
@@ -20,7 +22,7 @@ const WORDS_TO_START: usize = 1024;
/// The photos a smart album holds.
#[derive(Clone, Debug)]
enum Members {
pub(crate) enum Members {
/// One bit a photo id, and how many are set.
Bits {
words: Vec<u64>,
@@ -41,8 +43,7 @@ impl Members {
}
}
#[cfg(test)]
fn holds(&self, id: PhotoId) -> bool {
pub(crate) fn holds(&self, id: PhotoId) -> bool {
match self {
Members::Bits { words, .. } => {
usize::try_from(id.0 / 64).ok().and_then(|at| words.get(at)).is_some_and(|word| word & (1u64 << (id.0 % 64)) != 0)
@@ -114,21 +115,46 @@ pub struct AlbumTally {
impl AlbumTally {
/// Counted from every photo.
///
/// A smart album that tests another (`album is #14`) reads that album's photos, counted once for the whole
/// pass, instead of working its rules out again for every photo: albums are counted shortest chain first.
/// The photos are kept only until this function returns, so they can't be older than the catalog counted.
/// An album whose rules lead into a loop, or through a chain too deep to be sure of, is counted by its rules
/// as before: the pass ends before the first of them (they sort last), so nothing they evaluate reads it.
pub fn of(cat: &Catalog) -> AlbumTally {
let heights = chain_heights(cat);
let height_of = |id: AlbumId| heights.get(&id).copied().flatten().filter(|h| *h <= MAX_ALBUM_DEPTH);
let mut smart: Vec<AlbumId> = cat.albums().filter(|a| a.is_smart()).map(|a| a.id).collect();
smart.sort_by_key(|id| height_of(*id).unwrap_or(usize::MAX));
let held_by = |id: AlbumId| {
let mut held = Members::none();
for p in cat.photos().filter(|p| cat.album_contains(id, p)) {
held.set(p.id, true);
}
held
};
let mut counts = HashMap::new();
let mut members = HashMap::new();
for album in cat.albums() {
if album.is_smart() {
let mut held = Members::none();
for p in cat.photos().filter(|p| cat.album_contains(album.id, p)) {
held.set(p.id, true);
}
counts.insert(album.id, held.len());
members.insert(album.id, held);
} else {
counts.insert(album.id, cat.album_count(album.id));
let split = smart.partition_point(|id| height_of(*id).is_some());
let (with_height, without) = smart.split_at(split);
let pass = AlbumPass::begin();
for id in with_height {
let held = held_by(*id);
counts.insert(*id, held.len());
if let Some(height) = height_of(*id) {
pass.remember(*id, height, held);
}
}
members.extend(pass.finish());
for id in without {
let held = held_by(*id);
counts.insert(*id, held.len());
members.insert(*id, held);
}
for album in cat.albums().filter(|a| !a.is_smart()) {
counts.insert(album.id, cat.album_count(album.id));
}
AlbumTally { revision: cat.revision, counts, members }
}
@@ -184,6 +210,57 @@ impl AlbumTally {
}
}
/// For each smart album, the most smart albums in a chain its rules lead through (itself included), or `None`
/// when a loop is reachable from it (its answer may then depend on which albums are being evaluated around it).
fn chain_heights(cat: &Catalog) -> HashMap<AlbumId, Option<usize>> {
struct Frame {
id: AlbumId,
tests: Vec<AlbumId>,
next: usize,
tallest: usize,
loops: bool,
}
let tests = |id: AlbumId| -> Vec<AlbumId> {
let tested = cat.album(id).and_then(|a| a.smart.as_deref()).map(Filter::albums_tested).unwrap_or_default();
tested.into_iter().filter(|t| cat.album(*t).is_some_and(Album::is_smart)).collect()
};
let frame = |id: AlbumId| Frame { id, tests: tests(id), next: 0, tallest: 0, loops: false };
let mut done: HashMap<AlbumId, Option<usize>> = HashMap::new();
let mut open: HashSet<AlbumId> = HashSet::new();
for root in cat.albums().filter(|a| a.is_smart()).map(|a| a.id) {
if done.contains_key(&root) {
continue;
}
open.insert(root);
let mut stack = vec![frame(root)];
while let Some(top) = stack.last_mut() {
if let Some(&kid) = top.tests.get(top.next) {
top.next += 1;
match done.get(&kid) {
Some(Some(h)) => top.tallest = top.tallest.max(*h),
Some(None) => top.loops = true,
None if open.contains(&kid) => top.loops = true,
None => {
open.insert(kid);
stack.push(frame(kid));
}
}
} else if let Some(finished) = stack.pop() {
open.remove(&finished.id);
let height = (!finished.loops).then_some(finished.tallest + 1);
done.insert(finished.id, height);
if let Some(parent) = stack.last_mut() {
match height {
Some(h) => parent.tallest = parent.tallest.max(h),
None => parent.loops = true,
}
}
}
}
}
done
}
#[cfg(test)]
mod tests {
use super::*;
+85 -28
View File
@@ -904,17 +904,9 @@ fn search_text_finds_people_and_quoted_values() {
/// What the catalog remembers of its latest ops: which photos each changed and what of them, as long as that can be
/// said photo by photo.
#[test]
fn the_catalog_remembers_which_photos_its_latest_ops_changed_and_what_of_them() {
fn photo_ops_record_touched_ids_and_changed_aspects() {
let mut c = Catalog::default();
let photo = |c: &mut Catalog, name: &str| {
let id = c.alloc_photo_id();
c.apply(Op::AddPhoto {
photo: Box::new(Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00")),
})
.unwrap();
id
};
let (a, b) = (photo(&mut c, "a.jpg"), photo(&mut c, "b.jpg"));
let (a, b) = (photo(&mut c, "a.jpg", "2026-01-01T10:00:00"), photo(&mut c, "b.jpg", "2026-01-01T10:00:00"));
let start = c.revision;
assert_eq!(c.touched_since(start), Some(vec![]));
assert_eq!(c.aspects_since(start), Some(Aspects::NONE));
@@ -940,33 +932,31 @@ fn the_catalog_remembers_which_photos_its_latest_ops_changed_and_what_of_them()
assert_eq!(c.touched_since(before), None);
assert_eq!(c.aspects_since(start), None);
assert_eq!(c.touched_since(c.revision), Some(vec![]), "from after it, it is known again");
// a revision that is not this catalog's past
assert_eq!(c.touched_since(c.revision + 5), None);
// a revision set from outside (a library just loaded): nothing is known of how the catalog got there, and after
// the next op nothing of before it
let old = c.revision;
}
#[test]
fn history_handles_loaded_revisions_failed_batches_and_retention() {
let mut c = Catalog::default();
let a = photo(&mut c, "a.jpg", "2026-01-01T10:00:00");
let album = c.alloc_album_id();
c.apply(Op::AddAlbum { album: Album::new(album, "Trip") }).unwrap();
// a batch that fails midway is undone as a whole; a batch in a batch is remembered photo by photo; a batch
// with an op that changes more than photos is not
let before = c.revision;
c.revision = 7 << 32;
assert_eq!(c.touched_since(old), None);
assert_eq!(c.touched_since(before), None);
assert_eq!(c.aspects_since(c.revision), None);
let loaded = c.revision;
c.apply(Op::SetRating { id: a, rating: 1 }).unwrap();
assert_eq!(c.touched_since(loaded), Some(vec![a]));
assert_eq!(c.touched_since(old), None);
// an op that fails changes nothing, and what is remembered never says less than what happened
let before = c.revision;
assert!(c.apply(Op::SetRating { id: PhotoId(9_999), rating: 1 }).is_err());
assert_eq!(c.revision, before);
c.apply(Op::SetFlag { id: a, flag: Flag::Pick }).unwrap();
assert!(c.touched_since(before).is_some_and(|ids| ids.contains(&a)));
assert!(c.aspects_since(before).is_some_and(|x| x.any_of(Aspects::FLAG)));
// a batch that fails midway is undone as a whole; a batch in a batch is remembered photo by photo; a batch
// with an op that changes more than photos is not
assert_eq!(c.touched_since(before), None);
let before = c.revision;
assert!(c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 5 }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] }).is_err());
assert_eq!((c.revision, c.photo(a).map(|p| p.rating)), (before, Some(1)));
c.apply(Op::Batch { ops: vec![Op::Batch { ops: vec![Op::SetRating { id: a, rating: 2 }] }] }).unwrap();
// (the photo the failed batch asked for and never found may be named too: more is said, never less)
assert!(c.touched_since(before).is_some_and(|ids| ids.contains(&a)));
// (the failed batch is not remembered: only the batch that worked)
assert_eq!(c.touched_since(before), Some(vec![a]));
let before = c.revision;
c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 3 }, Op::RenameAlbum { id: album, name: "Journey".into() }] }).unwrap();
assert_eq!(c.touched_since(before), None);
@@ -978,3 +968,70 @@ fn the_catalog_remembers_which_photos_its_latest_ops_changed_and_what_of_them()
assert_eq!(c.touched_since(long_ago), None);
assert_eq!(c.touched_since(c.revision - 10), Some(vec![a]));
}
/// An op that fails leaves nothing behind in what the catalog remembers of its ops: no photo it never changed (one
/// that does not even exist), and, for a batch rolled back, none of what its first ops had touched.
#[test]
fn an_op_that_fails_leaves_no_touched_photos_behind() {
let mut c = Catalog::default();
let add = |c: &mut Catalog, name: &str| {
let id = c.alloc_photo_id();
c.apply(Op::AddPhoto {
photo: Box::new(Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00")),
})
.unwrap();
id
};
let (a, b) = (add(&mut c, "a.jpg"), add(&mut c, "b.jpg"));
let missing = PhotoId(9_999);
let start = c.revision;
// every op that names a photo, on one that does not exist
for op in [Op::SetRating { id: missing, rating: 1 }, Op::SetFlag { id: missing, flag: Flag::Pick }, Op::RemovePhoto { id: missing }] {
assert!(c.apply(op).is_err());
assert_eq!(c.revision, start, "a failed op makes no revision");
assert_eq!(c.touched_since(start), Some(vec![]));
assert_eq!(c.aspects_since(start), Some(Aspects::NONE));
}
// an op that changes more than photos and fails does not make earlier revisions unknown
assert!(c.apply(Op::RenameAlbum { id: AlbumId(77), name: "x".into() }).is_err());
assert_eq!(c.touched_since(start), Some(vec![]));
// a batch that fails on its second op names nothing of its first, nor of the rollback
assert!(c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 5 }, Op::SetRating { id: missing, rating: 1 }] }).is_err());
assert_eq!(c.revision, start);
assert_eq!(c.touched_since(start), Some(vec![]));
assert_eq!(c.aspects_since(start), Some(Aspects::NONE));
assert_eq!(c.photo(a).map(|p| p.rating), Some(0));
// a batch that ends in a failed removal of a photo that exists
assert!(c.apply(Op::Batch { ops: vec![Op::RemovePhoto { id: b }, Op::RemovePhoto { id: b }] }).is_err());
assert!(c.photo(b).is_some());
assert_eq!(c.touched_since(start), Some(vec![]));
// what succeeded after the failures is remembered, and only that
c.apply(Op::SetRating { id: a, rating: 2 }).unwrap();
assert_eq!(c.touched_since(start), Some(vec![a]));
assert_eq!(c.aspects_since(start), Some(Aspects::RATING));
}
/// A batch the rollback of which fails halfway leaves the catalog changed (here a stack is lost), so what the
/// catalog remembers must not say that nothing changed: anything may have.
#[test]
fn a_batch_that_cannot_be_rolled_back_whole_makes_earlier_changes_unknown() {
let mut c = Catalog::default();
let mut ids = Vec::new();
for name in ["a.jpg", "b.jpg"] {
let id = c.alloc_photo_id();
let photo = Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00");
c.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap();
ids.push(id);
}
let stack = c.alloc_stack_id();
c.apply(Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap();
let start = c.revision;
// the photo goes, then its stack, then an op fails: putting the stack back needs the photo, which comes later
let failing =
Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] };
assert!(c.apply(failing).is_err());
assert_eq!(c.revision, start + 1, "the catalog changed, so what is kept for the revision before is out of date");
assert!(c.photo(ids[0]).is_some() && c.stack(stack).is_none(), "the rollback went only part of the way");
assert_eq!(c.touched_since(start), None, "so nothing is said of what changed");
assert_eq!(c.touched_since(c.revision), Some(vec![]), "from after it, it is known again");
}
@@ -161,6 +161,63 @@ fn an_unlabelled_folder_moved_onto_a_stale_label_does_not_inherit_it() {
assert_eq!(c.folder_color_label("/pics/holiday"), Some(ColorLabel::Purple));
}
#[test]
fn a_located_folder_keeps_what_the_library_knows_of_the_folders_already_at_the_destination() {
let mut c = library();
label(&mut c, "/pics/trip", Some(ColorLabel::Red));
label(&mut c, "/pics/trip/day1", Some(ColorLabel::Green));
// other folders of the library at the place it is said to be at: nothing arrived there
label(&mut c, "/pics/home", Some(ColorLabel::Blue));
label(&mut c, "/pics/home/old", Some(ColorLabel::Yellow));
let before = c.to_snapshot();
let ops = c.folder_records_located("/pics/trip", "/pics/home");
let undo = c.apply(Op::Batch { ops }).unwrap();
assert_eq!(c.folder_record("/pics/trip"), None, "what was known at the old place goes");
assert_eq!(c.folder_record("/pics/trip/day1"), None);
assert_eq!(c.folder_color_label("/pics/home"), Some(ColorLabel::Red), "a record carried over replaces the one at the same place");
assert_eq!(c.folder_color_label("/pics/home/old"), Some(ColorLabel::Yellow), "a folder of the library there keeps its own");
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
}
#[test]
fn a_located_folder_with_labels_inside_lands_them_at_the_same_places_below() {
let mut c = library();
label(&mut c, "/pics/trip", Some(ColorLabel::Red));
label(&mut c, "/pics/trip/day1", Some(ColorLabel::Green));
let ops = c.folder_records_located("/pics/trip", "/mnt/nas/trip");
c.apply(Op::Batch { ops }).unwrap();
assert_eq!(c.folder_color_label("/mnt/nas/trip"), Some(ColorLabel::Red));
assert_eq!(c.folder_color_label("/mnt/nas/trip/day1"), Some(ColorLabel::Green));
}
#[test]
fn a_folder_located_below_itself_leaves_the_records_of_the_folders_already_there_in_place() {
let mut c = library();
label(&mut c, "/pics/trip", Some(ColorLabel::Red));
label(&mut c, "/pics/trip/day1", Some(ColorLabel::Green));
// another folder of the library already sits at the place the folder is said to be at
label(&mut c, "/pics/trip/day1/raw", Some(ColorLabel::Blue));
let before = c.to_snapshot();
let ops = c.folder_records_located("/pics/trip", "/pics/trip/day1");
let undo = c.apply(Op::Batch { ops }).unwrap();
assert_eq!(c.folder_record("/pics/trip"), None, "what was known at the old place goes");
assert_eq!(c.folder_color_label("/pics/trip/day1"), Some(ColorLabel::Red), "a record carried over replaces the one at the same place");
assert_eq!(c.folder_color_label("/pics/trip/day1/raw"), Some(ColorLabel::Blue), "a folder below the destination keeps its own");
assert_eq!(c.folder_record("/pics/trip/day1/day1"), None, "the record at the destination is not carried below itself");
assert_eq!(c.folder_record("/pics/trip/day1/day1/raw"), None);
c.apply(undo).unwrap();
assert_eq!(c.to_snapshot(), before);
}
#[test]
fn a_folder_located_where_it_is_or_without_labels_gives_no_ops() {
let mut c = library();
assert!(c.folder_records_located("/pics/trip", "/elsewhere/trip").is_empty());
label(&mut c, "/pics/trip", Some(ColorLabel::Red));
assert!(c.folder_records_located("/pics/trip", "/pics/trip").is_empty());
}
#[test]
fn labels_survive_the_journal_without_a_snapshot() {
let m = MemStore::new();
+49
View File
@@ -1,5 +1,6 @@
//! Forgetting untouched Local browse records (see [`crate::local`]).
use std::collections::HashSet;
use std::sync::Arc;
use lightcraft_develop::DevelopSettings;
@@ -265,3 +266,51 @@ fn op_photo_ids_cover_nested_ops() {
op.photo_ids(&mut |id| ids.push(id.0));
assert_eq!(ids, vec![1, 2, 3, 4]);
}
#[test]
fn drive_and_share_root_records_are_forgotten() {
for (path, folder) in [("C:\\IMG_1.JPG", "C:\\"), ("//srv/share/x.jpg", "//srv/share/")] {
let mut c = Catalog::new();
let id = c.alloc_photo_id();
let mut p = Photo::new(id, Source::File { path: path.into() }, "x.jpg", "JPEG", 60, 40, OLD);
p.local = true;
p.set_local_baseline();
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
c.apply(Op::SetBrowsed { folder: folder.into(), at: Some(OLD.into()) }).unwrap();
assert_eq!(plan(&c, 30).evict, vec![id], "{path}");
}
}
fn paths(folder: &str, ns: &[u32]) -> HashSet<String> {
ns.iter().map(|i| format!("/pics/{folder}/IMG_{i}.JPG")).collect()
}
#[test]
fn local_records_of_files_tell_what_can_give_way_from_what_holds_something() {
let mut c = Catalog::new();
let untouched = local(&mut c, "trip", 1);
let rated = local(&mut c, "trip", 2);
let in_album = local(&mut c, "trip", 3);
let _elsewhere = local(&mut c, "trip", 4);
c.apply(Op::SetRating { id: rated, rating: 3 }).unwrap();
let a = c.alloc_album_id();
let mut album = Album::new(a, "A");
album.photos.push(in_album);
c.apply(Op::AddAlbum { album }).unwrap();
let found = c.local_records_of(&paths("trip", &[1, 2, 3]));
assert_eq!(found.untouched, vec![untouched]);
assert_eq!(found.kept, vec![(rated, "/pics/trip/IMG_2.JPG".to_string()), (in_album, "/pics/trip/IMG_3.JPG".to_string())]);
}
#[test]
fn local_records_of_files_leave_out_library_photos_and_recently_deleted_ones() {
let mut c = Catalog::new();
let gone = local(&mut c, "trip", 1);
c.apply(Op::SetDeleted { id: gone, deleted: true }).unwrap();
let id = c.alloc_photo_id();
let p = Photo::new(id, Source::File { path: "/pics/trip/IMG_2.JPG".into() }, "IMG_2.JPG", "JPEG", 60, 40, OLD);
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
assert_eq!(c.local_records_of(&paths("trip", &[1, 2])), LocalRecords::default());
assert_eq!(c.local_records_of(&HashSet::new()), LocalRecords::default());
}
+68
View File
@@ -108,6 +108,74 @@ fn folder_loops_and_missing_parents_move_to_the_top() {
let _ = c.apply(Op::MoveAlbum { id: AlbumId(11), parent: Some(AlbumId(10)) });
}
/// Check the postcondition needed by every consumer that follows parent folders. This inspects
/// the repaired catalog, not its cache or a second implementation of the repair algorithm.
fn assert_all_album_chains_reach_roots(c: &Catalog) {
for album in c.albums.values() {
let mut seen = std::collections::HashSet::new();
let mut current = album;
while let Some(parent) = current.parent {
assert!(seen.insert(current.id), "album {} still reaches a cycle", album.id.0);
current = c.albums.get(&parent).expect("every retained parent exists");
assert!(current.folder, "every retained parent is a folder");
}
}
}
#[test]
fn a_child_visited_before_a_folder_cycle_keeps_its_content_and_gets_a_rooted_chain() {
let (c, ids) = sound();
let (mut c, report) = load_edited(&c, |v| {
// BTreeMap order visits10 first: cached Bad11/12 used to be skipped without repair.
v["albums"]["10"] = serde_json::to_value(album(10, Some(11), false, vec![ids[2]])).unwrap();
v["albums"]["11"] = serde_json::to_value(album(11, Some(12), true, vec![])).unwrap();
v["albums"]["12"] = serde_json::to_value(album(12, Some(11), true, vec![])).unwrap();
});
assert_all_album_chains_reach_roots(&c);
assert_eq!(c.album(AlbumId(10)).unwrap().parent, Some(AlbumId(11)), "the child remains in its actual folder");
assert_eq!(c.album(AlbumId(10)).unwrap().photos, vec![ids[2]], "repair preserves the child's photos");
assert_eq!(c.album(AlbumId(11)).unwrap().parent, None, "one cycle edge is repaired");
assert_eq!(c.album(AlbumId(12)).unwrap().parent, Some(AlbumId(11)), "the other folder edge is retained");
assert!(report.repaired.iter().any(|message| message.starts_with("album 11:")), "{:?}", report.repaired);
assert!(c.repair().is_empty(), "a second repair is idempotent");
}
#[test]
fn a_child_visited_before_a_folder_with_a_missing_parent_does_not_hide_the_bad_ancestor() {
let (c, ids) = sound();
let (mut c, report) = load_edited(&c, |v| {
v["albums"]["10"] = serde_json::to_value(album(10, Some(11), false, vec![ids[2]])).unwrap();
v["albums"]["11"] = serde_json::to_value(album(11, Some(999), true, vec![])).unwrap();
});
assert_all_album_chains_reach_roots(&c);
assert_eq!(c.album(AlbumId(10)).unwrap().parent, Some(AlbumId(11)));
assert_eq!(c.album(AlbumId(10)).unwrap().photos, vec![ids[2]]);
assert_eq!(c.album(AlbumId(11)).unwrap().parent, None, "repair the missing-parent edge itself");
assert!(report.repaired.iter().any(|message| message.starts_with("album 11:")), "{:?}", report.repaired);
assert!(c.repair().is_empty());
}
#[test]
fn a_long_valid_folder_chain_is_retained_when_its_child_is_visited_first() {
let (c, ids) = sound();
let (mut c, report) = load_edited(&c, |v| {
v["albums"]["10"] = serde_json::to_value(album(10, Some(100), false, vec![ids[2]])).unwrap();
for id in 100..612 {
v["albums"][id.to_string()] = serde_json::to_value(album(id, Some(id + 1), true, vec![])).unwrap();
}
v["albums"]["612"] = serde_json::to_value(album(612, None, true, vec![])).unwrap();
});
assert_all_album_chains_reach_roots(&c);
assert_eq!(c.album(AlbumId(10)).unwrap().parent, Some(AlbumId(100)));
assert_eq!(c.album(AlbumId(10)).unwrap().photos, vec![ids[2]]);
for id in 100..612 {
assert_eq!(c.album(AlbumId(id)).unwrap().parent, Some(AlbumId(id + 1)), "valid edge{id} remains");
}
assert_eq!(c.album(AlbumId(612)).unwrap().parent, None);
assert!(!report.repaired.iter().any(|message| message.starts_with("album ")), "valid parents must not be repaired: {:?}", report.repaired);
assert!(c.repair().is_empty());
}
/// Id counters left at the top (or behind the ids in use) by a damaged file: allocating no longer
/// overflows (a panic in debug builds) and never hands out an id already in use.
#[test]
+172
View File
@@ -0,0 +1,172 @@
//! A whole count of every album (`AlbumTally::of`) keeps each smart album's photos for the pass, so an album testing
//! another doesn't work its rules out again. The counts must be the ones each album gets counted alone.
use serde_json::json;
use super::*;
use crate::tally::AlbumTally;
fn smart(id: u64, rules: serde_json::Value) -> Album {
let rule_set = Some(serde_json::from_value(rules).unwrap());
Album { smart: Some(Box::new(Filter { rule_set, ..Default::default() })), ..Album::new(AlbumId(id), format!("Smart {id}")) }
}
fn photos(n: u64) -> Vec<Op> {
(0..n)
.map(|i| {
// folders with capitals, accents and a Windows path, so the text rules see every spelling
let dir = ["Asian/Japanese", "Été/Ünï", "C:\\Users\\Me\\Pictures", "plain", "[SITES]/x"][(i % 5) as usize];
let mut p = Photo::new(
PhotoId(i + 1),
Source::File { path: format!("/Volumes/share/photos/{dir}/name{}/IMG_{i:04}.jpg", i % 9) },
&format!("IMG_{i:04}.jpg"),
"JPEG",
6000,
4000,
"2026-01-01T00:00:00",
);
p.rating = (i % 6) as u8;
p.flag = [Flag::None, Flag::Pick, Flag::Reject][(i % 3) as usize];
p.label = (i % 4 == 0).then_some(ColorLabel::Red);
p.meta.keywords = (0..i % 4).map(|k| format!("kw{k}")).collect();
p.deleted = i % 37 == 0;
Op::AddPhoto { photo: Box::new(p) }
})
.collect()
}
fn is(album: u64) -> serde_json::Value {
json!({"field": "album", "op": "is", "value": album})
}
fn is_not(album: u64) -> serde_json::Value {
json!({"field": "album", "op": "isNot", "value": album})
}
fn path(op: &str, value: &str) -> serde_json::Value {
json!({"field": "filePath", "op": op, "value": value})
}
/// Every album's count in `c`, each album counted alone (no pass, rules worked out per photo).
fn counted_alone(c: &Catalog) -> Vec<(AlbumId, usize)> {
let mut v: Vec<_> = c.albums().map(|a| (a.id, c.album_count(a.id))).collect();
v.sort_unstable();
v
}
fn counted_together(c: &Catalog) -> Vec<(AlbumId, usize)> {
let tally = AlbumTally::of(c);
let mut v: Vec<_> = tally.counts().iter().map(|(id, n)| (*id, *n)).collect();
v.sort_unstable();
v
}
#[test]
fn a_whole_count_equals_each_album_counted_alone() {
let mut c = Catalog::new();
let mut ops = photos(240);
let mut plain = Album::new(AlbumId(1), "Picks");
plain.photos = (0..240).step_by(4).map(|i| PhotoId(i + 1)).collect();
let folder = Album { folder: true, ..Album::new(AlbumId(2), "Trips") };
let inside = Album { parent: Some(AlbumId(2)), photos: (0..240).step_by(3).map(|i| PhotoId(i + 1)).collect(), ..Album::new(AlbumId(3), "In") };
ops.extend([plain, folder, inside].map(|album| Op::AddAlbum { album }));
// the inner albums: #2-like, #14-like, then albums chained on it, the other way round, in groups and in different orders
ops.push(Op::AddAlbum {
album: smart(
10,
json!({"match": "any", "rules": [{"field": "flag", "op": "is", "value": "reject"}, {"field": "label", "op": "is", "value": "red"}]}),
),
});
ops.push(Op::AddAlbum {
album: smart(11, json!({"match": "all", "rules": [is_not(10), path("notContains", "Été"), path("notContains", "plain")]})),
});
for k in 0..9u64 {
let tail = path("contains", &format!("NAME{k}"));
let rules = match k % 3 {
0 => json!({"match": "all", "rules": [is(11), tail]}),
1 => json!({"match": "all", "rules": [json!({"field": "keywordCount", "op": "lte", "value": 2}), is(11), tail]}),
_ => json!({"match": "all", "rules": [tail, is(11)]}),
};
ops.push(Op::AddAlbum { album: smart(12 + k, rules) });
}
ops.push(Op::AddAlbum {
album: smart(
21,
json!({"match": "all", "rules": [{"group": {"match": "any", "rules": [is(11), is(1)]}}, {"field": "rating", "op": "gte", "value": 2}]}),
),
});
ops.push(Op::AddAlbum { album: smart(22, json!({"match": "all", "rules": [is_not(21), is(3)]})) });
ops.push(Op::AddAlbum { album: smart(23, json!({"match": "any", "rules": [is(2), is(999), is(1)]})) });
// a loop saved anyway (30 ↔ 31), albums that test it from outside (32, 33), and one that tests both worlds
ops.push(Op::AddAlbum { album: smart(30, json!({"rules": []})) });
ops.push(Op::AddAlbum { album: smart(31, json!({"rules": [is_not(30)]})) });
ops.push(Op::AddAlbum { album: smart(32, json!({"rules": [is(31), {"field": "rating", "op": "gte", "value": 1}]})) });
ops.push(Op::AddAlbum { album: smart(33, json!({"rules": [is_not(32), is(11)]})) });
ops.push(Op::AddAlbum { album: smart(34, json!({"rules": [is(34)]})) });
// a chain deeper than the limit on how deep albums may test albums
ops.push(Op::AddAlbum { album: smart(100, json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})) });
for k in 101..=140u64 {
ops.push(Op::AddAlbum { album: smart(k, json!({"rules": [is(k - 1)]})) });
}
ops.push(Op::AddAlbum { album: smart(141, json!({"rules": [is(140), is_not(11)]})) });
// an album past the depth limit that also tests a memoized album directly: where the shared album is read from the
// pass near the top, the chain below must still find it answered as it always did (200 ← 231 … 201, height 32)
ops.push(Op::AddAlbum { album: smart(200, json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})) });
for k in 201..=230u64 {
ops.push(Op::AddAlbum { album: smart(k, json!({"rules": [is(k + 1)]})) });
}
ops.push(Op::AddAlbum { album: smart(231, json!({"rules": [is(200)]})) });
ops.push(Op::AddAlbum { album: smart(250, json!({"match": "all", "rules": [is(200), is(201)]})) });
c.apply(Op::Batch { ops }).unwrap();
c.apply(Op::SetAlbumRules {
id: AlbumId(30),
rules: Box::new(Filter { rule_set: Some(serde_json::from_value(json!({"rules": [is_not(31)]})).unwrap()), ..Default::default() }),
})
.unwrap();
let alone = counted_alone(&c);
let count = |id: u64| alone.iter().find(|(a, _)| a.0 == id).map(|(_, n)| *n);
assert!(count(11) > Some(0) && count(131) > Some(0), "{alone:?}");
assert_eq!(count(132), Some(0), "the chain is too deep from here: holds nothing, as it did");
assert!(count(250) > Some(0), "200 is answered near the top, so the chain finds it answered");
assert_eq!(counted_together(&c), alone);
// the pass leaves nothing behind: the same answers whichever album asks first, and again after an edit
c.apply(Op::SetAlbumRules {
id: AlbumId(10),
rules: Box::new(Filter {
rule_set: Some(serde_json::from_value(json!({"rules": [{"field": "rating", "op": "is", "value": 5}]})).unwrap()),
..Default::default()
}),
})
.unwrap();
let after = counted_alone(&c);
assert_ne!(after, alone);
assert_eq!(counted_together(&c), after);
}
/// The reason for the pass: with an album tested by many, its rules are worked out once per photo, not once per
/// photo for each album that tests it.
#[test]
fn an_album_tested_by_many_is_worked_out_once_a_photo() {
let mut c = Catalog::new();
let mut ops: Vec<Op> = (0..60u64)
.map(|i| {
let mut p = Photo::new(PhotoId(i + 1), Source::Demo { scene: 0 }, "a.jpg", "JPEG", 10, 10, "2026-01-01T00:00:00");
p.rating = (i % 6) as u8;
Op::AddPhoto { photo: Box::new(p) }
})
.collect();
ops.push(Op::AddAlbum { album: smart(1, json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})) });
for k in 0..10u64 {
ops.push(Op::AddAlbum { album: smart(2 + k, json!({"rules": [is(1), {"field": "rating", "op": "lte", "value": k % 6}]})) });
}
c.apply(Op::Batch { ops }).unwrap();
let alone = counted_alone(&c);
crate::rules::EVALUATED.with(|n| n.set(0));
let tally = AlbumTally::of(&c);
let worked = crate::rules::EVALUATED.with(std::cell::Cell::get);
assert_eq!(worked, 11 * 60, "each of the 11 smart albums asks each of the 60 photos once");
let mut together: Vec<_> = tally.counts().iter().map(|(id, n)| (*id, *n)).collect();
together.sort_unstable();
assert_eq!(together, alone);
}
+82 -44
View File
@@ -227,7 +227,7 @@ pub enum TiffCompression {
/// Encode TIFF: 8/16-bit integer or 32-bit float, gray/RGB with optional (unassociated) alpha.
/// ICC and XMP are embedded; EXIF is not (write it through the TIFF writer in `lightcraft-tiff`).
pub fn encode_tiff(img: &EncodeImage, compression: TiffCompression, meta: &EncodeMeta) -> Result<Vec<u8>> {
use tiff::encoder::{Compression, DeflateLevel, TiffEncoder, colortype};
use tiff::encoder::{Compression, DeflateLevel, TiffEncoder};
use tiff::tags::Predictor;
img.validate()?;
let e = |e: tiff::TiffError| Error::Encode(e.to_string());
@@ -243,54 +243,92 @@ pub fn encode_tiff(img: &EncodeImage, compression: TiffCompression, meta: &Encod
if !float && matches!(compression, TiffCompression::Lzw | TiffCompression::Deflate) { Predictor::Horizontal } else { Predictor::None };
let mut enc = TiffEncoder::new(&mut cur).map_err(e)?.with_compression(comp).with_predictor(predictor);
let (w, h) = (img.width, img.height);
let n = w as usize * h as usize;
// Gray + alpha is stored as RGBA (the encoder has no GrayA colour type).
let ch = img.channels as usize;
macro_rules! write {
($ct:ty, $data:expr, $alpha:expr) => {{
let mut im = enc.new_image::<$ct>(w, h).map_err(e)?;
if let Some(ppi) = meta.ppi.filter(|p| *p > 0) {
im.resolution(tiff::tags::ResolutionUnit::Inch, tiff::encoder::Rational { n: ppi as u32, d: 1 });
}
if let Some(icc) = meta.icc {
im.encoder().write_tag(tiff::tags::Tag::IccProfile, icc).map_err(e)?;
}
if let Some(xmp) = meta.xmp {
im.encoder().write_tag(tiff::tags::Tag::from_u16_exhaustive(700), xmp.as_bytes()).map_err(e)?;
}
if $alpha {
im.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[2u16][..]).map_err(e)?;
}
im.write_data($data).map_err(e)?;
}};
}
fn expand_ga<T: Copy>(s: &[T], n: usize) -> Vec<T> {
s.as_chunks::<2>().0.iter().take(n).flat_map(|c| [c[0], c[0], c[0], c[1]]).collect()
}
let pixels = w as usize * h as usize;
match img.samples {
Samples::U8(s) => match ch {
1 => write!(colortype::Gray8, &s[..n], false),
2 => write!(colortype::RGBA8, &expand_ga(s, n), true),
3 => write!(colortype::RGB8, &s[..n * 3], false),
_ => write!(colortype::RGBA8, &s[..n * 4], true),
},
Samples::U16(s) => match ch {
1 => write!(colortype::Gray16, &s[..n], false),
2 => write!(colortype::RGBA16, &expand_ga(s, n), true),
3 => write!(colortype::RGB16, &s[..n * 3], false),
_ => write!(colortype::RGBA16, &s[..n * 4], true),
},
Samples::F32(s) => match ch {
1 => write!(colortype::Gray32Float, &s[..n], false),
2 => write!(colortype::RGBA32Float, &expand_ga(s, n), true),
3 => write!(colortype::RGB32Float, &s[..n * 3], false),
_ => write!(colortype::RGBA32Float, &s[..n * 4], true),
},
Samples::U8(samples) => write_tiff_u8(&mut enc, samples, pixels, img.channels as usize, img, meta)?,
Samples::U16(samples) => write_tiff_u16(&mut enc, samples, pixels, img.channels as usize, img, meta)?,
Samples::F32(samples) => write_tiff_f32(&mut enc, samples, pixels, img.channels as usize, img, meta)?,
}
Ok(cur.into_inner())
}
macro_rules! write_tiff_image {
($encoder:expr, $image:expr, $meta:expr, $color:ty, $data:expr, $alpha:expr) => {{
let mut image = $encoder.new_image::<$color>($image.width, $image.height).map_err(|e| Error::Encode(e.to_string()))?;
if let Some(ppi) = $meta.ppi.filter(|ppi| *ppi > 0) {
image.resolution(tiff::tags::ResolutionUnit::Inch, tiff::encoder::Rational { n: ppi as u32, d: 1 });
}
if let Some(icc) = $meta.icc {
image.encoder().write_tag(tiff::tags::Tag::IccProfile, icc).map_err(|e| Error::Encode(e.to_string()))?;
}
if let Some(xmp) = $meta.xmp {
image.encoder().write_tag(tiff::tags::Tag::from_u16_exhaustive(700), xmp.as_bytes()).map_err(|e| Error::Encode(e.to_string()))?;
}
if $alpha {
image.encoder().write_tag(tiff::tags::Tag::ExtraSamples, &[2u16][..]).map_err(|e| Error::Encode(e.to_string()))?;
}
image.write_data($data).map_err(|e| Error::Encode(e.to_string()))?;
}};
}
fn expanded_gray_alpha<T: Copy>(samples: &[T], pixels: usize) -> Vec<T> {
samples.as_chunks::<2>().0.iter().take(pixels).flat_map(|channel| [channel[0], channel[0], channel[0], channel[1]]).collect()
}
fn write_tiff_u8<W: std::io::Write + std::io::Seek>(
encoder: &mut tiff::encoder::TiffEncoder<W>,
samples: &[u8],
pixels: usize,
channels: usize,
image: &EncodeImage,
meta: &EncodeMeta,
) -> Result<()> {
use tiff::encoder::colortype;
match channels {
1 => write_tiff_image!(encoder, image, meta, colortype::Gray8, &samples[..pixels], false),
2 => write_tiff_image!(encoder, image, meta, colortype::RGBA8, &expanded_gray_alpha(samples, pixels), true),
3 => write_tiff_image!(encoder, image, meta, colortype::RGB8, &samples[..pixels * 3], false),
_ => write_tiff_image!(encoder, image, meta, colortype::RGBA8, &samples[..pixels * 4], true),
}
Ok(())
}
fn write_tiff_u16<W: std::io::Write + std::io::Seek>(
encoder: &mut tiff::encoder::TiffEncoder<W>,
samples: &[u16],
pixels: usize,
channels: usize,
image: &EncodeImage,
meta: &EncodeMeta,
) -> Result<()> {
use tiff::encoder::colortype;
match channels {
1 => write_tiff_image!(encoder, image, meta, colortype::Gray16, &samples[..pixels], false),
2 => write_tiff_image!(encoder, image, meta, colortype::RGBA16, &expanded_gray_alpha(samples, pixels), true),
3 => write_tiff_image!(encoder, image, meta, colortype::RGB16, &samples[..pixels * 3], false),
_ => write_tiff_image!(encoder, image, meta, colortype::RGBA16, &samples[..pixels * 4], true),
}
Ok(())
}
fn write_tiff_f32<W: std::io::Write + std::io::Seek>(
encoder: &mut tiff::encoder::TiffEncoder<W>,
samples: &[f32],
pixels: usize,
channels: usize,
image: &EncodeImage,
meta: &EncodeMeta,
) -> Result<()> {
use tiff::encoder::colortype;
match channels {
1 => write_tiff_image!(encoder, image, meta, colortype::Gray32Float, &samples[..pixels], false),
2 => write_tiff_image!(encoder, image, meta, colortype::RGBA32Float, &expanded_gray_alpha(samples, pixels), true),
3 => write_tiff_image!(encoder, image, meta, colortype::RGB32Float, &samples[..pixels * 3], false),
_ => write_tiff_image!(encoder, image, meta, colortype::RGBA32Float, &samples[..pixels * 4], true),
}
Ok(())
}
/// Encode a flat PSD (8/16-bit gray or RGB, no layers; alpha dropped): the hand-off an image
/// editor such as PhotoCraft saves back to in place. ICC, EXIF, XMP and resolution are embedded.
pub fn encode_psd(img: &EncodeImage, meta: &EncodeMeta) -> Result<Vec<u8>> {
+108 -8
View File
@@ -17,6 +17,8 @@ pub(crate) struct Markers {
pub sof: u8,
/// Number of components in the first scan (< `components` for non-interleaved sequential files).
pub first_scan_components: u8,
/// Number of APP1 segments: capped before the allocating decoders walk them again.
pub app1: u32,
pub exif: Option<Vec<u8>>,
/// Offset of the EXIF TIFF header within the file.
pub exif_offset: usize,
@@ -83,6 +85,7 @@ pub(crate) fn parse_markers(b: &[u8]) -> Option<Markers> {
m.components = seg[5];
}
0xE1 => {
m.app1 = m.app1.saturating_add(1);
if seg.starts_with(b"Exif\0\0") && m.exif.is_none() {
m.exif = Some(seg[6..].to_vec());
m.exif_offset = start + 6;
@@ -121,6 +124,8 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
decode_with_fallback(bytes, opts, None)
}
const MAX_APP1: u32 = 128;
/// Stored dimensions and EXIF orientation from the markers, without decoding the scan data. The
/// file is refused, as a decode would refuse it, when it has no frame header, an unsupported frame
/// type or component count, or when its markers don't run to an end-of-image marker after the
@@ -178,6 +183,11 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback:
return Err(Error::Malformed(F, "no frame header".into()));
}
check_size(F, m.width as u64, m.height as u64, opts)?;
// The allocating decoders below parse the markers again, all of them: the count is capped so
// their quadratic/unbounded handling of APP1 metadata stays linear in file size.
if m.app1 > MAX_APP1 {
return Err(Error::Malformed(F, "too many APP1 markers".into()));
}
let scale_to = opts.max_size.filter(|&(mw, mh)| mw > 0 && mh > 0 && (m.width >= mw.saturating_mul(2) || m.height >= mh.saturating_mul(2)));
// zune-jpeg handles the common cases fastest; jpeg-decoder covers DCT scaling, CMYK/YCCK,
// 12-bit, non-interleaved sequential scans (which zune-jpeg 0.5 mis-decodes with subsampling)
@@ -185,9 +195,9 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback:
let lossless = m.sof == 0xC3;
let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components;
let raw = if m.components == 4 || scale_to.is_some() || m.precision > 8 || non_interleaved || lossless {
decode_jpeg_decoder(bytes, &m, scale_to)?
decode_jpeg_decoder(bytes, &m, scale_to, opts)?
} else {
decode_zune(bytes, &m)?
decode_zune(bytes, &m, opts)?
};
// A raw container may carry the colour declaration of an otherwise untagged preview.
// Apply it before linearization/resizing; existing JPEG metadata always wins.
@@ -196,7 +206,7 @@ pub(crate) fn decode_with_fallback(bytes: &[u8], opts: &DecodeOptions, fallback:
finish(F, raw, meta, (m.width, m.height), opts)
}
fn decode_zune(bytes: &[u8], m: &Markers) -> Result<Raw> {
fn decode_zune(bytes: &[u8], m: &Markers, budget: &DecodeOptions) -> Result<Raw> {
use zune_core::bytestream::ZCursor;
use zune_core::colorspace::ColorSpace;
use zune_core::options::DecoderOptions;
@@ -207,6 +217,11 @@ fn decode_zune(bytes: &[u8], m: &Markers) -> Result<Raw> {
ColorSpace::RGB
});
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), opts);
// zune's `decode` allocates straight from the frame header it parses, with its own caps
// set in us: check that header against the same limits the other decoders honour first.
d.decode_headers().map_err(|e| Error::Malformed(F, e.to_string()))?;
let (zw, zh) = d.info().map(|i| (i.width as u64, i.height as u64)).ok_or_else(|| Error::Malformed(F, "no info".into()))?;
check_size(F, zw, zh, budget)?;
let px = d.decode().map_err(|e| Error::Malformed(F, e.to_string()))?;
let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?;
let (w, h) = (info.width as usize, info.height as usize);
@@ -217,10 +232,15 @@ fn decode_zune(bytes: &[u8], m: &Markers) -> Result<Raw> {
Ok(Raw { width: w, height: h, model, alpha: false, premultiplied: false, buf: Buf::U8(px), bit_depth: 8 })
}
fn decode_jpeg_decoder(bytes: &[u8], m: &Markers, scale_to: Option<(u32, u32)>) -> Result<Raw> {
fn decode_jpeg_decoder(bytes: &[u8], m: &Markers, scale_to: Option<(u32, u32)>, budget: &DecodeOptions) -> Result<Raw> {
use jpeg_decoder::PixelFormat;
let mut d = jpeg_decoder::Decoder::new(bytes);
d.read_info().map_err(|e| Error::Malformed(F, e.to_string()))?;
// Its frame header is what a decode allocates from (progressive coefficient buffers follow the
// unscaled MCU grid): check it against the same limits the other decoders honour, before any
// DCT scale is requested.
let info = d.info().ok_or_else(|| Error::Malformed(F, "no info".into()))?;
check_size(F, info.width as u64, info.height as u64, budget)?;
// `scale` is the DCT size, not a lossless resample: on a lossless frame it would cut the
// output to the top-left of each plane. Those decode at full size; `finish` scales after.
if let Some((mw, mh)) = scale_to.filter(|_| m.sof != 0xC3) {
@@ -369,11 +389,18 @@ pub(crate) fn decode_codes8(bytes: &[u8]) -> Result<(usize, usize, usize, Vec<u8
return Err(Error::Malformed(F, "no frame header".into()));
}
check_size(F, m.width as u64, m.height as u64, &DecodeOptions::default())?;
if m.app1 > MAX_APP1 {
return Err(Error::Malformed(F, "too many APP1 markers".into()));
}
if !matches!(m.components, 1 | 3) || m.precision != 8 {
return Err(Error::Malformed(F, "expected an 8-bit greyscale or RGB image".into()));
}
let non_interleaved = matches!(m.sof, 0xC0 | 0xC1) && m.first_scan_components < m.components;
let raw = if non_interleaved { decode_jpeg_decoder(bytes, &m, None)? } else { decode_zune(bytes, &m)? };
let raw = if non_interleaved {
decode_jpeg_decoder(bytes, &m, None, &DecodeOptions::default())?
} else {
decode_zune(bytes, &m, &DecodeOptions::default())?
};
let ch = raw.model.channels();
match raw.buf {
Buf::U8(v) if v.len() >= raw.width * raw.height * ch => Ok((raw.width, raw.height, ch, v)),
@@ -513,7 +540,7 @@ mod tests {
fn lossless_grayscale_samples_are_native_endian_and_left_justified() {
let bytes = lossless_jpeg(1, 8, 12);
let m = parse_markers(&bytes).unwrap();
let raw = decode_jpeg_decoder(&bytes, &m, None).unwrap();
let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap();
let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") };
assert_eq!(v, &vec![2048u16 << 4; 8], "0x0800 native-endian, left-justified");
assert_eq!((raw.model, raw.bit_depth), (Model::Gray, 16));
@@ -525,7 +552,7 @@ mod tests {
fn lossless_high_precision_rgb_is_16_bit() {
let bytes = lossless_jpeg(3, 2, 12);
let m = parse_markers(&bytes).unwrap();
let raw = decode_jpeg_decoder(&bytes, &m, None).unwrap();
let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap();
let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") };
assert_eq!(v, &vec![2048u16 << 4; 6]);
assert_eq!(raw.model, Model::Rgb);
@@ -536,7 +563,7 @@ mod tests {
fn lossless_high_precision_cmyk_is_16_bit() {
let bytes = lossless_jpeg(4, 2, 12);
let m = parse_markers(&bytes).unwrap();
let raw = decode_jpeg_decoder(&bytes, &m, None).unwrap();
let raw = decode_jpeg_decoder(&bytes, &m, None, &DecodeOptions::default()).unwrap();
let Buf::U16(v) = &raw.buf else { panic!("expected 16-bit samples") };
assert_eq!(v, &vec![2048u16 << 4; 8]);
assert_eq!((raw.model, raw.bit_depth), (Model::Cmyk, 16));
@@ -551,4 +578,77 @@ mod tests {
assert_eq!((d.width, d.height), (8, 1));
assert_eq!(d.bit_depth, 8);
}
/// Rewrites an encoded file's frame-header dimensions: same tables and scan, a hostile
/// annotated size.
fn with_dims(bytes: &[u8], w: u16, h: u16) -> Vec<u8> {
let mut out = bytes.to_vec();
let mut p = 2usize;
while p + 1 < out.len() {
if out[p] != 0xFF {
p += 1;
continue;
}
match out[p + 1] {
0xC0..=0xCF if out[p + 1] != 0xC4 && out[p + 1] != 0xC8 && out[p + 1] != 0xCC => {
out[p + 5..p + 7].copy_from_slice(&h.to_be_bytes());
out[p + 7..p + 9].copy_from_slice(&w.to_be_bytes());
return out;
}
0x01 | 0xD0..=0xD9 => p += 2,
0xFF => p += 1,
_ => {
let Some(l) = out.get(p + 2..p + 4) else { return out };
p += 2 + usize::from(u16::from_be_bytes([l[0], l[1]]));
}
}
}
out
}
/// A file claiming 65535×65535 must be refused for size before zune-jpeg allocates from
/// its frame header (4 GB+ of samples from roughly five hundred bytes of tables).
#[test]
fn zune_refuses_its_own_frame_header_over_the_budget() {
use crate::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let pixels = vec![128u8; 32 * 24];
let jpeg = encode_jpeg(&EncodeImage::new(32, 24, 1, Samples::U8(&pixels)), 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap();
let hostile = with_dims(&jpeg, 65535, 65535);
assert_ne!(hostile, jpeg);
match crate::decode(&hostile, DecodeOptions::default()) {
Err(Error::TooLarge(w, h)) => assert_eq!((w, h), (65535, 65535)),
other => panic!("unexpected: {other:?}"),
}
}
/// The jpeg-decoder branch (a 4-component file) is checked the same way: its own
/// `read_info` result is what a full-size decode allocates from.
#[test]
fn jpeg_decoder_refuses_its_own_frame_header_over_the_budget() {
use crate::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg};
let pixels = vec![128u8; 32 * 24 * 4];
let jpeg = encode_jpeg(&EncodeImage::new(32, 24, 4, Samples::U8(&pixels)), 90, ChromaSubsampling::S444, &EncodeMeta::default()).unwrap();
let hostile = with_dims(&jpeg, 65535, 65535);
match crate::decode(&hostile, DecodeOptions::default()) {
Err(Error::TooLarge(w, h)) => assert_eq!((w, h), (65535, 65535)),
other => panic!("unexpected: {other:?}"),
}
}
/// Extended XMP is reassembled from every APP1 fragment: an unbounded count is quadratic
/// memory in a marker walk, so the count is capped.
#[test]
fn an_app1_flood_is_refused_before_the_decoders_rewalk_it() {
let mut b = vec![0xFF, 0xD8];
// a 1-component SOF0: 8-bit, 2×2, component (1, 0x11, Q0)
b.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x0B, 8, 0, 2, 0, 2, 1, 0x01, 0x11, 0x00]);
for _ in 0..200 {
b.extend_from_slice(&[0xFF, 0xE1, 0x00, 0x02]);
}
b.extend_from_slice(&[0xFF, 0xD9]);
match crate::decode(&b, DecodeOptions::default()) {
Err(Error::Malformed(F, m)) => assert!(m.contains("APP1"), "{m}"),
other => panic!("unexpected: {other:?}"),
}
}
}
+76 -45
View File
@@ -255,9 +255,20 @@ fn fdct_quant(block: &[f32; 64], recip: &[f32; 64], out: &mut [i16; 64]) {
aan_1d(&mut d, c, 8);
}
for i in 0..64 {
out[i] = (d[i] * recip[i]).round() as i16;
out[i] = round_i16(d[i] * recip[i]);
}
}
/// `x.round() as i16` (half away from zero, saturating, NaN to 0) for every `x` (checked for all of them), in plain
/// arithmetic: without SSE4.1 `f32::round` is a libm call, one per coefficient, that keeps the loop from vectorising.
#[inline(always)]
fn round_i16(x: f32) -> i16 {
// (below 2^24 the truncation is exact and so is the remainder)
let c = x.clamp(-65536.0, 65536.0);
let t = c as i32;
let f = c - t as f32;
let r = t + i32::from(f >= 0.5) - i32::from(f <= -0.5);
r.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
}
#[inline]
fn magnitude(v: i32) -> (u32, u32) {
@@ -395,31 +406,30 @@ fn encode_with(
(true, _) | (false, ChromaSubsampling::S444) => (1usize, 1usize),
(false, _) => (2, 2),
};
// colour conversion (JFIF YCbCr, full range, level-shifted) in one pass; chroma averaged 2×2 for 4:2:0
let n = width * height;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
// 4:4:4: Y, Cb, Cr at full resolution in one pass; 4:2:0: Y here, chroma below straight from 2×2 RGB means
// colour conversion (JFIF YCbCr, full range, level-shifted) of the pixel rows `rows`, one band's worth at a
// time (in the band's task: the planes of the whole image would be ~290 MB at 24 MP, written and read back
// once): 4:4:4 Y, Cb, Cr at full resolution in one pass; 4:2:0 Y, and chroma (rows `crows` of the
// half-size planes) straight from 2×2 RGB means (conversion is linear: average first, then convert once)
let ncomp = if gray || hs == 2 { 1 } else { 3 };
let mut full: Vec<Vec<f32>> = (0..ncomp).map(|_| vec![0f32; n]).collect();
{
let rows: Vec<(usize, Vec<&mut [f32]>)> = {
let mut its: Vec<_> = full.iter_mut().map(|p| p.chunks_mut(width)).collect();
(0..height).map_while(|y| Some((y, its.iter_mut().map(|it| it.next()).collect::<Option<_>>()?))).collect()
};
let conv = |(y, mut out): (usize, Vec<&mut [f32]>)| {
let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
let convert = |rows: std::ops::Range<usize>, crows: std::ops::Range<usize>| -> Vec<Plane> {
let mut full: Vec<Vec<f32>> = (0..ncomp).map(|_| vec![0f32; rows.len() * width]).collect();
for (k, y) in rows.clone().enumerate() {
let src = &data[y * width * channels..(y + 1) * width * channels];
let mut out: Vec<&mut [f32]> = full.iter_mut().map(|p| &mut p[k * width..(k + 1) * width]).collect();
if gray {
for (o, p) in out[0].iter_mut().zip(src.chunks_exact(channels)) {
*o = p[0] as f32 - 128.0;
}
return;
continue;
}
if out.len() == 1 {
for (o, p) in out[0].iter_mut().zip(src.chunks_exact(channels)) {
*o = 0.299 * p[0] as f32 + 0.587 * p[1] as f32 + 0.114 * p[2] as f32 - 128.0;
}
return;
continue;
}
for (x, p) in src.chunks_exact(channels).enumerate() {
let (r, g, b) = (p[0] as f32, p[1] as f32, p[2] as f32);
@@ -427,37 +437,26 @@ fn encode_with(
out[1][x] = -0.168_736 * r - 0.331_264 * g + 0.5 * b;
out[2][x] = 0.5 * r - 0.418_688 * g - 0.081_312 * b;
}
};
#[cfg(feature = "parallel")]
rows.into_par_iter().for_each(conv);
#[cfg(not(feature = "parallel"))]
rows.into_iter().for_each(conv);
}
let mut it = full.into_iter();
let mut planes = vec![Plane { w: width, h: height, data: it.next().unwrap_or_default() }];
planes.extend(it.map(|c| Plane { w: width, h: height, data: c }));
if !gray && hs == 2 {
// conversion is linear: average RGB over 2×2 first, then convert once
let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
let (mut cb, mut cr) = (vec![0f32; cw * ch], vec![0f32; cw * ch]);
let down = |(cy, (ob, or)): (usize, (&mut [f32], &mut [f32]))| {
let (y0, y1) = (2 * cy, (2 * cy + 1).min(height - 1));
let (r0, r1) = (&data[y0 * width * channels..], &data[y1 * width * channels..]);
for cx in 0..cw {
let (x0, x1) = (2 * cx * channels, (2 * cx + 1).min(width - 1) * channels);
let s = |k: usize| (r0[x0 + k] as f32 + r0[x1 + k] as f32 + r1[x0 + k] as f32 + r1[x1 + k] as f32) * 0.25;
let (r, g, b) = (s(0), s(1), s(2));
ob[cx] = -0.168_736 * r - 0.331_264 * g + 0.5 * b;
or[cx] = 0.5 * r - 0.418_688 * g - 0.081_312 * b;
}
let mut planes: Vec<Plane> = full.into_iter().map(|data| Plane { w: width, h: rows.len(), data }).collect();
if !gray && hs == 2 {
let (mut cb, mut cr) = (vec![0f32; cw * crows.len()], vec![0f32; cw * crows.len()]);
for (cy, (ob, or)) in crows.clone().zip(cb.chunks_mut(cw).zip(cr.chunks_mut(cw))) {
let (y0, y1) = (2 * cy, (2 * cy + 1).min(height - 1));
let (r0, r1) = (&data[y0 * width * channels..], &data[y1 * width * channels..]);
for cx in 0..cw {
let (x0, x1) = (2 * cx * channels, (2 * cx + 1).min(width - 1) * channels);
let s = |k: usize| (r0[x0 + k] as f32 + r0[x1 + k] as f32 + r1[x0 + k] as f32 + r1[x1 + k] as f32) * 0.25;
let (r, g, b) = (s(0), s(1), s(2));
ob[cx] = -0.168_736 * r - 0.331_264 * g + 0.5 * b;
or[cx] = 0.5 * r - 0.418_688 * g - 0.081_312 * b;
}
}
};
#[cfg(feature = "parallel")]
cb.par_chunks_mut(cw).zip(cr.par_chunks_mut(cw)).enumerate().for_each(down);
#[cfg(not(feature = "parallel"))]
cb.chunks_mut(cw).zip(cr.chunks_mut(cw)).enumerate().for_each(down);
planes.push(Plane { w: cw, h: ch, data: cb });
planes.push(Plane { w: cw, h: ch, data: cr });
}
planes.push(Plane { w: cw, h: crows.len(), data: cb });
planes.push(Plane { w: cw, h: crows.len(), data: cr });
}
planes
};
let ql = scaled_quant(&Q_LUMA, quality);
let qc = scaled_quant(&Q_CHROMA, quality);
@@ -473,7 +472,12 @@ fn encode_with(
let (mut blk, mut q) = ([0f32; 64], [0i16; 64]);
let (mut tokens, mut freq) = (Vec::new(), [[0u64; 256]; 4]);
let mut pred = [0i32; 3];
for mcu_y in band * rows_per_band..((band + 1) * rows_per_band).min(my) {
let (m0, m1) = (band * rows_per_band, ((band + 1) * rows_per_band).min(my));
// the band's planes, its MCU row `m0` at their top (blocks past the image's bottom repeat its last row,
// which is the band's last row then)
let planes = convert(m0 * mcu_h..(m1 * mcu_h).min(height), m0 * 8..(m1 * 8).min(ch));
for mcu_y in m0..m1 {
let mcu_y = mcu_y - m0;
for mcu_x in 0..mx {
for vy in 0..vs {
for hx in 0..hs {
@@ -497,7 +501,6 @@ fn encode_with(
let tokenized: Vec<(Vec<Token>, [Freq; 4])> = bands.par_iter().map(tokenize_band).collect();
#[cfg(not(feature = "parallel"))]
let tokenized: Vec<(Vec<Token>, [Freq; 4])> = bands.iter().map(tokenize_band).collect();
drop(planes);
// the tables: DC luma, AC luma, DC chroma, AC chroma
let tables: [([u8; 16], Vec<u8>); 4] = if optimize {
let mut total = [[0u64; 256]; 4];
@@ -746,6 +749,34 @@ mod tests {
assert_eq!(jpeg_decoder::Decoder::new(&std[..]).decode().unwrap(), jpeg_decoder::Decoder::new(&opt[..]).decode().unwrap());
}
/// The bytes written for 4:4:4, 4:2:0, grayscale and RGBA input at a size cut into many bands, with partial MCUs
/// at the right and bottom edges, pinned: each band converts its own rows to YCbCr, which must not change a bit.
#[test]
fn encoded_bytes_are_pinned() {
let fnv = |b: &[u8]| b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| (h ^ u64::from(x)).wrapping_mul(0x100_0000_01b3));
let (w, h) = (1203, 1037);
let rgb = test_rgb(w, h);
let gray: Vec<u8> = rgb.as_chunks::<3>().0.iter().map(|p| p[1]).collect();
let rgba: Vec<u8> = rgb.as_chunks::<3>().0.iter().flat_map(|p| [p[0], p[1], p[2], 255]).collect();
let got = [
fnv(&encode(&rgb, w, h, 3, 90, ChromaSubsampling::S444, &[])),
fnv(&encode(&rgb, w, h, 3, 75, ChromaSubsampling::S420, &[])),
fnv(&encode(&gray, w, h, 1, 90, ChromaSubsampling::S444, &[])),
fnv(&encode(&rgba, w, h, 4, 85, ChromaSubsampling::S444, &[])),
];
assert_eq!(got, PINNED, "{got:#x?}");
}
/// [`round_i16`] against `f32::round` at the halves, the ends of `i16`, NaN and infinities, and a spread of every
/// magnitude (all 2^32 inputs were compared once, offline).
#[test]
fn round_i16_is_round_as_i16() {
let special = [0.5f32, -0.5, 1.5, -1.5, 2.5, -2.5, 0.499_999_97, -0.499_999_97, 32767.5, -32768.5, 32766.5, 1e9, -1e9];
let all = special.into_iter().chain([f32::NAN, f32::INFINITY, f32::NEG_INFINITY]).chain((0..=u32::MAX).step_by(9973).map(f32::from_bits));
for x in all {
assert_eq!(round_i16(x), x.round() as i16, "{x:e}");
}
}
const PINNED: [u64; 4] = [0x52ba_772a_589c_1430, 0x013f_8364_821f_1dde, 0xb2a3_b5e5_aef3_7402, 0x08df_d6dc_aa2f_1c78];
#[test]
fn grayscale_and_quality_monotone() {
let (w, h) = (300, 200);
+83
View File
@@ -5,6 +5,9 @@ use crate::{DecodeOptions, Decoded, Error, Format, Result};
use image::{DynamicImage, ImageDecoder};
pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Result<Decoded> {
if format == Format::Gif {
gated_first_frame(bytes, opts)?;
}
let err = |e: image::ImageError| Error::Malformed(format, e.to_string());
let cursor = std::io::Cursor::new(bytes);
let (img, icc) = match format {
@@ -36,3 +39,83 @@ pub(crate) fn decode(bytes: &[u8], format: Format, opts: &DecodeOptions) -> Resu
let raw = Raw { width: w as usize, height: h as usize, model, alpha, premultiplied: false, buf: Buf::U8(buf), bit_depth: 8 };
finish(format, raw, Meta { icc, ..Default::default() }, (w, h), opts)
}
/// Bounds a GIF's first image descriptor: the decoder composites frames into the logical screen
/// (bounded by [`check_size`] on the canvas) but allocates its own frame buffers at the frame's
/// declared size, which a small file can inflate far past the canvas. The canvas check cannot
/// see that size, so it is read from the block headers here.
fn gated_first_frame(bytes: &[u8], opts: &DecodeOptions) -> Result<()> {
// The constants of the header grammar: signature, logical screen descriptor (with its global
// colour table), extension blocks (0x21, skipped by their sub-block chains) and image
// descriptors (0x2C).
const SCREEN: usize = 13;
if bytes.len() < SCREEN {
return Ok(()); // too broken for a frame; the decoder reports the damage itself
}
let gct_entries = 1usize << (u32::from(bytes[10] & 0x07) + 1); // at most 256
let gct_bytes = if (bytes[10] & 0x80) != 0 { gct_entries * 3 } else { 0 };
let mut p = SCREEN.saturating_add(gct_bytes);
while let Some(&kind) = bytes.get(p) {
match kind {
0x2C => {
// Image descriptor: two LE coordinates then two LE edges, after the separator.
let end = p.checked_add(10).filter(|&e| e <= bytes.len());
let Some(d) = end.and_then(|e| bytes.get(p + 1..e)) else {
break; // cut short mid-descriptor: the decoder reports that
};
let (w, h) = (u16::from_le_bytes([d[4], d[5]]) as u64, u16::from_le_bytes([d[6], d[7]]) as u64);
return check_size(Format::Gif, w, h, opts);
}
0x21 => {
// Extension: a label byte, then <len,data> sub-blocks ended by a zero length.
p = p.saturating_add(2);
loop {
let Some(&len) = bytes.get(p) else {
return Ok(()); // ran past the data: decode reports the truncation
};
p = p.saturating_add(1);
if len == 0 {
break;
}
p = p.saturating_add(len as usize);
}
}
_ => p = p.saturating_add(1),
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use crate::{DecodeOptions, Error};
fn gif(blocks: &[u8]) -> Vec<u8> {
let mut b = b"GIF89a".to_vec();
// logical screen: 2×2, no global colour table, background 0, aspect 0
b.extend_from_slice(&[2, 0, 2, 0, 0x00, 0, 0]);
b.extend_from_slice(blocks);
b
}
/// `image`'s GIF decoder allocates its frame buffer at the image descriptor's declared
/// size, which the canvas bound ([`crate::decode`]'s `max_pixels` on the logical screen)
/// does not cover. A 20-byte file used to buy a 4 GB allocation before the gate.
#[test]
fn a_first_frame_over_the_bound_is_refused_without_allocating_it() {
let bytes = gif(&[0x2C, 0, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0x00]);
match crate::decode(&bytes, DecodeOptions::default()) {
Err(Error::TooLarge(w, h)) => assert_eq!((w, h), (65535, 65535)),
other => panic!("unexpected: {other:?}"),
}
}
/// A frame within the bound still reaches the decoder (which reports the truncated data);
/// the gate may only refuse on size.
#[test]
fn a_first_frame_within_the_bound_is_not_refused() {
let bytes = gif(&[0x2C, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0x00]);
let r = crate::decode(&bytes, DecodeOptions::default());
assert!(matches!(r, Err(Error::Malformed(..)) | Err(Error::TooLarge(..))), "{r:?}");
}
}
+64 -1
View File
@@ -7,6 +7,10 @@ use lightcraft_color::{Mat3, RgbSpace, Xy};
const F: Format = Format::Png;
/// Expansion cap for a compressed text chunk's payload: real XMP documents are a few hundred
/// kilobytes, so anything past this is hostile input, not metadata.
const MAX_TEXT_CHUNK: usize = 4 << 20;
fn err(e: impl std::fmt::Display) -> Error {
Error::Malformed(F, e.to_string())
}
@@ -42,11 +46,18 @@ pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
};
let raw = Raw { width: out.width as usize, height: out.height as usize, model, alpha, premultiplied: false, buf: samples, bit_depth: depth };
// png's `get_text()` inflates a compressed chunk with no bound of its own: a tiny
// iTXt can claim an XMP document of arbitrary size. Expand through the bounded path
// instead, and drop any XMP bigger than the cap.
let xmp = info
.utf8_text
.iter()
.find(|t| t.keyword == "XML:com.adobe.xmp")
.and_then(|t| t.get_text().ok())
.and_then(|t| {
let mut t = t.clone();
t.decompress_text_with_limit(MAX_TEXT_CHUNK).ok()?;
t.get_text().ok()
})
.or_else(|| info.uncompressed_latin1_text.iter().find(|t| t.keyword == "XML:com.adobe.xmp").map(|t| t.text.clone()));
let exif = info.exif_metadata.as_ref().map(|e| {
let e = e.to_vec();
@@ -168,3 +179,55 @@ fn rgb_to_xyz_d50_checked(space: &RgbSpace) -> Option<Mat3> {
}
Some(crate::space::rgb_to_xyz_d50(space))
}
#[cfg(test)]
mod tests {
use crate::DecodeOptions;
/// A compressed text chunk is expanded by `png` through our own cap: an XMP document
/// bigger than it is dropped, not inflated. Compressing an 8 MiB string is a few
/// kilobytes — the reverse of what the unbounded `get_text()` path allowed.
#[test]
fn compressed_xmp_over_the_cap_is_dropped() {
let out = png_with_compressed_xmp(&"x".repeat(8 << 20));
let d = crate::decode(&out, DecodeOptions::default()).unwrap();
assert!(d.xmp.is_none());
assert_eq!((d.width, d.height), (1, 1));
}
/// XMP within the cap is still read, compressed or not.
#[test]
fn compressed_xmp_under_the_cap_is_read() {
let out = png_with_compressed_xmp(&"<?xpacket?><xmp/>".repeat(100));
let d = crate::decode(&out, DecodeOptions::default()).unwrap();
assert!(d.xmp.as_deref().is_some_and(|x| x.contains("xmp/")));
}
/// A little-endian PNG with one compressed iTXt chunk carrying `payload` as XMP.
fn png_with_compressed_xmp(payload: &str) -> Vec<u8> {
use png::text_metadata::{EncodableTextChunk, ITXtChunk};
let mut base = Vec::new();
{
let mut enc = png::Encoder::new(&mut base, 1, 1);
enc.set_color(png::ColorType::Grayscale);
enc.set_depth(png::BitDepth::Eight);
let mut w = enc.write_header().unwrap();
w.write_image_data(&[0x7F]).unwrap();
w.finish().unwrap();
}
// `ITXtChunk::encode` writes the complete chunk (length, type, payload, CRC), with
// the text compressed.
let mut chunk = Vec::new();
let mut xmp = ITXtChunk::new("XML:com.adobe.xmp", payload);
xmp.compressed = true;
xmp.compress_text().unwrap();
xmp.encode(&mut chunk).unwrap();
// Text chunks after IDAT land in `info` once the stream is finished: insert ours
// before the trailing IEND (a zero-length chunk is exactly 12 bytes).
let split = base.len() - 12;
let mut out = base[..split].to_vec();
out.extend_from_slice(&chunk);
out.extend_from_slice(&base[split..]);
out
}
}
+1
View File
@@ -24,3 +24,4 @@ web-time = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
dhat = { workspace = true }
+18 -7
View File
@@ -14,6 +14,14 @@ pub struct Layout {
pub dy: usize,
}
/// The mosaic dimensions and cell origin for one square denoiser input tile.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TileRegion {
pub mosaic_size: (usize, usize),
pub cell_origin: (isize, isize),
pub tile_size: usize,
}
impl Layout {
/// The layout of a 2 × 2 colour pattern, row-major, colours 0 = red, 1 = green, 2 = blue; `None` when
/// it is not a Bayer cell (one red, one blue, the greens on the other diagonal).
@@ -65,7 +73,10 @@ pub fn reflect(i: isize, n: usize) -> usize {
/// Pack the `tile × tile` cells whose top-left cell is `(cx0, cy0)` into `out` as four planes `[R, G1, G2, B]`
/// (`4 · tile²` values, NCHW). G1 is the green beside the red sample, G2 the green under it. Samples outside
/// the picture are mirrored. Returns `false` (and writes nothing) when the sizes do not fit.
pub fn pack_tile(mosaic: &[f32], width: usize, height: usize, layout: Layout, cx0: isize, cy0: isize, tile: usize, out: &mut [f32]) -> bool {
pub fn pack_tile(mosaic: &[f32], layout: Layout, region: TileRegion, out: &mut [f32]) -> bool {
let (width, height) = region.mosaic_size;
let (cx0, cy0) = region.cell_origin;
let tile = region.tile_size;
let Some(plane) = tile.checked_mul(tile) else { return false };
let Some(values) = plane.checked_mul(4) else { return false };
if width == 0
@@ -113,7 +124,7 @@ mod tests {
let layout = Layout::from_cell([0, 1, 1, 2]).unwrap();
let mut out = [7.0; 4];
for (w, h, tile, x) in [(usize::MAX, 2, 1, 0), (1, 1, usize::MAX, 0), (1, 1, 0, 0), (1, 1, 1, isize::MAX), (1, 1, 1, isize::MIN)] {
assert!(!pack_tile(&[0.5], w, h, layout, x, 0, tile, &mut out));
assert!(!pack_tile(&[0.5], layout, TileRegion { mosaic_size: (w, h), cell_origin: (x, 0), tile_size: tile }, &mut out));
assert_eq!(out, [7.0; 4]);
}
for n in [1, 2, isize::MAX as usize, usize::MAX] {
@@ -160,7 +171,7 @@ mod tests {
let (nx, ny) = layout.cells(w, h);
let tile = nx.max(ny);
let mut out = vec![0.0; 4 * tile * tile];
assert!(pack_tile(&mosaic, w, h, layout, 0, 0, tile, &mut out));
assert!(pack_tile(&mosaic, layout, TileRegion { mosaic_size: (w, h), cell_origin: (0, 0), tile_size: tile }, &mut out));
let plane = tile * tile;
for (p, want) in [10.0, 20.0, 20.0, 30.0].into_iter().enumerate() {
assert!(out[p * plane..(p + 1) * plane].iter().all(|&v| v == want), "layout {cell:?} plane {p}");
@@ -174,7 +185,7 @@ mod tests {
let (w, h) = (4, 4);
let mosaic: Vec<f32> = (0..16).map(|i| i as f32).collect();
let mut out = vec![0.0; 4 * 4];
assert!(pack_tile(&mosaic, w, h, Layout { dx: 0, dy: 0 }, 0, 0, 2, &mut out));
assert!(pack_tile(&mosaic, Layout { dx: 0, dy: 0 }, TileRegion { mosaic_size: (w, h), cell_origin: (0, 0), tile_size: 2 }, &mut out));
// cell (0,0): R = site (0,0)=0, G1 = site (1,0)=1, G2 = site (0,1)=4, B = site (1,1)=5
assert_eq!([out[0], out[4], out[8], out[12]], [0.0, 1.0, 4.0, 5.0]);
// cell (1,0): sites (2,0)=2, (3,0)=3, (2,1)=6, (3,1)=7
@@ -184,8 +195,8 @@ mod tests {
#[test]
fn packing_rejects_wrong_sizes() {
let mut out = vec![0.0; 16];
assert!(!pack_tile(&[0.0; 15], 4, 4, Layout { dx: 0, dy: 0 }, 0, 0, 2, &mut out));
assert!(!pack_tile(&[0.0; 16], 4, 4, Layout { dx: 0, dy: 0 }, 0, 0, 3, &mut out));
assert!(!pack_tile(&[], 0, 0, Layout { dx: 0, dy: 0 }, 0, 0, 2, &mut out));
assert!(!pack_tile(&[0.0; 15], Layout { dx: 0, dy: 0 }, TileRegion { mosaic_size: (4, 4), cell_origin: (0, 0), tile_size: 2 }, &mut out));
assert!(!pack_tile(&[0.0; 16], Layout { dx: 0, dy: 0 }, TileRegion { mosaic_size: (4, 4), cell_origin: (0, 0), tile_size: 3 }, &mut out));
assert!(!pack_tile(&[], Layout { dx: 0, dy: 0 }, TileRegion { mosaic_size: (0, 0), cell_origin: (0, 0), tile_size: 2 }, &mut out));
}
}
+35 -2
View File
@@ -9,7 +9,7 @@
//! compressed length and CRC-32, then the strips' bytes. `key` says what the product was made from (the photo's
//! content, the model, this code's version, the settings it depends on); a file with another key is stale.
use std::io::{Read, Write};
use std::io::{Read, Seek, Write};
use std::path::Path;
use lightcraft_raster::Rgb32f;
@@ -216,6 +216,10 @@ fn read_start(r: &mut impl Read) -> Result<Start, ProductError> {
r.read_exact(&mut e)?;
let l = u32::from_le_bytes([e[0], e[1], e[2], e[3]]) as usize;
let c = u32::from_le_bytes([e[4], e[5], e[6], e[7]]);
// a strip never compresses to nothing (it has at least one row, so at least one deflated pixel)
if l == 0 {
return Err(ProductError::Format("a strip is empty".into()));
}
// a strip never compresses to much more than its raw size
if l > 12 * h.strip * h.width + 4096 {
return Err(ProductError::Format("a strip is larger than it can be".into()));
@@ -305,7 +309,6 @@ pub fn read_window(path: &Path, key: &str, window: Option<Window>, factor: usize
}
// the picture rows and columns the blocks cover
let (x_end, y_end) = if whole { (w.x + w.width, w.y + w.height) } else { (w.x + ow * factor, w.y + oh * factor) };
let mut out = Rgb32f { width: ow, height: oh, data: allocate(ow * oh, [0.0; 3])? };
let lut = f16_table();
let value = |raw: &[u8], c: usize, n: usize, i: usize| -> f32 {
let (lo, hi) = (raw.get(2 * c * n + i).copied().unwrap_or(0), raw.get((2 * c + 1) * n + i).copied().unwrap_or(0));
@@ -318,6 +321,21 @@ pub fn read_window(path: &Path, key: &str, window: Option<Window>, factor: usize
let strips: Vec<usize> = (0..table.len()).filter(|&s| wanted(s)).collect();
// skip the strips before the first one wanted
let skipped: usize = table.iter().take(strips.first().copied().unwrap_or(0)).map(|e| e.0).sum();
// The output is reserved only after the wanted strips' compressed bytes are present and match their checksums:
// a malformed cache whose strips are empty, damaged or short are rejected here, before the (large) result is
// allocated, not after. Reading them twice is cheap next to decoding them, and the fold below re-seeks here.
let strips_at = f.stream_position()?;
f.seek_relative(i64::try_from(skipped).map_err(|_| ProductError::Format("the file is too large".into()))?)?;
for &s in &strips {
let Some(&(len, expected)) = table.get(s) else { return Err(ProductError::Format("a strip is missing".into())) };
let mut packed = allocate(len, 0u8)?;
f.read_exact(&mut packed)?;
if crc(&packed) != expected {
return Err(ProductError::Format(format!("strip {s} is damaged")));
}
}
let mut out = Rgb32f { width: ow, height: oh, data: allocate(ow * oh, [0.0; 3])? };
f.seek(std::io::SeekFrom::Start(strips_at))?;
f.seek_relative(i64::try_from(skipped).map_err(|_| ProductError::Format("the file is too large".into()))?)?;
for group in strips.chunks(GROUP) {
let mut packed = Vec::with_capacity(group.len());
@@ -422,6 +440,21 @@ mod tests {
let _ = std::fs::remove_file(p);
}
#[test]
fn an_empty_strip_entry_is_rejected_by_the_header() {
let p = temp("empty-strip");
let header = serde_json::to_vec(&Header { width: 16, height: 1, strip: STRIP_ROWS, key: "k".into() }).unwrap();
let mut bytes = Vec::from(MAGIC.as_slice());
bytes.extend_from_slice(&[VERSION, 0, 0, 0]);
bytes.extend_from_slice(&(header.len() as u32).to_le_bytes());
bytes.extend_from_slice(&header);
// one strip with a zero-length entry: it has a row, so its deflated bytes are never empty
bytes.extend_from_slice(&[0; 8]);
std::fs::write(&p, bytes).unwrap();
assert!(matches!(read_header_at(&p), Err(ProductError::Format(why)) if why.contains("empty")));
let _ = std::fs::remove_file(p);
}
fn temp(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("lc-denoise-{name}-{}.lcdn", std::process::id()))
}
+7 -2
View File
@@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use lightcraft_raster::Rgb32f;
use rayon::prelude::*;
use crate::bayer::{Layout, pack_tile};
use crate::bayer::{Layout, TileRegion, pack_tile};
use crate::manifest::Gain;
use crate::tiles::{starts, weight};
@@ -139,7 +139,12 @@ pub fn denoise_bayer(
.par_iter()
.map(|&(x0, y0, bx, ax, by, ay)| {
let mut input = allocate(4 * p.tile * p.tile, 0f32)?;
if !pack_tile(mosaic, width, height, layout, x0 as isize, y0 as isize, p.tile, &mut input) {
if !pack_tile(
mosaic,
layout,
TileRegion { mosaic_size: (width, height), cell_origin: (x0 as isize, y0 as isize), tile_size: p.tile },
&mut input,
) {
return Err(Error::Input("a tile could not be packed".into()));
}
let mut out = runner.run(&input)?;
+50
View File
@@ -0,0 +1,50 @@
//! Peak heap of a `read_window` that must reject a product's strips (`crates/denoise-core/src/product.rs`), measured
//! with dhat's testing mode. The result is allocated only after the wanted strips' checksums are verified, so a cache
//! whose compressed bytes are damaged or absent fails without first reserving the (multi-megabyte) output. One test
//! per binary (dhat's profiler is global).
use lightcraft_denoise_core::product::read_window;
#[global_allocator]
static ALLOC: dhat::Alloc = dhat::Alloc;
fn temp(name: &str) -> std::path::PathBuf {
std::env::temp_dir().join(format!("lc-denoise-{name}-{}.lcdn", std::process::id()))
}
/// A 2000 × 1024 product of key `k` (a 24 MB result): its 8 strips each claim 8 bytes that do not match their
/// checksum, and the file is exactly the length its header and table declare. A 24 MB peak means the output was
/// reserved; the cap here bounds the header, the table and the strips' own bytes.
fn damaged_product() -> Vec<u8> {
let header = br#"{"width":2000,"height":1024,"strip":128,"key":"k"}"#;
const STRIP_LEN: usize = 8;
let mut bytes = Vec::from(b"LCDN".as_slice());
bytes.extend_from_slice(&[1, 0, 0, 0]);
bytes.extend_from_slice(&(header.len() as u32).to_le_bytes());
bytes.extend_from_slice(header);
let expected_len = 12 + header.len() + 8 * 8 + 8 * STRIP_LEN;
for _ in 0..8 {
// 8 claimed bytes whose recorded checksum does not match theirs (0xAA bytes do not have this CRC)
bytes.extend_from_slice(&(STRIP_LEN as u32).to_le_bytes());
bytes.extend_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD]);
}
for _ in 0..8 {
bytes.extend_from_slice(&[0xAAu8; STRIP_LEN]);
}
assert_eq!(bytes.len(), expected_len, "the crafted file lies about its length");
bytes
}
#[test]
fn a_damaged_product_is_rejected_before_its_output_is_allocated() {
let bytes = damaged_product();
let p = temp("damaged-product-heap");
std::fs::write(&p, &bytes).unwrap();
let _profiler = dhat::Profiler::builder().testing().build();
let why = read_window(&p, "k", None, 1, None).err().unwrap().to_string();
let peak = dhat::HeapStats::get().max_bytes;
let _ = std::fs::remove_file(p);
assert!(why.contains("damaged"), "{why}");
eprintln!("peak heap {peak} bytes");
assert!(peak < 4 << 20, "peak heap {peak} bytes: the output was reserved before the strips were checked");
}
+71 -5
View File
@@ -4,6 +4,12 @@
use crate::net::{Net, NetError, Op, TensorId};
use crate::run::{Error, TileRunner};
/// The tensors' size cap: the same one the real runner's buffers share (`crates/denoise/src/cpu.rs`). A hostile `Net`
/// only ever has to satisfy the final shape: a `ConvT2` doubles the sides and a `MaxPool` halves them, so a small
/// accepted graph can zoom its intermediates far out and back. Every tensor is counted here, and a run whose layers
/// would retain more than one real tile's whole working set is refused before the memory behind it is reserved.
const MAX_VALUES: usize = 128 * 1024 * 1024;
/// A tensor in `[channels][side][side]` order.
struct T {
channels: usize,
@@ -11,12 +17,36 @@ struct T {
data: Vec<f32>,
}
/// A tensor's plain float count, in bounds.
fn count(channels: usize, side: usize) -> Result<usize, NetError> {
channels
.checked_mul(side)
.and_then(|n| n.checked_mul(side))
.filter(|&n| n > 0 && n <= MAX_VALUES)
.ok_or_else(|| NetError::Invalid("a tensor has no size or is too large".into()))
}
/// A zeroed tensor, keeping the memory the run keeps alive in bounds (`tensors` retains every layer's result).
fn tensor(channels: usize, side: usize, total: &mut usize) -> Result<Vec<f32>, NetError> {
let n = count(channels, side)?;
*total = (*total).saturating_add(n);
if *total > MAX_VALUES {
return Err(NetError::Invalid("the tile needs too much working memory".into()));
}
let mut data = Vec::new();
data.try_reserve_exact(n).map_err(|_| NetError::Invalid("not enough memory for a reference tile".into()))?;
data.resize(n, 0.0);
Ok(data)
}
/// Run `net` on `input` (`in_channels` planes of `tile × tile`).
pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError> {
if !net.fits_tile(tile) || input.len() != net.in_channels * tile * tile {
return Err(NetError::Invalid("the tile does not fit the network".into()));
}
let mut tensors: Vec<T> = vec![T { channels: net.in_channels, side: tile, data: input.to_vec() }];
let input = input.to_vec();
let mut total = input.len();
let mut tensors = vec![T { channels: net.in_channels, side: tile, data: input }];
let get = |tensors: &[T], id: TensorId| -> Result<usize, NetError> {
if id < tensors.len() { Ok(id) } else { Err(NetError::Invalid("a layer reads a tensor that does not exist yet".into())) }
};
@@ -27,7 +57,7 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError>
let b = c.src2.map(|s| get(&tensors, s)).transpose()?;
let side = tensors[a].side;
let pad = (c.k - 1) / 2;
let mut data = vec![0f32; c.cout * side * side];
let mut data = tensor(c.cout, side, &mut total)?;
// the input channels in order: the first source's, then the second's
let planes: Vec<&[f32]> =
std::iter::once(&tensors[a]).chain(b.map(|b| &tensors[b])).flat_map(|t| t.data.chunks(side * side)).collect();
@@ -56,7 +86,7 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError>
let a = get(&tensors, c.src)?;
let side = tensors[a].side;
let out_side = 2 * side;
let mut data = vec![0f32; c.cout * out_side * out_side];
let mut data = tensor(c.cout, out_side, &mut total)?;
for co in 0..c.cout {
for y in 0..side {
for x in 0..side {
@@ -77,7 +107,7 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError>
Op::MaxPool2 { src } => {
let a = get(&tensors, *src)?;
let (channels, side) = (tensors[a].channels, tensors[a].side / 2);
let mut data = vec![0f32; channels * side * side];
let mut data = tensor(channels, side, &mut total)?;
for ch in 0..channels {
for y in 0..side {
for x in 0..side {
@@ -92,7 +122,7 @@ pub fn run(net: &Net, tile: usize, input: &[f32]) -> Result<Vec<f32>, NetError>
let a = get(&tensors, *src)?;
let (channels, side) = (tensors[a].channels / 4, tensors[a].side);
let out_side = 2 * side;
let mut data = vec![0f32; channels * out_side * out_side];
let mut data = tensor(channels, out_side, &mut total)?;
for ch in 0..channels {
for y in 0..side {
for x in 0..side {
@@ -131,3 +161,39 @@ impl TileRunner for ReferenceRunner {
run(&self.net, self.tile, input).map_err(|e| Error::Runtime(e.to_string()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::net::ConvT2;
fn convt(src: TensorId, cin: usize, cout: usize) -> Op {
Op::ConvT2(ConvT2 { src, cin, cout, weight: vec![0.1; cin * cout * 4], bias: vec![0.0; cout], leaky: None })
}
/// A graph that fits the final-shape check while zooming its intermediates out and back: 256 `ConvT2`s double
/// the sides (256 tiers), 255 `MaxPool`s halve them back to the layer above the input.
fn hostile() -> Net {
let mut ops = Vec::new();
let mut last = 0usize;
for _ in 0..256 {
ops.push(convt(last, 1, 1));
last += 1;
}
for _ in 0..255 {
ops.push(Op::MaxPool2 { src: last });
last += 1;
}
Net::new(1, ops).unwrap()
}
/// The zoomed-out layers' memory was never reserved: either one tensor or the retained whole (the two bounds
/// share the cap) says why the run stops.
#[test]
fn a_graph_that_zooms_its_intermediates_out_and_back_is_refused_before_their_memory_is_reserved() {
assert!(matches!(
run(&hostile(), 1, &[1.0]),
Err(NetError::Invalid(why)) if why.contains("too large") || why.contains("too much working memory")
));
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ thiserror = { workspace = true }
log = { workspace = true }
ab_glyph = { workspace = true }
# Apply the font’s vertical substitutions and origins to Japanese watermarks.
harfrust = { version = "0.12", default-features = false, features = ["std"] }
harfrust = { version = "0.13", default-features = false, features = ["std"] }
unicode-segmentation = "1.13"
lightcraft-segment = { workspace = true, optional = true }
+81
View File
@@ -0,0 +1,81 @@
//! Single-photo export benchmark (median and minimum of N runs):
//! `cargo run --release -p lightcraft-engine --example export_bench -- corpus/raw/arw-sony-a7m3-compressed.arw`
//!
//! Imports the files given and runs the export path the app, CLI and MCP share
//! ([`lightcraft_engine::export::export_photo`]: decode the original, render it full size, encode)
//! once per file per run, forgetting the decoded original between runs so each export reads and
//! decodes it like a batch export does. `N=9` runs (default), `OPT='{"format":"png"}'` for other
//! export options (JSON as `app.export` takes them), `LIGHTCRAFT_GPU=0` for the CPU pipeline,
//! `PHASES=1` to time render and encode separately, `OUT=dir` to write each file's export there
//! (for byte comparisons between builds).
use std::time::Instant;
use lightcraft_engine::Session;
use lightcraft_engine::catalog::PhotoId;
use lightcraft_engine::export::{ExportOptions, encode_rendered, export_metadata, export_photo};
fn stats(mut v: Vec<f64>) -> (f64, f64) {
v.sort_by(f64::total_cmp);
(v[v.len() / 2], v[0])
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
assert!(!args.is_empty(), "usage: export_bench FILE...");
let n: usize = std::env::var("N").ok().and_then(|v| v.parse().ok()).unwrap_or(9).max(1);
let opt: serde_json::Value =
std::env::var("OPT").ok().map(|s| serde_json::from_str(&s).expect("OPT is JSON")).unwrap_or_else(|| serde_json::json!({}));
let o = ExportOptions::from_params(&opt).expect("export options");
let mut s = Session::new().with_fs();
let paths: Vec<String> = args.iter().map(|p| std::fs::canonicalize(p).expect("input file").to_string_lossy().to_string()).collect();
let r = s.execute("library.import", &serde_json::json!({"paths": paths})).expect("import");
let ids: Vec<PhotoId> = r["imported"].as_array().expect("ids").iter().filter_map(|v| v.as_u64()).map(PhotoId).collect();
assert_eq!(ids.len(), args.len(), "every file imports");
println!("{} file(s), {:?}, {n} runs, gpu {}", ids.len(), o.format, lightcraft_engine::gpu::available());
let mut times = Vec::new();
for i in 0..=n {
let t = Instant::now();
for (k, &id) in ids.iter().enumerate() {
let e = export_photo(&mut s, id, &o, k + 1).expect("export");
if i == 0
&& let Some(dir) = std::env::var_os("OUT")
{
std::fs::write(std::path::Path::new(&dir).join(&e.file_name), &e.bytes).expect("write");
println!(" {} {}×{} {} bytes", e.file_name, e.width, e.height, e.bytes.len());
}
s.media.forget(id);
}
// run 0 warms up (GPU device, allocator, page cache)
if i > 0 {
times.push(t.elapsed().as_secs_f64() * 1e3);
}
}
let (med, min) = stats(times.clone());
println!("export: median {med:.1} ms, min {min:.1} ms (runs: {})", times.iter().map(|t| format!("{t:.0}")).collect::<Vec<_>>().join(" "));
if std::env::var_os("PHASES").is_none() {
return;
}
let (mut render, mut encode) = (Vec::new(), Vec::new());
for _ in 0..n {
let (mut tr, mut te) = (0.0, 0.0);
for &id in &ids {
let p = s.catalog.photo(id).expect("photo").clone();
let (w, h) = lightcraft_engine::export::output_size(&p, &o);
let meta = export_metadata(&p, &s.catalog, &o);
let job = s.export_job(id, w, h, o.effective_space(), o.effective_depth()).expect("job");
let t = Instant::now();
let r = job.run().rendered.expect("render");
tr += t.elapsed().as_secs_f64() * 1e3;
let t = Instant::now();
std::hint::black_box(encode_rendered(&r, &o, meta.as_ref()).expect("encode"));
te += t.elapsed().as_secs_f64() * 1e3;
s.media.forget(id);
}
render.push(tr);
encode.push(te);
}
let (rm, rn) = stats(render);
let (em, en) = stats(encode);
println!(" decode+render: median {rm:.1} ms, min {rn:.1} ms");
println!(" encode: median {em:.1} ms, min {en:.1} ms");
}
+100 -88
View File
@@ -91,107 +91,119 @@ fn diff(a: &lightcraft_raster::Rgba8, b: &lightcraft_raster::Rgba8) -> (u8, f64)
(max, sum as f64 / (a.data.len() * 3).max(1) as f64)
}
fn benchmark_jpeg(args: &[String], n: usize) {
// a JPEG (e.g. an embedded preview pulled out with exiftool) decoded to fit a few boxes
for path in args {
let bytes = std::fs::read(path).expect("read");
for edge in [256u32, 512, 1600, 2560] {
let o = lightcraft_codecs::DecodeOptions::fit(edge, edge);
let d = lightcraft_codecs::decode(&bytes, o).expect("decode");
println!(
" {path} fit {edge}: {}×{} {}",
d.image.width,
d.image.height,
best(n, || drop(lightcraft_codecs::decode(&bytes, o).expect("decode")))
);
}
}
}
fn benchmark_load(args: &[String], n: usize, only: &str) {
// opening a photo in the loupe, step by step: what the app's loaders cost (per file)
for path in args {
let bytes = std::fs::read(path).expect("read");
println!("{path}");
if std::env::var("LOADONLY").is_ok() {
// only the preview load (for a profiler)
println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load"))));
continue;
}
println!(" {:<36} {}", "file read:", best(n, || drop(std::fs::read(path).expect("read"))));
println!(" {:<36} {}", "raw decode:", best(n, || drop(lightcraft_raw::decode(&bytes).expect("decode"))));
let mut raw = lightcraft_raw::decode(&bytes).expect("decode");
if let lightcraft_raw::RawData::U16(d) = &raw.data {
let sum = d.iter().enumerate().fold(0u64, |a, (i, &v)| a.wrapping_mul(31).wrapping_add(v as u64 ^ i as u64));
println!(" decode checksum: {sum:016x}");
}
if only == "load1" {
println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load"))));
continue;
}
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
if let Some(k) = lightcraft_engine::files::bin_factor(&raw, 2560) {
println!(" {:<36} {}", format!("binned ×{k} masked:"), best(n, || drop(raw.develop_binned_masked(k, 0.99))));
}
for edge in [2560usize, 1600] {
println!(
" {:<36} {}",
format!("embedded srgb, whole file ({edge}):"),
best(n, || drop(lightcraft_engine::files::embedded_preview_srgb(&bytes, edge)))
);
let quick = lightcraft_engine::files::fs_preview_loader();
println!(" {:<36} {}", format!("fs_preview_loader ({edge}):"), best(n, || drop(quick(path, edge))));
}
println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load"))));
let (loader, _) = lightcraft_engine::files::fs_hooks();
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560).expect("load"))));
}
}
fn benchmark_source(args: &[String], n: usize) {
// opening a photo: where the time goes before the first sharp loupe (per file)
for path in args {
let bytes = std::fs::read(path).expect("read");
println!("{path}");
let mut raw = lightcraft_raw::decode(&bytes).expect("decode");
// as the loader does: lens corrections are applied by the pipeline, not in the raw develop
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
println!(" {}×{} cpp {} cfa {:?}", raw.width, raw.height, raw.cpp, raw.cfa.as_ref().map(|c| c.name()));
println!(" {:<36} {}", "raw decode:", best(n, || drop(lightcraft_raw::decode(&bytes).expect("decode"))));
println!(" {:<36} {}", "normalize:", best(n, || drop(raw.normalized().expect("norm"))));
let norm = raw.normalized().expect("norm");
println!(" {:<36} {}", "demosaic AHD:", best(n, || drop(lightcraft_raw::demosaic(&norm, lightcraft_raw::Method::Ahd))));
if let Some(k) = lightcraft_engine::files::bin_factor(&raw, 2560) {
println!(" {:<36} {}", format!("binned ×{k} (2560 preview):"), best(n, || drop(raw.develop_binned(k, 0.99))));
let img = raw.develop_binned(k, 0.99).expect("bin").expect("binnable");
let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw));
println!(
" {:<36} {}",
"highlight reconstruct (binned):",
best(n, || {
let mut i = img.clone();
lightcraft_raw::highlight::reconstruct(&mut i, t.wb, 0.99);
})
);
println!(" {:<36} {}", "clone (binned):", best(n, || drop(img.clone())));
println!(" {:<36} {}", "fit 2560 (binned):", best(n, || drop(fit(&img, 2560, 2560, Filter::Box))));
}
println!(" {:<36} {}", "embedded preview (2560):", best(n, || drop(lightcraft_engine::files::load_embedded_preview(&bytes, 2560))));
for edge in [512usize, 2560, usize::MAX] {
println!(
" {:<36} {}",
format!("load_bytes({edge}):"),
best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, edge).expect("load")))
);
}
}
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let n: usize = std::env::var("N").ok().and_then(|v| v.parse().ok()).unwrap_or(5);
let only = std::env::var("ONLY").unwrap_or_default();
let run = |name: &str| only.is_empty() || only.split(',').any(|o| name.contains(o));
if only == "jpeg" {
// a JPEG (e.g. an embedded preview pulled out with exiftool) decoded to fit a few boxes
for path in &args {
let bytes = std::fs::read(path).expect("read");
for edge in [256u32, 512, 1600, 2560] {
let o = lightcraft_codecs::DecodeOptions::fit(edge, edge);
let d = lightcraft_codecs::decode(&bytes, o).expect("decode");
println!(
" {path} fit {edge}: {}×{} {}",
d.image.width,
d.image.height,
best(n, || drop(lightcraft_codecs::decode(&bytes, o).expect("decode")))
);
}
}
benchmark_jpeg(&args, n);
return;
}
if only == "load" || only == "load1" {
// opening a photo in the loupe, step by step: what the app's loaders cost (per file)
for path in &args {
let bytes = std::fs::read(path).expect("read");
println!("{path}");
if std::env::var("LOADONLY").is_ok() {
// only the preview load (for a profiler)
println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load"))));
continue;
}
println!(" {:<36} {}", "file read:", best(n, || drop(std::fs::read(path).expect("read"))));
println!(" {:<36} {}", "raw decode:", best(n, || drop(lightcraft_raw::decode(&bytes).expect("decode"))));
let mut raw = lightcraft_raw::decode(&bytes).expect("decode");
if let lightcraft_raw::RawData::U16(d) = &raw.data {
let sum = d.iter().enumerate().fold(0u64, |a, (i, &v)| a.wrapping_mul(31).wrapping_add(v as u64 ^ i as u64));
println!(" decode checksum: {sum:016x}");
}
if only == "load1" {
println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load"))));
continue;
}
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
if let Some(k) = lightcraft_engine::files::bin_factor(&raw, 2560) {
println!(" {:<36} {}", format!("binned ×{k} masked:"), best(n, || drop(raw.develop_binned_masked(k, 0.99))));
}
for edge in [2560usize, 1600] {
println!(
" {:<36} {}",
format!("embedded srgb, whole file ({edge}):"),
best(n, || drop(lightcraft_engine::files::embedded_preview_srgb(&bytes, edge)))
);
let quick = lightcraft_engine::files::fs_preview_loader();
println!(" {:<36} {}", format!("fs_preview_loader ({edge}):"), best(n, || drop(quick(path, edge))));
}
println!(" {:<36} {}", "load_bytes(2560):", best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, 2560).expect("load"))));
let (loader, _) = lightcraft_engine::files::fs_hooks();
println!(" {:<36} {}", "fs loader (2560, read+load):", best(n, || drop(loader(path, 2560).expect("load"))));
}
benchmark_load(&args, n, &only);
return;
}
if only == "source" {
// opening a photo: where the time goes before the first sharp loupe (per file)
for path in &args {
let bytes = std::fs::read(path).expect("read");
println!("{path}");
let mut raw = lightcraft_raw::decode(&bytes).expect("decode");
// as the loader does: lens corrections are applied by the pipeline, not in the raw develop
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
println!(" {}×{} cpp {} cfa {:?}", raw.width, raw.height, raw.cpp, raw.cfa.as_ref().map(|c| c.name()));
println!(" {:<36} {}", "raw decode:", best(n, || drop(lightcraft_raw::decode(&bytes).expect("decode"))));
println!(" {:<36} {}", "normalize:", best(n, || drop(raw.normalized().expect("norm"))));
let norm = raw.normalized().expect("norm");
println!(" {:<36} {}", "demosaic AHD:", best(n, || drop(lightcraft_raw::demosaic(&norm, lightcraft_raw::Method::Ahd))));
if let Some(k) = lightcraft_engine::files::bin_factor(&raw, 2560) {
println!(" {:<36} {}", format!("binned ×{k} (2560 preview):"), best(n, || drop(raw.develop_binned(k, 0.99))));
let img = raw.develop_binned(k, 0.99).expect("bin").expect("binnable");
let t = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw));
println!(
" {:<36} {}",
"highlight reconstruct (binned):",
best(n, || {
let mut i = img.clone();
lightcraft_raw::highlight::reconstruct(&mut i, t.wb, 0.99);
})
);
println!(" {:<36} {}", "clone (binned):", best(n, || drop(img.clone())));
println!(" {:<36} {}", "fit 2560 (binned):", best(n, || drop(fit(&img, 2560, 2560, Filter::Box))));
}
println!(" {:<36} {}", "embedded preview (2560):", best(n, || drop(lightcraft_engine::files::load_embedded_preview(&bytes, 2560))));
for edge in [512usize, 2560, usize::MAX] {
println!(
" {:<36} {}",
format!("load_bytes({edge}):"),
best(n, || drop(lightcraft_engine::files::load_bytes(&bytes, edge).expect("load")))
);
}
}
benchmark_source(&args, n);
return;
}
let run = |name: &str| only.is_empty() || only.split(',').any(|o| name.contains(o));
let (full, info) = match args.first() {
Some(path) => {
let bytes = std::fs::read(path).expect("read");
+1 -523
View File
@@ -777,526 +777,4 @@ pub fn osascript() -> Runner {
}
#[cfg(test)]
mod tests {
use super::*;
/// A runner that records the arguments it got and answers `answer`.
fn fake(answer: Result<Output, RunError>) -> (Runner, Arc<Mutex<Vec<Vec<String>>>>) {
let calls = Arc::new(Mutex::new(Vec::new()));
let c = calls.clone();
let r: Runner = Arc::new(move |args: &[String], _| {
c.lock().unwrap().push(args.to_vec());
answer.clone()
});
(r, calls)
}
fn ok(stdout: &str) -> Result<Output, RunError> {
Ok(Output { status: Some(0), stdout: stdout.into(), stderr: String::new() })
}
fn failed(stderr: &str) -> Output {
Output { status: Some(1), stdout: String::new(), stderr: stderr.into() }
}
/// The script part of an argument list: everything before the marker.
fn script_of(args: &[String]) -> &[String] {
let at = args.iter().position(|a| a == MARKER).unwrap();
&args[..at]
}
#[test]
fn names_and_paths_are_arguments_never_script() {
let hostile = [
"",
"Holiday \"2026\"",
"back\\slash\\",
"line\nbreak\r\nand\ttab",
"end tell\ndo shell script \"rm -rf ~\"",
"-e",
"--help",
"日本の写真 📷 Ünïcödé",
"'single' & \"double\" » «",
];
let base = osascript_args("", &["/tmp/a.jpg".into()]);
for album in hostile {
let paths = vec!["/tmp/with \"quotes\".jpg".to_string(), "/tmp/new\nline/é\\x.jpg".to_string(), format!("/tmp/-{album}.jpg")];
let args = osascript_args(album, &paths);
// the script is the same whatever the input…
assert_eq!(script_of(&args), script_of(&base));
assert!(script_of(&args).chunks(2).all(|c| c[0] == "-e" && SCRIPT.lines().any(|l| l == c[1])));
// …and the input follows the marker as whole arguments, unchanged
let at = args.iter().position(|a| a == MARKER).unwrap();
assert_eq!(&args[at + 1], album);
assert_eq!(&args[at + 2..], &paths[..]);
}
// the script reads them from argv only
assert!(SCRIPT.starts_with("on run argv") && SCRIPT.contains("item 2 of argv") && SCRIPT.contains("item i of argv"));
assert!(!SCRIPT.contains("do shell script"));
// it imports into the album (made when missing) without skipping Photos' duplicate check
assert!(SCRIPT.contains("make new album named albumName"));
assert!(SCRIPT.contains("import mediaFiles into targetAlbum skip check duplicates false"));
}
/// Photos' `album` elements are every album, those in folders too, in no set order: the script
/// keeps the top-level ones of exactly that name and refuses when there are several.
#[test]
fn the_album_is_a_single_top_level_one() {
let lookup = SCRIPT.find("every album whose name is albumName").unwrap();
let choose = SCRIPT.find("set targetAlbum to item 1 of topLevel").unwrap();
let make = SCRIPT.find("make new album named albumName").unwrap();
let import = SCRIPT.find("import mediaFiles into targetAlbum").unwrap();
assert!(lookup < choose && choose < make && make < import);
let filter = &SCRIPT[lookup..choose];
assert!(filter.contains("parent of candidate") && filter.contains("candidateParent is missing value"), "{filter}");
assert!(filter.contains("considering case"), "exact names: {filter}");
assert!(filter.contains(&format!(
"if (count of topLevel) > 1 then error \"LightCraft: several top-level albums have this name\" number {AMBIGUOUS_ALBUM}"
)));
let m = explain(&failed(&format!("execution error: LightCraft: several top-level albums have this name ({AMBIGUOUS_ALBUM})")), "Trip");
assert!(m.contains("More than one album at the top level of Photos is named “Trip”") && m.contains("nothing was added"), "{m}");
}
#[test]
fn ids_are_one_per_line() {
assert_eq!(parse_ids("A1B2/L0/001\nC3D4/L0/001\n"), vec!["A1B2/L0/001", "C3D4/L0/001"]);
assert_eq!(parse_ids(" X/L0/001 \r\n\r\n Y/L0/001"), vec!["X/L0/001", "Y/L0/001"]);
assert!(parse_ids("").is_empty() && parse_ids("\n \n").is_empty());
}
#[test]
fn errors_say_what_to_do() {
let says = |stderr: &str, part: &str| {
let m = explain(&failed(stderr), "Trip");
assert!(m.contains(part), "{stderr:?}: {m}");
};
says("146:180: execution error: Not authorized to send Apple events to Photos. (-1743)", "System Settings › Privacy & Security › Automation");
says("execution error: Photos got an error: … (-1744)", "Automation");
says("execution error: Can’t get application \"Photos\". (-10814)", "couldn't be found");
says("execution error: Photos got an error: Application isn’t running. (-600)", "couldn't be found or opened");
says("execution error: User canceled. (-128)", "cancelled");
says("execution error: Photos got an error: AppleEvent timed out. (-1712)", "didn't answer in time");
says("execution error: File not found (-43)", "couldn't find a file");
says("execution error: Photos got an error: Something odd happened. (-2700)", "Something odd happened");
assert!(explain(&Output { status: Some(3), ..Default::default() }, "").contains("exited with 3"));
assert!(explain(&Output { status: None, ..Default::default() }, "").contains("stopped"));
assert!(explain_run_error(&RunError::NoPhotos).contains("couldn't be found"));
assert!(explain_run_error(&RunError::Spawn("denied".into())).contains("denied"));
assert!(explain_run_error(&RunError::Timeout(Duration::from_secs(65))).contains("65 s"));
// a stray parenthesis is not an error number
assert!(explain(&failed("execution error: (not a number)"), "").contains("not a number"));
}
fn files(tag: &str, n: usize) -> (std::path::PathBuf, Vec<String>) {
let dir = std::env::temp_dir().join(format!("lc-photos-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let paths = (0..n)
.map(|i| {
let p = dir.join(format!("photo {i} é.jpg"));
std::fs::write(&p, b"jpeg").unwrap();
p.to_string_lossy().to_string()
})
.collect();
(dir, paths)
}
#[test]
fn an_import_passes_the_files_and_returns_the_ids() {
let (dir, paths) = files("import", 2);
let (runner, calls) = fake(ok("ID-1/L0/001\nID-2/L0/001\n"));
let got = import(&runner, &paths, " Trip “2026” ").unwrap();
assert_eq!(got, Imported { ids: vec!["ID-1/L0/001".into(), "ID-2/L0/001".into()], requested: 2, album: Some("Trip “2026”".into()) });
assert_eq!(got.warning(), None);
let args = calls.lock().unwrap()[0].clone();
let at = args.iter().position(|a| a == MARKER).unwrap();
assert_eq!(&args[at + 1..], &[vec!["Trip “2026”".to_string()], paths.clone()].concat()[..]);
// fewer back than asked: a partial import, said so
let (runner, _) = fake(ok("ID-1/L0/001\n"));
let got = import(&runner, &paths, "").unwrap();
assert_eq!((got.ids.len(), got.album.clone()), (1, None));
assert!(got.warning().unwrap().contains("1 of 2"));
assert_eq!(got.to_json()["warning"], json!(got.warning().unwrap()));
// a failed run is the mapped message
let (runner, _) = fake(Ok(failed("execution error: Not authorized to send Apple events to Photos. (-1743)")));
assert!(import(&runner, &paths, "x").unwrap_err().contains("Automation"));
// a timeout names the request's limit
let (runner, _) = fake(Err(RunError::Timeout(Duration::from_secs(70))));
assert!(import(&runner, &paths, "x").unwrap_err().contains(&format!("{} s", timeout_for(2).as_secs())));
let _ = std::fs::remove_dir_all(dir);
}
/// Codex review of #643: every path was an argument of one osascript run, so a big export
/// (10,000 files) went over macOS's 1 MiB argument limit and Photos got nothing.
#[test]
fn big_imports_run_in_batches_within_the_argument_limit() {
let long = format!("/{}", "d/".repeat(500)); // about 1,000 bytes, near the longest path macOS opens
let paths: Vec<String> = (0..10_000).map(|i| format!("{long}{i:05}.jpg")).collect();
let runs = Arc::new(Mutex::new(Vec::<(usize, usize, Duration)>::new()));
let r = runs.clone();
let runner: Runner = Arc::new(move |args: &[String], limit| {
let files = args.len() - args.iter().position(|a| a == MARKER).unwrap() - 2;
r.lock().unwrap().push((files, args.iter().map(|a| a.len() + 1).sum(), limit));
Ok(Output { status: Some(0), stdout: (0..files).map(|i| format!("ID-{i}\n")).collect(), stderr: String::new() })
});
let got = execute(&runner, &paths, "Big").unwrap();
assert_eq!((got.ids.len(), got.requested, got.warning()), (10_000, 10_000, None));
let runs = runs.lock().unwrap().clone();
assert_eq!(runs.len(), 10_000 / BATCH);
assert!(runs.iter().all(|&(files, _, _)| files == BATCH));
let biggest = runs.iter().map(|&(_, bytes, _)| bytes).max().unwrap();
assert!(biggest < 1 << 18, "{biggest} bytes of arguments in one run");
// every run gets what is left of the request's limit, never more
assert!(runs.iter().all(|&(_, _, limit)| limit <= timeout_for(10_000)));
// a later batch failing: the error says how far Photos got
let calls = Arc::new(Mutex::new(0));
let c = calls.clone();
let runner: Runner = Arc::new(move |args: &[String], _| {
let mut n = c.lock().unwrap();
*n += 1;
let files = args.len() - args.iter().position(|a| a == MARKER).unwrap() - 2;
if *n == 2 {
return Ok(failed("execution error: Photos got an error: User canceled. (-128)"));
}
Ok(Output { status: Some(0), stdout: (0..files).map(|i| format!("ID-{i}\n")).collect(), stderr: String::new() })
});
let e = execute(&runner, &paths[..450], "Big").unwrap_err();
assert!(e.contains("cancelled") && e.contains("200 of the 450 files"), "{e}");
assert_eq!(*calls.lock().unwrap(), 2, "nothing more is sent after a failed batch");
// the batches share the request's one deadline: time a batch takes comes off the next one's
let limits = Arc::new(Mutex::new(Vec::<Duration>::new()));
let l = limits.clone();
let runner: Runner = Arc::new(move |args: &[String], limit| {
l.lock().unwrap().push(limit);
std::thread::sleep(Duration::from_millis(300));
let files = args.len() - args.iter().position(|a| a == MARKER).unwrap() - 2;
Ok(Output { status: Some(0), stdout: (0..files).map(|i| format!("ID-{i}\n")).collect(), stderr: String::new() })
});
execute(&runner, &paths[..450], "Big").unwrap();
let limits = limits.lock().unwrap().clone();
assert_eq!(limits.len(), 3);
let whole = timeout_for(450);
assert!(limits[0] <= whole && limits[0] > whole - Duration::from_millis(250), "{limits:?}");
assert!(limits[1] <= whole - Duration::from_millis(300) && limits[2] <= whole - Duration::from_millis(600), "{limits:?}");
}
#[test]
fn bad_requests_never_reach_osascript() {
let (dir, paths) = files("bad", 1);
let (runner, calls) = fake(ok(""));
assert!(import(&runner, &[], "").unwrap_err().contains("no files"));
assert!(import(&runner, &["relative/a.jpg".into()], "").unwrap_err().contains("absolute"));
assert!(import(&runner, &[format!("{}/missing.jpg", dir.display())], "").unwrap_err().contains("no such file"));
assert!(import(&runner, &[format!("{}/a\0b.jpg", dir.display())], "").unwrap_err().contains("NUL"));
assert!(import(&runner, &paths, "a\0b").unwrap_err().contains("NUL"));
assert!(calls.lock().unwrap().is_empty());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn after_an_export_the_written_files_are_added() {
let (dir, paths) = files("after", 2);
let exported = vec![
json!({"path": paths[0], "width": 10}),
json!({"skipped": "/elsewhere/x.jpg"}),
json!({"photo": 3, "error": "x"}),
json!({"path": paths[1]}),
];
let (runner, calls) = fake(ok("A/L0/001\nB/L0/001"));
let imports = Imports::default();
let out = imports.reserve(runner.clone(), " Album ").unwrap().run(&exported, false);
assert_eq!(out["imported"], 2);
assert_eq!(out["album"], "Album");
assert_eq!((out["job"].as_u64(), out["running"].as_bool()), (Some(1), Some(false)));
let args = calls.lock().unwrap()[0].clone();
assert_eq!(&args[args.len() - 2..], &paths[..], "only the files written, in order");
// nothing written, or cancelled: Photos isn't asked, and the slot is free again
let out = imports.reserve(runner.clone(), "").unwrap().run(&[json!({"skipped": "x"})], false);
assert!(out["skipped"].as_str().unwrap().contains("wrote no files"), "{out}");
assert_eq!(out.get("cancelled"), None, "{out}");
let out = imports.reserve(runner.clone(), "").unwrap().run(&exported, true);
assert!(out["skipped"].as_str().unwrap().contains("cancelled"), "{out}");
assert_eq!(out["cancelled"], true, "the app decides on the flag, not on the words: {out}");
assert_eq!(calls.lock().unwrap().len(), 1);
assert!(imports.running().is_none());
let _ = std::fs::remove_dir_all(dir);
}
/// An export that will add its files reserves the slot before writing them: a competing
/// import is refused, naming the export's job, and the export is never turned away after
/// writing. Every way the export can end frees the slot.
#[test]
fn an_export_reserves_the_import_before_writing() {
let (dir, paths) = files("reserve", 1);
let (runner, calls) = fake(ok("A\n"));
let imports = Imports::default();
let reserved = imports.reserve(runner.clone(), "Trip").unwrap();
assert_eq!(reserved.job().map(|j| j.json()), Some(json!({"job": 1, "running": true, "exporting": true, "requested": 0, "album": "Trip"})));
// while the export writes: other imports and exports are refused, naming it
let e = import_job(&runner, &imports, paths.clone(), "", false, None).unwrap_err();
assert!(e.contains("An export is about to add its files to Apple Photos (import 1)"), "{e}");
assert!(imports.reserve(runner.clone(), "").err().unwrap().contains("(import 1)"));
assert!(calls.lock().unwrap().is_empty());
// the export hands over its files: they are imported under its job
let out = reserved.run(&[json!({"path": paths[0]})], false);
assert_eq!((out["job"].as_u64(), out["imported"].as_u64(), out.get("exporting")), (Some(1), Some(1), None), "{out}");
// an export that fails or never runs (its reservation dropped) frees the slot
let dropped = imports.reserve(runner.clone(), "").unwrap();
let id = dropped.job().unwrap().id;
drop(dropped);
let j = imports.get(id).unwrap();
assert!(j.finished() && !j.take_announcement(), "skipped quietly");
assert!(j.json()["skipped"].as_str().unwrap().contains("ended before writing"));
// a file the export reported but that is gone: Photos isn't asked, the slot is freed
let out = imports.reserve(runner.clone(), "").unwrap().run(&[json!({"path": format!("{}/gone.jpg", dir.display())})], false);
assert!(out["error"].as_str().unwrap().contains("no such file"), "{out}");
assert_eq!(calls.lock().unwrap().len(), 1);
assert!(imports.running().is_none());
assert_eq!(import_job(&runner, &imports, paths, "", false, None).unwrap().id, 4);
let _ = std::fs::remove_dir_all(dir);
}
/// Review of #236: a runner that panics, here or on a worker, ends its import as failed and
/// frees the slot; it never stays "running", refusing every later import.
#[test]
fn a_panicking_runner_frees_the_slot() {
let (dir, paths) = files("panic", 1);
let panicky: Runner = Arc::new(|_: &[String], _| panic!("runner exploded"));
let (good, _) = fake(ok("A\n"));
let imports = Imports::default();
let stopped = |j: &ImportJob| j.json()["error"].as_str().is_some_and(|e| e.contains("stopped unexpectedly"));
// waiting here
let job = import_job(&panicky, &imports, paths.clone(), "", false, None).unwrap();
assert!(job.finished() && stopped(&job), "{}", job.json());
assert!(imports.running().is_none());
// on a worker
let job = import_job(&panicky, &imports, paths.clone(), "", true, None).unwrap();
let t0 = std::time::Instant::now();
while !job.finished() {
assert!(t0.elapsed() < Duration::from_secs(20));
std::thread::sleep(Duration::from_millis(5));
}
assert!(stopped(&job), "{}", job.json());
// an export's reservation, waiting and not
let out = imports.reserve(panicky.clone(), "").unwrap().run(&[json!({"path": paths[0]})], false);
assert!(out["error"].as_str().unwrap().contains("stopped unexpectedly"), "{out}");
assert!(imports.running().is_none());
let started = imports.reserve(panicky, "").unwrap().start(&[json!({"path": paths[0]})]);
let job = imports.get(started["job"].as_u64().unwrap()).unwrap();
while !job.finished() {
assert!(t0.elapsed() < Duration::from_secs(20));
std::thread::sleep(Duration::from_millis(5));
}
assert!(stopped(&job));
// the slot is free: the next import runs
assert_eq!(import_job(&good, &imports, paths, "", false, None).unwrap().json()["imported"], 1);
let _ = std::fs::remove_dir_all(dir);
}
/// A process about to end waits for an import still running, so it never abandons osascript.
#[test]
fn waiting_for_idle_outlasts_a_running_import() {
let (dir, paths) = files("idle", 1);
let (runner, go) = delayed();
let imports = Imports::default();
let job = import_job(&runner, &imports, paths, "", true, None).unwrap();
assert!(!job.finished());
let release = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(200));
go.send(()).unwrap();
});
imports.wait_idle();
assert!(job.finished() && imports.running().is_none());
release.join().unwrap();
// nothing running: returns at once
imports.wait_idle();
let _ = std::fs::remove_dir_all(dir);
}
/// Review of #236: shutdown while an export is still writing the files it reserved the import
/// for. The deadline follows the job: the write allowance while the export writes, then the
/// import's own time limit from when Photos was asked, not one deadline fixed at the start
/// (which gave up with the import still inside its limit). Scaled down: 300 ms of writing,
/// imports limited to 1.5 s (+ 0.1 s).
#[test]
fn shutdown_follows_an_export_into_its_import() {
let (dir, paths) = files("shutdown", 2);
let limits = WaitLimits {
writing: Duration::from_millis(300),
import: |_| Duration::from_millis(1500),
margin: Duration::from_millis(100),
cap: Duration::from_secs(20),
};
let taking = |ms: u64| -> Runner {
Arc::new(move |args: &[String], _| {
std::thread::sleep(Duration::from_millis(ms));
let n = args.len() - args.iter().position(|a| a == MARKER).unwrap() - 2;
Ok(Output { status: Some(0), stdout: "ID\n".repeat(n), stderr: String::new() })
})
};
let imports = Imports::default();
// the export is still writing when the wait begins; Photos then takes 1 s, past the write
// allowance but inside the import's own limit
let reserved = imports.reserve(taking(1000), "").unwrap();
let written: Vec<Value> = paths.iter().map(|p| json!({"path": p})).collect();
let exporter = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(150));
reserved.run(&written, false)
});
let t0 = std::time::Instant::now();
assert!(imports.wait_idle_within(limits), "waited for the import, not just the write allowance");
assert!(t0.elapsed() >= Duration::from_millis(1000), "{:?}", t0.elapsed());
assert_eq!(exporter.join().unwrap()["imported"], 2);
// an import past its own limit is given up on at its deadline (not the cap)
let job = import_job(&taking(3000), &imports, paths.clone(), "", true, None).unwrap();
let t0 = std::time::Instant::now();
assert!(!imports.wait_idle_within(limits));
let waited = t0.elapsed();
assert!(waited >= Duration::from_millis(1500) && waited < Duration::from_millis(2900), "{waited:?}");
while !job.finished() {
std::thread::sleep(Duration::from_millis(20));
}
// an export that never hands its files over: the write allowance, then it's left
let held = imports.reserve(taking(0), "").unwrap();
let t0 = std::time::Instant::now();
assert!(!imports.wait_idle_within(limits));
let waited = t0.elapsed();
assert!(waited >= Duration::from_millis(300) && waited < Duration::from_millis(1500), "{waited:?}");
drop(held);
assert!(imports.wait_idle_within(limits));
// and the cap holds over everything
let job = import_job(&taking(1000), &imports, paths, "", true, None).unwrap();
let t0 = std::time::Instant::now();
assert!(!imports.wait_idle_within(WaitLimits { cap: Duration::from_millis(200), ..limits }));
assert!(t0.elapsed() < Duration::from_millis(900));
while !job.finished() {
std::thread::sleep(Duration::from_millis(20));
}
let _ = std::fs::remove_dir_all(dir);
}
/// A runner that waits for `go` (at most 20 s, so a regression fails instead of hanging), then
/// answers one id per file.
fn delayed() -> (Runner, std::sync::mpsc::Sender<()>) {
let (go, wait) = std::sync::mpsc::channel::<()>();
let wait = Mutex::new(wait);
let r: Runner = Arc::new(move |args: &[String], _| {
let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(20));
let files = args.len() - args.iter().position(|a| a == MARKER).unwrap() - 2;
Ok(Output { status: Some(0), stdout: (0..files).map(|i| format!("ID-{i}\n")).collect(), stderr: String::new() })
});
(r, go)
}
/// Imports run as jobs: in the background the caller gets the job at once and its outcome
/// later; while one runs a second is refused (a retry must not add the files twice).
#[test]
fn a_slow_import_runs_as_a_job_and_refuses_a_second_one() {
let (dir, paths) = files("job", 2);
let (runner, go) = delayed();
let imports = Imports::default();
let t0 = std::time::Instant::now();
let job = import_job(&runner, &imports, paths.clone(), " Trip ", true, None).unwrap();
assert!(t0.elapsed() < Duration::from_secs(5), "the caller doesn't wait for Photos");
assert_eq!(job.json(), json!({"job": 1, "running": true, "requested": 2, "album": "Trip"}));
assert_eq!(imports.running().map(|j| j.id), Some(1));
let e = import_job(&runner, &imports, paths.clone(), "", true, None).unwrap_err();
assert!(e.contains("still adding 2 file(s) from an earlier request (import 1)"), "{e}");
let e = imports.reserve(runner.clone(), "").err().unwrap();
assert!(e.contains("still adding"), "{e}");
go.send(()).unwrap();
while !job.finished() {
assert!(t0.elapsed() < Duration::from_secs(20), "the job finishes");
std::thread::sleep(Duration::from_millis(5));
}
assert!(job.take_announcement() && !job.take_announcement(), "announced once");
let done = imports.get(1).unwrap().json();
assert_eq!((done["running"].as_bool(), done["imported"].as_u64(), done["album"].as_str()), (Some(false), Some(2), Some("Trip")), "{done}");
// finished: the next one may start; a failed one says why
let (fails, _) = fake(Err(RunError::Spawn("denied".into())));
let job = import_job(&fails, &imports, paths, "", false, None).unwrap();
assert_eq!(job.id, 2);
assert!(job.json()["error"].as_str().unwrap().contains("denied"));
assert!(imports.running().is_none() && imports.latest().is_some_and(|j| j.id == 2));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_session_remembers_its_last_imports() {
let (dir, paths) = files("kept", 1);
let (runner, _) = fake(ok("A\n"));
let imports = Imports::default();
for _ in 0..KEPT_JOBS + 3 {
import_job(&runner, &imports, paths.clone(), "", false, None).unwrap();
}
let all = imports.all();
assert_eq!(all.len(), KEPT_JOBS);
assert_eq!((all[0].id, all[KEPT_JOBS - 1].id), (4, KEPT_JOBS as u64 + 3));
assert!(imports.get(1).is_none());
let _ = std::fs::remove_dir_all(dir);
}
/// The activity stack (issue #345): an import of its own shows a row while Photos works (no ✕,
/// no count, the album as detail) and loses it when Photos is done; an export's own import
/// shows none of its own, the export's row covers it.
#[test]
fn imports_of_their_own_show_in_the_activity_stack() {
let (dir, paths) = files("activity", 2);
let activity = Activity::default();
let seen = Arc::new(Mutex::new(Vec::new()));
// Photos answers when the test lets it (`go`), so no assertion races the import's end
let (go, wait) = std::sync::mpsc::channel::<()>();
let wait = Mutex::new(wait);
let (a, rows) = (activity.clone(), seen.clone());
let runner: Runner = Arc::new(move |args: &[String], _| {
rows.lock().unwrap().push(a.list());
let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(20));
let n = args.len() - args.iter().position(|x| x == MARKER).unwrap() - 2;
Ok(Output { status: Some(0), stdout: "ID\n".repeat(n), stderr: String::new() })
});
let imports = Imports::default();
let ended = |job: &ImportJob| {
let deadline = std::time::Instant::now() + Duration::from_secs(20);
while !(job.finished() && activity.list().is_empty()) {
assert!(std::time::Instant::now() < deadline, "the import ends and its row goes");
std::thread::sleep(Duration::from_millis(5));
}
};
// waiting for Photos here
go.send(()).unwrap();
let job = import_job(&runner, &imports, paths.clone(), "Trip", false, Some(&activity)).unwrap();
assert_eq!(job.json()["imported"], 2);
assert!(activity.list().is_empty(), "the row goes when Photos is done");
let during = seen.lock().unwrap().last().cloned().unwrap();
assert_eq!(during.len(), 1, "{during:?}");
assert_eq!((during[0].kind, during[0].label.as_str(), during[0].detail.as_str()), (ACTIVITY_KIND, ACTIVITY_LABEL, "Trip"));
assert_eq!((during[0].cancellable, during[0].total), (false, 0), "no ✕ and no count");
// on a worker thread: the row stays while Photos works, and goes once the import ends
let job = import_job(&runner, &imports, paths.clone(), "", true, Some(&activity)).unwrap();
assert_eq!(activity.list().first().map(|r| r.kind), Some(ACTIVITY_KIND));
go.send(()).unwrap();
ended(&job);
// an export's own import: the export's row covers it
let exported: Vec<Value> = paths.iter().map(|p| json!({"path": p})).collect();
go.send(()).unwrap();
imports.reserve(runner.clone(), "").unwrap().shown_in(activity.clone()).run(&exported, false);
assert!(seen.lock().unwrap().last().unwrap().is_empty(), "no row of its own while the export's worker waits");
// ...unless it is left running on its own once the export is done
let started = imports.reserve(runner.clone(), "").unwrap().shown_in(activity.clone()).start(&exported);
assert_eq!(started["running"], true);
assert_eq!(activity.list().first().map(|r| r.kind), Some(ACTIVITY_KIND));
go.send(()).unwrap();
let job = imports.get(started["job"].as_u64().unwrap()).unwrap();
ended(&job);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn timeouts_grow_with_the_batch_and_stay_bounded() {
assert_eq!(timeout_for(1), Duration::from_secs(605));
assert_eq!(timeout_for(100), Duration::from_secs(1100));
assert_eq!(timeout_for(usize::MAX), Duration::from_secs(7200));
}
}
mod tests;
+521
View File
@@ -0,0 +1,521 @@
use super::*;
/// A runner that records the arguments it got and answers `answer`.
fn fake(answer: Result<Output, RunError>) -> (Runner, Arc<Mutex<Vec<Vec<String>>>>) {
let calls = Arc::new(Mutex::new(Vec::new()));
let c = calls.clone();
let r: Runner = Arc::new(move |args: &[String], _| {
c.lock().unwrap().push(args.to_vec());
answer.clone()
});
(r, calls)
}
fn ok(stdout: &str) -> Result<Output, RunError> {
Ok(Output { status: Some(0), stdout: stdout.into(), stderr: String::new() })
}
fn failed(stderr: &str) -> Output {
Output { status: Some(1), stdout: String::new(), stderr: stderr.into() }
}
/// The script part of an argument list: everything before the marker.
fn script_of(args: &[String]) -> &[String] {
let at = args.iter().position(|a| a == MARKER).unwrap();
&args[..at]
}
#[test]
fn names_and_paths_are_arguments_never_script() {
let hostile = [
"",
"Holiday \"2026\"",
"back\\slash\\",
"line\nbreak\r\nand\ttab",
"end tell\ndo shell script \"rm -rf ~\"",
"-e",
"--help",
"日本の写真 📷 Ünïcödé",
"'single' & \"double\" » «",
];
let base = osascript_args("", &["/tmp/a.jpg".into()]);
for album in hostile {
let paths = vec!["/tmp/with \"quotes\".jpg".to_string(), "/tmp/new\nline/é\\x.jpg".to_string(), format!("/tmp/-{album}.jpg")];
let args = osascript_args(album, &paths);
// the script is the same whatever the input…
assert_eq!(script_of(&args), script_of(&base));
assert!(script_of(&args).chunks(2).all(|c| c[0] == "-e" && SCRIPT.lines().any(|l| l == c[1])));
// …and the input follows the marker as whole arguments, unchanged
let at = args.iter().position(|a| a == MARKER).unwrap();
assert_eq!(&args[at + 1], album);
assert_eq!(&args[at + 2..], &paths[..]);
}
// the script reads them from argv only
assert!(SCRIPT.starts_with("on run argv") && SCRIPT.contains("item 2 of argv") && SCRIPT.contains("item i of argv"));
assert!(!SCRIPT.contains("do shell script"));
// it imports into the album (made when missing) without skipping Photos' duplicate check
assert!(SCRIPT.contains("make new album named albumName"));
assert!(SCRIPT.contains("import mediaFiles into targetAlbum skip check duplicates false"));
}
/// Photos' `album` elements are every album, those in folders too, in no set order: the script
/// keeps the top-level ones of exactly that name and refuses when there are several.
#[test]
fn the_album_is_a_single_top_level_one() {
let lookup = SCRIPT.find("every album whose name is albumName").unwrap();
let choose = SCRIPT.find("set targetAlbum to item 1 of topLevel").unwrap();
let make = SCRIPT.find("make new album named albumName").unwrap();
let import = SCRIPT.find("import mediaFiles into targetAlbum").unwrap();
assert!(lookup < choose && choose < make && make < import);
let filter = &SCRIPT[lookup..choose];
assert!(filter.contains("parent of candidate") && filter.contains("candidateParent is missing value"), "{filter}");
assert!(filter.contains("considering case"), "exact names: {filter}");
assert!(filter.contains(&format!(
"if (count of topLevel) > 1 then error \"LightCraft: several top-level albums have this name\" number {AMBIGUOUS_ALBUM}"
)));
let m = explain(&failed(&format!("execution error: LightCraft: several top-level albums have this name ({AMBIGUOUS_ALBUM})")), "Trip");
assert!(m.contains("More than one album at the top level of Photos is named “Trip”") && m.contains("nothing was added"), "{m}");
}
#[test]
fn ids_are_one_per_line() {
assert_eq!(parse_ids("A1B2/L0/001\nC3D4/L0/001\n"), vec!["A1B2/L0/001", "C3D4/L0/001"]);
assert_eq!(parse_ids(" X/L0/001 \r\n\r\n Y/L0/001"), vec!["X/L0/001", "Y/L0/001"]);
assert!(parse_ids("").is_empty() && parse_ids("\n \n").is_empty());
}
#[test]
fn errors_say_what_to_do() {
let says = |stderr: &str, part: &str| {
let m = explain(&failed(stderr), "Trip");
assert!(m.contains(part), "{stderr:?}: {m}");
};
says("146:180: execution error: Not authorized to send Apple events to Photos. (-1743)", "System Settings › Privacy & Security › Automation");
says("execution error: Photos got an error: … (-1744)", "Automation");
says("execution error: Can’t get application \"Photos\". (-10814)", "couldn't be found");
says("execution error: Photos got an error: Application isn’t running. (-600)", "couldn't be found or opened");
says("execution error: User canceled. (-128)", "cancelled");
says("execution error: Photos got an error: AppleEvent timed out. (-1712)", "didn't answer in time");
says("execution error: File not found (-43)", "couldn't find a file");
says("execution error: Photos got an error: Something odd happened. (-2700)", "Something odd happened");
assert!(explain(&Output { status: Some(3), ..Default::default() }, "").contains("exited with 3"));
assert!(explain(&Output { status: None, ..Default::default() }, "").contains("stopped"));
assert!(explain_run_error(&RunError::NoPhotos).contains("couldn't be found"));
assert!(explain_run_error(&RunError::Spawn("denied".into())).contains("denied"));
assert!(explain_run_error(&RunError::Timeout(Duration::from_secs(65))).contains("65 s"));
// a stray parenthesis is not an error number
assert!(explain(&failed("execution error: (not a number)"), "").contains("not a number"));
}
fn files(tag: &str, n: usize) -> (std::path::PathBuf, Vec<String>) {
let dir = std::env::temp_dir().join(format!("lc-photos-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let paths = (0..n)
.map(|i| {
let p = dir.join(format!("photo {i} é.jpg"));
std::fs::write(&p, b"jpeg").unwrap();
p.to_string_lossy().to_string()
})
.collect();
(dir, paths)
}
#[test]
fn an_import_passes_the_files_and_returns_the_ids() {
let (dir, paths) = files("import", 2);
let (runner, calls) = fake(ok("ID-1/L0/001\nID-2/L0/001\n"));
let got = import(&runner, &paths, " Trip “2026” ").unwrap();
assert_eq!(got, Imported { ids: vec!["ID-1/L0/001".into(), "ID-2/L0/001".into()], requested: 2, album: Some("Trip “2026”".into()) });
assert_eq!(got.warning(), None);
let args = calls.lock().unwrap()[0].clone();
let at = args.iter().position(|a| a == MARKER).unwrap();
assert_eq!(&args[at + 1..], &[vec!["Trip “2026”".to_string()], paths.clone()].concat()[..]);
// fewer back than asked: a partial import, said so
let (runner, _) = fake(ok("ID-1/L0/001\n"));
let got = import(&runner, &paths, "").unwrap();
assert_eq!((got.ids.len(), got.album.clone()), (1, None));
assert!(got.warning().unwrap().contains("1 of 2"));
assert_eq!(got.to_json()["warning"], json!(got.warning().unwrap()));
// a failed run is the mapped message
let (runner, _) = fake(Ok(failed("execution error: Not authorized to send Apple events to Photos. (-1743)")));
assert!(import(&runner, &paths, "x").unwrap_err().contains("Automation"));
// a timeout names the request's limit
let (runner, _) = fake(Err(RunError::Timeout(Duration::from_secs(70))));
assert!(import(&runner, &paths, "x").unwrap_err().contains(&format!("{} s", timeout_for(2).as_secs())));
let _ = std::fs::remove_dir_all(dir);
}
/// Codex review of #643: every path was an argument of one osascript run, so a big export
/// (10,000 files) went over macOS's 1 MiB argument limit and Photos got nothing.
#[test]
fn big_imports_run_in_batches_within_the_argument_limit() {
let long = format!("/{}", "d/".repeat(500)); // about 1,000 bytes, near the longest path macOS opens
let paths: Vec<String> = (0..10_000).map(|i| format!("{long}{i:05}.jpg")).collect();
let runs = Arc::new(Mutex::new(Vec::<(usize, usize, Duration)>::new()));
let r = runs.clone();
let runner: Runner = Arc::new(move |args: &[String], limit| {
let files = args.len() - args.iter().position(|a| a == MARKER).unwrap() - 2;
r.lock().unwrap().push((files, args.iter().map(|a| a.len() + 1).sum(), limit));
Ok(Output { status: Some(0), stdout: (0..files).map(|i| format!("ID-{i}\n")).collect(), stderr: String::new() })
});
let got = execute(&runner, &paths, "Big").unwrap();
assert_eq!((got.ids.len(), got.requested, got.warning()), (10_000, 10_000, None));
let runs = runs.lock().unwrap().clone();
assert_eq!(runs.len(), 10_000 / BATCH);
assert!(runs.iter().all(|&(files, _, _)| files == BATCH));
let biggest = runs.iter().map(|&(_, bytes, _)| bytes).max().unwrap();
assert!(biggest < 1 << 18, "{biggest} bytes of arguments in one run");
// every run gets what is left of the request's limit, never more
assert!(runs.iter().all(|&(_, _, limit)| limit <= timeout_for(10_000)));
// a later batch failing: the error says how far Photos got
let calls = Arc::new(Mutex::new(0));
let c = calls.clone();
let runner: Runner = Arc::new(move |args: &[String], _| {
let mut n = c.lock().unwrap();
*n += 1;
let files = args.len() - args.iter().position(|a| a == MARKER).unwrap() - 2;
if *n == 2 {
return Ok(failed("execution error: Photos got an error: User canceled. (-128)"));
}
Ok(Output { status: Some(0), stdout: (0..files).map(|i| format!("ID-{i}\n")).collect(), stderr: String::new() })
});
let e = execute(&runner, &paths[..450], "Big").unwrap_err();
assert!(e.contains("cancelled") && e.contains("200 of the 450 files"), "{e}");
assert_eq!(*calls.lock().unwrap(), 2, "nothing more is sent after a failed batch");
// the batches share the request's one deadline: time a batch takes comes off the next one's
let limits = Arc::new(Mutex::new(Vec::<Duration>::new()));
let l = limits.clone();
let runner: Runner = Arc::new(move |args: &[String], limit| {
l.lock().unwrap().push(limit);
std::thread::sleep(Duration::from_millis(300));
let files = args.len() - args.iter().position(|a| a == MARKER).unwrap() - 2;
Ok(Output { status: Some(0), stdout: (0..files).map(|i| format!("ID-{i}\n")).collect(), stderr: String::new() })
});
execute(&runner, &paths[..450], "Big").unwrap();
let limits = limits.lock().unwrap().clone();
assert_eq!(limits.len(), 3);
let whole = timeout_for(450);
assert!(limits[0] <= whole && limits[0] > whole - Duration::from_millis(250), "{limits:?}");
assert!(limits[1] <= whole - Duration::from_millis(300) && limits[2] <= whole - Duration::from_millis(600), "{limits:?}");
}
#[test]
fn bad_requests_never_reach_osascript() {
let (dir, paths) = files("bad", 1);
let (runner, calls) = fake(ok(""));
assert!(import(&runner, &[], "").unwrap_err().contains("no files"));
assert!(import(&runner, &["relative/a.jpg".into()], "").unwrap_err().contains("absolute"));
assert!(import(&runner, &[format!("{}/missing.jpg", dir.display())], "").unwrap_err().contains("no such file"));
assert!(import(&runner, &[format!("{}/a\0b.jpg", dir.display())], "").unwrap_err().contains("NUL"));
assert!(import(&runner, &paths, "a\0b").unwrap_err().contains("NUL"));
assert!(calls.lock().unwrap().is_empty());
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn after_an_export_the_written_files_are_added() {
let (dir, paths) = files("after", 2);
let exported = vec![
json!({"path": paths[0], "width": 10}),
json!({"skipped": "/elsewhere/x.jpg"}),
json!({"photo": 3, "error": "x"}),
json!({"path": paths[1]}),
];
let (runner, calls) = fake(ok("A/L0/001\nB/L0/001"));
let imports = Imports::default();
let out = imports.reserve(runner.clone(), " Album ").unwrap().run(&exported, false);
assert_eq!(out["imported"], 2);
assert_eq!(out["album"], "Album");
assert_eq!((out["job"].as_u64(), out["running"].as_bool()), (Some(1), Some(false)));
let args = calls.lock().unwrap()[0].clone();
assert_eq!(&args[args.len() - 2..], &paths[..], "only the files written, in order");
// nothing written, or cancelled: Photos isn't asked, and the slot is free again
let out = imports.reserve(runner.clone(), "").unwrap().run(&[json!({"skipped": "x"})], false);
assert!(out["skipped"].as_str().unwrap().contains("wrote no files"), "{out}");
assert_eq!(out.get("cancelled"), None, "{out}");
let out = imports.reserve(runner.clone(), "").unwrap().run(&exported, true);
assert!(out["skipped"].as_str().unwrap().contains("cancelled"), "{out}");
assert_eq!(out["cancelled"], true, "the app decides on the flag, not on the words: {out}");
assert_eq!(calls.lock().unwrap().len(), 1);
assert!(imports.running().is_none());
let _ = std::fs::remove_dir_all(dir);
}
/// An export that will add its files reserves the slot before writing them: a competing
/// import is refused, naming the export's job, and the export is never turned away after
/// writing. Every way the export can end frees the slot.
#[test]
fn an_export_reserves_the_import_before_writing() {
let (dir, paths) = files("reserve", 1);
let (runner, calls) = fake(ok("A\n"));
let imports = Imports::default();
let reserved = imports.reserve(runner.clone(), "Trip").unwrap();
assert_eq!(reserved.job().map(|j| j.json()), Some(json!({"job": 1, "running": true, "exporting": true, "requested": 0, "album": "Trip"})));
// while the export writes: other imports and exports are refused, naming it
let e = import_job(&runner, &imports, paths.clone(), "", false, None).unwrap_err();
assert!(e.contains("An export is about to add its files to Apple Photos (import 1)"), "{e}");
assert!(imports.reserve(runner.clone(), "").err().unwrap().contains("(import 1)"));
assert!(calls.lock().unwrap().is_empty());
// the export hands over its files: they are imported under its job
let out = reserved.run(&[json!({"path": paths[0]})], false);
assert_eq!((out["job"].as_u64(), out["imported"].as_u64(), out.get("exporting")), (Some(1), Some(1), None), "{out}");
// an export that fails or never runs (its reservation dropped) frees the slot
let dropped = imports.reserve(runner.clone(), "").unwrap();
let id = dropped.job().unwrap().id;
drop(dropped);
let j = imports.get(id).unwrap();
assert!(j.finished() && !j.take_announcement(), "skipped quietly");
assert!(j.json()["skipped"].as_str().unwrap().contains("ended before writing"));
// a file the export reported but that is gone: Photos isn't asked, the slot is freed
let out = imports.reserve(runner.clone(), "").unwrap().run(&[json!({"path": format!("{}/gone.jpg", dir.display())})], false);
assert!(out["error"].as_str().unwrap().contains("no such file"), "{out}");
assert_eq!(calls.lock().unwrap().len(), 1);
assert!(imports.running().is_none());
assert_eq!(import_job(&runner, &imports, paths, "", false, None).unwrap().id, 4);
let _ = std::fs::remove_dir_all(dir);
}
/// Review of #236: a runner that panics, here or on a worker, ends its import as failed and
/// frees the slot; it never stays "running", refusing every later import.
#[test]
fn a_panicking_runner_frees_the_slot() {
let (dir, paths) = files("panic", 1);
let panicky: Runner = Arc::new(|_: &[String], _| panic!("runner exploded"));
let (good, _) = fake(ok("A\n"));
let imports = Imports::default();
let stopped = |j: &ImportJob| j.json()["error"].as_str().is_some_and(|e| e.contains("stopped unexpectedly"));
// waiting here
let job = import_job(&panicky, &imports, paths.clone(), "", false, None).unwrap();
assert!(job.finished() && stopped(&job), "{}", job.json());
assert!(imports.running().is_none());
// on a worker
let job = import_job(&panicky, &imports, paths.clone(), "", true, None).unwrap();
let t0 = std::time::Instant::now();
while !job.finished() {
assert!(t0.elapsed() < Duration::from_secs(20));
std::thread::sleep(Duration::from_millis(5));
}
assert!(stopped(&job), "{}", job.json());
// an export's reservation, waiting and not
let out = imports.reserve(panicky.clone(), "").unwrap().run(&[json!({"path": paths[0]})], false);
assert!(out["error"].as_str().unwrap().contains("stopped unexpectedly"), "{out}");
assert!(imports.running().is_none());
let started = imports.reserve(panicky, "").unwrap().start(&[json!({"path": paths[0]})]);
let job = imports.get(started["job"].as_u64().unwrap()).unwrap();
while !job.finished() {
assert!(t0.elapsed() < Duration::from_secs(20));
std::thread::sleep(Duration::from_millis(5));
}
assert!(stopped(&job));
// the slot is free: the next import runs
assert_eq!(import_job(&good, &imports, paths, "", false, None).unwrap().json()["imported"], 1);
let _ = std::fs::remove_dir_all(dir);
}
/// A process about to end waits for an import still running, so it never abandons osascript.
#[test]
fn waiting_for_idle_outlasts_a_running_import() {
let (dir, paths) = files("idle", 1);
let (runner, go) = delayed();
let imports = Imports::default();
let job = import_job(&runner, &imports, paths, "", true, None).unwrap();
assert!(!job.finished());
let release = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(200));
go.send(()).unwrap();
});
imports.wait_idle();
assert!(job.finished() && imports.running().is_none());
release.join().unwrap();
// nothing running: returns at once
imports.wait_idle();
let _ = std::fs::remove_dir_all(dir);
}
/// Review of #236: shutdown while an export is still writing the files it reserved the import
/// for. The deadline follows the job: the write allowance while the export writes, then the
/// import's own time limit from when Photos was asked, not one deadline fixed at the start
/// (which gave up with the import still inside its limit). Scaled down: 300 ms of writing,
/// imports limited to 1.5 s (+ 0.1 s).
#[test]
fn shutdown_follows_an_export_into_its_import() {
let (dir, paths) = files("shutdown", 2);
let limits = WaitLimits {
writing: Duration::from_millis(300),
import: |_| Duration::from_millis(1500),
margin: Duration::from_millis(100),
cap: Duration::from_secs(20),
};
let taking = |ms: u64| -> Runner {
Arc::new(move |args: &[String], _| {
std::thread::sleep(Duration::from_millis(ms));
let n = args.len() - args.iter().position(|a| a == MARKER).unwrap() - 2;
Ok(Output { status: Some(0), stdout: "ID\n".repeat(n), stderr: String::new() })
})
};
let imports = Imports::default();
// the export is still writing when the wait begins; Photos then takes 1 s, past the write
// allowance but inside the import's own limit
let reserved = imports.reserve(taking(1000), "").unwrap();
let written: Vec<Value> = paths.iter().map(|p| json!({"path": p})).collect();
let exporter = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(150));
reserved.run(&written, false)
});
let t0 = std::time::Instant::now();
assert!(imports.wait_idle_within(limits), "waited for the import, not just the write allowance");
assert!(t0.elapsed() >= Duration::from_millis(1000), "{:?}", t0.elapsed());
assert_eq!(exporter.join().unwrap()["imported"], 2);
// an import past its own limit is given up on at its deadline (not the cap)
let job = import_job(&taking(3000), &imports, paths.clone(), "", true, None).unwrap();
let t0 = std::time::Instant::now();
assert!(!imports.wait_idle_within(limits));
let waited = t0.elapsed();
assert!(waited >= Duration::from_millis(1500) && waited < Duration::from_millis(2900), "{waited:?}");
while !job.finished() {
std::thread::sleep(Duration::from_millis(20));
}
// an export that never hands its files over: the write allowance, then it's left
let held = imports.reserve(taking(0), "").unwrap();
let t0 = std::time::Instant::now();
assert!(!imports.wait_idle_within(limits));
let waited = t0.elapsed();
assert!(waited >= Duration::from_millis(300) && waited < Duration::from_millis(1500), "{waited:?}");
drop(held);
assert!(imports.wait_idle_within(limits));
// and the cap holds over everything
let job = import_job(&taking(1000), &imports, paths, "", true, None).unwrap();
let t0 = std::time::Instant::now();
assert!(!imports.wait_idle_within(WaitLimits { cap: Duration::from_millis(200), ..limits }));
assert!(t0.elapsed() < Duration::from_millis(900));
while !job.finished() {
std::thread::sleep(Duration::from_millis(20));
}
let _ = std::fs::remove_dir_all(dir);
}
/// A runner that waits for `go` (at most 20 s, so a regression fails instead of hanging), then
/// answers one id per file.
fn delayed() -> (Runner, std::sync::mpsc::Sender<()>) {
let (go, wait) = std::sync::mpsc::channel::<()>();
let wait = Mutex::new(wait);
let r: Runner = Arc::new(move |args: &[String], _| {
let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(20));
let files = args.len() - args.iter().position(|a| a == MARKER).unwrap() - 2;
Ok(Output { status: Some(0), stdout: (0..files).map(|i| format!("ID-{i}\n")).collect(), stderr: String::new() })
});
(r, go)
}
/// Imports run as jobs: in the background the caller gets the job at once and its outcome
/// later; while one runs a second is refused (a retry must not add the files twice).
#[test]
fn a_slow_import_runs_as_a_job_and_refuses_a_second_one() {
let (dir, paths) = files("job", 2);
let (runner, go) = delayed();
let imports = Imports::default();
let t0 = std::time::Instant::now();
let job = import_job(&runner, &imports, paths.clone(), " Trip ", true, None).unwrap();
assert!(t0.elapsed() < Duration::from_secs(5), "the caller doesn't wait for Photos");
assert_eq!(job.json(), json!({"job": 1, "running": true, "requested": 2, "album": "Trip"}));
assert_eq!(imports.running().map(|j| j.id), Some(1));
let e = import_job(&runner, &imports, paths.clone(), "", true, None).unwrap_err();
assert!(e.contains("still adding 2 file(s) from an earlier request (import 1)"), "{e}");
let e = imports.reserve(runner.clone(), "").err().unwrap();
assert!(e.contains("still adding"), "{e}");
go.send(()).unwrap();
while !job.finished() {
assert!(t0.elapsed() < Duration::from_secs(20), "the job finishes");
std::thread::sleep(Duration::from_millis(5));
}
assert!(job.take_announcement() && !job.take_announcement(), "announced once");
let done = imports.get(1).unwrap().json();
assert_eq!((done["running"].as_bool(), done["imported"].as_u64(), done["album"].as_str()), (Some(false), Some(2), Some("Trip")), "{done}");
// finished: the next one may start; a failed one says why
let (fails, _) = fake(Err(RunError::Spawn("denied".into())));
let job = import_job(&fails, &imports, paths, "", false, None).unwrap();
assert_eq!(job.id, 2);
assert!(job.json()["error"].as_str().unwrap().contains("denied"));
assert!(imports.running().is_none() && imports.latest().is_some_and(|j| j.id == 2));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_session_remembers_its_last_imports() {
let (dir, paths) = files("kept", 1);
let (runner, _) = fake(ok("A\n"));
let imports = Imports::default();
for _ in 0..KEPT_JOBS + 3 {
import_job(&runner, &imports, paths.clone(), "", false, None).unwrap();
}
let all = imports.all();
assert_eq!(all.len(), KEPT_JOBS);
assert_eq!((all[0].id, all[KEPT_JOBS - 1].id), (4, KEPT_JOBS as u64 + 3));
assert!(imports.get(1).is_none());
let _ = std::fs::remove_dir_all(dir);
}
/// The activity stack (issue #345): an import of its own shows a row while Photos works (no ✕,
/// no count, the album as detail) and loses it when Photos is done; an export's own import
/// shows none of its own, the export's row covers it.
#[test]
fn imports_of_their_own_show_in_the_activity_stack() {
let (dir, paths) = files("activity", 2);
let activity = Activity::default();
let seen = Arc::new(Mutex::new(Vec::new()));
// Photos answers when the test lets it (`go`), so no assertion races the import's end
let (go, wait) = std::sync::mpsc::channel::<()>();
let wait = Mutex::new(wait);
let (a, rows) = (activity.clone(), seen.clone());
let runner: Runner = Arc::new(move |args: &[String], _| {
rows.lock().unwrap().push(a.list());
let _ = wait.lock().unwrap().recv_timeout(Duration::from_secs(20));
let n = args.len() - args.iter().position(|x| x == MARKER).unwrap() - 2;
Ok(Output { status: Some(0), stdout: "ID\n".repeat(n), stderr: String::new() })
});
let imports = Imports::default();
let ended = |job: &ImportJob| {
let deadline = std::time::Instant::now() + Duration::from_secs(20);
while !(job.finished() && activity.list().is_empty()) {
assert!(std::time::Instant::now() < deadline, "the import ends and its row goes");
std::thread::sleep(Duration::from_millis(5));
}
};
// waiting for Photos here
go.send(()).unwrap();
let job = import_job(&runner, &imports, paths.clone(), "Trip", false, Some(&activity)).unwrap();
assert_eq!(job.json()["imported"], 2);
assert!(activity.list().is_empty(), "the row goes when Photos is done");
let during = seen.lock().unwrap().last().cloned().unwrap();
assert_eq!(during.len(), 1, "{during:?}");
assert_eq!((during[0].kind, during[0].label.as_str(), during[0].detail.as_str()), (ACTIVITY_KIND, ACTIVITY_LABEL, "Trip"));
assert_eq!((during[0].cancellable, during[0].total), (false, 0), "no ✕ and no count");
// on a worker thread: the row stays while Photos works, and goes once the import ends
let job = import_job(&runner, &imports, paths.clone(), "", true, Some(&activity)).unwrap();
assert_eq!(activity.list().first().map(|r| r.kind), Some(ACTIVITY_KIND));
go.send(()).unwrap();
ended(&job);
// an export's own import: the export's row covers it
let exported: Vec<Value> = paths.iter().map(|p| json!({"path": p})).collect();
go.send(()).unwrap();
imports.reserve(runner.clone(), "").unwrap().shown_in(activity.clone()).run(&exported, false);
assert!(seen.lock().unwrap().last().unwrap().is_empty(), "no row of its own while the export's worker waits");
// ...unless it is left running on its own once the export is done
let started = imports.reserve(runner.clone(), "").unwrap().shown_in(activity.clone()).start(&exported);
assert_eq!(started["running"], true);
assert_eq!(activity.list().first().map(|r| r.kind), Some(ACTIVITY_KIND));
go.send(()).unwrap();
let job = imports.get(started["job"].as_u64().unwrap()).unwrap();
ended(&job);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn timeouts_grow_with_the_batch_and_stay_bounded() {
assert_eq!(timeout_for(1), Duration::from_secs(605));
assert_eq!(timeout_for(100), Duration::from_secs(1100));
assert_eq!(timeout_for(usize::MAX), Duration::from_secs(7200));
}
+347 -28
View File
@@ -7,6 +7,16 @@
//! there"; the render worker finds out if it isn't), known answers are rechecked after
//! [`RECHECK`]. Everywhere else (CLI, MCP, tests) the default is synchronous: every question is a
//! fresh check, as before.
//!
//! The same worker can check a list of files, such as every library photo's, now and then
//! ([`Availability::sweep`]), one at a time and only while nothing is asked. That is for the
//! Missing Photos count ([`Availability::is_gone`]): one stream of checks on a share, not one per
//! thing that wants to know. The app starts the sweeps; nothing here does.
//!
//! A sweep of a large library on a share takes tens of minutes, and its `stat`s compete with the
//! reads of an import or a scan on the same share. So the worker starts no sweep check while the
//! caller says files are busy ([`Availability::sweep_yields_to`]); what is asked still gets
//! answered (within [`YIELD_POLL`]), and the sweep goes on where it stopped when the work ends.
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
@@ -14,9 +24,16 @@ use std::time::Duration;
/// Checks whether a path exists (injectable: tests use a slow one).
pub type ExistsProbe = Arc<dyn Fn(&str) -> bool + Send + Sync>;
/// Called (from the worker) when an answer changed, e.g. to repaint the UI.
/// Called (from the worker) when an answer changed, e.g. to repaint the UI (a sweep's first look
/// at a file that is there changes no answer anyone sees, so it wakes nobody).
pub type Waker = Arc<dyn Fn() + Send + Sync>;
/// Whether file work that a sweep should not compete with is going on.
pub type Busy = Arc<dyn Fn() -> bool + Send + Sync>;
/// How often a sweep that is giving way looks whether the work has ended.
const YIELD_POLL: Duration = Duration::from_millis(250);
/// How long a cached answer is used before it is checked again (it is still returned meanwhile).
pub const RECHECK: Duration = Duration::from_secs(15);
@@ -31,9 +48,17 @@ struct State {
known: HashMap<String, (bool, std::time::Instant)>,
queue: VecDeque<String>,
queued: HashSet<String>,
/// What a sweep has left to check: after the queue, whatever it holds.
sweep: VecDeque<String>,
/// The files found not there (and not found there since).
gone: HashSet<String>,
worker: bool,
/// Bumped whenever an answer changes (callers recompute what depends on it).
generation: u64,
/// Bumped when the sweep under way is dropped for another one ([`Availability::restart_sweeps`]).
sweep_epoch: u64,
/// Whether file work a sweep gives way to is going on.
busy: Option<Busy>,
/// Bumped whenever a file is found gone, or found back.
gone_generation: u64,
}
fn lock(m: &Mutex<State>) -> MutexGuard<'_, State> {
@@ -66,7 +91,8 @@ impl Availability {
self.probe = probe;
let mut st = lock(&self.state);
st.known.clear();
st.generation += 1;
st.gone.clear();
st.gone_generation += 1;
}
/// Answer from the cache and check on a worker thread from now on; `wake` runs when an
@@ -78,6 +104,14 @@ impl Availability {
self.background = Some(wake);
}
/// The sweep starts no check while `busy` says so (the caller's import, scan or Local read in
/// flight); asked files are answered all the same, and the sweep resumes where it was left when
/// `busy` turns false. `busy` should read state that a task's guard owns (the activity stack), so
/// a task that never ends cleanly can't hold the sweep for good.
pub fn sweep_yields_to(&self, busy: Busy) {
lock(&self.state).busy = Some(busy);
}
/// The existence check itself (blocking: for worker threads, e.g. the Rename preview's).
pub fn probe(&self) -> ExistsProbe {
self.probe.clone()
@@ -99,12 +133,7 @@ impl Availability {
if cached.is_none_or(|(_, at)| now.saturating_duration_since(at) >= RECHECK) && !st.queued.contains(path) {
st.queued.insert(path.to_string());
st.queue.push_back(path.to_string());
if !st.worker {
st.worker = true;
drop(st);
self.spawn_worker(wake.clone());
return cached.map(|c| c.0);
}
self.start(st, wake);
}
cached.map(|c| c.0)
}
@@ -114,9 +143,10 @@ impl Availability {
self.exists(path) == Some(false)
}
/// Changes whenever a cached answer changes.
pub fn generation(&self) -> u64 {
lock(&self.state).generation
/// Changes whenever a file is found gone or found back: what [`Availability::is_offline`]
/// says changed for some file. (A file found there at its first check changes nothing.)
pub fn gone_generation(&self) -> u64 {
lock(&self.state).gone_generation
}
/// Paths waiting for the worker.
@@ -124,37 +154,123 @@ impl Availability {
lock(&self.state).queue.len()
}
/// Check `paths` too, in the background and after whatever is asked meanwhile, skipping those
/// checked less than [`RECHECK`] ago. One sweep at a time: `false` (and nothing queued) while
/// one is under way, or in synchronous mode. A sweep's answers wake only when a file is found
/// gone or back.
pub fn sweep(&self, paths: Vec<String>) -> bool {
self.sweep_checked(None, paths)
}
fn sweep_checked(&self, epoch: Option<u64>, paths: Vec<String>) -> bool {
let Some(wake) = &self.background else { return false };
let mut st = lock(&self.state);
if !st.sweep.is_empty() || epoch.is_some_and(|e| e != st.sweep_epoch) {
return false;
}
st.sweep = paths.into();
self.start(st, wake);
true
}
/// Drop what the sweep under way has left (another library was opened: its files are not the
/// ones to check now) and say which sweeps may start from here ([`Availability::sweep_in`]): a
/// list of files being made for the old one is then refused.
pub fn restart_sweeps(&self) -> u64 {
let mut st = lock(&self.state);
st.sweep.clear();
st.sweep_epoch += 1;
st.sweep_epoch
}
/// [`Availability::sweep`], unless [`Availability::restart_sweeps`] was called since it
/// returned `epoch`.
pub fn sweep_in(&self, epoch: u64, paths: Vec<String>) -> bool {
self.sweep_checked(Some(epoch), paths)
}
/// Whether the file at `path` was found gone (and not found there since): `false` for a file
/// not checked yet.
pub fn is_gone(&self, path: &str) -> bool {
lock(&self.state).gone.contains(path)
}
/// How many files are found gone.
pub fn gone_len(&self) -> usize {
lock(&self.state).gone.len()
}
/// What the sweep under way has left to check (0: none under way, though its last file may still
/// be in flight).
pub fn sweeping(&self) -> usize {
lock(&self.state).sweep.len()
}
/// Start the worker, unless it runs.
fn start(&self, mut st: MutexGuard<'_, State>, wake: &Waker) {
if !st.worker {
st.worker = true;
drop(st);
self.spawn_worker(wake.clone());
}
}
fn spawn_worker(&self, wake: Waker) {
let (state, probe) = (self.state.clone(), self.probe.clone());
let started = std::thread::Builder::new().name("lc-availability".into()).spawn(move || {
loop {
let path = {
// what was asked first; a sweep's next file when nothing is (unless it is asked
// about too, or was checked a moment ago)
let (path, asked) = {
let mut st = lock(&state);
let Some(p) = st.queue.pop_front() else {
st.worker = false;
return;
};
p
let giving_way = if st.queue.is_empty() && !st.sweep.is_empty() { st.busy.clone() } else { None };
if let Some(busy) = giving_way {
drop(st);
if busy() {
// (the worker stays: a question asked meanwhile is answered within YIELD_POLL)
std::thread::sleep(YIELD_POLL);
continue;
}
st = lock(&state);
}
match st.queue.pop_front() {
Some(p) => (p, true),
None => loop {
let Some(p) = st.sweep.pop_front() else {
st.worker = false;
return;
};
let fresh = st.known.get(&p).is_some_and(|(_, at)| at.elapsed() < RECHECK);
if !fresh && !st.queued.contains(&p) {
break (p, false);
}
},
}
};
let ok = probe(&path);
let changed = {
let wakes = {
let mut st = lock(&state);
st.queued.remove(&path);
if asked {
st.queued.remove(&path);
}
let gone_changed = if ok { st.gone.remove(&path) } else { st.gone.insert(path.clone()) };
let prev = st.known.insert(path, (ok, std::time::Instant::now()));
let changed = prev.map(|p| p.0) != Some(ok);
if changed {
st.generation += 1;
if gone_changed {
st.gone_generation += 1;
}
changed
(asked && changed) || gone_changed
};
if changed {
if wakes {
wake();
}
}
});
if started.is_err() {
// try again on the next question
lock(&self.state).worker = false;
// try again on the next question; a sweep nobody works on would refuse every new one
let mut st = lock(&self.state);
st.worker = false;
st.sweep.clear();
}
}
}
@@ -210,6 +326,209 @@ mod tests {
assert!(a.is_offline("gone") && !a.is_offline("here") && !a.is_offline("unknown"));
assert_eq!(on_caller.load(Ordering::SeqCst), 0, "never probed on the calling thread");
assert!(woke.load(Ordering::SeqCst) >= 2);
assert!(a.generation() >= 2);
assert!(a.gone_generation() >= 2);
}
fn wait_until(what: &str, done: impl Fn() -> bool) {
let deadline = std::time::Instant::now() + Duration::from_secs(20);
while !done() {
assert!(std::time::Instant::now() < deadline, "timed out waiting: {what}");
std::thread::sleep(Duration::from_millis(2));
}
}
fn held<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
/// A background `Availability` whose probe logs what it checks; files named `gone…` are not there.
fn logged() -> (Availability, Arc<Mutex<Vec<String>>>, Arc<AtomicUsize>) {
let mut a = Availability::default();
let log = Arc::new(Mutex::new(Vec::new()));
let l = log.clone();
a.set_probe(Arc::new(move |p| {
held(&l).push(p.to_string());
!p.starts_with("gone")
}));
let woke = Arc::new(AtomicUsize::new(0));
let w = woke.clone();
a.run_in_background(Arc::new(move || {
w.fetch_add(1, Ordering::SeqCst);
}));
(a, log, woke)
}
#[test]
fn the_files_a_sweep_finds_gone_are_counted() {
let (a, _, _) = logged();
assert!(a.sweep(vec!["here".into(), "gone 1".into(), "also here".into(), "gone 2".into()]));
wait_until("the sweep", || a.sweeping() == 0 && a.pending() == 0);
wait_until("the answers", || a.gone_len() == 2);
assert!(a.is_gone("gone 1") && a.is_gone("gone 2") && !a.is_gone("here") && !a.is_gone("also here"));
}
#[test]
fn files_found_there_at_first_look_change_nothing_for_missing_photos() {
let (a, _, woke) = logged();
let before = a.gone_generation();
a.sweep(vec!["a".into(), "b".into(), "c".into()]);
wait_until("the answers", || ["a", "b", "c"].iter().all(|p| lock(&a.state).known.contains_key(*p)));
assert_eq!(a.gone_generation(), before, "nothing went missing");
assert_eq!(woke.load(Ordering::SeqCst), 0, "a sweep finding files there wakes nobody");
a.sweep(vec!["gone".into()]);
wait_until("the gone file", || a.gone_generation() != before);
wait_until("the wake", || woke.load(Ordering::SeqCst) == 1);
}
#[test]
fn what_is_asked_is_checked_before_the_rest_of_a_sweep_and_one_sweep_runs_at_a_time() {
let mut a = Availability::default();
let log = Arc::new(Mutex::new(Vec::<String>::new()));
// the first file of the sweep holds the worker until the test has asked about another
let gate = Arc::new((Mutex::new(false), std::sync::Condvar::new()));
let (l, g) = (log.clone(), gate.clone());
a.set_probe(Arc::new(move |p| {
if p == "sweep 0" {
let (open, cv) = &*g;
let mut open = held(open);
while !*open {
open = cv.wait(open).unwrap_or_else(PoisonError::into_inner);
}
}
held(&l).push(p.to_string());
true
}));
a.run_in_background(Arc::new(|| {}));
assert!(a.sweep((0..50).map(|i| format!("sweep {i}")).collect()));
assert!(!a.sweep(vec!["another".into()]), "a sweep under way: the next one waits for its turn");
assert_eq!(a.exists("asked"), None, "not known yet");
*held(&gate.0) = true;
gate.1.notify_all();
wait_until("the log", || held(&log).len() == 51);
let log = held(&log);
// (at most the file the worker was already checking comes first)
assert!(matches!(log.iter().position(|p| p == "asked"), Some(0 | 1)), "asked next, ahead of the sweep: {log:?}");
assert!(!log.iter().any(|p| p == "another"));
}
#[test]
fn a_new_sweep_replaces_the_one_under_way_and_a_list_made_for_the_old_one_is_refused() {
let mut a = Availability::default();
let log = Arc::new(Mutex::new(Vec::<String>::new()));
// the old sweep's first file holds the worker until the new one is in place
let gate = Arc::new((Mutex::new(false), std::sync::Condvar::new()));
let (l, g) = (log.clone(), gate.clone());
a.set_probe(Arc::new(move |p| {
if p == "old 0" {
let (open, cv) = &*g;
let mut open = held(open);
while !*open {
open = cv.wait(open).unwrap_or_else(PoisonError::into_inner);
}
}
held(&l).push(p.to_string());
true
}));
a.run_in_background(Arc::new(|| {}));
let old = a.restart_sweeps();
assert!(a.sweep_in(old, (0..20).map(|i| format!("old {i}")).collect()));
wait_until("the worker takes the first file", || a.sweeping() == 19);
// another library is opened: what is left of the old sweep goes, and a list still being made for it too
let new = a.restart_sweeps();
assert_eq!(a.sweeping(), 0);
assert!(!a.sweep_in(old, vec!["old late".into()]), "a list made for the old library is refused");
assert!(a.sweep_in(new, (0..3).map(|i| format!("new {i}")).collect()));
*held(&gate.0) = true;
gate.1.notify_all();
wait_until("the new sweep", || held(&log).len() == 4);
assert_eq!(*held(&log), ["old 0", "new 0", "new 1", "new 2"]);
}
#[test]
fn files_found_gone_are_told_apart_from_files_never_checked() {
let (a, _, _) = logged();
assert!(!a.is_gone("gone 1") && a.gone_len() == 0);
assert!(a.sweep(vec!["gone 1".into(), "here".into()]));
wait_until("the sweep", || a.sweeping() == 0 && a.pending() == 0 && a.gone_len() == 1);
assert!(a.is_gone("gone 1") && !a.is_gone("here") && !a.is_gone("never asked"));
}
fn busy_flag(a: &Availability) -> Arc<std::sync::atomic::AtomicBool> {
let busy = Arc::new(std::sync::atomic::AtomicBool::new(true));
let b = busy.clone();
a.sweep_yields_to(Arc::new(move || b.load(Ordering::SeqCst)));
busy
}
#[test]
fn a_sweep_gives_way_to_file_work_answers_what_is_asked_and_resumes_after() {
let (a, log, _) = logged();
let busy = busy_flag(&a);
assert!(a.sweep((0..20).map(|i| format!("sweep {i}")).collect()));
std::thread::sleep(YIELD_POLL * 3);
assert!(held(&log).is_empty(), "no sweep check while files are busy");
assert_eq!(a.sweeping(), 20, "nothing of the sweep is lost");
assert_eq!(a.exists("asked"), None);
wait_until("the answer", || a.exists("asked") == Some(true));
assert_eq!(*held(&log), ["asked"], "what is asked is answered, the sweep still waits");
busy.store(false, Ordering::SeqCst);
wait_until("the sweep", || a.sweeping() == 0);
wait_until("the log", || held(&log).len() == 21);
// it went on from its first file, not from scratch
assert_eq!(held(&log).iter().filter(|p| *p == "sweep 0").count(), 1);
}
#[test]
fn a_sweep_stopped_part_way_goes_on_from_there() {
let mut a = Availability::default();
let log = Arc::new(Mutex::new(Vec::<String>::new()));
let l = log.clone();
// the worker is held inside the fourth check until the sweep is told to give way
let hold = Arc::new(std::sync::atomic::AtomicBool::new(true));
let h = hold.clone();
a.set_probe(Arc::new(move |p| {
while p == "sweep 3" && h.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(1));
}
held(&l).push(p.to_string());
true
}));
a.run_in_background(Arc::new(|| {}));
let busy = busy_flag(&a);
busy.store(false, Ordering::SeqCst);
assert!(a.sweep((0..100).map(|i| format!("sweep {i}")).collect()));
wait_until("a few checks", || held(&log).len() >= 3);
busy.store(true, Ordering::SeqCst);
hold.store(false, Ordering::SeqCst);
std::thread::sleep(YIELD_POLL * 2);
let stopped = held(&log).len();
assert_eq!(stopped, 4, "stopped part way, after the check it was in");
std::thread::sleep(YIELD_POLL * 2);
assert_eq!(held(&log).len(), stopped, "paused");
assert_eq!(a.sweeping(), 100 - stopped, "what is left is kept");
busy.store(false, Ordering::SeqCst);
wait_until("the sweep", || a.sweeping() == 0 && held(&log).len() == 100);
let mut all = held(&log).clone();
all.sort();
all.dedup();
assert_eq!(all.len(), 100, "every file checked once, none again from the start");
}
#[test]
fn a_sweep_that_yields_to_nothing_runs_as_before() {
let (a, log, _) = logged();
assert!(a.sweep(vec!["a".into(), "b".into()]));
wait_until("the sweep", || held(&log).len() == 2);
}
#[test]
fn a_sweep_skips_files_checked_a_moment_ago() {
let (a, log, _) = logged();
assert_eq!(a.exists("a"), None);
wait_until("the answer", || a.exists("a").is_some());
a.sweep(vec!["a".into(), "b".into()]);
wait_until("b", || held(&log).iter().any(|p| p == "b"));
wait_until("the sweep", || a.sweeping() == 0);
assert_eq!(held(&log).iter().filter(|p| *p == "a").count(), 1, "`a` was checked a moment ago");
}
}
File diff suppressed because it is too large. Load diff
+232
View File
@@ -0,0 +1,232 @@
use super::look_fit::{fit_dng_tone, fit_preview};
use super::mono::{fit_dark_tone, monochrome_look};
use super::proxy::{LensGeometry, proxies};
use super::{CameraLook, CameraTone, CameraTransform, ColorData, D50, D65, Mat3, ProfileLook, REC2020, RawFormat, RawImage, ToneCurve, Xy, bradford};
/// Long edge of the sensor/JPEG proxy a single photo's look is fitted on (the acceptance gates
/// below were set at this size).
pub(super) const PROXY: usize = 96;
/// Long edge of the proxies pooled for a camera profile: small objects (a shirt) get 4× the samples.
pub(crate) const PROFILE_PROXY: usize = 192;
/// Raw formats whose decoder supplies vendor white-balance multipliers but no camera colour matrix:
/// their starting look is fitted to the file's own JPEG, and white balance is relative to the
/// as-shot look (`docs/camera-preview-colour.md`). The catalog's `Photo::relative_wb` matches the
/// same formats by file extension.
pub(crate) fn file_local_look(format: RawFormat) -> bool {
matches!(
format,
RawFormat::Arw
| RawFormat::Nef
| RawFormat::Nrw
| RawFormat::Rw2
| RawFormat::Raf
| RawFormat::Cr3
| RawFormat::Cr2
| RawFormat::Pef
| RawFormat::Srw
| RawFormat::Orf
| RawFormat::Mrw
| RawFormat::Erf
)
}
/// The colour a raw starts from, first available first: the file's own colour matrices (DNG); a look fitted to the
/// file's JPEG ([`fit_preview`]: with the camera profile for its model when there is one, else with colour fitted to
/// this photo alone); the model's colour matrices from measured spectral sensitivities (`lightcraft_raw::spectral`);
/// the neutral fallback. The spectral matrices only stand in for the neutral fallback, so a photo whose JPEG fit is
/// accepted renders as without them; when used they are written into `raw.color`. A photo whose JPEG is black and
/// white (a monochrome picture style) has no colour to fit, but still gives its tone curve: with the camera profile's
/// colour in [`fit_preview`], else on top of the spectral matrices or the fallback ([`monochrome_look`]). Returns the
/// as-shot white, the camera transform at it and the fitted look.
/// `lens` is the file's own lens-correction warp ([`lens_geometry`], read before the caller removes it from
/// `OpcodeList3`): the camera applied it to its JPEG, so the sensor proxy is warped the same way before pairing.
/// `embedded` is the file's embedded lens vignetting, for the DNG tone fit.
pub(crate) fn starting_colour(
raw: &mut RawImage,
bytes: &[u8],
lens: Option<&LensGeometry>,
embedded: Option<&lightcraft_develop::EmbeddedLens>,
) -> (Xy, CameraTransform, Option<CameraLook>) {
let (xy, t, look) = starting_colour_with(
raw,
|raw, t| fit_preview(raw, bytes, t, lens),
|raw, t| monochrome_look(raw, bytes, t, lens),
|raw, t| {
if !file_local_look(raw.format) {
return None;
}
let (sensor, reference, clipped) = proxies(raw, bytes, t, PROXY, 0.0, lens)?;
fit_dark_tone(&sensor, &reference, &clipped)
},
);
if look.is_none() && dng_tone_eligible(raw, &t) {
let look = fit_dng_tone(raw, bytes, &t, embedded);
return (xy, t, look);
}
(xy, t, look)
}
/// Whether the profile's tone curve is absent or the identity (within 0.005 over the range).
fn identity_tone_curve(curve: Option<&lightcraft_raw::profile::ToneCurve>) -> bool {
curve.is_none_or(|c| {
(0..=32).all(|i| {
let x = i as f32 / 32.0;
(c.eval(x) - x).abs() < 0.005
})
})
}
/// A DNG with its own colour model whose tone is not (yet) defined by the file: a matrix, no
/// non-identity `ProfileToneCurve` and no `ProfileGainTableMap`. A `LookTable` does not define the tone: an
/// Adobe Standard profile carries one without a tone curve and is rendered with Lightroom's default curve on
/// top (Lightroom Classic's lossy DNGs rendered flat and dull without a fit), and the fit applies the tables
/// to its proxy, so it fits only the tone around them.
pub(crate) fn dng_tone_eligible(raw: &RawImage, t: &CameraTransform) -> bool {
let p = &raw.color.profile;
raw.format == RawFormat::Dng && !t.matrix_is_fallback && identity_tone_curve(p.tone_curve.as_ref()) && p.gain_table_map.is_none()
}
/// [`starting_colour`] with the JPEG fit (the look, and whether the JPEG is black and white) and the black-and-white
/// JPEG's tone fit and the near-black tone fallback passed in (tests pin the order with them).
pub(super) fn starting_colour_with(
raw: &mut RawImage,
fit: impl FnOnce(&RawImage, &CameraTransform) -> (Option<CameraLook>, bool),
monochrome: impl FnOnce(&RawImage, &CameraTransform) -> Option<CameraLook>,
dark: impl FnOnce(&RawImage, &CameraTransform) -> Option<CameraLook>,
) -> (Xy, CameraTransform, Option<CameraLook>) {
let start = |raw: &RawImage| {
let xy = lightcraft_raw::color::as_shot_white_xy(raw);
(xy, lightcraft_raw::color::camera_transform(raw, xy))
};
let (xy, t) = start(raw);
if !t.matrix_is_fallback {
return (xy, t, None);
}
let (look, black_and_white) = fit(raw, &t);
if let Some(look) = look {
return (xy, t, Some(look));
}
let (xy, t) = match raw.metadata.model.as_deref().and_then(|model| lightcraft_raw::spectral::find(raw.metadata.make.as_deref(), model)) {
Some(camera) => {
camera.fill(&mut raw.color);
if lightcraft_pipeline::profiling() {
eprintln!("[profile] {:?} camera colour from spectral sensitivities: {} {}", raw.format, camera.make, camera.model);
}
start(raw)
}
None => (xy, t),
};
// A black-and-white JPEG first tries its existing tone fit on the chosen colour.
let look = if black_and_white { monochrome(raw, &t) } else { None };
(xy, t, look.or_else(|| dark(raw, &t)))
}
/// The colour a raw starts from ([`starting_colour`]) as DNG colour tags, for a DNG of the raw's camera RGB (Photo
/// Merge, issue #965): without them a merge of CR2s, whose colour comes from a look fitted to their JPEG, rendered
/// green and dark. `None` when the file has colour matrices of its own (a DNG keeps them).
pub(crate) fn starting_colour_tags(raw: &mut RawImage, bytes: &[u8]) -> Option<ColorData> {
if lightcraft_raw::color::has_matrix(&raw.color) {
return None;
}
// the white the source shows, decided before `starting_colour` may fill in measured matrices
let scale = crate::files::WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata);
let white = scale.dng_white(&raw.color, lightcraft_raw::color::as_shot_white_xy(raw));
// (a merge frame arrives without its lens warp: `lightcraft_merge` removes it before calling)
let (_, t, look) = starting_colour(raw, bytes, None, None);
dng_colour(&raw.color, &white, &t, look.as_ref())
}
/// Give a raw about to be written as a DNG of its own (Export as DNG, Convert / Copy as DNG) the colour it opens
/// with, when the file has no colour matrices (issue #1745: a Z 9 NEF's DNG had no `ColorMatrix1`, and other raw
/// converters refused it). The lens corrections stay in the DNG; only the fit sees the raw without them, as when
/// the photo opens.
pub(crate) fn with_starting_colour(raw: &mut RawImage, bytes: &[u8]) {
if lightcraft_raw::color::has_matrix(&raw.color) {
return;
}
let list3 = raw.opcodes.list3.clone();
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
let tags = starting_colour_tags(raw, bytes);
raw.opcodes.list3 = list3;
if let Some(tags) = tags {
raw.color = tags;
}
}
/// DNG tags that render white-balanced camera RGB at its as-shot white as `t` with `look` on top does: one forward
/// matrix (with a colour matrix and as-shot neutral that agree with it at that white), the look's hue/saturation
/// table as `ProfileHueSatMap` and its tone curve as `ProfileToneCurve`. Not quite the same render: a DNG table
/// doesn't keep each pixel's luminance as the fitted one does ([`HueSat`]), and the chroma curve has no tag; on two
/// CC0 CR2s (EOS 550D, 40D) an HDR merge of three copies renders within mean CIE76 ΔE 1.07 and 0.47 of the photo
/// (1.47 and 0.66 without the table; 26 and 23 with no colour tags at all).
/// The colour matrices declare `declared`, the white balance the source shows ([`crate::files::WbScaleOf::dng_white`]),
/// so the DNG opens at the source's As Shot temperature and tint and a white-balance edit starts from it. Matrices
/// derived from `forward` put the declared white wherever the look and the generic camera model took it: ARW merges
/// opened at about 7000 K / +115 where the ARWs show 4800 K / +8, and any white-balance edit turned them green.
/// `forward` is used only with the as-shot neutral, so the render at As Shot doesn't depend on them.
/// `None` when the white balance or the matrix can't give tags.
pub(crate) fn dng_colour(tags: &ColorData, declared: &crate::files::DngWhite, t: &CameraTransform, look: Option<&CameraLook>) -> Option<ColorData> {
let m = look.map_or(t.matrix, |l| l.matrix.mul(&t.matrix));
// the DNG model renders the camera's white at unit brightness: what a look does to white's brightness goes
// into the baseline exposure
let white = m.apply([1.0; 3]);
let k = (white[0] + white[1] + white[2]) / 3.0;
if !(k.is_finite() && k > 1e-6 && t.wb.iter().all(|w| w.is_finite() && *w > 0.0)) {
return None;
}
let m = Mat3(m.0.map(|r| r.map(|v| v / k)));
let forward = bradford(D65, D50).mul(&REC2020.to_xyz()).mul(&m);
let wb = t.wb.map(f64::from);
let neutral = wb.map(|w| wb.iter().cloned().fold(f64::MAX, f64::min) / w);
let (illuminant, color_matrix) = match declared {
crate::files::DngWhite::Matrices(c) if lightcraft_raw::color::has_matrix(c) => (c.illuminant, c.color_matrix),
crate::files::DngWhite::Matrices(_) => ([21, 0], [Some(declaring(t.white_xy, neutral)?), None]),
crate::files::DngWhite::At(xy) => ([21, 0], [Some(declaring(*xy, neutral)?), None]),
};
if !color_matrix.iter().flatten().all(|m| m.0.iter().flatten().all(|v| v.is_finite())) {
return None;
}
Some(ColorData {
illuminant,
color_matrix,
// a second colour matrix comes with a second forward matrix (DNG spec): the same one, fitted at one white
forward_matrix: [Some(forward), color_matrix[1].map(|_| forward)],
camera_calibration: [None, None],
analog_balance: None,
as_shot_neutral: Some(neutral),
as_shot_white_xy: None,
baseline_exposure: t.baseline_exposure + k.log2(),
baseline_sharpness: tags.baseline_sharpness,
kelvin_presets: None,
profile: ProfileLook {
hue_sat_map: [look.and_then(|l| l.hue_sat.clone()), None],
tone_curve: look.and_then(|l| dng_tone_curve(&l.tone)),
..Default::default()
},
})
}
/// An XYZ → camera colour matrix under which camera `neutral` is white `xy`: the generic camera model, scaled per
/// channel. `None` when the model gives no positive neutral there.
fn declaring(xy: Xy, neutral: [f64; 3]) -> Option<Mat3> {
let g = lightcraft_raw::color::xyz_to_camera(&ColorData::default(), xy);
let n = g.apply(xy.to_xyz());
if !n.iter().all(|v| v.is_finite() && *v > 1e-9) {
return None;
}
Some(Mat3::diag(neutral[0] / n[0], neutral[1] / n[1], neutral[2] / n[2]).mul(&g))
}
/// A camera tone curve as a DNG `ProfileToneCurve` (linear in, linear out, 1 = white): sampled densely over the
/// 12 stops below white, the range the curve is read back over (`files::dng_tone_curve`).
fn dng_tone_curve(tone: &CameraTone) -> Option<ToneCurve> {
const N: usize = 256;
let samples = (0..=N).map(|i| {
let x = 2f32.powf(-12.0 + 12.0 * i as f32 / N as f32);
[x, tone.apply(x).min(1.0)]
});
let flat: Vec<f64> = std::iter::once([0.0, 0.0]).chain(samples).flatten().map(f64::from).collect();
ToneCurve::from_tag(&flat)
}
+271
View File
@@ -0,0 +1,271 @@
use super::mono::to_prophoto;
use super::pairs::{displayed, luma};
use super::{CameraLook, CameraTone, HsvTable, Mat3, ToneMap, luminance_2020};
/// [`HueSat::apply`] restores the luminance in full only if the table kept at least this share of it. A colour
/// the table darkens to [`NO_LUMINANCE_KEPT`] or less (only near-black noise, whose channels go negative) keeps
/// its colour; in between the two are blended, so noisy shadows show no step.
pub(super) const MIN_LUMINANCE_KEPT: f32 = 0.25;
pub(super) const NO_LUMINANCE_KEPT: f32 = 0.15;
/// How much of the table's colour a pixel gets when the table kept `share` of its luminance: 0 up to
/// [`NO_LUMINANCE_KEPT`], 1 from [`MIN_LUMINANCE_KEPT`], a smoothstep between.
pub(super) fn restore_weight(share: f32) -> f32 {
if !share.is_finite() {
return 0.0;
}
let t = ((share - NO_LUMINANCE_KEPT) / (MIN_LUMINANCE_KEPT - NO_LUMINANCE_KEPT)).clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
/// A fitted [`CameraLook::hue_sat`] table, ready to apply to linear Rec.2020 pixels. It changes
/// hue and saturation only: luminance is restored, the camera tone curve owns it.
pub(crate) struct HueSat<'a> {
table: &'a HsvTable,
pub(super) to: [[f32; 3]; 3],
pub(super) from: [[f32; 3]; 3],
}
impl<'a> HueSat<'a> {
pub fn new(table: &'a HsvTable) -> Option<HueSat<'a>> {
let to = to_prophoto();
Some(HueSat { table, to: to.to_f32(), from: to.inverse()?.to_f32() })
}
#[inline]
pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {
let mul = |m: &[[f32; 3]; 3], v: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2]) };
let out = mul(&self.from, self.table.apply(mul(&self.to, rgb)));
let (before, after) = (luminance_2020(rgb), luminance_2020(out));
// restoring the luminance divides by the table's: near black, where noise makes some channels
// negative, the table can bring it close to 0, and the gain would turn the pixel white (#820)
if before <= 0.0 || after <= 0.0 || !out.iter().all(|v| v.is_finite()) {
return rgb;
}
let w = restore_weight(after / before);
if w >= 1.0 {
return out.map(|v| v * before / after);
}
if w <= 0.0 {
return rgb;
}
std::array::from_fn(|i| rgb[i] + (out[i] * before / after - rgb[i]) * w)
}
/// [`Self::apply`] to `N` pixels at once (`rgb[channel][lane]`), bit for bit, through
/// [`HsvTable::apply_lanes`], with the guards as selects.
#[inline]
pub fn apply_lanes<const N: usize>(&self, rgb: [[f32; N]; 3]) -> [[f32; N]; 3] {
let mul = |m: &[[f32; 3]; 3], v: &[[f32; N]; 3]| {
let mut out = [[0.0f32; N]; 3];
for (row, out) in m.iter().zip(&mut out) {
for l in 0..N {
out[l] = row[0] * v[0][l] + row[1] * v[1][l] + row[2] * v[2][l];
}
}
out
};
let out = mul(&self.from, &self.table.apply_lanes(mul(&self.to, &rgb)));
let mut restored = rgb;
for l in 0..N {
let (input, out) = ([rgb[0][l], rgb[1][l], rgb[2][l]], [out[0][l], out[1][l], out[2][l]]);
let (before, after) = (luminance_2020(input), luminance_2020(out));
let untouched = (before <= 0.0) | (after <= 0.0) | !(out[0].is_finite() & out[1].is_finite() & out[2].is_finite());
let w = restore_weight(after / before);
for (c, restored) in restored.iter_mut().enumerate() {
let full = out[c] * before / after;
let blend = input[c] + (full - input[c]) * w;
// (`w >= 1` and `w <= 0` exclude each other)
restored[l] = if untouched | (w <= 0.0) {
input[c]
} else if w >= 1.0 {
full
} else {
blend
};
}
}
restored
}
}
/// HSV hue (degrees) and saturation; `None` for black or non-finite colours.
pub(super) fn hue_saturation(p: [f64; 3]) -> Option<(f64, f64)> {
let max = p[0].max(p[1]).max(p[2]);
let min = p[0].min(p[1]).min(p[2]);
if !(max.is_finite() && min.is_finite()) || max <= 0.0 {
return None;
}
let d = max - min;
if d <= 0.0 {
return Some((0.0, 0.0));
}
let h = if max == p[0] {
((p[1] - p[2]) / d).rem_euclid(6.0)
} else if max == p[1] {
(p[2] - p[0]) / d + 2.0
} else {
(p[0] - p[1]) / d + 4.0
};
Some((h * 60.0, d / max))
}
/// Table resolution: 5° hue steps (a coarser grid blurred the lime shirt into neighbouring browns
/// that want the opposite shift), saturation 0, 0.25 … 1. Value is not an axis: tone is fitted separately.
const TABLE_HUES: usize = 72;
const TABLE_SATS: usize = 5;
/// Value levels (sRGB-encoded, as DNG tables with encoding 1): cameras turn dark yellows toward
/// orange but bright yellow-greens toward green, which one shift per hue averages away.
const TABLE_VALS: usize = 5;
/// Kernel widths around each table node (hue in degrees, saturation, encoded value).
const KERNEL_HUE: f64 = 2.5;
const KERNEL_SAT: f64 = 0.15;
const KERNEL_VAL: f64 = 0.12;
/// Kernel weight at which a node keeps half of its estimate; sparse nodes shrink to identity.
const SHRINK_WEIGHT: f64 = 5.0;
/// Fit hue shifts and saturation scales of the training pairs left after `matrix`, per (hue,
/// saturation) node, kernel-weighted and shrunk toward identity where the photo has few samples.
/// Saturation 0 stays identity, so neutrals are never tinted.
pub(super) fn fit_hue_sat(pairs: &[([f64; 3], [f64; 3])], matrix: &Mat3) -> Option<HsvTable> {
let to = to_prophoto();
let samples: Vec<(f64, f64, f64, f64, f64)> = pairs
.iter()
.enumerate()
.filter(|(i, _)| i % 3 != 0)
.filter_map(|(_, (x, y))| {
let p = to.apply(matrix.apply(*x));
let (hp, sp) = hue_saturation(p)?;
let value = f64::from(lightcraft_color::transfer::linear_to_srgb(p[0].max(p[1]).max(p[2]).min(1.0) as f32));
let (ht, st) = hue_saturation(to.apply(*y))?;
// hue is meaningless near neutral
if sp < 0.08 || st < 0.02 {
return None;
}
let shift = ((ht - hp + 180.0).rem_euclid(360.0) - 180.0).clamp(-30.0, 30.0);
let log_scale = (st / sp).ln().clamp(-0.7, 0.7);
Some((hp, sp.min(1.0), value, shift, log_scale))
})
.collect();
if samples.len() < 64 {
return None;
}
// Samples by table hue step: a node only looks at hues within its kernel's reach.
let step = 360.0 / TABLE_HUES as f64;
let mut by_hue: Vec<Vec<(f64, f64, f64, f64, f64)>> = vec![Vec::new(); TABLE_HUES];
for sample in samples {
if let Some(bin) = by_hue.get_mut(((sample.0.rem_euclid(360.0) / step) as usize).min(TABLE_HUES - 1)) {
bin.push(sample);
}
}
let reach = (4.0 * KERNEL_HUE / step).ceil() as usize + 1;
use rayon::prelude::*;
let data: Vec<[f32; 3]> = (0..TABLE_VALS * TABLE_HUES * TABLE_SATS)
.into_par_iter()
.map(|index| {
let (v, h, s) = (index / (TABLE_HUES * TABLE_SATS), index / TABLE_SATS % TABLE_HUES, index % TABLE_SATS);
if s == 0 {
return [0.0, 1.0, 1.0];
}
let (val, hue, sat) = (v as f64 / (TABLE_VALS - 1) as f64, h as f64 * step, s as f64 / (TABLE_SATS - 1) as f64);
let (mut weight, mut shift, mut log_scale) = (0.0, 0.0, 0.0);
for offset in 0..=2 * reach {
let Some(bin) = by_hue.get((h + TABLE_HUES * 2 + offset - reach) % TABLE_HUES) else { continue };
for &(hp, sp, vp, dh, ls) in bin {
let dhue = (hp - hue + 180.0).rem_euclid(360.0) - 180.0;
if dhue.abs() > 4.0 * KERNEL_HUE {
continue;
}
let d2 = (dhue / KERNEL_HUE).powi(2) + ((sp - sat) / KERNEL_SAT).powi(2) + ((vp - val) / KERNEL_VAL).powi(2);
let k = (-0.5 * d2).exp() * sp;
weight += k;
shift += k * dh;
log_scale += k * ls;
}
}
if weight <= 0.0 {
return [0.0, 1.0, 1.0];
}
let shrink = 1.0 / (weight + SHRINK_WEIGHT);
[(shift * shrink) as f32, (log_scale * shrink).exp() as f32, 1.0]
})
.collect();
data.iter().all(|e| e.iter().all(|v| v.is_finite())).then_some(HsvTable {
hue_divisions: TABLE_HUES,
sat_divisions: TABLE_SATS,
val_divisions: TABLE_VALS,
data,
srgb_value: true,
})
}
/// Kernel width of the chroma curve's nodes (display luminance) and the weight at which a node
/// keeps half of its estimate.
const CHROMA_KERNEL: f64 = 0.08;
const CHROMA_SHRINK: f64 = 2.0;
/// The look's tone curve with a chroma-by-display-luminance curve fitted to `pairs` (two thirds
/// train, one third held out), when that lowers the held-out error. Colourfulness is compared as
/// the distance from neutral of luminance-normalised RGB.
pub(super) fn fit_chroma(pairs: &[([f64; 3], [f64; 3])], look: &CameraLook) -> Option<CameraTone> {
let correction = look.hue_sat.as_ref().and_then(HueSat::new);
let scene = |x: &[f64; 3]| {
let p = look.matrix.apply(*x);
correction.as_ref().map_or(p, |c| c.apply(p.map(|v| v as f32)).map(f64::from))
};
let tone = ToneMap::camera(&look.tone, 0.0, 0.0, 0.0);
let predict = |x: &[f64; 3]| displayed(scene(x), &tone);
let chroma = |p: [f64; 3]| {
let y = luma(p);
(y > 0.0).then(|| p.iter().map(|v| (v / y - 1.0).powi(2)).sum::<f64>().sqrt())
};
let samples: Vec<(f64, f64, f64)> = pairs
.iter()
.enumerate()
.filter(|(i, _)| i % 3 != 0)
.filter_map(|(_, (x, y))| {
let p = predict(x);
let (cp, cy) = (chroma(p)?, chroma(*y)?);
(cp > 0.05).then(|| (luma(p), cp, (cy.max(1e-3) / cp).ln().clamp(0.05f64.ln(), 2.5f64.ln())))
})
.collect();
if samples.len() < 64 {
return None;
}
let mut curve = [1.0f32; lightcraft_pipeline::tone::CHROMA_N];
for (j, node) in curve.iter_mut().enumerate() {
let at = j as f64 / (lightcraft_pipeline::tone::CHROMA_N - 1) as f64;
let (mut weight, mut sum) = (0.0, 0.0);
for &(o, cp, log_ratio) in &samples {
let k = (-0.5 * ((o - at) / CHROMA_KERNEL).powi(2)).exp() * cp;
weight += k;
sum += k * log_ratio;
}
*node = (sum / (weight + CHROMA_SHRINK)).exp() as f32;
}
let fitted = look.tone.with_chroma(curve)?;
let with = ToneMap::camera(&fitted, 0.0, 0.0, 0.0);
let error = |map: &ToneMap| -> f64 {
pairs
.iter()
.step_by(3)
.map(|(x, y)| {
let p = displayed(scene(x), map);
(0..3).map(|c| (p[c] - y[c]).powi(2)).sum::<f64>()
})
.sum()
};
let (before, after) = (error(&tone), error(&with));
if lightcraft_pipeline::profiling() {
eprintln!("[profile] ARW chroma curve {curve:?}: held-out error {before:.4} -> {after:.4}");
}
(after.is_finite() && after < before).then_some(fitted)
}
@@ -0,0 +1,273 @@
use super::colour::{PROXY, file_local_look};
use super::mono::{fit_tone_only_with, monochrome};
use super::pairs::{Attempt, TONE_FITS, fit_attempt, fit_partial, search_ordered};
use super::proxy::{CLIP_TOLERANCE, LensGeometry, MIN_PREVIEW_FRACTION, proxies, structure_agrees};
use super::tone::{HighlightCheck, highlights};
use super::{CameraLook, CameraTone, CameraTransform, HsvTable, Mat3, RawImage, Rgb32f, ToneMap, luminance_2020};
/// The look fitted to the file's camera JPEG, and whether that JPEG is black and white ([`monochrome`]).
pub(crate) fn fit_preview(raw: &RawImage, bytes: &[u8], transform: &CameraTransform, lens: Option<&LensGeometry>) -> (Option<CameraLook>, bool) {
if !transform.matrix_is_fallback || !file_local_look(raw.format) {
return (None, false);
}
let Some((sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, 0.0, lens) else { return (None, false) };
let black_and_white = monochrome(&reference);
// A camera profile pooled from many photos knows colours this photo shows too little of;
// try its colour first and fit tone/chroma per photo (picture styles vary).
let profile = raw.metadata.model.as_deref().and_then(crate::camera_profiles::get);
let colour = profile.as_ref().and_then(|p| Some((p.matrix().mul(&transform.matrix.inverse()?), p.hue_sat.clone())));
// Sony's Dynamic Range Optimizer (on by default) brightens the camera JPEG's darker regions,
// not the raw: keep the colour fitted to the JPEG, take the tone curve without DRO.
let dro = lightcraft_raw::embedded_preview_dynamic_range_optimized(bytes) == Some(true);
let look = match fit_look_with(&sensor, &reference, &clipped, colour.clone(), dro) {
Some(look) => look,
// A black-and-white JPEG has no colour to fit: the profile's colour and the JPEG's tone curve
// (`monochrome_look` does it without a profile).
None if colour.is_some() && black_and_white => {
let unclipped = without_clipped(&sensor, &clipped);
let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro, grey: true };
let Some(look) = fit_tone_only_with(unclipped.as_ref().unwrap_or(&sensor), &reference, colour, &bright) else { return (None, true) };
look
}
None => return (None, black_and_white),
};
let look = if dro { with_dro_off_tone(look) } else { look };
if lightcraft_pipeline::profiling() {
eprintln!(
"[profile] {:?} camera look: {:?}, {:?}, hue/sat table {}, camera profile available {}, DRO tone replaced {dro}",
raw.format,
look.matrix.0,
look.tone,
look.hue_sat.is_some(),
profile.is_some()
);
}
(Some(look), black_and_white)
}
/// Sensor level (normalised, white = 1) at or above which a raw channel counts as clipped, as in
/// the render's highlight reconstruction.
pub(super) const SENSOR_CLIP: f32 = 0.99;
/// [`fit_look_with`] for a photo without Sony's DRO.
#[cfg(test)]
pub(super) fn fit_look(sensor: &Rgb32f, reference: &Rgb32f, clipped: &[bool], colour: Option<(Mat3, Option<HsvTable>)>) -> Option<CameraLook> {
fit_look_with(sensor, reference, clipped, colour, false)
}
/// The photo's look, refitted without the proxy pixels whose sensor values are clipped.
///
/// A clipped raw pixel no longer records the scene's colour: with one channel held at the clip
/// level while the others keep rising, a white overcast sky comes out magenta or blue through the
/// camera matrix, while the camera JPEG shows it white. As correspondences such pixels teach the
/// colour matrix to pull colours toward grey, and the chroma curve to remove colour at their
/// display luminance (on a Z 6II forest under a clipped sky the curve cut colourfulness above
/// display luminance 0.4 to 13–19%, and every one of its samples there was clipped). The render
/// rebuilds clipped highlights separately (`lightcraft_raw::highlight`), so the look is fitted on
/// what the sensor measured.
///
/// The search on all pixels decides, as before, whether the photo gets a look and which attempt
/// of [`search_ordered`] gives it; only that attempt is refitted without the clipped pixels, and
/// when the refit misses the acceptance gates the look on all pixels is kept. So no photo loses
/// its look and none switches attempt (a refit that just clears the gate on all pixels must not
/// replace a look fitted away from edges). A photo that had no look gets one when the search
/// without the clipped pixels finds it, and otherwise the [`fit_partial`] look when that is clearly
/// closer to the camera JPEG than the neutral fallback.
pub(super) fn fit_look_with(
sensor: &Rgb32f,
reference: &Rgb32f,
clipped: &[bool],
colour: Option<(Mat3, Option<HsvTable>)>,
dro: bool,
) -> Option<CameraLook> {
let unclipped = without_clipped(sensor, clipped);
// from the proxies as they are: the retries' filters (clipped pixels, edges) don't remove them
let bright = HighlightCheck { pairs: highlights(sensor, reference), dro, grey: false };
let Some((look, attempt)) = search_ordered(sensor, reference, colour.clone(), TONE_FITS, &bright) else {
return unclipped
.as_ref()
.and_then(|u| search_ordered(u, reference, colour, TONE_FITS, &bright))
.map(|(look, _)| look)
.or_else(|| fit_partial(unclipped.as_ref().unwrap_or(sensor), reference, &bright));
};
let Some(unclipped) = unclipped else { return Some(look) };
let refit = fit_attempt(&unclipped, reference, &colour, attempt, &bright);
if refit.is_none() && lightcraft_pipeline::profiling() {
eprintln!("[profile] camera look: no fit without the clipped pixels on the accepted attempt, keeping the fit on all pixels");
}
Some(refit.unwrap_or(look))
}
/// `sensor` with its clipped pixels set to NaN (left out of every training pair), or `None` when
/// none is clipped.
pub(super) fn without_clipped(sensor: &Rgb32f, clipped: &[bool]) -> Option<Rgb32f> {
if clipped.len() != sensor.data.len() || !clipped.iter().any(|c| *c) {
return None;
}
let mut out = sensor.clone();
for (p, c) in out.data.iter_mut().zip(clipped) {
if *c {
*p = [f32::NAN; 3];
}
}
if lightcraft_pipeline::profiling() {
eprintln!(
"[profile] camera look: {} of {} proxy pixels have a clipped sensor channel",
clipped.iter().filter(|c| **c).count(),
clipped.len()
);
}
Some(out)
}
/// 1 where any channel of a camera-RGB pixel is at or above [`SENSOR_CLIP`], else 0.
pub(super) fn clip_mask(camera: &Rgb32f) -> Rgb32f {
let mut mask = camera.clone();
mask.map_in_place(|p| if p.iter().any(|v| *v >= SENSOR_CLIP) { [1.0; 3] } else { [0.0; 3] });
mask
}
/// Sony's global tone curve with the Dynamic Range Optimizer off (Standard creative style), pooled
/// from 12 CC0 raw.pixls.us ARWs of 10 interchangeable-lens bodies and their camera JPEGs; the file
/// lists them and how the curve was derived (`assets/ATTRIBUTION.md`). Pooled the same way from 55
/// private ILCE-7CR photos with DRO off, the curve differs by at most 1.2 L* between scene luminance
/// 0.01 and 0.5. Issue #244, `docs/camera-preview-colour.md`.
const SONY_DRO_OFF_TONE: &str = include_str!("../../../../assets/camera-tone/sony-dro-off.json");
/// [`SONY_DRO_OFF_TONE`]'s curve (`None` only if the built-in file were invalid; a test checks it).
pub(super) fn sony_dro_off_tone() -> Option<CameraTone> {
#[derive(serde::Deserialize)]
struct File {
knots: [[f32; 2]; 32],
}
static TONE: std::sync::OnceLock<Option<CameraTone>> = std::sync::OnceLock::new();
*TONE.get_or_init(|| serde_json::from_str::<File>(SONY_DRO_OFF_TONE).ok().and_then(|f| CameraTone::new(f.knots)))
}
/// `look`, fitted to a camera JPEG brightened by Sony's Dynamic Range Optimizer, with its tone
/// curve lowered to Sony's without DRO ([`SONY_DRO_OFF_TONE`]) wherever that is darker. DRO only
/// brightens, so the fitted curve bounds the curve without it from above, everywhere: where Sony's
/// curve is brighter than the photo's own (the 1″ compacts map raw values darker), the photo keeps
/// its own. Its colour (matrix, hue/saturation table and chroma curve) stays as fitted.
pub(super) fn with_dro_off_tone(look: CameraLook) -> CameraLook {
CameraLook { tone: dro_off(&look.tone), ..look }
}
/// The curve of [`with_dro_off_tone`]: `own` lowered to Sony's without DRO wherever that is darker,
/// or `own` unchanged when it can't be.
pub(super) fn dro_off(own_tone: &CameraTone) -> CameraTone {
let Some(dro_off) = sony_dro_off_tone() else { return *own_tone };
let own = own_tone.knots();
let mut knots = own.map(|[x, y]| [x, y.min(dro_off.apply(x))]);
// Past its last knot a curve goes on as a shoulder whose rate comes from its last two knots
// (`CameraTone::apply`): lowering the second-last knot more than the last steepens it, and the
// extended highlights would end up above the fitted curve. Raise the second-last knot (never
// above the fitted curve) until the rate is at most the fitted curve's.
let ([a, b], last) = ([own[30], own[31]], knots[31]);
let rate = ((b[1] - a[1]) / (b[0] - a[0])).clamp(0.1, 16.0) / (1.0 - b[1]).max(0.01);
let floor = last[1] - rate * (1.0 - last[1]).max(0.01) * (b[0] - a[0]);
knots[30][1] = knots[30][1].max(floor).min(last[1]);
let Some(tone) = CameraTone::new(knots).and_then(|tone| tone.with_chroma(*own_tone.chroma())) else { return *own_tone };
if !at_most(&tone, own_tone) {
return *own_tone;
}
tone
}
/// Whether curve `a` is nowhere brighter than `b` over the scene luminances the finish stage's tone
/// table covers ([`ToneMap::camera`]).
pub(super) fn at_most(a: &CameraTone, b: &CameraTone) -> bool {
use lightcraft_pipeline::tone::{GREY, LUT_MAX_EV, LUT_MIN_EV, LUT_N};
(0..LUT_N).all(|i| {
let x = GREY * 2f32.powf(LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32);
a.apply(x) <= b.apply(x) + 1e-5
})
}
/// Pixel cap for the embedded JPEG decoded for the fit. The codec checks it before decoding and
/// decodes at full size, so a 66.5 MP full-frame ILCE-7RM6 JPEG transiently needs ~200 MB (3 B/px);
/// 128 MP also admits 100 MP medium-format previews.
pub(super) const FIT_PREVIEW_MAX_PIXELS: u64 = 128_000_000;
/// A DNG's tone and chroma curves fitted to its own camera JPEG ([`dng_tone_eligible`]); the file's colour model
/// (matrix, profile tables, white balance) stays as it is: the proxy goes through the file's tables and the given
/// colour of the search is the identity. Same held-out acceptance gates as [`fit_look`]; the preview must not be a
/// thumbnail ([`MIN_PREVIEW_FRACTION`]), must show the same picture ([`structure_agrees`]), and the curve must not
/// clip more highlights than the plain render ([`clips_more`]).
pub(super) fn fit_dng_tone(
raw: &RawImage,
bytes: &[u8],
transform: &CameraTransform,
lens: Option<&lightcraft_develop::EmbeddedLens>,
) -> Option<CameraLook> {
// Logged under LIGHTCRAFT_PROFILE so a corpus run can count the outcome per gate.
let refuse = |why: &str| {
if std::env::var_os("LIGHTCRAFT_PROFILE").is_some() {
eprintln!("DNGTONE refused {why}");
}
None
};
let Some((mut sensor, reference, clipped)) = proxies(raw, bytes, transform, PROXY, MIN_PREVIEW_FRACTION, None) else { return refuse("preview") };
// As the loader renders it: the profile's tables around the baseline exposure.
let xy = lightcraft_raw::color::as_shot_white_xy(raw);
if let Some(tables) = lightcraft_raw::profile::ProfileTables::new(&raw.color.profile, lightcraft_raw::color::illuminant_weight(&raw.color, xy)) {
let gain = 2f32.powf(transform.baseline_exposure as f32);
sensor.map_in_place(|p| tables.apply(p.map(|v| v / gain), gain));
}
correct_vignetting(&mut sensor, lens, raw.orientation);
if (sensor.width, sensor.height) != (reference.width, reference.height) {
return refuse("preview");
}
if !structure_agrees(&sensor, &reference) {
return refuse("structure");
}
let unclipped = without_clipped(&sensor, &clipped);
let fit_on = unclipped.as_ref().unwrap_or(&sensor);
let colour = Some((Mat3::IDENTITY, None));
let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro: false, grey: false };
let look = TONE_FITS.iter().find_map(|&tone| {
[false, true].into_iter().find_map(|away_from_edges| {
fit_attempt(fit_on, &reference, &colour, Attempt { tone, profile: true, away_from_edges, dark: true }, &bright)
})
});
let Some(look) = look else { return refuse("fit") };
let plain = match raw.color.profile.tone_curve.as_ref().and_then(crate::files::dng_tone_curve) {
Some(curve) => ToneMap::camera(&curve, 0.0, 0.0, 0.0),
None => ToneMap::new(0.0, 0.0, 0.0),
};
let fitted = ToneMap::camera(&look.tone, 0.0, 0.0, 0.0);
if clips_more(&sensor, &reference, &fitted, &plain) {
return refuse("clip");
}
if std::env::var_os("LIGHTCRAFT_PROFILE").is_some() {
eprintln!("DNGTONE accepted");
}
Some(look)
}
/// Whether the fitted tone map puts clearly more of the photo's proxy pixels at or near white than both the plain
/// render and the camera's own preview do ([`CLIP_TOLERANCE`]): a fit that clips what the camera clips too is the
/// camera's look, one that clips what neither does loses highlight detail.
pub(super) fn clips_more(sensor: &Rgb32f, reference: &Rgb32f, fitted: &ToneMap, plain: &ToneMap) -> bool {
let near_white = |tone: &ToneMap| {
let n = sensor.data.iter().filter(|p| p.iter().all(|v| v.is_finite()) && tone.apply(luminance_2020(p.map(|v| v.max(0.0)))) >= 0.98).count();
n as f64 / sensor.data.len().max(1) as f64
};
let preview = reference.data.iter().filter(|p| luminance_2020(**p) >= 0.98).count() as f64 / reference.data.len().max(1) as f64;
near_white(fitted) > near_white(plain).max(preview) + CLIP_TOLERANCE
}
/// Multiply the sensor proxy (sensor orientation, default crop) by the embedded vignetting correction, the gain the
/// pipeline applies to the render (`optics::embedded_vignette_gain`; `lens` is in the oriented, cropped frame): the
/// camera JPEG has it applied, so a tone fitted without it brightens the render's corners twice.
pub(super) fn correct_vignetting(sensor: &mut Rgb32f, lens: Option<&lightcraft_develop::EmbeddedLens>, orientation: lightcraft_geom::Orientation) {
let Some(vignette) = lens.and_then(|l| l.vignette) else { return };
let (w, h) = (sensor.width as f64, sensor.height as f64);
let (ow, oh) = if orientation.swaps_axes() { (h, w) } else { (w, h) };
let width = sensor.width.max(1);
for (i, p) in sensor.data.iter_mut().enumerate() {
let (x, y) = orientation.map((i % width) as f64 + 0.5, (i / width) as f64 + 0.5, w, h);
let gain = lightcraft_pipeline::optics::embedded_vignette_gain(&vignette, lightcraft_geom::Point::new(x, y), ow, oh) as f32;
*p = p.map(|v| v * gain);
}
}
+212
View File
@@ -0,0 +1,212 @@
use super::colour::{PROXY, file_local_look};
use super::hue_sat::HueSat;
use super::look_fit::{with_dro_off_tone, without_clipped};
use super::pairs::{
EDGE_CONTRAST, MIN_IMPROVEMENT, PARTIAL_MIN_RANK_CORRELATION, Pairs, collect_pairs, displayed, fit_tone_with_shadows, local_contrast, luma,
rank_correlation_ties,
};
use super::proxy::{LensGeometry, proxies};
use super::tone::{HighlightCheck, ToneFit, fit_tone, highlights, highlights_hold};
use super::{CameraLook, CameraTransform, D50, D65, HsvTable, Mat3, PROPHOTO, REC2020, RawImage, Rgb32f, ToneMap, bradford, luminance_2020};
/// A camera JPEG pixel's channels may differ by this much (linear) and still count as grey.
const GREY_SPREAD: f32 = 0.002;
/// Whether the camera JPEG is black and white: a monochrome picture style (Canon Monochrome, Sony B/W, Nikon
/// Monochrome), shot from a full-colour raw. All but one proxy pixel in a thousand are grey within
/// [`GREY_SPREAD`]. A toned monochrome (sepia) has colour, so it isn't one.
pub(super) fn monochrome(reference: &Rgb32f) -> bool {
let coloured = reference
.data
.iter()
.filter(|p| {
let (min, max) = p.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
!p.iter().all(|v| v.is_finite()) || max - min > GREY_SPREAD
})
.count();
reference.data.len() >= 256 && coloured.saturating_mul(1000) <= reference.data.len()
}
/// The look of a raw whose camera JPEG is black and white ([`monochrome`]; issue #577) and gave no look with a camera
/// profile's colour in [`fit_preview`] (or whose model has no profile). Such a JPEG has no colour to fit, so the photo
/// would start from the spectral matrices or the neutral fallback with the default tone curve, about 1.3 EV darker
/// and flatter than the same body's photos shot in colour. But the JPEG still shows the camera's tone curve.
/// `transform` is the colour the photo gets otherwise (the spectral matrices or the fallback's); the look keeps it and
/// adds the tone curve alone ([`fit_tone_only_with`]), as [`fit_look_with`] tries the photo's own colour after a profile's. The
/// chroma curve stays neutral: the JPEG has no colourfulness to learn.
pub(super) fn monochrome_look(raw: &RawImage, bytes: &[u8], transform: &CameraTransform, lens: Option<&LensGeometry>) -> Option<CameraLook> {
if !file_local_look(raw.format) {
return None;
}
let (sensor, reference, clipped) = proxies(raw, bytes, transform, PROXY, 0.0, lens)?;
if !monochrome(&reference) {
return None;
}
// Sony's Dynamic Range Optimizer brightens a B/W JPEG as much as a colour one
let dro = lightcraft_raw::embedded_preview_dynamic_range_optimized(bytes) == Some(true);
let unclipped = without_clipped(&sensor, &clipped);
let bright = HighlightCheck { pairs: highlights(&sensor, &reference), dro, grey: true };
let look = fit_tone_only_with(unclipped.as_ref().unwrap_or(&sensor), &reference, None, &bright)?;
let look = if dro { with_dro_off_tone(look) } else { look };
if lightcraft_pipeline::profiling() {
eprintln!(
"[profile] {:?} camera look from a black-and-white JPEG: tone {:?}, {} colour, DRO tone replaced {dro}",
raw.format,
look.tone,
if transform.matrix_is_fallback { "fallback" } else { "spectral" }
);
}
Some(look)
}
/// The tone curve of a black-and-white camera JPEG, on top of `colour` (a camera profile's, in the sensor proxy's
/// space) or, without one, of the sensor proxy's own colour. Fitted like [`fit_partial`]'s, by quantile matching of
/// the luminances, on all pixels and then away from edges, and used only when the JPEG shows the same picture
/// ([`PARTIAL_MIN_RANK_CORRELATION`]) and the look cuts the held-out squared luminance error to below
/// [`MIN_IMPROVEMENT`] of the default curve's, in linear and in gamma-encoded display values. A curve narrower than
/// [`NARROW_TONE_RANGE`] must also keep the JPEG's bright areas ([`highlights_hold`], by luminance).
pub(super) fn fit_tone_only_with(
sensor: &Rgb32f,
reference: &Rgb32f,
colour: Option<(Mat3, Option<HsvTable>)>,
highlights: &HighlightCheck,
) -> Option<CameraLook> {
[None, Some(EDGE_CONTRAST)].into_iter().find_map(|edge_limit| fit_tone_only_on(sensor, reference, &colour, edge_limit, highlights))
}
/// [`fit_tone_only_with`] for a photo without Sony's DRO, checked against its own bright areas.
#[cfg(test)]
pub(super) fn fit_tone_only(sensor: &Rgb32f, reference: &Rgb32f, colour: Option<(Mat3, Option<HsvTable>)>) -> Option<CameraLook> {
fit_tone_only_with(sensor, reference, colour, &HighlightCheck { pairs: highlights(sensor, reference), dro: false, grey: true })
}
fn fit_tone_only_on(
sensor: &Rgb32f,
reference: &Rgb32f,
colour: &Option<(Mat3, Option<HsvTable>)>,
edge_limit: Option<f32>,
highlights: &HighlightCheck,
) -> Option<CameraLook> {
// every pair counts: the JPEG has no colour to require
let (pairs, _) = collect_pairs(sensor, reference, f32::NEG_INFINITY, edge_limit, false)?;
fit_tone_only_pairs(sensor, reference, colour, edge_limit, &pairs, false, highlights)
}
/// A near-black frame may have enough luminance signal for tone but fewer than 256 colour pairs.
/// Try only after every existing look fails. Keep the colour of the source transform,
/// exclude clipped pixels from training, and keep their luminance at least as close to the JPEG
/// as the default curve does. Bright JPEGs need the existing fits to constrain their highlights.
pub(super) fn fit_dark_tone(sensor: &Rgb32f, reference: &Rgb32f, clipped: &[bool]) -> Option<CameraLook> {
if (sensor.width, sensor.height) != (reference.width, reference.height)
|| sensor.data.len() != reference.data.len()
|| clipped.len() != sensor.data.len()
|| sensor.data.is_empty()
|| sensor.data.iter().any(|p| !p.iter().all(|v| v.is_finite()))
|| reference.data.iter().any(|p| !p.iter().all(|v| v.is_finite() && *v >= 0.0) || luminance_2020(*p) >= 0.85)
{
return None;
}
let dark = reference.data.iter().filter(|p| luminance_2020(**p) < 0.015).count();
if (dark as f64) < reference.data.len() as f64 * 0.9 {
return None;
}
// no JPEG pixel reaches 0.85 here, so the bright-area check has nothing to hold
let bright = HighlightCheck { pairs: highlights(sensor, reference), dro: false, grey: true };
[None, Some(EDGE_CONTRAST)].into_iter().find_map(|edge_limit| {
let pairs: Pairs = sensor
.data
.iter()
.zip(&reference.data)
.enumerate()
.filter(|(i, (input, output))| {
// The same signal floors as the camera toe, without colour ratios or counts.
!clipped.get(*i).copied().unwrap_or(true)
&& input.iter().all(|v| *v > 0.0001 && *v < 1.5)
&& (0.0003..0.85).contains(&luminance_2020(**output))
&& edge_limit.is_none_or(|limit| local_contrast(sensor, *i) <= limit && local_contrast(reference, *i) <= limit)
})
.map(|(_, (input, output))| (input.map(f64::from), output.map(f64::from)))
.collect();
if pairs.len() < 256 {
return None;
}
let look = fit_tone_only_pairs(sensor, reference, &None, edge_limit, &pairs, true, &bright)?;
let (tone, neutral) = (ToneMap::camera(&look.tone, 0.0, 0.0, 0.0), ToneMap::new(0.0, 0.0, 0.0));
for ((input, target), clipped) in sensor.data.iter().zip(&reference.data).zip(clipped) {
if *clipped {
let target = luma(target.map(f64::from));
let before = luma(displayed(input.map(f64::from), &neutral));
let after = luma(displayed(input.map(f64::from), &tone));
if !after.is_finite() || (after - target).abs() > (before - target).abs() {
return None;
}
}
}
Some(look)
})
}
fn fit_tone_only_pairs(
sensor: &Rgb32f,
reference: &Rgb32f,
colour: &Option<(Mat3, Option<HsvTable>)>,
edge_limit: Option<f32>,
pairs: &Pairs,
dark: bool,
highlights: &HighlightCheck,
) -> Option<CameraLook> {
let kind = if dark { "near-black scene" } else { "black-and-white JPEG" };
let related = rank_correlation_ties(pairs);
if related < PARTIAL_MIN_RANK_CORRELATION {
if lightcraft_pipeline::profiling() {
eprintln!("[profile] camera look from a {kind}: luminance rank correlation {related:.3}, not the same picture");
}
return None;
}
let (matrix, hue_sat) = colour.clone().unwrap_or((Mat3::IDENTITY, None));
let correction = hue_sat.as_ref().and_then(HueSat::new);
let coloured = |x: [f64; 3]| {
let p = matrix.apply(x);
correction.as_ref().map_or(p, |c| c.apply(p.map(|v| v as f32)).map(f64::from))
};
let tone = if dark {
// Split this wider set once. The camera toe's separate colour/extra split belongs to
// the original colour pairs and would put some of these held-out pixels into training.
fit_tone(
pairs.iter().enumerate().filter(|(i, _)| i % 3 != 0).map(|(_, (x, y))| (luma(coloured(*x).map(|v| v.max(0.0))), luma(*y))).collect(),
)?
} else {
fit_tone_with_shadows(ToneFit::Quantile, pairs, sensor, reference, edge_limit, coloured)?
};
let look = CameraLook { matrix, tone, hue_sat: hue_sat.clone() };
if !highlights_hold(&look.tone, highlights, coloured) {
return None;
}
let (tone, neutral) = (ToneMap::camera(&look.tone, 0.0, 0.0, 0.0), ToneMap::new(0.0, 0.0, 0.0));
let encoded = |v: f64| v.max(0.0).powf(1.0 / 2.2);
let (mut before, mut after, mut before_encoded, mut after_encoded, mut samples) = (0.0, 0.0, 0.0, 0.0, 0);
for (x, target) in pairs.iter().step_by(3) {
let (fallback, toned, target) = (luma(displayed(*x, &neutral)), luma(displayed(coloured(*x), &tone)), luma(*target));
before += (fallback - target).powi(2);
after += (toned - target).powi(2);
before_encoded += (encoded(fallback) - encoded(target)).powi(2);
after_encoded += (encoded(toned) - encoded(target)).powi(2);
samples += 1;
}
if lightcraft_pipeline::profiling() {
eprintln!(
"[profile] camera look from a {kind}: holdout luminance RMS {:.5} -> {:.5} ({samples} pixels{})",
(before / samples.max(1) as f64).sqrt(),
(after / samples.max(1) as f64).sqrt(),
if edge_limit.is_some() { ", away from edges" } else { "" }
);
}
let better =
after.is_finite() && after_encoded.is_finite() && after < before * MIN_IMPROVEMENT && after_encoded < before_encoded * MIN_IMPROVEMENT;
(samples > 0 && better).then_some(look)
}
/// Linear Rec.2020 D65 → linear ProPhoto RGB D50, the space DNG hue/saturation tables work in.
pub(super) fn to_prophoto() -> Mat3 {
PROPHOTO.from_xyz().mul(&bradford(D65, D50)).mul(&REC2020.to_xyz())
}
+499
View File
@@ -0,0 +1,499 @@
use super::hue_sat::{HueSat, fit_chroma, fit_hue_sat};
use super::proxy::DARK_FLOOR;
#[cfg(test)]
use super::tone::highlights;
use super::tone::{HighlightCheck, ToneFit, highlights_hold};
use super::{CameraLook, CameraTone, HsvTable, Mat3, Rgb32f, ToneMap, luminance_2020};
/// A fit must cut the held-out squared error to below this share of the fallback's.
pub(super) const MIN_IMPROVEMENT: f64 = 0.7;
/// ...and stay within this per-channel RMS of the camera JPEG (linear display values). On public
/// raw.pixls.us samples (eight Sony bodies) good fits that still beat the fallback 1.5–3× landed
/// at 0.065–0.093 (camera local tone, vignetting and lens processing that a global matrix + curve
/// cannot follow): visibly better renders that 0.055 rejected.
const MAX_HOLDOUT_RMS: f64 = 0.10;
pub(super) fn luma(p: [f64; 3]) -> f64 {
p[0] * 0.2627 + p[1] * 0.6780 + p[2] * 0.0593
}
/// The finish stage's tone map and chroma curve (`lightcraft_pipeline::finish`).
pub(super) fn displayed(scene: [f64; 3], tone: &ToneMap) -> [f64; 3] {
let scene = scene.map(|v| v.max(0.0));
let y = luma(scene);
if y <= 0.0 {
return [0.0; 3];
}
let o = f64::from(tone.apply(y as f32));
let k = f64::from(tone.chroma_scale(o as f32));
scene.map(|v| o + (v * o / y - o) * k)
}
#[cfg(test)]
pub(super) fn fit_pairs(sensor: &Rgb32f, reference: &Rgb32f) -> Option<CameraLook> {
fit_pairs_with(sensor, reference, None)
}
/// Largest luminance ratio within the 3×3 neighbourhood of pixel `i` (1 on flat areas, large on edges).
pub(super) fn local_contrast(image: &Rgb32f, i: usize) -> f32 {
let (w, h) = (image.width, image.height);
if w == 0 {
return f32::INFINITY;
}
let (x, y) = (i % w, i / w);
let (mut lo, mut hi) = (f32::INFINITY, 0f32);
for row in y.saturating_sub(1)..(y + 2).min(h) {
for col in x.saturating_sub(1)..(x + 2).min(w) {
let l = image.data.get(row * w + col).map_or(0.0, |p| luminance_2020(*p));
lo = lo.min(l);
hi = hi.max(l);
}
}
if hi.is_finite() { hi / lo.max(1e-4) } else { f32::INFINITY }
}
/// Training pairs (sensor → JPEG, unclipped midtones) and the wider set including highlights
/// (for the chroma curve); `None` when too few, or the photo has too little colour. With
/// `edge_limit`, pixels whose 3×3 neighbourhood in either proxy spans a larger luminance ratio
/// are left out: there a small geometric mismatch between the raw and its JPEG pairs unrelated
/// colours (see [`EDGE_CONTRAST`]).
pub(super) type Pair = ([f64; 3], [f64; 3]);
pub(super) type Pairs = Vec<Pair>;
pub(super) fn collect_pairs(sensor: &Rgb32f, reference: &Rgb32f, min_chroma: f32, edge_limit: Option<f32>, dark: bool) -> Option<(Pairs, Pairs)> {
if (sensor.width, sensor.height) != (reference.width, reference.height) || sensor.data.len() != reference.data.len() {
return None;
}
let mut pairs = Vec::new();
// Highlights too (camera JPEGs bleach colours toward white there), for the chroma curve only.
let mut bright = Vec::new();
let mut colour = 0;
for (i, (input, output)) in sensor.data.iter().zip(&reference.data).enumerate() {
if edge_limit.is_some_and(|limit| local_contrast(sensor, i) > limit || local_contrast(reference, i) > limit) {
continue;
}
let y = luminance_2020(*output);
if !input.iter().all(|v| v.is_finite() && *v > 0.001 && *v < 1.5) || !output.iter().all(|v| v.is_finite() && *v >= 0.0) {
continue;
}
if (0.015..=1.0).contains(&y) {
bright.push((input.map(f64::from), output.map(f64::from)));
}
let floors = if dark { DARK_FLOOR } else { (0.015, 0.004) };
if !colour_pair_above(*input, *output, floors) {
continue;
}
let min = output.iter().copied().fold(f32::INFINITY, f32::min);
let max = output.iter().copied().fold(0.0, f32::max);
colour += usize::from(max - min > min_chroma);
pairs.push((input.map(f64::from), output.map(f64::from)));
}
(pairs.len() >= 256 && colour >= pairs.len() / 20).then_some((pairs, bright))
}
/// The original colour-pair eligibility, also used to preserve its held-out split in tone fitting.
pub(super) fn colour_pair(input: [f32; 3], output: [f32; 3]) -> bool {
colour_pair_above(input, output, (0.015, 0.004))
}
/// [`colour_pair`] with its lowest preview luminance and channel value given (`floors`: the usual 0.015 and 0.004, or
/// [`DARK_FLOOR`] for the tone-only fit of a DNG).
fn colour_pair_above(input: [f32; 3], output: [f32; 3], (ylo, clo): (f32, f32)) -> bool {
input.iter().all(|v| v.is_finite() && *v > 0.001 && *v < 1.5)
&& output.iter().all(|v| *v > clo && *v < 0.98)
&& (ylo..0.85).contains(&luminance_2020(output))
}
/// Fit tone independently of colour eligibility when enough dark JPEG signal is available.
/// The original pairs and their split still own the colour fit and its acceptance gates.
/// Luminance needs no channel ratios, so the binned proxy can use a lower sensor floor and
/// keep JPEG pixels with a channel near black. Quantile medians limit the effect of noise.
pub(super) fn fit_tone_with_shadows(
fit: ToneFit,
pairs: &[([f64; 3], [f64; 3])],
sensor: &Rgb32f,
reference: &Rgb32f,
edge_limit: Option<f32>,
colour: impl Fn([f64; 3]) -> [f64; 3],
) -> Option<CameraTone> {
let luminances = |x: [f64; 3], y: [f64; 3]| (luma(colour(x).map(|v| v.max(0.0))), luma(y));
let original = fit.fit(pairs.iter().enumerate().filter(|(i, _)| i % 3 != 0).map(|(_, (x, y))| luminances(*x, *y)).collect());
let mut eligible = Vec::new();
let (mut colour_index, mut extra_index) = (0, 0);
for (i, (input, output)) in sensor.data.iter().zip(&reference.data).enumerate() {
if edge_limit.is_some_and(|limit| local_contrast(sensor, i) > limit || local_contrast(reference, i) > limit) {
continue;
}
// About one 8-bit sRGB code above black: don't learn a flat black segment from
// JPEG compression. The sensor proxy averages many samples before this test.
if !input.iter().all(|v| v.is_finite() && *v > 0.0001 && *v < 1.5)
|| !output.iter().all(|v| v.is_finite() && *v >= 0.0)
|| !(0.0003..0.85).contains(&luminance_2020(*output))
{
continue;
}
// A colour holdout must never enter tone training just because the wider sample set
// changes its index. Split the extra samples separately, keeping every colour index.
let index = if colour_pair(*input, *output) { &mut colour_index } else { &mut extra_index };
let held = *index % 3 == 0;
*index += 1;
let (x, y) = luminances(input.map(f64::from), output.map(f64::from));
if x.is_finite() && x > 0.0 {
eligible.push((x, y, held));
}
}
let dark = eligible.iter().filter(|(_, y, _)| *y < 0.015).count();
let held: Pairs = eligible.iter().filter(|(_, y, held)| *held && *y < 0.015).map(|(x, y, _)| ([*x; 3], [*y; 3])).collect();
// Sparse or uncorrelated shadow noise cannot teach a toe. Tied JPEG levels share a rank,
// so a single quantized grey also keeps the original curve.
if dark < 96 || held.len() < 32 || rank_correlation_ties(&held) < PARTIAL_MIN_RANK_CORRELATION {
return original;
}
let training = eligible.iter().filter(|(_, _, held)| !held).map(|(x, y, _)| (*x, *y)).collect();
let Some(candidate) = fit.fit(training) else { return original };
let error = |tone: &CameraTone| -> f64 {
held.iter().map(|(x, y)| (f64::from(tone.apply(x[0] as f32)).powf(1.0 / 2.2) - y[0].powf(1.0 / 2.2)).powi(2)).sum()
};
// A wider histogram must also help independent dark pixels, not just redistribute the
// knots. The usual held-out gates still check the completed look on the colour pairs.
if let Some(old) = original {
let (before, after) = (error(&old), error(&candidate));
if lightcraft_pipeline::profiling() {
eprintln!("[profile] camera toe: {dark} dark pairs, held-out error {before:.5} -> {after:.5}");
}
if !after.is_finite() || after >= before * 0.99 {
return original;
}
}
Some(candidate)
}
/// Ridge-regularised 3×3 chromaticity matrix (luminance-normalised RGB) on the training pairs.
pub(super) fn fit_matrix(pairs: &[([f64; 3], [f64; 3])]) -> Option<Mat3> {
let mut gram = [[0.0; 3]; 3];
let mut cross = [[0.0; 3]; 3];
for (i, (x, y)) in pairs.iter().enumerate() {
if i % 3 == 0 {
continue;
}
let (lx, ly) = (luma(*x), luma(*y));
if lx <= 0.0 || ly <= 0.0 {
continue;
}
for row in 0..3 {
for col in 0..3 {
// Normalising by luminance prevents a camera S-curve from corrupting colour.
gram[row][col] += x[row] * x[col] / (lx * lx);
cross[row][col] += y[row] * x[col] / (ly * lx);
}
}
}
let trace: f64 = (0..3).map(|i| gram[i][i]).sum();
let inverse = Mat3(gram).inverse()?;
let condition = trace * (0..3).map(|i| inverse.0[i][i].abs()).sum::<f64>();
if trace <= 0.0 || !condition.is_finite() || condition > 1e6 {
return None;
}
let regularization = trace * 1e-4;
for i in 0..3 {
gram[i][i] += regularization;
cross[i][i] += regularization;
}
let matrix = Mat3(cross).mul(&Mat3(gram).inverse()?);
matrix.0.iter().flatten().all(|v| v.is_finite() && v.abs() < 8.0).then_some(matrix)
}
/// Neighbourhood luminance ratio above which a pixel counts as an edge for the second attempt
/// of [`search_ordered`]. Camera JPEGs are often lens-corrected (Sony "Distortion Comp.: Auto",
/// compacts and kit zooms): on a 51 mm ILCE-7RM2 shot of a glass façade the JPEG is up to 15 px
/// of 1440 (about one proxy pixel) off the raw, and the fit failed the gate on the mismatched
/// window frames alone (held-out RMS 0.111; 0.059 for the same shot with distortion correction
/// off). Away from edges: 0.049. Issue #232.
pub(super) const EDGE_CONTRAST: f32 = 3.0;
/// The look on all pixels (the search of [`search_ordered`] with [`TONE_FITS`]), as before
/// clipped pixels were left out.
#[cfg(test)]
pub(super) fn fit_pairs_with(sensor: &Rgb32f, reference: &Rgb32f, colour: Option<(Mat3, Option<HsvTable>)>) -> Option<CameraLook> {
fit_pairs_ordered(sensor, reference, colour, TONE_FITS)
}
/// The look from [`search_ordered`] without its attempt.
#[cfg(test)]
pub(super) fn fit_pairs_ordered(
sensor: &Rgb32f,
reference: &Rgb32f,
colour: Option<(Mat3, Option<HsvTable>)>,
order: &[ToneFit],
) -> Option<CameraLook> {
search_ordered(sensor, reference, colour, order, &HighlightCheck { pairs: highlights(sensor, reference), dro: false, grey: false })
.map(|(look, _)| look)
}
/// The tone fits the search tries, in order: the first whose look passes the acceptance gates is
/// used. Quantile matching comes first because it cannot produce flat steps; the
/// conditional-median fit follows because on a few photos (compacts, early Micro Four Thirds) its
/// slightly lower held-out error is what clears the gates, and a photo must not lose its look to
/// the change of fit.
pub(super) const TONE_FITS: &[ToneFit] = &[ToneFit::Quantile, ToneFit::ConditionalMedian];
/// One attempt of the search: tone fit, the camera profile's colour or the photo's own, all pixels
/// or only those away from edges.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) struct Attempt {
pub(super) tone: ToneFit,
pub(super) profile: bool,
pub(super) away_from_edges: bool,
/// Train on the dark end of the preview too ([`DARK_FLOOR`]): the tone-only fit of a DNG.
pub(super) dark: bool,
}
/// The photo's look and the attempt that produced it: its own matrix (with and without a
/// hue/saturation table), or the given colour model (a camera profile's, in the sensor proxy's
/// space), each completed with a tone and chroma curve fitted to this photo. Per tone fit in
/// `order`: the camera profile's colour (when there is one), then the photo's own, as a different
/// picture style can make a camera profile fail the gates; each fitted on all pixels and, when that
/// fails the gates, once more on the pixels away from edges (same gates): there colour pairs stay
/// valid when the camera JPEG's geometry differs slightly from the raw's (issue #232). The whole
/// search runs with one tone fit before the next is tried, so the conditional-median fallback
/// accepts exactly what the previous releases accepted.
pub(super) fn search_ordered(
sensor: &Rgb32f,
reference: &Rgb32f,
colour: Option<(Mat3, Option<HsvTable>)>,
order: &[ToneFit],
bright: &HighlightCheck,
) -> Option<(CameraLook, Attempt)> {
let profiles: &[bool] = if colour.is_some() { &[true, false] } else { &[false] };
order.iter().find_map(|&tone| {
profiles.iter().find_map(|&profile| {
[false, true].into_iter().find_map(|away_from_edges| {
let attempt = Attempt { tone, profile, away_from_edges, dark: false };
fit_attempt(sensor, reference, &colour, attempt, bright).map(|look| (look, attempt))
})
})
})
}
pub(super) fn fit_attempt(
sensor: &Rgb32f,
reference: &Rgb32f,
colour: &Option<(Mat3, Option<HsvTable>)>,
attempt: Attempt,
bright: &HighlightCheck,
) -> Option<CameraLook> {
let colour = if attempt.profile { colour.clone() } else { None };
fit_pairs_on(sensor, reference, colour, attempt.away_from_edges.then_some(EDGE_CONTRAST), attempt.tone, attempt.dark, bright)
}
fn fit_pairs_on(
sensor: &Rgb32f,
reference: &Rgb32f,
colour: Option<(Mat3, Option<HsvTable>)>,
edge_limit: Option<f32>,
tone_fit: ToneFit,
dark: bool,
highlights: &HighlightCheck,
) -> Option<CameraLook> {
// A known colour model needs enough signal for tone fitting, not a scene rich enough to
// learn a new colour matrix. Still reject monochrome references.
let (pairs, bright) = collect_pairs(sensor, reference, if colour.is_some() { 0.005 } else { 0.05 }, edge_limit, dark)?;
let candidates = match colour {
Some(given) => vec![given],
None => {
let matrix = fit_matrix(&pairs)?;
vec![(matrix, fit_hue_sat(&pairs, &matrix)), (matrix, None)]
}
};
// Matrix + table when the table helps the held-out pixels, else the matrix alone. Chosen by
// error in gamma-encoded display values (closer to what is seen: in linear values a slightly
// missed bright rock outweighs a clearly wrong dark shirt); the acceptance gates below stay linear.
let mut best: Option<(f64, f64, usize, CameraLook)> = None;
for (matrix, hue_sat) in candidates {
let correction = hue_sat.as_ref().and_then(HueSat::new);
let colour = |x: [f64; 3]| {
let p = matrix.apply(x);
correction.as_ref().map_or(p, |c| c.apply(p.map(|v| v as f32)).map(f64::from))
};
let Some(curve) = fit_tone_with_shadows(tone_fit, &pairs, sensor, reference, edge_limit, colour) else { continue };
let mut look = CameraLook { matrix, tone: curve, hue_sat: hue_sat.clone() };
if let Some(tone) = fit_chroma(&bright, &look) {
look.tone = tone;
}
let tone = ToneMap::camera(&look.tone, 0.0, 0.0, 0.0);
if !highlights_hold(&look.tone, highlights, colour) {
continue;
}
let (mut linear, mut perceptual, mut samples) = (0.0, 0.0, 0);
for (x, target) in pairs.iter().step_by(3) {
let corrected = displayed(colour(*x), &tone);
for c in 0..3 {
linear += (corrected[c] - target[c]).powi(2);
perceptual += (corrected[c].max(0.0).powf(1.0 / 2.2) - target[c].max(0.0).powf(1.0 / 2.2)).powi(2);
samples += 1;
}
}
if linear.is_finite() && perceptual.is_finite() && best.as_ref().is_none_or(|b| perceptual < b.0) {
best = Some((perceptual, linear, samples, look));
}
}
let (_, after, samples, look) = best?;
let original_tone = ToneMap::new(0.0, 0.0, 0.0);
let before: f64 = pairs
.iter()
.step_by(3)
.map(|(x, target)| {
let original = displayed(*x, &original_tone);
(0..3).map(|c| (original[c] - target[c]).powi(2)).sum::<f64>()
})
.sum();
if lightcraft_pipeline::profiling() {
eprintln!(
"[profile] camera look holdout RMS {:.5} -> {:.5} ({samples} channels{}{})",
(before / samples as f64).sqrt(),
(after / samples as f64).sqrt(),
if edge_limit.is_some() { ", away from edges" } else { "" },
if tone_fit == ToneFit::ConditionalMedian { ", conditional-median tone" } else { "" }
);
}
if samples == 0 || after >= before * MIN_IMPROVEMENT || after / samples as f64 > MAX_HOLDOUT_RMS.powi(2) {
return None;
}
Some(look)
}
/// Weight of the photo's own colour matrix in a [`fit_partial`] look; the rest is the identity (the
/// neutral fallback's generic camera ≈ sRGB colour). On the CC0 archive's proxies, with the
/// matrix at full weight 2 of the 23 colourful photos without a look came out more than 2° further
/// from the camera's hues than the neutral fallback, at half weight none (median hue error 9.6° with
/// the generic colour, which the tone and chroma curves make visible, 5.1° at half weight).
const PARTIAL_MATRIX_WEIGHT: f64 = 0.5;
/// Smallest rank correlation of scene and camera JPEG luminance over a [`fit_partial`] look's pairs:
/// the JPEG must show the same picture. A look that only matches the brightness distribution of an
/// unrelated picture can still beat the dark neutral fallback pixel for pixel. On the CC0 archive's
/// proxies the accepted full looks have 0.55 or more, lens-corrected compacts without one 0.53–0.77,
/// three old Coolpix files whose raw decodes wrongly 0.07–0.27.
pub(super) const PARTIAL_MIN_RANK_CORRELATION: f64 = 0.5;
/// Spearman rank correlation of the scene's and the JPEG's luminance over `pairs`.
fn rank_correlation(pairs: &[([f64; 3], [f64; 3])]) -> f64 {
let ranks = |values: Vec<f64>| {
let mut order: Vec<usize> = (0..values.len()).collect();
order.sort_by(|a, b| values[*a].total_cmp(&values[*b]));
let mut ranks = vec![0.0; values.len()];
for (rank, i) in order.into_iter().enumerate() {
ranks[i] = rank as f64;
}
ranks
};
let scene = ranks(pairs.iter().map(|(x, _)| luma(*x)).collect());
let jpeg = ranks(pairs.iter().map(|(_, y)| luma(*y)).collect());
let mean = (pairs.len() as f64 - 1.0) / 2.0;
let (covariance, variance) =
scene.iter().zip(&jpeg).fold((0.0, 0.0), |(c, v), (a, b)| (c + (a - mean) * (b - mean), v + (a - mean) * (a - mean)));
if variance > 0.0 { covariance / variance } else { 0.0 }
}
/// [`rank_correlation`] with tied luminances sharing their mean rank, and 0 when either side has no spread. Without
/// colour to require, a JPEG may be flat (one grey for every pixel): [`rank_correlation`] ranks ties in pixel order,
/// so a flat JPEG of a scene whose pixels are stored in brightness order looks perfectly related.
pub(super) fn rank_correlation_ties(pairs: &[([f64; 3], [f64; 3])]) -> f64 {
let ranks = |values: Vec<f64>| {
let mut order: Vec<usize> = (0..values.len()).collect();
order.sort_by(|a, b| values[*a].total_cmp(&values[*b]));
let mut ranks = vec![0.0; values.len()];
let mut start = 0;
while start < order.len() {
let mut end = start + 1;
while end < order.len() && values[order[end]] == values[order[start]] {
end += 1;
}
let mean = (start + end - 1) as f64 / 2.0;
for &i in &order[start..end] {
ranks[i] = mean;
}
start = end;
}
ranks
};
let scene = ranks(pairs.iter().map(|(x, _)| luma(*x)).collect());
let jpeg = ranks(pairs.iter().map(|(_, y)| luma(*y)).collect());
let mean = (pairs.len() as f64 - 1.0) / 2.0;
let (covariance, scene_variance, jpeg_variance) = scene
.iter()
.zip(&jpeg)
.fold((0.0, 0.0, 0.0), |(c, va, vb), (a, b)| (c + (a - mean) * (b - mean), va + (a - mean) * (a - mean), vb + (b - mean) * (b - mean)));
if scene_variance > 0.0 && jpeg_variance > 0.0 { covariance / (scene_variance * jpeg_variance).sqrt() } else { 0.0 }
}
/// A partial look for a photo whose full look misses the acceptance gates (lens-corrected JPEGs of
/// compacts, dull or nearly colourless scenes): the tone curve by quantile matching, which needs
/// no pixel-exact registration and was the largest part of the neutral fallback's error (rendered
/// 9–22 L* too dark), the chroma curve (the fallback kept about a third of the camera's
/// colourfulness), and, when the scene has enough colour to learn one (the full look's condition),
/// the photo's own colour matrix at [`PARTIAL_MATRIX_WEIGHT`]. No hue/saturation table. Tried on
/// all pixels and then, like the full look, on the pixels away from edges; used only when it cuts
/// the held-out squared error to below [`MIN_IMPROVEMENT`] of the neutral fallback's, in linear
/// and in gamma-encoded display values, and when the JPEG shows the same picture
/// ([`PARTIAL_MIN_RANK_CORRELATION`]). There is no limit on its own error: it only has to be clearly
/// closer to the camera JPEG than what the photo would get otherwise.
pub(super) fn fit_partial(sensor: &Rgb32f, reference: &Rgb32f, highlights: &HighlightCheck) -> Option<CameraLook> {
[None, Some(EDGE_CONTRAST)].into_iter().find_map(|edge_limit| fit_partial_on(sensor, reference, edge_limit, highlights))
}
fn fit_partial_on(sensor: &Rgb32f, reference: &Rgb32f, edge_limit: Option<f32>, highlights: &HighlightCheck) -> Option<CameraLook> {
// as for a known colour model: enough signal for the tone, but no monochrome reference
let (pairs, bright) = collect_pairs(sensor, reference, 0.005, edge_limit, false)?;
let related = rank_correlation(&pairs);
if related < PARTIAL_MIN_RANK_CORRELATION {
if lightcraft_pipeline::profiling() {
eprintln!("[profile] camera look partial: luminance rank correlation {related:.3}, not the same picture");
}
return None;
}
let spread = |y: &[f64; 3]| y.iter().copied().fold(f64::NEG_INFINITY, f64::max) - y.iter().copied().fold(f64::INFINITY, f64::min);
let colourful = pairs.iter().filter(|(_, y)| spread(y) > 0.05).count() >= pairs.len() / 20;
let matrix = match colourful.then(|| fit_matrix(&pairs)).flatten() {
Some(own) => Mat3(std::array::from_fn(|r| {
std::array::from_fn(|c| Mat3::IDENTITY.0[r][c] + PARTIAL_MATRIX_WEIGHT * (own.0[r][c] - Mat3::IDENTITY.0[r][c]))
})),
None => Mat3::IDENTITY,
};
let tone = fit_tone_with_shadows(ToneFit::Quantile, &pairs, sensor, reference, edge_limit, |x| matrix.apply(x))?;
let mut look = CameraLook { matrix, tone, hue_sat: None };
if let Some(tone) = fit_chroma(&bright, &look) {
look.tone = tone;
}
let (tone, neutral) = (ToneMap::camera(&look.tone, 0.0, 0.0, 0.0), ToneMap::new(0.0, 0.0, 0.0));
if !highlights_hold(&look.tone, highlights, |x| matrix.apply(x)) {
return None;
}
let encoded = |v: f64| v.max(0.0).powf(1.0 / 2.2);
let (mut before, mut after, mut before_encoded, mut after_encoded, mut samples) = (0.0, 0.0, 0.0, 0.0, 0);
for (x, target) in pairs.iter().step_by(3) {
let (fallback, partial) = (displayed(*x, &neutral), displayed(matrix.apply(*x), &tone));
for c in 0..3 {
before += (fallback[c] - target[c]).powi(2);
after += (partial[c] - target[c]).powi(2);
before_encoded += (encoded(fallback[c]) - encoded(target[c])).powi(2);
after_encoded += (encoded(partial[c]) - encoded(target[c])).powi(2);
samples += 1;
}
}
if lightcraft_pipeline::profiling() {
eprintln!(
"[profile] camera look partial (tone{}{}) holdout RMS {:.5} -> {:.5} ({samples} channels{})",
if look.tone.chroma().iter().any(|k| *k != 1.0) { ", chroma" } else { "" },
if matrix != Mat3::IDENTITY { ", damped matrix" } else { "" },
(before / samples.max(1) as f64).sqrt(),
(after / samples.max(1) as f64).sqrt(),
if edge_limit.is_some() { ", away from edges" } else { "" }
);
}
let better =
after.is_finite() && after_encoded.is_finite() && after < before * MIN_IMPROVEMENT && after_encoded < before_encoded * MIN_IMPROVEMENT;
(samples > 0 && better).then_some(look)
}
+442
View File
@@ -0,0 +1,442 @@
use super::colour::{PROFILE_PROXY, PROXY, file_local_look};
use super::hue_sat::fit_hue_sat;
use super::look_fit::{FIT_PREVIEW_MAX_PIXELS, SENSOR_CLIP, clip_mask, without_clipped};
use super::pairs::{collect_pairs, fit_matrix};
use super::{CameraTransform, Filter, HsvTable, Mat3, RawFormat, RawImage, Rgb32f, fit, luminance_2020, resize};
/// The embedded preview's long edge must be at least this share of the raw's (and 384 px): a DNG whose preview is a
/// small thumbnail is not fitted. The fit itself runs on a proxy of at most 384 px, so the 1024 px preview
/// Lightroom writes into its DNGs (15% of a 33 MP raw's long edge) is plenty.
pub(super) const MIN_PREVIEW_FRACTION: f64 = 0.1;
/// Lowest preview luminance and channel value a tone-only fit trains on (the other fits use 0.015 and 0.004): a dark
/// night scene has most of its pixels below 0.015, and a curve fitted without them overshoots its shadows.
pub(super) const DARK_FLOOR: (f32, f32) = (0.004, 0.001);
/// Share of the proxy by which the fitted curve may clip more highlights than the plain render and the camera's
/// preview (chosen on the CC0 and user DNGs from the clipped share of their 1440 px renders: it refuses the fits
/// that clip about 1% more than the camera does and passes the ones that clip like the camera).
pub(super) const CLIP_TOLERANCE: f64 = 0.001;
/// Log-luminance correlation (5 × 5 box blurred) the unshifted proxies must reach.
const MIN_STRUCTURE: f64 = 0.85;
/// Whether the sensor proxy and the camera JPEG proxy show the same picture in the same place: their log luminance
/// correlates by at least [`MIN_STRUCTURE`] unshifted, and no shift of more than one proxy pixel (within ±3)
/// correlates better.
pub(super) fn structure_agrees(sensor: &Rgb32f, reference: &Rgb32f) -> bool {
let (w, h) = (sensor.width, sensor.height);
if (w, h) != (reference.width, reference.height) || w < 16 || h < 16 || sensor.data.len() != w * h || reference.data.len() != w * h {
return false;
}
let log = |img: &Rgb32f| -> Vec<f64> {
let l: Vec<f64> =
img.data.iter().map(|p| f64::from(luminance_2020(p.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 }))).max(1e-4).ln()).collect();
(0..w * h)
.map(|i| {
let (x, y) = (i % w, i / w);
let (mut sum, mut n) = (0.0, 0.0);
for yy in y.saturating_sub(2)..(y + 3).min(h) {
for xx in x.saturating_sub(2)..(x + 3).min(w) {
if let Some(v) = l.get(yy * w + xx) {
sum += v;
n += 1.0;
}
}
}
sum / f64::max(n, 1.0)
})
.collect()
};
let (a, b) = (log(sensor), log(reference));
const M: usize = 3;
let corr = |dx: isize, dy: isize| -> f64 {
let (mut n, mut sa, mut sb, mut saa, mut sbb, mut sab) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
for y in M..h - M {
for x in M..w - M {
let (xx, yy) = (x.saturating_add_signed(dx), y.saturating_add_signed(dy));
let (Some(&u), Some(&v)) = (a.get(y * w + x), b.get(yy * w + xx)) else { continue };
n += 1.0;
sa += u;
sb += v;
saa += u * u;
sbb += v * v;
sab += u * v;
}
}
let var = (saa - sa * sa / n) * (sbb - sb * sb / n);
if n < 2.0 || var <= 1e-12 { 0.0 } else { (sab - sa * sb / n) / var.sqrt() }
};
let at_zero = corr(0, 0);
let (mut best, mut shift) = (at_zero, (0isize, 0isize));
for dy in -(M as isize)..=M as isize {
for dx in -(M as isize)..=M as isize {
let c = corr(dx, dy);
if c > best + 1e-9 {
(best, shift) = (c, (dx, dy));
}
}
}
at_zero >= MIN_STRUCTURE && shift.0.abs() <= 1 && shift.1.abs() <= 1
}
/// Same-size proxies of the sensor (white-balanced, baseline exposure, through `transform`'s
/// matrix: the generic camera ≈ sRGB model) and of the file's embedded camera JPEG (linear Rec.2020),
/// and per proxy pixel whether any sensor sample it covers is clipped.
pub(super) fn proxies(
raw: &RawImage,
bytes: &[u8],
transform: &CameraTransform,
size: usize,
min_fraction: f64,
lens: Option<&LensGeometry>,
) -> Option<(Rgb32f, Rgb32f, Vec<bool>)> {
let edge = (2 * size).max(384) as u32;
let decoded = crate::files::decode_raw_preview(
bytes,
lightcraft_codecs::DecodeOptions { max_size: Some((edge, edge)), max_pixels: FIT_PREVIEW_MAX_PIXELS },
None,
)?;
let (a, crop) = (raw.active_area, raw.crop.clipped(raw.active_area.width, raw.active_area.height));
// a preview below `min_fraction` of the crop's long edge (or under 384 px) is refused; 0 = any
if min_fraction > 0.0 && (decoded.source_width.max(decoded.source_height) as f64) < (min_fraction * crop.width.max(crop.height) as f64).max(384.0)
{
return None;
}
let mut reference = decoded.to_working();
if crop.width == 0 || crop.height == 0 || reference.width == 0 || reference.height == 0 {
return None;
}
let matches = |w: usize, h: usize, rw: usize, rh: usize| (rw as f64 / rh as f64 / (w as f64 / h as f64) - 1.0).abs() <= 0.02;
if !matches(crop.width, crop.height, reference.width, reference.height) {
// Panasonic previews show the whole active area while the default crop is the in-camera aspect ratio
if !matches(a.width, a.height, reference.width, reference.height) {
return None;
}
let (sx, sy) = (reference.width as f64 / a.width as f64, reference.height as f64 / a.height as f64);
let (x, y) = ((crop.x as f64 * sx).round() as usize, (crop.y as f64 * sy).round() as usize);
let (w, h) = ((crop.width as f64 * sx).round() as usize, (crop.height as f64 * sy).round() as usize);
if w < 16 || h < 16 || x + w > reference.width || y + h > reference.height {
return None;
}
reference = reference.into_crop(x, y, w, h);
}
// Fixed, bounded proxy: the selected look cannot depend on thumbnail/export resolution.
let k = (crop.width.max(crop.height).div_ceil(edge as usize).max(2)).div_ceil(2) * 2;
let mut sensor = sensor_proxy(raw, k, edge as usize)?;
let mut clipped = clip_mask(&sensor);
// The camera may have corrected its JPEG with the lens warp the file carries (Nikon Z lenses always, at up to 9 %
// zoom; other cameras when their correction setting is on): the sensor moved into that geometry is a candidate,
// kept below when it lines up with the JPEG better than the uncorrected one.
let warped = lens
.filter(|_| raw.format != RawFormat::Cr3)
.and_then(|l| Some((into_lens_geometry(&sensor, raw, k, l)?, into_lens_geometry(&clipped, raw, k, l)?)));
let gain = 2f32.powf(transform.baseline_exposure as f32);
let to_working = |p: [f32; 3]| transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * gain));
if raw.format == RawFormat::Cr3 {
// Orient the camera JPEG and the sensor identically before collecting pixel correspondences.
sensor = sensor.into_oriented(raw.orientation);
clipped = clipped.into_oriented(raw.orientation);
reference = reference.into_oriented(raw.orientation);
sensor.map_in_place(to_working);
// Canon's JPEG can be cropped differently from the sensor. Estimate only that common
// framing from edge directions, independently of the subsequent colour fit.
(sensor, clipped) = align_cr3_framing(sensor, clipped, &reference);
}
let mut sensor = fit(&sensor, size, size, Filter::Box);
let mut reference_small = reference_at(&reference, &sensor);
if let Some((warped, warped_clipped)) = warped {
let candidate = fit(&warped, size, size, Filter::Box);
let candidate_reference = reference_at(&reference, &candidate);
if alignment(&candidate, &candidate_reference) > alignment(&sensor, &reference_small) {
(sensor, reference_small, clipped) = (candidate, candidate_reference, warped_clipped);
}
}
let reference = reference_small;
// A proxy pixel is clipped when any sample it averages is (outside the CR3 framing the mask is
// NaN: those pixels are left out of the pairs anyway). Resized to exactly the proxy's size, like
// the reference, so the mask pairs pixel for pixel.
let clipped: Vec<bool> = resize(&clipped, sensor.width, sensor.height, Filter::Box).data.iter().map(|p| p[0] > 0.0).collect();
if raw.format != RawFormat::Cr3 {
sensor.map_in_place(to_working);
}
Some((sensor, reference, clipped))
}
/// The camera JPEG at exactly the sensor proxy's size, so the two pair pixel for pixel. Fitting it
/// into the proxy's box instead keeps its own aspect, which can round a pixel short: an ILCE-7RM4's
/// 1616×1080 preview, decoded at 384×257, fits a 192×128 proxy as 191×128, and `collect_pairs`
/// then rejected every file `lightcraft-cli calibrate` was given. `proxies` has already checked
/// that the aspects agree within 2 %.
pub(super) fn reference_at(reference: &Rgb32f, sensor: &Rgb32f) -> Rgb32f {
resize(reference, sensor.width, sensor.height, Filter::Box)
}
#[derive(Clone, Copy, Debug)]
pub(super) struct Cr3Framing {
pub(super) scale: f32,
/// Translation as a fraction of the oriented frame's width and height.
pub(super) offset: [f32; 2],
}
impl Cr3Framing {
const IDENTITY: Self = Self { scale: 1.0, offset: [0.0; 2] };
pub(super) fn source(self, x: f32, y: f32, w: usize, h: usize) -> (f32, f32) {
let (w, h) = (w as f32, h as f32);
((x - w * 0.5) * self.scale + w * (0.5 + self.offset[0]), (y - h * 0.5) * self.scale + h * (0.5 + self.offset[1]))
}
}
/// Register the JPEG's remaining framing on a fixed proxy. Edge directions survive different
/// white balance and monotone camera tone; no target RGB values train this three-parameter fit.
/// A separate third of the edges must confirm a substantial improvement and a close match.
/// A weak, flat or unrelated preview leaves the sensor framing unchanged.
pub(super) fn estimate_cr3_framing(sensor: &Rgb32f, reference: &Rgb32f) -> Option<Cr3Framing> {
if sensor.width.checked_mul(sensor.height)? != sensor.data.len() || reference.width.checked_mul(reference.height)? != reference.data.len() {
return None;
}
let sensor = fit(sensor, PROXY, PROXY, Filter::Box);
let (w, h) = (sensor.width, sensor.height);
if w < 16 || h < 16 {
return None;
}
let reference = fit(reference, w, h, Filter::Box);
if (reference.width, reference.height) != (w, h) {
return None;
}
let mut gradients = Rgb32f::new(w, h);
let mut edges = Vec::new();
for y in 1..h - 1 {
for x in 1..w - 1 {
let derivative = |image: &Rgb32f| {
[
luminance_2020(image.data[y * w + x + 1]) - luminance_2020(image.data[y * w + x - 1]),
luminance_2020(image.data[(y + 1) * w + x]) - luminance_2020(image.data[(y - 1) * w + x]),
]
};
let d = derivative(&sensor);
gradients.data[y * w + x] = [d[0], d[1], 0.0];
let d = derivative(&reference);
let magnitude = d[0].hypot(d[1]);
let value = luminance_2020(reference.data[y * w + x]);
if (0.02..0.9).contains(&value) && magnitude.is_finite() && magnitude > 0.03 {
edges.push((x as f32 + 0.5, y as f32 + 0.5, d, magnitude, (x * 17 + y * 11) % 3 == 0));
}
}
}
if edges.len() < 192 {
return None;
}
let score = |framing: Cr3Framing, held_out: bool| -> Option<f64> {
let (mut agreement, mut weight, mut valid, mut total) = (0.0, 0.0, 0usize, 0usize);
for &(x, y, target, magnitude, holdout) in &edges {
if holdout != held_out {
continue;
}
total += 1;
let (sx, sy) = framing.source(x, y, w, h);
if sx < 1.5 || sy < 1.5 || sx > w as f32 - 1.5 || sy > h as f32 - 1.5 {
continue;
}
let sample = gradients.sample_bilinear(sx, sy);
let length = sample[0].hypot(sample[1]);
if !length.is_finite() || length <= 0.01 {
continue;
}
let k = f64::from(magnitude.min(0.25));
agreement += k * f64::from((sample[0] * target[0] + sample[1] * target[1]) / (length * magnitude));
weight += k;
valid += 1;
}
(valid >= 64 && valid * 5 >= total * 4 && weight > 0.0).then_some(agreement / weight)
};
let before = score(Cr3Framing::IDENTITY, false)?;
let mut best = (before, Cr3Framing::IDENTITY);
// At most 10% zoom and two proxy pixels of translation; a coarse search followed by one
// local refinement prevents unbounded optimisation on the photograph's contents.
for s in -10..=10 {
for tx in -4..=4 {
for ty in -4..=4 {
let framing = Cr3Framing { scale: 1.0 + s as f32 * 0.01, offset: [tx as f32 * 0.5 / w as f32, ty as f32 * 0.5 / h as f32] };
if let Some(value) = score(framing, false)
&& value > best.0
{
best = (value, framing);
}
}
}
}
let coarse = best.1;
for s in -5..=5 {
for tx in -4..=4 {
for ty in -4..=4 {
let framing = Cr3Framing {
scale: coarse.scale + s as f32 * 0.002,
offset: [coarse.offset[0] + tx as f32 * 0.125 / w as f32, coarse.offset[1] + ty as f32 * 0.125 / h as f32],
};
if !(0.9..=1.1).contains(&framing.scale) || framing.offset[0].abs() > 2.0 / w as f32 || framing.offset[1].abs() > 2.0 / h as f32 {
continue;
}
if let Some(value) = score(framing, false)
&& value > best.0
{
best = (value, framing);
}
}
}
}
let (held_before, held_after) = (score(Cr3Framing::IDENTITY, true)?, score(best.1, true)?);
if best.0 < 0.9 || best.0 < before + 0.04 || held_after < 0.9 || held_after < held_before + 0.04 {
return None;
}
if lightcraft_pipeline::profiling() {
eprintln!("[profile] CR3 JPEG framing {:?}, held-out edge agreement {held_before:.4} -> {held_after:.4}", best.1);
}
Some(best.1)
}
/// The sensor proxy and its clip mask (same size), both moved to the camera JPEG's framing.
fn align_cr3_framing(sensor: Rgb32f, clipped: Rgb32f, reference: &Rgb32f) -> (Rgb32f, Rgb32f) {
let Some(framing) = estimate_cr3_framing(&sensor, reference) else { return (sensor, clipped) };
let apply = |image: &Rgb32f| {
let (w, h) = (image.width, image.height);
let mut aligned = Rgb32f::new(w, h);
for (i, pixel) in aligned.data.iter_mut().enumerate() {
let (x, y) = framing.source((i % w) as f32 + 0.5, (i / w) as f32 + 0.5, w, h);
*pixel = if x >= 0.5 && y >= 0.5 && x <= w as f32 - 0.5 && y <= h as f32 - 0.5 { image.sample_bilinear(x, y) } else { [f32::NAN; 3] };
}
aligned
};
(apply(&sensor), apply(&clipped))
}
/// Colour training pairs of one raw for a camera profile: white-balanced camera RGB (with the
/// baseline exposure) → its camera JPEG (linear Rec.2020). `None` for formats with their own
/// colour matrices, other files or unusable previews.
pub(crate) fn profile_pairs(raw: &RawImage, bytes: &[u8], lens: Option<&LensGeometry>) -> Option<Vec<([f64; 3], [f64; 3])>> {
if !file_local_look(raw.format) || lightcraft_raw::color::has_matrix(&raw.color) {
return None;
}
let transform = lightcraft_raw::color::camera_transform(raw, lightcraft_raw::color::as_shot_white_xy(raw));
let (sensor, reference, clipped) = proxies(raw, bytes, &transform, PROFILE_PROXY, 0.0, lens)?;
let to_camera = transform.matrix.inverse()?;
// clipped sensor pixels don't record the scene's colour (see `fit_look`)
let sensor = without_clipped(&sensor, &clipped).unwrap_or(sensor);
let (pairs, _) = collect_pairs(&sensor, &reference, 0.05, None, false)?;
Some(pairs.into_iter().map(|(x, y)| (to_camera.apply(x), y)).collect())
}
/// A camera profile's colour model (matrix from white-balanced camera RGB, hue/saturation table)
/// fitted to pairs pooled from many photos.
pub(crate) fn fit_profile(pairs: &[([f64; 3], [f64; 3])]) -> Option<(Mat3, Option<HsvTable>)> {
let matrix = fit_matrix(pairs)?;
Some((matrix, fit_hue_sat(pairs, &matrix)))
}
/// A raw's lens-correction warp, as its camera applied it to the embedded JPEG: the first `WarpRectilinear` of
/// `OpcodeList3` (its green plane; the in-file corrections LightCraft reads have no tangential terms). `None` without
/// one, or for a DNG 1.6 `WarpRectilinear2` chain (phone DNGs, which carry colour matrices and are not fitted).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct LensGeometry {
/// `kr0..kr3`: source radius = r * (kr0 + kr1 r^2 + kr2 r^4 + kr3 r^6), r over the farthest corner distance.
pub(super) k: [f64; 4],
/// The optical centre, relative to the active area (as the opcode has it).
pub(super) center: [f64; 2],
}
pub(crate) fn lens_geometry(list3: &[lightcraft_raw::Opcode]) -> Option<LensGeometry> {
use lightcraft_raw::Opcode;
let ops: Vec<&Opcode> = lightcraft_raw::opcodes::applied_ops(list3).collect();
if ops.iter().any(|op| matches!(op, Opcode::WarpRectilinear2 { .. })) {
return None;
}
ops.into_iter().find_map(|op| match op {
Opcode::WarpRectilinear { planes, center } => {
let p = planes.get(1).or(planes.first())?;
let k = [p[0], p[1], p[2], p[3]];
(k.iter().chain(center).all(|v| v.is_finite()) && (0.0..=1.0).contains(&center[0]) && (0.0..=1.0).contains(&center[1]))
.then_some(LensGeometry { k, center: *center })
}
_ => None,
})
}
/// How well two same-size proxies line up: the correlation of their high-passed log luminance over the pixels both
/// have (a tone curve or colour change leaves it alone, a geometric offset lowers it). `-1` without enough pixels.
pub(super) fn alignment(a: &Rgb32f, b: &Rgb32f) -> f64 {
let (w, h) = (a.width, a.height);
if (b.width, b.height) != (w, h) || w < 3 || h < 3 {
return -1.0;
}
let lum = |img: &Rgb32f| img.data.iter().map(|p| (luminance_2020(*p).max(1e-4) as f64).ln()).collect::<Vec<f64>>();
let high = |l: &[f64]| -> Vec<f64> {
(0..w * h)
.map(|i| {
let (x, y) = (i % w, i / w);
if x == 0 || y == 0 || x + 1 == w || y + 1 == h {
return f64::NAN;
}
let around = [i - w - 1, i - w, i - w + 1, i - 1, i + 1, i + w - 1, i + w, i + w + 1];
l[i] - around.iter().map(|&j| l[j]).sum::<f64>() / 8.0
})
.collect()
};
let (ha, hb) = (high(&lum(a)), high(&lum(b)));
let pairs: Vec<(f64, f64)> = ha.into_iter().zip(hb).filter(|(x, y)| x.is_finite() && y.is_finite()).collect();
if pairs.len() < 64 {
return -1.0;
}
let n = pairs.len() as f64;
let (ma, mb) = (pairs.iter().map(|p| p.0).sum::<f64>() / n, pairs.iter().map(|p| p.1).sum::<f64>() / n);
let cov: f64 = pairs.iter().map(|p| (p.0 - ma) * (p.1 - mb)).sum();
let (va, vb): (f64, f64) = (pairs.iter().map(|p| (p.0 - ma).powi(2)).sum(), pairs.iter().map(|p| (p.1 - mb).powi(2)).sum());
let r = cov / (va * vb).sqrt().max(1e-12);
if r.is_finite() { r } else { -1.0 }
}
/// A `k`-binned sensor proxy of `raw` ([`sensor_proxy`]: the default crop, or the active area when the crop is
/// smaller than a block, at `1/k`) moved into the camera JPEG's geometry: each pixel samples the proxy where `lens`
/// maps it, and is NaN where that falls outside the proxy (the pairs leave it out). `None` for a proxy of another
/// size (the demosaiced fallback of linear raws).
pub(super) fn into_lens_geometry(img: &Rgb32f, raw: &RawImage, k: usize, lens: &LensGeometry) -> Option<Rgb32f> {
let a = raw.active_area;
let c = raw.crop.clipped(a.width, a.height);
let c = if c.width < k || c.height < k { lightcraft_raw::Rect::new(0, 0, a.width, a.height) } else { c };
let (w, h) = (img.width, img.height);
if k == 0 || w != c.width / k || h != c.height / k || w == 0 || h == 0 || a.width < 2 || a.height < 2 {
return None;
}
let (aw, ah) = (a.width as f64 - 1.0, a.height as f64 - 1.0);
let (cx, cy) = (lens.center[0] * aw, lens.center[1] * ah);
let m = [(0.0, 0.0), (aw, 0.0), (0.0, ah), (aw, ah)].iter().map(|&(x, y)| (x - cx).hypot(y - cy)).fold(0.0, f64::max).max(1e-9);
let [k0, k1, k2, k3] = lens.k;
let kf = k as f64;
let (x0, y0) = (c.x as f64, c.y as f64);
let mut out = Rgb32f::new(w, h);
for (i, px) in out.data.iter_mut().enumerate() {
// the proxy pixel's centre in active-area pixel-index coordinates, mapped to the sensor
let (ox, oy) = (x0 + ((i % w) as f64 + 0.5) * kf - 0.5, y0 + ((i / w) as f64 + 0.5) * kf - 0.5);
let (dx, dy) = ((ox - cx) / m, (oy - cy) / m);
let r2 = dx * dx + dy * dy;
let f = k0 + r2 * (k1 + r2 * (k2 + r2 * k3));
let (sx, sy) = ((cx + m * dx * f + 0.5 - x0) / kf, (cy + m * dy * f + 0.5 - y0) / kf);
*px = if sx >= 0.5 && sy >= 0.5 && sx <= w as f64 - 0.5 && sy <= h as f64 - 0.5 {
img.sample_bilinear(sx as f32, sy as f32)
} else {
[f32::NAN; 3]
};
}
Some(out)
}
pub(super) fn sensor_proxy(raw: &RawImage, k: usize, edge: usize) -> Option<Rgb32f> {
Some(match raw.develop_binned(k, SENSOR_CLIP).ok()? {
Some(sensor) => sensor,
// Lens opcodes cannot be applied to a binned mosaic: they are defined at full resolution.
None if (raw.cpp == 3 && raw.cfa.is_none()) || (raw.format == RawFormat::Dng && !raw.opcodes.list3.is_empty()) => {
fit(&raw.develop(lightcraft_raw::Method::Bilinear).ok()?, edge, edge, Filter::Box)
}
None => return None,
})
}
File diff suppressed because it is too large. Load diff
+186
View File
@@ -0,0 +1,186 @@
use super::look_fit::dro_off;
use super::pairs::{Pairs, displayed, luma};
use super::{CameraTone, Rgb32f, ToneMap, luminance_2020};
/// How the per-photo tone curve is fitted ([`fit_pairs_ordered`] tries them in order).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum ToneFit {
/// [`fit_tone`]: no flat steps, no pixel-exact registration needed.
Quantile,
/// [`fit_tone_conditional`]: the earlier fit, kept as the fallback.
ConditionalMedian,
}
impl ToneFit {
pub(super) fn fit(self, pairs: Vec<(f64, f64)>) -> Option<CameraTone> {
match self {
ToneFit::Quantile => fit_tone(pairs),
ToneFit::ConditionalMedian => fit_tone_conditional(pairs),
}
}
}
/// The bright areas a narrow tone curve is checked against ([`highlights_hold`]): every proxy pixel
/// whose camera JPEG luminance is 0.85 or more, with its sensor value as developed (for a clipped
/// pixel a lower bound of the scene). Taken from the proxies before any training filter (clipped
/// pixels, edges, the sensor value range of [`collect_pairs`]), so no retry of the search can
/// leave them out.
pub(super) fn highlights(sensor: &Rgb32f, reference: &Rgb32f) -> Pairs {
if sensor.data.len() != reference.data.len() {
return Vec::new();
}
sensor
.data
.iter()
.zip(&reference.data)
.filter(|(x, y)| x.iter().chain(y.iter()).all(|v| v.is_finite() && *v >= 0.0) && luminance_2020(**y) >= 0.85)
.map(|(x, y)| (x.map(f64::from), y.map(f64::from)))
.collect()
}
/// Smallest ratio between the scene luminance of the brightest and of the darkest 1/32 of the
/// pairs a tone curve is fitted to (its last and first knot). Below it the training pairs are
/// nearly uniform (under 0.26 EV from their darker to their brighter parts): the curve would be
/// fitted to a sliver of the tone range and the rest of it extrapolated. Above it the acceptance
/// gates judge the curve. This was 1.5, which rejected low-contrast scenes the curve fits very
/// well: in a hazy ILCE-7RM4 burst the frames at 1.46–1.49 opened with the neutral fallback (no full or partial
/// look, 18 L* darker than the camera JPEG) while the frame at 1.51 fitted at a held-out RMS of
/// 0.013, as the others do once allowed (issue #631). Across 135 public Sony files the lowest is 4.0.
/// A curve under [`NARROW_TONE_RANGE`] must also pass [`highlights_hold`].
const MIN_TONE_RANGE: f32 = 1.2;
/// [`MIN_TONE_RANGE`] before issue #631. A curve fitted to a narrower range than this must also
/// render the photo's bright areas no further from the camera JPEG than the neutral fallback does
/// ([`highlights_hold`]). Neither the fit nor the held-out gates see those areas (camera JPEG
/// luminance 0.85 and up, left out of the training pairs by [`collect_pairs`]), and a curve fitted
/// to a sliver of the tone range extrapolates them: in review, a synthetic frame whose curve passed
/// the gates at a held-out RMS of 0.0004 rendered its bright sky at 0.29 where the camera JPEG has
/// 0.93.
const NARROW_TONE_RANGE: f32 = 1.5;
/// What a narrow tone curve is checked against ([`highlights_hold`]).
pub(super) struct HighlightCheck {
/// The frame's [`highlights`].
pub(super) pairs: Pairs,
/// The photo's curve will be lowered to Sony's without DRO ([`with_dro_off_tone`]) after the
/// fit, so the check looks at it lowered.
pub(super) dro: bool,
/// The camera JPEG is black and white ([`fit_tone_only_with`]): the check compares luminance, as that
/// fit's gates do, since the JPEG has no colour to match.
pub(super) grey: bool,
}
/// Whether a look with this `tone` and `colour` (sensor value to the finish stage's input) keeps
/// the frame's [`highlights`] (camera JPEG luminance 0.85 and up, left out of the fit) no further
/// from the camera JPEG than the neutral fallback does, with the tone curve as the photo will get
/// it (lowered for DRO), in luminance alone for a black-and-white JPEG. Only asked of curves narrower than
/// [`NARROW_TONE_RANGE`]: true for wider ones, and for frames without such pixels.
pub(super) fn highlights_hold(tone: &CameraTone, check: &HighlightCheck, colour: impl Fn([f64; 3]) -> [f64; 3]) -> bool {
let knots = tone.knots();
if knots[31][0] >= knots[0][0] * NARROW_TONE_RANGE {
return true;
}
// the curve as the photo will get it
let used = if check.dro { dro_off(tone) } else { *tone };
let (map, neutral) = (ToneMap::camera(&used, 0.0, 0.0, 0.0), ToneMap::new(0.0, 0.0, 0.0));
let (mut look, mut fallback) = (0.0, 0.0);
for (x, target) in &check.pairs {
let (rendered, base) = (displayed(colour(*x), &map), displayed(*x, &neutral));
if check.grey {
look += (luma(rendered) - luma(*target)).powi(2);
fallback += (luma(base) - luma(*target)).powi(2);
continue;
}
for c in 0..3 {
look += (rendered[c] - target[c]).powi(2);
fallback += (base[c] - target[c]).powi(2);
}
}
let hold = look.is_finite() && look <= fallback;
if !hold && lightcraft_pipeline::profiling() {
eprintln!("[profile] camera look: narrow tone curve renders the bright areas worse than the fallback ({look:.3} > {fallback:.3})");
}
hold
}
/// The camera's tone curve from scene/JPEG luminance pairs, by quantile matching: knot `i` pairs
/// the median of the `i`-th 1/32 of the sorted scene luminances with the median of the `i`-th
/// 1/32 of the sorted JPEG luminances. A tone curve is monotone, so it maps each quantile of the
/// scene to the same quantile of the JPEG; matching the two distributions needs no pixel-exact
/// registration and is increasing by construction.
///
/// Binning the pairs by scene luminance and taking the JPEG's median per bin instead (followed by
/// isotonic pooling) fails on real files: camera JPEGs are lens-corrected and sharpened, so on a
/// 96 px proxy of a busy scene neighbouring pairs disagree by more than the gap between bins.
/// The conditional medians then zig-zag, pooling turns them into flat steps (13 of 31 segments
/// on a Z 6II forest, issue #475) that render as posterised patches, and regression toward the
/// mean flattens both ends of the curve (lifted blacks, dull highlights).
pub(super) fn fit_tone(pairs: Vec<(f64, f64)>) -> Option<CameraTone> {
if pairs.len() < 128 || !pairs.iter().all(|(x, y)| x.is_finite() && *x > 0.0 && y.is_finite()) {
return None;
}
let mut xs: Vec<f64> = pairs.iter().map(|p| p.0).collect();
let mut ys: Vec<f64> = pairs.iter().map(|p| p.1).collect();
xs.sort_by(f64::total_cmp);
ys.sort_by(f64::total_cmp);
let n = xs.len();
let mut knots = [[0.0; 2]; 32];
for (i, knot) in knots.iter_mut().enumerate() {
let (a, b) = (i * n / 32, (i + 1) * n / 32);
let mid = a + (b - a) / 2;
*knot = [*xs.get(mid)? as f32, *ys.get(mid)? as f32];
}
if knots[31][0] < knots[0][0] * MIN_TONE_RANGE {
return None;
}
CameraTone::new(knots)
}
fn median(values: &mut [f64]) -> Option<f64> {
values.sort_by(f64::total_cmp);
values.get(values.len() / 2).copied()
}
/// The earlier tone fit, kept as the fallback of [`ToneFit`]: the JPEG's median per equal-population
/// bin of scene luminance, then pooled-adjacent-violators isotonic regression. It follows the
/// per-pixel pairs closely when the two images are registered, which is why it can clear the
/// acceptance gates where [`fit_tone`] just misses them, but on lens-corrected JPEGs of busy scenes
/// the pooling leaves flat steps (issue #475).
pub(super) fn fit_tone_conditional(mut pairs: Vec<(f64, f64)>) -> Option<CameraTone> {
if pairs.len() < 128 || !pairs.iter().all(|(x, y)| x.is_finite() && *x > 0.0 && y.is_finite()) {
return None;
}
pairs.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut knots = [[0.0; 2]; 32];
for (i, knot) in knots.iter_mut().enumerate() {
let bin = pairs.get(i * pairs.len() / 32..(i + 1) * pairs.len() / 32)?;
let mut xs: Vec<_> = bin.iter().map(|p| p.0).collect();
let mut ys: Vec<_> = bin.iter().map(|p| p.1).collect();
*knot = [median(&mut xs)? as f32, median(&mut ys)? as f32];
}
if knots[31][0] < knots[0][0] * MIN_TONE_RANGE {
return None;
}
// Pool adjacent violating bins (isotonic regression): no reversals or arbitrary polynomial.
let mut blocks: Vec<(f32, usize)> = Vec::new();
for knot in knots {
blocks.push((knot[1], 1));
while blocks.len() >= 2 {
let (a, an) = *blocks.get(blocks.len() - 2)?;
let (b, bn) = *blocks.last()?;
if a <= b {
break;
}
blocks.truncate(blocks.len() - 2);
blocks.push(((a * an as f32 + b * bn as f32) / (an + bn) as f32, an + bn));
}
}
let mut i = 0;
for (y, n) in blocks {
for knot in knots.get_mut(i..i + n)? {
knot[1] = y;
}
i += n;
}
CameraTone::new(knots)
}
+1
View File
@@ -28,6 +28,7 @@ pub const BUNDLED: &[(&str, &str)] = &[
("ILCA-99M2", include_str!("../../../assets/camera-profiles/ILCA-99M2.json")),
("ILCE-7CR", include_str!("../../../assets/camera-profiles/ILCE-7CR.json")),
("ILCE-7M4", include_str!("../../../assets/camera-profiles/ILCE-7M4.json")),
("ILCE-7RM5", include_str!("../../../assets/camera-profiles/ILCE-7RM5.json")),
("NIKON D5300", include_str!("../../../assets/camera-profiles/NIKON_D5300.json")),
("NIKON Z 6_2", include_str!("../../../assets/camera-profiles/NIKON_Z_6_2.json")),
("NIKON Z 8", include_str!("../../../assets/camera-profiles/NIKON_Z_8.json")),
File renamed without changes.
+1 -1
View File
@@ -20,7 +20,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Cancel Background Task",
[],
None,
"{id} | {all: true} → {cancelled: n} — ask a task (or every cancellable task) to stop; it stops at its next file or photo. An unknown id (it may have just finished) or a task that can't be cancelled is an error",
"{id} | {all: true} → {cancelled: n} — ask a task (or every cancellable task) to stop; it stops at its next file or photo (a preview build also stops between a photo's own previews). An unknown id (it may have just finished) or a task that can't be cancelled is an error",
always,
|s, p| {
const C: &str = "activity.cancel";
+2 -1
View File
@@ -35,8 +35,9 @@ fn browse(s: &mut Session, p: &Value) -> Result<Value> {
let mut v: Vec<String> = std::fs::read_dir(&dir)
.map_err(|e| bad(C, format!("{path}: {e}")))?
.flatten()
.filter(|e| !crate::walk::is_hidden_entry(e))
.map(|e| e.path())
.filter(|f| f.is_file() && is_supported(f) && !f.file_name().is_some_and(|n| n.to_string_lossy().starts_with('.')))
.filter(|f| f.is_file() && is_supported(f))
.map(|f| f.to_string_lossy().to_string())
.collect();
v.sort();
+26 -7
View File
@@ -9,10 +9,12 @@ use serde_json::{Value, json};
use super::{CommandSpec, always, cmd};
use crate::{Result, Session};
/// Seconds between shots of the same burst at most.
const BURST_GAP: i64 = 10;
/// Signature similarity for "the same scene".
const SAME: f32 = 0.93;
/// Seconds between shots of the same burst at most (default of `burstGap`).
const BURST_GAP: f64 = 10.0;
/// Signature similarity for "the same scene" (default of `similarity`).
const SAME: f64 = 0.93;
/// The longest `burstGap` accepted: a day.
const MAX_GAP: f64 = 86_400.0;
fn secs(iso: &str) -> Option<i64> {
let d = lightcraft_meta::DateTime::parse_iso(iso)?;
@@ -26,6 +28,7 @@ fn analyze(s: &mut Session, p: &Value) -> Result<Value> {
let ids: Vec<PhotoId> = ids.into_iter().filter(|id| seen.insert(*id)).collect();
let reject_below = p.get("rejectBelow").and_then(Value::as_f64).map(|v| v as f32);
let pick_best = p.get("pickBest").and_then(Value::as_bool).unwrap_or(false);
let (gap, same) = burst_params(p)?;
// measure (thumbnail-level sources: fast, and enough for focus at 512 px)
let mut rows: Vec<(PhotoId, Option<i64>, f32, f32, [f32; 64])> = Vec::new();
let mut failed = Vec::new();
@@ -45,8 +48,8 @@ fn analyze(s: &mut Session, p: &Value) -> Result<Value> {
let mut next = 1u32;
for i in 1..rows.len() {
let (a, b) = (&rows[i - 1], &rows[i]);
let close = matches!((a.1, b.1), (Some(x), Some(y)) if (y - x).abs() <= BURST_GAP);
if close && lightcraft_pipeline::cull::similarity(&a.4, &b.4) >= SAME {
let close = matches!((a.1, b.1), (Some(x), Some(y)) if (y.saturating_sub(x)).unsigned_abs() as f64 <= gap);
if close && lightcraft_pipeline::cull::similarity(&a.4, &b.4) >= same {
let g = *group_of[i - 1].get_or_insert_with(|| {
next += 1;
next - 1
@@ -86,6 +89,22 @@ fn analyze(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"photos": out, "groups": best.len(), "rejected": rejected, "picked": picked, "failed": failed}))
}
/// `burstGap` (seconds, 0..=a day) and `similarity` (0..=1) of `photo.analyze`, refused before
/// anything is measured when they are not numbers in range.
fn burst_params(p: &Value) -> Result<(f64, f32)> {
const C: &str = "photo.analyze";
let num = |key: &str, d: f64, max: f64| -> Result<f64> {
match p.get(key) {
None | Some(Value::Null) => Ok(d),
Some(v) => match v.as_f64() {
Some(x) if x.is_finite() && (0.0..=max).contains(&x) => Ok(x),
_ => Err(super::bad(C, format!("`{key}` must be a number from 0 to {max}"))),
},
}
};
Ok((num("burstGap", BURST_GAP, MAX_GAP)?, num("similarity", SAME, 1.0)? as f32))
}
/// Find Similar: photos that look like `id` (signatures from thumbnail-level sources, cached by
/// content), most similar first; the view is filtered to them.
fn find_similar(s: &mut Session, p: &Value) -> Result<Value> {
@@ -139,7 +158,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Assisted Culling",
[],
None,
"{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots taken within 10 s and mark the sharpest of each; optionally reject blurry photos and pick each group's best; one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, rejected, picked}",
"{ids?, rejectBelow?: sharpness 0..100, pickBest?: bool, burstGap?: seconds 0..86400 (10), similarity?: 0..1 (0.93)} — score the selected photos (else all in view) for focus (0..100) and clipping, group look-alike shots (signature similarity at least `similarity`) taken at most `burstGap` seconds apart and mark the sharpest of each; optionally reject blurry photos and pick each group's best; one undo step → {photos: [{id, sharpness, clipped, group, best}], groups, rejected, picked}",
always,
analyze
),
+22 -9
View File
@@ -129,16 +129,18 @@ fn identify(path: &Path, c: &str, sha_known: Option<&str>) -> Result<Source> {
/// Install the model in `src`. A model that passes its self-test becomes the one in use (`activate`, the default): installing
/// a model is how someone says they want it. `verified` is for a download whose hash was already checked.
fn install_file(
dir: &Path,
loader: &crate::denoise::Loader,
struct InstallFile<'a> {
dir: &'a Path,
run_on: RunOn,
accepted_at: String,
c: &str,
src: &Path,
command: &'a str,
src: &'a Path,
acknowledged: bool,
verified: bool,
) -> Result<(Value, Arc<dyn crate::denoise::Model>)> {
}
fn install_file(loader: &crate::denoise::Loader, request: InstallFile<'_>) -> Result<(Value, Arc<dyn crate::denoise::Model>)> {
let InstallFile { dir, run_on, accepted_at, command: c, src, acknowledged, verified } = request;
let ident = identify(src, c, None)?;
let m = ident.manifest.clone();
manifest::validate(&m).map_err(|e| bad(c, e.to_string()))?;
@@ -262,7 +264,8 @@ fn start_install(s: &mut Session, src: PathBuf, id: String, activate: bool, veri
.spawn(move || {
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _held = crate::memory::work_gate().acquire(512 * 1024 * 1024);
install_file(&dir, &loader, run_on, at, C, &src, true, verified).map_err(|e| plain(&e))
install_file(&loader, InstallFile { dir: &dir, run_on, accepted_at: at, command: C, src: &src, acknowledged: true, verified })
.map_err(|e| plain(&e))
}))
.unwrap_or_else(|_| Err("the model installation stopped unexpectedly".into()));
if verified {
@@ -290,8 +293,18 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
if s.denoise.install.is_some() {
return Err(bad(C, "another model is being installed"));
}
let (result, model) =
install_file(&models_dir(s, C)?, &s.denoise.loader, s.denoise.settings.run_on(), (s.clock)(), C, Path::new(path), acknowledged, false)?;
let (result, model) = install_file(
&s.denoise.loader,
InstallFile {
dir: &models_dir(s, C)?,
run_on: s.denoise.settings.run_on(),
accepted_at: (s.clock)(),
command: C,
src: Path::new(path),
acknowledged,
verified: false,
},
)?;
activate_install(s, &result, model, activate)
}
+4 -1
View File
@@ -192,7 +192,10 @@ mod download {
use lightcraft_geocode::{GEONAMES_BASE, GEONAMES_ZIP};
use super::*;
use super::{
Cancel, DownloadOutcome, GEONAMES_ATTRIBUTION, GEONAMES_FILES, GeoNames, PoisonError, Result, Session, Value, bad, dataset_dir, json,
str_param,
};
use crate::activity::Unit;
const MAX_ZIP: u64 = 64 * 1024 * 1024;
+32 -1
View File
@@ -154,6 +154,16 @@ pub fn keyword_sets_json(s: &Session) -> Value {
json!({"sets": sets, "current": s.keyword_set.clone().unwrap_or_else(|| RECENT.into()), "keywords": current_keywords(s)})
}
/// Make the set `step` places after the current one current, in the Keyword Set menu's order
/// (Recent Keywords, then the saved sets), wrapping around from the last to the first and back.
fn step_set(s: &mut Session, step: isize) -> Result<Value> {
let at = s.keyword_set.as_deref().and_then(|n| s.keyword_sets.iter().position(|x| same_set(&x.name, n))).map_or(0, |i| i + 1);
let next = (at as isize + step).rem_euclid(s.keyword_sets.len() as isize + 1) as usize;
s.keyword_set = next.checked_sub(1).and_then(|i| s.keyword_sets.get(i)).map(|x| x.name.clone());
s.save_prefs()?;
Ok(keyword_sets_json(s))
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(query "keyword.sets", "Keyword Sets", [], None, "{} → {sets: [{name, keywords}], current, keywords: the nine ⌥1–⌥9 apply}", always, |s, _| Ok(keyword_sets_json(s))),
@@ -174,6 +184,24 @@ pub fn specs() -> Vec<CommandSpec> {
s.save_prefs()?;
Ok(keyword_sets_json(s))
}),
cmd!(
"keyword.nextSet",
"Next Keyword Set",
[],
Some("Alt+0"),
"{}: the set after the current one (after the last, Recent Keywords)",
always,
|s, _| step_set(s, 1)
),
cmd!(
"keyword.previousSet",
"Previous Keyword Set",
[],
Some("Alt+Shift+0"),
"{}: the set before the current one (before Recent Keywords, the last)",
always,
|s, _| step_set(s, -1)
),
cmd!(
"keyword.saveSet",
"Save Keyword Set",
@@ -451,7 +479,10 @@ pub fn specs() -> Vec<CommandSpec> {
let mut r = json!({"keywords": file.written.len(), "captureOneRefuses": refuses, "unwritable": file.unwritable});
match str_param(p, "path").map(str::trim).filter(|x| !x.is_empty()) {
Some(path) => {
std::fs::write(path, &file.text).map_err(|e| crate::EngineError::Other(format!("{path}: {e}")))?;
s.check_write_target(path).map_err(|e| bad("keyword.export", e))?;
// A folder that isn't there is an error, not created.
lightcraft_catalog::safe_file::write_atomic(std::path::Path::new(path), file.text.as_bytes())
.map_err(|e| crate::EngineError::Other(format!("{path}: {e}")))?;
r["path"] = json!(path);
}
None => r["text"] = json!(file.text),
Loaded 100 of 656 files, more files were not shown because too many files have changed in this diff. Show more