mirror of
https://github.com/storytold/lightcraft.git
synced 2026-12-05 13:32:52 -05:00
Merge remote-tracking branch 'upstream/main' into HEAD
# Conflicts: # crates/ui-egui/src/panels/edit.rs # docs/parity-checklist.md
This commit is contained in:
commit
9f7d4bcc14
532 files changed
+101328
-66904
No files matched your search
@@ -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: ""
|
||||
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
Generated
+1198
-304
File diff suppressed because it is too large.
Load diff
+31
-8
@@ -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.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 }
|
||||
@@ -61,7 +63,7 @@ dhat = "0.3" # opt-in heap profiling (lightcraft-cli --features dhat-heap) and h
|
||||
|
||||
# formats
|
||||
quick-xml = "0.41"
|
||||
miniz_oxide = "0.8"
|
||||
miniz_oxide = "0.9"
|
||||
|
||||
# codecs
|
||||
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tiff", "webp"] }
|
||||
@@ -91,10 +93,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)
|
||||
@@ -169,3 +174,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" }
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -305,7 +305,7 @@ LightCraft 很年轻,而且进展很快。**我们如实所处的位置**(
|
||||
- **作为日常使用的工具,我们更接近 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 显示、视频,以及经典版式中的打印/画册/地图模块。**
|
||||
|
||||
+1
-1
@@ -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);
|
||||
|
||||
@@ -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()
|
||||
})),
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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 }
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,10 @@
|
||||
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;
|
||||
|
||||
@@ -168,6 +168,9 @@ 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();
|
||||
@@ -228,7 +231,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| {
|
||||
@@ -271,7 +279,7 @@ 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;
|
||||
}
|
||||
}
|
||||
@@ -414,7 +422,37 @@ struct WebApp {
|
||||
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();
|
||||
@@ -470,7 +508,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();
|
||||
@@ -496,7 +539,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,
|
||||
@@ -515,25 +558,31 @@ impl WebApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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());
|
||||
// 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 !dropped.is_empty() && self.app.ui.dialog.is_some() {
|
||||
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 dropped {
|
||||
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) => 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() {
|
||||
match self.app.run("library.import", json!({"paths": paths})) {
|
||||
// what the import did, not what was submitted: duplicates and unsupported files add nothing,
|
||||
@@ -587,7 +636,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();
|
||||
@@ -677,13 +726,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
|
||||
@@ -692,26 +742,22 @@ 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());
|
||||
@@ -721,6 +767,22 @@ impl eframe::App for WebApp {
|
||||
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());
|
||||
|
||||
@@ -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 }
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
use super::prefs::config_dir;
|
||||
use super::*;
|
||||
|
||||
/// 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()
|
||||
))
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
}
|
||||
+30
-1263
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,11 @@
|
||||
//! - 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};
|
||||
@@ -480,17 +485,21 @@ 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);
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
use super::*;
|
||||
|
||||
/// 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
#[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 {
|
||||
// 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())))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
@@ -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
@@ -2,3 +2,6 @@ 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)" },
|
||||
]
|
||||
@@ -70,3 +70,7 @@ sync_github_name = true
|
||||
|
||||
[people.ronibalthazar]
|
||||
sync_github_name = true
|
||||
|
||||
[people.dotCooCoo]
|
||||
real_name = "Robert Lee"
|
||||
sync_github_name = true
|
||||
@@ -822,714 +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");
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -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);
|
||||
}
|
||||
+26
-40
@@ -1098,55 +1098,41 @@ impl Catalog {
|
||||
}
|
||||
st.photos.len() >= 2
|
||||
});
|
||||
let parents: Vec<(AlbumId, Option<AlbumId>)> = self.albums.values().map(|a| (a.id, a.parent)).collect();
|
||||
// A folder chain is shared by every album under it, so each chain is validated once and its
|
||||
// verdict is what later albums reused: a valid chain encoded in a flat snapshot made the old
|
||||
// per-album walk quadratic in the album count (CWE-407).
|
||||
enum Chain {
|
||||
Ok,
|
||||
Bad,
|
||||
}
|
||||
let mut chains: std::collections::HashMap<AlbumId, Chain> = std::collections::HashMap::new();
|
||||
for (id, parent) in parents {
|
||||
let Some(p) = parent else { continue };
|
||||
if chains.contains_key(&id) {
|
||||
continue;
|
||||
}
|
||||
// Walk up from `p` once, recording everything seen; what it reaches decides every node
|
||||
// walked (a chain already judged by an earlier album stops the walk early — the rest of
|
||||
// the chain was judged then).
|
||||
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 ok = {
|
||||
let mut cur = Some(p);
|
||||
let broken = {
|
||||
let mut cur = id;
|
||||
let mut on: std::collections::HashSet<AlbumId> = std::collections::HashSet::new();
|
||||
loop {
|
||||
match cur {
|
||||
None => break true,
|
||||
Some(c) => {
|
||||
if c == id || !on.insert(c) {
|
||||
break false;
|
||||
}
|
||||
match chains.get(&c) {
|
||||
Some(Chain::Bad) => break false,
|
||||
Some(Chain::Ok) => break true,
|
||||
None => {}
|
||||
}
|
||||
match self.albums.get(&c) {
|
||||
Some(a) if a.folder => walked.push(c),
|
||||
_ => break false,
|
||||
}
|
||||
cur = self.albums[&c].parent;
|
||||
}
|
||||
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;
|
||||
}
|
||||
};
|
||||
for c in walked {
|
||||
chains.insert(c, if ok { Chain::Ok } else { Chain::Bad });
|
||||
}
|
||||
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) = (
|
||||
|
||||
+1
-786
@@ -1179,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;
|
||||
@@ -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 +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]
|
||||
|
||||
@@ -24,3 +24,4 @@ web-time = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
dhat = { workspace = true }
|
||||
@@ -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()))
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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")
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -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));
|
||||
}
|
||||
+41
-4498
File diff suppressed because it is too large.
Load diff
@@ -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::*;
|
||||
|
||||
/// 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)
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
use super::mono::to_prophoto;
|
||||
use super::pairs::{displayed, luma};
|
||||
use super::*;
|
||||
|
||||
/// [`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::*;
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
@@ -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::*;
|
||||
|
||||
/// 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())
|
||||
}
|
||||
@@ -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::*;
|
||||
|
||||
/// 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)
|
||||
}
|
||||
@@ -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::*;
|
||||
|
||||
/// 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(¢er[0]) && (0.0..=1.0).contains(¢er[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
@@ -0,0 +1,186 @@
|
||||
use super::look_fit::dro_off;
|
||||
use super::pairs::{Pairs, displayed, luma};
|
||||
use super::*;
|
||||
|
||||
/// 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)
|
||||
}
|
||||
@@ -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.
@@ -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";
|
||||
|
||||
@@ -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",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,92 @@
|
||||
use super::*;
|
||||
|
||||
/// `base` with a partial Filter (JSON) merged on top.
|
||||
/// `patch` merged onto `base`, its rules brought up to date (`RuleSet::upgrade`), unchecked (see
|
||||
/// [`merge_rules`]).
|
||||
fn merge_filter(base: &lightcraft_catalog::Filter, patch: &Value, c: &str) -> Result<lightcraft_catalog::Filter> {
|
||||
let mut v = serde_json::to_value(base).unwrap_or_default();
|
||||
lightcraft_develop::presets::deep_merge(&mut v, patch);
|
||||
let mut f: lightcraft_catalog::Filter = serde_json::from_value(v).map_err(|e| bad(c, e.to_string()))?;
|
||||
if let Some(rules) = f.rule_set.as_mut() {
|
||||
rules.upgrade();
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// `patch` merged onto `base`, refused when the rule set it sets has problems (`RuleSet::check_for`;
|
||||
/// `owner` is the smart album the rules are for, so testing an album that leads back to it is a
|
||||
/// problem too).
|
||||
pub(super) fn merge_rules(
|
||||
base: &lightcraft_catalog::Filter,
|
||||
patch: &Value,
|
||||
c: &str,
|
||||
cat: &lightcraft_catalog::Catalog,
|
||||
owner: Option<AlbumId>,
|
||||
) -> Result<lightcraft_catalog::Filter> {
|
||||
let f = merge_filter(base, patch, c)?;
|
||||
// only rules this change sets are checked: one that stopped checking since (its album was
|
||||
// deleted) doesn't block editing the album's other settings
|
||||
let sets_rules = patch.get("ruleSet").is_some_and(|r| !r.is_null());
|
||||
let mut problems = f.rule_set.as_ref().filter(|_| sets_rules).map(|r| r.check_for(cat, owner)).unwrap_or_default();
|
||||
// and a loop through the album field the change sets
|
||||
if patch.get("album").is_some_and(|a| !a.is_null()) {
|
||||
problems.extend(cat.album_filter_problem(&f, owner));
|
||||
}
|
||||
if !problems.is_empty() {
|
||||
return Err(bad(c, problems.iter().map(ToString::to_string).collect::<Vec<_>>().join("; ")));
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
/// Whether `path` lies above a disk: some of its `ids` photos are on a disk (not the startup
|
||||
/// disk) that the folder does not lie in. Such a folder (`/Volumes`, `/mnt`…) is not a folder of
|
||||
/// one disk but a way to reach several.
|
||||
pub(crate) fn covers_other_disks(s: &Session, path: &str, ids: &[PhotoId]) -> bool {
|
||||
ids.iter()
|
||||
.filter_map(|id| s.catalog.photo(*id))
|
||||
.filter_map(|p| lightcraft_catalog::folders::volume_of(p))
|
||||
.any(|v| v != "/" && !lightcraft_catalog::query::folder_within(path, &v))
|
||||
}
|
||||
|
||||
/// The current view (source + filter) as smart-album rules. Viewing a smart album starts from
|
||||
/// its rules with the filter bar's settings on top.
|
||||
pub(super) fn view_rules(s: &Session) -> lightcraft_catalog::Filter {
|
||||
use lightcraft_catalog::Filter;
|
||||
let smart = match s.source {
|
||||
LibrarySource::Album(a) => s.catalog.album(a).and_then(|a| a.smart.as_deref().cloned()),
|
||||
_ => None,
|
||||
};
|
||||
match smart {
|
||||
Some(base) => {
|
||||
// overlay the fields the filter bar changed
|
||||
let cur = serde_json::to_value(&s.filter).unwrap_or_default();
|
||||
let def = serde_json::to_value(Filter::default()).unwrap_or_default();
|
||||
let mut patch = serde_json::Map::new();
|
||||
if let (Some(c), Some(d)) = (cur.as_object(), def.as_object()) {
|
||||
for (k, v) in c {
|
||||
if d.get(k) != Some(v) {
|
||||
patch.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
// the view as it is: a rule that no longer checks (its album was deleted) just matches
|
||||
// nothing there, and mustn't cost the filter bar's settings
|
||||
merge_filter(&base, &Value::Object(patch), "").unwrap_or(base)
|
||||
}
|
||||
None => {
|
||||
let mut f = s.source.to_filter(&s.filter, &s.catalog);
|
||||
f.deleted = false;
|
||||
if s.source == LibrarySource::LibraryFolder {
|
||||
f.library_folder = s.library_folder.clone();
|
||||
}
|
||||
f
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The current view (source + filter) as smart-album rules (see `album.createSmart`).
|
||||
pub fn view_rules(&self) -> lightcraft_catalog::Filter {
|
||||
view_rules(self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/// Coordinates typed by a person: "51.5072, -0.1276", "51.5072 N 0.1276 W",
|
||||
/// "51°30'26\"N 0°7'39\"W" (degrees, minutes, seconds; N/S/E/W or signs).
|
||||
pub(crate) fn parse_gps(t: &str) -> Option<(f64, f64)> {
|
||||
// typographic minus signs and dashes mean a negative value, like ASCII '-'
|
||||
let t = t.replace(['\u{2212}', '\u{2012}', '\u{2013}', '\u{FE63}', '\u{FF0D}'], "-");
|
||||
let t = t.trim();
|
||||
// split into the two coordinates: at a comma, else after the first N/S hemisphere letter
|
||||
let (a, b) = match t.split_once(',') {
|
||||
Some((a, b)) => (a.trim().to_string(), b.trim().to_string()),
|
||||
None => {
|
||||
let lead = t.starts_with(['N', 'S', 'n', 's']);
|
||||
let i = if lead {
|
||||
// hemisphere letter first: "N 51.5 W 0.1" splits at the E/W letter
|
||||
t.char_indices().skip(1).find(|(_, c)| matches!(c, 'E' | 'W' | 'e' | 'w')).map(|(i, _)| i)
|
||||
} else {
|
||||
t.find(['N', 'S', 'n', 's']).map(|i| i + 1)
|
||||
}
|
||||
.or_else(|| t.find(char::is_whitespace))?;
|
||||
(t[..i].trim().to_string(), t[i..].trim().to_string())
|
||||
}
|
||||
};
|
||||
let one = |s: &str, pos: char, neg: char| -> Option<f64> {
|
||||
let up = s.to_ascii_uppercase();
|
||||
let sign = if up.contains(neg) || up.trim_start().starts_with('-') { -1.0 } else { 1.0 };
|
||||
let nums: Vec<f64> =
|
||||
up.split(|c: char| !(c.is_ascii_digit() || c == '.')).filter(|x| !x.is_empty()).map(|x| x.parse::<f64>().ok()).collect::<Option<_>>()?;
|
||||
let v = match nums.as_slice() {
|
||||
[d] => *d,
|
||||
[d, m] => d + m / 60.0,
|
||||
[d, m, s] => d + m / 60.0 + s / 3600.0,
|
||||
_ => return None,
|
||||
};
|
||||
let _ = pos;
|
||||
Some(sign * v)
|
||||
};
|
||||
let (la, lo) = (one(&a, 'N', 'S')?, one(&b, 'E', 'W')?);
|
||||
(la.abs() <= 90.0 && lo.abs() <= 180.0).then_some((la, lo))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod gps_tests {
|
||||
#[test]
|
||||
fn coordinates_people_type() {
|
||||
let p = super::parse_gps;
|
||||
assert_eq!(p("51.5072, -0.1276"), Some((51.5072, -0.1276)));
|
||||
let (la, lo) = p("51°30'26\"N 0°7'39\"W").unwrap();
|
||||
assert!((la - 51.50722).abs() < 1e-4 && (lo + 0.1275).abs() < 1e-4, "{la} {lo}");
|
||||
let (la, lo) = p("33.8688 S, 151.2093 E").unwrap();
|
||||
assert!((la + 33.8688).abs() < 1e-9 && (lo - 151.2093).abs() < 1e-9);
|
||||
assert_eq!(p("51.5 N 0.1 W"), Some((51.5, -0.1)));
|
||||
assert_eq!(p("N 51.5072 W 0.1276"), Some((51.5072, -0.1276)));
|
||||
assert_eq!(p("S 33.8688 E 151.2093"), Some((-33.8688, 151.2093)));
|
||||
assert_eq!(p("\u{2212}33.8688, 151.2093"), Some((-33.8688, 151.2093)));
|
||||
assert_eq!(p("95, 10"), None);
|
||||
assert_eq!(p("hello"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
use super::selection::strs;
|
||||
use super::*;
|
||||
|
||||
/// The auto-import folder's visible files with their sizes (the file-system half of
|
||||
/// `library.autoImportScan`; the app lists on a worker thread and passes `listing`).
|
||||
pub fn list_auto_import_folder(folder: &str) -> std::result::Result<Vec<(String, u64)>, String> {
|
||||
let rd = std::fs::read_dir(folder).map_err(|e| format!("{folder}: {e}"))?;
|
||||
Ok(rd
|
||||
.flatten()
|
||||
.filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
|
||||
.filter_map(|e| {
|
||||
let m = std::fs::metadata(e.path()).ok()?;
|
||||
m.is_file().then(|| (e.path().to_string_lossy().to_string(), m.len()))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// `library.import`'s params, checked (no file-system calls).
|
||||
pub struct ImportRequest {
|
||||
pub paths: Vec<String>,
|
||||
pub opts: crate::import::ImportOptions,
|
||||
pub album: Option<u64>,
|
||||
pub album_name: Option<String>,
|
||||
}
|
||||
|
||||
/// Parse and check `library.import`'s params (the app's import task runs the import itself, on a
|
||||
/// worker thread, with the same options).
|
||||
pub fn import_params(s: &Session, p: &Value) -> Result<ImportRequest> {
|
||||
let paths = strs(p, "paths");
|
||||
let mode = match str_param(p, "mode").unwrap_or("add") {
|
||||
"add" => crate::import::ImportMode::Add,
|
||||
"copy" => crate::import::ImportMode::Copy,
|
||||
"move" => crate::import::ImportMode::Move,
|
||||
other => return Err(bad("library.import", format!("unknown mode `{other}` (add|copy|move)"))),
|
||||
};
|
||||
let preset = match str_param(p, "preset").filter(|x| !x.is_empty()) {
|
||||
Some(id) => Some(s.presets.iter().find(|x| x.id == id).cloned().ok_or_else(|| bad("library.import", format!("unknown preset `{id}`")))?),
|
||||
None => None,
|
||||
};
|
||||
let album = p.get("album").and_then(Value::as_u64);
|
||||
if let Some(a) = album
|
||||
&& s.catalog.album(AlbumId(a)).is_none_or(|al| al.folder || al.is_smart())
|
||||
{
|
||||
return Err(bad("library.import", "album must be a regular album"));
|
||||
}
|
||||
let organize = match str_param(p, "organize") {
|
||||
Some(o) => crate::import::Organize::parse(o).ok_or_else(|| {
|
||||
bad("library.import", format!("unknown organize `{o}` (date|month|flat, or a folder template like {{date:%Y}}/{{date:%Y%m%d}})"))
|
||||
})?,
|
||||
None => Default::default(),
|
||||
};
|
||||
if let crate::import::Organize::Template(t) = &organize
|
||||
&& let Some(e) = crate::rename::folder_template_error(t)
|
||||
{
|
||||
return Err(bad("library.import", e));
|
||||
}
|
||||
let metadata_preset = str_param(p, "metadataPreset").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
|
||||
if let Some(n) = &metadata_preset
|
||||
&& !s.metadata_presets.iter().any(|m| m.name.eq_ignore_ascii_case(n))
|
||||
{
|
||||
return Err(bad("library.import", format!("unknown metadata preset `{n}`")));
|
||||
}
|
||||
let on_deleted = match str_param(p, "onDeleted") {
|
||||
Some(v) => {
|
||||
crate::import::OnDeleted::parse(v).ok_or_else(|| bad("library.import", format!("unknown onDeleted `{v}` (restore|skip|fresh)")))?
|
||||
}
|
||||
None => Default::default(),
|
||||
};
|
||||
let opts = crate::import::ImportOptions {
|
||||
on_deleted,
|
||||
mode,
|
||||
preset,
|
||||
keywords: strs(p, "keywords"),
|
||||
destination: str_param(p, "destination").map(str::to_string),
|
||||
organize,
|
||||
rename: str_param(p, "rename").map(str::to_string),
|
||||
rename_start: p.get("renameStart").and_then(Value::as_u64).unwrap_or(1) as usize,
|
||||
metadata_preset,
|
||||
convert_dng: bool_or(p, "dng", false),
|
||||
local: bool_or(p, "local", false),
|
||||
};
|
||||
let album_name = str_param(p, "albumName").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string);
|
||||
Ok(ImportRequest { paths, opts, album, album_name })
|
||||
}
|
||||
|
||||
/// After a batch of an import was committed: the album (a new one named `album_name` when there
|
||||
/// is no `album` and something was imported) gets the photos. Returns the report as JSON (with
|
||||
/// `album`).
|
||||
pub fn import_batch_done(s: &mut Session, report: crate::import::ImportReport, mut album: Option<u64>, album_name: Option<&str>) -> Result<Value> {
|
||||
let mut report = serde_json::to_value(report).unwrap_or_default();
|
||||
// photos an import restored from Recently Deleted take part like new ones (album, selection)
|
||||
let imported: Vec<u64> =
|
||||
["imported", "restored"].iter().flat_map(|k| report[*k].as_array().into_iter().flatten().filter_map(Value::as_u64)).collect();
|
||||
if album.is_none()
|
||||
&& let Some(name) = album_name
|
||||
&& !imported.is_empty()
|
||||
{
|
||||
let r = s.execute("album.create", &json!({"name": name}))?;
|
||||
album = r["id"].as_u64();
|
||||
}
|
||||
if let Some(a) = album
|
||||
&& !imported.is_empty()
|
||||
{
|
||||
// (album.addPhotos wants a selection: the new photos are about to be it)
|
||||
s.selection = Selection::single(PhotoId(imported[0]));
|
||||
s.execute("album.addPhotos", &json!({"id": a, "ids": imported}))?;
|
||||
report["album"] = json!(a);
|
||||
}
|
||||
Ok(report)
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
use super::*;
|
||||
|
||||
/// The selection after photos left the view (deleted, or rated, flagged or labelled out of it).
|
||||
/// Its callers end an open edit (a slider drag) before their own change, as moving to the next
|
||||
/// photo does, so it is its own undo step and comes first.
|
||||
pub(super) fn select_after_deletion(s: &mut Session, before: &[PhotoId]) {
|
||||
let at = before.iter().position(|id| Some(*id) == s.selection.active);
|
||||
let remaining: std::collections::HashSet<_> = s.visible_cloned().into_iter().collect();
|
||||
s.selection.ids.retain(|id| remaining.contains(id));
|
||||
s.selection.active = s.selection.active.filter(|id| remaining.contains(id)).or_else(|| s.selection.ids.first().copied());
|
||||
if s.selection.active.is_none()
|
||||
&& let Some(at) = at
|
||||
{
|
||||
// Keep culling near the deleted photo: next visible survivor, or the previous one at the end.
|
||||
let neighbour = before.iter().skip(at.saturating_add(1)).chain(before.iter().take(at).rev()).find(|id| remaining.contains(id));
|
||||
s.selection = neighbour.map(|id| Selection::single(*id)).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn album_param(p: &Value, key: &str, c: &str) -> Result<AlbumId> {
|
||||
p.get(key).and_then(Value::as_u64).map(AlbumId).ok_or_else(|| bad(c, format!("missing album `{key}`")))
|
||||
}
|
||||
|
||||
/// An optional album id: absent or `null` is `None`, anything but a number is an error.
|
||||
pub(super) fn opt_album_param(p: &Value, key: &str, c: &str) -> Result<Option<AlbumId>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) => v.as_u64().map(|n| Some(AlbumId(n))).ok_or_else(|| bad(c, format!("`{key}` must be an album id or null"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn strs(p: &Value, key: &str) -> Vec<String> {
|
||||
p.get(key).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The targets an album can hold and how many were browsed (Local) photos, which album views
|
||||
/// never show (issue #684): those are skipped, and reported, instead of becoming invisible members.
|
||||
pub(super) fn album_targets(s: &Session, targets: Vec<PhotoId>) -> (Vec<PhotoId>, usize) {
|
||||
let before = targets.len();
|
||||
let kept: Vec<PhotoId> = targets.into_iter().filter(|id| s.catalog.photo(*id).is_none_or(|p| !p.local)).collect();
|
||||
let skipped = before - kept.len();
|
||||
(kept, skipped)
|
||||
}
|
||||
|
||||
/// Album targets, or the error for a selection that was nothing but Local photos.
|
||||
pub(super) fn album_targets_or_err(s: &Session, command: &str, targets: Vec<PhotoId>) -> Result<(Vec<PhotoId>, usize)> {
|
||||
let (kept, skipped) = album_targets(s, targets);
|
||||
if kept.is_empty() && skipped > 0 {
|
||||
return Err(bad(command, crate::cmd::LOCAL_ONLY));
|
||||
}
|
||||
Ok((kept, skipped))
|
||||
}
|
||||
|
||||
/// Move to Recently Deleted and drop the photos from stacks so leftover members do not keep
|
||||
/// showing `i/n` (issue #1493).
|
||||
pub(super) fn mark_deleted(s: &mut Session, ids: &[PhotoId], label: &str) -> Result<usize> {
|
||||
let mut ops: Vec<Op> = ids.iter().map(|id| Op::SetDeleted { id: *id, deleted: true }).collect();
|
||||
let n = ops.len();
|
||||
if n == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
ops.extend(s.catalog.remove_from_stacks_ops(ids));
|
||||
s.commit(label, Op::Batch { ops })?;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Apply one op per target as a single undo step.
|
||||
pub(super) fn for_targets(s: &mut Session, p: &Value, label: &str, f: impl Fn(PhotoId) -> Option<Op>) -> Result<Value> {
|
||||
let targets = s.targets(p)?;
|
||||
let ops: Vec<Op> = targets.iter().filter_map(|id| f(*id)).collect();
|
||||
let n = ops.len();
|
||||
if n > 0 {
|
||||
s.commit(label, Op::Batch { ops })?;
|
||||
}
|
||||
Ok(json!({"changed": n}))
|
||||
}
|
||||
|
||||
/// Adjust each target's own rating; unchanged bounds do not create an undo step.
|
||||
pub(super) fn change_rating(s: &mut Session, p: &Value, delta: i8, label: &str) -> Result<Value> {
|
||||
let mut ops = Vec::new();
|
||||
for id in s.targets(p)? {
|
||||
let old = s.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?.rating;
|
||||
let rating = (i16::from(old) + i16::from(delta)).clamp(0, 5) as u8;
|
||||
if rating != old {
|
||||
ops.push(Op::SetRating { id, rating });
|
||||
}
|
||||
}
|
||||
let n = ops.len();
|
||||
if n > 0 {
|
||||
s.commit(label, Op::Batch { ops })?;
|
||||
}
|
||||
Ok(json!({"changed": n}))
|
||||
}
|
||||
|
||||
/// Move each target's own flag by `step`: cycling wraps unflagged -> pick -> reject -> unflagged,
|
||||
/// raising/lowering clamps on reject < unflagged < pick. Unchanged photos make no history step.
|
||||
pub(super) fn change_flag(s: &mut Session, p: &Value, label: &str, step: impl Fn(Flag) -> Flag) -> Result<Value> {
|
||||
let mut ops = Vec::new();
|
||||
for id in s.targets(p)? {
|
||||
let old = s.catalog.photo(id).ok_or(lightcraft_catalog::CatalogError::NoPhoto(id))?.flag;
|
||||
let flag = step(old);
|
||||
if flag != old {
|
||||
ops.push(Op::SetFlag { id, flag });
|
||||
}
|
||||
}
|
||||
let n = ops.len();
|
||||
if n > 0 {
|
||||
s.commit(label, Op::Batch { ops })?;
|
||||
}
|
||||
Ok(json!({"changed": n}))
|
||||
}
|
||||
|
||||
/// Rate, flag or label (`edit`), then `advance`. When the edit took the active photo out of the view (the filter bar,
|
||||
/// Picks or a smart album shows it no more), culling goes on from its place, as after a delete: the photo after it is
|
||||
/// active, or the one before it at the end (#2312), not the view's first photo. That photo is the next one, so
|
||||
/// `advance` doesn't step past it. Photos named by `ids` / `id` leave the selection to the caller: Compare and Survey
|
||||
/// keep showing the photo they rate.
|
||||
pub(super) fn cull(s: &mut Session, p: &Value, edit: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Value> {
|
||||
let named = [p.get("ids"), p.get("id")].into_iter().any(|t| t.is_some_and(|t| !t.is_null()));
|
||||
// the view as it was, then an open drag ends first, as its own undo step (the selection may
|
||||
// move on; the drag itself can take the photo out of the view)
|
||||
let before = (!named).then(|| s.visible_shared().1);
|
||||
if !named {
|
||||
s.end_interaction()?;
|
||||
}
|
||||
let active = s.selection.active;
|
||||
let v = edit(s)?;
|
||||
if let Some(before) = before
|
||||
&& active.is_some_and(|a| before.contains(&a) && !s.visible().contains(&a))
|
||||
{
|
||||
select_after_deletion(s, &before);
|
||||
s.active_mask = None;
|
||||
s.active_spot = None;
|
||||
} else {
|
||||
advance_if(s, p);
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn advance_if(s: &mut Session, p: &Value) {
|
||||
if bool_or(p, "advance", false) {
|
||||
let _ = step(s, 1);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn step(s: &mut Session, d: isize) -> Result<Value> {
|
||||
let vis = s.visible_cloned();
|
||||
if vis.is_empty() {
|
||||
return ok();
|
||||
}
|
||||
let cur = s.selection.active.and_then(|a| vis.iter().position(|x| *x == a));
|
||||
let next = match cur {
|
||||
Some(i) => (i as isize + d).clamp(0, vis.len() as isize - 1) as usize,
|
||||
None => 0,
|
||||
};
|
||||
s.end_interaction()?;
|
||||
s.selection = Selection::single(vis[next]);
|
||||
s.active_mask = None;
|
||||
s.active_spot = None;
|
||||
Ok(json!({"active": vis[next].0}))
|
||||
}
|
||||
|
||||
/// `library.up` / `library.down`: how many photos to move (at least 1, capped so hostile input
|
||||
/// can't overflow).
|
||||
pub(super) fn row_step(p: &Value) -> isize {
|
||||
p.get("rows").and_then(Value::as_u64).unwrap_or(1).clamp(1, 1 << 20) as isize
|
||||
}
|
||||
|
||||
pub(super) fn rotate(s: &mut Session, p: &Value, cw: bool) -> Result<Value> {
|
||||
let targets = s.targets(p)?;
|
||||
let mut ops = Vec::new();
|
||||
for id in targets {
|
||||
if let Some(d) = s.develop_of(id) {
|
||||
let mut d = (*d).clone();
|
||||
d.orientation = d.orientation.rotated(cw);
|
||||
// the crop lives in the oriented frame, so it turns with the image (else it keeps the old width and height and cuts the photo)
|
||||
let turn = lightcraft_geom::Orientation::Normal.rotated(cw);
|
||||
d.crop.geometry.rect = turn.map_norm_rect(d.crop.geometry.rect);
|
||||
d.crop.aspect = d.crop.aspect.map(|(w, h)| (h, w));
|
||||
ops.extend(s.develop_op(id, d, "Rotate"));
|
||||
}
|
||||
}
|
||||
let n = ops.len();
|
||||
s.commit(if cw { "Rotate Right" } else { "Rotate Left" }, Op::Batch { ops })?;
|
||||
Ok(json!({"changed": n}))
|
||||
}
|
||||
|
||||
pub(super) fn flip(s: &mut Session, p: &Value, horizontal: bool) -> Result<Value> {
|
||||
let targets = s.targets(p)?;
|
||||
let mut ops = Vec::new();
|
||||
for id in targets {
|
||||
if let Some(d) = s.develop_of(id) {
|
||||
let mut d = (*d).clone();
|
||||
if horizontal {
|
||||
d.crop.flip_h = !d.crop.flip_h;
|
||||
} else {
|
||||
d.crop.flip_v = !d.crop.flip_v;
|
||||
}
|
||||
ops.extend(s.develop_op(id, d, "Flip"));
|
||||
}
|
||||
}
|
||||
let n = ops.len();
|
||||
s.commit("Flip", Op::Batch { ops })?;
|
||||
Ok(json!({"changed": n}))
|
||||
}
|
||||
|
||||
/// `library.selectBy`: select the photos in view that match every given criterion.
|
||||
pub(super) fn select_by(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.selectBy";
|
||||
let flag: Option<lightcraft_catalog::Flag> = match p.get("flag") {
|
||||
Some(v) => Some(serde_json::from_value(v.clone()).map_err(|_| bad(C, "flag is pick, reject or none"))?),
|
||||
None => None,
|
||||
};
|
||||
let rating = p.get("rating").and_then(Value::as_u64).map(|r| r.min(5) as u8);
|
||||
let op = p.get("ratingOp").and_then(Value::as_str).unwrap_or("gte");
|
||||
let label: Option<Option<lightcraft_catalog::ColorLabel>> = match p.get("label").and_then(Value::as_str) {
|
||||
Some("none") => Some(None),
|
||||
Some(l) => Some(Some(serde_json::from_value(json!(l)).map_err(|_| bad(C, format!("unknown label `{l}`")))?)),
|
||||
None => None,
|
||||
};
|
||||
if flag.is_none() && rating.is_none() && label.is_none() {
|
||||
return Err(bad(C, "give flag, rating and/or label"));
|
||||
}
|
||||
let matches = |ph: &lightcraft_catalog::Photo| {
|
||||
flag.is_none_or(|f| ph.flag == f)
|
||||
&& rating.is_none_or(|r| match op {
|
||||
"eq" => ph.rating == r,
|
||||
"lte" => ph.rating <= r,
|
||||
_ => ph.rating >= r,
|
||||
})
|
||||
&& label.is_none_or(|l| ph.label == l)
|
||||
};
|
||||
let mut ids: Vec<PhotoId> = if bool_or(p, "add", false) { s.selection.ids.clone() } else { Vec::new() };
|
||||
for id in s.visible_cloned() {
|
||||
if !ids.contains(&id) && s.catalog.photo(id).is_some_and(|ph| matches(ph)) {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
let active = s.selection.active.filter(|a| ids.contains(a)).or(ids.first().copied());
|
||||
let n = ids.len();
|
||||
s.selection = Selection { ids, active };
|
||||
Ok(json!({"selected": n}))
|
||||
}
|
||||
|
||||
pub(super) fn has_library(s: &Session) -> std::result::Result<(), String> {
|
||||
if s.library.is_some() { Ok(()) } else { Err("no library is open (in-memory session)".into()) }
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -31,6 +31,10 @@ pub struct PreviewBuild {
|
||||
pub what: &'static str,
|
||||
/// Why the whole build failed (e.g. the smart previews folder isn't there).
|
||||
pub error: std::sync::Mutex<Option<String>>,
|
||||
/// Test-only: the gate this build's lanes wait at before a photo's first render (see
|
||||
/// [`test_gate`]). Captured by `build` on the calling thread; production builds never have one.
|
||||
#[cfg(test)]
|
||||
pub(crate) gate: Option<Arc<test_gate::PreviewGate>>,
|
||||
}
|
||||
|
||||
impl PreviewBuild {
|
||||
@@ -79,10 +83,15 @@ fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard {
|
||||
|
||||
/// Render one photo's jobs in order. The source the first job decodes serves the ones after it
|
||||
/// (the grid thumbnail is made from the view's source instead of decoding the file again).
|
||||
pub(crate) fn run_photo(jobs: Vec<RenderJob>) -> bool {
|
||||
/// `None` when `cancel` was asked for before a job started: that photo is not counted as done.
|
||||
fn run_photo_cancellable(jobs: Vec<RenderJob>, cancel: Option<&AtomicBool>) -> Option<bool> {
|
||||
let mut decoded: Option<crate::media::DecodedSource> = None;
|
||||
let mut ok = true;
|
||||
for mut j in jobs {
|
||||
// between a photo's own previews too (a cancelled 1:1 view skips its grid thumbnail)
|
||||
if cancel.is_some_and(|c| c.load(Ordering::Relaxed)) {
|
||||
return None;
|
||||
}
|
||||
if let Some(src) = &decoded
|
||||
&& !matches!(j.source, crate::media::SourceRef::Loaded(_))
|
||||
{
|
||||
@@ -94,7 +103,13 @@ pub(crate) fn run_photo(jobs: Vec<RenderJob>) -> bool {
|
||||
decoded = r.loaded;
|
||||
}
|
||||
}
|
||||
ok
|
||||
Some(ok)
|
||||
}
|
||||
|
||||
/// [`run_photo_cancellable`] for callers that render a photo without a cancel flag.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn run_photo(jobs: Vec<RenderJob>) -> bool {
|
||||
run_photo_cancellable(jobs, None) == Some(true)
|
||||
}
|
||||
|
||||
/// How many photos render side by side: as many as an export batch for standard previews (each
|
||||
@@ -105,6 +120,112 @@ fn lanes(n: usize, full: bool) -> usize {
|
||||
if full { l.min(2) } else { l }
|
||||
}
|
||||
|
||||
/// A test-only rendezvous at the start of a photo's jobs, so a cancel can be delivered at a known
|
||||
/// point instead of racing a render. One gate belongs to the build `build` starts on the test
|
||||
/// thread that installed it ([`install`]); it is never global and production builds have none.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_gate {
|
||||
use std::sync::{Arc, Condvar, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The longest a lane waits for a test to open the gate: if a test ends without its
|
||||
/// [`ReleaseOnDrop`] running, the build still finishes instead of stranding its worker.
|
||||
const MAX_HOLD: Duration = Duration::from_secs(30);
|
||||
/// The longest a test waits for a lane to reach the gate.
|
||||
const MAX_ENTER_WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
entered: usize,
|
||||
released: bool,
|
||||
}
|
||||
|
||||
/// The gate a test's preview build waits at before rendering a photo (see `install`).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct PreviewGate {
|
||||
state: Mutex<State>,
|
||||
opened: Condvar,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PreviewGate {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("PreviewGate").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl PreviewGate {
|
||||
pub(crate) fn new() -> Arc<Self> {
|
||||
Arc::new(Self::default())
|
||||
}
|
||||
|
||||
/// Called by a lane about to render a photo's first job; returns once the test opens the
|
||||
/// gate, or after `MAX_HOLD` so a lost test cannot strand the worker.
|
||||
pub(crate) fn enter(&self) {
|
||||
let mut st = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
st.entered = st.entered.saturating_add(1);
|
||||
self.opened.notify_all();
|
||||
let deadline = Instant::now() + MAX_HOLD;
|
||||
while !st.released {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
break;
|
||||
}
|
||||
let (next, _) = self.opened.wait_timeout(st, remaining).unwrap_or_else(|e| e.into_inner());
|
||||
st = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait (at most `MAX_ENTER_WAIT`) until at least `n` lanes have reached the gate.
|
||||
pub(crate) fn wait_entered(&self, n: usize) -> bool {
|
||||
let mut st = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let deadline = Instant::now() + MAX_ENTER_WAIT;
|
||||
loop {
|
||||
if st.entered >= n {
|
||||
return true;
|
||||
}
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
return false;
|
||||
}
|
||||
let (next, _) = self.opened.wait_timeout(st, remaining).unwrap_or_else(|e| e.into_inner());
|
||||
st = next;
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the gate: every lane waiting, or arriving later, passes without waiting.
|
||||
pub(crate) fn release(&self) {
|
||||
let mut st = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
st.released = true;
|
||||
self.opened.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the gate when dropped, wherever a test ends (assertion failure, panic, early return).
|
||||
pub(crate) struct ReleaseOnDrop(pub(crate) Arc<PreviewGate>);
|
||||
|
||||
impl Drop for ReleaseOnDrop {
|
||||
fn drop(&mut self) {
|
||||
self.0.release();
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The gate for the next preview build started on this thread, taken by `build` so it is
|
||||
/// per invocation (never shared by two builds or two tests).
|
||||
static NEXT_GATE: std::cell::RefCell<Option<Arc<PreviewGate>>> = const { std::cell::RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Have the next preview build started on this thread wait at `gate` before its first photo.
|
||||
pub(crate) fn install(gate: Arc<PreviewGate>) {
|
||||
NEXT_GATE.with(|g| *g.borrow_mut() = Some(gate));
|
||||
}
|
||||
|
||||
/// Take the gate installed for this build, leaving none for later builds.
|
||||
pub(crate) fn take() -> Option<Arc<PreviewGate>> {
|
||||
NEXT_GATE.with(|g| g.borrow_mut().take())
|
||||
}
|
||||
}
|
||||
|
||||
fn run_all(jobs: Vec<Vec<RenderJob>>, state: &PreviewBuild, task: &TaskGuard, lanes: usize) {
|
||||
let total = jobs.len();
|
||||
let queue = std::sync::Mutex::new(jobs.into_iter());
|
||||
@@ -115,7 +236,17 @@ fn run_all(jobs: Vec<Vec<RenderJob>>, state: &PreviewBuild, task: &TaskGuard, la
|
||||
}
|
||||
let next = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner).next();
|
||||
let Some(photo_jobs) = next else { break };
|
||||
let ok = crate::guard::catch("building previews", || run_photo(photo_jobs)).unwrap_or(false);
|
||||
// A cancel accepted while this lane waited for the queue (or for another lane's
|
||||
// photo) stops before this photo's first render; a cancelled photo is not counted.
|
||||
if state.cancel.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(gate) = &state.gate {
|
||||
gate.enter();
|
||||
}
|
||||
let outcome = crate::guard::catch("building previews", || run_photo_cancellable(photo_jobs, Some(&state.cancel))).unwrap_or(Some(false));
|
||||
let Some(ok) = outcome else { break };
|
||||
if !ok {
|
||||
state.failed.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
@@ -143,6 +274,9 @@ fn run_all(jobs: Vec<Vec<RenderJob>>, state: &PreviewBuild, task: &TaskGuard, la
|
||||
|
||||
fn build(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "library.buildPreviews";
|
||||
// tests: this invocation's gate, consumed here so an early error cannot attach it to a later build
|
||||
#[cfg(test)]
|
||||
let gate = test_gate::take();
|
||||
let edge = match str_param(p, "size").unwrap_or("standard") {
|
||||
"standard" => Some(p.get("edge").and_then(Value::as_u64).map_or(STANDARD_EDGE, |e| e.clamp(256, 8192) as usize)),
|
||||
"full" | "1:1" => None,
|
||||
@@ -154,6 +288,9 @@ fn build(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// explicit ids, else the selection, else everything in view
|
||||
let ids = if p.get("ids").is_some() || p.get("id").is_some() || !s.selection.ids.is_empty() { s.targets(p)? } else { s.visible_cloned() };
|
||||
let jobs: Vec<Vec<RenderJob>> = ids.iter().map(|id| jobs_for(s, *id, edge)).filter(|j| !j.is_empty()).collect();
|
||||
#[cfg(test)]
|
||||
let state = Arc::new(PreviewBuild { total: jobs.len(), gate, ..Default::default() });
|
||||
#[cfg(not(test))]
|
||||
let state = Arc::new(PreviewBuild { total: jobs.len(), ..Default::default() });
|
||||
s.preview_build = Some(state.clone());
|
||||
let task = task_for(s, &state);
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
//! * `print.get`, `print.set {layout?, image?, page?, guides?, job?}`, `print.reset`
|
||||
//! * `print.cell.add|move|resize|delete|stack|photo|page`, `print.layout.autoLayout|newPage|clear`
|
||||
//! * `print.exportPdf {path, ids?}`
|
||||
//! * `print.template.list|save|apply|delete`
|
||||
//! * `print.template.list|save|apply|delete`, `print.template.export|import` (`.lcprint` files)
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{CommandSpec, always, bad, cmd, f64_req};
|
||||
use crate::print::layout::{Layout, MAX_PAGES, Rect, Snap, Stack, paper_names, paper_size};
|
||||
use crate::print::template::{MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_name};
|
||||
use crate::print::template::{FILE_EXT, MAX_FILE, MAX_TEMPLATES, PrintSettings, PrintTemplate, clean_name, unique_name};
|
||||
use crate::{Result, Session};
|
||||
|
||||
fn rect_json(r: &Rect) -> Value {
|
||||
@@ -277,10 +277,21 @@ fn template_name(p: &Value, id: &str) -> Result<String> {
|
||||
clean_name(p.get("name").and_then(Value::as_str).ok_or_else(|| bad(id, "missing `name`"))?).map_err(|e| bad(id, e))
|
||||
}
|
||||
|
||||
/// Save the preferences after a change to the templates; if that fails, the templates go back to
|
||||
/// `before`, so the list matches what is saved and a retry does the same thing.
|
||||
fn save_templates(s: &mut Session, before: Vec<PrintTemplate>) -> Result<()> {
|
||||
if let Err(e) = s.save_prefs() {
|
||||
s.print_templates = before;
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn template_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const ID: &str = "print.template.save";
|
||||
let name = template_name(p, ID)?;
|
||||
let t = PrintTemplate::new(&name, &s.print).map_err(|e| bad(ID, e))?;
|
||||
let before = s.print_templates.clone();
|
||||
match s.print_templates.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
|
||||
Some(x) => *x = t,
|
||||
None => {
|
||||
@@ -290,7 +301,7 @@ fn template_save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.print_templates.push(t);
|
||||
}
|
||||
}
|
||||
s.save_prefs()?;
|
||||
save_templates(s, before)?;
|
||||
Ok(template_list(s))
|
||||
}
|
||||
|
||||
@@ -309,15 +320,66 @@ fn template_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn template_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const ID: &str = "print.template.delete";
|
||||
let name = template_name(p, ID)?;
|
||||
let before = s.print_templates.len();
|
||||
let before = s.print_templates.clone();
|
||||
s.print_templates.retain(|x| !x.name.eq_ignore_ascii_case(&name));
|
||||
if s.print_templates.len() == before {
|
||||
if s.print_templates.len() == before.len() {
|
||||
return Err(bad(ID, format!("no print template `{name}`")));
|
||||
}
|
||||
s.save_prefs()?;
|
||||
save_templates(s, before)?;
|
||||
Ok(template_list(s))
|
||||
}
|
||||
|
||||
fn template_path<'a>(p: &'a Value, id: &str) -> Result<&'a str> {
|
||||
p.get("path").and_then(Value::as_str).map(str::trim).filter(|x| !x.is_empty()).ok_or_else(|| bad(id, "missing `path`"))
|
||||
}
|
||||
|
||||
fn template_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const ID: &str = "print.template.export";
|
||||
let name = template_name(p, ID)?;
|
||||
let mut path = std::path::PathBuf::from(template_path(p, ID)?);
|
||||
if path.extension().is_none() {
|
||||
path.set_extension(FILE_EXT);
|
||||
}
|
||||
let t = s
|
||||
.print_templates
|
||||
.iter()
|
||||
.find(|x| x.name.eq_ignore_ascii_case(&name))
|
||||
.ok_or_else(|| bad(ID, format!("no print template `{name}` (see print.template.list)")))?;
|
||||
let bytes = serde_json::to_vec_pretty(&t.to_file()).map_err(|e| crate::EngineError::Other(e.to_string()))?;
|
||||
let name = t.name.clone();
|
||||
let target = path.to_string_lossy();
|
||||
s.check_write_target(&target).map_err(|e| bad(ID, e))?;
|
||||
crate::export::write_file(&target, &bytes).map_err(|e| bad(ID, e))?;
|
||||
Ok(json!({"name": name, "path": target}))
|
||||
}
|
||||
|
||||
fn template_import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const ID: &str = "print.template.import";
|
||||
let path = std::path::Path::new(template_path(p, ID)?);
|
||||
let meta = std::fs::metadata(path).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?;
|
||||
if !meta.is_file() {
|
||||
return Err(bad(ID, format!("{}: not a file", path.display())));
|
||||
}
|
||||
if meta.len() > MAX_FILE {
|
||||
return Err(bad(ID, format!("{}: {} bytes is too large for a print template (at most {} KB)", path.display(), meta.len(), MAX_FILE / 1024)));
|
||||
}
|
||||
let bytes = std::fs::read(path).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?;
|
||||
let mut t = PrintTemplate::from_file(&bytes).map_err(|e| bad(ID, format!("{}: {e}", path.display())))?;
|
||||
if s.print_templates.len() >= MAX_TEMPLATES {
|
||||
return Err(bad(ID, format!("at most {MAX_TEMPLATES} templates; delete one first")));
|
||||
}
|
||||
let name = unique_name(&t.name, &s.print_templates);
|
||||
let renamed = name != t.name;
|
||||
t.name = name.clone();
|
||||
let before = s.print_templates.clone();
|
||||
s.print_templates.push(t);
|
||||
save_templates(s, before)?;
|
||||
let mut out = template_list(s);
|
||||
out["name"] = json!(name);
|
||||
out["renamed"] = json!(renamed);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(query "print.get", "Print Settings", [], None,
|
||||
@@ -349,5 +411,11 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always, template_save),
|
||||
cmd!(query "print.template.apply", "Apply Print Template", [], None, "{name} → print.get", always, template_apply),
|
||||
cmd!(query "print.template.delete", "Delete Print Template", [], None, "{name} → print.template.list", always, template_delete),
|
||||
cmd!(query "print.template.export", "Export Print Template", [], None,
|
||||
"{name, path}: writes the template as a .lcprint JSON file ({format, version, name, settings}; `.lcprint` is added when the path has no extension); replaces an existing file, never an original → {name, path}",
|
||||
always, template_export),
|
||||
cmd!(query "print.template.import", "Import Print Template", [], None,
|
||||
"{path: a .lcprint file (at most 256 KB)}: checked like a saved template (format, version, name, every setting; cell photos and guides are dropped) and added under its name; a name taken (any case) gets \" (2)\"… → print.template.list + {name, renamed}",
|
||||
always, template_import),
|
||||
]
|
||||
}
|
||||
@@ -379,7 +379,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Slideshow Playback Settings",
|
||||
[],
|
||||
None,
|
||||
"{slideDuration?: seconds (0.5–120), fadeDuration?: seconds (0 = cut; at most 10 and the slide duration), fadeColor?: \"#rrggbb\"|[r,g,b]|null (fade through a colour instead of crossfading), randomOrder?: bool, repeat?: bool, preparePreviews?: bool (render the next slides before they are due)} — omitted keys keep their value, {} reads them; saved with the library → {slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews}",
|
||||
"{slideDuration?: seconds (0.5–120), fadeDuration?: seconds (0 = cut; at most 10 and the slide duration), fadeColor?: \"#rrggbb\"|[r,g,b]|null (fade through a colour instead of crossfading), randomOrder?: bool, repeat?: bool, preparePreviews?: bool (render the next slides before they are due), manual?: bool (manual slideshow: a slide stays up until ← or → changes it)} — omitted keys keep their value, {} reads them; saved with the library → {slideDuration, fadeDuration, fadeColor, randomOrder, repeat, preparePreviews, manual}",
|
||||
always,
|
||||
playback
|
||||
),
|
||||
|
||||
+1
-357
@@ -552,360 +552,4 @@ pub fn preset_from_xmp(xmp: &str, fallback_name: &str) -> Option<Preset> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_develop::{DevelopSettings, Upright, VignetteStyle, WbMode, apply_partial};
|
||||
|
||||
/// A hand-written sidecar in attribute form (as many tools write it).
|
||||
const SIDECAR: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/">
|
||||
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:Version="99.0" crs:ProcessVersion="11.0" crs:WhiteBalance="Custom" crs:Temperature="5150" crs:Tint="+12"
|
||||
crs:Exposure2012="+0.65" crs:Contrast2012="-14" crs:Highlights2012="-58" crs:Shadows2012="+41"
|
||||
crs:Whites2012="+9" crs:Blacks2012="-17" crs:Texture="+6" crs:Clarity2012="+11" crs:Dehaze="+4"
|
||||
crs:Vibrance="+19" crs:Saturation="-3" crs:HueAdjustmentOrange="-7" crs:SaturationAdjustmentBlue="-22"
|
||||
crs:LuminanceAdjustmentAqua="+13" crs:ParametricShadows="+5" crs:ParametricHighlights="-8"
|
||||
crs:ParametricMidtoneSplit="55" crs:CurveRefineSaturation="40" crs:SplitToningShadowHue="210" crs:SplitToningShadowSaturation="14"
|
||||
crs:SplitToningHighlightHue="40" crs:SplitToningHighlightSaturation="9" crs:SplitToningBalance="+20"
|
||||
crs:ColorGradeMidtoneHue="120" crs:ColorGradeMidtoneSat="6" crs:ColorGradeBlending="70"
|
||||
crs:Sharpness="55" crs:SharpenRadius="+1.2" crs:SharpenDetail="30" crs:SharpenEdgeMasking="12"
|
||||
crs:LuminanceSmoothing="18" crs:ColorNoiseReduction="25" crs:PostCropVignetteAmount="-21"
|
||||
crs:PostCropVignetteStyle="2" crs:GrainAmount="15" crs:GrainSize="30" crs:GrainFrequency="60"
|
||||
crs:PerspectiveUpright="2" crs:PerspectiveVertical="-10" crs:AutoLateralCA="1" crs:ConvertToGrayscale="False"
|
||||
crs:ShadowTint="-7" crs:RedHue="+12" crs:RedSaturation="+20" crs:GreenHue="-5" crs:GreenSaturation="+3"
|
||||
crs:BlueHue="-15" crs:BlueSaturation="+25"
|
||||
crs:HasCrop="True" crs:CropTop="0.1" crs:CropLeft="0.05" crs:CropBottom="0.9" crs:CropRight="0.8" crs:CropAngle="1.5">
|
||||
<crs:ToneCurvePV2012>
|
||||
<rdf:Seq><rdf:li>0, 0</rdf:li><rdf:li>64, 52</rdf:li><rdf:li>192, 205</rdf:li><rdf:li>255, 255</rdf:li></rdf:Seq>
|
||||
</crs:ToneCurvePV2012>
|
||||
<crs:ToneCurvePV2012Red>
|
||||
<rdf:Seq><rdf:li>0, 0</rdf:li><rdf:li>255, 255</rdf:li></rdf:Seq>
|
||||
</crs:ToneCurvePV2012Red>
|
||||
</rdf:Description>
|
||||
</rdf:RDF>
|
||||
</x:xmpmeta>"#;
|
||||
|
||||
fn props(x: &str) -> Props {
|
||||
lightcraft_meta::parse_xmp(x).unwrap().properties
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_common_fields() {
|
||||
let p = props(SIDECAR);
|
||||
assert!(has_adjustments(&p));
|
||||
let partial = to_partial(&p, Target::RawAbsolute);
|
||||
let s = apply_partial(&DevelopSettings::for_raw(5000.0, 0.0), &partial, 1.0);
|
||||
assert_eq!(s.wb.mode, WbMode::Custom);
|
||||
assert_eq!((s.wb.temp, s.wb.tint), (5150.0, 12.0));
|
||||
assert_eq!(s.light.exposure, 0.65);
|
||||
assert_eq!((s.light.contrast, s.light.highlights, s.light.shadows, s.light.whites, s.light.blacks), (-14.0, -58.0, 41.0, 9.0, -17.0));
|
||||
assert_eq!((s.effects.texture, s.effects.clarity, s.effects.dehaze), (6.0, 11.0, 4.0));
|
||||
assert_eq!((s.color.vibrance, s.color.saturation), (19.0, -3.0));
|
||||
assert_eq!(s.mixer.orange.hue, -7.0);
|
||||
assert_eq!(s.mixer.blue.sat, -22.0);
|
||||
assert_eq!(s.mixer.aqua.lum, 13.0);
|
||||
assert_eq!((s.curve.shadows, s.curve.highlights, s.curve.split_mid), (5.0, -8.0, 55.0));
|
||||
assert_eq!(s.curve.master.len(), 4);
|
||||
assert_eq!(s.curve.refine_saturation, 40.0);
|
||||
assert!((s.curve.master[1].x - 64.0 / 255.0).abs() < 1e-9 && (s.curve.master[1].y - 52.0 / 255.0).abs() < 1e-9);
|
||||
assert!(s.curve.red.is_empty(), "identity channel curve maps to no curve");
|
||||
assert_eq!((s.grading.shadows.hue, s.grading.shadows.sat), (210.0, 14.0));
|
||||
assert_eq!((s.grading.highlights.hue, s.grading.highlights.sat), (40.0, 9.0));
|
||||
assert_eq!((s.grading.midtones.hue, s.grading.midtones.sat), (120.0, 6.0));
|
||||
assert_eq!((s.grading.balance, s.grading.blending), (20.0, 70.0));
|
||||
assert_eq!((s.detail.sharpen_amount, s.detail.sharpen_radius, s.detail.sharpen_detail, s.detail.sharpen_masking), (55.0, 1.2, 30.0, 12.0));
|
||||
assert_eq!((s.detail.nr_luminance, s.detail.nr_color), (18.0, 25.0));
|
||||
assert_eq!(s.vignette.amount, -21.0);
|
||||
assert_eq!(s.vignette.style, VignetteStyle::ColorPriority);
|
||||
assert_eq!((s.grain.amount, s.grain.size, s.grain.roughness), (15.0, 30.0, 60.0));
|
||||
assert_eq!(s.geometry.upright, Upright::Level);
|
||||
assert_eq!(s.geometry.vertical, -10.0);
|
||||
assert!(s.optics.remove_ca);
|
||||
assert_eq!(s.treatment, lightcraft_develop::Treatment::Color);
|
||||
let cal = s.calibration;
|
||||
assert_eq!(
|
||||
(cal.shadows_tint, cal.red_hue, cal.red_sat, cal.green_hue, cal.green_sat, cal.blue_hue, cal.blue_sat),
|
||||
(-7.0, 12.0, 20.0, -5.0, 3.0, -15.0, 25.0)
|
||||
);
|
||||
let c = s.crop.geometry;
|
||||
assert_eq!((c.rect.x0, c.rect.y0, c.rect.x1, c.rect.y1, c.angle), (0.05, 0.1, 0.8, 0.9, 1.5));
|
||||
}
|
||||
|
||||
/// A sidecar curve with a `NaN` or `inf` point (Rust's `parse` reads both) is not a curve:
|
||||
/// it is left out, rather than stored with a point the curve editor can't place.
|
||||
#[test]
|
||||
fn curves_with_non_finite_points_are_left_out() {
|
||||
for bad in ["NaN, 0", "64, inf", "-inf, 3"] {
|
||||
let x = SIDECAR.replace("<rdf:li>64, 52</rdf:li>", &format!("<rdf:li>{bad}</rdf:li>"));
|
||||
let partial = to_partial(&props(&x), Target::RawAbsolute);
|
||||
let s = apply_partial(&DevelopSettings::for_raw(5000.0, 0.0), &partial, 1.0);
|
||||
assert!(s.curve.master.is_empty(), "{bad}: {:?}", s.curve.master);
|
||||
assert!(s.curve.master.iter().all(|p| p.x.is_finite() && p.y.is_finite()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_present_fields_are_in_the_partial() {
|
||||
let x = r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description
|
||||
xmlns:c="http://ns.adobe.com/camera-raw-settings/1.0/" c:Vibrance="+30" c:GrainAmount="10"/></rdf:RDF>"#;
|
||||
let partial = to_partial(&props(x), Target::Any);
|
||||
assert_eq!(partial, json!({"color": {"vibrance": 30.0}, "grain": {"amount": 10.0}}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hdr_edit_mode_turns_hdr_editing_on_or_off() {
|
||||
let x = |v: &str| {
|
||||
format!(
|
||||
r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description
|
||||
xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:HDREditMode="{v}" crs:Exposure2012="+1.5"/></rdf:RDF>"#
|
||||
)
|
||||
};
|
||||
let on = apply_partial(&DevelopSettings::default(), &to_partial(&props(&x("1")), Target::RawAbsolute), 1.0);
|
||||
assert!(on.hdr.enabled);
|
||||
assert_eq!(on.light.exposure, 1.5);
|
||||
assert_eq!(on.hdr.max_ev, lightcraft_develop::Hdr::DEFAULT_MAX_EV, "the rest of the HDR settings keep their defaults");
|
||||
let true_form = apply_partial(&DevelopSettings::default(), &to_partial(&props(&x("True")), Target::RawAbsolute), 1.0);
|
||||
assert!(true_form.hdr.enabled);
|
||||
let mut hdr = DevelopSettings::default();
|
||||
hdr.hdr.enabled = true;
|
||||
assert!(!apply_partial(&hdr, &to_partial(&props(&x("0")), Target::RawAbsolute), 1.0).hdr.enabled, "0 turns it off");
|
||||
// without the field nothing about HDR changes
|
||||
let plain = r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description
|
||||
xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Exposure2012="+1.5"/></rdf:RDF>"#;
|
||||
assert!(to_partial(&props(plain), Target::RawAbsolute).get("hdr").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn element_form_bw_and_incremental_wb() {
|
||||
let x = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/">
|
||||
<crs:ConvertToGrayscale>True</crs:ConvertToGrayscale>
|
||||
<crs:GrayMixerBlue>-35</crs:GrayMixerBlue>
|
||||
<crs:IncrementalTemperature>25</crs:IncrementalTemperature>
|
||||
<crs:IncrementalTint>-6</crs:IncrementalTint>
|
||||
<crs:Temperature>4800</crs:Temperature>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
let p = props(x);
|
||||
let rendered = apply_partial(&DevelopSettings::default(), &to_partial(&p, Target::Rendered), 1.0);
|
||||
assert_eq!(rendered.treatment, lightcraft_develop::Treatment::Bw);
|
||||
assert_eq!(rendered.bw_mix.blue, -35.0);
|
||||
assert!((rendered.wb.temp - rel_to_kelvin(25.0)).abs() < 1e-6 && rendered.wb.temp > 6500.0);
|
||||
assert_eq!(rendered.wb.tint, -6.0);
|
||||
let raw = apply_partial(&DevelopSettings::default(), &to_partial(&p, Target::RawAbsolute), 1.0);
|
||||
assert_eq!(raw.wb.temp, 4800.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_wb_and_already_applied() {
|
||||
let x = r#"<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:WhiteBalance="Daylight" crs:Temperature="5500" crs:Tint="10" crs:AlreadyApplied="True"/>"#;
|
||||
let p = props(x);
|
||||
assert_eq!(to_partial(&p, Target::RawAbsolute), json!({"wb": {"mode": "daylight"}}));
|
||||
assert!(!has_adjustments(&p));
|
||||
let bookkeeping = r#"<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Version="1" crs:HasSettings="True"/>"#;
|
||||
assert!(!has_adjustments(&props(bookkeeping)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_kelvin_on_relative_wb_raws_shifts_from_the_as_shot_white() {
|
||||
// Issue #510: a Sony ARW edited in Lightroom to Custom 3578 K / −5 next to an as-shot white
|
||||
// of 3650 K / −2 (written for this test from the numbers in the issue).
|
||||
let x = r#"<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:WhiteBalance="Custom" crs:Temperature="3578" crs:Tint="-5" crs:AsShotTemperature="3650" crs:AsShotTint="-2"/>"#;
|
||||
let p = props(x);
|
||||
let rel = to_partial(&p, Target::RawRelative);
|
||||
// 3650 → 3578 K is +5.5 mired: the same shift from 6500 K lands near 6275 K on our scale
|
||||
let t = rel["wb"]["temp"].as_f64().unwrap();
|
||||
assert!((t - 6275.0).abs() < 5.0, "{t}");
|
||||
assert_eq!(rel["wb"]["tint"], -3.0);
|
||||
assert_eq!(rel["wb"]["mode"], "custom");
|
||||
// a rendered file without `Incremental*` fields shifts the same way; a raw with a measured
|
||||
// illuminant (and a preset) keeps the Kelvin value
|
||||
assert_eq!(to_partial(&p, Target::Rendered)["wb"]["temp"], rel["wb"]["temp"]);
|
||||
assert_eq!(to_partial(&p, Target::RawAbsolute)["wb"]["temp"], 3578.0);
|
||||
assert_eq!(to_partial(&p, Target::Any)["wb"]["temp"], 3578.0);
|
||||
// Kelvin read as Kelvin says so, so it stays Kelvin on a raw with that scale; a shift does not
|
||||
assert_eq!(to_partial(&p, Target::RawAbsolute)["wb"]["scale"], "kelvin");
|
||||
assert_eq!(to_partial(&p, Target::Any)["wb"]["scale"], "kelvin");
|
||||
assert!(rel["wb"].get("scale").is_none() && to_partial(&p, Target::Rendered)["wb"].get("scale").is_none());
|
||||
// the as-shot fields are a reference, not an adjustment: nothing to report
|
||||
assert!(to_partial_report(&p, None, Target::RawRelative, 1.5).1.is_empty());
|
||||
// no tint next to the as-shot tint: the custom tint is taken as the shift itself
|
||||
let no_tint = props(&x.replace(r#" crs:AsShotTint="-2""#, ""));
|
||||
assert_eq!(to_partial(&no_tint, Target::RawRelative)["wb"]["tint"], -5.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_kelvin_without_an_as_shot_reference_stays_as_shot_and_is_reported() {
|
||||
// The same edit from a Lightroom catalog, which keeps no as-shot white for Custom photos:
|
||||
// 3578 K read on the relative scale would be a large blue shift (issue #510)
|
||||
let x = r#"<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:WhiteBalance="Custom" crs:Temperature="3578" crs:Tint="-5" crs:Exposure2012="+0.3"/>"#;
|
||||
let p = props(x);
|
||||
let (partial, unmapped) = to_partial_report(&p, None, Target::RawRelative, 1.5);
|
||||
assert_eq!(partial["wb"], json!({"mode": "asShot"}));
|
||||
assert_eq!(partial["light"]["exposure"], 0.3);
|
||||
assert_eq!(unmapped.len(), 1, "{unmapped:?}");
|
||||
assert!(unmapped[0].starts_with("Temperature, Tint"), "{unmapped:?}");
|
||||
// a raw with a measured illuminant and a rendered file read it as before, and report nothing
|
||||
assert_eq!(to_partial(&p, Target::RawAbsolute)["wb"]["temp"], 3578.0);
|
||||
assert_eq!(to_partial(&p, Target::Rendered)["wb"]["temp"], 3578.0);
|
||||
assert!(to_partial_report(&p, None, Target::RawAbsolute, 1.5).1.is_empty());
|
||||
// an unusable reference (zero) counts as none
|
||||
let zero = props(&x.replace(r#" crs:Tint="-5""#, r#" crs:Tint="-5" crs:AsShotTemperature="0""#));
|
||||
assert_eq!(to_partial(&zero, Target::RawRelative)["wb"], json!({"mode": "asShot"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_follows_the_file() {
|
||||
use lightcraft_catalog::MediaKind;
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "ARW", false, ""), Target::RawRelative);
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "nef", false, "NIKON CORPORATION NIKON D7500"), Target::RawRelative);
|
||||
// Lightroom's `fileFormat` name for proprietary raws
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "RAW", false, "SONY ILCE-7M2"), Target::RawRelative);
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "DNG", false, ""), Target::RawAbsolute);
|
||||
// a raw shown from its embedded preview develops like a rendered file
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "ARW", true, "SONY ILCE-7M3"), Target::Rendered);
|
||||
assert_eq!(Target::for_file(MediaKind::Image, "JPG", false, "SONY ILCE-7M3"), Target::Rendered);
|
||||
// a camera with measured matrices edits in Kelvin (issue #730), under any of its names
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "ARW", false, "SONY ILCE-7M3"), Target::RawAbsolute);
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "RAW", false, "ILCE-7M3"), Target::RawAbsolute);
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "NEF", false, "NIKON CORPORATION NIKON D850"), Target::RawAbsolute);
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "CR2", false, "Canon Canon EOS 5D Mark III"), Target::RawAbsolute);
|
||||
let mut p =
|
||||
lightcraft_catalog::Photo::new(lightcraft_catalog::PhotoId(1), lightcraft_catalog::Source::Demo { scene: 0 }, "a.arw", "ARW", 1, 1, "");
|
||||
p.kind = MediaKind::Raw;
|
||||
assert_eq!(Target::for_photo(&p), Target::RawRelative);
|
||||
p.meta.camera = "SONY ILCE-7M3".into();
|
||||
assert_eq!(Target::for_photo(&p), Target::RawAbsolute);
|
||||
}
|
||||
|
||||
/// Lightroom writes `crs:Temperature` as Kelvin for a raw whose camera LightCraft has matrices for: the value
|
||||
/// is read as written, marked Kelvin, and the as-shot reference is not needed (issue #730); the same packet on
|
||||
/// a raw without matrices still takes the #510 shift.
|
||||
#[test]
|
||||
fn kelvin_is_direct_on_raws_whose_camera_has_matrices() {
|
||||
use lightcraft_catalog::MediaKind;
|
||||
let x = r#"<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:WhiteBalance="Custom" crs:Temperature="4650" crs:Tint="+3" crs:AsShotTemperature="5400" crs:AsShotTint="-1"/>"#;
|
||||
let p = props(x);
|
||||
let a7m3 = Target::for_file(MediaKind::Raw, "ARW", false, "SONY ILCE-7M3");
|
||||
assert_eq!(to_partial(&p, a7m3)["wb"], json!({"mode": "custom", "temp": 4650.0, "tint": 3.0, "scale": "kelvin"}));
|
||||
let a7m2 = Target::for_file(MediaKind::Raw, "ARW", false, "SONY ILCE-7M2");
|
||||
let shifted = to_partial(&p, a7m2);
|
||||
assert!(shifted["wb"]["temp"].as_f64().is_some_and(|t| t > 5000.0 && t < 6500.0), "{shifted}");
|
||||
assert_eq!(shifted["wb"]["tint"], 4.0);
|
||||
assert!(shifted["wb"].get("scale").is_none());
|
||||
// without the reference the Kelvin camera still reads it, the other stays As Shot
|
||||
let bare = props(&x.replace(r#" crs:AsShotTemperature="5400" crs:AsShotTint="-1""#, ""));
|
||||
assert_eq!(to_partial(&bare, a7m3)["wb"]["temp"], 4650.0);
|
||||
assert_eq!(to_partial(&bare, a7m2)["wb"], json!({"mode": "asShot"}));
|
||||
// a named preset carries no numbers either way
|
||||
let daylight = props(&x.replace(r#"crs:WhiteBalance="Custom""#, r#"crs:WhiteBalance="Daylight""#));
|
||||
assert_eq!(to_partial(&daylight, a7m3)["wb"], json!({"mode": "daylight"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xmp_preset_with_name_and_group() {
|
||||
// Written for this test: a minimal preset-shaped packet with localized name/group.
|
||||
let x = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:PresetType="Normal" crs:UUID="0123ABCD" crs:Contrast2012="+25" crs:SupportsAmount="True">
|
||||
<crs:Name><rdf:Alt><rdf:li xml:lang="x-default">Punchy Test</rdf:li></rdf:Alt></crs:Name>
|
||||
<crs:Group><rdf:Alt><rdf:li xml:lang="x-default">My Looks</rdf:li></rdf:Alt></crs:Group>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
let p = preset_from_xmp(x, "file").unwrap();
|
||||
assert_eq!((p.name.as_str(), p.group.as_str(), p.id.as_str()), ("Punchy Test", "My Looks", "user.xmp.0123abcd"));
|
||||
assert_eq!(p.settings, json!({"light": {"contrast": 25.0}}));
|
||||
assert!(!p.builtin);
|
||||
assert!(preset_from_xmp("<x/>", "f").is_none());
|
||||
}
|
||||
|
||||
/// A preset packet (written for this test) with the bookkeeping fields Lightroom presets carry.
|
||||
fn preset_packet(extra_attrs: &str, extra_elems: &str) -> String {
|
||||
format!(
|
||||
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:PresetType="Normal" crs:Cluster="" crs:UUID="0123ABCD" crs:SupportsAmount2="True" crs:SupportsAmount="True"
|
||||
crs:RequiresRGBTables="False" crs:Contrast2012="+25" crs:LensProfileEnable="0" crs:OverrideLookVignette="False"
|
||||
crs:CropConstrainToWarp="0" crs:AsShotTemperature="5500" crs:AsShotTint="10" {extra_attrs}>
|
||||
<crs:SortName><rdf:Alt><rdf:li xml:lang="x-default"/></rdf:Alt></crs:SortName>
|
||||
<crs:Description><rdf:Alt><rdf:li xml:lang="x-default"/></rdf:Alt></crs:Description>
|
||||
{extra_elems}
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_curves_need_the_master_and_all_channel_curves() {
|
||||
// Lightroom applies red / green / blue curves only when the master and all three are present
|
||||
let seq = |name: &str, pts: &str| format!("<crs:{name}><rdf:Seq>{pts}</rdf:Seq></crs:{name}>");
|
||||
let identity = "<rdf:li>0, 0</rdf:li><rdf:li>255, 255</rdf:li>";
|
||||
let bent = "<rdf:li>0, 0</rdf:li><rdf:li>64, 40</rdf:li><rdf:li>255, 255</rdf:li>";
|
||||
let packet = |curves: &[String]| {
|
||||
format!(
|
||||
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:ToneCurveName2012="Custom">{}
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#,
|
||||
curves.concat()
|
||||
)
|
||||
};
|
||||
let partial = |curves: &[String]| to_partial(&props(&packet(curves)), Target::RawAbsolute);
|
||||
let (master, red, green, blue) = (
|
||||
seq("ToneCurvePV2012", identity),
|
||||
seq("ToneCurvePV2012Red", identity),
|
||||
seq("ToneCurvePV2012Green", bent),
|
||||
seq("ToneCurvePV2012Blue", identity),
|
||||
);
|
||||
// a channel curve alone, or with the master but without its two siblings: ignored
|
||||
let alone = partial(std::slice::from_ref(&green));
|
||||
assert!(alone.pointer("/curve/green").is_none(), "{alone}");
|
||||
let master_and_green = partial(&[master.clone(), green.clone()]);
|
||||
assert!(master_and_green.pointer("/curve/green").is_none() && master_and_green.pointer("/curve/master").is_some(), "{master_and_green}");
|
||||
// all four: read
|
||||
let all = partial(&[master, red, green, blue]);
|
||||
assert!(["/curve/master", "/curve/red", "/curve/green", "/curve/blue"].iter().all(|p| all.pointer(p).is_some()), "{all}");
|
||||
}
|
||||
|
||||
fn unmapped(x: &str) -> Vec<String> {
|
||||
to_partial_report(&props(x), None, Target::Any, 1.5).1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_bookkeeping_is_not_reported_but_real_gaps_are() {
|
||||
let empty_points = "<crs:PointColors><rdf:Seq><rdf:li>-1.000000, -1.000000, -1.000000, -1.000000</rdf:li></rdf:Seq></crs:PointColors>";
|
||||
assert_eq!(unmapped(&preset_packet(r#"crs:HDREditMode="0""#, empty_points)), Vec::<String>::new());
|
||||
// a used Point Color slot and an unknown adjustment still are (an HDR edit is carried over)
|
||||
let used_points = "<crs:PointColors><rdf:Seq><rdf:li>0.5, 0.2, 0.1, 10, 0, 0, 0, 0</rdf:li></rdf:Seq></crs:PointColors>";
|
||||
let got = unmapped(&preset_packet(r#"crs:HDREditMode="1" crs:FutureSlider="12""#, used_points));
|
||||
assert_eq!(got, ["FutureSlider", "PointColors"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lightroom_profile_bookkeeping_is_not_reported() {
|
||||
// what Lightroom Classic writes next to every raw's edit: none of it changes the rendering
|
||||
let bookkeeping = r#"crs:CompatibleVersion="268435456" crs:CameraProfileDigest="0A1B" crs:LensProfileDigest="2C3D"
|
||||
crs:LensProfileName="Sony FE 24-70mm" crs:LensProfileFilename="x.lcp" crs:LensProfileIsEmbedded="False"
|
||||
crs:LensProfileSetup="LensDefaults" crs:LensProfileDistortionScale="100" crs:LensProfileVignettingScale="100"
|
||||
crs:CropConstrainToUnitSquare="1""#;
|
||||
let look = r#"<crs:Look rdf:parseType="Resource"><crs:Name>Vivid</crs:Name></crs:Look>"#;
|
||||
assert_eq!(unmapped(&preset_packet(bookkeeping, "")), Vec::<String>::new());
|
||||
assert_eq!(unmapped(&preset_packet(bookkeeping, look)), ["Look"], "the Look is a real gap");
|
||||
// a lens profile's strength away from 100 % is an adjustment we don't carry over
|
||||
let scaled = preset_packet(r#"crs:LensProfileDistortionScale="60""#, "");
|
||||
assert_eq!(unmapped(&scaled), ["LensProfileDistortionScale"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_lens_profile_switch_keeps_embedded_corrections() {
|
||||
// Lightroom applies a file's built-in lens corrections regardless of its profile switch,
|
||||
// and ours are only those: a preset's `LensProfileEnable=0` must not turn them off
|
||||
let p = props(&preset_packet("", ""));
|
||||
let mut d = DevelopSettings::default();
|
||||
d.optics.lens_profile = true;
|
||||
assert!(apply_partial(&d, &to_partial(&p, Target::Any), 1.0).optics.lens_profile);
|
||||
let on = props(&preset_packet("", "").replace(r#"crs:LensProfileEnable="0""#, r#"crs:LensProfileEnable="1""#));
|
||||
assert!(apply_partial(&DevelopSettings::default(), &to_partial(&on, Target::Any), 1.0).optics.lens_profile);
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,355 @@
|
||||
use super::*;
|
||||
use lightcraft_develop::{DevelopSettings, Upright, VignetteStyle, WbMode, apply_partial};
|
||||
|
||||
/// A hand-written sidecar in attribute form (as many tools write it).
|
||||
const SIDECAR: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/">
|
||||
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:Version="99.0" crs:ProcessVersion="11.0" crs:WhiteBalance="Custom" crs:Temperature="5150" crs:Tint="+12"
|
||||
crs:Exposure2012="+0.65" crs:Contrast2012="-14" crs:Highlights2012="-58" crs:Shadows2012="+41"
|
||||
crs:Whites2012="+9" crs:Blacks2012="-17" crs:Texture="+6" crs:Clarity2012="+11" crs:Dehaze="+4"
|
||||
crs:Vibrance="+19" crs:Saturation="-3" crs:HueAdjustmentOrange="-7" crs:SaturationAdjustmentBlue="-22"
|
||||
crs:LuminanceAdjustmentAqua="+13" crs:ParametricShadows="+5" crs:ParametricHighlights="-8"
|
||||
crs:ParametricMidtoneSplit="55" crs:CurveRefineSaturation="40" crs:SplitToningShadowHue="210" crs:SplitToningShadowSaturation="14"
|
||||
crs:SplitToningHighlightHue="40" crs:SplitToningHighlightSaturation="9" crs:SplitToningBalance="+20"
|
||||
crs:ColorGradeMidtoneHue="120" crs:ColorGradeMidtoneSat="6" crs:ColorGradeBlending="70"
|
||||
crs:Sharpness="55" crs:SharpenRadius="+1.2" crs:SharpenDetail="30" crs:SharpenEdgeMasking="12"
|
||||
crs:LuminanceSmoothing="18" crs:ColorNoiseReduction="25" crs:PostCropVignetteAmount="-21"
|
||||
crs:PostCropVignetteStyle="2" crs:GrainAmount="15" crs:GrainSize="30" crs:GrainFrequency="60"
|
||||
crs:PerspectiveUpright="2" crs:PerspectiveVertical="-10" crs:AutoLateralCA="1" crs:ConvertToGrayscale="False"
|
||||
crs:ShadowTint="-7" crs:RedHue="+12" crs:RedSaturation="+20" crs:GreenHue="-5" crs:GreenSaturation="+3"
|
||||
crs:BlueHue="-15" crs:BlueSaturation="+25"
|
||||
crs:HasCrop="True" crs:CropTop="0.1" crs:CropLeft="0.05" crs:CropBottom="0.9" crs:CropRight="0.8" crs:CropAngle="1.5">
|
||||
<crs:ToneCurvePV2012>
|
||||
<rdf:Seq><rdf:li>0, 0</rdf:li><rdf:li>64, 52</rdf:li><rdf:li>192, 205</rdf:li><rdf:li>255, 255</rdf:li></rdf:Seq>
|
||||
</crs:ToneCurvePV2012>
|
||||
<crs:ToneCurvePV2012Red>
|
||||
<rdf:Seq><rdf:li>0, 0</rdf:li><rdf:li>255, 255</rdf:li></rdf:Seq>
|
||||
</crs:ToneCurvePV2012Red>
|
||||
</rdf:Description>
|
||||
</rdf:RDF>
|
||||
</x:xmpmeta>"#;
|
||||
|
||||
fn props(x: &str) -> Props {
|
||||
lightcraft_meta::parse_xmp(x).unwrap().properties
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_common_fields() {
|
||||
let p = props(SIDECAR);
|
||||
assert!(has_adjustments(&p));
|
||||
let partial = to_partial(&p, Target::RawAbsolute);
|
||||
let s = apply_partial(&DevelopSettings::for_raw(5000.0, 0.0), &partial, 1.0);
|
||||
assert_eq!(s.wb.mode, WbMode::Custom);
|
||||
assert_eq!((s.wb.temp, s.wb.tint), (5150.0, 12.0));
|
||||
assert_eq!(s.light.exposure, 0.65);
|
||||
assert_eq!((s.light.contrast, s.light.highlights, s.light.shadows, s.light.whites, s.light.blacks), (-14.0, -58.0, 41.0, 9.0, -17.0));
|
||||
assert_eq!((s.effects.texture, s.effects.clarity, s.effects.dehaze), (6.0, 11.0, 4.0));
|
||||
assert_eq!((s.color.vibrance, s.color.saturation), (19.0, -3.0));
|
||||
assert_eq!(s.mixer.orange.hue, -7.0);
|
||||
assert_eq!(s.mixer.blue.sat, -22.0);
|
||||
assert_eq!(s.mixer.aqua.lum, 13.0);
|
||||
assert_eq!((s.curve.shadows, s.curve.highlights, s.curve.split_mid), (5.0, -8.0, 55.0));
|
||||
assert_eq!(s.curve.master.len(), 4);
|
||||
assert_eq!(s.curve.refine_saturation, 40.0);
|
||||
assert!((s.curve.master[1].x - 64.0 / 255.0).abs() < 1e-9 && (s.curve.master[1].y - 52.0 / 255.0).abs() < 1e-9);
|
||||
assert!(s.curve.red.is_empty(), "identity channel curve maps to no curve");
|
||||
assert_eq!((s.grading.shadows.hue, s.grading.shadows.sat), (210.0, 14.0));
|
||||
assert_eq!((s.grading.highlights.hue, s.grading.highlights.sat), (40.0, 9.0));
|
||||
assert_eq!((s.grading.midtones.hue, s.grading.midtones.sat), (120.0, 6.0));
|
||||
assert_eq!((s.grading.balance, s.grading.blending), (20.0, 70.0));
|
||||
assert_eq!((s.detail.sharpen_amount, s.detail.sharpen_radius, s.detail.sharpen_detail, s.detail.sharpen_masking), (55.0, 1.2, 30.0, 12.0));
|
||||
assert_eq!((s.detail.nr_luminance, s.detail.nr_color), (18.0, 25.0));
|
||||
assert_eq!(s.vignette.amount, -21.0);
|
||||
assert_eq!(s.vignette.style, VignetteStyle::ColorPriority);
|
||||
assert_eq!((s.grain.amount, s.grain.size, s.grain.roughness), (15.0, 30.0, 60.0));
|
||||
assert_eq!(s.geometry.upright, Upright::Level);
|
||||
assert_eq!(s.geometry.vertical, -10.0);
|
||||
assert!(s.optics.remove_ca);
|
||||
assert_eq!(s.treatment, lightcraft_develop::Treatment::Color);
|
||||
let cal = s.calibration;
|
||||
assert_eq!(
|
||||
(cal.shadows_tint, cal.red_hue, cal.red_sat, cal.green_hue, cal.green_sat, cal.blue_hue, cal.blue_sat),
|
||||
(-7.0, 12.0, 20.0, -5.0, 3.0, -15.0, 25.0)
|
||||
);
|
||||
let c = s.crop.geometry;
|
||||
assert_eq!((c.rect.x0, c.rect.y0, c.rect.x1, c.rect.y1, c.angle), (0.05, 0.1, 0.8, 0.9, 1.5));
|
||||
}
|
||||
|
||||
/// A sidecar curve with a `NaN` or `inf` point (Rust's `parse` reads both) is not a curve:
|
||||
/// it is left out, rather than stored with a point the curve editor can't place.
|
||||
#[test]
|
||||
fn curves_with_non_finite_points_are_left_out() {
|
||||
for bad in ["NaN, 0", "64, inf", "-inf, 3"] {
|
||||
let x = SIDECAR.replace("<rdf:li>64, 52</rdf:li>", &format!("<rdf:li>{bad}</rdf:li>"));
|
||||
let partial = to_partial(&props(&x), Target::RawAbsolute);
|
||||
let s = apply_partial(&DevelopSettings::for_raw(5000.0, 0.0), &partial, 1.0);
|
||||
assert!(s.curve.master.is_empty(), "{bad}: {:?}", s.curve.master);
|
||||
assert!(s.curve.master.iter().all(|p| p.x.is_finite() && p.y.is_finite()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_present_fields_are_in_the_partial() {
|
||||
let x = r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description
|
||||
xmlns:c="http://ns.adobe.com/camera-raw-settings/1.0/" c:Vibrance="+30" c:GrainAmount="10"/></rdf:RDF>"#;
|
||||
let partial = to_partial(&props(x), Target::Any);
|
||||
assert_eq!(partial, json!({"color": {"vibrance": 30.0}, "grain": {"amount": 10.0}}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hdr_edit_mode_turns_hdr_editing_on_or_off() {
|
||||
let x = |v: &str| {
|
||||
format!(
|
||||
r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description
|
||||
xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:HDREditMode="{v}" crs:Exposure2012="+1.5"/></rdf:RDF>"#
|
||||
)
|
||||
};
|
||||
let on = apply_partial(&DevelopSettings::default(), &to_partial(&props(&x("1")), Target::RawAbsolute), 1.0);
|
||||
assert!(on.hdr.enabled);
|
||||
assert_eq!(on.light.exposure, 1.5);
|
||||
assert_eq!(on.hdr.max_ev, lightcraft_develop::Hdr::DEFAULT_MAX_EV, "the rest of the HDR settings keep their defaults");
|
||||
let true_form = apply_partial(&DevelopSettings::default(), &to_partial(&props(&x("True")), Target::RawAbsolute), 1.0);
|
||||
assert!(true_form.hdr.enabled);
|
||||
let mut hdr = DevelopSettings::default();
|
||||
hdr.hdr.enabled = true;
|
||||
assert!(!apply_partial(&hdr, &to_partial(&props(&x("0")), Target::RawAbsolute), 1.0).hdr.enabled, "0 turns it off");
|
||||
// without the field nothing about HDR changes
|
||||
let plain = r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description
|
||||
xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Exposure2012="+1.5"/></rdf:RDF>"#;
|
||||
assert!(to_partial(&props(plain), Target::RawAbsolute).get("hdr").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn element_form_bw_and_incremental_wb() {
|
||||
let x = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/">
|
||||
<crs:ConvertToGrayscale>True</crs:ConvertToGrayscale>
|
||||
<crs:GrayMixerBlue>-35</crs:GrayMixerBlue>
|
||||
<crs:IncrementalTemperature>25</crs:IncrementalTemperature>
|
||||
<crs:IncrementalTint>-6</crs:IncrementalTint>
|
||||
<crs:Temperature>4800</crs:Temperature>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
let p = props(x);
|
||||
let rendered = apply_partial(&DevelopSettings::default(), &to_partial(&p, Target::Rendered), 1.0);
|
||||
assert_eq!(rendered.treatment, lightcraft_develop::Treatment::Bw);
|
||||
assert_eq!(rendered.bw_mix.blue, -35.0);
|
||||
assert!((rendered.wb.temp - rel_to_kelvin(25.0)).abs() < 1e-6 && rendered.wb.temp > 6500.0);
|
||||
assert_eq!(rendered.wb.tint, -6.0);
|
||||
let raw = apply_partial(&DevelopSettings::default(), &to_partial(&p, Target::RawAbsolute), 1.0);
|
||||
assert_eq!(raw.wb.temp, 4800.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_wb_and_already_applied() {
|
||||
let x = r#"<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:WhiteBalance="Daylight" crs:Temperature="5500" crs:Tint="10" crs:AlreadyApplied="True"/>"#;
|
||||
let p = props(x);
|
||||
assert_eq!(to_partial(&p, Target::RawAbsolute), json!({"wb": {"mode": "daylight"}}));
|
||||
assert!(!has_adjustments(&p));
|
||||
let bookkeeping = r#"<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Version="1" crs:HasSettings="True"/>"#;
|
||||
assert!(!has_adjustments(&props(bookkeeping)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_kelvin_on_relative_wb_raws_shifts_from_the_as_shot_white() {
|
||||
// Issue #510: a Sony ARW edited in Lightroom to Custom 3578 K / −5 next to an as-shot white
|
||||
// of 3650 K / −2 (written for this test from the numbers in the issue).
|
||||
let x = r#"<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:WhiteBalance="Custom" crs:Temperature="3578" crs:Tint="-5" crs:AsShotTemperature="3650" crs:AsShotTint="-2"/>"#;
|
||||
let p = props(x);
|
||||
let rel = to_partial(&p, Target::RawRelative);
|
||||
// 3650 → 3578 K is +5.5 mired: the same shift from 6500 K lands near 6275 K on our scale
|
||||
let t = rel["wb"]["temp"].as_f64().unwrap();
|
||||
assert!((t - 6275.0).abs() < 5.0, "{t}");
|
||||
assert_eq!(rel["wb"]["tint"], -3.0);
|
||||
assert_eq!(rel["wb"]["mode"], "custom");
|
||||
// a rendered file without `Incremental*` fields shifts the same way; a raw with a measured
|
||||
// illuminant (and a preset) keeps the Kelvin value
|
||||
assert_eq!(to_partial(&p, Target::Rendered)["wb"]["temp"], rel["wb"]["temp"]);
|
||||
assert_eq!(to_partial(&p, Target::RawAbsolute)["wb"]["temp"], 3578.0);
|
||||
assert_eq!(to_partial(&p, Target::Any)["wb"]["temp"], 3578.0);
|
||||
// Kelvin read as Kelvin says so, so it stays Kelvin on a raw with that scale; a shift does not
|
||||
assert_eq!(to_partial(&p, Target::RawAbsolute)["wb"]["scale"], "kelvin");
|
||||
assert_eq!(to_partial(&p, Target::Any)["wb"]["scale"], "kelvin");
|
||||
assert!(rel["wb"].get("scale").is_none() && to_partial(&p, Target::Rendered)["wb"].get("scale").is_none());
|
||||
// the as-shot fields are a reference, not an adjustment: nothing to report
|
||||
assert!(to_partial_report(&p, None, Target::RawRelative, 1.5).1.is_empty());
|
||||
// no tint next to the as-shot tint: the custom tint is taken as the shift itself
|
||||
let no_tint = props(&x.replace(r#" crs:AsShotTint="-2""#, ""));
|
||||
assert_eq!(to_partial(&no_tint, Target::RawRelative)["wb"]["tint"], -5.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_kelvin_without_an_as_shot_reference_stays_as_shot_and_is_reported() {
|
||||
// The same edit from a Lightroom catalog, which keeps no as-shot white for Custom photos:
|
||||
// 3578 K read on the relative scale would be a large blue shift (issue #510)
|
||||
let x = r#"<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:WhiteBalance="Custom" crs:Temperature="3578" crs:Tint="-5" crs:Exposure2012="+0.3"/>"#;
|
||||
let p = props(x);
|
||||
let (partial, unmapped) = to_partial_report(&p, None, Target::RawRelative, 1.5);
|
||||
assert_eq!(partial["wb"], json!({"mode": "asShot"}));
|
||||
assert_eq!(partial["light"]["exposure"], 0.3);
|
||||
assert_eq!(unmapped.len(), 1, "{unmapped:?}");
|
||||
assert!(unmapped[0].starts_with("Temperature, Tint"), "{unmapped:?}");
|
||||
// a raw with a measured illuminant and a rendered file read it as before, and report nothing
|
||||
assert_eq!(to_partial(&p, Target::RawAbsolute)["wb"]["temp"], 3578.0);
|
||||
assert_eq!(to_partial(&p, Target::Rendered)["wb"]["temp"], 3578.0);
|
||||
assert!(to_partial_report(&p, None, Target::RawAbsolute, 1.5).1.is_empty());
|
||||
// an unusable reference (zero) counts as none
|
||||
let zero = props(&x.replace(r#" crs:Tint="-5""#, r#" crs:Tint="-5" crs:AsShotTemperature="0""#));
|
||||
assert_eq!(to_partial(&zero, Target::RawRelative)["wb"], json!({"mode": "asShot"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_follows_the_file() {
|
||||
use lightcraft_catalog::MediaKind;
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "ARW", false, ""), Target::RawRelative);
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "nef", false, "NIKON CORPORATION NIKON D7500"), Target::RawRelative);
|
||||
// Lightroom's `fileFormat` name for proprietary raws
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "RAW", false, "SONY ILCE-7M2"), Target::RawRelative);
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "DNG", false, ""), Target::RawAbsolute);
|
||||
// a raw shown from its embedded preview develops like a rendered file
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "ARW", true, "SONY ILCE-7M3"), Target::Rendered);
|
||||
assert_eq!(Target::for_file(MediaKind::Image, "JPG", false, "SONY ILCE-7M3"), Target::Rendered);
|
||||
// a camera with measured matrices edits in Kelvin (issue #730), under any of its names
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "ARW", false, "SONY ILCE-7M3"), Target::RawAbsolute);
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "RAW", false, "ILCE-7M3"), Target::RawAbsolute);
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "NEF", false, "NIKON CORPORATION NIKON D850"), Target::RawAbsolute);
|
||||
assert_eq!(Target::for_file(MediaKind::Raw, "CR2", false, "Canon Canon EOS 5D Mark III"), Target::RawAbsolute);
|
||||
let mut p =
|
||||
lightcraft_catalog::Photo::new(lightcraft_catalog::PhotoId(1), lightcraft_catalog::Source::Demo { scene: 0 }, "a.arw", "ARW", 1, 1, "");
|
||||
p.kind = MediaKind::Raw;
|
||||
assert_eq!(Target::for_photo(&p), Target::RawRelative);
|
||||
p.meta.camera = "SONY ILCE-7M3".into();
|
||||
assert_eq!(Target::for_photo(&p), Target::RawAbsolute);
|
||||
}
|
||||
|
||||
/// Lightroom writes `crs:Temperature` as Kelvin for a raw whose camera LightCraft has matrices for: the value
|
||||
/// is read as written, marked Kelvin, and the as-shot reference is not needed (issue #730); the same packet on
|
||||
/// a raw without matrices still takes the #510 shift.
|
||||
#[test]
|
||||
fn kelvin_is_direct_on_raws_whose_camera_has_matrices() {
|
||||
use lightcraft_catalog::MediaKind;
|
||||
let x = r#"<rdf:Description xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:WhiteBalance="Custom" crs:Temperature="4650" crs:Tint="+3" crs:AsShotTemperature="5400" crs:AsShotTint="-1"/>"#;
|
||||
let p = props(x);
|
||||
let a7m3 = Target::for_file(MediaKind::Raw, "ARW", false, "SONY ILCE-7M3");
|
||||
assert_eq!(to_partial(&p, a7m3)["wb"], json!({"mode": "custom", "temp": 4650.0, "tint": 3.0, "scale": "kelvin"}));
|
||||
let a7m2 = Target::for_file(MediaKind::Raw, "ARW", false, "SONY ILCE-7M2");
|
||||
let shifted = to_partial(&p, a7m2);
|
||||
assert!(shifted["wb"]["temp"].as_f64().is_some_and(|t| t > 5000.0 && t < 6500.0), "{shifted}");
|
||||
assert_eq!(shifted["wb"]["tint"], 4.0);
|
||||
assert!(shifted["wb"].get("scale").is_none());
|
||||
// without the reference the Kelvin camera still reads it, the other stays As Shot
|
||||
let bare = props(&x.replace(r#" crs:AsShotTemperature="5400" crs:AsShotTint="-1""#, ""));
|
||||
assert_eq!(to_partial(&bare, a7m3)["wb"]["temp"], 4650.0);
|
||||
assert_eq!(to_partial(&bare, a7m2)["wb"], json!({"mode": "asShot"}));
|
||||
// a named preset carries no numbers either way
|
||||
let daylight = props(&x.replace(r#"crs:WhiteBalance="Custom""#, r#"crs:WhiteBalance="Daylight""#));
|
||||
assert_eq!(to_partial(&daylight, a7m3)["wb"], json!({"mode": "daylight"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xmp_preset_with_name_and_group() {
|
||||
// Written for this test: a minimal preset-shaped packet with localized name/group.
|
||||
let x = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:PresetType="Normal" crs:UUID="0123ABCD" crs:Contrast2012="+25" crs:SupportsAmount="True">
|
||||
<crs:Name><rdf:Alt><rdf:li xml:lang="x-default">Punchy Test</rdf:li></rdf:Alt></crs:Name>
|
||||
<crs:Group><rdf:Alt><rdf:li xml:lang="x-default">My Looks</rdf:li></rdf:Alt></crs:Group>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
let p = preset_from_xmp(x, "file").unwrap();
|
||||
assert_eq!((p.name.as_str(), p.group.as_str(), p.id.as_str()), ("Punchy Test", "My Looks", "user.xmp.0123abcd"));
|
||||
assert_eq!(p.settings, json!({"light": {"contrast": 25.0}}));
|
||||
assert!(!p.builtin);
|
||||
assert!(preset_from_xmp("<x/>", "f").is_none());
|
||||
}
|
||||
|
||||
/// A preset packet (written for this test) with the bookkeeping fields Lightroom presets carry.
|
||||
fn preset_packet(extra_attrs: &str, extra_elems: &str) -> String {
|
||||
format!(
|
||||
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"
|
||||
crs:PresetType="Normal" crs:Cluster="" crs:UUID="0123ABCD" crs:SupportsAmount2="True" crs:SupportsAmount="True"
|
||||
crs:RequiresRGBTables="False" crs:Contrast2012="+25" crs:LensProfileEnable="0" crs:OverrideLookVignette="False"
|
||||
crs:CropConstrainToWarp="0" crs:AsShotTemperature="5500" crs:AsShotTint="10" {extra_attrs}>
|
||||
<crs:SortName><rdf:Alt><rdf:li xml:lang="x-default"/></rdf:Alt></crs:SortName>
|
||||
<crs:Description><rdf:Alt><rdf:li xml:lang="x-default"/></rdf:Alt></crs:Description>
|
||||
{extra_elems}
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_curves_need_the_master_and_all_channel_curves() {
|
||||
// Lightroom applies red / green / blue curves only when the master and all three are present
|
||||
let seq = |name: &str, pts: &str| format!("<crs:{name}><rdf:Seq>{pts}</rdf:Seq></crs:{name}>");
|
||||
let identity = "<rdf:li>0, 0</rdf:li><rdf:li>255, 255</rdf:li>";
|
||||
let bent = "<rdf:li>0, 0</rdf:li><rdf:li>64, 40</rdf:li><rdf:li>255, 255</rdf:li>";
|
||||
let packet = |curves: &[String]| {
|
||||
format!(
|
||||
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:ToneCurveName2012="Custom">{}
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#,
|
||||
curves.concat()
|
||||
)
|
||||
};
|
||||
let partial = |curves: &[String]| to_partial(&props(&packet(curves)), Target::RawAbsolute);
|
||||
let (master, red, green, blue) = (
|
||||
seq("ToneCurvePV2012", identity),
|
||||
seq("ToneCurvePV2012Red", identity),
|
||||
seq("ToneCurvePV2012Green", bent),
|
||||
seq("ToneCurvePV2012Blue", identity),
|
||||
);
|
||||
// a channel curve alone, or with the master but without its two siblings: ignored
|
||||
let alone = partial(std::slice::from_ref(&green));
|
||||
assert!(alone.pointer("/curve/green").is_none(), "{alone}");
|
||||
let master_and_green = partial(&[master.clone(), green.clone()]);
|
||||
assert!(master_and_green.pointer("/curve/green").is_none() && master_and_green.pointer("/curve/master").is_some(), "{master_and_green}");
|
||||
// all four: read
|
||||
let all = partial(&[master, red, green, blue]);
|
||||
assert!(["/curve/master", "/curve/red", "/curve/green", "/curve/blue"].iter().all(|p| all.pointer(p).is_some()), "{all}");
|
||||
}
|
||||
|
||||
fn unmapped(x: &str) -> Vec<String> {
|
||||
to_partial_report(&props(x), None, Target::Any, 1.5).1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_bookkeeping_is_not_reported_but_real_gaps_are() {
|
||||
let empty_points = "<crs:PointColors><rdf:Seq><rdf:li>-1.000000, -1.000000, -1.000000, -1.000000</rdf:li></rdf:Seq></crs:PointColors>";
|
||||
assert_eq!(unmapped(&preset_packet(r#"crs:HDREditMode="0""#, empty_points)), Vec::<String>::new());
|
||||
// a used Point Color slot and an unknown adjustment still are (an HDR edit is carried over)
|
||||
let used_points = "<crs:PointColors><rdf:Seq><rdf:li>0.5, 0.2, 0.1, 10, 0, 0, 0, 0</rdf:li></rdf:Seq></crs:PointColors>";
|
||||
let got = unmapped(&preset_packet(r#"crs:HDREditMode="1" crs:FutureSlider="12""#, used_points));
|
||||
assert_eq!(got, ["FutureSlider", "PointColors"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lightroom_profile_bookkeeping_is_not_reported() {
|
||||
// what Lightroom Classic writes next to every raw's edit: none of it changes the rendering
|
||||
let bookkeeping = r#"crs:CompatibleVersion="268435456" crs:CameraProfileDigest="0A1B" crs:LensProfileDigest="2C3D"
|
||||
crs:LensProfileName="Sony FE 24-70mm" crs:LensProfileFilename="x.lcp" crs:LensProfileIsEmbedded="False"
|
||||
crs:LensProfileSetup="LensDefaults" crs:LensProfileDistortionScale="100" crs:LensProfileVignettingScale="100"
|
||||
crs:CropConstrainToUnitSquare="1""#;
|
||||
let look = r#"<crs:Look rdf:parseType="Resource"><crs:Name>Vivid</crs:Name></crs:Look>"#;
|
||||
assert_eq!(unmapped(&preset_packet(bookkeeping, "")), Vec::<String>::new());
|
||||
assert_eq!(unmapped(&preset_packet(bookkeeping, look)), ["Look"], "the Look is a real gap");
|
||||
// a lens profile's strength away from 100 % is an adjustment we don't carry over
|
||||
let scaled = preset_packet(r#"crs:LensProfileDistortionScale="60""#, "");
|
||||
assert_eq!(unmapped(&scaled), ["LensProfileDistortionScale"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_lens_profile_switch_keeps_embedded_corrections() {
|
||||
// Lightroom applies a file's built-in lens corrections regardless of its profile switch,
|
||||
// and ours are only those: a preset's `LensProfileEnable=0` must not turn them off
|
||||
let p = props(&preset_packet("", ""));
|
||||
let mut d = DevelopSettings::default();
|
||||
d.optics.lens_profile = true;
|
||||
assert!(apply_partial(&d, &to_partial(&p, Target::Any), 1.0).optics.lens_profile);
|
||||
let on = props(&preset_packet("", "").replace(r#"crs:LensProfileEnable="0""#, r#"crs:LensProfileEnable="1""#));
|
||||
assert!(apply_partial(&DevelopSettings::default(), &to_partial(&on, Target::Any), 1.0).optics.lens_profile);
|
||||
}
|
||||
@@ -446,337 +446,4 @@ pub fn refit_radials(partial: &mut Value, from: f64, to: f64) {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_develop::{DevelopSettings, MaskOp, MaskShape};
|
||||
|
||||
/// A packet in the shape local corrections take (values written for this test).
|
||||
const PACKET: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Exposure2012="0.2">
|
||||
<crs:MaskGroupBasedCorrections><rdf:Seq>
|
||||
<rdf:li><rdf:Description crs:What="Correction" crs:CorrectionAmount="1" crs:CorrectionActive="true" crs:CorrectionName="Darker sky"
|
||||
crs:LocalExposure2012="-0.25" crs:LocalSaturation="0.3" crs:LocalTemperature="-0.1">
|
||||
<crs:CorrectionMasks><rdf:Seq>
|
||||
<rdf:li crs:What="Mask/Image" crs:MaskSubType="2" crs:MaskBlendMode="0" crs:MaskInverted="false"/>
|
||||
<rdf:li crs:What="Mask/Gradient" crs:MaskBlendMode="2" crs:FullX="0.5" crs:FullY="0" crs:ZeroX="0.5" crs:ZeroY="0.6"/>
|
||||
</rdf:Seq></crs:CorrectionMasks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:What="Correction" crs:CorrectionAmount="0.5" crs:LocalContrast2012="0.2">
|
||||
<crs:CorrectionMasks><rdf:Seq>
|
||||
<rdf:li crs:What="Mask/CircularGradient" crs:Top="0.3" crs:Left="0.2" crs:Bottom="0.7" crs:Right="0.8" crs:Angle="10" crs:Feather="40" crs:Flipped="true" crs:Version="2"/>
|
||||
<rdf:li crs:What="Mask/RangeMask" crs:MaskBlendMode="2"><crs:CorrectionRangeMask crs:Type="2" crs:LumRange="0.4 0.5 0.8 0.9"/></rdf:li>
|
||||
<rdf:li crs:What="Mask/Image" crs:MaskSubType="9"/>
|
||||
</rdf:Seq></crs:CorrectionMasks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:What="Correction" crs:CorrectionActive="false" crs:LocalExposure2012="1">
|
||||
<crs:CorrectionMasks><rdf:Seq><rdf:li crs:What="Mask/Image" crs:MaskSubType="1"/></rdf:Seq></crs:CorrectionMasks>
|
||||
</rdf:Description></rdf:li>
|
||||
</rdf:Seq></crs:MaskGroupBasedCorrections>
|
||||
<crs:PaintBasedCorrections><rdf:Seq>
|
||||
<rdf:li crs:What="Correction" crs:LocalClarity2012="0.4"><crs:CorrectionMasks><rdf:Seq>
|
||||
<rdf:li crs:What="Mask/Paint" crs:Radius="0.05" crs:Flow="0.8" crs:CenterWeight="0.3" crs:MaskValue="1">
|
||||
<crs:Dabs><rdf:Seq><rdf:li>d 0.1 0.2</rdf:li><rdf:li>d 0.15 0.22</rdf:li></rdf:Seq></crs:Dabs></rdf:li>
|
||||
<rdf:li crs:What="Mask/Paint" crs:Radius="0.02" crs:MaskValue="1"><crs:Dabs><rdf:Seq><rdf:li>d 0.5 0.5</rdf:li></rdf:Seq></crs:Dabs></rdf:li>
|
||||
</rdf:Seq></crs:CorrectionMasks></rdf:li>
|
||||
</rdf:Seq></crs:PaintBasedCorrections>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
|
||||
fn settings() -> (DevelopSettings, Vec<String>) {
|
||||
let d = lightcraft_meta::parse_xmp(PACKET).unwrap();
|
||||
let (partial, unmapped) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
(DevelopSettings::default().merged(&partial).expect("valid settings"), unmapped)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrections_become_masks() {
|
||||
let (s, unmapped) = settings();
|
||||
assert_eq!(s.light.exposure, 0.2, "global settings still map");
|
||||
assert_eq!(s.masks.len(), 3, "inactive corrections are skipped: {:?}", s.masks);
|
||||
let sky = &s.masks[0];
|
||||
assert_eq!(sky.name, "Darker sky");
|
||||
assert_eq!((sky.adjust.exposure, sky.adjust.saturation, sky.adjust.temp, sky.adjust.amount), (-1.0, 30.0, -10.0, 100.0));
|
||||
assert_eq!(sky.components[0].shape, MaskShape::Sky);
|
||||
assert_eq!(sky.components[1].op, MaskOp::Intersect);
|
||||
let MaskShape::Linear { start, end } = &sky.components[1].shape else { panic!() };
|
||||
assert_eq!((start.y, end.y), (0.0, 0.6), "full effect at the Full point");
|
||||
let rad = &s.masks[1];
|
||||
assert_eq!((rad.name.as_str(), rad.adjust.contrast, rad.adjust.amount), ("Mask 2", 20.0, 50.0));
|
||||
let MaskShape::Radial { center, rx, ry, angle, feather, invert } = &rad.components[0].shape else { panic!() };
|
||||
assert!((center.x - 0.5).abs() < 1e-9 && (center.y - 0.5).abs() < 1e-9);
|
||||
assert!((rx - 0.3).abs() < 1e-9 && (ry - 0.2 / 1.5).abs() < 1e-9, "radii in long-edge units: {rx} {ry}");
|
||||
assert_eq!((*angle, *feather, *invert), (10.0, 40.0, false), "Flipped=\"true\" is Lightroom's ordinary radial: effect inside");
|
||||
assert!(!rad.components[0].invert);
|
||||
let MaskShape::LuminanceRange { lo, hi, lo_feather, .. } = &rad.components[1].shape else { panic!() };
|
||||
assert!(lo < hi && *lo_feather > 0.0);
|
||||
let brush = &s.masks[2];
|
||||
assert_eq!(brush.adjust.clarity, 40.0);
|
||||
assert_eq!(brush.components.len(), 1, "the brush's dab runs are one component");
|
||||
let MaskShape::Brush { strokes } = &brush.components[0].shape else { panic!() };
|
||||
assert_eq!((strokes.len(), strokes[0].points.len(), strokes[0].flow, strokes[0].feather), (2, 2, 80.0, 30.0));
|
||||
assert_eq!(unmapped, vec!["Mask: AI mask (9)".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_render() {
|
||||
let (s, _) = settings();
|
||||
let img = lightcraft_scenes::demo_library()[0].render(96, 64);
|
||||
let render = |d: &DevelopSettings| {
|
||||
lightcraft_pipeline::render(&img, &Default::default(), d, &lightcraft_pipeline::RenderRequest::fit(96, 64)).image.data
|
||||
};
|
||||
assert_ne!(render(&DevelopSettings { light: s.light, ..Default::default() }), render(&s), "the masks change the picture");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_to_white_stays_open_and_unmapped_local_sliders_are_reported() {
|
||||
// written for this test: a highlights range (full from 0.85 up to white) carrying a local slider we lack
|
||||
let x = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/">
|
||||
<crs:MaskGroupBasedCorrections><rdf:Seq>
|
||||
<rdf:li><rdf:Description crs:What="Correction" crs:LocalClarity2012="-0.3" crs:LocalGrain="0.4" crs:LocalCurveRefineSaturation="100">
|
||||
<crs:CorrectionMasks><rdf:Seq>
|
||||
<rdf:li crs:What="Mask/RangeMask"><crs:CorrectionRangeMask crs:Type="2" crs:LumRange="0.6 0.85 1 1"/></rdf:li>
|
||||
</rdf:Seq></crs:CorrectionMasks>
|
||||
</rdf:Description></rdf:li>
|
||||
</rdf:Seq></crs:MaskGroupBasedCorrections>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
let d = lightcraft_meta::parse_xmp(x).unwrap();
|
||||
let (partial, unmapped) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
let s = DevelopSettings::default().merged(&partial).expect("valid settings");
|
||||
let MaskShape::LuminanceRange { hi, hi_feather, .. } = &s.masks[0].components[0].shape else { panic!() };
|
||||
assert_eq!((*hi, *hi_feather), (1.0, 0.0), "brighter than scene white is still in the range");
|
||||
assert_eq!(s.masks[0].adjust.clarity, -30.0);
|
||||
assert_eq!(unmapped, ["Mask: LocalGrain"], "a refine saturation of 100 is neutral, not reported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lrtemplate_corrections() {
|
||||
let t = r#"s = { title = "Grad", value = { settings = { Exposure2012 = 0.1, GradientBasedCorrections = {
|
||||
{ What = "Correction", CorrectionAmount = 1, LocalExposure2012 = -0.5, CorrectionMasks = {
|
||||
{ What = "Mask/Gradient", ZeroX = 0.5, ZeroY = 0.5, FullX = 0.5, FullY = 0, MaskValue = 1 } } } } } } }"#;
|
||||
let v = crate::preset_import::read_presets("Grad.lrtemplate", t.as_bytes(), None).unwrap();
|
||||
assert!(v[0].unmapped.is_empty(), "{:?}", v[0].unmapped);
|
||||
let s = DevelopSettings::default().merged(&v[0].preset.settings).unwrap();
|
||||
assert_eq!(s.masks.len(), 1);
|
||||
assert_eq!(s.masks[0].adjust.exposure, -2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_add_masks_once() {
|
||||
let (s, _) = settings();
|
||||
let partial = json!({"masks": serde_json::to_value(&s.masks).unwrap(), "light": {"exposure": 0.5}});
|
||||
let p =
|
||||
lightcraft_develop::Preset { id: "t".into(), name: "t".into(), group: "g".into(), settings: partial, favorite: false, builtin: false };
|
||||
let mut mine = DevelopSettings::default();
|
||||
mine.masks.push(lightcraft_develop::Mask { id: 7, name: "Mine".into(), ..Default::default() });
|
||||
let once = p.apply(&mine, 1.0);
|
||||
assert_eq!(once.masks.len(), 4, "added to the photo's own mask");
|
||||
assert_eq!(once.masks[1].id, 8, "fresh ids");
|
||||
assert_eq!(p.apply(&once, 1.0).masks.len(), 4, "applying again adds nothing");
|
||||
let half = p.apply(&mine, 0.5);
|
||||
assert_eq!(half.masks[1].adjust.amount, 50.0, "amount scales the masks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidecar_radials_fit_the_photo() {
|
||||
let mut v = json!({"masks": [{"components": [{"shape": {"kind": "radial", "rx": 0.3, "ry": 0.2}}]}]});
|
||||
refit_radials(&mut v, 1.5, 1.0);
|
||||
let s = &v["masks"][0]["components"][0]["shape"];
|
||||
assert!((s["rx"].as_f64().unwrap() - 0.3).abs() < 1e-9);
|
||||
assert!((s["ry"].as_f64().unwrap() - 0.3).abs() < 1e-9, "square photo: y radius = its box half-height");
|
||||
}
|
||||
|
||||
/// One radial correction in `container`, with `attrs` on its mask component (values written
|
||||
/// for this test; the component attributes follow what Lightroom Classic writes).
|
||||
fn radial_packet(container: &str, attrs: &str) -> String {
|
||||
format!(
|
||||
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Exposure2012="0">
|
||||
<crs:{container}><rdf:Seq>
|
||||
<rdf:li><rdf:Description crs:What="Correction" crs:CorrectionAmount="1" crs:LocalExposure2012="0.25">
|
||||
<crs:CorrectionMasks><rdf:Seq>
|
||||
<rdf:li crs:What="Mask/CircularGradient" crs:MaskValue="1" crs:Top="0.25" crs:Left="0.25" crs:Bottom="0.75" crs:Right="0.75" crs:Angle="0" crs:Midpoint="50" crs:Roundness="0" {attrs}/>
|
||||
</rdf:Seq></crs:CorrectionMasks>
|
||||
</rdf:Description></rdf:li>
|
||||
</rdf:Seq></crs:{container}>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#
|
||||
)
|
||||
}
|
||||
|
||||
fn radial_settings(container: &str, attrs: &str) -> DevelopSettings {
|
||||
let d = lightcraft_meta::parse_xmp(&radial_packet(container, attrs)).unwrap();
|
||||
let (partial, unmapped) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
assert!(unmapped.is_empty(), "{unmapped:?}");
|
||||
let s = DevelopSettings::default().merged(&partial).unwrap();
|
||||
assert_eq!(s.masks.len(), 1, "{:?}", s.masks);
|
||||
s
|
||||
}
|
||||
|
||||
/// (the radial's `invert`, its feather, the component's `invert`).
|
||||
fn radial_of(s: &DevelopSettings) -> (bool, f64, bool) {
|
||||
let c = &s.masks[0].components[0];
|
||||
let MaskShape::Radial { invert, feather, .. } = &c.shape else { panic!("{:?}", c.shape) };
|
||||
(*invert, *feather, c.invert)
|
||||
}
|
||||
|
||||
/// How much brighter the mask makes the centre and a corner of a flat grey frame (8-bit green).
|
||||
fn lift_inside_outside(s: &DevelopSettings) -> (i32, i32) {
|
||||
let img = lightcraft_raster::Image { width: 90, height: 60, data: vec![[0.18f32; 3]; 90 * 60] };
|
||||
let render =
|
||||
|d: &DevelopSettings| lightcraft_pipeline::render(&img, &Default::default(), d, &lightcraft_pipeline::RenderRequest::fit(90, 60)).image;
|
||||
let (with, without) = (render(s), render(&DevelopSettings { light: s.light, ..Default::default() }));
|
||||
let g = |im: &lightcraft_raster::Rgba8, x: usize, y: usize| i32::from(im.data[y * im.width + x][1]);
|
||||
(g(&with, 45, 30) - g(&without, 45, 30), g(&with, 3, 3) - g(&without, 3, 3))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lightroom_radial_flipped_is_inside() {
|
||||
// as Lightroom Classic writes an ordinary radial mask today (#1815)
|
||||
let s = radial_settings("MaskGroupBasedCorrections", r#"crs:MaskInverted="false" crs:Feather="25" crs:Flipped="true" crs:Version="2""#);
|
||||
assert_eq!(radial_of(&s), (false, 25.0, false));
|
||||
let (inside, outside) = lift_inside_outside(&s);
|
||||
assert!(inside > 20 && outside == 0, "the effect is inside the circle: {inside} {outside}");
|
||||
// no MaskInverted at all reads the same
|
||||
let s = radial_settings("MaskGroupBasedCorrections", r#"crs:Feather="25" crs:Flipped="true" crs:Version="2""#);
|
||||
assert_eq!(radial_of(&s), (false, 25.0, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lightroom_radial_mask_inverted_is_outside() {
|
||||
let s = radial_settings("MaskGroupBasedCorrections", r#"crs:MaskInverted="true" crs:Feather="25" crs:Flipped="true" crs:Version="2""#);
|
||||
assert_eq!(radial_of(&s), (false, 25.0, true), "the inversion is the component's");
|
||||
let (inside, outside) = lift_inside_outside(&s);
|
||||
assert!(inside == 0 && outside > 20, "the effect is outside the circle: {inside} {outside}");
|
||||
// version 2 with Flipped="false": outside, the legacy sense of the flag
|
||||
let s = radial_settings("MaskGroupBasedCorrections", r#"crs:MaskInverted="false" crs:Feather="25" crs:Flipped="false" crs:Version="2""#);
|
||||
assert_eq!(radial_of(&s), (true, 25.0, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versionless_group_radial_is_inside_with_half_the_feather() {
|
||||
// Lightroom renders both inside and rewrites them Flipped="true", Feather halved, Version="2"
|
||||
for flipped in ["true", "false"] {
|
||||
let s = radial_settings("MaskGroupBasedCorrections", &format!(r#"crs:MaskInverted="false" crs:Feather="50" crs:Flipped="{flipped}""#));
|
||||
assert_eq!(radial_of(&s), (false, 25.0, false), "Flipped={flipped}");
|
||||
let (inside, outside) = lift_inside_outside(&s);
|
||||
assert!(inside > 20 && outside == 0, "Flipped={flipped}: {inside} {outside}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_radial_filter_is_outside_unless_flipped() {
|
||||
// the process-2012 Radial Filter: effect outside by default, "Invert Mask" = Flipped="true"
|
||||
let s = radial_settings("CircularGradientBasedCorrections", r#"crs:Feather="50" crs:Flipped="false""#);
|
||||
assert_eq!(radial_of(&s), (true, 50.0, false));
|
||||
let (inside, outside) = lift_inside_outside(&s);
|
||||
assert!(inside == 0 && outside > 20, "default: outside: {inside} {outside}");
|
||||
assert_eq!(radial_of(&radial_settings("CircularGradientBasedCorrections", r#"crs:Feather="50""#)), (true, 50.0, false));
|
||||
let s = radial_settings("CircularGradientBasedCorrections", r#"crs:Feather="50" crs:Flipped="true""#);
|
||||
assert_eq!(radial_of(&s), (false, 50.0, false));
|
||||
let (inside, outside) = lift_inside_outside(&s);
|
||||
assert!(inside > 20 && outside == 0, "inverted: inside: {inside} {outside}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lrtemplate_radial_filter_reads_flipped() {
|
||||
// .lrtemplate presets and catalog develop settings are the same Lua tables
|
||||
let t = |flipped: &str| {
|
||||
format!(
|
||||
r#"s = {{ title = "Rad", value = {{ settings = {{ CircularGradientBasedCorrections = {{
|
||||
{{ What = "Correction", CorrectionAmount = 1, LocalExposure2012 = 0.25, CorrectionMasks = {{
|
||||
{{ What = "Mask/CircularGradient", Top = 0.25, Left = 0.25, Bottom = 0.75, Right = 0.75, Angle = 0, Feather = 50, Flipped = {flipped}, MaskValue = 1 }} }} }} }} }} }} }}"#
|
||||
)
|
||||
};
|
||||
for (flipped, outside) in [("true", false), ("false", true)] {
|
||||
let v = crate::preset_import::read_presets("Rad.lrtemplate", t(flipped).as_bytes(), None).unwrap();
|
||||
let s = DevelopSettings::default().merged(&v[0].preset.settings).unwrap();
|
||||
assert_eq!(radial_of(&s).0, outside, "Flipped = {flipped}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Spot removal in the shape Lightroom Classic writes it (values written for this test):
|
||||
/// a healed circle with an explicit source, a cloned circle with an automatic source, a
|
||||
/// brushed removal, a circular-gradient spot, one without a mask, and the legacy list.
|
||||
const SPOTS: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Exposure2012="0.1">
|
||||
<crs:RetouchInfo><rdf:Seq>
|
||||
<rdf:li>centerX = 0.4, centerY = 0.3, radius = 0.01, sourceState = sourceSetExplicitly, sourceX = 0.45, sourceY = 0.3, spotType = heal</rdf:li>
|
||||
</rdf:Seq></crs:RetouchInfo>
|
||||
<crs:RetouchAreas><rdf:Seq>
|
||||
<rdf:li><rdf:Description crs:SpotType="heal" crs:SourceState="sourceSetExplicitly" crs:Method="poisson" crs:SourceX="0.45" crs:OffsetY="0.3" crs:Opacity="1" crs:Feather="0" crs:Seed="1">
|
||||
<crs:Masks><rdf:Seq><rdf:li crs:What="Mask/Ellipse" crs:MaskActive="true" crs:MaskValue="1" crs:X="0.4" crs:Y="0.3" crs:SizeX="0.01" crs:SizeY="0.015"/></rdf:Seq></crs:Masks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:SpotType="clone" crs:SourceState="sourceAutoComputed" crs:Opacity="0.5" crs:Feather="0.25">
|
||||
<crs:Masks><rdf:Seq><rdf:li crs:What="Mask/Ellipse" crs:X="0.7" crs:Y="0.6" crs:SizeX="0.02" crs:SizeY="0.02"/></rdf:Seq></crs:Masks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:SpotType="heal" crs:SourceState="sourceSetExplicitly" crs:SourceX="0.2" crs:OffsetY="0.9">
|
||||
<crs:Masks><rdf:Seq><rdf:li crs:What="Mask/Paint" crs:Radius="0.03" crs:MaskValue="1">
|
||||
<crs:Dabs><rdf:Seq><rdf:li>d 0.1 0.8</rdf:li><rdf:li>d 0.12 0.82</rdf:li><rdf:li>d 0.14 0.84</rdf:li></rdf:Seq></crs:Dabs></rdf:li></rdf:Seq></crs:Masks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:SpotType="heal" crs:SourceX="0.6" crs:OffsetY="0.5">
|
||||
<crs:Masks><rdf:Seq><rdf:li crs:What="Mask/CircularGradient" crs:Top="0.48" crs:Left="0.49" crs:Bottom="0.52" crs:Right="0.51"/></rdf:Seq></crs:Masks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:SpotType="heal">
|
||||
<crs:Masks><rdf:Seq><rdf:li crs:What="Mask/Gradient" crs:FullX="0" crs:FullY="0" crs:ZeroX="1" crs:ZeroY="1"/></rdf:Seq></crs:Masks>
|
||||
</rdf:Description></rdf:li>
|
||||
</rdf:Seq></crs:RetouchAreas>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
|
||||
#[test]
|
||||
fn retouch_areas_become_spots() {
|
||||
use lightcraft_develop::SpotMode;
|
||||
let d = lightcraft_meta::parse_xmp(SPOTS).unwrap();
|
||||
let (partial, unmapped) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
let s = DevelopSettings::default().merged(&partial).expect("valid settings");
|
||||
assert_eq!(s.light.exposure, 0.1, "global settings still map");
|
||||
assert_eq!(s.spots.len(), 4, "the gradient 'spot' is skipped: {:?}", s.spots);
|
||||
let heal = &s.spots[0];
|
||||
assert_eq!((heal.mode, heal.points.len(), heal.opacity, heal.feather), (SpotMode::Heal, 1, 100.0, 0.0));
|
||||
assert!((heal.points[0].x - 0.4).abs() < 1e-9 && (heal.points[0].y - 0.3).abs() < 1e-9);
|
||||
assert!((heal.size - 0.01).abs() < 1e-9, "a landscape target: width fractions are long-edge fractions");
|
||||
let src = heal.source_offset.expect("explicit source");
|
||||
assert!((src.x - 0.05).abs() < 1e-9 && src.y.abs() < 1e-9, "source stored absolute, ours an offset: {src:?}");
|
||||
let clone = &s.spots[1];
|
||||
assert_eq!((clone.mode, clone.opacity, clone.feather, clone.source_offset), (SpotMode::Clone, 50.0, 25.0, None));
|
||||
let brushed = &s.spots[2];
|
||||
assert_eq!((brushed.points.len(), brushed.size), (3, 0.03));
|
||||
let src = brushed.source_offset.expect("explicit source");
|
||||
assert!((src.x - 0.1).abs() < 1e-9 && (src.y - 0.1).abs() < 1e-9);
|
||||
let circ = &s.spots[3];
|
||||
assert!((circ.points[0].x - 0.5).abs() < 1e-9 && (circ.points[0].y - 0.5).abs() < 1e-9 && (circ.size - 0.01).abs() < 1e-9);
|
||||
assert_eq!(unmapped, vec!["Spot: Gradient".to_string()], "{unmapped:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portrait_target_scales_spot_sizes() {
|
||||
let d = lightcraft_meta::parse_xmp(SPOTS).unwrap();
|
||||
let (partial, _) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 2.0 / 3.0);
|
||||
let s = DevelopSettings::default().merged(&partial).unwrap();
|
||||
assert!((s.spots[0].size - 0.01 * 2.0 / 3.0).abs() < 1e-9, "a width fraction on a portrait target: {}", s.spots[0].size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_retouch_info_is_read_on_its_own() {
|
||||
let packet = SPOTS.replace("crs:RetouchAreas", "crs:Ignored");
|
||||
let d = lightcraft_meta::parse_xmp(&packet).unwrap();
|
||||
let (partial, unmapped) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
let s = DevelopSettings::default().merged(&partial).unwrap();
|
||||
assert_eq!(s.spots.len(), 1, "{:?}", s.spots);
|
||||
assert_eq!(s.spots[0].mode, lightcraft_develop::SpotMode::Heal);
|
||||
assert!((s.spots[0].points[0].x - 0.4).abs() < 1e-9 && (s.spots[0].size - 0.01).abs() < 1e-9);
|
||||
assert!(s.spots[0].source_offset.is_some_and(|o| (o.x - 0.05).abs() < 1e-9));
|
||||
assert!(unmapped.iter().any(|u| u == "Ignored"), "{unmapped:?}");
|
||||
assert!(!unmapped.iter().any(|u| u == "RetouchInfo"), "{unmapped:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spots_render() {
|
||||
let d = lightcraft_meta::parse_xmp(SPOTS).unwrap();
|
||||
let (partial, _) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
let s = DevelopSettings::default().merged(&partial).unwrap();
|
||||
let img = lightcraft_scenes::demo_library()[0].render(96, 64);
|
||||
let render = |d: &DevelopSettings| {
|
||||
lightcraft_pipeline::render(&img, &Default::default(), d, &lightcraft_pipeline::RenderRequest::fit(96, 64)).image.data
|
||||
};
|
||||
assert_ne!(render(&DevelopSettings { light: s.light, ..Default::default() }), render(&s), "the spots change the picture");
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,329 @@
|
||||
use super::*;
|
||||
use lightcraft_develop::{DevelopSettings, MaskOp, MaskShape};
|
||||
|
||||
/// A packet in the shape local corrections take (values written for this test).
|
||||
const PACKET: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Exposure2012="0.2">
|
||||
<crs:MaskGroupBasedCorrections><rdf:Seq>
|
||||
<rdf:li><rdf:Description crs:What="Correction" crs:CorrectionAmount="1" crs:CorrectionActive="true" crs:CorrectionName="Darker sky"
|
||||
crs:LocalExposure2012="-0.25" crs:LocalSaturation="0.3" crs:LocalTemperature="-0.1">
|
||||
<crs:CorrectionMasks><rdf:Seq>
|
||||
<rdf:li crs:What="Mask/Image" crs:MaskSubType="2" crs:MaskBlendMode="0" crs:MaskInverted="false"/>
|
||||
<rdf:li crs:What="Mask/Gradient" crs:MaskBlendMode="2" crs:FullX="0.5" crs:FullY="0" crs:ZeroX="0.5" crs:ZeroY="0.6"/>
|
||||
</rdf:Seq></crs:CorrectionMasks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:What="Correction" crs:CorrectionAmount="0.5" crs:LocalContrast2012="0.2">
|
||||
<crs:CorrectionMasks><rdf:Seq>
|
||||
<rdf:li crs:What="Mask/CircularGradient" crs:Top="0.3" crs:Left="0.2" crs:Bottom="0.7" crs:Right="0.8" crs:Angle="10" crs:Feather="40" crs:Flipped="true" crs:Version="2"/>
|
||||
<rdf:li crs:What="Mask/RangeMask" crs:MaskBlendMode="2"><crs:CorrectionRangeMask crs:Type="2" crs:LumRange="0.4 0.5 0.8 0.9"/></rdf:li>
|
||||
<rdf:li crs:What="Mask/Image" crs:MaskSubType="9"/>
|
||||
</rdf:Seq></crs:CorrectionMasks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:What="Correction" crs:CorrectionActive="false" crs:LocalExposure2012="1">
|
||||
<crs:CorrectionMasks><rdf:Seq><rdf:li crs:What="Mask/Image" crs:MaskSubType="1"/></rdf:Seq></crs:CorrectionMasks>
|
||||
</rdf:Description></rdf:li>
|
||||
</rdf:Seq></crs:MaskGroupBasedCorrections>
|
||||
<crs:PaintBasedCorrections><rdf:Seq>
|
||||
<rdf:li crs:What="Correction" crs:LocalClarity2012="0.4"><crs:CorrectionMasks><rdf:Seq>
|
||||
<rdf:li crs:What="Mask/Paint" crs:Radius="0.05" crs:Flow="0.8" crs:CenterWeight="0.3" crs:MaskValue="1">
|
||||
<crs:Dabs><rdf:Seq><rdf:li>d 0.1 0.2</rdf:li><rdf:li>d 0.15 0.22</rdf:li></rdf:Seq></crs:Dabs></rdf:li>
|
||||
<rdf:li crs:What="Mask/Paint" crs:Radius="0.02" crs:MaskValue="1"><crs:Dabs><rdf:Seq><rdf:li>d 0.5 0.5</rdf:li></rdf:Seq></crs:Dabs></rdf:li>
|
||||
</rdf:Seq></crs:CorrectionMasks></rdf:li>
|
||||
</rdf:Seq></crs:PaintBasedCorrections>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
|
||||
fn settings() -> (DevelopSettings, Vec<String>) {
|
||||
let d = lightcraft_meta::parse_xmp(PACKET).unwrap();
|
||||
let (partial, unmapped) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
(DevelopSettings::default().merged(&partial).expect("valid settings"), unmapped)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrections_become_masks() {
|
||||
let (s, unmapped) = settings();
|
||||
assert_eq!(s.light.exposure, 0.2, "global settings still map");
|
||||
assert_eq!(s.masks.len(), 3, "inactive corrections are skipped: {:?}", s.masks);
|
||||
let sky = &s.masks[0];
|
||||
assert_eq!(sky.name, "Darker sky");
|
||||
assert_eq!((sky.adjust.exposure, sky.adjust.saturation, sky.adjust.temp, sky.adjust.amount), (-1.0, 30.0, -10.0, 100.0));
|
||||
assert_eq!(sky.components[0].shape, MaskShape::Sky);
|
||||
assert_eq!(sky.components[1].op, MaskOp::Intersect);
|
||||
let MaskShape::Linear { start, end } = &sky.components[1].shape else { panic!() };
|
||||
assert_eq!((start.y, end.y), (0.0, 0.6), "full effect at the Full point");
|
||||
let rad = &s.masks[1];
|
||||
assert_eq!((rad.name.as_str(), rad.adjust.contrast, rad.adjust.amount), ("Mask 2", 20.0, 50.0));
|
||||
let MaskShape::Radial { center, rx, ry, angle, feather, invert } = &rad.components[0].shape else { panic!() };
|
||||
assert!((center.x - 0.5).abs() < 1e-9 && (center.y - 0.5).abs() < 1e-9);
|
||||
assert!((rx - 0.3).abs() < 1e-9 && (ry - 0.2 / 1.5).abs() < 1e-9, "radii in long-edge units: {rx} {ry}");
|
||||
assert_eq!((*angle, *feather, *invert), (10.0, 40.0, false), "Flipped=\"true\" is Lightroom's ordinary radial: effect inside");
|
||||
assert!(!rad.components[0].invert);
|
||||
let MaskShape::LuminanceRange { lo, hi, lo_feather, .. } = &rad.components[1].shape else { panic!() };
|
||||
assert!(lo < hi && *lo_feather > 0.0);
|
||||
let brush = &s.masks[2];
|
||||
assert_eq!(brush.adjust.clarity, 40.0);
|
||||
assert_eq!(brush.components.len(), 1, "the brush's dab runs are one component");
|
||||
let MaskShape::Brush { strokes } = &brush.components[0].shape else { panic!() };
|
||||
assert_eq!((strokes.len(), strokes[0].points.len(), strokes[0].flow, strokes[0].feather), (2, 2, 80.0, 30.0));
|
||||
assert_eq!(unmapped, vec!["Mask: AI mask (9)".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_render() {
|
||||
let (s, _) = settings();
|
||||
let img = lightcraft_scenes::demo_library()[0].render(96, 64);
|
||||
let render =
|
||||
|d: &DevelopSettings| lightcraft_pipeline::render(&img, &Default::default(), d, &lightcraft_pipeline::RenderRequest::fit(96, 64)).image.data;
|
||||
assert_ne!(render(&DevelopSettings { light: s.light, ..Default::default() }), render(&s), "the masks change the picture");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_to_white_stays_open_and_unmapped_local_sliders_are_reported() {
|
||||
// written for this test: a highlights range (full from 0.85 up to white) carrying a local slider we lack
|
||||
let x = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/">
|
||||
<crs:MaskGroupBasedCorrections><rdf:Seq>
|
||||
<rdf:li><rdf:Description crs:What="Correction" crs:LocalClarity2012="-0.3" crs:LocalGrain="0.4" crs:LocalCurveRefineSaturation="100">
|
||||
<crs:CorrectionMasks><rdf:Seq>
|
||||
<rdf:li crs:What="Mask/RangeMask"><crs:CorrectionRangeMask crs:Type="2" crs:LumRange="0.6 0.85 1 1"/></rdf:li>
|
||||
</rdf:Seq></crs:CorrectionMasks>
|
||||
</rdf:Description></rdf:li>
|
||||
</rdf:Seq></crs:MaskGroupBasedCorrections>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
let d = lightcraft_meta::parse_xmp(x).unwrap();
|
||||
let (partial, unmapped) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
let s = DevelopSettings::default().merged(&partial).expect("valid settings");
|
||||
let MaskShape::LuminanceRange { hi, hi_feather, .. } = &s.masks[0].components[0].shape else { panic!() };
|
||||
assert_eq!((*hi, *hi_feather), (1.0, 0.0), "brighter than scene white is still in the range");
|
||||
assert_eq!(s.masks[0].adjust.clarity, -30.0);
|
||||
assert_eq!(unmapped, ["Mask: LocalGrain"], "a refine saturation of 100 is neutral, not reported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lrtemplate_corrections() {
|
||||
let t = r#"s = { title = "Grad", value = { settings = { Exposure2012 = 0.1, GradientBasedCorrections = {
|
||||
{ What = "Correction", CorrectionAmount = 1, LocalExposure2012 = -0.5, CorrectionMasks = {
|
||||
{ What = "Mask/Gradient", ZeroX = 0.5, ZeroY = 0.5, FullX = 0.5, FullY = 0, MaskValue = 1 } } } } } } }"#;
|
||||
let v = crate::preset_import::read_presets("Grad.lrtemplate", t.as_bytes(), None).unwrap();
|
||||
assert!(v[0].unmapped.is_empty(), "{:?}", v[0].unmapped);
|
||||
let s = DevelopSettings::default().merged(&v[0].preset.settings).unwrap();
|
||||
assert_eq!(s.masks.len(), 1);
|
||||
assert_eq!(s.masks[0].adjust.exposure, -2.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_add_masks_once() {
|
||||
let (s, _) = settings();
|
||||
let partial = json!({"masks": serde_json::to_value(&s.masks).unwrap(), "light": {"exposure": 0.5}});
|
||||
let p = lightcraft_develop::Preset { id: "t".into(), name: "t".into(), group: "g".into(), settings: partial, favorite: false, builtin: false };
|
||||
let mut mine = DevelopSettings::default();
|
||||
mine.masks.push(lightcraft_develop::Mask { id: 7, name: "Mine".into(), ..Default::default() });
|
||||
let once = p.apply(&mine, 1.0);
|
||||
assert_eq!(once.masks.len(), 4, "added to the photo's own mask");
|
||||
assert_eq!(once.masks[1].id, 8, "fresh ids");
|
||||
assert_eq!(p.apply(&once, 1.0).masks.len(), 4, "applying again adds nothing");
|
||||
let half = p.apply(&mine, 0.5);
|
||||
assert_eq!(half.masks[1].adjust.amount, 50.0, "amount scales the masks");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidecar_radials_fit_the_photo() {
|
||||
let mut v = json!({"masks": [{"components": [{"shape": {"kind": "radial", "rx": 0.3, "ry": 0.2}}]}]});
|
||||
refit_radials(&mut v, 1.5, 1.0);
|
||||
let s = &v["masks"][0]["components"][0]["shape"];
|
||||
assert!((s["rx"].as_f64().unwrap() - 0.3).abs() < 1e-9);
|
||||
assert!((s["ry"].as_f64().unwrap() - 0.3).abs() < 1e-9, "square photo: y radius = its box half-height");
|
||||
}
|
||||
|
||||
/// One radial correction in `container`, with `attrs` on its mask component (values written
|
||||
/// for this test; the component attributes follow what Lightroom Classic writes).
|
||||
fn radial_packet(container: &str, attrs: &str) -> String {
|
||||
format!(
|
||||
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Exposure2012="0">
|
||||
<crs:{container}><rdf:Seq>
|
||||
<rdf:li><rdf:Description crs:What="Correction" crs:CorrectionAmount="1" crs:LocalExposure2012="0.25">
|
||||
<crs:CorrectionMasks><rdf:Seq>
|
||||
<rdf:li crs:What="Mask/CircularGradient" crs:MaskValue="1" crs:Top="0.25" crs:Left="0.25" crs:Bottom="0.75" crs:Right="0.75" crs:Angle="0" crs:Midpoint="50" crs:Roundness="0" {attrs}/>
|
||||
</rdf:Seq></crs:CorrectionMasks>
|
||||
</rdf:Description></rdf:li>
|
||||
</rdf:Seq></crs:{container}>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#
|
||||
)
|
||||
}
|
||||
|
||||
fn radial_settings(container: &str, attrs: &str) -> DevelopSettings {
|
||||
let d = lightcraft_meta::parse_xmp(&radial_packet(container, attrs)).unwrap();
|
||||
let (partial, unmapped) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
assert!(unmapped.is_empty(), "{unmapped:?}");
|
||||
let s = DevelopSettings::default().merged(&partial).unwrap();
|
||||
assert_eq!(s.masks.len(), 1, "{:?}", s.masks);
|
||||
s
|
||||
}
|
||||
|
||||
/// (the radial's `invert`, its feather, the component's `invert`).
|
||||
fn radial_of(s: &DevelopSettings) -> (bool, f64, bool) {
|
||||
let c = &s.masks[0].components[0];
|
||||
let MaskShape::Radial { invert, feather, .. } = &c.shape else { panic!("{:?}", c.shape) };
|
||||
(*invert, *feather, c.invert)
|
||||
}
|
||||
|
||||
/// How much brighter the mask makes the centre and a corner of a flat grey frame (8-bit green).
|
||||
fn lift_inside_outside(s: &DevelopSettings) -> (i32, i32) {
|
||||
let img = lightcraft_raster::Image { width: 90, height: 60, data: vec![[0.18f32; 3]; 90 * 60] };
|
||||
let render =
|
||||
|d: &DevelopSettings| lightcraft_pipeline::render(&img, &Default::default(), d, &lightcraft_pipeline::RenderRequest::fit(90, 60)).image;
|
||||
let (with, without) = (render(s), render(&DevelopSettings { light: s.light, ..Default::default() }));
|
||||
let g = |im: &lightcraft_raster::Rgba8, x: usize, y: usize| i32::from(im.data[y * im.width + x][1]);
|
||||
(g(&with, 45, 30) - g(&without, 45, 30), g(&with, 3, 3) - g(&without, 3, 3))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lightroom_radial_flipped_is_inside() {
|
||||
// as Lightroom Classic writes an ordinary radial mask today (#1815)
|
||||
let s = radial_settings("MaskGroupBasedCorrections", r#"crs:MaskInverted="false" crs:Feather="25" crs:Flipped="true" crs:Version="2""#);
|
||||
assert_eq!(radial_of(&s), (false, 25.0, false));
|
||||
let (inside, outside) = lift_inside_outside(&s);
|
||||
assert!(inside > 20 && outside == 0, "the effect is inside the circle: {inside} {outside}");
|
||||
// no MaskInverted at all reads the same
|
||||
let s = radial_settings("MaskGroupBasedCorrections", r#"crs:Feather="25" crs:Flipped="true" crs:Version="2""#);
|
||||
assert_eq!(radial_of(&s), (false, 25.0, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lightroom_radial_mask_inverted_is_outside() {
|
||||
let s = radial_settings("MaskGroupBasedCorrections", r#"crs:MaskInverted="true" crs:Feather="25" crs:Flipped="true" crs:Version="2""#);
|
||||
assert_eq!(radial_of(&s), (false, 25.0, true), "the inversion is the component's");
|
||||
let (inside, outside) = lift_inside_outside(&s);
|
||||
assert!(inside == 0 && outside > 20, "the effect is outside the circle: {inside} {outside}");
|
||||
// version 2 with Flipped="false": outside, the legacy sense of the flag
|
||||
let s = radial_settings("MaskGroupBasedCorrections", r#"crs:MaskInverted="false" crs:Feather="25" crs:Flipped="false" crs:Version="2""#);
|
||||
assert_eq!(radial_of(&s), (true, 25.0, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versionless_group_radial_is_inside_with_half_the_feather() {
|
||||
// Lightroom renders both inside and rewrites them Flipped="true", Feather halved, Version="2"
|
||||
for flipped in ["true", "false"] {
|
||||
let s = radial_settings("MaskGroupBasedCorrections", &format!(r#"crs:MaskInverted="false" crs:Feather="50" crs:Flipped="{flipped}""#));
|
||||
assert_eq!(radial_of(&s), (false, 25.0, false), "Flipped={flipped}");
|
||||
let (inside, outside) = lift_inside_outside(&s);
|
||||
assert!(inside > 20 && outside == 0, "Flipped={flipped}: {inside} {outside}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_radial_filter_is_outside_unless_flipped() {
|
||||
// the process-2012 Radial Filter: effect outside by default, "Invert Mask" = Flipped="true"
|
||||
let s = radial_settings("CircularGradientBasedCorrections", r#"crs:Feather="50" crs:Flipped="false""#);
|
||||
assert_eq!(radial_of(&s), (true, 50.0, false));
|
||||
let (inside, outside) = lift_inside_outside(&s);
|
||||
assert!(inside == 0 && outside > 20, "default: outside: {inside} {outside}");
|
||||
assert_eq!(radial_of(&radial_settings("CircularGradientBasedCorrections", r#"crs:Feather="50""#)), (true, 50.0, false));
|
||||
let s = radial_settings("CircularGradientBasedCorrections", r#"crs:Feather="50" crs:Flipped="true""#);
|
||||
assert_eq!(radial_of(&s), (false, 50.0, false));
|
||||
let (inside, outside) = lift_inside_outside(&s);
|
||||
assert!(inside > 20 && outside == 0, "inverted: inside: {inside} {outside}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lrtemplate_radial_filter_reads_flipped() {
|
||||
// .lrtemplate presets and catalog develop settings are the same Lua tables
|
||||
let t = |flipped: &str| {
|
||||
format!(
|
||||
r#"s = {{ title = "Rad", value = {{ settings = {{ CircularGradientBasedCorrections = {{
|
||||
{{ What = "Correction", CorrectionAmount = 1, LocalExposure2012 = 0.25, CorrectionMasks = {{
|
||||
{{ What = "Mask/CircularGradient", Top = 0.25, Left = 0.25, Bottom = 0.75, Right = 0.75, Angle = 0, Feather = 50, Flipped = {flipped}, MaskValue = 1 }} }} }} }} }} }} }}"#
|
||||
)
|
||||
};
|
||||
for (flipped, outside) in [("true", false), ("false", true)] {
|
||||
let v = crate::preset_import::read_presets("Rad.lrtemplate", t(flipped).as_bytes(), None).unwrap();
|
||||
let s = DevelopSettings::default().merged(&v[0].preset.settings).unwrap();
|
||||
assert_eq!(radial_of(&s).0, outside, "Flipped = {flipped}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Spot removal in the shape Lightroom Classic writes it (values written for this test):
|
||||
/// a healed circle with an explicit source, a cloned circle with an automatic source, a
|
||||
/// brushed removal, a circular-gradient spot, one without a mask, and the legacy list.
|
||||
const SPOTS: &str = r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:Exposure2012="0.1">
|
||||
<crs:RetouchInfo><rdf:Seq>
|
||||
<rdf:li>centerX = 0.4, centerY = 0.3, radius = 0.01, sourceState = sourceSetExplicitly, sourceX = 0.45, sourceY = 0.3, spotType = heal</rdf:li>
|
||||
</rdf:Seq></crs:RetouchInfo>
|
||||
<crs:RetouchAreas><rdf:Seq>
|
||||
<rdf:li><rdf:Description crs:SpotType="heal" crs:SourceState="sourceSetExplicitly" crs:Method="poisson" crs:SourceX="0.45" crs:OffsetY="0.3" crs:Opacity="1" crs:Feather="0" crs:Seed="1">
|
||||
<crs:Masks><rdf:Seq><rdf:li crs:What="Mask/Ellipse" crs:MaskActive="true" crs:MaskValue="1" crs:X="0.4" crs:Y="0.3" crs:SizeX="0.01" crs:SizeY="0.015"/></rdf:Seq></crs:Masks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:SpotType="clone" crs:SourceState="sourceAutoComputed" crs:Opacity="0.5" crs:Feather="0.25">
|
||||
<crs:Masks><rdf:Seq><rdf:li crs:What="Mask/Ellipse" crs:X="0.7" crs:Y="0.6" crs:SizeX="0.02" crs:SizeY="0.02"/></rdf:Seq></crs:Masks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:SpotType="heal" crs:SourceState="sourceSetExplicitly" crs:SourceX="0.2" crs:OffsetY="0.9">
|
||||
<crs:Masks><rdf:Seq><rdf:li crs:What="Mask/Paint" crs:Radius="0.03" crs:MaskValue="1">
|
||||
<crs:Dabs><rdf:Seq><rdf:li>d 0.1 0.8</rdf:li><rdf:li>d 0.12 0.82</rdf:li><rdf:li>d 0.14 0.84</rdf:li></rdf:Seq></crs:Dabs></rdf:li></rdf:Seq></crs:Masks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:SpotType="heal" crs:SourceX="0.6" crs:OffsetY="0.5">
|
||||
<crs:Masks><rdf:Seq><rdf:li crs:What="Mask/CircularGradient" crs:Top="0.48" crs:Left="0.49" crs:Bottom="0.52" crs:Right="0.51"/></rdf:Seq></crs:Masks>
|
||||
</rdf:Description></rdf:li>
|
||||
<rdf:li><rdf:Description crs:SpotType="heal">
|
||||
<crs:Masks><rdf:Seq><rdf:li crs:What="Mask/Gradient" crs:FullX="0" crs:FullY="0" crs:ZeroX="1" crs:ZeroY="1"/></rdf:Seq></crs:Masks>
|
||||
</rdf:Description></rdf:li>
|
||||
</rdf:Seq></crs:RetouchAreas>
|
||||
</rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
|
||||
#[test]
|
||||
fn retouch_areas_become_spots() {
|
||||
use lightcraft_develop::SpotMode;
|
||||
let d = lightcraft_meta::parse_xmp(SPOTS).unwrap();
|
||||
let (partial, unmapped) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
let s = DevelopSettings::default().merged(&partial).expect("valid settings");
|
||||
assert_eq!(s.light.exposure, 0.1, "global settings still map");
|
||||
assert_eq!(s.spots.len(), 4, "the gradient 'spot' is skipped: {:?}", s.spots);
|
||||
let heal = &s.spots[0];
|
||||
assert_eq!((heal.mode, heal.points.len(), heal.opacity, heal.feather), (SpotMode::Heal, 1, 100.0, 0.0));
|
||||
assert!((heal.points[0].x - 0.4).abs() < 1e-9 && (heal.points[0].y - 0.3).abs() < 1e-9);
|
||||
assert!((heal.size - 0.01).abs() < 1e-9, "a landscape target: width fractions are long-edge fractions");
|
||||
let src = heal.source_offset.expect("explicit source");
|
||||
assert!((src.x - 0.05).abs() < 1e-9 && src.y.abs() < 1e-9, "source stored absolute, ours an offset: {src:?}");
|
||||
let clone = &s.spots[1];
|
||||
assert_eq!((clone.mode, clone.opacity, clone.feather, clone.source_offset), (SpotMode::Clone, 50.0, 25.0, None));
|
||||
let brushed = &s.spots[2];
|
||||
assert_eq!((brushed.points.len(), brushed.size), (3, 0.03));
|
||||
let src = brushed.source_offset.expect("explicit source");
|
||||
assert!((src.x - 0.1).abs() < 1e-9 && (src.y - 0.1).abs() < 1e-9);
|
||||
let circ = &s.spots[3];
|
||||
assert!((circ.points[0].x - 0.5).abs() < 1e-9 && (circ.points[0].y - 0.5).abs() < 1e-9 && (circ.size - 0.01).abs() < 1e-9);
|
||||
assert_eq!(unmapped, vec!["Spot: Gradient".to_string()], "{unmapped:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portrait_target_scales_spot_sizes() {
|
||||
let d = lightcraft_meta::parse_xmp(SPOTS).unwrap();
|
||||
let (partial, _) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 2.0 / 3.0);
|
||||
let s = DevelopSettings::default().merged(&partial).unwrap();
|
||||
assert!((s.spots[0].size - 0.01 * 2.0 / 3.0).abs() < 1e-9, "a width fraction on a portrait target: {}", s.spots[0].size);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_retouch_info_is_read_on_its_own() {
|
||||
let packet = SPOTS.replace("crs:RetouchAreas", "crs:Ignored");
|
||||
let d = lightcraft_meta::parse_xmp(&packet).unwrap();
|
||||
let (partial, unmapped) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
let s = DevelopSettings::default().merged(&partial).unwrap();
|
||||
assert_eq!(s.spots.len(), 1, "{:?}", s.spots);
|
||||
assert_eq!(s.spots[0].mode, lightcraft_develop::SpotMode::Heal);
|
||||
assert!((s.spots[0].points[0].x - 0.4).abs() < 1e-9 && (s.spots[0].size - 0.01).abs() < 1e-9);
|
||||
assert!(s.spots[0].source_offset.is_some_and(|o| (o.x - 0.05).abs() < 1e-9));
|
||||
assert!(unmapped.iter().any(|u| u == "Ignored"), "{unmapped:?}");
|
||||
assert!(!unmapped.iter().any(|u| u == "RetouchInfo"), "{unmapped:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spots_render() {
|
||||
let d = lightcraft_meta::parse_xmp(SPOTS).unwrap();
|
||||
let (partial, _) = crate::crs::to_partial_report(&d.properties, Some(&d.values), crate::crs::Target::Any, 1.5);
|
||||
let s = DevelopSettings::default().merged(&partial).unwrap();
|
||||
let img = lightcraft_scenes::demo_library()[0].render(96, 64);
|
||||
let render =
|
||||
|d: &DevelopSettings| lightcraft_pipeline::render(&img, &Default::default(), d, &lightcraft_pipeline::RenderRequest::fit(96, 64)).image.data;
|
||||
assert_ne!(render(&DevelopSettings { light: s.light, ..Default::default() }), render(&s), "the spots change the picture");
|
||||
}
|
||||
+1
-363
@@ -329,366 +329,4 @@ fn trim_scene_cache(c: &mut SceneCache, limit: usize) {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn small_scene() -> lightcraft_scenes::Scene {
|
||||
lightcraft_scenes::demo_library().swap_remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scene_is_generated_once_per_size_and_shared() {
|
||||
let s = small_scene();
|
||||
let a = scene_pixels(&s, 48).unwrap();
|
||||
let b = scene_pixels(&s, 48).unwrap();
|
||||
assert!(Arc::ptr_eq(&a, &b), "the second request reuses the first generation");
|
||||
assert_eq!(a.width.max(a.height), 48);
|
||||
assert_eq!(a.data, s.render_fit(48).data, "the same pixels as generating it directly");
|
||||
let c = scene_pixels(&s, 40).unwrap();
|
||||
assert_eq!(c.width.max(c.height), 40, "another size is its own generation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_requests_wait_for_one_generation() {
|
||||
let s = small_scene();
|
||||
let edge = 37; // a size no other test asks for
|
||||
let got: Vec<_> = std::thread::scope(|sc| {
|
||||
let hs: Vec<_> = (0..4).map(|_| sc.spawn(|| scene_pixels(&s, edge).unwrap())).collect();
|
||||
hs.into_iter().map(|h| h.join().unwrap()).collect()
|
||||
});
|
||||
assert!(got.windows(2).all(|w| Arc::ptr_eq(&w[0], &w[1])), "every request got the same pixels");
|
||||
}
|
||||
|
||||
/// Run `f` on a thread of its own and wait for it at most `secs`: a deadlock fails the test instead of hanging it.
|
||||
fn within<T: Send + 'static>(secs: u64, f: impl FnOnce() -> T + Send + 'static) -> T {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(f());
|
||||
});
|
||||
rx.recv_timeout(std::time::Duration::from_secs(secs)).expect("deadlocked")
|
||||
}
|
||||
|
||||
/// Wait (at most ten seconds) until `n` callers wait for `slot`'s generation.
|
||||
fn until_waiting(slot: &SceneSlot, n: usize) {
|
||||
let started = std::time::Instant::now();
|
||||
while slot.lock().waiting < n {
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "the callers never got to wait");
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
fn pixels(n: usize) -> lightcraft_raster::Rgb32f {
|
||||
lightcraft_raster::Rgb32f::new(n, 1)
|
||||
}
|
||||
|
||||
/// Rayon workers asking for a scene while it is generated never deadlock. The render is parallel, and a rayon worker
|
||||
/// waiting for rows another worker took runs queued jobs on top of itself: generating on the caller's thread, the
|
||||
/// faces scan's pool threads ended up waiting on the generation further down their own stack and hung. Requests
|
||||
/// keep arriving on a four-thread pool while the scene is generated, as when several photos are queued; every one
|
||||
/// of them must come back, at least four of them must have overlapped the generation, and the test waits with a
|
||||
/// timeout, so a deadlock fails it instead of hanging.
|
||||
#[test]
|
||||
fn rayon_workers_asking_for_a_scene_being_generated_never_deadlock() {
|
||||
let scene = Arc::new(small_scene());
|
||||
let edge = 601; // a size no other test asks for
|
||||
const ASKED: usize = 24;
|
||||
let (overlap, sizes) = within(120, move || {
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap();
|
||||
let issued = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let (done_tx, done_rx) = std::sync::mpsc::channel();
|
||||
for _ in 0..ASKED {
|
||||
let (scene, done, issued) = (scene.clone(), done_tx.clone(), issued.clone());
|
||||
issued.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
pool.spawn(move || {
|
||||
let got = scene_pixels(&scene, edge).unwrap();
|
||||
// how many requests had been made when this one came back
|
||||
let _ = done.send((issued.load(std::sync::atomic::Ordering::SeqCst), got.data.len()));
|
||||
});
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
let replies: Vec<(usize, usize)> = (0..ASKED).map(|_| done_rx.recv().unwrap()).collect();
|
||||
(replies.iter().map(|r| r.0).min().unwrap(), replies.iter().map(|r| r.1).collect::<Vec<_>>())
|
||||
});
|
||||
assert_eq!(sizes.len(), ASKED, "every request came back");
|
||||
assert!(sizes.iter().all(|n| *n == sizes[0] && *n > 0));
|
||||
assert!(overlap >= 4, "requests overlapped the generation (only {overlap} had been made when the first came back)");
|
||||
}
|
||||
|
||||
/// However many requests (from rayon workers and other threads) arrive while a scene is generated, it is rendered
|
||||
/// once, and never twice at the same time: duplicates would each hold a whole image (288 MB for a 24 MP original).
|
||||
#[test]
|
||||
fn a_scene_is_rendered_once_however_many_ask() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let (renders, peak) = within(120, || {
|
||||
let slot = Arc::new(SceneSlot::default());
|
||||
let (running, peak, renders) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
|
||||
let render = {
|
||||
let (running, peak, renders) = (running.clone(), peak.clone(), renders.clone());
|
||||
move |how: Render| {
|
||||
let now = running.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
peak.fetch_max(now, Ordering::SeqCst);
|
||||
renders.fetch_add(1, Ordering::SeqCst);
|
||||
// work like the real render's: in parallel, the rendering thread waits for rows other threads took
|
||||
use rayon::prelude::*;
|
||||
let sum: u64 = match how {
|
||||
Render::Parallel => (0..2_000_000u64).into_par_iter().map(|i| i % 7).sum(),
|
||||
Render::Serial => (0..2_000_000u64).map(|i| i % 7).sum(),
|
||||
};
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
running.fetch_sub(1, Ordering::SeqCst);
|
||||
pixels(sum as usize % 5 + 1)
|
||||
}
|
||||
};
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
for _ in 0..16 {
|
||||
let (slot, render, tx) = (slot.clone(), render.clone(), tx.clone());
|
||||
pool.spawn(move || {
|
||||
let _ = tx.send(slot.get_or_generate(render).unwrap());
|
||||
});
|
||||
}
|
||||
for _ in 0..4 {
|
||||
let (slot, render, tx) = (slot.clone(), render.clone(), tx.clone());
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(slot.get_or_generate(render).unwrap());
|
||||
});
|
||||
}
|
||||
let got: Vec<_> = (0..20).map(|_| rx.recv().unwrap()).collect();
|
||||
assert!(got.windows(2).all(|w| Arc::ptr_eq(&w[0], &w[1])), "every request got the same pixels");
|
||||
(renders.load(Ordering::SeqCst), peak.load(Ordering::SeqCst))
|
||||
});
|
||||
assert_eq!((renders, peak), (1, 1));
|
||||
}
|
||||
|
||||
/// A rayon worker (the faces scan's) renders a scene on its own thread alone, so the work stays within its pool
|
||||
/// and that pool's limits; other threads render in parallel on the scene pool.
|
||||
#[test]
|
||||
fn a_rayon_worker_renders_alone_on_its_own_thread() {
|
||||
let ((how, caller, renderer), (other_how, other_name)) = within(120, || {
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap();
|
||||
let slot = SceneSlot::default();
|
||||
let mut seen = None;
|
||||
pool.install(|| {
|
||||
let caller = std::thread::current().id();
|
||||
slot.get_or_generate(|how| {
|
||||
seen = Some((how, caller, std::thread::current().id()));
|
||||
pixels(1)
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
let other = SceneSlot::default();
|
||||
let mut other_seen = None;
|
||||
other
|
||||
.get_or_generate(|how| {
|
||||
other_seen = Some((how, std::thread::current().name().unwrap_or_default().to_string()));
|
||||
pixels(1)
|
||||
})
|
||||
.unwrap();
|
||||
(seen.unwrap(), other_seen.unwrap())
|
||||
});
|
||||
assert_eq!((how, renderer), (Render::Serial, caller));
|
||||
assert_eq!(other_how, Render::Parallel);
|
||||
assert!(other_name.starts_with("lc-demo-scene-"), "{other_name}");
|
||||
}
|
||||
|
||||
/// A caller finding a generation running waits for it instead of rendering its own (one 24 MP original costs
|
||||
/// minutes of CPU time on a small machine).
|
||||
#[test]
|
||||
fn callers_wait_for_the_generation_running() {
|
||||
let (a, b, renders) = within(120, || {
|
||||
let slot = Arc::new(SceneSlot::default());
|
||||
let renders = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let (started_tx, started) = std::sync::mpsc::channel::<()>();
|
||||
let (go, go_rx) = std::sync::mpsc::channel::<()>();
|
||||
let (started_tx, go_rx) = (Arc::new(std::sync::Mutex::new(started_tx)), Arc::new(std::sync::Mutex::new(go_rx)));
|
||||
let ask = |slot: &Arc<SceneSlot>| {
|
||||
let (slot, renders, started_tx, go_rx) = (slot.clone(), renders.clone(), started_tx.clone(), go_rx.clone());
|
||||
std::thread::spawn(move || {
|
||||
slot.get_or_generate(move |_| {
|
||||
renders.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let _ = started_tx.lock().unwrap().send(());
|
||||
let _ = go_rx.lock().unwrap().recv();
|
||||
pixels(1)
|
||||
})
|
||||
})
|
||||
};
|
||||
let first = ask(&slot);
|
||||
started.recv().unwrap();
|
||||
let second = ask(&slot);
|
||||
until_waiting(&slot, 1);
|
||||
go.send(()).unwrap();
|
||||
let (a, b) = (first.join().unwrap().unwrap(), second.join().unwrap().unwrap());
|
||||
(a, b, renders.load(std::sync::atomic::Ordering::SeqCst))
|
||||
});
|
||||
assert!(Arc::ptr_eq(&a, &b) && a.width == 1, "one generation, shared");
|
||||
assert_eq!(renders, 1);
|
||||
}
|
||||
|
||||
/// A generation that fails (its render panicked) is an error for its callers, never a hang, and the next request
|
||||
/// generates the scene again.
|
||||
#[test]
|
||||
fn a_failed_generation_is_an_error_and_the_next_request_tries_again() {
|
||||
let (first, waiters, again) = within(120, || {
|
||||
let slot = Arc::new(SceneSlot::default());
|
||||
let (started_tx, started) = std::sync::mpsc::channel::<()>();
|
||||
let (go, go_rx) = std::sync::mpsc::channel::<()>();
|
||||
let failing = {
|
||||
let slot = slot.clone();
|
||||
std::thread::spawn(move || {
|
||||
slot.get_or_generate(move |_| {
|
||||
let _ = started_tx.send(());
|
||||
let _ = go_rx.recv();
|
||||
panic!("render failed");
|
||||
})
|
||||
})
|
||||
};
|
||||
started.recv().unwrap();
|
||||
let waiters: Vec<_> = (0..2)
|
||||
.map(|_| {
|
||||
let slot = slot.clone();
|
||||
std::thread::spawn(move || slot.get_or_generate(|_| pixels(2)))
|
||||
})
|
||||
.collect();
|
||||
until_waiting(&slot, 2);
|
||||
drop(go);
|
||||
let first = failing.join().unwrap();
|
||||
let waiters: Vec<_> = waiters.into_iter().map(|w| w.join().unwrap()).collect();
|
||||
(first, waiters, slot.get_or_generate(|_| pixels(3)))
|
||||
});
|
||||
assert!(first.is_err() && waiters.iter().all(Result::is_err), "the callers of the failed generation get its error");
|
||||
assert_eq!(again.unwrap().width, 3);
|
||||
}
|
||||
|
||||
/// Callers get the outcome of the generation they waited for, even when a retry starts (or finishes) before they
|
||||
/// look: a failed generation followed by a retry is still an error for them.
|
||||
#[test]
|
||||
fn a_retry_never_changes_the_outcome_waited_for() {
|
||||
let mut st = SlotState::default();
|
||||
let n = st.start();
|
||||
assert!(st.outcome(n).is_none(), "running");
|
||||
st.generation = Generation::Failed;
|
||||
let m = st.start();
|
||||
assert!(matches!(st.outcome(n), Some(Err(_))));
|
||||
assert!(st.outcome(m).is_none());
|
||||
st.generation = Generation::Ready(Arc::new(pixels(1)));
|
||||
assert!(matches!(st.outcome(n), Some(Err(_))), "even once the retry succeeded");
|
||||
assert!(matches!(st.outcome(m), Some(Ok(_))));
|
||||
// and with threads: a retry racing the waiters of a failed generation never hands them its result
|
||||
let wrong = within(120, || {
|
||||
let mut wrong = 0;
|
||||
for _ in 0..20 {
|
||||
let slot = Arc::new(SceneSlot::default());
|
||||
let (started_tx, started) = std::sync::mpsc::channel::<()>();
|
||||
let (go, go_rx) = std::sync::mpsc::channel::<()>();
|
||||
let failing = {
|
||||
let slot = slot.clone();
|
||||
std::thread::spawn(move || {
|
||||
slot.get_or_generate(move |_| {
|
||||
let _ = started_tx.send(());
|
||||
let _ = go_rx.recv();
|
||||
panic!("render failed");
|
||||
})
|
||||
})
|
||||
};
|
||||
started.recv().unwrap();
|
||||
let waiters: Vec<_> = (0..3)
|
||||
.map(|_| {
|
||||
let slot = slot.clone();
|
||||
std::thread::spawn(move || slot.get_or_generate(|_| pixels(2)))
|
||||
})
|
||||
.collect();
|
||||
until_waiting(&slot, 3);
|
||||
let retry = {
|
||||
let slot = slot.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
if matches!(slot.lock().generation, Generation::Failed) {
|
||||
return slot.get_or_generate(|_| pixels(4));
|
||||
}
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
})
|
||||
};
|
||||
drop(go);
|
||||
let _ = failing.join().unwrap();
|
||||
wrong += waiters.into_iter().map(|w| w.join().unwrap()).filter(Result::is_ok).count();
|
||||
assert!(retry.join().unwrap().is_ok());
|
||||
}
|
||||
wrong
|
||||
});
|
||||
assert_eq!(wrong, 0, "waiters of a failed generation got a retry's pixels");
|
||||
}
|
||||
|
||||
/// Generating a scene never touches the global rayon pool, so a process whose global pool couldn't start (asking it
|
||||
/// anything then panics) still gets its demo scenes. Run in a process of its own: the global pool is the process's.
|
||||
#[test]
|
||||
fn scenes_are_generated_when_the_global_pool_is_broken() {
|
||||
use std::io::Read;
|
||||
use std::process::Stdio;
|
||||
let mut child = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "demo::tests::with_a_broken_global_pool", "--ignored", "--test-threads=1"])
|
||||
.env("LC_DEMO_BROKEN_GLOBAL_POOL", "1")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
// Drain both pipes on threads so a chatty child can't block on a full pipe.
|
||||
let drain = |mut r: Box<dyn Read + Send>| {
|
||||
std::thread::spawn(move || {
|
||||
let mut s = String::new();
|
||||
let _ = r.read_to_string(&mut s);
|
||||
s
|
||||
})
|
||||
};
|
||||
let (stdout, stderr) = (drain(Box::new(child.stdout.take().unwrap())), drain(Box::new(child.stderr.take().unwrap())));
|
||||
// A deadlocked child fails the test instead of hanging CI.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
break status;
|
||||
}
|
||||
if std::time::Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
panic!("the child process did not finish within 120 s");
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
};
|
||||
let (stdout, stderr) = (stdout.join().unwrap(), stderr.join().unwrap());
|
||||
assert!(status.success() && stdout.contains("1 passed"), "{stdout}\n{stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "run in a process of its own by scenes_are_generated_when_the_global_pool_is_broken"]
|
||||
fn with_a_broken_global_pool() {
|
||||
if std::env::var_os("LC_DEMO_BROKEN_GLOBAL_POOL").is_none() {
|
||||
return;
|
||||
}
|
||||
let broken = rayon::ThreadPoolBuilder::new().spawn_handler(|_| Err(std::io::Error::other("no threads"))).build_global();
|
||||
assert!(broken.is_err());
|
||||
assert!(std::panic::catch_unwind(rayon::current_num_threads).is_err(), "the global pool is broken");
|
||||
let s = small_scene();
|
||||
let got = scene_pixels(&s, 33).unwrap();
|
||||
assert_eq!(got.data, s.render_fit_serial(33).data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_keeps_the_most_recent_scenes_within_its_limit() {
|
||||
let key = |max_edge| SceneKey { kind: lightcraft_scenes::Kind::Dunes, seed: 1, width: 3, height: 2, max_edge };
|
||||
let entry = |max_edge, used, px: Option<usize>| {
|
||||
let slot = Arc::new(SceneSlot::default());
|
||||
if let Some(n) = px {
|
||||
slot.lock().generation = Generation::Ready(Arc::new(lightcraft_raster::Rgb32f::new(n, 1)));
|
||||
}
|
||||
SceneEntry { key: key(max_edge), slot, used }
|
||||
};
|
||||
let px = std::mem::size_of::<[f32; 3]>();
|
||||
let mut c = SceneCache { entries: vec![entry(1, 3, Some(10)), entry(2, 1, Some(10)), entry(3, 0, None), entry(4, 2, Some(10))], tick: 3 };
|
||||
trim_scene_cache(&mut c, 25 * px);
|
||||
let mut kept: Vec<usize> = c.entries.iter().map(|e| e.key.max_edge).collect();
|
||||
kept.sort_unstable();
|
||||
assert_eq!(kept, vec![1, 3, 4], "the least recently used finished scene went; the one in progress stays");
|
||||
trim_scene_cache(&mut c, 0);
|
||||
assert_eq!(c.entries.iter().map(|e| e.key.max_edge).collect::<Vec<_>>(), vec![3], "only the scene in progress is left");
|
||||
}
|
||||
}
|
||||
mod tests;
|
||||
@@ -0,0 +1,361 @@
|
||||
use super::*;
|
||||
|
||||
fn small_scene() -> lightcraft_scenes::Scene {
|
||||
lightcraft_scenes::demo_library().swap_remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scene_is_generated_once_per_size_and_shared() {
|
||||
let s = small_scene();
|
||||
let a = scene_pixels(&s, 48).unwrap();
|
||||
let b = scene_pixels(&s, 48).unwrap();
|
||||
assert!(Arc::ptr_eq(&a, &b), "the second request reuses the first generation");
|
||||
assert_eq!(a.width.max(a.height), 48);
|
||||
assert_eq!(a.data, s.render_fit(48).data, "the same pixels as generating it directly");
|
||||
let c = scene_pixels(&s, 40).unwrap();
|
||||
assert_eq!(c.width.max(c.height), 40, "another size is its own generation");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_requests_wait_for_one_generation() {
|
||||
let s = small_scene();
|
||||
let edge = 37; // a size no other test asks for
|
||||
let got: Vec<_> = std::thread::scope(|sc| {
|
||||
let hs: Vec<_> = (0..4).map(|_| sc.spawn(|| scene_pixels(&s, edge).unwrap())).collect();
|
||||
hs.into_iter().map(|h| h.join().unwrap()).collect()
|
||||
});
|
||||
assert!(got.windows(2).all(|w| Arc::ptr_eq(&w[0], &w[1])), "every request got the same pixels");
|
||||
}
|
||||
|
||||
/// Run `f` on a thread of its own and wait for it at most `secs`: a deadlock fails the test instead of hanging it.
|
||||
fn within<T: Send + 'static>(secs: u64, f: impl FnOnce() -> T + Send + 'static) -> T {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(f());
|
||||
});
|
||||
rx.recv_timeout(std::time::Duration::from_secs(secs)).expect("deadlocked")
|
||||
}
|
||||
|
||||
/// Wait (at most ten seconds) until `n` callers wait for `slot`'s generation.
|
||||
fn until_waiting(slot: &SceneSlot, n: usize) {
|
||||
let started = std::time::Instant::now();
|
||||
while slot.lock().waiting < n {
|
||||
assert!(started.elapsed() < std::time::Duration::from_secs(10), "the callers never got to wait");
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
fn pixels(n: usize) -> lightcraft_raster::Rgb32f {
|
||||
lightcraft_raster::Rgb32f::new(n, 1)
|
||||
}
|
||||
|
||||
/// Rayon workers asking for a scene while it is generated never deadlock. The render is parallel, and a rayon worker
|
||||
/// waiting for rows another worker took runs queued jobs on top of itself: generating on the caller's thread, the
|
||||
/// faces scan's pool threads ended up waiting on the generation further down their own stack and hung. Requests
|
||||
/// keep arriving on a four-thread pool while the scene is generated, as when several photos are queued; every one
|
||||
/// of them must come back, at least four of them must have overlapped the generation, and the test waits with a
|
||||
/// timeout, so a deadlock fails it instead of hanging.
|
||||
#[test]
|
||||
fn rayon_workers_asking_for_a_scene_being_generated_never_deadlock() {
|
||||
let scene = Arc::new(small_scene());
|
||||
let edge = 601; // a size no other test asks for
|
||||
const ASKED: usize = 24;
|
||||
let (overlap, sizes) = within(120, move || {
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap();
|
||||
let issued = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let (done_tx, done_rx) = std::sync::mpsc::channel();
|
||||
for _ in 0..ASKED {
|
||||
let (scene, done, issued) = (scene.clone(), done_tx.clone(), issued.clone());
|
||||
issued.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
pool.spawn(move || {
|
||||
let got = scene_pixels(&scene, edge).unwrap();
|
||||
// how many requests had been made when this one came back
|
||||
let _ = done.send((issued.load(std::sync::atomic::Ordering::SeqCst), got.data.len()));
|
||||
});
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
let replies: Vec<(usize, usize)> = (0..ASKED).map(|_| done_rx.recv().unwrap()).collect();
|
||||
(replies.iter().map(|r| r.0).min().unwrap(), replies.iter().map(|r| r.1).collect::<Vec<_>>())
|
||||
});
|
||||
assert_eq!(sizes.len(), ASKED, "every request came back");
|
||||
assert!(sizes.iter().all(|n| *n == sizes[0] && *n > 0));
|
||||
assert!(overlap >= 4, "requests overlapped the generation (only {overlap} had been made when the first came back)");
|
||||
}
|
||||
|
||||
/// However many requests (from rayon workers and other threads) arrive while a scene is generated, it is rendered
|
||||
/// once, and never twice at the same time: duplicates would each hold a whole image (288 MB for a 24 MP original).
|
||||
#[test]
|
||||
fn a_scene_is_rendered_once_however_many_ask() {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
let (renders, peak) = within(120, || {
|
||||
let slot = Arc::new(SceneSlot::default());
|
||||
let (running, peak, renders) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
|
||||
let render = {
|
||||
let (running, peak, renders) = (running.clone(), peak.clone(), renders.clone());
|
||||
move |how: Render| {
|
||||
let now = running.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
peak.fetch_max(now, Ordering::SeqCst);
|
||||
renders.fetch_add(1, Ordering::SeqCst);
|
||||
// work like the real render's: in parallel, the rendering thread waits for rows other threads took
|
||||
use rayon::prelude::*;
|
||||
let sum: u64 = match how {
|
||||
Render::Parallel => (0..2_000_000u64).into_par_iter().map(|i| i % 7).sum(),
|
||||
Render::Serial => (0..2_000_000u64).map(|i| i % 7).sum(),
|
||||
};
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
running.fetch_sub(1, Ordering::SeqCst);
|
||||
pixels(sum as usize % 5 + 1)
|
||||
}
|
||||
};
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(4).build().unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
for _ in 0..16 {
|
||||
let (slot, render, tx) = (slot.clone(), render.clone(), tx.clone());
|
||||
pool.spawn(move || {
|
||||
let _ = tx.send(slot.get_or_generate(render).unwrap());
|
||||
});
|
||||
}
|
||||
for _ in 0..4 {
|
||||
let (slot, render, tx) = (slot.clone(), render.clone(), tx.clone());
|
||||
std::thread::spawn(move || {
|
||||
let _ = tx.send(slot.get_or_generate(render).unwrap());
|
||||
});
|
||||
}
|
||||
let got: Vec<_> = (0..20).map(|_| rx.recv().unwrap()).collect();
|
||||
assert!(got.windows(2).all(|w| Arc::ptr_eq(&w[0], &w[1])), "every request got the same pixels");
|
||||
(renders.load(Ordering::SeqCst), peak.load(Ordering::SeqCst))
|
||||
});
|
||||
assert_eq!((renders, peak), (1, 1));
|
||||
}
|
||||
|
||||
/// A rayon worker (the faces scan's) renders a scene on its own thread alone, so the work stays within its pool
|
||||
/// and that pool's limits; other threads render in parallel on the scene pool.
|
||||
#[test]
|
||||
fn a_rayon_worker_renders_alone_on_its_own_thread() {
|
||||
let ((how, caller, renderer), (other_how, other_name)) = within(120, || {
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap();
|
||||
let slot = SceneSlot::default();
|
||||
let mut seen = None;
|
||||
pool.install(|| {
|
||||
let caller = std::thread::current().id();
|
||||
slot.get_or_generate(|how| {
|
||||
seen = Some((how, caller, std::thread::current().id()));
|
||||
pixels(1)
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
let other = SceneSlot::default();
|
||||
let mut other_seen = None;
|
||||
other
|
||||
.get_or_generate(|how| {
|
||||
other_seen = Some((how, std::thread::current().name().unwrap_or_default().to_string()));
|
||||
pixels(1)
|
||||
})
|
||||
.unwrap();
|
||||
(seen.unwrap(), other_seen.unwrap())
|
||||
});
|
||||
assert_eq!((how, renderer), (Render::Serial, caller));
|
||||
assert_eq!(other_how, Render::Parallel);
|
||||
assert!(other_name.starts_with("lc-demo-scene-"), "{other_name}");
|
||||
}
|
||||
|
||||
/// A caller finding a generation running waits for it instead of rendering its own (one 24 MP original costs
|
||||
/// minutes of CPU time on a small machine).
|
||||
#[test]
|
||||
fn callers_wait_for_the_generation_running() {
|
||||
let (a, b, renders) = within(120, || {
|
||||
let slot = Arc::new(SceneSlot::default());
|
||||
let renders = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let (started_tx, started) = std::sync::mpsc::channel::<()>();
|
||||
let (go, go_rx) = std::sync::mpsc::channel::<()>();
|
||||
let (started_tx, go_rx) = (Arc::new(std::sync::Mutex::new(started_tx)), Arc::new(std::sync::Mutex::new(go_rx)));
|
||||
let ask = |slot: &Arc<SceneSlot>| {
|
||||
let (slot, renders, started_tx, go_rx) = (slot.clone(), renders.clone(), started_tx.clone(), go_rx.clone());
|
||||
std::thread::spawn(move || {
|
||||
slot.get_or_generate(move |_| {
|
||||
renders.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
let _ = started_tx.lock().unwrap().send(());
|
||||
let _ = go_rx.lock().unwrap().recv();
|
||||
pixels(1)
|
||||
})
|
||||
})
|
||||
};
|
||||
let first = ask(&slot);
|
||||
started.recv().unwrap();
|
||||
let second = ask(&slot);
|
||||
until_waiting(&slot, 1);
|
||||
go.send(()).unwrap();
|
||||
let (a, b) = (first.join().unwrap().unwrap(), second.join().unwrap().unwrap());
|
||||
(a, b, renders.load(std::sync::atomic::Ordering::SeqCst))
|
||||
});
|
||||
assert!(Arc::ptr_eq(&a, &b) && a.width == 1, "one generation, shared");
|
||||
assert_eq!(renders, 1);
|
||||
}
|
||||
|
||||
/// A generation that fails (its render panicked) is an error for its callers, never a hang, and the next request
|
||||
/// generates the scene again.
|
||||
#[test]
|
||||
fn a_failed_generation_is_an_error_and_the_next_request_tries_again() {
|
||||
let (first, waiters, again) = within(120, || {
|
||||
let slot = Arc::new(SceneSlot::default());
|
||||
let (started_tx, started) = std::sync::mpsc::channel::<()>();
|
||||
let (go, go_rx) = std::sync::mpsc::channel::<()>();
|
||||
let failing = {
|
||||
let slot = slot.clone();
|
||||
std::thread::spawn(move || {
|
||||
slot.get_or_generate(move |_| {
|
||||
let _ = started_tx.send(());
|
||||
let _ = go_rx.recv();
|
||||
panic!("render failed");
|
||||
})
|
||||
})
|
||||
};
|
||||
started.recv().unwrap();
|
||||
let waiters: Vec<_> = (0..2)
|
||||
.map(|_| {
|
||||
let slot = slot.clone();
|
||||
std::thread::spawn(move || slot.get_or_generate(|_| pixels(2)))
|
||||
})
|
||||
.collect();
|
||||
until_waiting(&slot, 2);
|
||||
drop(go);
|
||||
let first = failing.join().unwrap();
|
||||
let waiters: Vec<_> = waiters.into_iter().map(|w| w.join().unwrap()).collect();
|
||||
(first, waiters, slot.get_or_generate(|_| pixels(3)))
|
||||
});
|
||||
assert!(first.is_err() && waiters.iter().all(Result::is_err), "the callers of the failed generation get its error");
|
||||
assert_eq!(again.unwrap().width, 3);
|
||||
}
|
||||
|
||||
/// Callers get the outcome of the generation they waited for, even when a retry starts (or finishes) before they
|
||||
/// look: a failed generation followed by a retry is still an error for them.
|
||||
#[test]
|
||||
fn a_retry_never_changes_the_outcome_waited_for() {
|
||||
let mut st = SlotState::default();
|
||||
let n = st.start();
|
||||
assert!(st.outcome(n).is_none(), "running");
|
||||
st.generation = Generation::Failed;
|
||||
let m = st.start();
|
||||
assert!(matches!(st.outcome(n), Some(Err(_))));
|
||||
assert!(st.outcome(m).is_none());
|
||||
st.generation = Generation::Ready(Arc::new(pixels(1)));
|
||||
assert!(matches!(st.outcome(n), Some(Err(_))), "even once the retry succeeded");
|
||||
assert!(matches!(st.outcome(m), Some(Ok(_))));
|
||||
// and with threads: a retry racing the waiters of a failed generation never hands them its result
|
||||
let wrong = within(120, || {
|
||||
let mut wrong = 0;
|
||||
for _ in 0..20 {
|
||||
let slot = Arc::new(SceneSlot::default());
|
||||
let (started_tx, started) = std::sync::mpsc::channel::<()>();
|
||||
let (go, go_rx) = std::sync::mpsc::channel::<()>();
|
||||
let failing = {
|
||||
let slot = slot.clone();
|
||||
std::thread::spawn(move || {
|
||||
slot.get_or_generate(move |_| {
|
||||
let _ = started_tx.send(());
|
||||
let _ = go_rx.recv();
|
||||
panic!("render failed");
|
||||
})
|
||||
})
|
||||
};
|
||||
started.recv().unwrap();
|
||||
let waiters: Vec<_> = (0..3)
|
||||
.map(|_| {
|
||||
let slot = slot.clone();
|
||||
std::thread::spawn(move || slot.get_or_generate(|_| pixels(2)))
|
||||
})
|
||||
.collect();
|
||||
until_waiting(&slot, 3);
|
||||
let retry = {
|
||||
let slot = slot.clone();
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
if matches!(slot.lock().generation, Generation::Failed) {
|
||||
return slot.get_or_generate(|_| pixels(4));
|
||||
}
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
})
|
||||
};
|
||||
drop(go);
|
||||
let _ = failing.join().unwrap();
|
||||
wrong += waiters.into_iter().map(|w| w.join().unwrap()).filter(Result::is_ok).count();
|
||||
assert!(retry.join().unwrap().is_ok());
|
||||
}
|
||||
wrong
|
||||
});
|
||||
assert_eq!(wrong, 0, "waiters of a failed generation got a retry's pixels");
|
||||
}
|
||||
|
||||
/// Generating a scene never touches the global rayon pool, so a process whose global pool couldn't start (asking it
|
||||
/// anything then panics) still gets its demo scenes. Run in a process of its own: the global pool is the process's.
|
||||
#[test]
|
||||
fn scenes_are_generated_when_the_global_pool_is_broken() {
|
||||
use std::io::Read;
|
||||
use std::process::Stdio;
|
||||
let mut child = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "demo::tests::with_a_broken_global_pool", "--ignored", "--test-threads=1"])
|
||||
.env("LC_DEMO_BROKEN_GLOBAL_POOL", "1")
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
// Drain both pipes on threads so a chatty child can't block on a full pipe.
|
||||
let drain = |mut r: Box<dyn Read + Send>| {
|
||||
std::thread::spawn(move || {
|
||||
let mut s = String::new();
|
||||
let _ = r.read_to_string(&mut s);
|
||||
s
|
||||
})
|
||||
};
|
||||
let (stdout, stderr) = (drain(Box::new(child.stdout.take().unwrap())), drain(Box::new(child.stderr.take().unwrap())));
|
||||
// A deadlocked child fails the test instead of hanging CI.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
break status;
|
||||
}
|
||||
if std::time::Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
panic!("the child process did not finish within 120 s");
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
};
|
||||
let (stdout, stderr) = (stdout.join().unwrap(), stderr.join().unwrap());
|
||||
assert!(status.success() && stdout.contains("1 passed"), "{stdout}\n{stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "run in a process of its own by scenes_are_generated_when_the_global_pool_is_broken"]
|
||||
fn with_a_broken_global_pool() {
|
||||
if std::env::var_os("LC_DEMO_BROKEN_GLOBAL_POOL").is_none() {
|
||||
return;
|
||||
}
|
||||
let broken = rayon::ThreadPoolBuilder::new().spawn_handler(|_| Err(std::io::Error::other("no threads"))).build_global();
|
||||
assert!(broken.is_err());
|
||||
assert!(std::panic::catch_unwind(rayon::current_num_threads).is_err(), "the global pool is broken");
|
||||
let s = small_scene();
|
||||
let got = scene_pixels(&s, 33).unwrap();
|
||||
assert_eq!(got.data, s.render_fit_serial(33).data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_keeps_the_most_recent_scenes_within_its_limit() {
|
||||
let key = |max_edge| SceneKey { kind: lightcraft_scenes::Kind::Dunes, seed: 1, width: 3, height: 2, max_edge };
|
||||
let entry = |max_edge, used, px: Option<usize>| {
|
||||
let slot = Arc::new(SceneSlot::default());
|
||||
if let Some(n) = px {
|
||||
slot.lock().generation = Generation::Ready(Arc::new(lightcraft_raster::Rgb32f::new(n, 1)));
|
||||
}
|
||||
SceneEntry { key: key(max_edge), slot, used }
|
||||
};
|
||||
let px = std::mem::size_of::<[f32; 3]>();
|
||||
let mut c = SceneCache { entries: vec![entry(1, 3, Some(10)), entry(2, 1, Some(10)), entry(3, 0, None), entry(4, 2, Some(10))], tick: 3 };
|
||||
trim_scene_cache(&mut c, 25 * px);
|
||||
let mut kept: Vec<usize> = c.entries.iter().map(|e| e.key.max_edge).collect();
|
||||
kept.sort_unstable();
|
||||
assert_eq!(kept, vec![1, 3, 4], "the least recently used finished scene went; the one in progress stays");
|
||||
trim_scene_cache(&mut c, 0);
|
||||
assert_eq!(c.entries.iter().map(|e| e.key.max_edge).collect::<Vec<_>>(), vec![3], "only the scene in progress is left");
|
||||
}
|
||||
+25
-1911
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,152 @@
|
||||
#[cfg(feature = "denoise")]
|
||||
use super::model::{GpuSide, STACK};
|
||||
#[cfg(feature = "denoise")]
|
||||
use super::*;
|
||||
|
||||
/// Tiles run at once on a graphics card: enough to keep it fed while others are packed and blended.
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) const GPU_PARALLEL: usize = 4;
|
||||
|
||||
/// How far the GPU's answer on the check tile may be from the CPU's (of the answer's largest value) before it is not used.
|
||||
#[cfg(feature = "denoise")]
|
||||
const GPU_AGREE: f32 = 1e-3;
|
||||
|
||||
/// Longest the card may take to set up (build its kernels, run the check tile, time it) before the processor does the
|
||||
/// work instead.
|
||||
#[cfg(feature = "denoise")]
|
||||
const GPU_SETUP_LIMIT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Tiles the card may get wrong (an error, numbers that are not finite) before it stops being used for the model.
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) const GPU_MAX_FALLBACKS: usize = 3;
|
||||
|
||||
/// The file beside a model while the graphics card is set up for it (see [`set_up_card`]).
|
||||
pub(crate) const GPU_SETUP_MARKER: &str = "gpu-setup.marker";
|
||||
|
||||
/// Why the card is not tried when a set-up marker is found.
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) const GPU_CRASHED: &str = "LightCraft closed while it was setting up the graphics card for AI Denoise last time";
|
||||
|
||||
/// Why the card is not used when its set-up ran out of time (the start of it).
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) const GPU_SLOW: &str = "setting up the graphics card took longer than";
|
||||
|
||||
/// Why the card is not used while a set-up that ran out of time is still going.
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) const GPU_STUCK: &str = "the graphics card is still setting up from before (it took too long)";
|
||||
|
||||
/// Whether the card (`card_ms` a tile) is faster than the CPU running `threads` tiles at once, from the CPU's time for
|
||||
/// one tile alone (`cpu_ms`). Tiles at once share the memory and the cores' second threads, so each one more counts as
|
||||
/// half a tile's speed: on a 16-core laptop one tile alone took 1.4 s and sixteen at once finished one every 0.2 s.
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) fn card_is_faster(card_ms: f64, cpu_ms: f64, threads: usize) -> bool {
|
||||
let at_once = 1.0 + 0.5 * threads.saturating_sub(1) as f64;
|
||||
card_ms.is_finite() && card_ms <= cpu_ms / at_once
|
||||
}
|
||||
|
||||
/// Card set-ups of this process that have not finished, by marker (their markers are not a crash's).
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) static SETTING_UP: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Removes a set-up's marker when the set-up ends, however it ends — but not when the process dies inside the driver.
|
||||
#[cfg(feature = "denoise")]
|
||||
struct SetUpEnded(PathBuf);
|
||||
|
||||
#[cfg(feature = "denoise")]
|
||||
impl Drop for SetUpEnded {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
SETTING_UP.lock().unwrap_or_else(PoisonError::into_inner).retain(|m| m != &self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the graphics card up with `card` on a thread of its own while `meanwhile` runs here, and give up on the card when
|
||||
/// it takes longer than `limit` (a driver building kernels for minutes, or stuck). The `marker` file exists while `card`
|
||||
/// runs: one found before it starts was left by a LightCraft that closed during a set-up (a driver crash takes the app
|
||||
/// with it), so the card is not tried again until the user chooses where denoise runs (`denoise.settings {runOn}`).
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) fn set_up_card<T: Send + 'static, R>(
|
||||
marker: &Path,
|
||||
limit: Duration,
|
||||
card: impl FnOnce() -> Result<T, String> + Send + 'static,
|
||||
meanwhile: impl FnOnce() -> R,
|
||||
) -> Result<(T, R), String> {
|
||||
let ended = {
|
||||
let mut running = SETTING_UP.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if running.iter().any(|m| m == marker) {
|
||||
return Err(GPU_STUCK.into());
|
||||
}
|
||||
if marker.exists() {
|
||||
return Err(GPU_CRASHED.into());
|
||||
}
|
||||
let secs = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs());
|
||||
// a marker that cannot be written only loses the crash guard
|
||||
let _ = std::fs::write(marker, format!("setting up the graphics card for AI Denoise (unix time {secs})\n"));
|
||||
running.push(marker.to_path_buf());
|
||||
SetUpEnded(marker.to_path_buf())
|
||||
};
|
||||
let started = web_time::Instant::now();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("denoise-gpu-setup".into())
|
||||
.stack_size(STACK)
|
||||
.spawn(move || {
|
||||
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(card)).unwrap_or_else(|_| Err("the GPU runner gave up".into()));
|
||||
drop(ended);
|
||||
let _ = tx.send(r);
|
||||
})
|
||||
.map_err(|e| format!("could not start setting up the graphics card: {e}"))?;
|
||||
let here = meanwhile();
|
||||
match rx.recv_timeout(limit.saturating_sub(started.elapsed())) {
|
||||
Ok(r) => r.map(|t| (t, here)),
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Err(format!("{GPU_SLOW} {} s, so it is not used", limit.as_secs_f64())),
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err("the GPU runner gave up".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The card's time for one tile once it is warm: the fastest of up to three runs, stopping after about two seconds (a
|
||||
/// slow card is slow enough to tell at once).
|
||||
#[cfg(feature = "denoise")]
|
||||
fn card_tile_ms(runner: &dyn TileRunner, input: &[f32]) -> f64 {
|
||||
if runner.run(input).is_err() {
|
||||
return f64::INFINITY;
|
||||
}
|
||||
let began = web_time::Instant::now();
|
||||
let mut best = f64::INFINITY;
|
||||
for _ in 0..3 {
|
||||
let one = web_time::Instant::now();
|
||||
if runner.run(input).is_err() {
|
||||
break;
|
||||
}
|
||||
best = best.min(one.elapsed().as_secs_f64() * 1000.0);
|
||||
if began.elapsed() > Duration::from_secs(2) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Set the card up for the model at `path`: kernels built, the check tile run on both and compared, both timed.
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) fn make_gpu(cpu: &lightcraft_denoise::runtime::CpuRunner, path: &Path, tile: usize) -> Result<GpuSide, String> {
|
||||
let input = Arc::new(lightcraft_denoise::runtime::check_tile(tile));
|
||||
let (on_card, net) = (input.clone(), cpu.net().clone());
|
||||
let card = move || -> Result<_, String> {
|
||||
let runner = lightcraft_gpu::nn::runner(&net, tile)?;
|
||||
let got = runner.run(&on_card).map_err(|e| format!("the GPU could not run the check tile: {e}"))?;
|
||||
let card_ms = card_tile_ms(&runner, &on_card);
|
||||
Ok((runner, got, card_ms))
|
||||
};
|
||||
let on_cpu = || {
|
||||
let started = web_time::Instant::now();
|
||||
(cpu.run(&input), started.elapsed().as_secs_f64() * 1000.0)
|
||||
};
|
||||
let ((runner, got, card_ms), (want, cpu_ms)) = set_up_card(&path.with_file_name(GPU_SETUP_MARKER), GPU_SETUP_LIMIT, card, on_cpu)?;
|
||||
let want = want.map_err(|e| format!("the CPU could not check the GPU: {e}"))?;
|
||||
let scale = want.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-12);
|
||||
let worst = want.iter().zip(&got).fold(0f32, |m, (a, b)| m.max((a - b).abs())) / scale;
|
||||
if got.len() != want.len() || !got.iter().all(|v| v.is_finite()) || worst > GPU_AGREE {
|
||||
return Err(format!("its answer on the check tile is not the CPU's (off by {worst:.1e} of the largest value): not used"));
|
||||
}
|
||||
Ok(GpuSide { adapter: runner.adapter(), runner: Box::new(runner), card_ms, cpu_ms })
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
use super::*;
|
||||
use lightcraft_denoise::manifest::{Domain, Gain};
|
||||
|
||||
/// A folder of the test's own: the card's set-up leaves its marker beside the model.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("lc-engine-gpu-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// The model file is read again when the card is set up (for the first photo), so it stays until the test ends.
|
||||
fn model(name: &str, tile: u64) -> (Arc<dyn Model>, lightcraft_denoise::runtime::CpuRunner, PathBuf) {
|
||||
let path = folder(name).join("model.onnx");
|
||||
std::fs::write(&path, lightcraft_denoise::synthetic::unet_onnx(tile, 8, 2, 7)).unwrap();
|
||||
let manifest = DenoiserManifest {
|
||||
id: "synthetic".into(),
|
||||
name: "Synthetic".into(),
|
||||
version: "1".into(),
|
||||
licence: Default::default(),
|
||||
source: None,
|
||||
sha256: None,
|
||||
size_bytes: None,
|
||||
provenance: String::new(),
|
||||
domain: Domain::BayerToRgb,
|
||||
tile: tile as u32,
|
||||
overlap: 16,
|
||||
gain: Gain::MatchMean { nominal: 1.0, max_deviation: 0.05 },
|
||||
};
|
||||
let loaded = default_loader()(&path, &manifest).unwrap();
|
||||
let cpu = lightcraft_denoise::runtime::CpuRunner::load(&path, &manifest).unwrap();
|
||||
(loaded, cpu, path)
|
||||
}
|
||||
|
||||
fn worst(want: &[f32], got: &[f32]) -> f32 {
|
||||
assert_eq!(want.len(), got.len());
|
||||
let scale = want.iter().fold(1e-9f32, |m, v| m.max(v.abs()));
|
||||
want.iter().zip(got).fold(0f32, |m, (a, b)| m.max((a - b).abs())) / scale
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tile_on_the_card_is_the_cpus_tile() {
|
||||
let (model, cpu, path) = model("same", 64);
|
||||
let (input, _) = lightcraft_denoise::runtime::test_tile(64);
|
||||
let want = cpu.run(&input).unwrap();
|
||||
let (runner, at_once) = model.runner(RunOn::Gpu, 16);
|
||||
assert!(worst(&want, &runner.run(&input).unwrap()) < 1e-3);
|
||||
let device = model.device(RunOn::Gpu);
|
||||
eprintln!("device: {device}");
|
||||
match device["kind"].as_str() {
|
||||
Some("gpu") => {
|
||||
assert!(device["adapter"].as_str().is_some_and(|a| !a.is_empty()));
|
||||
assert!(at_once <= GPU_PARALLEL, "a card is fed by a few tiles at once");
|
||||
assert!(device["cardMs"].as_f64().is_some_and(|ms| ms > 0.0) && device["cpuMs"].as_f64().is_some_and(|ms| ms > 0.0), "{device}");
|
||||
}
|
||||
Some("cpu") => {
|
||||
assert!(device["reason"].as_str().is_some_and(|r| !r.is_empty()), "the CPU is only used for a reason: {device}");
|
||||
assert_eq!(at_once, 16);
|
||||
}
|
||||
other => panic!("the first photo decides where the work runs, not {other:?}"),
|
||||
}
|
||||
assert!(!path.with_file_name(GPU_SETUP_MARKER).exists(), "a set-up that ended leaves no marker");
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
/// A server on this computer running `cpu` for the model with `sha256`.
|
||||
fn server(cpu: lightcraft_denoise::runtime::CpuRunner, sha256: &str, tile: usize) -> String {
|
||||
use lightcraft_denoise::remote::{ModelId, ServerOptions, serve};
|
||||
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = l.local_addr().unwrap().to_string();
|
||||
let id = ModelId { id: "synthetic".into(), version: "1".into(), sha256: sha256.into() };
|
||||
let run: lightcraft_denoise::remote::RunTile = Arc::new(move |input: &[f32]| cpu.run(input));
|
||||
let opts = ServerOptions { token: "remote-test-token-0123".into(), ..Default::default() };
|
||||
std::thread::spawn(move || serve(l, id, tile, "CPU (test server)".into(), run, opts, Arc::new(|_| {})));
|
||||
addr
|
||||
}
|
||||
|
||||
fn with_remote(path: &Path, tile: u64, addr: &str, sha256: &str) -> Network {
|
||||
let manifest = DenoiserManifest {
|
||||
id: "synthetic".into(),
|
||||
name: "Synthetic".into(),
|
||||
version: "1".into(),
|
||||
licence: Default::default(),
|
||||
source: None,
|
||||
sha256: None,
|
||||
size_bytes: None,
|
||||
provenance: String::new(),
|
||||
domain: Domain::BayerToRgb,
|
||||
tile: tile as u32,
|
||||
overlap: 16,
|
||||
gain: Gain::MatchMean { nominal: 1.0, max_deviation: 0.05 },
|
||||
};
|
||||
let remote = RemoteSide::new(lightcraft_denoise::remote::Remote::new(addr, "remote-test-token-0123", sha256, tile as usize));
|
||||
network(path, &manifest, Some(remote)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_remote_server_shares_the_tiles_and_drops_out_when_it_cannot() {
|
||||
let (_, cpu, path) = model("remote", 64);
|
||||
let sha = lightcraft_denoise::hash::sha256_file(&path).unwrap();
|
||||
let (input, _) = lightcraft_denoise::runtime::test_tile(64);
|
||||
let want = cpu.run(&input).unwrap();
|
||||
// the same model on the server: its slots come on top of this computer's threads, answers within f16 rounding
|
||||
let addr = server(lightcraft_denoise::runtime::CpuRunner::load(&path, &cpu.manifest().clone()).unwrap(), &sha, 64);
|
||||
let net = with_remote(&path, 64, &addr, &sha);
|
||||
let (runner, at_once) = net.runner(RunOn::Cpu, 2);
|
||||
assert_eq!(at_once, 2 + 4, "four server slots on top of two local threads");
|
||||
assert!(worst(&want, &runner.run(&input).unwrap()) < 5e-3);
|
||||
let d = net.device(RunOn::Cpu);
|
||||
assert_eq!(d["remote"]["state"], "used", "{d}");
|
||||
assert_eq!(d["remote"]["device"], "CPU (test server)");
|
||||
// a local card faster than the server there and back (here a stand-in that takes no time): nothing is shared,
|
||||
// the photo never waits for the slower server, and the status says why
|
||||
let mut net = with_remote(&path, 64, &addr, &sha);
|
||||
net.gpu = OnceLock::from(Ok(GpuSide { runner: Box::new(cpu.clone()), adapter: "Fast card".into(), card_ms: 1e-6, cpu_ms: 1000.0 }));
|
||||
let (_, at_once) = net.runner(RunOn::Gpu, 8);
|
||||
assert_eq!(at_once, GPU_PARALLEL, "no server slots");
|
||||
let d = net.device(RunOn::Gpu);
|
||||
assert_eq!(d["remote"]["state"], "slower", "{d}");
|
||||
assert!(d["remote"]["remoteMs"].as_f64().is_some_and(|ms| ms > 0.0) && d["remote"]["localMs"].as_f64().is_some(), "{d}");
|
||||
// a server running another model is refused: everything runs here
|
||||
let other = server(lightcraft_denoise::runtime::CpuRunner::load(&path, &cpu.manifest().clone()).unwrap(), "0000", 64);
|
||||
let net = with_remote(&path, 64, &other, &sha);
|
||||
let (runner, at_once) = net.runner(RunOn::Cpu, 2);
|
||||
assert_eq!(at_once, 2);
|
||||
assert_eq!(runner.run(&input).unwrap(), want, "the CPU path, bit for bit");
|
||||
let d = net.device(RunOn::Cpu);
|
||||
assert!(d["remote"]["reason"].as_str().is_some_and(|r| r.contains("another model")), "{d}");
|
||||
// nobody listening: the same
|
||||
let net = with_remote(&path, 64, "127.0.0.1:1", &sha);
|
||||
assert_eq!(net.runner(RunOn::Cpu, 3).1, 3);
|
||||
assert_eq!(net.device(RunOn::Cpu)["remote"]["state"], "unavailable");
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_the_processor_chosen_everything_runs_on_the_cpu() {
|
||||
let (model, cpu, path) = model("cpu", 64);
|
||||
let (input, _) = lightcraft_denoise::runtime::test_tile(64);
|
||||
let (runner, at_once) = model.runner(RunOn::Cpu, 16);
|
||||
assert_eq!(runner.run(&input).unwrap(), cpu.run(&input).unwrap(), "the CPU path is the CPU runner, bit for bit");
|
||||
assert_eq!(at_once, 16, "the threads asked for are the threads used");
|
||||
assert_eq!(model.device(RunOn::Cpu)["kind"], "cpu");
|
||||
assert_eq!(model.device(RunOn::Auto)["kind"], "pending", "the card was not even set up");
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_card_is_used_where_it_is_faster_than_the_processor() {
|
||||
// measured: a tile alone on one CPU thread 1.4 s; an RTX 4090 Laptop 13 ms; a Radeon 610M 490 ms
|
||||
for threads in [1, 2, 8, 16, 64] {
|
||||
assert!(card_is_faster(13.0, 1400.0, threads), "a big card wins at {threads}");
|
||||
}
|
||||
assert!(card_is_faster(490.0, 1400.0, 2), "a small card beats the two threads background work gets");
|
||||
assert!(!card_is_faster(490.0, 1400.0, 16), "and loses to sixteen");
|
||||
assert!(!card_is_faster(f64::INFINITY, 1400.0, 1) && !card_is_faster(f64::NAN, 1400.0, 1), "a card that never ran is never faster");
|
||||
assert!(!card_is_faster(10.0, 0.0, 1));
|
||||
}
|
||||
|
||||
/// A card that gives numbers that are not finite.
|
||||
struct Garbage(AtomicUsize);
|
||||
|
||||
impl TileRunner for Garbage {
|
||||
fn run(&self, input: &[f32]) -> Result<Vec<f32>, RunError> {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
let n = input.len() / 4 * 12;
|
||||
Ok(vec![f32::NAN; n])
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tile_the_card_gets_wrong_is_run_on_the_processor_and_three_stop_the_card() {
|
||||
let (_, cpu, path) = model("garbage", 64);
|
||||
let card = GpuSide { runner: Box::new(Garbage(AtomicUsize::new(0))), adapter: "Test card".into(), card_ms: 1.0, cpu_ms: 1000.0 };
|
||||
let model = Network {
|
||||
cpu: cpu.clone(),
|
||||
path: path.clone(),
|
||||
tile: 32,
|
||||
gpu: OnceLock::from(Ok(card)),
|
||||
fallbacks: AtomicUsize::new(0),
|
||||
last_threads: AtomicUsize::new(0),
|
||||
remote: None,
|
||||
local_card: AtomicBool::new(true),
|
||||
};
|
||||
let (input, _) = lightcraft_denoise::runtime::test_tile(64);
|
||||
let want = cpu.run(&input).unwrap();
|
||||
let (runner, at_once) = model.runner(RunOn::Auto, 8);
|
||||
assert_eq!(at_once, GPU_PARALLEL, "the (fast) card is chosen");
|
||||
for _ in 0..GPU_MAX_FALLBACKS {
|
||||
assert_eq!(runner.run(&input).unwrap(), want, "a wrong tile is the CPU's tile");
|
||||
}
|
||||
let device = model.device(RunOn::Auto);
|
||||
assert_eq!(device["kind"], "cpu", "{device}");
|
||||
assert!(device["reason"].as_str().unwrap().contains("tiles wrong"), "{device}");
|
||||
assert_eq!(device["fellBack"], GPU_MAX_FALLBACKS);
|
||||
let (_, at_once) = model.runner(RunOn::Gpu, 8);
|
||||
assert_eq!(at_once, 8, "the next photo runs on the CPU, even with the card chosen");
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_card_is_left_out_unless_it_is_chosen() {
|
||||
let (_, cpu, path) = model("slow", 64);
|
||||
let slow = GpuSide { runner: Box::new(cpu.clone()), adapter: "Slow card".into(), card_ms: 490.0, cpu_ms: 1400.0 };
|
||||
let model = Network {
|
||||
cpu,
|
||||
path: path.clone(),
|
||||
tile: 32,
|
||||
gpu: OnceLock::from(Ok(slow)),
|
||||
fallbacks: AtomicUsize::new(0),
|
||||
last_threads: AtomicUsize::new(0),
|
||||
remote: None,
|
||||
local_card: AtomicBool::new(true),
|
||||
};
|
||||
assert_eq!(model.runner(RunOn::Auto, 16).1, 16, "sixteen threads beat it");
|
||||
let device = model.device(RunOn::Auto);
|
||||
assert_eq!((device["kind"].as_str(), device["reason"].as_str()), (Some("cpu"), Some("it is faster than Slow card on this computer")));
|
||||
assert_eq!(device["cardMs"], 490.0, "the times measured are reported");
|
||||
assert_eq!(device["retry"], false, "trying again would not make it faster");
|
||||
assert_eq!(model.runner(RunOn::Auto, 2).1, GPU_PARALLEL.min(2), "two threads do not");
|
||||
assert_eq!(model.device(RunOn::Auto)["kind"], "gpu");
|
||||
assert_eq!(model.runner(RunOn::Gpu, 16).1, GPU_PARALLEL, "chosen, it is used anyway");
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_up_marker_left_behind_keeps_the_card_off() {
|
||||
let (model, _, path) = model("crashed", 64);
|
||||
let marker = path.with_file_name(GPU_SETUP_MARKER);
|
||||
std::fs::write(&marker, "setting up the graphics card for AI Denoise (unix time 0)").unwrap();
|
||||
let (_, at_once) = model.runner(RunOn::Gpu, 4);
|
||||
assert_eq!(at_once, 4, "the CPU does the work");
|
||||
let device = model.device(RunOn::Gpu);
|
||||
assert_eq!((device["kind"].as_str(), device["reason"].as_str()), (Some("cpu"), Some(GPU_CRASHED)), "{device}");
|
||||
assert_eq!(device["retry"], true, "the interface offers to try again");
|
||||
assert!(marker.exists(), "it stays until the user chooses where denoise runs");
|
||||
let _ = std::fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_up_runs_beside_the_cpu_and_removes_its_marker() {
|
||||
let dir = folder("setup");
|
||||
let marker = dir.join(GPU_SETUP_MARKER);
|
||||
let seen = Arc::new(AtomicBool::new(false));
|
||||
let (m, s) = (marker.clone(), seen.clone());
|
||||
let r = set_up_card(
|
||||
&marker,
|
||||
Duration::from_secs(10),
|
||||
move || {
|
||||
s.store(m.exists(), Ordering::Relaxed);
|
||||
Ok(7)
|
||||
},
|
||||
|| "cpu",
|
||||
);
|
||||
assert_eq!(r, Ok((7, "cpu")));
|
||||
assert!(seen.load(Ordering::Relaxed), "the marker is there while the card is set up");
|
||||
assert!(!marker.exists(), "and gone after");
|
||||
// a set-up that fails or panics removes it too
|
||||
assert_eq!(set_up_card(&marker, Duration::from_secs(10), || Err::<(), _>("no card".into()), || ()), Err("no card".into()));
|
||||
assert!(!marker.exists());
|
||||
let r = set_up_card(&marker, Duration::from_secs(10), || -> Result<(), String> { panic!("driver") }, || ());
|
||||
assert!(r.is_err() && !marker.exists(), "{r:?}");
|
||||
// a marker found before the set-up starts means the last one took LightCraft down: the card is not touched
|
||||
std::fs::write(&marker, "left behind").unwrap();
|
||||
let touched = Arc::new(AtomicBool::new(false));
|
||||
let t = touched.clone();
|
||||
let r = set_up_card(
|
||||
&marker,
|
||||
Duration::from_secs(10),
|
||||
move || {
|
||||
t.store(true, Ordering::Relaxed);
|
||||
Ok(())
|
||||
},
|
||||
|| (),
|
||||
);
|
||||
assert_eq!(r, Err(GPU_CRASHED.to_string()));
|
||||
assert!(!touched.load(Ordering::Relaxed) && marker.exists());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_up_that_takes_too_long_is_given_up_on() {
|
||||
let dir = folder("slowsetup");
|
||||
let marker = dir.join(GPU_SETUP_MARKER);
|
||||
let started = web_time::Instant::now();
|
||||
let slow = || -> Result<(), String> {
|
||||
std::thread::sleep(Duration::from_millis(600));
|
||||
Ok(())
|
||||
};
|
||||
let r = set_up_card(&marker, Duration::from_millis(50), slow, || ());
|
||||
assert!(r.as_ref().is_err_and(|e| e.contains("took longer") && worth_retrying(e)), "{r:?}");
|
||||
assert!(started.elapsed() < Duration::from_millis(500), "the caller does not wait for the card");
|
||||
// while the first is still stuck, another set-up of the same model does not start a second one
|
||||
let again = set_up_card(&marker, Duration::from_secs(5), || Ok(()), || ());
|
||||
assert!(again.is_err_and(|e| e.contains("still setting up") && worth_retrying(&e)));
|
||||
// once it ends its marker goes, and the card can be set up again
|
||||
while marker.exists() {
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "the stuck set-up ended");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
while SETTING_UP.lock().unwrap().iter().any(|m| m == &marker) {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
assert_eq!(set_up_card(&marker, Duration::from_secs(5), || Ok(1), || 2), Ok((1, 2)));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
#[cfg(feature = "denoise")]
|
||||
use super::gpu::{GPU_CRASHED, GPU_MAX_FALLBACKS, GPU_PARALLEL, GPU_SLOW, GPU_STUCK, card_is_faster, make_gpu};
|
||||
#[cfg(feature = "denoise")]
|
||||
use super::settings::{installed_models, read_settings};
|
||||
#[cfg(feature = "denoise")]
|
||||
use super::state::Pace;
|
||||
use super::*;
|
||||
|
||||
/// Stack of the threads that run the model (the runtime recurses through its graph).
|
||||
pub(super) const STACK: usize = 16 << 20;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
// the model
|
||||
|
||||
/// Where the model runs (Settings ▸ AI Denoise ▸ Speed; `denoise.settings {runOn}`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum RunOn {
|
||||
/// The graphics card where it is faster than the processor at the pace the work goes at (both are timed on this
|
||||
/// computer when the card is set up), else the processor.
|
||||
#[default]
|
||||
Auto,
|
||||
/// The graphics card whenever it can run the model, even where the processor would be faster.
|
||||
Gpu,
|
||||
/// Always the processor.
|
||||
Cpu,
|
||||
}
|
||||
|
||||
impl RunOn {
|
||||
/// `auto`, `gpu` or `cpu`.
|
||||
pub fn parse(name: &str) -> Option<RunOn> {
|
||||
match name {
|
||||
"auto" => Some(RunOn::Auto),
|
||||
"gpu" => Some(RunOn::Gpu),
|
||||
"cpu" => Some(RunOn::Cpu),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
RunOn::Auto => "auto",
|
||||
RunOn::Gpu => "gpu",
|
||||
RunOn::Cpu => "cpu",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A loaded denoise model: what runs tiles, and a self-check.
|
||||
pub(crate) trait Model: Send + Sync {
|
||||
/// What runs a photo's tiles, and how many to run at once, when `threads` may be used and the setting is `run_on`
|
||||
/// (a graphics card is kept busy by a few). The first time the card may be used it is set up and checked here.
|
||||
fn runner(&self, run_on: RunOn, threads: usize) -> (&dyn TileRunner, usize);
|
||||
/// Check it does something sensible: the test's result, or why not. Unless `run_on` is the processor the graphics
|
||||
/// card is set up and checked too, and the result says where the work will run.
|
||||
fn self_test(&self, run_on: RunOn) -> Result<Value, String>;
|
||||
/// Conservative scratch bound for an unknown runner.
|
||||
fn bytes_per_tile(&self) -> usize {
|
||||
512 * 1024 * 1024
|
||||
}
|
||||
/// Where the tiles run: `{kind: "gpu", adapter}`, `{kind: "cpu", reason?}` or `{kind: "pending"}` (the card is not
|
||||
/// set up yet), with the card's and the processor's time for the check tile (`cardMs`, `cpuMs`) once both were
|
||||
/// timed. Never starts anything.
|
||||
fn device(&self, _run_on: RunOn) -> Value {
|
||||
json!({"kind": "cpu"})
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads the model at a path as its manifest describes it.
|
||||
pub(crate) type Loader = Arc<dyn Fn(&Path, &DenoiserManifest) -> Result<Arc<dyn Model>, String> + Send + Sync>;
|
||||
|
||||
/// A set-up that may work another time (a crash, the time limit), unlike one the card or the model cannot do.
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) fn worth_retrying(why: &str) -> bool {
|
||||
why == GPU_CRASHED || why == GPU_STUCK || why.starts_with(GPU_SLOW)
|
||||
}
|
||||
|
||||
/// The model on our pure-Rust CPU runner, and on the graphics card when there is one that can run it: the card is set up for the
|
||||
/// first photo that may use it, checked against the CPU's answer on a check tile and timed against it, and used while
|
||||
/// it keeps working; a tile it gets wrong is run on the CPU, so a photo is always finished.
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) struct Network {
|
||||
pub(super) cpu: lightcraft_denoise::runtime::CpuRunner,
|
||||
pub(super) path: PathBuf,
|
||||
pub(super) tile: usize,
|
||||
pub(super) gpu: OnceLock<Result<GpuSide, String>>,
|
||||
/// Tiles the card got wrong (an error, numbers that are not finite) and the CPU ran.
|
||||
pub(super) fallbacks: AtomicUsize,
|
||||
/// Tiles at once of the photo started last (0: none yet), to say where the work runs.
|
||||
pub(super) last_threads: AtomicUsize,
|
||||
/// Another computer's graphics card (`LIGHTCRAFT_DENOISE_URL` + `LIGHTCRAFT_DENOISE_TOKEN`; see
|
||||
/// `docs/denoise.md` → Another computer's graphics card), greeted on first use: it takes tiles while it has a free
|
||||
/// slot, on top of this computer's runner.
|
||||
pub(super) remote: Option<RemoteSide>,
|
||||
/// Whether this computer's share runs on the card (else the CPU), as chosen for the photo started last.
|
||||
pub(super) local_card: AtomicBool,
|
||||
}
|
||||
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) struct RemoteSide {
|
||||
runner: lightcraft_denoise::remote::Remote,
|
||||
/// The greeting, and the server's time for the check tile there and back (ms; the faster of two runs).
|
||||
greeted: OnceLock<Result<(lightcraft_denoise::remote::ServerInfo, f64), String>>,
|
||||
/// Whether the photo started last shares tiles with the server, and if not because it is slower, the two times.
|
||||
share: AtomicBool,
|
||||
slower: Mutex<Option<(f64, f64)>>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "denoise")]
|
||||
impl RemoteSide {
|
||||
/// From the environment, for the model whose file has `sha256` and tiles of `tile` cells.
|
||||
fn from_env(sha256: &str, tile: usize) -> Option<RemoteSide> {
|
||||
let var = |k: &str| std::env::var(k).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty());
|
||||
let address = var("LIGHTCRAFT_DENOISE_URL")?;
|
||||
let token = var("LIGHTCRAFT_DENOISE_TOKEN").unwrap_or_default();
|
||||
Some(RemoteSide::new(lightcraft_denoise::remote::Remote::new(&address, &token, sha256, tile)))
|
||||
}
|
||||
|
||||
pub(super) fn new(runner: lightcraft_denoise::remote::Remote) -> RemoteSide {
|
||||
RemoteSide { runner, greeted: OnceLock::new(), share: AtomicBool::new(false), slower: Mutex::new(None) }
|
||||
}
|
||||
|
||||
/// Greet the server and time a check tile there and back: a server behind a slow link can take seconds a tile, and
|
||||
/// handing it tiles a fast local card would finish sooner only makes the photo wait for it.
|
||||
fn greet(&self) -> Result<(lightcraft_denoise::remote::ServerInfo, f64), String> {
|
||||
let info = self.runner.hello().map_err(|e| e.to_string())?;
|
||||
let input = lightcraft_denoise::runtime::check_tile(info.tile);
|
||||
let mut best = f64::INFINITY;
|
||||
for _ in 0..2 {
|
||||
let started = web_time::Instant::now();
|
||||
match self.runner.try_run(&input) {
|
||||
Some(Ok(_)) => best = best.min(started.elapsed().as_secs_f64() * 1000.0),
|
||||
Some(Err(e)) => return Err(format!("the check tile failed: {e}")),
|
||||
None => return Err("no free slot for the check tile".into()),
|
||||
}
|
||||
}
|
||||
Ok((info, best))
|
||||
}
|
||||
|
||||
/// The server when it can take tiles now (greeting it the first time), else why not.
|
||||
fn usable(&self, start: bool) -> Result<&lightcraft_denoise::remote::Remote, String> {
|
||||
let greeted = if start { Some(self.greeted.get_or_init(|| self.greet())) } else { self.greeted.get() };
|
||||
match greeted {
|
||||
None => Err("not contacted yet".into()),
|
||||
Some(Err(why)) => Err(why.clone()),
|
||||
Some(Ok(_)) if !self.runner.healthy() => {
|
||||
Err(format!("it failed {} tiles ({})", self.runner.failures(), self.runner.last_error().unwrap_or_default()))
|
||||
}
|
||||
Some(Ok(_)) => Ok(&self.runner),
|
||||
}
|
||||
}
|
||||
|
||||
/// The server's time for a tile, once greeted.
|
||||
fn tile_ms(&self) -> Option<f64> {
|
||||
self.greeted.get().and_then(|g| g.as_ref().ok()).map(|g| g.1)
|
||||
}
|
||||
|
||||
fn describe(&self) -> Value {
|
||||
match self.greeted.get() {
|
||||
None => json!({"address": self.runner.address(), "state": "pending"}),
|
||||
Some(Err(why)) => json!({"address": self.runner.address(), "state": "unavailable", "reason": why}),
|
||||
Some(Ok((info, ms))) => {
|
||||
let slower = *self.slower.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let state = match () {
|
||||
_ if !self.runner.healthy() => "given up",
|
||||
_ if slower.is_some() => "slower",
|
||||
_ if self.share.load(Ordering::Relaxed) => "used",
|
||||
_ => "idle",
|
||||
};
|
||||
let mut v =
|
||||
json!({"address": info.address, "device": info.device, "state": state, "remoteMs": ms, "failures": self.runner.failures()});
|
||||
if let (Some((_, local)), Some(o)) = (slower, v.as_object_mut()) {
|
||||
o.insert("localMs".into(), json!(local));
|
||||
}
|
||||
if let (Some(e), Some(o)) = (self.runner.last_error(), v.as_object_mut()) {
|
||||
o.insert("lastError".into(), json!(e));
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) struct GpuSide {
|
||||
pub(super) runner: Box<dyn TileRunner + Send>,
|
||||
pub(super) adapter: String,
|
||||
/// The check tile on the card, the fastest of a few runs (ms).
|
||||
pub(super) card_ms: f64,
|
||||
/// The check tile on the CPU, on one thread (ms).
|
||||
pub(super) cpu_ms: f64,
|
||||
}
|
||||
|
||||
#[cfg(feature = "denoise")]
|
||||
impl Network {
|
||||
/// The card when it can be used now, else why not. `start` sets it up when that has not been tried yet; without it
|
||||
/// nothing is started.
|
||||
fn card(&self, start: bool) -> Result<&GpuSide, String> {
|
||||
let side = if start {
|
||||
Some(self.gpu.get_or_init(|| {
|
||||
let made = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| make_gpu(&self.cpu, &self.path, self.tile)))
|
||||
.unwrap_or_else(|_| Err("the GPU runner gave up".into()));
|
||||
if let Err(why) = &made {
|
||||
log::info!("denoise: running on the CPU ({why})");
|
||||
}
|
||||
made
|
||||
}))
|
||||
} else {
|
||||
self.gpu.get()
|
||||
};
|
||||
let g = match side {
|
||||
None => return Err("the graphics card is not set up yet".into()),
|
||||
Some(Err(why)) => return Err(why.clone()),
|
||||
Some(Ok(g)) => g,
|
||||
};
|
||||
if let Some(why) = lightcraft_gpu::nn::broken_reason() {
|
||||
return Err(format!("the graphics card stopped working ({why})"));
|
||||
}
|
||||
if self.fallbacks.load(Ordering::Relaxed) >= GPU_MAX_FALLBACKS {
|
||||
return Err(format!("{} got {GPU_MAX_FALLBACKS} tiles wrong", g.adapter));
|
||||
}
|
||||
Ok(g)
|
||||
}
|
||||
|
||||
/// The card, when a photo made `threads` tiles at a time under `run_on` runs on it; else why the CPU does.
|
||||
fn choose(&self, run_on: RunOn, threads: usize, start: bool) -> Result<&GpuSide, String> {
|
||||
if run_on == RunOn::Cpu {
|
||||
return Err("the processor is chosen in Settings".into());
|
||||
}
|
||||
let g = self.card(start)?;
|
||||
if run_on == RunOn::Auto && !card_is_faster(g.card_ms, g.cpu_ms, threads) {
|
||||
return Err(format!("it is faster than {} on this computer", g.adapter));
|
||||
}
|
||||
Ok(g)
|
||||
}
|
||||
|
||||
fn fell_back(&self, why: &str) {
|
||||
let n = self.fallbacks.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if n == 1 {
|
||||
log::warn!("denoise: a tile came back wrong from the GPU ({why}); the CPU runs it");
|
||||
} else if n == GPU_MAX_FALLBACKS {
|
||||
log::warn!("denoise: the GPU got {n} tiles wrong; the CPU does the rest");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A remote server's free slot first (when there is one), then the card when this photo runs on it, with the CPU
|
||||
/// running any tile either gets wrong. Handed out for photos that run on the card or have a server to share.
|
||||
#[cfg(feature = "denoise")]
|
||||
impl TileRunner for Network {
|
||||
fn run(&self, input: &[f32]) -> Result<Vec<f32>, RunError> {
|
||||
if let Some(Ok(remote)) = self.remote.as_ref().filter(|r| r.share.load(Ordering::Relaxed)).map(|r| r.usable(false))
|
||||
&& let Some(Ok(out)) = remote.try_run(input)
|
||||
{
|
||||
return Ok(out);
|
||||
}
|
||||
if !self.local_card.load(Ordering::Relaxed) {
|
||||
return self.cpu.run(input);
|
||||
}
|
||||
if let Ok(g) = self.card(false) {
|
||||
match g.runner.run(input) {
|
||||
Ok(out) if out.iter().all(|v| v.is_finite()) => return Ok(out),
|
||||
Ok(_) => self.fell_back("numbers that are not finite"),
|
||||
Err(e) => self.fell_back(&e.to_string()),
|
||||
}
|
||||
}
|
||||
self.cpu.run(input)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "denoise")]
|
||||
impl Model for Network {
|
||||
fn bytes_per_tile(&self) -> usize {
|
||||
self.cpu.bytes_per_tile()
|
||||
}
|
||||
fn runner(&self, run_on: RunOn, threads: usize) -> (&dyn TileRunner, usize) {
|
||||
let threads = threads.max(1);
|
||||
self.last_threads.store(threads, Ordering::Relaxed);
|
||||
let (card, local) = match self.choose(run_on, threads, true) {
|
||||
Ok(_) => (true, threads.min(GPU_PARALLEL)),
|
||||
Err(_) => (false, threads),
|
||||
};
|
||||
self.local_card.store(card, Ordering::Relaxed);
|
||||
if let Some(r) = &self.remote {
|
||||
// this computer's time for a tile: the card's, or the CPU's with `threads` tiles sharing it (as
|
||||
// `card_is_faster` counts them); unknown when the card was never set up (then the server is used)
|
||||
let local_ms = match self.gpu.get() {
|
||||
Some(Ok(g)) if card => g.card_ms,
|
||||
Some(Ok(g)) => g.cpu_ms / (1.0 + 0.5 * threads.saturating_sub(1) as f64),
|
||||
_ => f64::INFINITY,
|
||||
};
|
||||
let share = match (r.usable(true), r.tile_ms()) {
|
||||
(Ok(_), Some(ms)) if ms < local_ms => {
|
||||
*r.slower.lock().unwrap_or_else(PoisonError::into_inner) = None;
|
||||
true
|
||||
}
|
||||
(Ok(_), Some(ms)) => {
|
||||
*r.slower.lock().unwrap_or_else(PoisonError::into_inner) = Some((ms, local_ms));
|
||||
false
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
r.share.store(share, Ordering::Relaxed);
|
||||
if let (true, Ok(remote)) = (share, r.usable(false)) {
|
||||
// the server's slots come on top of this computer's own tiles at once
|
||||
return (self, local + remote.slots());
|
||||
}
|
||||
}
|
||||
if card { (self, local) } else { (&self.cpu, local) }
|
||||
}
|
||||
|
||||
fn self_test(&self, run_on: RunOn) -> Result<Value, String> {
|
||||
let t = self.cpu.self_test();
|
||||
if !t.ok {
|
||||
let failed: Vec<&str> = t.checks.iter().filter(|(_, ok)| !*ok).map(|(c, _)| c.as_str()).collect();
|
||||
return Err(format!("the model failed its self-test: it does not {}", failed.join(", and does not ")));
|
||||
}
|
||||
let mut v = serde_json::to_value(&t).map_err(|e| e.to_string())?;
|
||||
// the card is set up and checked here, so the test says where the work will run
|
||||
if run_on != RunOn::Cpu {
|
||||
let _ = self.card(true);
|
||||
}
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("device".into(), self.device(run_on));
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
fn device(&self, run_on: RunOn) -> Value {
|
||||
if run_on != RunOn::Cpu && self.gpu.get().is_none() {
|
||||
return json!({"kind": "pending"});
|
||||
}
|
||||
let threads = match self.last_threads.load(Ordering::Relaxed) {
|
||||
0 => Pace::Full.parallel(std::thread::available_parallelism().map_or(1, |n| n.get()), None),
|
||||
n => n,
|
||||
};
|
||||
let mut v = match self.choose(run_on, threads, false) {
|
||||
Ok(g) => json!({"kind": "gpu", "adapter": g.adapter}),
|
||||
// a set-up that crashed or ran out of time can be tried again (`denoise.settings {runOn}`)
|
||||
Err(why) => json!({"kind": "cpu", "retry": worth_retrying(&why), "reason": why}),
|
||||
};
|
||||
if let (Some(Ok(g)), Some(o)) = (self.gpu.get(), v.as_object_mut()) {
|
||||
// measured on this computer, on the check tile: the card's best run, and one tile alone on the CPU
|
||||
o.insert("cardMs".into(), json!(g.card_ms));
|
||||
o.insert("cpuMs".into(), json!(g.cpu_ms));
|
||||
o.insert("fellBack".into(), json!(self.fallbacks.load(Ordering::Relaxed)));
|
||||
}
|
||||
if let (Some(r), Some(o)) = (&self.remote, v.as_object_mut()) {
|
||||
o.insert("remote".into(), r.describe());
|
||||
}
|
||||
v
|
||||
}
|
||||
}
|
||||
|
||||
/// The loader of this build: our pure-Rust executor with the `denoise` feature, else one that says why nothing can run.
|
||||
pub(crate) fn default_loader() -> Loader {
|
||||
#[cfg(feature = "denoise")]
|
||||
{
|
||||
Arc::new(|path, manifest| {
|
||||
// the server must run this very file: identified by the manifest's hash, else the file's
|
||||
let sha256 = match &manifest.sha256 {
|
||||
Some(h) => Some(h.clone()),
|
||||
None if std::env::var_os("LIGHTCRAFT_DENOISE_URL").is_some() => lightcraft_denoise::hash::sha256_file(path).ok(),
|
||||
None => None,
|
||||
};
|
||||
let remote = sha256.and_then(|h| RemoteSide::from_env(&h, manifest.tile as usize));
|
||||
Ok(Arc::new(network(path, manifest, remote)?) as Arc<dyn Model>)
|
||||
})
|
||||
}
|
||||
#[cfg(not(feature = "denoise"))]
|
||||
{
|
||||
Arc::new(|_, _| Err("this build cannot run denoise models".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The model at `path` on this computer, sharing tiles with `remote` when there is one.
|
||||
#[cfg(feature = "denoise")]
|
||||
pub(super) fn network(path: &Path, manifest: &DenoiserManifest, remote: Option<RemoteSide>) -> Result<Network, String> {
|
||||
let cpu = lightcraft_denoise::runtime::CpuRunner::load(path, manifest).map_err(|e| e.to_string())?;
|
||||
Ok(Network {
|
||||
remote,
|
||||
local_card: AtomicBool::new(true),
|
||||
cpu,
|
||||
path: path.to_path_buf(),
|
||||
tile: manifest.tile as usize,
|
||||
gpu: OnceLock::new(),
|
||||
fallbacks: AtomicUsize::new(0),
|
||||
last_threads: AtomicUsize::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
/// A model ready to be served to other computers (`lightcraft-cli denoise-serve`).
|
||||
#[cfg(feature = "denoise")]
|
||||
pub struct Serving {
|
||||
pub model: lightcraft_denoise::remote::ModelId,
|
||||
pub tile: usize,
|
||||
/// Where its tiles run here: the graphics card's name, or why the CPU does.
|
||||
pub device: String,
|
||||
pub run: lightcraft_denoise::remote::RunTile,
|
||||
}
|
||||
|
||||
/// The installed model `id` (default: the one selected in Settings) in the models folder `dir` (default: this user's),
|
||||
/// set up to run on `run_on` as the app would: the card checked against the CPU first, the CPU when the card can't.
|
||||
#[cfg(feature = "denoise")]
|
||||
pub fn serving(dir: Option<&Path>, id: Option<&str>, run_on: RunOn) -> Result<Serving, String> {
|
||||
let dir = match dir {
|
||||
Some(d) => d.to_path_buf(),
|
||||
None => crate::config::default_denoise_models_dir().ok_or("no denoise models folder (set LIGHTCRAFT_DENOISE_MODELS)")?,
|
||||
};
|
||||
let want = match id {
|
||||
Some(i) => i.to_string(),
|
||||
None => read_settings(&dir).model.ok_or_else(|| {
|
||||
format!("no denoise model is selected in {} (install one in Settings ▸ AI Denoise, or name it with --model)", dir.display())
|
||||
})?,
|
||||
};
|
||||
let installed = installed_models(&dir)
|
||||
.into_iter()
|
||||
.find(|m| m.manifest.id == want)
|
||||
.ok_or_else(|| format!("no installed denoise model `{want}` in {}", dir.display()))?;
|
||||
let m = &installed.manifest;
|
||||
// the same identity a client derives (see `default_loader`)
|
||||
let sha256 = match &m.sha256 {
|
||||
Some(h) => h.clone(),
|
||||
None => lightcraft_denoise::hash::sha256_file(&installed.onnx).map_err(|e| format!("{}: {e}", installed.onnx.display()))?,
|
||||
};
|
||||
let net = Arc::new(network(&installed.onnx, m, None)?);
|
||||
let tile = m.tile as usize;
|
||||
// set the card up now (and say where the tiles run) rather than with the first client's tile
|
||||
let _ = net.runner(run_on, GPU_PARALLEL);
|
||||
let d = net.device(run_on);
|
||||
let device = match d["kind"].as_str() {
|
||||
Some("gpu") => format!("GPU: {}", d["adapter"].as_str().unwrap_or("?")),
|
||||
_ => format!("CPU ({})", d["reason"].as_str().unwrap_or("chosen")),
|
||||
};
|
||||
let run: lightcraft_denoise::remote::RunTile = Arc::new(move |input: &[f32]| net.runner(run_on, GPU_PARALLEL).0.run(input));
|
||||
Ok(Serving { model: lightcraft_denoise::remote::ModelId { id: m.id.clone(), version: m.version.clone(), sha256 }, tile, device, run })
|
||||
}
|
||||
|
||||
/// A model that is loaded on first use and kept, shared by the background job and the exports.
|
||||
pub(crate) type ModelSlot = Arc<Mutex<Option<Arc<dyn Model>>>>;
|
||||
@@ -0,0 +1,234 @@
|
||||
use super::model::{Loader, Model, ModelSlot, RunOn, STACK};
|
||||
use super::settings::EXT;
|
||||
use super::*;
|
||||
|
||||
/// Samples at or above this (white = 1) are clipped: the model leaves them as the camera recorded them.
|
||||
const CLIP: f32 = 0.99;
|
||||
|
||||
/// The model in use.
|
||||
pub(crate) struct Active {
|
||||
pub id: String,
|
||||
pub manifest: DenoiserManifest,
|
||||
pub onnx: PathBuf,
|
||||
pub fingerprint: String,
|
||||
pub model: ModelSlot,
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
// products
|
||||
|
||||
/// The photos whose files can be denoised at all: raw files developed from their sensor data and read from disk.
|
||||
pub(crate) fn eligible(p: &Photo) -> bool {
|
||||
p.develops_raw() && matches!(p.source, Source::File { .. }) && !p.deleted
|
||||
}
|
||||
|
||||
/// A product's name: what it was made from and with.
|
||||
pub(crate) fn product_key(fingerprint: &str, p: &Photo) -> String {
|
||||
let mut h = Hasher128::new();
|
||||
h.str("lcdn").u64(u64::from(product::ALGORITHM)).str(fingerprint).str(&crate::media::content_key(p));
|
||||
h.finish().to_string()
|
||||
}
|
||||
|
||||
pub(crate) fn product_path(dir: &Path, key: &str) -> PathBuf {
|
||||
dir.join(format!("{key}.{EXT}"))
|
||||
}
|
||||
|
||||
/// The `.lcdn` files in `dir`: path, size, last change.
|
||||
pub(super) fn products_in(dir: &Path) -> Vec<(PathBuf, u64, SystemTime)> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
entries
|
||||
.flatten()
|
||||
.filter(|e| e.path().extension().is_some_and(|x| x == EXT))
|
||||
.filter_map(|e| {
|
||||
let m = e.metadata().ok()?;
|
||||
m.is_file().then(|| (e.path(), m.len(), m.modified().unwrap_or(SystemTime::UNIX_EPOCH)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Make sure only one thread writes a product at a time: a second one waits, then finds it made.
|
||||
fn making() -> &'static (Mutex<HashSet<PathBuf>>, Condvar) {
|
||||
static MAKING: OnceLock<(Mutex<HashSet<PathBuf>>, Condvar)> = OnceLock::new();
|
||||
MAKING.get_or_init(|| (Mutex::new(HashSet::new()), Condvar::new()))
|
||||
}
|
||||
|
||||
struct Slot(PathBuf);
|
||||
|
||||
impl Slot {
|
||||
fn enter(path: &Path) -> Slot {
|
||||
let (set, cv) = making();
|
||||
let mut g = set.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
while g.contains(path) {
|
||||
g = cv.wait(g).unwrap_or_else(PoisonError::into_inner);
|
||||
}
|
||||
g.insert(path.to_path_buf());
|
||||
Slot(path.to_path_buf())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Slot {
|
||||
fn drop(&mut self) {
|
||||
let (set, cv) = making();
|
||||
set.lock().unwrap_or_else(PoisonError::into_inner).remove(&self.0);
|
||||
cv.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
// making a product
|
||||
|
||||
/// Everything a thread needs to make one product, detached from the session.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct JobSpec {
|
||||
/// The original file.
|
||||
pub path: String,
|
||||
pub read: Option<ByteReader>,
|
||||
pub product: PathBuf,
|
||||
pub key: String,
|
||||
pub manifest: DenoiserManifest,
|
||||
pub onnx: PathBuf,
|
||||
pub model: ModelSlot,
|
||||
pub loader: Loader,
|
||||
/// Tiles run at once.
|
||||
pub parallel: usize,
|
||||
/// Where the model runs (the setting).
|
||||
pub run_on: RunOn,
|
||||
}
|
||||
|
||||
/// Why a product was not made.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(crate) enum MakeError {
|
||||
/// Denoise does not apply to this file (not a Bayer raw): nothing is wrong.
|
||||
Unsupported(String),
|
||||
Failed(String),
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
impl From<RunError> for MakeError {
|
||||
fn from(e: RunError) -> Self {
|
||||
match e {
|
||||
RunError::Cancelled => MakeError::Cancelled,
|
||||
other => MakeError::Failed(other.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Progress and cancel of a running job.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Progress {
|
||||
pub(super) done: AtomicUsize,
|
||||
pub(super) total: AtomicUsize,
|
||||
cancel: AtomicBool,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
/// Ask the job to stop at the next tile.
|
||||
pub(crate) fn cancel_now(&self) {
|
||||
self.cancel.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// The loaded model, loading it first when it is not (kept for the next photo).
|
||||
pub(super) fn loaded(spec: &JobSpec) -> Result<Arc<dyn Model>, MakeError> {
|
||||
if let Some(m) = spec.model.lock().unwrap_or_else(PoisonError::into_inner).clone() {
|
||||
return Ok(m);
|
||||
}
|
||||
let m = (spec.loader)(&spec.onnx, &spec.manifest).map_err(|e| MakeError::Failed(format!("the denoise model could not be loaded: {e}")))?;
|
||||
*spec.model.lock().unwrap_or_else(PoisonError::into_inner) = Some(m.clone());
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// The cell `[(0,0), (1,0), (0,1), (1,1)]` colours of a Bayer mosaic and so its layout.
|
||||
fn layout_of(cfa: &lightcraft_raw::Cfa) -> Option<Layout> {
|
||||
Layout::from_cell([cfa.color_at(0, 0), cfa.color_at(1, 0), cfa.color_at(0, 1), cfa.color_at(1, 1)])
|
||||
}
|
||||
|
||||
/// Make the product of `spec` unless it is there: decode the photo, run the model over its mosaic, write the result.
|
||||
/// `Ok(true)` when it was made now, `Ok(false)` when it already existed.
|
||||
pub(crate) fn make_product(spec: &JobSpec, progress: Option<&Progress>) -> Result<bool, MakeError> {
|
||||
let _slot = Slot::enter(&spec.product);
|
||||
if product::is_current(&spec.product, &spec.key) {
|
||||
return Ok(false);
|
||||
}
|
||||
let began = web_time::Instant::now();
|
||||
let cancelled = || progress.is_some_and(|p| p.cancel.load(Ordering::Relaxed));
|
||||
if cancelled() {
|
||||
return Err(MakeError::Cancelled);
|
||||
}
|
||||
let bytes = match &spec.read {
|
||||
Some(r) => r(&spec.path).map_err(MakeError::Failed)?,
|
||||
None => std::fs::read(&spec.path).map_err(|e| MakeError::Failed(format!("{}: {e}", spec.path)))?,
|
||||
};
|
||||
// the decode and the normalised mosaic wait their turn at the process-wide memory gate, as every decode does
|
||||
let (mosaic, layout) = {
|
||||
let _held = crate::memory::work_gate().acquire(bytes.len().saturating_mul(4));
|
||||
if lightcraft_raw::probe(&bytes).is_none() {
|
||||
return Err(MakeError::Unsupported("not a raw file".into()));
|
||||
}
|
||||
let raw = match lightcraft_raw::decode(&bytes) {
|
||||
Ok(r) => r,
|
||||
Err(lightcraft_raw::RawError::Unsupported(why)) => return Err(MakeError::Unsupported(why)),
|
||||
Err(e) => return Err(MakeError::Failed(e.to_string())),
|
||||
};
|
||||
drop(bytes);
|
||||
if raw.cpp != 1 || !raw.cfa.as_ref().is_some_and(lightcraft_raw::Cfa::is_bayer) {
|
||||
return Err(MakeError::Unsupported(
|
||||
"only Bayer raw files can be denoised (this one has another sensor layout or is already demosaiced)".into(),
|
||||
));
|
||||
}
|
||||
let n = raw.normalized().map_err(|e| MakeError::Failed(e.to_string()))?;
|
||||
drop(raw);
|
||||
let layout =
|
||||
n.cfa.as_ref().and_then(layout_of).ok_or_else(|| MakeError::Unsupported("the colour filter layout is not a Bayer pattern".into()))?;
|
||||
(n, layout)
|
||||
};
|
||||
if cancelled() {
|
||||
return Err(MakeError::Cancelled);
|
||||
}
|
||||
let decoded = began.elapsed();
|
||||
let model = loaded(spec)?;
|
||||
// Packed input, returned RGB and the preceding group's RGB overlap while tiles run.
|
||||
let scratch =
|
||||
model.bytes_per_tile().saturating_add(128usize.saturating_mul(spec.manifest.tile as usize).saturating_mul(spec.manifest.tile as usize));
|
||||
let (_, budget) = crate::memory::work_gate().usage();
|
||||
let parallel = spec.parallel.clamp(1, 4).min((budget / scratch.max(1)).max(1));
|
||||
let _held = crate::memory::work_gate().acquire(mosaic.data.len().saturating_mul(20).saturating_add(scratch.saturating_mul(parallel)));
|
||||
let (runner, parallel) = model.runner(spec.run_on, parallel);
|
||||
let params = Params {
|
||||
tile: spec.manifest.tile as usize,
|
||||
overlap: spec.manifest.overlap as usize,
|
||||
gain: spec.manifest.gain,
|
||||
clip: Some(CLIP),
|
||||
parallel: parallel.max(1),
|
||||
};
|
||||
let report = |done: usize, total: usize| {
|
||||
if let Some(p) = progress {
|
||||
p.total.store(total, Ordering::Relaxed);
|
||||
p.done.store(done, Ordering::Relaxed);
|
||||
}
|
||||
};
|
||||
let ctl = Control { cancel: progress.map(|p| &p.cancel), progress: Some(&report) };
|
||||
// the tiles run on threads of their own, so a busy window's renders keep theirs
|
||||
let pool = rayon::ThreadPoolBuilder::new()
|
||||
.num_threads(params.parallel)
|
||||
.stack_size(STACK)
|
||||
.thread_name(|i| format!("denoise-{i}"))
|
||||
.build()
|
||||
.map_err(|e| MakeError::Failed(format!("could not start the worker threads: {e}")))?;
|
||||
let rgb = pool.install(|| denoise_bayer(&mosaic.data, mosaic.width, mosaic.height, layout, runner, ¶ms, &ctl))?;
|
||||
drop(mosaic);
|
||||
if cancelled() {
|
||||
return Err(MakeError::Cancelled);
|
||||
}
|
||||
let ran = began.elapsed();
|
||||
product::write(&spec.product, &rgb, &spec.key).map_err(|e| MakeError::Failed(format!("could not save the denoised picture: {e}")))?;
|
||||
if std::env::var_os("LIGHTCRAFT_PROFILE").is_some() {
|
||||
eprintln!(
|
||||
"[denoise] read + decode {:.0} ms, model (set-up, tiles, blend) {:.0} ms, write {:.0} ms",
|
||||
decoded.as_secs_f64() * 1e3,
|
||||
(ran - decoded).as_secs_f64() * 1e3,
|
||||
(began.elapsed() - ran).as_secs_f64() * 1e3
|
||||
);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
#[cfg(doc)]
|
||||
use super::model::Model;
|
||||
use super::model::STACK;
|
||||
use super::products::{Active, JobSpec, MakeError, Progress, eligible, make_product, product_key, product_path, products_in};
|
||||
use super::settings::{DIR, SETTINGS_TTL, installed_models, read_settings};
|
||||
use super::state::{AUTO_LOOK, Failure, MAX_QUEUE, Outcome, Pace, PhotoState, Running};
|
||||
use super::*;
|
||||
|
||||
impl Session {
|
||||
/// Where the active model's tiles run (see [`Model::device`]); `{kind: "none"}` while no model is loaded.
|
||||
pub(crate) fn denoise_device(&self) -> Value {
|
||||
let loaded = self.denoise.active.as_ref().and_then(|a| a.model.lock().unwrap_or_else(PoisonError::into_inner).clone());
|
||||
match loaded {
|
||||
Some(m) => m.device(self.denoise.settings.run_on()),
|
||||
None => json!({"kind": "none"}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder the products of the open library are kept in; `None` without a library on disk.
|
||||
pub(crate) fn denoise_products_dir(&self) -> Option<PathBuf> {
|
||||
self.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.join(DIR))
|
||||
}
|
||||
|
||||
/// Read which model is in use (at most every couple of seconds): the manifest and file of the model the settings
|
||||
/// name, if it is installed.
|
||||
pub(crate) fn denoise_refresh_active(&mut self, force: bool) {
|
||||
let fresh = self.denoise.active_seen.is_some_and(|t| t.elapsed() < SETTINGS_TTL);
|
||||
if fresh && !force {
|
||||
return;
|
||||
}
|
||||
self.denoise.active_seen = Some(web_time::Instant::now());
|
||||
self.denoise.settings = self.denoise.models_dir.as_deref().map(read_settings).unwrap_or_default();
|
||||
let chosen = self.denoise.models_dir.as_deref().and_then(|dir| {
|
||||
let id = self.denoise.settings.model.clone()?;
|
||||
installed_models(dir).into_iter().find(|i| i.manifest.id == id)
|
||||
});
|
||||
let found = chosen.map(|i| (i.fingerprint(), i));
|
||||
let same = match (&self.denoise.active, &found) {
|
||||
(None, None) => true,
|
||||
(Some(a), Some((fp, _))) => a.fingerprint == *fp,
|
||||
_ => false,
|
||||
};
|
||||
if same {
|
||||
return;
|
||||
}
|
||||
// another model: what was made with the old one is not this one's, and what failed may work now
|
||||
self.denoise.active = found.map(|(fingerprint, i)| Active {
|
||||
id: i.manifest.id.clone(),
|
||||
manifest: i.manifest,
|
||||
onnx: i.onnx,
|
||||
fingerprint,
|
||||
model: Arc::new(Mutex::new(None)),
|
||||
});
|
||||
if let Some(r) = self.denoise.running.take() {
|
||||
r.progress.cancel_now();
|
||||
}
|
||||
self.denoise.queue.clear();
|
||||
self.denoise.failed.clear();
|
||||
self.denoise.dirty = true;
|
||||
}
|
||||
|
||||
fn denoise_spec(&self, p: &Photo) -> Option<(DenoiseSpec, String)> {
|
||||
let (dir, active) = (self.denoise_products_dir()?, self.denoise.active.as_ref()?);
|
||||
let key = product_key(&active.fingerprint, p);
|
||||
Some((DenoiseSpec { product: product_path(&dir, &key), key: key.clone(), make: None }, key))
|
||||
}
|
||||
|
||||
/// Make the index of ready photos from the products on disk (a directory listing and a hash per photo: no file is
|
||||
/// opened). Pictures that appeared or vanished drop the decoded sources they affect. The photo being made is its
|
||||
/// job's to report (see [`Self::denoise_check_photo`]).
|
||||
pub(crate) fn denoise_reindex(&mut self) {
|
||||
self.denoise.dirty = false;
|
||||
self.denoise.reindexed = Some((self.catalog.revision, web_time::Instant::now()));
|
||||
let running = self.denoise.running.as_ref().map(|r| r.photo);
|
||||
let mut now: HashMap<PhotoId, DenoiseSpec> = HashMap::new();
|
||||
if let (Some(dir), Some(active)) = (self.denoise_products_dir(), self.denoise.active.as_ref()) {
|
||||
let names: HashSet<String> =
|
||||
products_in(&dir).into_iter().filter_map(|(p, _, _)| p.file_stem().and_then(|s| s.to_str()).map(str::to_string)).collect();
|
||||
if !names.is_empty() {
|
||||
for p in self.catalog.photos().filter(|p| eligible(p) && running != Some(p.id)) {
|
||||
let key = product_key(&active.fingerprint, p);
|
||||
if names.contains(&key) {
|
||||
now.insert(p.id, DenoiseSpec { product: product_path(&dir, &key), key, make: None });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut changed = false;
|
||||
for id in self.media.denoise.ids() {
|
||||
if !now.contains_key(&id) {
|
||||
self.media.denoise.remove(id);
|
||||
self.media.forget(id);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (id, spec) in now {
|
||||
if self.media.denoise.spec(id).is_none_or(|old| old.key != spec.key) {
|
||||
self.media.denoise.set(id, spec);
|
||||
self.media.forget(id);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.denoise.generation += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// A photo whose file changed (its content key is not the one its index entry was made for) has no picture.
|
||||
///
|
||||
/// The photo whose picture is being made is left to its job: the worker saves the picture before it reports, so the
|
||||
/// file is on disk while the job still counts as running. Finding it here would make the photo Ready while the session
|
||||
/// is busy with it (#719); [`Self::denoise_poll`] makes it Ready in the pump that takes the job's result instead.
|
||||
fn denoise_check_photo(&mut self, id: PhotoId) {
|
||||
if self.denoise.running.as_ref().is_some_and(|r| r.photo == id) {
|
||||
return;
|
||||
}
|
||||
let Some(p) = self.catalog.photo(id).cloned() else { return };
|
||||
let Some((spec, _)) = self.denoise_spec(&p) else { return };
|
||||
match self.media.denoise.spec(id) {
|
||||
Some(have) if have.key != spec.key => {
|
||||
self.media.denoise.remove(id);
|
||||
self.media.forget(id);
|
||||
self.denoise.generation += 1;
|
||||
}
|
||||
None if spec.product.is_file() && product::is_current(&spec.product, &spec.key) => {
|
||||
// made by an export, or by another session
|
||||
self.media.denoise.set(id, spec);
|
||||
self.media.forget(id);
|
||||
self.denoise.generation += 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// How photo `id` stands.
|
||||
pub fn denoise_photo_state(&self, id: PhotoId) -> PhotoState {
|
||||
let Some(p) = self.catalog.photo(id) else { return PhotoState::NotApplicable };
|
||||
if !eligible(p) {
|
||||
return PhotoState::NotApplicable;
|
||||
}
|
||||
if self.denoise.active.is_none() {
|
||||
// the model folder has not been looked at yet (just started): not "no model" until it has been
|
||||
return if self.denoise.active_seen.is_none() { PhotoState::Idle } else { PhotoState::NoModel };
|
||||
}
|
||||
if self.denoise_products_dir().is_none() {
|
||||
return PhotoState::Failed {
|
||||
why: "AI Denoise keeps its pictures in the library folder, and this session has none.".into(),
|
||||
unsupported: true,
|
||||
};
|
||||
}
|
||||
if self.media.denoise.spec(id).is_some() {
|
||||
return PhotoState::Ready;
|
||||
}
|
||||
if let Some(r) = self.denoise.running.as_ref().filter(|r| r.photo == id) {
|
||||
return PhotoState::Running { done: r.progress.done.load(Ordering::Relaxed), total: r.progress.total.load(Ordering::Relaxed) };
|
||||
}
|
||||
if let Some(ahead) = self.denoise.queue.iter().position(|q| *q == id) {
|
||||
return PhotoState::Queued { ahead: ahead + usize::from(self.denoise.running.is_some()) };
|
||||
}
|
||||
let key = self.denoise_spec(p).map(|s| s.1);
|
||||
match self.denoise.failed.get(&id) {
|
||||
Some(f) if Some(&f.key) == key.as_ref() => PhotoState::Failed { why: f.why.clone(), unsupported: f.unsupported },
|
||||
_ => PhotoState::Idle,
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask for photos' pictures to be made (the ones that are not made, queued or known to be impossible). With `retry`
|
||||
/// a photo that failed before is tried again. A photo that is not raw is skipped. Returns how many were queued.
|
||||
pub(crate) fn denoise_enqueue(&mut self, ids: &[PhotoId], front: bool, retry: bool) -> usize {
|
||||
self.denoise_refresh_active(false);
|
||||
if self.denoise.active.is_none() || self.denoise_products_dir().is_none() {
|
||||
return 0;
|
||||
}
|
||||
let mut added = 0;
|
||||
for id in ids {
|
||||
let Some(p) = self.catalog.photo(*id).cloned() else { continue };
|
||||
if !eligible(&p) || self.media.denoise.spec(*id).is_some() || self.denoise.queue.contains(id) {
|
||||
continue;
|
||||
}
|
||||
if self.denoise.running.as_ref().is_some_and(|r| r.photo == *id) || self.denoise.queue.len() >= MAX_QUEUE {
|
||||
continue;
|
||||
}
|
||||
let Some((_, key)) = self.denoise_spec(&p) else { continue };
|
||||
if retry {
|
||||
self.denoise.failed.remove(id);
|
||||
} else if self.denoise.failed.get(id).is_some_and(|f| f.key == key) {
|
||||
continue;
|
||||
}
|
||||
if front {
|
||||
self.denoise.queue.push_front(*id);
|
||||
} else {
|
||||
self.denoise.queue.push_back(*id);
|
||||
}
|
||||
added += 1;
|
||||
}
|
||||
added
|
||||
}
|
||||
|
||||
/// Stop the job that is running, and with `all` forget everything that waits.
|
||||
pub(crate) fn denoise_cancel(&mut self, photo: Option<PhotoId>, all: bool) -> usize {
|
||||
let mut n = 0;
|
||||
if let Some(r) = &self.denoise.running
|
||||
&& photo.is_none_or(|p| p == r.photo)
|
||||
{
|
||||
r.progress.cancel_now();
|
||||
n += 1;
|
||||
}
|
||||
let before = self.denoise.queue.len();
|
||||
match photo {
|
||||
Some(p) => self.denoise.queue.retain(|q| *q != p),
|
||||
None if all => self.denoise.queue.clear(),
|
||||
None => {}
|
||||
}
|
||||
n + before - self.denoise.queue.len()
|
||||
}
|
||||
|
||||
/// The photos the automatic queue looks at: the one open and the ones selected, those with a Denoise amount.
|
||||
fn denoise_wanted(&self) -> Vec<PhotoId> {
|
||||
let Selection { active, ids, .. } = &self.selection;
|
||||
active
|
||||
.iter()
|
||||
.chain(ids.iter().take(AUTO_LOOK))
|
||||
.copied()
|
||||
.filter(|id| self.catalog.photo(*id).is_some_and(|p| p.develop.denoise_amount() > 0.0))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn denoise_job_spec(&self, p: &Photo, parallel: usize) -> Option<JobSpec> {
|
||||
let Source::File { path } = &p.source else { return None };
|
||||
let (spec, _) = self.denoise_spec(p)?;
|
||||
let active = self.denoise.active.as_ref()?;
|
||||
Some(JobSpec {
|
||||
path: path.clone(),
|
||||
read: self.media.file_bytes.clone(),
|
||||
product: spec.product,
|
||||
key: spec.key,
|
||||
manifest: active.manifest.clone(),
|
||||
onnx: active.onnx.clone(),
|
||||
model: active.model.clone(),
|
||||
loader: self.denoise.loader.clone(),
|
||||
parallel,
|
||||
run_on: self.denoise.settings.run_on(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Start the next queued photo on its own thread.
|
||||
fn denoise_start_next(&mut self, parallel: usize) {
|
||||
while let Some(id) = self.denoise.queue.pop_front() {
|
||||
let Some(p) = self.catalog.photo(id).cloned() else { continue };
|
||||
if !eligible(&p) || self.media.denoise.spec(id).is_some() {
|
||||
continue;
|
||||
}
|
||||
let Some(spec) = self.denoise_job_spec(&p, parallel) else { continue };
|
||||
// another session or an export may have made it since it was queued
|
||||
if product::is_current(&spec.product, &spec.key) {
|
||||
self.denoise_check_photo(id);
|
||||
continue;
|
||||
}
|
||||
let progress = Arc::new(Progress::default());
|
||||
let outcome: Arc<Mutex<Option<Outcome>>> = Arc::new(Mutex::new(None));
|
||||
let (key, product) = (spec.key.clone(), spec.product.clone());
|
||||
let (worker_progress, worker_outcome) = (progress.clone(), outcome.clone());
|
||||
let started = std::thread::Builder::new().name("denoise".into()).stack_size(STACK).spawn(move || {
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| make_product(&spec, Some(&worker_progress))));
|
||||
let o = match result {
|
||||
Ok(Ok(_)) => Outcome::Done,
|
||||
Ok(Err(MakeError::Cancelled)) => Outcome::Cancelled,
|
||||
Ok(Err(MakeError::Unsupported(why))) => Outcome::Failed(why, true),
|
||||
Ok(Err(MakeError::Failed(why))) => Outcome::Failed(why, false),
|
||||
Err(_) => Outcome::Failed("the denoiser stopped unexpectedly".into(), false),
|
||||
};
|
||||
*worker_outcome.lock().unwrap_or_else(PoisonError::into_inner) = Some(o);
|
||||
});
|
||||
match started {
|
||||
Ok(_) => {
|
||||
self.denoise.running = Some(Running { photo: id, key, product, progress, outcome, started: web_time::Instant::now() });
|
||||
}
|
||||
Err(e) => {
|
||||
self.denoise.failed.insert(id, Failure { key, why: format!("could not start the denoiser: {e}"), unsupported: false });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// Take in the running job's result.
|
||||
fn denoise_poll(&mut self) {
|
||||
let Some(r) = &self.denoise.running else { return };
|
||||
let Some(outcome) = r.outcome.lock().unwrap_or_else(PoisonError::into_inner).take() else { return };
|
||||
let Some(r) = self.denoise.running.take() else { return };
|
||||
match outcome {
|
||||
Outcome::Done => {
|
||||
self.denoise.made += 1;
|
||||
self.denoise_check_photo(r.photo);
|
||||
self.denoise_evict(Some(&r.product));
|
||||
}
|
||||
Outcome::Failed(why, unsupported) => {
|
||||
self.denoise.failed.insert(r.photo, Failure { key: r.key, why, unsupported });
|
||||
}
|
||||
Outcome::Cancelled => {}
|
||||
}
|
||||
// the picture's state changed: the interface draws it again
|
||||
self.denoise.generation += 1;
|
||||
}
|
||||
|
||||
/// Keep the cache within its limit: the pictures nobody asks for go first, the oldest first; `keep` (the one just
|
||||
/// made) never goes. The index forgets what was deleted.
|
||||
pub(crate) fn denoise_evict(&mut self, keep: Option<&Path>) {
|
||||
let Some(models) = self.denoise.models_dir.clone() else { return };
|
||||
self.denoise_evict_to(read_settings(&models).cache_bytes(), keep);
|
||||
}
|
||||
|
||||
/// [`Self::denoise_evict`] for a limit of `limit` bytes.
|
||||
pub(crate) fn denoise_evict_to(&mut self, limit: u64, keep: Option<&Path>) {
|
||||
let Some(dir) = self.denoise_products_dir() else { return };
|
||||
let mut files = products_in(&dir);
|
||||
let mut total: u64 = files.iter().map(|f| f.1).sum();
|
||||
if total <= limit {
|
||||
return;
|
||||
}
|
||||
// the pictures photos use now (a Denoise amount above 0) are the last to go
|
||||
let wanted: HashSet<PathBuf> = self
|
||||
.media
|
||||
.denoise
|
||||
.ids()
|
||||
.into_iter()
|
||||
.filter(|id| self.catalog.photo(*id).is_some_and(|p| p.develop.denoise_amount() > 0.0))
|
||||
.filter_map(|id| self.media.denoise.spec(id).map(|s| s.product.clone()))
|
||||
.collect();
|
||||
files.sort_by_key(|(path, _, modified)| (wanted.contains(path), *modified));
|
||||
let mut gone: HashSet<PathBuf> = HashSet::new();
|
||||
for (path, size, _) in files {
|
||||
if total <= limit {
|
||||
break;
|
||||
}
|
||||
if keep == Some(path.as_path()) {
|
||||
continue;
|
||||
}
|
||||
if std::fs::remove_file(&path).is_ok() {
|
||||
total = total.saturating_sub(size);
|
||||
gone.insert(path);
|
||||
}
|
||||
}
|
||||
if gone.is_empty() {
|
||||
return;
|
||||
}
|
||||
for id in self.media.denoise.ids() {
|
||||
if self.media.denoise.spec(id).is_some_and(|s| gone.contains(&s.product)) {
|
||||
self.media.denoise.remove(id);
|
||||
self.media.forget(id);
|
||||
}
|
||||
}
|
||||
self.denoise.generation += 1;
|
||||
}
|
||||
|
||||
/// Delete every product of this library (they are made again when wanted).
|
||||
pub(crate) fn denoise_clear(&mut self) -> (usize, u64) {
|
||||
self.denoise_cancel(None, true);
|
||||
let (mut files, mut bytes) = (0, 0);
|
||||
if let Some(dir) = self.denoise_products_dir() {
|
||||
for (path, size, _) in products_in(&dir) {
|
||||
if std::fs::remove_file(&path).is_ok() {
|
||||
files += 1;
|
||||
bytes += size;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.denoise.failed.clear();
|
||||
self.denoise.touch();
|
||||
(files, bytes)
|
||||
}
|
||||
|
||||
/// Per frame: take in what finished, look at what the user is looking at, and keep one job going. Cheap when
|
||||
/// nothing is happening (no file is opened unless a photo with a Denoise amount lacks its picture).
|
||||
pub(crate) fn denoise_pump(&mut self, pace: Pace) {
|
||||
crate::cmd::denoise::finish_downloads(self);
|
||||
self.denoise_refresh_active(false);
|
||||
// photos that changed (a replaced file has another key) must not keep the picture of what they were
|
||||
let stale = !self.media.denoise.is_empty()
|
||||
&& self.denoise.reindexed.is_none_or(|(rev, at)| rev != self.catalog.revision && at.elapsed() > SETTINGS_TTL);
|
||||
if self.denoise.dirty || stale {
|
||||
self.denoise_reindex();
|
||||
}
|
||||
self.denoise_poll();
|
||||
if self.denoise.active.is_none() || self.denoise_products_dir().is_none() {
|
||||
return;
|
||||
}
|
||||
let (cap, auto) = (self.denoise.settings.threads, self.denoise.settings.auto());
|
||||
let wanted = self.denoise_wanted();
|
||||
for id in &wanted {
|
||||
self.denoise_check_photo(*id);
|
||||
}
|
||||
if auto {
|
||||
// the photo being edited goes first
|
||||
let (open, others): (Vec<PhotoId>, Vec<PhotoId>) = wanted.into_iter().partition(|id| self.selection.active == Some(*id));
|
||||
self.denoise_enqueue(&others, false, false);
|
||||
self.denoise_enqueue(&open, true, false);
|
||||
}
|
||||
if self.denoise.running.is_none() && pace != Pace::Pause {
|
||||
let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
|
||||
self.denoise_start_next(pace.parallel(cores, cap));
|
||||
}
|
||||
}
|
||||
|
||||
/// The statistics `denoise.status` reports besides the queue (reads the cache folder).
|
||||
pub(crate) fn denoise_cache_usage(&self) -> (usize, u64) {
|
||||
match self.denoise_products_dir() {
|
||||
Some(dir) => {
|
||||
let files = products_in(&dir);
|
||||
(files.len(), files.iter().map(|f| f.1).sum())
|
||||
}
|
||||
None => (0, 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Are pictures made without being asked for photos being looked at (Settings ▸ AI Denoise)?
|
||||
pub fn denoise_auto(&self) -> bool {
|
||||
self.denoise.settings.auto()
|
||||
}
|
||||
|
||||
/// Is a picture being made, or waiting for its turn with a model to make it? (Headless runs wait for this.)
|
||||
pub fn denoise_busy(&self) -> bool {
|
||||
self.denoise.running.is_some() || (!self.denoise.queue.is_empty() && self.denoise.active.is_some())
|
||||
}
|
||||
|
||||
/// Keep AI Denoise's row in the activity stack up to date (each `denoise.pump`): there while a photo is being made or
|
||||
/// waits its turn, with the running photo's tiles and its file name; gone when the queue is idle. It has no ✕: what is
|
||||
/// made follows the photos' Denoise amounts and Settings ▸ AI Denoise.
|
||||
pub(crate) fn denoise_track(&mut self) {
|
||||
if !self.denoise_busy() {
|
||||
self.denoise.task = None;
|
||||
return;
|
||||
}
|
||||
let task = self.denoise.task.get_or_insert_with(|| {
|
||||
let t = self.activity.start("denoise", "AI Denoise", crate::activity::Cancel::No);
|
||||
t.set_unit(crate::activity::Unit::Percent);
|
||||
t
|
||||
});
|
||||
match &self.denoise.running {
|
||||
Some(r) => {
|
||||
task.progress(r.progress.done.load(Ordering::Relaxed) as u64, r.progress.total.load(Ordering::Relaxed) as u64);
|
||||
task.detail(self.catalog.photo(r.photo).map_or("", |p| p.file_name.as_str()));
|
||||
}
|
||||
None => {
|
||||
task.progress(0, 0);
|
||||
task.detail("");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds the running job has been going, and its progress.
|
||||
pub(crate) fn denoise_running_json(&self) -> Value {
|
||||
match &self.denoise.running {
|
||||
Some(r) => json!({
|
||||
"photo": r.photo.0,
|
||||
"done": r.progress.done.load(Ordering::Relaxed),
|
||||
"total": r.progress.total.load(Ordering::Relaxed),
|
||||
"seconds": r.started.elapsed().as_secs_f64(),
|
||||
}),
|
||||
None => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn denoise_made(&self) -> u64 {
|
||||
self.denoise.made
|
||||
}
|
||||
|
||||
/// The running job's product path and key (tests stand in for the worker's save).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn denoise_running_product(&self) -> Option<(PathBuf, String)> {
|
||||
self.denoise.running.as_ref().map(|r| (r.product.clone(), r.key.clone()))
|
||||
}
|
||||
|
||||
/// What an export of photo `id` with `settings` needs for its Denoise amount: its denoised picture, made now when the
|
||||
/// queue has not got to it. `Ok(None)` when denoise does not apply (amount 0, not a Bayer raw), `Err` when it should
|
||||
/// have and cannot (no model chosen, nowhere to keep the picture, the model failing).
|
||||
pub(crate) fn denoise_for_export(&mut self, id: PhotoId, settings: &DevelopSettings) -> Result<Option<(DenoiseSpec, PairLoader)>, String> {
|
||||
if settings.denoise_amount() <= 0.0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(p) = self.catalog.photo(id).cloned() else { return Ok(None) };
|
||||
let Some(loader) = self.media.denoise.loader.clone() else { return Ok(None) };
|
||||
if !eligible(&p) {
|
||||
return Ok(None);
|
||||
}
|
||||
self.denoise_refresh_active(false);
|
||||
let name = &p.file_name;
|
||||
if self.denoise.active.is_none() {
|
||||
return Err(format!("{name}: Denoise is on for this photo but no denoise model is chosen; choose one in Settings, or set Denoise to 0"));
|
||||
}
|
||||
if self.denoise_products_dir().is_none() {
|
||||
return Err(format!("{name}: Denoise needs a library on disk to keep its pictures in"));
|
||||
}
|
||||
self.denoise_check_photo(id);
|
||||
let Some(job) = self.denoise_job_spec(&p, Pace::Full.parallel(std::thread::available_parallelism().map_or(1, |n| n.get()), None)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let label = name.clone();
|
||||
let spec = job.clone();
|
||||
let make: MakeProduct = Arc::new(move || match make_product(&spec, None) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(MakeError::Unsupported(_)) => Ok(false),
|
||||
Err(MakeError::Failed(why)) => Err(format!("{label}: could not denoise: {why}")),
|
||||
Err(MakeError::Cancelled) => Err(format!("{label}: denoise was cancelled")),
|
||||
});
|
||||
Ok(Some((DenoiseSpec { product: job.product, key: job.key, make: Some(make) }, loader)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
use super::gpu::GPU_SETUP_MARKER;
|
||||
use super::model::RunOn;
|
||||
use super::*;
|
||||
|
||||
/// Extension of a product file.
|
||||
pub const EXT: &str = "lcdn";
|
||||
|
||||
/// Where the products of a library are kept, inside the library's folder (safe to delete, like `thumbs/`).
|
||||
pub const DIR: &str = "denoise";
|
||||
|
||||
/// What the cache may take up unless the user says otherwise (GB). A product is about as large as the raw file's
|
||||
/// decoded samples, compressed: ~100 MB for 24 megapixels.
|
||||
pub const DEFAULT_CACHE_GB: u32 = 20;
|
||||
|
||||
/// How long a look at the model settings is trusted.
|
||||
pub(super) const SETTINGS_TTL: Duration = Duration::from_secs(2);
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
// settings and installed models
|
||||
|
||||
/// `settings.json` in the models folder.
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub(crate) struct Settings {
|
||||
/// The installed model in use; `None`: denoise is off.
|
||||
pub model: Option<String>,
|
||||
/// Photos with a Denoise amount above 0 that are being looked at (active, selected) get their picture made without
|
||||
/// being asked (`None`: yes).
|
||||
pub auto: Option<bool>,
|
||||
/// Cache size limit (GB; `None`: [`DEFAULT_CACHE_GB`]).
|
||||
pub cache_gb: Option<u32>,
|
||||
/// Most tiles run at once (`None`: by how hard the pump says to work).
|
||||
pub threads: Option<u32>,
|
||||
/// Where the model runs: `auto`, `gpu` or `cpu` (`None` or anything else: `auto`; see [`RunOn`]).
|
||||
pub run_on: Option<String>,
|
||||
/// What came before `runOn`: `false` was the processor only.
|
||||
pub gpu: Option<bool>,
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
pub fn auto(&self) -> bool {
|
||||
self.auto.unwrap_or(true)
|
||||
}
|
||||
|
||||
pub fn run_on(&self) -> RunOn {
|
||||
match self.run_on.as_deref().and_then(RunOn::parse) {
|
||||
Some(r) => r,
|
||||
None if self.gpu == Some(false) => RunOn::Cpu,
|
||||
None => RunOn::Auto,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cache_bytes(&self) -> u64 {
|
||||
u64::from(self.cache_gb.unwrap_or(DEFAULT_CACHE_GB).clamp(1, 10_000)) << 30
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn read_capped(path: &Path, max: usize) -> Option<Vec<u8>> {
|
||||
use std::io::Read;
|
||||
let mut buf = Vec::new();
|
||||
std::fs::File::open(path).ok()?.take(max as u64 + 1).read_to_end(&mut buf).ok()?;
|
||||
(buf.len() <= max).then_some(buf)
|
||||
}
|
||||
|
||||
pub(crate) fn read_settings(dir: &Path) -> Settings {
|
||||
read_capped(&dir.join("settings.json"), 4096).and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Write a file next to its final name and rename it into place.
|
||||
pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
|
||||
let part = path.with_extension("part");
|
||||
std::fs::write(&part, bytes).map_err(|e| format!("could not write {}: {e}", path.display()))?;
|
||||
std::fs::rename(&part, path).map_err(|e| {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
format!("could not write {}: {e}", path.display())
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn write_settings(dir: &Path, st: &Settings) -> Result<(), String> {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("could not create the denoise models folder: {e}"))?;
|
||||
write_atomic(&dir.join("settings.json"), &serde_json::to_vec_pretty(st).map_err(|e| e.to_string())?)
|
||||
}
|
||||
|
||||
/// An installed model folder: `<id>/model.onnx`, `denoise-model.json`, `installed.json`.
|
||||
pub(crate) struct Installed {
|
||||
pub manifest: DenoiserManifest,
|
||||
pub onnx: PathBuf,
|
||||
/// What was recorded when it was installed (terms accepted, hash of the file, self-test).
|
||||
pub accepted: Value,
|
||||
}
|
||||
|
||||
impl Installed {
|
||||
/// Names the model file the cache is made with: a hash of the file as installed, so another file with the same id
|
||||
/// never finds this one's products.
|
||||
pub fn fingerprint(&self) -> String {
|
||||
let sha = self.accepted.get("sha256").and_then(Value::as_str).or(self.manifest.sha256.as_deref()).unwrap_or("");
|
||||
let len = std::fs::metadata(&self.onnx).map(|m| m.len()).unwrap_or(0);
|
||||
format!("{}@{}:{len}", self.manifest.id, sha)
|
||||
}
|
||||
}
|
||||
|
||||
/// The models in the folder. A folder that is not a valid model (wrong name, no model file, a manifest that does not
|
||||
/// validate or does not match its folder) is ignored, never trusted.
|
||||
pub(crate) fn installed_models(dir: &Path) -> Vec<Installed> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
let Some(name) = p.file_name().and_then(|n| n.to_str()).map(str::to_string) else { continue };
|
||||
let onnx = p.join("model.onnx");
|
||||
if !lightcraft_denoise::licence::valid_id(&name) || !p.is_dir() || !onnx.is_file() {
|
||||
continue;
|
||||
}
|
||||
let Some(m) = read_capped(&p.join("denoise-model.json"), lightcraft_denoise::manifest::MAX_MANIFEST_BYTES)
|
||||
.and_then(|b| lightcraft_denoise::manifest::parse(&b).ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if m.id != name {
|
||||
continue;
|
||||
}
|
||||
let accepted = read_capped(&p.join("installed.json"), 8192).and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or(Value::Null);
|
||||
out.push(Installed { manifest: m, onnx, accepted });
|
||||
}
|
||||
out.sort_by(|a, b| a.manifest.id.cmp(&b.manifest.id));
|
||||
out
|
||||
}
|
||||
|
||||
/// Forget that setting the graphics card up for a model closed LightCraft before (the markers [`set_up_card`] leaves):
|
||||
/// the user chose where denoise runs, so the card may be tried again.
|
||||
pub(crate) fn forget_gpu_set_ups(dir: &Path) {
|
||||
for i in installed_models(dir) {
|
||||
let _ = std::fs::remove_file(i.onnx.with_file_name(GPU_SETUP_MARKER));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
use super::model::{Loader, default_loader};
|
||||
use super::products::{Active, Progress};
|
||||
use super::settings::Settings;
|
||||
use super::*;
|
||||
|
||||
/// Most photos waiting in the queue.
|
||||
pub(super) const MAX_QUEUE: usize = 5000;
|
||||
|
||||
/// Most selected photos the automatic queue looks at in one pump.
|
||||
pub(super) const AUTO_LOOK: usize = 64;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
// the session's state
|
||||
|
||||
/// How hard the background work may go (the app picks it from what the user is doing, like the face scan).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Pace {
|
||||
/// Start nothing new.
|
||||
Pause,
|
||||
/// Two tiles at once.
|
||||
Light,
|
||||
/// Half the machine.
|
||||
Normal,
|
||||
/// Most of the machine: the user is watching the progress.
|
||||
Full,
|
||||
}
|
||||
|
||||
impl Pace {
|
||||
/// `pause`, `light`, `normal` or `full`; anything else is `normal`.
|
||||
pub fn parse(name: Option<&str>) -> Pace {
|
||||
match name {
|
||||
Some("pause") => Pace::Pause,
|
||||
Some("light") => Pace::Light,
|
||||
Some("full") => Pace::Full,
|
||||
_ => Pace::Normal,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tiles to run at once on a machine with `cores` threads (`cap`: the user's own limit).
|
||||
pub fn parallel(self, cores: usize, cap: Option<u32>) -> usize {
|
||||
let n = match self {
|
||||
Pace::Pause | Pace::Light => 2,
|
||||
Pace::Normal => cores / 2,
|
||||
Pace::Full => cores * 4 / 5,
|
||||
}
|
||||
.clamp(1, 16);
|
||||
cap.map_or(n, |c| n.min(c.max(1) as usize))
|
||||
}
|
||||
}
|
||||
|
||||
/// How a photo stands, for the interface.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(tag = "state", rename_all = "camelCase")]
|
||||
pub enum PhotoState {
|
||||
/// Not a photo denoise applies to (not a raw, offline, a demo).
|
||||
NotApplicable,
|
||||
/// No model is chosen: nothing can be made.
|
||||
NoModel,
|
||||
/// Its picture is made: the Amount slider works.
|
||||
Ready,
|
||||
Queued {
|
||||
/// Photos ahead of it (0 = next).
|
||||
ahead: usize,
|
||||
},
|
||||
Running {
|
||||
done: usize,
|
||||
total: usize,
|
||||
},
|
||||
/// Making it failed (`why`), or denoise does not apply to this file (`unsupported`).
|
||||
Failed {
|
||||
why: String,
|
||||
unsupported: bool,
|
||||
},
|
||||
/// Nothing has asked for it yet.
|
||||
Idle,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Failure {
|
||||
pub(super) key: String,
|
||||
pub(super) why: String,
|
||||
pub(super) unsupported: bool,
|
||||
}
|
||||
|
||||
pub(super) enum Outcome {
|
||||
Done,
|
||||
Failed(String, bool),
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
pub(super) struct Running {
|
||||
pub(super) photo: PhotoId,
|
||||
pub(super) key: String,
|
||||
pub(super) product: PathBuf,
|
||||
pub(super) progress: Arc<Progress>,
|
||||
pub(super) outcome: Arc<Mutex<Option<Outcome>>>,
|
||||
pub(super) started: web_time::Instant,
|
||||
}
|
||||
|
||||
pub(crate) struct State {
|
||||
/// Where the models are kept (`None` where there is no file system).
|
||||
pub models_dir: Option<PathBuf>,
|
||||
/// Models being downloaded at the user's request.
|
||||
pub downloads: Downloads,
|
||||
pub(crate) install: Option<crate::cmd::denoise::InstallJob>,
|
||||
/// How a model is loaded (tests put another in).
|
||||
pub loader: Loader,
|
||||
pub(crate) active: Option<Active>,
|
||||
pub(super) active_seen: Option<web_time::Instant>,
|
||||
/// `settings.json` as last read (with the model choice).
|
||||
pub(crate) settings: Settings,
|
||||
/// The index must be made again (the library, the model or the cache changed).
|
||||
pub(super) dirty: bool,
|
||||
/// The catalog revision and time of the last index, to look again when photos changed.
|
||||
pub(super) reindexed: Option<(u64, web_time::Instant)>,
|
||||
pub(super) queue: VecDeque<PhotoId>,
|
||||
pub(super) running: Option<Running>,
|
||||
pub(super) failed: HashMap<PhotoId, Failure>,
|
||||
/// Counts every change of what is ready, so the interface knows to draw again.
|
||||
pub generation: u64,
|
||||
/// Photos made since the session started.
|
||||
pub(super) made: u64,
|
||||
/// AI Denoise's row in the activity stack, while a photo is being made or waits its turn.
|
||||
pub(super) task: Option<crate::activity::TaskGuard>,
|
||||
}
|
||||
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
State {
|
||||
models_dir: None,
|
||||
downloads: Downloads::default(),
|
||||
install: None,
|
||||
loader: default_loader(),
|
||||
active: None,
|
||||
active_seen: None,
|
||||
settings: Settings::default(),
|
||||
dirty: true,
|
||||
reindexed: None,
|
||||
queue: VecDeque::new(),
|
||||
running: None,
|
||||
failed: HashMap::new(),
|
||||
generation: 0,
|
||||
made: 0,
|
||||
task: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for State {
|
||||
/// Quitting stops the job instead of leaving it to finish a photo nobody will see.
|
||||
fn drop(&mut self) {
|
||||
if let Some(r) = &self.running {
|
||||
r.progress.cancel_now();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// The library was replaced: nothing carries over (photo ids are per library).
|
||||
pub fn library_changed(&mut self) {
|
||||
if let Some(r) = self.running.take() {
|
||||
r.progress.cancel_now();
|
||||
}
|
||||
self.queue.clear();
|
||||
self.failed.clear();
|
||||
self.dirty = true;
|
||||
self.generation += 1;
|
||||
}
|
||||
|
||||
/// The model choice or the cache changed on disk: look again at the next pump.
|
||||
pub fn touch(&mut self) {
|
||||
self.active_seen = None;
|
||||
self.dirty = true;
|
||||
}
|
||||
|
||||
pub fn queued(&self) -> usize {
|
||||
self.queue.len()
|
||||
}
|
||||
}
|
||||
+35
-3740
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,198 @@
|
||||
use super::place::Placer;
|
||||
use super::prepare::{Destination, Exported, PreparedExport};
|
||||
use super::*;
|
||||
|
||||
/// Run prepared exports in order: pick each one's path, and hand the bytes (and sidecars) to
|
||||
/// `write`. `exists` tells whether a path is taken. The conflict policy applies to a file and its
|
||||
/// sidecars as one: with Unique both get the same free name, with Skip the photo is skipped when
|
||||
/// either is taken. A path that is a catalogued original (or its sidecar) is refused whatever the
|
||||
/// policy. `progress(done, next file)` is called before each photo; returning false cancels the
|
||||
/// rest. Returns one JSON object per photo: `{path, width, height, bytes, sidecars}`,
|
||||
/// `{skipped: path}` or (unless `stop_on_error`) `{photo, file, error}`.
|
||||
///
|
||||
/// Several photos render side by side ([`export_parallelism`], within the memory of
|
||||
/// [`crate::memory::export_gate`]), so one photo's decode, encode or GPU wait overlaps another's
|
||||
/// render (issue #496). Paths, writes, results and `progress` still follow the batch order, and the
|
||||
/// files are the same as one at a time.
|
||||
pub fn run_batch(
|
||||
items: Vec<PreparedExport>,
|
||||
o: &ExportOptions,
|
||||
to: &Destination,
|
||||
write: &mut dyn FnMut(&str, &[u8]) -> Result<(), String>,
|
||||
exists: &dyn Fn(&str) -> bool,
|
||||
stop_on_error: bool,
|
||||
progress: &mut dyn FnMut(usize, &str) -> bool,
|
||||
) -> Result<Vec<serde_json::Value>, String> {
|
||||
let lanes = export_parallelism(items.len());
|
||||
run_batch_with(items, &mut Placer::new(o, to, write, exists, stop_on_error), progress, lanes)
|
||||
}
|
||||
|
||||
/// How many photos of a batch of `n` render side by side. Each render already spreads its rows
|
||||
/// over every core; the others fill the cores while it decodes, encodes or waits for the GPU.
|
||||
/// One on wasm32 (no threads).
|
||||
pub fn export_parallelism(n: usize) -> usize {
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return 1;
|
||||
}
|
||||
let cores = std::thread::available_parallelism().map_or(1, |c| c.get());
|
||||
(cores / 4).clamp(1, 4).min(n.max(1))
|
||||
}
|
||||
|
||||
/// [`run_batch`] with `lanes` photos in flight (the calling thread is one of them).
|
||||
pub(super) fn run_batch_with(
|
||||
items: Vec<PreparedExport>,
|
||||
placer: &mut Placer<'_>,
|
||||
progress: &mut dyn FnMut(usize, &str) -> bool,
|
||||
lanes: usize,
|
||||
) -> Result<Vec<serde_json::Value>, String> {
|
||||
placer.single = items.len() == 1;
|
||||
if lanes <= 1 || items.len() <= 1 {
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
if !progress(i, &item.file_name) {
|
||||
break;
|
||||
}
|
||||
let (photo, name, guard, source_dir) = (item.photo, item.file_name.clone(), item.guard.clone(), item.source_dir.clone());
|
||||
placer.place(photo, name, source_dir.as_deref(), &guard, run_gated(item))?;
|
||||
}
|
||||
return Ok(std::mem::take(&mut placer.out));
|
||||
}
|
||||
let heads: Vec<_> = items.iter().map(|i| (i.photo, i.file_name.clone(), i.guard.clone(), i.source_dir.clone())).collect();
|
||||
let queue = Queue {
|
||||
lane: std::sync::Mutex::new(Lane { items: items.into_iter().map(Some).collect(), next: 0, placed: 0, stop: false, done: Default::default() }),
|
||||
cv: std::sync::Condvar::new(),
|
||||
ahead: lanes,
|
||||
};
|
||||
std::thread::scope(|sc| {
|
||||
// stops the lanes however this thread leaves the scope: a panic in `progress` or the placer
|
||||
// would otherwise leave them waiting and the scope's join would never return
|
||||
let _stop = StopOnDrop(&queue);
|
||||
for k in 1..lanes {
|
||||
let q = &queue;
|
||||
// a lane that can't start leaves its photos to the others (and to this thread)
|
||||
if std::thread::Builder::new().name(format!("export-{k}")).spawn_scoped(sc, move || q.work()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let placed = || {
|
||||
for (i, (photo, name, guard, source_dir)) in heads.into_iter().enumerate() {
|
||||
if !progress(i, &name) {
|
||||
break;
|
||||
}
|
||||
let e = queue.result(i);
|
||||
placer.place(photo, name, source_dir.as_deref(), &guard, e)?;
|
||||
}
|
||||
Ok::<_, String>(())
|
||||
};
|
||||
placed()
|
||||
})?;
|
||||
Ok(std::mem::take(&mut placer.out))
|
||||
}
|
||||
|
||||
/// Stops a [`Queue`] when dropped, also while unwinding from a panic.
|
||||
struct StopOnDrop<'a>(&'a Queue);
|
||||
|
||||
impl Drop for StopOnDrop<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.0.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// Run one photo's export holding its working memory from [`crate::memory::export_gate`]; a panic
|
||||
/// becomes that photo's error, not the batch's end.
|
||||
fn run_gated(item: PreparedExport) -> Result<Exported, String> {
|
||||
let _held = crate::memory::export_gate().acquire(item.weight);
|
||||
let what = format!("exporting {}", item.file_name);
|
||||
crate::guard::catch(&what, || item.run()).and_then(|r| r)
|
||||
}
|
||||
|
||||
/// The photos of a batch shared by its lanes: each lane takes the next one, at most
|
||||
/// [`Queue::ahead`] past the last placed. That bounds the finished files waiting in memory for
|
||||
/// their turn too (their working memory is given back to the gate as soon as they are encoded).
|
||||
struct Queue {
|
||||
lane: std::sync::Mutex<Lane>,
|
||||
cv: std::sync::Condvar,
|
||||
ahead: usize,
|
||||
}
|
||||
|
||||
struct Lane {
|
||||
items: Vec<Option<PreparedExport>>,
|
||||
/// The next photo to start.
|
||||
next: usize,
|
||||
/// Photos handed to the placer so far.
|
||||
placed: usize,
|
||||
stop: bool,
|
||||
done: std::collections::HashMap<usize, Result<Exported, String>>,
|
||||
}
|
||||
|
||||
impl Lane {
|
||||
fn take_next(&mut self) -> Option<(usize, PreparedExport)> {
|
||||
let i = self.next;
|
||||
let item = self.items.get_mut(i)?.take()?;
|
||||
self.next += 1;
|
||||
Some((i, item))
|
||||
}
|
||||
}
|
||||
|
||||
impl Queue {
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, Lane> {
|
||||
self.lane.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn wait<'a>(&self, g: std::sync::MutexGuard<'a, Lane>) -> std::sync::MutexGuard<'a, Lane> {
|
||||
self.cv.wait(g).unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn finish(&self, i: usize, r: Result<Exported, String>) {
|
||||
self.lock().done.insert(i, r);
|
||||
self.cv.notify_all();
|
||||
}
|
||||
|
||||
/// A lane thread: run photos until none is left or the batch stops.
|
||||
fn work(&self) {
|
||||
loop {
|
||||
let mut l = self.lock();
|
||||
let (i, item) = loop {
|
||||
if l.stop || l.next >= l.items.len() {
|
||||
return;
|
||||
}
|
||||
if l.next < l.placed.saturating_add(self.ahead) {
|
||||
match l.take_next() {
|
||||
Some(t) => break t,
|
||||
None => return,
|
||||
}
|
||||
}
|
||||
l = self.wait(l);
|
||||
};
|
||||
drop(l);
|
||||
self.finish(i, run_gated(item));
|
||||
}
|
||||
}
|
||||
|
||||
/// Photo `i`'s result, waiting for it; run here when no lane has started it yet.
|
||||
fn result(&self, i: usize) -> Result<Exported, String> {
|
||||
let mut l = self.lock();
|
||||
loop {
|
||||
if let Some(r) = l.done.remove(&i) {
|
||||
l.placed = i + 1;
|
||||
drop(l);
|
||||
self.cv.notify_all();
|
||||
return r;
|
||||
}
|
||||
if l.next == i {
|
||||
let Some((_, item)) = l.take_next() else {
|
||||
return Err("export: photo missing from the batch".into());
|
||||
};
|
||||
drop(l);
|
||||
self.finish(i, run_gated(item));
|
||||
l = self.lock();
|
||||
continue;
|
||||
}
|
||||
l = self.wait(l);
|
||||
}
|
||||
}
|
||||
|
||||
fn stop(&self) {
|
||||
self.lock().stop = true;
|
||||
self.cv.notify_all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
use super::options::{ExportFormat, MetadataPolicy, SharpenAmount, SharpenFor};
|
||||
use super::watermark::{Watermark, draw_watermark, draw_watermark_deep};
|
||||
use super::*;
|
||||
|
||||
/// Unsharp mask on an 8-bit image (separable box-blur approximation of a small Gaussian).
|
||||
pub fn output_sharpen(img: &mut Rgba8, target: SharpenFor, amount: SharpenAmount) {
|
||||
let src: Vec<[f32; 3]> = img.data.iter().map(|p| [p[0] as f32, p[1] as f32, p[2] as f32]).collect();
|
||||
if let Some(out) = unsharp(img.width, img.height, &src, target, amount) {
|
||||
for (p, v) in img.data.iter_mut().zip(out) {
|
||||
for c in 0..3 {
|
||||
p[c] = v[c].round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`output_sharpen`] on a high-bit-depth image (float images are sharpened in linear light).
|
||||
pub fn output_sharpen_deep(img: &mut DeepImage, target: SharpenFor, amount: SharpenAmount) {
|
||||
let (w, h) = (img.width, img.height);
|
||||
match &mut img.samples {
|
||||
DeepSamples::U16(v) => {
|
||||
let src: Vec<[f32; 3]> = v.as_chunks::<3>().0.iter().map(|c| [c[0] as f32, c[1] as f32, c[2] as f32]).collect();
|
||||
if let Some(out) = unsharp(w, h, &src, target, amount) {
|
||||
for (d, s) in v.iter_mut().zip(out.as_flattened()) {
|
||||
*d = s.round().clamp(0.0, 65535.0) as u16;
|
||||
}
|
||||
}
|
||||
}
|
||||
DeepSamples::F32(v) => {
|
||||
let src: Vec<[f32; 3]> = v.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect();
|
||||
if let Some(out) = unsharp(w, h, &src, target, amount) {
|
||||
for (d, s) in v.iter_mut().zip(out.as_flattened()) {
|
||||
*d = s.max(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sharpened values of `src` (`w × h`), or `None` when nothing is to be done.
|
||||
fn unsharp(w: usize, h: usize, src: &[[f32; 3]], target: SharpenFor, amount: SharpenAmount) -> Option<Vec<[f32; 3]>> {
|
||||
let (radius, base) = match target {
|
||||
SharpenFor::None => return None,
|
||||
SharpenFor::Screen => (1usize, 0.35f32),
|
||||
SharpenFor::Matte => (2, 0.6),
|
||||
SharpenFor::Glossy => (1, 0.5),
|
||||
};
|
||||
let k = base
|
||||
* match amount {
|
||||
SharpenAmount::Low => 0.6,
|
||||
SharpenAmount::Standard => 1.0,
|
||||
SharpenAmount::High => 1.5,
|
||||
};
|
||||
if w < 3 || h < 3 {
|
||||
return None;
|
||||
}
|
||||
let r = radius as isize;
|
||||
let box_pass = |inp: &[[f32; 3]], horizontal: bool| -> Vec<[f32; 3]> {
|
||||
let mut out = vec![[0.0; 3]; inp.len()];
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut acc = [0.0f32; 3];
|
||||
for d in -r..=r {
|
||||
let (sx, sy) = if horizontal {
|
||||
((x as isize + d).clamp(0, w as isize - 1) as usize, y)
|
||||
} else {
|
||||
(x, (y as isize + d).clamp(0, h as isize - 1) as usize)
|
||||
};
|
||||
let p = inp[sy * w + sx];
|
||||
acc = [acc[0] + p[0], acc[1] + p[1], acc[2] + p[2]];
|
||||
}
|
||||
let n = (2 * r + 1) as f32;
|
||||
out[y * w + x] = acc.map(|v| v / n);
|
||||
}
|
||||
}
|
||||
out
|
||||
};
|
||||
let blur = box_pass(&box_pass(src, true), false);
|
||||
Some(src.iter().zip(&blur).map(|(s, b)| std::array::from_fn(|c| s[c] + (s[c] - b[c]) * k)).collect())
|
||||
}
|
||||
|
||||
/// Encode a rendered display-referred image according to `o` (its pixels must already be in
|
||||
/// `o.effective_space()`). Resizing to `long_edge` is the
|
||||
/// caller's job (render at that size); sharpening is applied here.
|
||||
pub fn encode_image(img: &Rgba8, o: &ExportOptions) -> Result<Vec<u8>, String> {
|
||||
encode_with_metadata(img, o, None)
|
||||
}
|
||||
|
||||
/// Like [`encode_image`], embedding `meta` (already filtered by the policy) as EXIF + XMP.
|
||||
pub fn encode_with_metadata(img: &Rgba8, o: &ExportOptions, meta: Option<&Metadata>) -> Result<Vec<u8>, String> {
|
||||
let img = finish_8bit(img, o);
|
||||
let space = o.effective_space();
|
||||
let profile = icc::write_named(named_space(space));
|
||||
let exif = meta.map(lightcraft_meta::write_exif);
|
||||
let xmp = meta.map(|m| lightcraft_meta::write_xmp(m, None));
|
||||
let meta = EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: Some(o.ppi) };
|
||||
// Opaque photo exports need no alpha channel (#1670). Keep real transparency for
|
||||
// callers of this encoder, and leave unrelated formats on their existing path.
|
||||
let rgb: Option<Vec<u8>> = (matches!(o.format, ExportFormat::Png | ExportFormat::Tiff | ExportFormat::Webp)
|
||||
&& img.data.iter().all(|p| p.last() == Some(&255)))
|
||||
.then(|| img.data.iter().flat_map(|p| p.iter().take(3).copied()).collect());
|
||||
let e = match &rgb {
|
||||
Some(data) => EncodeImage::new(img.width as u32, img.height as u32, 3, Samples::U8(data)),
|
||||
None => EncodeImage::rgba8(&img),
|
||||
};
|
||||
let r = match o.format {
|
||||
ExportFormat::Jpeg => {
|
||||
// 4:4:4 normally; 4:2:0 when targeting a file size (much smaller at equal visual quality).
|
||||
let sub = if o.limit_kb.is_some() { ChromaSubsampling::S420 } else { ChromaSubsampling::S444 };
|
||||
return encode_jpeg_with_limit(o, |q| encode::encode_jpeg(&e, q, sub, &meta));
|
||||
}
|
||||
ExportFormat::Png => encode::encode_png(&e, &meta),
|
||||
ExportFormat::Tiff => encode::encode_tiff(&e, o.tiff_compression, &meta),
|
||||
ExportFormat::Psd => encode::encode_psd(&e, &meta),
|
||||
ExportFormat::Webp => encode::encode_webp_lossless(&e, &meta),
|
||||
ExportFormat::Avif => encode::encode_avif(&e, o.quality, 8, &meta),
|
||||
ExportFormat::Jxl => lightcraft_codecs::encode_jxl(&e, &o.jxl(space, false), &meta),
|
||||
f @ (ExportFormat::Original | ExportFormat::Dng) => return Err(format!("{f:?} export does not encode pixels")),
|
||||
ExportFormat::RenderedDng => return Err("Render to DNG needs a float render".into()),
|
||||
};
|
||||
r.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Apply the same file-size policy to ordinary JPEGs and complete HDR gain map JPEGs.
|
||||
fn encode_jpeg_with_limit(o: &ExportOptions, jpeg: impl Fn(u8) -> lightcraft_codecs::Result<Vec<u8>>) -> Result<Vec<u8>, String> {
|
||||
let Some(kb) = o.limit_kb else { return jpeg(o.quality).map_err(|e| e.to_string()) };
|
||||
let limit = u64::from(kb) * 1024;
|
||||
let (mut lo, mut hi) = (1u8, o.quality.min(100));
|
||||
let mut best = None;
|
||||
while lo <= hi {
|
||||
let mid = lo + (hi - lo) / 2;
|
||||
let b = jpeg(mid).map_err(|e| e.to_string())?;
|
||||
if b.len() as u64 <= limit {
|
||||
best = Some(b);
|
||||
lo = mid + 1;
|
||||
} else if mid == 1 {
|
||||
break;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
best.ok_or_else(|| format!("cannot fit within {kb} KB"))
|
||||
}
|
||||
|
||||
/// Output sharpening and the watermark on an 8-bit render in `o.effective_space()`.
|
||||
fn finish_8bit(img: &Rgba8, o: &ExportOptions) -> Rgba8 {
|
||||
let mut img = img.clone();
|
||||
output_sharpen(&mut img, o.sharpen, o.sharpen_amount);
|
||||
let space = o.effective_space();
|
||||
if let Some(wm) = &o.watermark {
|
||||
let wm = Watermark { color: srgb8_in(space, wm.color), target: Some(space), ..wm.clone() };
|
||||
draw_watermark(&mut img, &wm);
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
/// Output sharpening and the watermark on a high-bit-depth render.
|
||||
fn finish_deep(img: &DeepImage, o: &ExportOptions) -> DeepImage {
|
||||
let mut img = img.clone();
|
||||
output_sharpen_deep(&mut img, o.sharpen, o.sharpen_amount);
|
||||
if let Some(wm) = &o.watermark {
|
||||
let wm = Watermark { color: srgb8_in(img.space, wm.color), target: Some(img.space), ..wm.clone() };
|
||||
draw_watermark_deep(&mut img, &wm);
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
/// Encode an ISO 21496-1 gain map JPEG from the SDR rendition `sdr` (8-bit, in the output space)
|
||||
/// and the HDR rendition `hdr` (float linear, same space and size). The gain map is measured
|
||||
/// against the base as written, so its 8-bit rounding is handed back by the map.
|
||||
pub fn encode_gain_map_jpeg(sdr: &Rgba8, hdr: &DeepImage, o: &ExportOptions, meta: Option<&Metadata>) -> Result<Vec<u8>, String> {
|
||||
use lightcraft_codecs::gainmap;
|
||||
let base = finish_8bit(sdr, o);
|
||||
let hdr = finish_deep(hdr, o);
|
||||
let DeepSamples::F32(hv) = &hdr.samples else {
|
||||
return Err("HDR export needs a float HDR render".into());
|
||||
};
|
||||
let (w, h) = (base.width, base.height);
|
||||
if (hdr.width, hdr.height) != (w, h) || hv.len() < w * h * 3 {
|
||||
return Err("HDR and SDR renders differ in size".into());
|
||||
}
|
||||
let space = o.effective_space();
|
||||
let trc = space.trc();
|
||||
let sdr_lin: Vec<[f32; 3]> = base.data.iter().map(|p| [0, 1, 2].map(|c| trc.decode(p[c] as f32 / 255.0))).collect();
|
||||
let hdr_lin: &[[f32; 3]] = hv.as_chunks::<3>().0;
|
||||
let (map, gm) = gainmap::compute(&sdr_lin, hdr_lin, w, h, space.luma(), &gainmap::GainMapOptions::default()).map_err(|e| e.to_string())?;
|
||||
let profile = icc::write_named(named_space(space));
|
||||
let exif = meta.map(lightcraft_meta::write_exif);
|
||||
let xmp = meta.map(|m| lightcraft_meta::write_xmp(m, None));
|
||||
let em = EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: Some(o.ppi) };
|
||||
let sub = if o.limit_kb.is_some() { ChromaSubsampling::S420 } else { ChromaSubsampling::S444 };
|
||||
encode_jpeg_with_limit(o, |q| gainmap::encode_jpeg(&EncodeImage::rgba8(&base), &map, &gm, q, sub, &em))
|
||||
}
|
||||
|
||||
/// The codecs' name of an output space (for its ICC profile).
|
||||
pub fn named_space(s: OutputSpace) -> NamedSpace {
|
||||
match s {
|
||||
OutputSpace::Srgb => NamedSpace::Srgb,
|
||||
OutputSpace::DisplayP3 => NamedSpace::DisplayP3,
|
||||
OutputSpace::AdobeRgb => NamedSpace::AdobeRgb,
|
||||
OutputSpace::ProPhoto => NamedSpace::ProPhoto,
|
||||
OutputSpace::Rec2020 => NamedSpace::Rec2020,
|
||||
}
|
||||
}
|
||||
|
||||
/// An 8-bit sRGB colour expressed in `space` (encoded with its curve).
|
||||
pub fn srgb8_in(space: OutputSpace, c: [u8; 3]) -> [u8; 3] {
|
||||
if space == OutputSpace::Srgb {
|
||||
return c;
|
||||
}
|
||||
let lin = c.map(lightcraft_color::transfer::decode_srgb8);
|
||||
let m = lightcraft_color::SRGB.to_space(&space.rgb_space()).to_f32();
|
||||
let t = space.trc();
|
||||
std::array::from_fn(|i| {
|
||||
let v = m[i][0] * lin[0] + m[i][1] * lin[1] + m[i][2] * lin[2];
|
||||
(t.encode(v) * 255.0 + 0.5) as u8
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode a render according to `o`: its high-bit-depth samples when it has them (16-bit PNG/TIFF,
|
||||
/// 10-bit AVIF, 32-bit float linear TIFF), else its 8-bit image.
|
||||
pub fn encode_rendered(r: &lightcraft_pipeline::Rendered, o: &ExportOptions, meta: Option<&Metadata>) -> Result<Vec<u8>, String> {
|
||||
match &r.deep {
|
||||
Some(d) if o.effective_depth() != OutputDepth::U8 => encode_deep(d, o, meta),
|
||||
_ => encode_with_metadata(&r.image, o, meta),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a high-bit-depth image (see [`encode_rendered`]).
|
||||
pub fn encode_deep(img: &DeepImage, o: &ExportOptions, meta: Option<&Metadata>) -> Result<Vec<u8>, String> {
|
||||
let meta_src = meta;
|
||||
let img = finish_deep(img, o);
|
||||
let profile = match img.samples {
|
||||
DeepSamples::F32(_) => icc::write_matrix_trc(&img.space.rgb_space(), &lightcraft_codecs::Trc::Linear),
|
||||
DeepSamples::U16(_) => icc::write_named(named_space(img.space)),
|
||||
};
|
||||
let exif = meta.map(lightcraft_meta::write_exif);
|
||||
let xmp = meta.map(|m| lightcraft_meta::write_xmp(m, None));
|
||||
let meta = EncodeMeta { icc: Some(&profile), exif: exif.as_deref(), xmp: xmp.as_deref(), ppi: Some(o.ppi) };
|
||||
let (w, h) = (img.width as u32, img.height as u32);
|
||||
let e = match &img.samples {
|
||||
DeepSamples::U16(v) => EncodeImage::new(w, h, 3, Samples::U16(v)),
|
||||
DeepSamples::F32(v) => EncodeImage::new(w, h, 3, Samples::F32(v)),
|
||||
};
|
||||
let r = match (o.format, &img.samples) {
|
||||
(ExportFormat::Png, DeepSamples::F32(v)) if img.space == OutputSpace::Rec2020 => lightcraft_codecs::encode_png_pq(w, h, v, &meta),
|
||||
(ExportFormat::Png, _) => encode::encode_png(&e, &meta),
|
||||
(ExportFormat::Tiff, _) => encode::encode_tiff(&e, o.tiff_compression, &meta),
|
||||
(ExportFormat::Psd, _) => encode::encode_psd(&e, &meta),
|
||||
(ExportFormat::RenderedDng, DeepSamples::F32(v)) => {
|
||||
let m = meta_src.cloned().unwrap_or_default();
|
||||
return lightcraft_raw::write_rendered_dng(img.width, img.height, v, &img.space.rgb_space(), &m, xmp.clone()).map_err(|e| e.to_string());
|
||||
}
|
||||
(ExportFormat::Avif, DeepSamples::F32(v)) if img.space == OutputSpace::Rec2020 => {
|
||||
lightcraft_codecs::encode_avif_hdr(w, h, v, o.quality, 8, &meta, o.hdr_transfer.codec())
|
||||
}
|
||||
(ExportFormat::Avif, _) => encode::encode_avif(&e, o.quality, 8, &meta),
|
||||
(ExportFormat::Jxl, DeepSamples::F32(_)) if img.space == OutputSpace::Rec2020 => {
|
||||
lightcraft_codecs::encode_jxl(&e, &o.jxl(img.space, true), &meta)
|
||||
}
|
||||
(ExportFormat::Jxl, DeepSamples::U16(_)) => lightcraft_codecs::encode_jxl(&e, &o.jxl(img.space, false), &meta),
|
||||
(f, _) => return Err(format!("{f:?} export is 8-bit only")),
|
||||
};
|
||||
r.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Whether the export of `photo` under `o` leaves out its location (GPS and place names).
|
||||
/// (`photo` and `catalog` let library-level privacy rules add to the export option.)
|
||||
pub fn removes_location(_photo: &lightcraft_catalog::Photo, _catalog: &lightcraft_catalog::Catalog, o: &ExportOptions) -> bool {
|
||||
o.remove_location
|
||||
}
|
||||
|
||||
/// The metadata to embed for `photo` under `o.metadata` / `o.remove_location`. `None` = embed nothing.
|
||||
/// Keywords follow the catalog's keyword list (`Catalog::export_keywords`).
|
||||
pub fn export_metadata(photo: &lightcraft_catalog::Photo, catalog: &lightcraft_catalog::Catalog, o: &ExportOptions) -> Option<Metadata> {
|
||||
let m = &photo.meta;
|
||||
let text = |s: &str| (!s.trim().is_empty()).then(|| s.to_string());
|
||||
// copyright info (also under "copyright only"): notice, creator, status, usage terms, info URL
|
||||
let mut out = Metadata {
|
||||
copyright: text(&m.copyright),
|
||||
copyright_marked: m.copyright_status.marked(),
|
||||
usage_terms: text(&m.usage_terms),
|
||||
copyright_url: text(&m.copyright_url),
|
||||
artist: text(&m.creator),
|
||||
software: Some("LightCraft".into()),
|
||||
..Default::default()
|
||||
};
|
||||
match o.metadata {
|
||||
MetadataPolicy::None => return None,
|
||||
MetadataPolicy::Copyright => return Some(out),
|
||||
MetadataPolicy::All | MetadataPolicy::AllExceptCamera => {}
|
||||
}
|
||||
out.title = text(&m.title);
|
||||
out.caption = text(&m.caption);
|
||||
out.alt_text = text(&m.alt_text);
|
||||
out.extended_description = text(&m.extended_description);
|
||||
if !o.remove_location {
|
||||
out.sublocation = text(&m.location);
|
||||
out.city = text(&m.city);
|
||||
out.state = text(&m.state);
|
||||
out.country = text(&m.country);
|
||||
}
|
||||
let keywords = catalog.export_keywords(&m.keywords);
|
||||
out.keywords = keywords.flat;
|
||||
out.hierarchical_keywords = keywords.hierarchical;
|
||||
out.capture_time = photo.captured.as_deref().and_then(DateTime::parse_iso);
|
||||
out.rating = (photo.rating > 0).then_some(photo.rating as i8);
|
||||
// Pixels are exported upright: orientation is baked in.
|
||||
out.orientation = Some(lightcraft_meta::Orientation::Normal);
|
||||
if !o.remove_location {
|
||||
out.gps = m.gps.map(|(latitude, longitude)| Gps { latitude, longitude, altitude: None });
|
||||
}
|
||||
if o.metadata == MetadataPolicy::All {
|
||||
out.model = text(&m.camera);
|
||||
out.lens_model = text(&m.lens);
|
||||
out.focal_length = m.focal_mm.map(f64::from);
|
||||
out.f_number = m.aperture.map(f64::from);
|
||||
out.exposure_time = lightcraft_catalog::parse_shutter_seconds(&m.shutter);
|
||||
out.iso = m.iso;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ExportFormat {
|
||||
#[default]
|
||||
Jpeg,
|
||||
Png,
|
||||
Tiff,
|
||||
/// A flat PSD (8/16-bit, no layers): what an image editor such as PhotoCraft saves back to.
|
||||
Psd,
|
||||
Webp,
|
||||
Avif,
|
||||
/// JPEG XL: lossy (VarDCT) or lossless, 8/16-bit, HDR as Rec. 2020 PQ.
|
||||
Jxl,
|
||||
/// The original file, unchanged, with an XMP sidecar holding the edits.
|
||||
Original,
|
||||
/// A DNG of the raw data (raw photos only), the edits embedded as XMP.
|
||||
Dng,
|
||||
/// Render to DNG: a linear DNG (16-bit float) of the rendered photo, the edit baked in.
|
||||
RenderedDng,
|
||||
}
|
||||
|
||||
impl ExportFormat {
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
Some(match s.to_ascii_lowercase().as_str() {
|
||||
"jpeg" | "jpg" => Self::Jpeg,
|
||||
"png" => Self::Png,
|
||||
"tiff" | "tif" => Self::Tiff,
|
||||
"psd" => Self::Psd,
|
||||
"webp" => Self::Webp,
|
||||
"avif" => Self::Avif,
|
||||
"jxl" | "jpegxl" | "jpeg-xl" | "jpeg_xl" => Self::Jxl,
|
||||
"original" => Self::Original,
|
||||
"dng" => Self::Dng,
|
||||
"rendereddng" | "renderdng" | "render-dng" | "lineardng" => Self::RenderedDng,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
pub fn extension(self) -> &'static str {
|
||||
match self {
|
||||
Self::Jpeg => "jpg",
|
||||
Self::Png => "png",
|
||||
Self::Tiff => "tif",
|
||||
Self::Psd => "psd",
|
||||
Self::Webp => "webp",
|
||||
Self::Avif => "avif",
|
||||
Self::Jxl => "jxl",
|
||||
// the original keeps its own extension (see `ExportOptions::file_name_for`)
|
||||
Self::Original => "",
|
||||
Self::Dng | Self::RenderedDng => "dng",
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats that render pixels (everything but `Original` and `Dng`).
|
||||
pub fn is_rendered(self) -> bool {
|
||||
!matches!(self, Self::Original | Self::Dng)
|
||||
}
|
||||
}
|
||||
|
||||
/// How the output size is chosen (see [`Resize`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ResizeMode {
|
||||
/// `value` = long edge in pixels.
|
||||
#[default]
|
||||
LongEdge,
|
||||
/// `value` = short edge in pixels.
|
||||
ShortEdge,
|
||||
/// `value` = width in pixels.
|
||||
Width,
|
||||
/// `value` = height in pixels.
|
||||
Height,
|
||||
/// Fit inside `value` wide × `height` tall as the photo stands: width ≤ `value`, height ≤
|
||||
/// `height` (Lightroom's "Width & Height").
|
||||
WidthHeight,
|
||||
/// Fit inside `value × height` pixels, whichever way round the photo is (long edge ≤ the
|
||||
/// larger; Lightroom's "Dimensions").
|
||||
Dimensions,
|
||||
/// `value` = megapixels.
|
||||
Megapixels,
|
||||
/// `value` = percent of the full size.
|
||||
Percent,
|
||||
}
|
||||
|
||||
/// Output size: a mode, its value(s) and whether smaller photos are left at their own size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Resize {
|
||||
pub mode: ResizeMode,
|
||||
pub value: f32,
|
||||
/// Second dimension for [`ResizeMode::Dimensions`] and [`ResizeMode::WidthHeight`].
|
||||
pub height: u32,
|
||||
/// Never upscale past the photo's own (cropped) size.
|
||||
pub dont_enlarge: bool,
|
||||
}
|
||||
|
||||
impl Default for Resize {
|
||||
fn default() -> Self {
|
||||
Self { mode: ResizeMode::LongEdge, value: 2048.0, height: 2048, dont_enlarge: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// The most pixels an export enlarged past its photo's own size can have: 512 megapixels, also
|
||||
/// Lightroom's ceiling. A full-size or smaller export is never held to it.
|
||||
pub const MAX_ENLARGED_PIXELS: f64 = 512e6;
|
||||
|
||||
impl Resize {
|
||||
pub fn long_edge(px: u32) -> Self {
|
||||
Self { value: px as f32, ..Default::default() }
|
||||
}
|
||||
|
||||
/// Scale factor from a `w × h` (cropped, full-resolution) photo to the output.
|
||||
pub fn scale(&self, w: f64, h: f64) -> f64 {
|
||||
let (w, h) = (w.max(1.0), h.max(1.0));
|
||||
let (long, short) = (w.max(h), w.min(h));
|
||||
let v = (self.value as f64).max(0.0);
|
||||
let k = match self.mode {
|
||||
ResizeMode::LongEdge => v / long,
|
||||
ResizeMode::ShortEdge => v / short,
|
||||
ResizeMode::Width => v / w,
|
||||
ResizeMode::Height => v / h,
|
||||
ResizeMode::WidthHeight => (v / w).min(self.height as f64 / h),
|
||||
ResizeMode::Dimensions => {
|
||||
let (a, b) = (v, self.height as f64);
|
||||
(a.max(b) / long).min(a.min(b) / short)
|
||||
}
|
||||
ResizeMode::Megapixels => (v * 1e6 / (w * h)).sqrt(),
|
||||
ResizeMode::Percent => v / 100.0,
|
||||
};
|
||||
let k = if self.dont_enlarge { k.min(1.0) } else { k };
|
||||
// an enlargement stops at 512 megapixels (Lightroom's ceiling too): 20000 typed for 2000
|
||||
// with Don't Enlarge off asked for gigapixels, more memory than a computer has
|
||||
let k = k.min((MAX_ENLARGED_PIXELS / (w * h)).sqrt().max(1.0));
|
||||
// at least one pixel, at most the encoders' 65535 limit; the limit wins for a photo more
|
||||
// than 65535 times as long as it is short (where `clamp` would panic: min above max)
|
||||
k.max(1.0 / short).min(65_535.0 / long)
|
||||
}
|
||||
|
||||
/// Output size for a `w × h` (cropped, full-resolution) photo.
|
||||
pub fn apply(&self, w: f64, h: f64) -> (usize, usize) {
|
||||
let k = self.scale(w, h);
|
||||
(((w * k).round() as usize).max(1), ((h * k).round() as usize).max(1))
|
||||
}
|
||||
}
|
||||
|
||||
/// What happens when an output file already exists.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Conflict {
|
||||
/// Add `-2`, `-3`, … to the name.
|
||||
#[default]
|
||||
Unique,
|
||||
Overwrite,
|
||||
/// Leave the existing file and skip the photo.
|
||||
Skip,
|
||||
}
|
||||
|
||||
/// Where a batch's files go (Lightroom Classic's Export To).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DestinationMode {
|
||||
/// One folder for the whole batch ([`Destination::dir`]).
|
||||
#[default]
|
||||
SpecificFolder,
|
||||
/// Each photo's own folder: the folder its original is in. A photo without one on disk (a
|
||||
/// demo photo, a photo in the browser's storage) or whose folder is gone gets an error.
|
||||
SameAsOriginal,
|
||||
}
|
||||
|
||||
impl DestinationMode {
|
||||
/// `specificFolder` / `sameAsOriginal` (any case).
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"specificfolder" => Some(Self::SpecificFolder),
|
||||
"sameasoriginal" => Some(Self::SameAsOriginal),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Conflict {
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.to_ascii_lowercase().as_str() {
|
||||
"unique" => Some(Self::Unique),
|
||||
"overwrite" => Some(Self::Overwrite),
|
||||
"skip" => Some(Self::Skip),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A named set of `app.export` params.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ExportPreset {
|
||||
pub name: String,
|
||||
pub params: serde_json::Value,
|
||||
}
|
||||
|
||||
/// The built-in export presets (File → Export with Preset).
|
||||
pub fn builtin_presets() -> Vec<ExportPreset> {
|
||||
let p = |name: &str, params: serde_json::Value| ExportPreset { name: name.into(), params };
|
||||
vec![
|
||||
p("JPEG (Small)", serde_json::json!({"format": "jpeg", "quality": 85, "longEdge": 2048, "colorSpace": "srgb"})),
|
||||
p("JPEG (Large)", serde_json::json!({"format": "jpeg", "quality": 92, "longEdge": 0, "colorSpace": "srgb"})),
|
||||
p("Original + Settings", serde_json::json!({"format": "original"})),
|
||||
p("DNG", serde_json::json!({"format": "dng"})),
|
||||
]
|
||||
}
|
||||
|
||||
/// Output sharpening target (applied after resizing, in display-encoded values).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SharpenFor {
|
||||
#[default]
|
||||
None,
|
||||
Screen,
|
||||
Matte,
|
||||
Glossy,
|
||||
}
|
||||
|
||||
impl SharpenFor {
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.to_ascii_lowercase().as_str() {
|
||||
"none" => Some(Self::None),
|
||||
"screen" => Some(Self::Screen),
|
||||
"matte" => Some(Self::Matte),
|
||||
"glossy" => Some(Self::Glossy),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SharpenAmount {
|
||||
Low,
|
||||
#[default]
|
||||
Standard,
|
||||
High,
|
||||
}
|
||||
|
||||
impl SharpenAmount {
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.to_ascii_lowercase().as_str() {
|
||||
"low" => Some(Self::Low),
|
||||
"standard" => Some(Self::Standard),
|
||||
"high" => Some(Self::High),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which metadata is embedded in exported files.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MetadataPolicy {
|
||||
/// Everything we know: camera, capture settings, lens, location, title, caption, keywords, copyright.
|
||||
#[default]
|
||||
All,
|
||||
/// Everything except camera/lens make, model and capture settings.
|
||||
AllExceptCamera,
|
||||
/// Copyright and creator only.
|
||||
Copyright,
|
||||
/// Nothing (the sRGB profile is still embedded).
|
||||
None,
|
||||
}
|
||||
|
||||
impl MetadataPolicy {
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.to_ascii_lowercase().as_str() {
|
||||
"all" => Some(Self::All),
|
||||
"allexceptcamera" => Some(Self::AllExceptCamera),
|
||||
"copyright" => Some(Self::Copyright),
|
||||
"none" => Some(Self::None),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Transfer curve of an HDR AVIF export (`hdrTransfer`): PQ (absolute, SDR white at 203 cd/m²) or
|
||||
/// HLG (relative to the display; BT.2100 with SDR white at signal 0.75).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum HdrCurve {
|
||||
#[default]
|
||||
Pq,
|
||||
Hlg,
|
||||
}
|
||||
|
||||
impl HdrCurve {
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.to_ascii_lowercase().as_str() {
|
||||
"pq" => Some(Self::Pq),
|
||||
"hlg" => Some(Self::Hlg),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub(super) fn codec(self) -> lightcraft_codecs::HdrTransfer {
|
||||
match self {
|
||||
Self::Pq => lightcraft_codecs::HdrTransfer::Pq,
|
||||
Self::Hlg => lightcraft_codecs::HdrTransfer::Hlg,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,615 @@
|
||||
use super::options::{Conflict, DestinationMode, ExportFormat, HdrCurve, MetadataPolicy, Resize, ResizeMode, SharpenAmount, SharpenFor};
|
||||
use super::prepare::DngCompression;
|
||||
use super::watermark::{Anchor, Watermark};
|
||||
use super::*;
|
||||
|
||||
impl Default for ExportOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
format: ExportFormat::Jpeg,
|
||||
quality: 90,
|
||||
resize: None,
|
||||
ppi: 240,
|
||||
limit_kb: None,
|
||||
sharpen: SharpenFor::None,
|
||||
sharpen_amount: SharpenAmount::Standard,
|
||||
naming: "{name}".into(),
|
||||
start_number: 1,
|
||||
destination_mode: DestinationMode::SpecificFolder,
|
||||
subfolder: String::new(),
|
||||
conflict: Conflict::Unique,
|
||||
tiff_compression: TiffCompression::Deflate,
|
||||
dng_compression: DngCompression::Lossless,
|
||||
metadata: MetadataPolicy::All,
|
||||
remove_location: false,
|
||||
watermark: None,
|
||||
color_space: OutputSpace::Srgb,
|
||||
bit_depth: None,
|
||||
hdr: false,
|
||||
jxl_lossless: false,
|
||||
jxl_effort: JxlEffort::Normal,
|
||||
jxl_progressive: false,
|
||||
add_to_photos: false,
|
||||
photos_album: String::new(),
|
||||
hdr_transfer: HdrCurve::Pq,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `app.export` params that are not export options: which photos, where to, a preset to start
|
||||
/// from, and the desktop app's background flag.
|
||||
pub const TARGET_PARAMS: &[&str] = &["id", "ids", "path", "dir", "preset", "background"];
|
||||
|
||||
/// The export option params [`ExportOptions::from_json`] reads (and [`ExportOptions::to_json`] writes).
|
||||
pub const OPTION_PARAMS: &[&str] = &[
|
||||
"format",
|
||||
"quality",
|
||||
"resize",
|
||||
"longEdge",
|
||||
"shortEdge",
|
||||
"width",
|
||||
"height",
|
||||
"megapixels",
|
||||
"percent",
|
||||
"fit",
|
||||
"dontEnlarge",
|
||||
"ppi",
|
||||
"limitKb",
|
||||
"sharpen",
|
||||
"sharpenAmount",
|
||||
"naming",
|
||||
"startNumber",
|
||||
"destinationMode",
|
||||
"subfolder",
|
||||
"conflict",
|
||||
"tiffCompression",
|
||||
"dngCompression",
|
||||
"metadata",
|
||||
"removeLocation",
|
||||
"watermark",
|
||||
"colorSpace",
|
||||
"bitDepth",
|
||||
"hdr",
|
||||
"jxlLossless",
|
||||
"jxlEffort",
|
||||
"jxlProgressive",
|
||||
"addToPhotos",
|
||||
"photosAlbum",
|
||||
"hdrTransfer",
|
||||
];
|
||||
|
||||
/// Why an export can't add its files to Apple Photos on this platform (`None`: it can, when the
|
||||
/// session has the runner; see [`crate::Session::after_export`]).
|
||||
pub fn apple_photos_unsupported() -> Option<&'static str> {
|
||||
(!cfg!(target_os = "macos")).then_some("Apple Photos is only available on macOS")
|
||||
}
|
||||
|
||||
/// The keys of a `watermark` object ([`Watermark`], camelCase). `inset` sets `insetX` and `insetY`
|
||||
/// together (what versions before the two margins wrote); either of those, when given, wins.
|
||||
pub const WATERMARK_PARAMS: &[&str] =
|
||||
&["text", "vertical", "size", "opacity", "anchor", "insetX", "insetY", "inset", "rotation", "color", "shadow", "image", "imageWidth"];
|
||||
|
||||
/// Text height as a fraction of the short edge: the range the renderer draws without clamping.
|
||||
pub const WATERMARK_SIZE_RANGE: (f32, f32) = (0.005, 0.5);
|
||||
|
||||
/// Margin as a fraction of the short edge.
|
||||
pub const WATERMARK_INSET_RANGE: (f32, f32) = (0.0, 0.4);
|
||||
|
||||
/// A graphic's width as a fraction of the photo's width.
|
||||
pub const WATERMARK_IMAGE_WIDTH_RANGE: (f32, f32) = (0.01, 1.0);
|
||||
|
||||
/// Levenshtein distance, for "did you mean" on a misspelled key (both inputs are short).
|
||||
fn edit_distance(a: &str, b: &str) -> usize {
|
||||
let (a, b): (Vec<char>, Vec<char>) = (a.chars().collect(), b.chars().collect());
|
||||
let mut prev: Vec<usize> = (0..=b.len()).collect();
|
||||
for (i, ca) in a.iter().enumerate() {
|
||||
let mut cur = vec![i + 1; b.len() + 1];
|
||||
for (j, cb) in b.iter().enumerate() {
|
||||
let sub = prev.get(j).copied().unwrap_or(0) + usize::from(ca != cb);
|
||||
let del = prev.get(j + 1).copied().unwrap_or(0) + 1;
|
||||
let ins = cur.get(j).copied().unwrap_or(0) + 1;
|
||||
if let Some(c) = cur.get_mut(j + 1) {
|
||||
*c = sub.min(del).min(ins);
|
||||
}
|
||||
}
|
||||
prev = cur;
|
||||
}
|
||||
prev.last().copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// `unknown parameter \`k\``, naming the closest known key when one is near.
|
||||
fn unknown_key(what: &str, k: &str, known: &[&str]) -> String {
|
||||
let near = known.iter().map(|n| (edit_distance(&k.to_ascii_lowercase(), &n.to_ascii_lowercase()), *n)).filter(|(d, _)| *d <= 2).min();
|
||||
match near {
|
||||
Some((_, n)) => format!("unknown {what} `{k}` (did you mean `{n}`?)"),
|
||||
None => format!("unknown {what} `{k}` (one of {})", known.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A JSON integer (`92`; never `92.5` or `"92"`), as [`ExportOptions::from_json`] reads them.
|
||||
fn whole(v: &serde_json::Value) -> Option<i64> {
|
||||
v.as_i64()
|
||||
}
|
||||
|
||||
/// A `watermark` object as a [`Watermark`]; a legacy `inset` fills whichever of `insetX` and
|
||||
/// `insetY` is missing.
|
||||
fn watermark_from_json(v: &serde_json::Value) -> serde_json::Result<Watermark> {
|
||||
let mut v = v.clone();
|
||||
if let Some(o) = v.as_object_mut()
|
||||
&& let Some(inset) = o.remove("inset")
|
||||
{
|
||||
o.entry("insetX").or_insert_with(|| inset.clone());
|
||||
o.entry("insetY").or_insert(inset);
|
||||
}
|
||||
serde_json::from_value(v)
|
||||
}
|
||||
|
||||
impl ExportOptions {
|
||||
/// Stored export settings (a saved preset, `prefs.json ▸ lastExport`) with the keys an older or
|
||||
/// newer version may have written and this one doesn't know dropped, also inside `watermark`.
|
||||
/// [`ExportOptions::validate`] is strict about what a caller types; settings saved on disk are
|
||||
/// not the caller's typo, and refusing them would make a preset or Export with Previous fail
|
||||
/// for good after an update. A `bitDepth` the stored format doesn't have (written at the
|
||||
/// format's own depth before issue #1952) is dropped too.
|
||||
pub fn known_keys_only(p: &serde_json::Value) -> serde_json::Value {
|
||||
let mut p = Self::known_keys(p);
|
||||
Self::drop_unfit_depth(&mut p, ExportFormat::default());
|
||||
p
|
||||
}
|
||||
|
||||
/// [`ExportOptions::known_keys_only`] keeping `bitDepth`, for a preset whose format may only be
|
||||
/// known once the call's own params (`path`) are merged in.
|
||||
pub(crate) fn known_keys(p: &serde_json::Value) -> serde_json::Value {
|
||||
let mut p = p.clone();
|
||||
if let Some(o) = p.as_object_mut() {
|
||||
o.retain(|k, _| OPTION_PARAMS.contains(&k.as_str()) || TARGET_PARAMS.contains(&k.as_str()));
|
||||
if let Some(w) = o.get_mut("watermark").and_then(serde_json::Value::as_object_mut) {
|
||||
w.retain(|k, _| WATERMARK_PARAMS.contains(&k.as_str()));
|
||||
}
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// Drop a stored `bitDepth` the format `p` exports ([`ExportOptions::export_format`] with
|
||||
/// `fallback`) doesn't have: it was written at the format's own depth before issue #1952.
|
||||
pub(crate) fn drop_unfit_depth(p: &mut serde_json::Value, fallback: ExportFormat) {
|
||||
let format = Self::export_format(p, fallback);
|
||||
if let Some(o) = p.as_object_mut()
|
||||
&& let Some(depth) = o.get("bitDepth").and_then(whole)
|
||||
&& !Self::bit_depths(format).iter().any(|d| i64::from(d.0) == depth)
|
||||
{
|
||||
o.remove("bitDepth");
|
||||
}
|
||||
}
|
||||
|
||||
/// Strict [`ExportOptions::from_json`] for a command that is about to export (issue #181): an
|
||||
/// unknown parameter or a value that cannot be read as what it is for is an error, never a
|
||||
/// silent default. `app.export` targets (`id`, `ids`, `path`, `dir`, `preset`, `background`)
|
||||
/// are accepted and left to the caller.
|
||||
pub fn from_params(p: &serde_json::Value) -> crate::Result<Self> {
|
||||
Self::from_params_or(p, ExportFormat::default())
|
||||
}
|
||||
|
||||
/// [`ExportOptions::from_params`] for a caller that writes `fallback` to a `path` naming no
|
||||
/// format; the format returned is [`ExportOptions::export_format`], the one written.
|
||||
pub fn from_params_or(p: &serde_json::Value, fallback: ExportFormat) -> crate::Result<Self> {
|
||||
let format = Self::export_format(p, fallback);
|
||||
Self::validate_as("app.export", p, Some(format))?;
|
||||
Ok(Self { format, ..Self::from_json(p) })
|
||||
}
|
||||
|
||||
/// The format `app.export` writes: `format` (`null`: the default), else the one the extension of
|
||||
/// `path` names, else `fallback` for a path that names none (the desktop app writes JPEG there,
|
||||
/// the headless backend PNG), else the default.
|
||||
pub fn export_format(p: &serde_json::Value, fallback: ExportFormat) -> ExportFormat {
|
||||
use serde_json::Value;
|
||||
match (p.get("format"), p.get("path").and_then(Value::as_str)) {
|
||||
(Some(f), _) => f.as_str().and_then(ExportFormat::parse).unwrap_or_default(),
|
||||
(None, Some(path)) => std::path::Path::new(path).extension().and_then(|e| e.to_str()).and_then(ExportFormat::parse).unwrap_or(fallback),
|
||||
(None, None) => ExportFormat::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check `app.export` params for `cmd` (the command named in the error): every key must be an
|
||||
/// export option ([`OPTION_PARAMS`]) or a target ([`TARGET_PARAMS`]), every value must be the
|
||||
/// kind of thing its key takes, and a `watermark` object must hold only [`WATERMARK_PARAMS`]
|
||||
/// with its sizes in range (issue #183). `null` means "not given", as a dropped key does.
|
||||
pub fn validate(cmd: &str, p: &serde_json::Value) -> crate::Result<()> {
|
||||
Self::validate_as(cmd, p, Some(Self::export_format(p, ExportFormat::default())))
|
||||
}
|
||||
|
||||
/// [`ExportOptions::validate`] with `bitDepth` checked against `format`, the one exported
|
||||
/// (`None`: not known yet, as for a preset without `format`).
|
||||
pub(crate) fn validate_as(cmd: &str, p: &serde_json::Value, format: Option<ExportFormat>) -> crate::Result<()> {
|
||||
use serde_json::Value;
|
||||
let bad = |msg: String| crate::cmd::bad(cmd, msg);
|
||||
let Some(obj) = p.as_object() else { return Err(bad("params must be an object".into())) };
|
||||
let known: Vec<&str> = OPTION_PARAMS.iter().chain(TARGET_PARAMS).copied().collect();
|
||||
let int = |k: &str, v: &Value, lo: i64, hi: i64| -> crate::Result<i64> {
|
||||
whole(v).filter(|i| (lo..=hi).contains(i)).ok_or_else(|| bad(format!("`{k}` must be an integer {lo}..{hi}")))
|
||||
};
|
||||
let num = |k: &str, v: &Value, lo: f64, hi: f64| -> crate::Result<f64> {
|
||||
v.as_f64().filter(|f| f.is_finite() && (lo..=hi).contains(f)).ok_or_else(|| bad(format!("`{k}` must be a number {lo}..{hi}")))
|
||||
};
|
||||
fn string<'a>(cmd: &str, k: &str, v: &'a Value) -> crate::Result<&'a str> {
|
||||
v.as_str().ok_or_else(|| crate::cmd::bad(cmd, format!("`{k}` must be a string")))
|
||||
}
|
||||
let boolean = |k: &str, v: &Value| -> crate::Result<bool> { v.as_bool().ok_or_else(|| bad(format!("`{k}` must be true or false"))) };
|
||||
let one_of = |k: &str, v: &Value, options: &[&str]| -> crate::Result<()> {
|
||||
let s = string(cmd, k, v)?;
|
||||
if options.iter().any(|o| o.eq_ignore_ascii_case(s)) { Ok(()) } else { Err(bad(format!("`{k}` must be one of {}", options.join("|")))) }
|
||||
};
|
||||
// a choice `from_json` reads with the same `parse`, so what passes here is what gets exported
|
||||
let parses = |k: &str, v: &Value, parse: fn(&str) -> bool, options: &[&str]| -> crate::Result<()> {
|
||||
if parse(string(cmd, k, v)?) { Ok(()) } else { Err(bad(format!("`{k}` must be one of {}", options.join("|")))) }
|
||||
};
|
||||
for (k, v) in obj {
|
||||
if v.is_null() {
|
||||
continue;
|
||||
}
|
||||
match k.as_str() {
|
||||
"format" => {
|
||||
if ExportFormat::parse(string(cmd, k, v)?).is_none() {
|
||||
return Err(bad(format!("`{k}` must be one of jpeg|png|tiff|webp|avif|jxl|dng|original")));
|
||||
}
|
||||
}
|
||||
"quality" => {
|
||||
int(k, v, 1, 100)?;
|
||||
}
|
||||
"ppi" => {
|
||||
int(k, v, 1, u16::MAX as i64)?;
|
||||
}
|
||||
"limitKb" => {
|
||||
int(k, v, 0, u32::MAX as i64)?;
|
||||
}
|
||||
"startNumber" => {
|
||||
int(k, v, 0, 999_999)?;
|
||||
}
|
||||
"bitDepth" => {
|
||||
if !matches!(whole(v), Some(8 | 10 | 16 | 32)) {
|
||||
return Err(bad(format!("`{k}` must be 8, 10, 16 or 32")));
|
||||
}
|
||||
}
|
||||
"longEdge" | "shortEdge" | "width" | "height" | "megapixels" | "percent" => {
|
||||
num(k, v, 0.0, 1.0e9)?;
|
||||
}
|
||||
"fit" => one_of(k, v, &["dimensions", "widthHeight"])?,
|
||||
"resize" => {
|
||||
let Some(r) = v.as_object() else { return Err(bad(format!("`{k}` must be an object {{mode, value, height?, dontEnlarge?}}"))) };
|
||||
if let Some(x) = r.keys().find(|x| !matches!(x.as_str(), "mode" | "value" | "height" | "dontEnlarge")) {
|
||||
return Err(bad(unknown_key("resize key", x, &["mode", "value", "height", "dontEnlarge"])));
|
||||
}
|
||||
serde_json::from_value::<Resize>(v.clone()).map_err(|e| bad(format!("`{k}`: {e}")))?;
|
||||
}
|
||||
"dontEnlarge" | "removeLocation" | "background" | "hdr" | "jxlLossless" | "jxlProgressive" => {
|
||||
boolean(k, v)?;
|
||||
}
|
||||
"addToPhotos" => {
|
||||
if boolean(k, v)?
|
||||
&& let Some(why) = apple_photos_unsupported()
|
||||
{
|
||||
return Err(bad(format!("`{k}`: {why}")));
|
||||
}
|
||||
}
|
||||
"photosAlbum" => {
|
||||
if string(cmd, k, v)?.contains('\0') {
|
||||
return Err(bad(format!("`{k}` can't contain a NUL character")));
|
||||
}
|
||||
}
|
||||
"naming" | "subfolder" | "path" | "dir" | "preset" => {
|
||||
string(cmd, k, v)?;
|
||||
}
|
||||
"sharpen" => parses(k, v, |s| SharpenFor::parse(s).is_some(), &["none", "screen", "matte", "glossy"])?,
|
||||
"sharpenAmount" => parses(k, v, |s| SharpenAmount::parse(s).is_some(), &["low", "standard", "high"])?,
|
||||
"hdrTransfer" => one_of(k, v, &["pq", "hlg"])?,
|
||||
"conflict" => parses(k, v, |s| Conflict::parse(s).is_some(), &["unique", "overwrite", "skip"])?,
|
||||
"destinationMode" => one_of(k, v, &["specificFolder", "sameAsOriginal"])?,
|
||||
"tiffCompression" => one_of(k, v, &["none", "lzw", "zip", "deflate"])?,
|
||||
"jxlEffort" => one_of(k, v, &["fast", "normal"])?,
|
||||
"dngCompression" => {
|
||||
serde_json::from_value::<DngCompression>(v.clone())
|
||||
.map_err(|_| bad(format!("`{k}` must be one of lossless|deflate|uncompressed|lossy")))?;
|
||||
}
|
||||
"metadata" => parses(k, v, |s| MetadataPolicy::parse(s).is_some(), &["all", "allExceptCamera", "copyright", "none"])?,
|
||||
"colorSpace" => {
|
||||
if OutputSpace::parse(string(cmd, k, v)?).is_none() {
|
||||
return Err(bad(format!("`{k}` must be one of srgb|displayP3|adobeRgb|proPhoto|rec2020")));
|
||||
}
|
||||
}
|
||||
"watermark" => Self::validate_watermark(cmd, v)?,
|
||||
"id" => {
|
||||
int(k, v, 0, i64::MAX)?;
|
||||
}
|
||||
"ids" => {
|
||||
let ok = v.as_array().is_some_and(|a| a.iter().all(|x| x.is_u64()));
|
||||
if !ok {
|
||||
return Err(bad(format!("`{k}` must be an array of photo ids")));
|
||||
}
|
||||
}
|
||||
_ => return Err(bad(unknown_key("parameter", k, &known))),
|
||||
}
|
||||
}
|
||||
// issue #1952: a depth the format doesn't have would be written at the format's own depth
|
||||
if let (Some(format), Some(depth)) = (format, obj.get("bitDepth").and_then(whole)) {
|
||||
let mut depths: Vec<u8> = Self::bit_depths(format).iter().map(|d| d.0).collect();
|
||||
if !depths.iter().any(|d| i64::from(*d) == depth) {
|
||||
depths.sort_unstable();
|
||||
let mut list: Vec<String> = depths.iter().map(u8::to_string).collect();
|
||||
let last = list.pop().unwrap_or_default();
|
||||
let list = if list.is_empty() { last } else { format!("{} or {last}", list.join(", ")) };
|
||||
let name = serde_json::to_value(format).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
|
||||
return Err(bad(format!("`bitDepth` must be {list} for {name}")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A `watermark` value: text, or an object of [`WATERMARK_PARAMS`] (issue #183).
|
||||
pub(crate) fn validate_watermark(cmd: &str, v: &serde_json::Value) -> crate::Result<()> {
|
||||
use serde_json::Value;
|
||||
let bad = |msg: String| crate::cmd::bad(cmd, msg);
|
||||
let obj = match v {
|
||||
Value::String(_) => return Ok(()),
|
||||
Value::Object(o) => o,
|
||||
_ => {
|
||||
return Err(bad(
|
||||
"`watermark` must be text or an object {text, vertical, size, opacity, anchor, insetX, insetY, inset, rotation, color, shadow, image, imageWidth}".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
let frac = |k: &str, v: &Value, (lo, hi): (f32, f32), unit: &str| -> crate::Result<()> {
|
||||
match v.as_f64() {
|
||||
Some(f) if f.is_finite() && (f64::from(lo)..=f64::from(hi)).contains(&f) => Ok(()),
|
||||
_ => Err(bad(format!("`watermark.{k}` must be a number {lo}..{hi} ({unit})"))),
|
||||
}
|
||||
};
|
||||
for (k, v) in obj {
|
||||
if v.is_null() {
|
||||
continue;
|
||||
}
|
||||
match k.as_str() {
|
||||
"text" | "image" => {
|
||||
v.as_str().ok_or_else(|| bad(format!("`watermark.{k}` must be a string")))?;
|
||||
}
|
||||
"vertical" | "shadow" => {
|
||||
v.as_bool().ok_or_else(|| bad(format!("`watermark.{k}` must be true or false")))?;
|
||||
}
|
||||
"size" => frac(k, v, WATERMARK_SIZE_RANGE, "fraction of the short edge")?,
|
||||
"opacity" => frac(k, v, (0.0, 1.0), "0 = invisible, 1 = solid")?,
|
||||
"insetX" | "insetY" | "inset" => frac(k, v, WATERMARK_INSET_RANGE, "fraction of the short edge")?,
|
||||
"imageWidth" => frac(k, v, WATERMARK_IMAGE_WIDTH_RANGE, "fraction of the photo's width")?,
|
||||
"rotation" => {
|
||||
if !matches!(whole(v), Some(0 | 90 | 180 | 270)) {
|
||||
return Err(bad("`watermark.rotation` must be 0, 90, 180 or 270 (degrees clockwise)".into()));
|
||||
}
|
||||
}
|
||||
"anchor" => {
|
||||
serde_json::from_value::<Anchor>(v.clone()).map_err(|_| {
|
||||
bad("`watermark.anchor` must be one of topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight".into())
|
||||
})?;
|
||||
}
|
||||
"color" => {
|
||||
let ok = v.as_array().is_some_and(|a| a.len() == 3 && a.iter().all(|c| matches!(whole(c), Some(0..=255))));
|
||||
if !ok {
|
||||
return Err(bad("`watermark.color` must be [r, g, b] with 0..255 each (sRGB)".into()));
|
||||
}
|
||||
}
|
||||
_ => return Err(bad(unknown_key("watermark key", k, WATERMARK_PARAMS))),
|
||||
}
|
||||
}
|
||||
watermark_from_json(v).map(|_| ()).map_err(|e| bad(format!("`watermark`: {e}")))
|
||||
}
|
||||
|
||||
/// Read options from command params (`format`, `quality`, `limitKb`, `sharpen`, `sharpenAmount`,
|
||||
/// `naming`, `metadata`, `removeLocation`, `watermark`, `colorSpace`, `bitDepth`, `ppi`,
|
||||
/// `addToPhotos`, `photosAlbum`) and the
|
||||
/// size: one of `longEdge`, `shortEdge`, `width`, `height` (both = fit inside W × H),
|
||||
/// `megapixels`, `percent` (absent or 0 = full size), or a [`Resize`] object as `resize`; plus
|
||||
/// `dontEnlarge` (default true).
|
||||
///
|
||||
/// Lenient: anything unknown or unreadable falls back to the default, which suits stored
|
||||
/// prefs and dialog prefill. A command that is about to export uses
|
||||
/// [`ExportOptions::from_params`], which validates first.
|
||||
pub fn from_json(p: &serde_json::Value) -> Self {
|
||||
use serde_json::Value;
|
||||
let d = Self::default();
|
||||
let s = |k: &str| p.get(k).and_then(Value::as_str);
|
||||
let u = |k: &str| p.get(k).and_then(Value::as_u64);
|
||||
fn enm<T: serde::de::DeserializeOwned>(p: &Value, k: &str) -> Option<T> {
|
||||
p.get(k).cloned().and_then(|v| serde_json::from_value(v).ok())
|
||||
}
|
||||
Self {
|
||||
format: s("format").and_then(ExportFormat::parse).unwrap_or(d.format),
|
||||
quality: u("quality").map_or(d.quality, |q| q.clamp(1, 100) as u8),
|
||||
resize: Self::resize_from_json(p),
|
||||
ppi: u("ppi").filter(|v| *v > 0).map_or(d.ppi, |v| v.min(u16::MAX as u64) as u16),
|
||||
limit_kb: u("limitKb").filter(|v| *v > 0).map(|v| v.min(u32::MAX as u64) as u32),
|
||||
sharpen: s("sharpen").and_then(SharpenFor::parse).unwrap_or(d.sharpen),
|
||||
sharpen_amount: s("sharpenAmount").and_then(SharpenAmount::parse).unwrap_or(d.sharpen_amount),
|
||||
naming: s("naming").map_or(d.naming, str::to_string),
|
||||
start_number: u("startNumber").map_or(d.start_number, |v| v.min(999_999) as u32),
|
||||
destination_mode: s("destinationMode").and_then(DestinationMode::parse).unwrap_or(d.destination_mode),
|
||||
subfolder: s("subfolder").map_or(d.subfolder, |v| v.trim().replace(['\\', ':', '\0'], "_")),
|
||||
conflict: s("conflict").and_then(Conflict::parse).unwrap_or(d.conflict),
|
||||
tiff_compression: match s("tiffCompression").map(str::to_ascii_lowercase).as_deref() {
|
||||
Some("none") => TiffCompression::None,
|
||||
Some("lzw") => TiffCompression::Lzw,
|
||||
Some("zip" | "deflate") => TiffCompression::Deflate,
|
||||
_ => d.tiff_compression,
|
||||
},
|
||||
dng_compression: enm(p, "dngCompression").unwrap_or(d.dng_compression),
|
||||
metadata: s("metadata").and_then(MetadataPolicy::parse).unwrap_or(d.metadata),
|
||||
remove_location: p.get("removeLocation").and_then(Value::as_bool).unwrap_or(d.remove_location),
|
||||
watermark: match p.get("watermark") {
|
||||
Some(Value::String(t)) => Some(Watermark { text: t.clone(), ..Default::default() }),
|
||||
Some(v @ Value::Object(_)) => watermark_from_json(v).ok(),
|
||||
_ => None,
|
||||
}
|
||||
.filter(|w: &Watermark| !w.text.trim().is_empty() || !w.image.trim().is_empty()),
|
||||
color_space: s("colorSpace").and_then(OutputSpace::parse).unwrap_or(d.color_space),
|
||||
bit_depth: u("bitDepth").filter(|b| matches!(b, 8 | 10 | 16 | 32)).map(|b| b as u8),
|
||||
hdr: p.get("hdr").and_then(Value::as_bool).unwrap_or(d.hdr),
|
||||
jxl_lossless: p.get("jxlLossless").and_then(Value::as_bool).unwrap_or(d.jxl_lossless),
|
||||
jxl_effort: s("jxlEffort").and_then(JxlEffort::parse).unwrap_or(d.jxl_effort),
|
||||
jxl_progressive: p.get("jxlProgressive").and_then(Value::as_bool).unwrap_or(d.jxl_progressive),
|
||||
add_to_photos: p.get("addToPhotos").and_then(Value::as_bool).unwrap_or(d.add_to_photos),
|
||||
photos_album: s("photosAlbum").map_or(d.photos_album, |a| a.trim().to_string()),
|
||||
hdr_transfer: s("hdrTransfer").and_then(HdrCurve::parse).unwrap_or(d.hdr_transfer),
|
||||
}
|
||||
}
|
||||
|
||||
fn resize_from_json(p: &serde_json::Value) -> Option<Resize> {
|
||||
use serde_json::Value;
|
||||
let f = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| *v > 0.0);
|
||||
let dont_enlarge = p.get("dontEnlarge").and_then(Value::as_bool).unwrap_or(true);
|
||||
if let Some(r) = p.get("resize").filter(|v| v.is_object()) {
|
||||
let r: Resize = serde_json::from_value(r.clone()).ok()?;
|
||||
return (r.value > 0.0).then_some(Resize { dont_enlarge: p.get("dontEnlarge").and_then(Value::as_bool).unwrap_or(r.dont_enlarge), ..r });
|
||||
}
|
||||
let r = |mode, value: f64| Resize { mode, value: value.min(65_535.0) as f32, height: 0, dont_enlarge };
|
||||
// `fit: widthHeight` binds each edge to its own number; the default fits either orientation
|
||||
let bound = p.get("fit").and_then(Value::as_str).is_some_and(|fit| fit.eq_ignore_ascii_case("widthHeight"));
|
||||
Some(match (f("width"), f("height")) {
|
||||
(Some(w), Some(h)) => {
|
||||
Resize { height: h.min(65_535.0) as u32, ..r(if bound { ResizeMode::WidthHeight } else { ResizeMode::Dimensions }, w) }
|
||||
}
|
||||
(Some(w), None) => r(ResizeMode::Width, w),
|
||||
(None, Some(h)) => r(ResizeMode::Height, h),
|
||||
(None, None) => {
|
||||
if let Some(v) = f("longEdge") {
|
||||
r(ResizeMode::LongEdge, v)
|
||||
} else if let Some(v) = f("shortEdge") {
|
||||
r(ResizeMode::ShortEdge, v)
|
||||
} else if let Some(v) = f("megapixels") {
|
||||
r(ResizeMode::Megapixels, v)
|
||||
} else {
|
||||
let v = f("percent")?;
|
||||
r(ResizeMode::Percent, v)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// These options as `app.export` params ([`ExportOptions::from_json`] reads them back
|
||||
/// unchanged; full size is written as `longEdge: 0`).
|
||||
pub fn to_json(&self) -> serde_json::Value {
|
||||
let mut v = serde_json::to_value(self).unwrap_or_default();
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.remove("resize");
|
||||
if let Some(sz) = Self::resize_json(self.resize.as_ref()).as_object() {
|
||||
o.extend(sz.clone());
|
||||
}
|
||||
if self.resize.is_none() {
|
||||
o.insert("longEdge".into(), 0.into());
|
||||
}
|
||||
o.retain(|_, v| !v.is_null());
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Whether `p` names an output size (any of the size params, even 0 = full size).
|
||||
pub fn has_size_param(p: &serde_json::Value) -> bool {
|
||||
["resize", "longEdge", "shortEdge", "width", "height", "megapixels", "percent"].iter().any(|k| p.get(k).is_some())
|
||||
}
|
||||
|
||||
/// The size params of [`ExportOptions::from_json`] for `resize` (`{}` = full size).
|
||||
pub fn resize_json(resize: Option<&Resize>) -> serde_json::Value {
|
||||
match resize {
|
||||
None => serde_json::json!({}),
|
||||
Some(r) => serde_json::json!({"resize": r, "dontEnlarge": r.dont_enlarge}),
|
||||
}
|
||||
}
|
||||
|
||||
/// The sample format the file is written with (unsupported requests fall back to the closest).
|
||||
pub fn effective_depth(&self) -> OutputDepth {
|
||||
match (self.format, self.bit_depth) {
|
||||
(ExportFormat::Jpeg | ExportFormat::Webp | ExportFormat::Original | ExportFormat::Dng, _) => OutputDepth::U8,
|
||||
(ExportFormat::Png, _) if self.hdr => OutputDepth::F32Hdr,
|
||||
(ExportFormat::Png, Some(16 | 32)) => OutputDepth::U16,
|
||||
(ExportFormat::Png, _) => OutputDepth::U8,
|
||||
(ExportFormat::Tiff, Some(8)) => OutputDepth::U8,
|
||||
(ExportFormat::Tiff, Some(32)) if self.hdr => OutputDepth::F32Hdr,
|
||||
(ExportFormat::Tiff, Some(32)) => OutputDepth::F32Linear,
|
||||
(ExportFormat::Tiff, _) => OutputDepth::U16,
|
||||
(ExportFormat::RenderedDng, _) if self.hdr => OutputDepth::F32Hdr,
|
||||
(ExportFormat::RenderedDng, _) => OutputDepth::F32Linear,
|
||||
(ExportFormat::Psd, Some(8)) => OutputDepth::U8,
|
||||
(ExportFormat::Psd, _) => OutputDepth::U16,
|
||||
(ExportFormat::Avif, _) if self.hdr => OutputDepth::F32Hdr,
|
||||
(ExportFormat::Avif, Some(10 | 16 | 32)) => OutputDepth::U16,
|
||||
(ExportFormat::Avif, _) => OutputDepth::U8,
|
||||
(ExportFormat::Jxl, _) if self.hdr => OutputDepth::F32Hdr,
|
||||
(ExportFormat::Jxl, Some(10 | 16 | 32)) => OutputDepth::U16,
|
||||
(ExportFormat::Jxl, _) => OutputDepth::U8,
|
||||
}
|
||||
}
|
||||
|
||||
/// The bit depths `format` offers (value, label); the first is its default.
|
||||
pub fn bit_depths(format: ExportFormat) -> &'static [(u8, &'static str)] {
|
||||
match format {
|
||||
ExportFormat::Jpeg | ExportFormat::Webp | ExportFormat::Original | ExportFormat::Dng => &[(8, "8-bit")],
|
||||
ExportFormat::Png => &[(8, "8-bit"), (16, "16-bit")],
|
||||
ExportFormat::Tiff => &[(16, "16-bit"), (8, "8-bit"), (32, "32-bit float")],
|
||||
ExportFormat::Psd => &[(16, "16-bit"), (8, "8-bit")],
|
||||
ExportFormat::RenderedDng => &[(16, "16-bit float")],
|
||||
ExportFormat::Avif => &[(8, "8-bit"), (10, "10-bit")],
|
||||
ExportFormat::Jxl => &[(8, "8-bit"), (16, "16-bit")],
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether these options write HDR files (for photos edited in HDR): JPEG (gain map), AVIF,
|
||||
/// PNG or JPEG XL (PQ) or 32-bit float TIFF with [`ExportOptions::hdr`].
|
||||
pub fn hdr_output(&self) -> bool {
|
||||
self.hdr
|
||||
&& matches!(
|
||||
(self.format, self.bit_depth),
|
||||
(ExportFormat::Jpeg | ExportFormat::Avif | ExportFormat::Png | ExportFormat::Jxl, _) | (ExportFormat::Tiff, Some(32))
|
||||
)
|
||||
}
|
||||
|
||||
/// The colour space the file is actually written in (AVIF: sRGB; AVIF, PNG and JPEG XL HDR:
|
||||
/// Rec. 2020; lossy JPEG XL: Adobe RGB and ProPhoto as Rec. 2020, the widest space its encoder
|
||||
/// can declare without a profile).
|
||||
pub fn effective_space(&self) -> OutputSpace {
|
||||
match self.format {
|
||||
ExportFormat::Avif | ExportFormat::Png | ExportFormat::Jxl if self.hdr => OutputSpace::Rec2020,
|
||||
ExportFormat::Avif => OutputSpace::Srgb,
|
||||
ExportFormat::Jxl if !self.jxl_lossless && matches!(self.color_space, OutputSpace::AdobeRgb | OutputSpace::ProPhoto) => {
|
||||
OutputSpace::Rec2020
|
||||
}
|
||||
_ => self.color_space,
|
||||
}
|
||||
}
|
||||
|
||||
/// The JPEG XL encoder settings for these options, writing samples in `space`.
|
||||
pub(super) fn jxl(&self, space: OutputSpace, hdr: bool) -> JxlOptions {
|
||||
let colour = match space {
|
||||
_ if hdr => JxlColour::Rec2020Pq,
|
||||
OutputSpace::DisplayP3 => JxlColour::DisplayP3,
|
||||
OutputSpace::Rec2020 => JxlColour::Rec2020,
|
||||
// lossless files carry the ICC profile; lossy ones never get here (`effective_space`)
|
||||
OutputSpace::Srgb | OutputSpace::AdobeRgb | OutputSpace::ProPhoto => JxlColour::Srgb,
|
||||
};
|
||||
JxlOptions { quality: self.quality, lossless: self.jxl_lossless, effort: self.jxl_effort, progressive: self.jxl_progressive, colour }
|
||||
}
|
||||
|
||||
/// Output file name for photo `p` at 1-based position `seq` in a batch (the original's
|
||||
/// extension is kept for [`ExportFormat::Original`]).
|
||||
pub fn file_name_for(&self, p: &lightcraft_catalog::Photo, seq: usize) -> String {
|
||||
let base = if self.naming.trim().is_empty() { "{name}" } else { self.naming.as_str() };
|
||||
let n = seq + self.start_number.max(1) as usize - 1;
|
||||
let name = crate::rename::expand_tokens(base, p, n, 3);
|
||||
let mut name: String = name.chars().map(|c| if matches!(c, '/' | '\\' | ':' | '\0') { '_' } else { c }).collect();
|
||||
let (stem, ext) = p.file_name.rsplit_once('.').unwrap_or((&p.file_name, ""));
|
||||
if name.trim().is_empty() {
|
||||
// every token came out empty (no title, no capture time…): keep the original name
|
||||
name = stem.to_string();
|
||||
}
|
||||
if self.format == ExportFormat::Original {
|
||||
let base = name.trim_end_matches('.');
|
||||
if ext.is_empty() { base.to_string() } else { format!("{base}.{ext}") }
|
||||
} else {
|
||||
format!("{name}.{}", self.format.extension())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
use super::options::{Conflict, DestinationMode};
|
||||
use super::prepare::{Destination, Exported};
|
||||
use super::*;
|
||||
|
||||
/// Write an exported or rendered file on disk: its folder is created if needed, and the file is
|
||||
/// replaced atomically ([`lightcraft_catalog::safe_file::write_atomic_nosync`]: a temp file
|
||||
/// renamed into place), so a failure part-way leaves any previous file intact and no truncated
|
||||
/// one. Not synced to disk (issue #134): an export can always be made again from the original.
|
||||
/// The native writer behind exports, renders and screenshots (app, CLI, MCP).
|
||||
pub fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
write_with(path, bytes, false)
|
||||
}
|
||||
|
||||
/// [`write_file`], synced to disk: for a written file that becomes a library photo (Edit a Copy)
|
||||
/// and so can't simply be exported again once the catalog points at it.
|
||||
pub fn write_file_durable(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
write_with(path, bytes, true)
|
||||
}
|
||||
|
||||
/// Write `path` only when nothing exists there: the destination is prepared as a complete temp
|
||||
/// file and published with create-new semantics, so a file that appears after a caller's check is
|
||||
/// never replaced. Screenshots of an initially absent path use this instead of the overwriting
|
||||
/// writer.
|
||||
pub fn write_file_new(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||||
let p = std::path::Path::new(path);
|
||||
if let Some(dir) = p.parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
lightcraft_catalog::safe_file::write_new(p, bytes).map_err(|e| format!("{path}: {e}"))
|
||||
}
|
||||
|
||||
fn write_with(path: &str, bytes: &[u8], durable: bool) -> Result<(), String> {
|
||||
use lightcraft_catalog::safe_file::{write_atomic, write_atomic_nosync};
|
||||
let p = std::path::Path::new(path);
|
||||
if let Some(dir) = p.parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
}
|
||||
if durable { write_atomic(p, bytes) } else { write_atomic_nosync(p, bytes) }.map_err(|e| format!("{path}: {e}"))
|
||||
}
|
||||
|
||||
/// The path of the sidecar with extension `ext` of the exported file `main`.
|
||||
fn sidecar_path(main: &str, ext: &str) -> String {
|
||||
std::path::Path::new(main).with_extension(ext).to_string_lossy().to_string()
|
||||
}
|
||||
|
||||
/// Where a batch's files go: each photo's path (destination folder, subfolder, conflict policy,
|
||||
/// sidecars, never an original) and its write, in batch order.
|
||||
pub(super) struct Placer<'a> {
|
||||
o: &'a ExportOptions,
|
||||
to: &'a Destination,
|
||||
pub(super) single: bool,
|
||||
taken: std::collections::HashSet<String>,
|
||||
pub(super) out: Vec<serde_json::Value>,
|
||||
write: &'a mut dyn FnMut(&str, &[u8]) -> Result<(), String>,
|
||||
exists: &'a dyn Fn(&str) -> bool,
|
||||
stop_on_error: bool,
|
||||
}
|
||||
|
||||
fn join_path(a: &str, b: &str) -> String {
|
||||
if a.is_empty() { b.to_string() } else { format!("{}/{b}", a.trim_end_matches('/')) }
|
||||
}
|
||||
|
||||
impl<'a> Placer<'a> {
|
||||
pub(super) fn new(
|
||||
o: &'a ExportOptions,
|
||||
to: &'a Destination,
|
||||
write: &'a mut dyn FnMut(&str, &[u8]) -> Result<(), String>,
|
||||
exists: &'a dyn Fn(&str) -> bool,
|
||||
stop_on_error: bool,
|
||||
) -> Placer<'a> {
|
||||
Placer { o, to, single: false, taken: Default::default(), out: Vec::new(), write, exists, stop_on_error }
|
||||
}
|
||||
|
||||
/// The folder photo `name` (its original in `source_dir`) is written to: the batch's folder or
|
||||
/// the photo's own ([`DestinationMode`]), plus the subfolder. An error for a photo with no
|
||||
/// folder of its own, or whose folder is gone: never a file written somewhere else instead.
|
||||
fn folder_for(&self, name: &str, source_dir: Option<&str>) -> Result<String, String> {
|
||||
let base = match self.o.destination_mode {
|
||||
DestinationMode::SpecificFolder => self.to.dir.clone(),
|
||||
DestinationMode::SameAsOriginal => {
|
||||
let Some(d) = source_dir else {
|
||||
return Err(format!(
|
||||
"{name}: the photo has no folder on disk (a demo photo or one in the browser's storage), so it can't be exported to the same folder as its original; choose a specific folder"
|
||||
));
|
||||
};
|
||||
if !(self.exists)(d) {
|
||||
return Err(format!("{name}: the original's folder is missing ({d}); reconnect it or choose a specific folder"));
|
||||
}
|
||||
d.to_string()
|
||||
}
|
||||
};
|
||||
Ok(if self.o.subfolder.is_empty() { base } else { join_path(&base, &self.o.subfolder) })
|
||||
}
|
||||
|
||||
/// Place photo `photo`'s export result (file `name`, its original in `source_dir`): write it
|
||||
/// and record the outcome. `Err` only when it failed and `stop_on_error` is set.
|
||||
pub(super) fn place(
|
||||
&mut self,
|
||||
photo: lightcraft_catalog::PhotoId,
|
||||
name: String,
|
||||
source_dir: Option<&str>,
|
||||
guard: &crate::originals::OriginalGuard,
|
||||
e: Result<Exported, String>,
|
||||
) -> Result<(), String> {
|
||||
use serde_json::json;
|
||||
// an exact file path needs no folder
|
||||
let dir = if self.to.exact.is_some() && self.single { Ok(String::new()) } else { self.folder_for(&name, source_dir) };
|
||||
let (o, exists) = (self.o, self.exists);
|
||||
let (dir, e) = match dir.and_then(|dir| e.map(|e| (dir, e))) {
|
||||
Ok(v) => v,
|
||||
Err(err) if self.stop_on_error => return Err(err),
|
||||
Err(err) => {
|
||||
self.out.push(json!({"photo": photo.0, "file": name, "error": err}));
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let dir = dir.as_str();
|
||||
// the exported file and its sidecars
|
||||
let group = |main: &str| std::iter::once(main.to_string()).chain(e.sidecars.iter().map(|(x, _)| sidecar_path(main, x))).collect::<Vec<_>>();
|
||||
let path = match self.to.exact.as_deref().filter(|_| self.single) {
|
||||
Some(p) => Ok(p.to_string()),
|
||||
None => {
|
||||
let path = join_path(dir, &e.file_name);
|
||||
let taken = &self.taken;
|
||||
let busy = |main: &str| group(main).iter().any(|p| taken.contains(p) || exists(p));
|
||||
if !busy(&path) {
|
||||
Ok(path)
|
||||
} else {
|
||||
match o.conflict {
|
||||
Conflict::Overwrite => Ok(path),
|
||||
Conflict::Skip => {
|
||||
self.out.push(json!({"skipped": path}));
|
||||
return Ok(());
|
||||
}
|
||||
Conflict::Unique => {
|
||||
let (stem, ext) = e.file_name.rsplit_once('.').map_or((e.file_name.as_str(), None), |(a, b)| (a, Some(b)));
|
||||
let name = |n: usize| join_path(dir, &ext.map_or(format!("{stem}-{n}"), |x| format!("{stem}-{n}.{x}")));
|
||||
(2..1_000_000).map(name).find(|p| !busy(p)).ok_or_else(|| format!("{path}: no free file name"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let file = path.clone().unwrap_or_else(|_| name.clone());
|
||||
let write = &mut *self.write;
|
||||
let written = path.and_then(|path| {
|
||||
let files = group(&path);
|
||||
// never over an original, whatever the conflict policy or the exact path said
|
||||
for f in &files {
|
||||
guard.check(std::path::Path::new(f))?;
|
||||
}
|
||||
write(&path, &e.bytes)?;
|
||||
let mut sidecars = Vec::new();
|
||||
for ((_, bytes), sc) in e.sidecars.iter().zip(files.iter().skip(1)) {
|
||||
write(sc, bytes)?;
|
||||
sidecars.push(sc.clone());
|
||||
}
|
||||
Ok((path, files, sidecars))
|
||||
});
|
||||
match written {
|
||||
Ok((path, files, sidecars)) => {
|
||||
self.taken.extend(files);
|
||||
let mut entry = json!({"path": path, "width": e.width, "height": e.height, "bytes": e.bytes.len(), "sidecars": sidecars});
|
||||
if let Some(why) = &e.gpu_fallback {
|
||||
entry["gpuFallback"] = json!(why);
|
||||
}
|
||||
self.out.push(entry);
|
||||
}
|
||||
Err(err) if self.stop_on_error => return Err(err),
|
||||
Err(err) => self.out.push(json!({"photo": photo.0, "file": file, "error": err})),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
use super::batch::run_batch;
|
||||
use super::encoding::{encode_gain_map_jpeg, encode_rendered, export_metadata, removes_location};
|
||||
use super::options::ExportFormat;
|
||||
use super::params::apple_photos_unsupported;
|
||||
use super::*;
|
||||
|
||||
/// One exported file.
|
||||
pub struct Exported {
|
||||
pub file_name: String,
|
||||
pub bytes: Vec<u8>,
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
/// Files written next to it, named like it with another extension: `(extension, bytes)` (the
|
||||
/// XMP sidecar of an `Original` export).
|
||||
pub sidecars: Vec<(&'static str, Vec<u8>)>,
|
||||
/// Set when the render was tried on the GPU and fell back to the CPU: why (see
|
||||
/// `docs/gpu-pipeline.md`). The file holds the CPU render either way.
|
||||
pub gpu_fallback: Option<String>,
|
||||
}
|
||||
|
||||
/// Output size of photo `p` under `o` (its cropped full size when `o.resize` is `None`).
|
||||
pub fn output_size(p: &lightcraft_catalog::Photo, o: &ExportOptions) -> (usize, usize) {
|
||||
let (w, h) = lightcraft_pipeline::native_output_size(p.width.max(1) as usize, p.height.max(1) as usize, &p.develop);
|
||||
// whole pixels first: a crop's float noise (5999.999… for 6000) must not decide a half-pixel tie
|
||||
let (w, h) = (w.round().max(1.0), h.round().max(1.0));
|
||||
match &o.resize {
|
||||
Some(r) => r.apply(w, h),
|
||||
None => (w as usize, h as usize),
|
||||
}
|
||||
}
|
||||
|
||||
/// Render photo `id` at the requested size and encode it (or copy / convert its original for
|
||||
/// [`ExportFormat::Original`] / [`ExportFormat::Dng`]).
|
||||
pub fn export_photo(session: &mut crate::Session, id: lightcraft_catalog::PhotoId, o: &ExportOptions, seq: usize) -> Result<Exported, String> {
|
||||
prepare_export(session, id, o, seq)?.run()
|
||||
}
|
||||
|
||||
/// One photo's export, set up from the session ([`prepare_export`]). [`PreparedExport::run`] does
|
||||
/// the heavy part (read, decode, render, encode) without the session, so it can run on another
|
||||
/// thread.
|
||||
pub struct PreparedExport {
|
||||
pub photo: lightcraft_catalog::PhotoId,
|
||||
pub file_name: String,
|
||||
/// The folder of the photo's original on disk ([`DestinationMode::SameAsOriginal`]); `None`
|
||||
/// for a demo photo or one in the browser's storage.
|
||||
pub source_dir: Option<String>,
|
||||
work: Work,
|
||||
/// The library's originals, which [`run_batch`] never writes over (shared by a batch).
|
||||
pub(super) guard: std::sync::Arc<crate::originals::OriginalGuard>,
|
||||
/// Estimated working memory of [`Self::run`] (bytes), held from [`crate::memory::export_gate`]
|
||||
/// while it runs beside other photos of a batch.
|
||||
pub(super) weight: usize,
|
||||
}
|
||||
|
||||
struct RenderWork {
|
||||
job: crate::media::RenderJob,
|
||||
/// The HDR rendition of a gain map JPEG (`job` renders its SDR base).
|
||||
hdr_job: Option<crate::media::RenderJob>,
|
||||
meta: Option<Metadata>,
|
||||
opts: ExportOptions,
|
||||
}
|
||||
|
||||
enum Work {
|
||||
Render(Box<RenderWork>),
|
||||
/// [`ExportFormat::Original`] (the file's bytes + an XMP sidecar) or [`ExportFormat::Dng`] (the
|
||||
/// raw data re-encoded as a lossless DNG with the edits in its XMP).
|
||||
File {
|
||||
path: String,
|
||||
read: Option<crate::merge::ByteReader>,
|
||||
packet: String,
|
||||
dng: Option<DngCompression>,
|
||||
/// Lossy DNG: JPEG quality and the long edge to scale to (`None`: full size).
|
||||
quality: u8,
|
||||
lossy_edge: Option<u32>,
|
||||
/// The original must not carry a location ([`removes_location`]).
|
||||
remove_location: bool,
|
||||
label: String,
|
||||
size: (usize, usize),
|
||||
},
|
||||
}
|
||||
|
||||
/// Set up the export of photo `id` at 1-based position `seq` of a batch. (For a whole batch use
|
||||
/// [`prepare_batch`]: it looks at the library's originals once.)
|
||||
pub fn prepare_export(
|
||||
session: &mut crate::Session,
|
||||
id: lightcraft_catalog::PhotoId,
|
||||
o: &ExportOptions,
|
||||
seq: usize,
|
||||
) -> Result<PreparedExport, String> {
|
||||
let guard = std::sync::Arc::new(session.original_guard());
|
||||
prepare_guarded(session, id, o, seq, guard)
|
||||
}
|
||||
|
||||
/// [`prepare_export`] for each of `ids` in order (`{seq}` = position, from 1).
|
||||
pub fn prepare_batch(session: &mut crate::Session, ids: &[lightcraft_catalog::PhotoId], o: &ExportOptions) -> Result<Vec<PreparedExport>, String> {
|
||||
let guard = std::sync::Arc::new(session.original_guard());
|
||||
ids.iter().enumerate().map(|(i, id)| prepare_guarded(session, *id, o, i + 1, guard.clone())).collect()
|
||||
}
|
||||
|
||||
fn prepare_guarded(
|
||||
session: &mut crate::Session,
|
||||
id: lightcraft_catalog::PhotoId,
|
||||
o: &ExportOptions,
|
||||
seq: usize,
|
||||
guard: std::sync::Arc<crate::originals::OriginalGuard>,
|
||||
) -> Result<PreparedExport, String> {
|
||||
let p = session.catalog.photo(id).ok_or("no such photo")?;
|
||||
let file_name = o.file_name_for(p, seq);
|
||||
let source_dir = original_folder(&p.source);
|
||||
// HDR output only for photos edited in HDR; the rest of the batch exports as usual
|
||||
let sdr_opts;
|
||||
let o = if o.hdr && !p.develop.hdr.enabled {
|
||||
sdr_opts = ExportOptions { hdr: false, ..o.clone() };
|
||||
&sdr_opts
|
||||
} else {
|
||||
o
|
||||
};
|
||||
let (full_px, long) = ((p.width as usize).saturating_mul(p.height as usize), p.width.max(p.height) as usize);
|
||||
let (work, weight) = if o.format.is_rendered() {
|
||||
let (w, h) = output_size(p, o);
|
||||
let (nw, nh) = lightcraft_pipeline::native_output_size(p.width.max(1) as usize, p.height.max(1) as usize, &p.develop);
|
||||
let native_px = (nw.round().max(1.0) * nh.round().max(1.0)) as usize;
|
||||
let label = p.file_name.clone();
|
||||
let meta = export_metadata(p, &session.catalog, o);
|
||||
let gain_map = o.hdr_output() && o.format == ExportFormat::Jpeg;
|
||||
let job = session.export_job(id, w, h, o.effective_space(), o.effective_depth())?;
|
||||
let weight = render_weight(full_px, long, job.level, w.saturating_mul(h));
|
||||
if let Some(why) = too_big_for_memory((w, h), native_px, weight, crate::memory::total_ram()) {
|
||||
return Err(format!("{label}: {why}"));
|
||||
}
|
||||
let hdr_job = if gain_map { Some(session.export_job(id, w, h, o.effective_space(), OutputDepth::F32Hdr)?) } else { None };
|
||||
(Work::Render(Box::new(RenderWork { job, hdr_job, meta, opts: o.clone() })), weight)
|
||||
} else {
|
||||
let lightcraft_catalog::Source::File { path } = &p.source else {
|
||||
return Err(format!("{} is a generated demo photo: it has no original file to export", p.file_name));
|
||||
};
|
||||
let dng = (o.format == ExportFormat::Dng).then_some(o.dng_compression);
|
||||
// the file's bytes; a DNG also decodes the raw data (16-bit samples) and writes it again
|
||||
let weight = (p.file_size as usize).saturating_add(if dng.is_some() { full_px.saturating_mul(6) } else { 0 });
|
||||
let work = Work::File {
|
||||
path: path.clone(),
|
||||
read: session.media.file_bytes.clone(),
|
||||
packet: crate::sidecar::sidecar_packet_with(p, &session.catalog, removes_location(p, &session.catalog, o)),
|
||||
dng,
|
||||
quality: o.quality,
|
||||
lossy_edge: o.resize.is_some().then(|| {
|
||||
let (w, h) = output_size(p, o);
|
||||
u32::try_from(w.max(h)).unwrap_or(u32::MAX)
|
||||
}),
|
||||
remove_location: removes_location(p, &session.catalog, o),
|
||||
label: p.file_name.clone(),
|
||||
size: (p.width as usize, p.height as usize),
|
||||
};
|
||||
(work, weight)
|
||||
};
|
||||
Ok(PreparedExport { photo: id, file_name, source_dir, work, guard, weight })
|
||||
}
|
||||
|
||||
/// The folder a photo's original is in, for [`DestinationMode::SameAsOriginal`]. None for a demo
|
||||
/// photo, and on the web, where an original lives in the browser's storage, not in a folder.
|
||||
fn original_folder(source: &lightcraft_catalog::Source) -> Option<String> {
|
||||
let lightcraft_catalog::Source::File { path } = source else { return None };
|
||||
if cfg!(target_arch = "wasm32") {
|
||||
return None;
|
||||
}
|
||||
let dir = std::path::Path::new(path).parent()?.to_string_lossy().to_string();
|
||||
(!dir.is_empty()).then_some(dir)
|
||||
}
|
||||
|
||||
/// Why an export of `out` pixels (`w`, `h`), from a photo of `native_px` pixels at its own size,
|
||||
/// can't be made on a computer with `ram` bytes, given its working memory `weight`: an export
|
||||
/// enlarged past the photo's size that needs more memory than the computer has would fail to
|
||||
/// allocate, which ends the process rather than the export. Full-size and smaller exports, and
|
||||
/// computers whose memory isn't known, are never refused.
|
||||
pub(super) fn too_big_for_memory(out: (usize, usize), native_px: usize, weight: usize, ram: Option<usize>) -> Option<String> {
|
||||
let ram = ram?;
|
||||
if out.0.saturating_mul(out.1) <= native_px || weight <= ram {
|
||||
return None;
|
||||
}
|
||||
let gb = |b: usize| b as f64 / (1u64 << 30) as f64;
|
||||
Some(format!(
|
||||
"exporting at {} × {} needs about {:.0} GB of memory, more than this computer has ({:.0} GB); choose a smaller size",
|
||||
out.0,
|
||||
out.1,
|
||||
gb(weight).ceil(),
|
||||
gb(ram)
|
||||
))
|
||||
}
|
||||
|
||||
/// Working memory of rendering a photo of `full_px` pixels (long edge `long`) from source level
|
||||
/// `level` into `out_px` output pixels: the decoded source (linear RGB f32, 12 B/px) plus the
|
||||
/// pipeline's planes and the encoded output (~36 B per output pixel). Measured: a 24 MP export
|
||||
/// peaks at ~1.2 GB, one at 2048 px from the 2560 px preview at ~150 MB.
|
||||
pub(super) fn render_weight(full_px: usize, long: usize, level: crate::media::SourceLevel, out_px: usize) -> usize {
|
||||
let edge = level.max_edge().min(long.max(1));
|
||||
let scale = edge as f64 / long.max(1) as f64;
|
||||
let src_px = (full_px as f64 * scale * scale).min(usize::MAX as f64 / 64.0) as usize;
|
||||
src_px.saturating_mul(12).saturating_add(out_px.saturating_mul(36))
|
||||
}
|
||||
|
||||
impl PreparedExport {
|
||||
pub fn run(self) -> Result<Exported, String> {
|
||||
let file_name = self.file_name;
|
||||
match self.work {
|
||||
Work::Render(w) => {
|
||||
let RenderWork { job, hdr_job, meta, opts } = *w;
|
||||
let result = job.run();
|
||||
let r = result.rendered?;
|
||||
let gpu_fallback = result.gpu_fallback;
|
||||
let bytes = match hdr_job {
|
||||
Some(hj) => {
|
||||
let hr = hj.run().rendered?;
|
||||
let hdr = hr.deep.ok_or("the HDR render has no float samples")?;
|
||||
encode_gain_map_jpeg(&r.image, &hdr, &opts, meta.as_ref())?
|
||||
}
|
||||
None => encode_rendered(&r, &opts, meta.as_ref())?,
|
||||
};
|
||||
Ok(Exported { file_name, bytes, width: r.image.width, height: r.image.height, sidecars: Vec::new(), gpu_fallback })
|
||||
}
|
||||
Work::File { path, read, packet, dng, quality, lossy_edge, label, size, remove_location } => {
|
||||
let bytes = match &read {
|
||||
Some(r) => r(&path)?,
|
||||
None => std::fs::read(&path).map_err(|e| format!("{path}: {e}"))?,
|
||||
};
|
||||
let Some(dng) = dng else {
|
||||
// the file is copied byte for byte: refuse rather than leak a location it embeds
|
||||
if remove_location {
|
||||
let metadata = lightcraft_meta::try_extract(&bytes)
|
||||
.map_err(|e| format!("{label}: can't verify location metadata in this original file: {e}"))?;
|
||||
if metadata.gps.is_some() {
|
||||
return Err(format!(
|
||||
"{label}: can't remove the location from an original file that embeds GPS; export as JPEG, TIFF or DNG instead"
|
||||
));
|
||||
}
|
||||
}
|
||||
return Ok(Exported {
|
||||
file_name,
|
||||
bytes,
|
||||
width: size.0,
|
||||
height: size.1,
|
||||
sidecars: vec![("xmp", packet.into_bytes())],
|
||||
gpu_fallback: None,
|
||||
});
|
||||
};
|
||||
if lightcraft_raw::probe(&bytes).is_none() {
|
||||
return Err(format!("{label}: DNG export needs a raw photo"));
|
||||
}
|
||||
let mut raw = lightcraft_raw::decode(&bytes).map_err(|e| format!("{label}: {e}"))?;
|
||||
crate::camera_preview::with_starting_colour(&mut raw, &bytes);
|
||||
drop(bytes);
|
||||
let compression = match dng {
|
||||
DngCompression::Lossless => lightcraft_raw::DngCompression::Lj92 { tile: 256 },
|
||||
DngCompression::Deflate => lightcraft_raw::DngCompression::Deflate { tile: 256, half: false },
|
||||
DngCompression::Uncompressed => lightcraft_raw::DngCompression::Uncompressed,
|
||||
DngCompression::Lossy => {
|
||||
lightcraft_raw::DngCompression::LossyJpeg { tile: 256, quality: quality.clamp(1, 100), long_edge: lossy_edge }
|
||||
}
|
||||
};
|
||||
let dng = lightcraft_raw::write_dng(&raw, &lightcraft_raw::DngWriteOptions { xmp: Some(packet), compression, ..Default::default() })
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Exported { file_name, bytes: dng, width: raw.width, height: raw.height, sidecars: Vec::new(), gpu_fallback: None })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How an exported DNG stores its raw data.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DngCompression {
|
||||
/// Lossless JPEG (the usual DNG compression).
|
||||
#[default]
|
||||
Lossless,
|
||||
/// Deflate (zip) tiles with prediction.
|
||||
Deflate,
|
||||
Uncompressed,
|
||||
/// Lossy DNG: demosaiced linear data as JPEG tiles at the export quality, scaled to the resize
|
||||
/// setting when there is one (Lightroom's "Use Lossy Compression").
|
||||
Lossy,
|
||||
}
|
||||
|
||||
/// The destination of a batch: a folder (with `ExportOptions::subfolder` and the conflict policy
|
||||
/// applied to each file together with its sidecars; with [`DestinationMode::SameAsOriginal`] each
|
||||
/// photo's own folder instead of `dir`), or one exact file path (single photo; an ordinary file
|
||||
/// already there is replaced). Either way a catalogued original (or its sidecar)
|
||||
/// is never written over: see [`crate::originals`].
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Destination {
|
||||
pub dir: String,
|
||||
pub exact: Option<String>,
|
||||
}
|
||||
|
||||
/// What happens after an export has written its files (Lightroom's Post-Processing): nothing, or
|
||||
/// adding them to Apple Photos ([`ExportOptions::add_to_photos`]). Made by
|
||||
/// [`crate::Session::after_export`] before the export starts, so an export asking for something
|
||||
/// this session can't do fails before writing anything; for Photos it holds the import slot
|
||||
/// (a [`crate::apple_photos::Reservation`]) until the files are handed over, and frees it when
|
||||
/// dropped unused (the export failed or never ran). `Send`: a background export takes it to its
|
||||
/// worker.
|
||||
#[derive(Default)]
|
||||
pub struct AfterExport {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
apple_photos: Option<crate::apple_photos::Reservation>,
|
||||
}
|
||||
|
||||
impl AfterExport {
|
||||
/// Add the files to Apple Photos with `runner`, into `album` when it isn't blank, reserving
|
||||
/// the import slot of `imports` now. (Front ends get this from
|
||||
/// [`crate::Session::after_export`], which checks the platform first.)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn apple_photos(runner: crate::apple_photos::Runner, album: &str, imports: &crate::apple_photos::Imports) -> Result<Self, String> {
|
||||
Ok(Self { apple_photos: Some(imports.reserve(runner, album)?) })
|
||||
}
|
||||
|
||||
/// Nothing to do.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn is_none(&self) -> bool {
|
||||
self.apple_photos.is_none()
|
||||
}
|
||||
|
||||
/// Nothing to do.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn is_none(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// Do it now for an export's per-photo results ([`run_batch`]'s: only the files written
|
||||
/// count), waiting for Photos: for a worker thread (the app's background export) or a caller
|
||||
/// without a window (MCP, lightcraft-cli). `None` when there was nothing to do, else the
|
||||
/// outcome to report as the export's `applePhotos`: the finished job (`{job, running: false,
|
||||
/// requested, album}` with `{imported, ids, warning?}`, `{error}`, or `{skipped}` when the
|
||||
/// export was cancelled or wrote nothing). Never fails the export: its files are written
|
||||
/// either way.
|
||||
pub fn run(self, files: &[serde_json::Value], cancelled: bool) -> Option<serde_json::Value> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(r) = self.apple_photos {
|
||||
return Some(r.run(files, cancelled));
|
||||
}
|
||||
let _ = (files, cancelled);
|
||||
None
|
||||
}
|
||||
|
||||
/// Like [`AfterExport::run`], without waiting: Photos works on a worker thread and the
|
||||
/// outcome is the running job (`{job, running: true, requested, album}`; its result comes
|
||||
/// from `export.photosImports`, and the desktop app announces it). For a caller on the UI
|
||||
/// thread, which must not wait minutes for Photos.
|
||||
pub fn start(self, files: &[serde_json::Value]) -> Option<serde_json::Value> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(r) = self.apple_photos {
|
||||
return Some(r.start(files));
|
||||
}
|
||||
let _ = files;
|
||||
None
|
||||
}
|
||||
|
||||
/// [`AfterExport::start`] where the session answers on a UI thread
|
||||
/// ([`crate::Session::apple_photos_background`]), else [`AfterExport::run`].
|
||||
pub fn finish(self, s: &crate::Session, files: &[serde_json::Value]) -> Option<serde_json::Value> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if s.apple_photos_background {
|
||||
return self.start(files);
|
||||
}
|
||||
let _ = s;
|
||||
self.run(files, false)
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Session {
|
||||
/// What an export with `o` does after writing its files; an error, before anything is written,
|
||||
/// when it asks for Apple Photos and this platform or session has no way to reach it, or
|
||||
/// another import is reserved or running. For Photos the import slot is reserved from now on.
|
||||
pub fn after_export(&self, o: &ExportOptions) -> Result<AfterExport, String> {
|
||||
if !o.add_to_photos {
|
||||
return Ok(AfterExport::default());
|
||||
}
|
||||
if let Some(why) = apple_photos_unsupported() {
|
||||
return Err(why.into());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let runner = self.apple_photos.clone().ok_or_else(|| crate::apple_photos::unavailable().to_string())?;
|
||||
let mut after = AfterExport::apple_photos(runner, &o.photos_album, &self.apple_photos_imports)?;
|
||||
after.apple_photos = after.apple_photos.map(|r| r.shown_in(self.activity.clone()));
|
||||
Ok(after)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Err("Apple Photos is only available on macOS".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Export `ids` in order ([`prepare_batch`] + [`run_batch`]), stopping at the first error.
|
||||
pub fn export_batch(
|
||||
session: &mut crate::Session,
|
||||
ids: &[lightcraft_catalog::PhotoId],
|
||||
o: &ExportOptions,
|
||||
to: &Destination,
|
||||
write: &mut dyn FnMut(&str, &[u8]) -> Result<(), String>,
|
||||
exists: &dyn Fn(&str) -> bool,
|
||||
) -> Result<Vec<serde_json::Value>, String> {
|
||||
let items = prepare_batch(session, ids, o)?;
|
||||
run_batch(items, o, to, write, exists, true, &mut |_, _| true)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,306 @@
|
||||
use super::encoding::srgb8_in;
|
||||
use super::*;
|
||||
|
||||
/// Where a watermark sits.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Anchor {
|
||||
TopLeft,
|
||||
Top,
|
||||
TopRight,
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
BottomLeft,
|
||||
Bottom,
|
||||
#[default]
|
||||
BottomRight,
|
||||
}
|
||||
|
||||
/// A text watermark, sized relative to the image so every export size looks the same.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Watermark {
|
||||
pub text: String,
|
||||
/// Basic Japanese vertical lettering: upright glyphs in columns from right to left.
|
||||
pub vertical: bool,
|
||||
/// Text height as a fraction of the image's short edge.
|
||||
pub size: f32,
|
||||
/// 0..1.
|
||||
pub opacity: f32,
|
||||
pub anchor: Anchor,
|
||||
/// Margin from the left or right edge, as a fraction of the short edge (unused when the anchor
|
||||
/// is centred across: top, center, bottom).
|
||||
pub inset_x: f32,
|
||||
/// Margin from the top or bottom edge, as a fraction of the short edge (unused when the anchor
|
||||
/// is centred down: left, center, right).
|
||||
pub inset_y: f32,
|
||||
/// Degrees clockwise: 0, 90, 180 or 270 (anything else draws unrotated). The watermark is
|
||||
/// sized before it is turned, and the insets are measured to the turned watermark.
|
||||
pub rotation: u16,
|
||||
/// sRGB colour.
|
||||
pub color: [u8; 3],
|
||||
/// Soft dark drop shadow for legibility on bright areas.
|
||||
pub shadow: bool,
|
||||
/// A graphic (PNG with transparency, JPEG, …) drawn instead of the text (empty = text).
|
||||
pub image: String,
|
||||
/// The graphic's width as a fraction of the photo's width.
|
||||
pub image_width: f32,
|
||||
/// The colour space the photo is in (set by the encoder; the graphic is converted into it).
|
||||
#[serde(skip)]
|
||||
pub target: Option<OutputSpace>,
|
||||
}
|
||||
|
||||
impl Default for Watermark {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
text: String::new(),
|
||||
vertical: false,
|
||||
size: 0.035,
|
||||
opacity: 0.7,
|
||||
anchor: Anchor::BottomRight,
|
||||
inset_x: 0.025,
|
||||
inset_y: 0.025,
|
||||
rotation: 0,
|
||||
color: [255; 3],
|
||||
shadow: true,
|
||||
image: String::new(),
|
||||
image_width: 0.2,
|
||||
target: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Watermark {
|
||||
/// `rotation` in clockwise quarter turns.
|
||||
fn quarter_turns(&self) -> u8 {
|
||||
match self.rotation {
|
||||
90 => 1,
|
||||
180 => 2,
|
||||
270 => 3,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the point `(x, y)` of a `w × h` box lands when the box is turned `turns` quarter turns
|
||||
/// clockwise (for pixel coordinates: the turned box is `h × w` for odd turns).
|
||||
fn turn(turns: u8, x: f32, y: f32, w: f32, h: f32) -> (f32, f32) {
|
||||
match turns {
|
||||
1 => (h - 1.0 - y, x),
|
||||
2 => (w - 1.0 - x, h - 1.0 - y),
|
||||
3 => (y, w - 1.0 - x),
|
||||
_ => (x, y),
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw `wm` onto `img` (straight alpha blending of the encoded values).
|
||||
pub fn draw_watermark(img: &mut Rgba8, wm: &Watermark) {
|
||||
blend_watermark(img, wm, 1.0);
|
||||
}
|
||||
|
||||
/// Draw `wm` onto `img`, a preview of an export whose short edge is `export_short_edge` pixels.
|
||||
/// The smallest text size and shadow offset scale with the preview, so it looks like the file.
|
||||
pub fn draw_watermark_preview(img: &mut Rgba8, wm: &Watermark, export_short_edge: usize) {
|
||||
let short = img.width.min(img.height);
|
||||
let scale = if export_short_edge == 0 { 1.0 } else { short as f32 / export_short_edge as f32 };
|
||||
blend_watermark(img, wm, scale);
|
||||
}
|
||||
|
||||
fn blend_watermark(img: &mut Rgba8, wm: &Watermark, floor_scale: f32) {
|
||||
let width = img.width;
|
||||
watermark_coverage(img.width, img.height, wm, crate::fonts::CRAFT_FONTS, floor_scale, |x, y, k, col| {
|
||||
let p = &mut img.data[y * width + x];
|
||||
for c in 0..3 {
|
||||
p[c] = (p[c] as f32 + (col[c] as f32 - p[c] as f32) * k).round() as u8;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Draw `wm` into the `w × h` area of `img` whose top-left corner is (`x0`, `y0`), sized and
|
||||
/// anchored as on an image of that size (a slideshow slide's photo). The area is clipped to `img`.
|
||||
pub fn draw_watermark_in(img: &mut Rgba8, wm: &Watermark, x0: usize, y0: usize, w: usize, h: usize) {
|
||||
let (width, height) = (img.width, img.height);
|
||||
watermark_coverage(w, h, wm, crate::fonts::CRAFT_FONTS, 1.0, |x, y, k, col| {
|
||||
let (px, py) = (x0.saturating_add(x), y0.saturating_add(y));
|
||||
if px >= width || py >= height {
|
||||
return;
|
||||
}
|
||||
if let Some(p) = img.data.get_mut(py * width + px) {
|
||||
for c in 0..3 {
|
||||
p[c] = (p[c] as f32 + (col[c] as f32 - p[c] as f32) * k).round() as u8;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Draw `wm` onto a high-bit-depth image (`wm.color` is in the image's space, 8-bit encoded; float
|
||||
/// images are linear and blend in linear light).
|
||||
pub fn draw_watermark_deep(img: &mut DeepImage, wm: &Watermark) {
|
||||
let (width, trc) = (img.width, img.space.trc());
|
||||
match &mut img.samples {
|
||||
DeepSamples::U16(v) => watermark_coverage(img.width, img.height, wm, crate::fonts::CRAFT_FONTS, 1.0, |x, y, k, col| {
|
||||
let i = (y * width + x) * 3;
|
||||
for c in 0..3 {
|
||||
let p = v[i + c] as f32;
|
||||
v[i + c] = (p + (col[c] as f32 * 257.0 - p) * k).round().clamp(0.0, 65535.0) as u16;
|
||||
}
|
||||
}),
|
||||
DeepSamples::F32(v) => watermark_coverage(img.width, img.height, wm, crate::fonts::CRAFT_FONTS, 1.0, |x, y, k, col| {
|
||||
let i = (y * width + x) * 3;
|
||||
for c in 0..3 {
|
||||
let target = trc.decode(col[c] as f32 / 255.0);
|
||||
v[i + c] += (target - v[i + c]) * k;
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lay out `wm` on a `width × height` image and call `blend(x, y, coverage × opacity, colour)` for
|
||||
/// every covered pixel (shadow pass first). `craft` is [`crate::fonts::CRAFT_FONTS`] (a parameter
|
||||
/// so tests can render without it). `floor_scale` is this image's size over the exported file's
|
||||
/// (1 when drawing the file itself): the 6 px minimum text size is a minimum in the file.
|
||||
pub(super) fn watermark_coverage(
|
||||
width: usize,
|
||||
height: usize,
|
||||
wm: &Watermark,
|
||||
craft: &'static [crate::fonts::CraftFont],
|
||||
floor_scale: f32,
|
||||
mut blend_px: impl FnMut(usize, usize, f32, [u8; 3]),
|
||||
) {
|
||||
if !wm.image.trim().is_empty() {
|
||||
logo_coverage(width, height, wm, blend_px);
|
||||
return;
|
||||
}
|
||||
let text = wm.text.trim();
|
||||
if text.is_empty() || width == 0 || height == 0 {
|
||||
return;
|
||||
}
|
||||
let short = width.min(height) as f32;
|
||||
let px = (wm.size.clamp(0.005, 0.5) * short).max(6.0 * floor_scale);
|
||||
let Some(layout) = crate::text::TextLayout::new(text, px, wm.vertical, craft) else { return };
|
||||
let (tw, th) = (layout.width, layout.height);
|
||||
// laid out unturned in a tw × th box, placed by the box it becomes
|
||||
let turns = wm.quarter_turns();
|
||||
let (bw, bh) = if turns % 2 == 1 { (th, tw) } else { (tw, th) };
|
||||
let (ix, iy) = (wm.inset_x.clamp(0.0, 0.4) * short, wm.inset_y.clamp(0.0, 0.4) * short);
|
||||
let (w, h) = (width as f32, height as f32);
|
||||
use Anchor::*;
|
||||
let ox = match wm.anchor {
|
||||
TopLeft | Left | BottomLeft => ix,
|
||||
Top | Center | Bottom => (w - bw) / 2.0,
|
||||
TopRight | Right | BottomRight => w - ix - bw,
|
||||
};
|
||||
let oy = match wm.anchor {
|
||||
TopLeft | Top | TopRight => iy,
|
||||
Left | Center | Right => (h - bh) / 2.0,
|
||||
BottomLeft | Bottom | BottomRight => h - iy - bh,
|
||||
};
|
||||
let alpha = wm.opacity.clamp(0.0, 1.0);
|
||||
let passes: &[(f32, [u8; 3], f32)] =
|
||||
if wm.shadow { &[((px * 0.05).max(floor_scale), [0, 0, 0], 0.45), (0.0, wm.color, 1.0)] } else { &[(0.0, wm.color, 1.0)] };
|
||||
for &(off, col, a) in passes {
|
||||
let mut put = |gx: i32, gy: i32, cov: f32| {
|
||||
if gx < 0 || gy < 0 || gx >= width as i32 || gy >= height as i32 {
|
||||
return;
|
||||
}
|
||||
blend_px(gx as usize, gy as usize, (cov * a * alpha).clamp(0.0, 1.0), col);
|
||||
};
|
||||
if turns == 0 {
|
||||
layout.draw_in(ox + off, oy + off, w, h, &mut put);
|
||||
} else {
|
||||
// turned with the box; the shadow still falls down and to the right
|
||||
layout.draw_points(|x, y, cov| {
|
||||
let (x, y) = turn(turns, x, y, tw, th);
|
||||
put((ox + off + x) as i32, (oy + off + y) as i32, cov);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A watermark graphic, decoded once per file (and again when the file changes).
|
||||
pub(crate) fn watermark_logo(path: &str) -> Option<std::sync::Arc<Rgba8>> {
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
static CACHE: Mutex<Option<HashMap<String, (std::time::SystemTime, Arc<Rgba8>)>>> = Mutex::new(None);
|
||||
let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok()?;
|
||||
let mut c = CACHE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let map = c.get_or_insert_with(HashMap::new);
|
||||
if let Some((m, img)) = map.get(path)
|
||||
&& *m == modified
|
||||
{
|
||||
return Some(img.clone());
|
||||
}
|
||||
let img = Arc::new(read_graphic(path).ok()?);
|
||||
map.insert(path.to_string(), (modified, img.clone()));
|
||||
Some(img)
|
||||
}
|
||||
|
||||
/// A graphic file (a PNG with transparency, typically) as 8-bit sRGB with its alpha: the
|
||||
/// watermark logo, the loupe's layout image. Applies EXIF orientation before either consumer sizes it.
|
||||
/// The error says why it couldn't be read or decoded.
|
||||
pub fn read_graphic(path: &str) -> Result<Rgba8, String> {
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("can't read {path}: {e}"))?;
|
||||
let decoded = lightcraft_codecs::decode(&bytes, Default::default()).map_err(|e| format!("can't decode {path}: {e}"))?;
|
||||
Ok(decoded.to_srgb8().into_oriented(lightcraft_geom::Orientation::from_exif(decoded.orientation)))
|
||||
}
|
||||
|
||||
/// The graphic watermark: scaled (premultiplied, so transparent edges stay clean) to
|
||||
/// `image_width` of the photo, placed like the text, blended with its alpha × opacity.
|
||||
fn logo_coverage(width: usize, height: usize, wm: &Watermark, mut blend_px: impl FnMut(usize, usize, f32, [u8; 3])) {
|
||||
let Some(logo) = watermark_logo(wm.image.trim()) else {
|
||||
log::warn!("watermark: can't read {}", wm.image);
|
||||
return;
|
||||
};
|
||||
if width == 0 || height == 0 || logo.width == 0 || logo.height == 0 {
|
||||
return;
|
||||
}
|
||||
let turns = wm.quarter_turns();
|
||||
// Reserve the inset on anchored axes before fitting the turned box. Centered axes
|
||||
// ignore insets, just as placement below does. One scale preserves the graphic's shape.
|
||||
let short = width.min(height) as f32;
|
||||
let (ix, iy) = (wm.inset_x.clamp(0.0, 0.4) * short, wm.inset_y.clamp(0.0, 0.4) * short);
|
||||
use Anchor::*;
|
||||
let available_w = width as f64 - if matches!(wm.anchor, Top | Center | Bottom) { 0.0 } else { ix as f64 };
|
||||
let available_h = height as f64 - if matches!(wm.anchor, Left | Center | Right) { 0.0 } else { iy as f64 };
|
||||
let (max_w, max_h) = if turns % 2 == 1 { (available_h, available_w) } else { (available_w, available_h) };
|
||||
let scale =
|
||||
(wm.image_width.clamp(0.01, 1.0) as f64 * width as f64 / logo.width as f64).min(max_w / logo.width as f64).min(max_h / logo.height as f64);
|
||||
let lw = (logo.width as f64 * scale).round().max(1.0) as usize;
|
||||
let lh = (logo.height as f64 * scale).round().max(1.0) as usize;
|
||||
let pre: lightcraft_raster::Image<[f32; 4]> = lightcraft_raster::Image::from_fn(logo.width, logo.height, |x, y| {
|
||||
let p = logo.get(x, y);
|
||||
let a = p[3] as f32 / 255.0;
|
||||
[p[0] as f32 * a, p[1] as f32 * a, p[2] as f32 * a, a]
|
||||
});
|
||||
let scaled = lightcraft_raster::resample::resize(&pre, lw, lh, lightcraft_raster::resample::Filter::Mitchell);
|
||||
let (bw, bh) = if turns % 2 == 1 { (lh, lw) } else { (lw, lh) };
|
||||
let (w, h, lwf, lhf) = (width as f32, height as f32, bw as f32, bh as f32);
|
||||
let ox = match wm.anchor {
|
||||
TopLeft | Left | BottomLeft => ix,
|
||||
Top | Center | Bottom => (w - lwf) / 2.0,
|
||||
TopRight | Right | BottomRight => w - ix - lwf,
|
||||
}
|
||||
.max(0.0) as usize;
|
||||
let oy = match wm.anchor {
|
||||
TopLeft | Top | TopRight => iy,
|
||||
Left | Center | Right => (h - lhf) / 2.0,
|
||||
BottomLeft | Bottom | BottomRight => h - iy - lhf,
|
||||
}
|
||||
.max(0.0) as usize;
|
||||
let space = wm.target.unwrap_or(OutputSpace::Srgb);
|
||||
let op = wm.opacity.clamp(0.0, 1.0);
|
||||
for y in 0..lh {
|
||||
for x in 0..lw {
|
||||
let [r, g, b, a] = scaled.get(x, y);
|
||||
let a = a.clamp(0.0, 1.0);
|
||||
let (tx, ty) = turn(turns, x as f32, y as f32, lw as f32, lh as f32);
|
||||
let (px, py) = (ox + tx as usize, oy + ty as usize);
|
||||
if a <= 1e-4 || px >= width || py >= height {
|
||||
continue;
|
||||
}
|
||||
let c = [r, g, b].map(|v| (v / a).round().clamp(0.0, 255.0) as u8);
|
||||
blend_px(px, py, a * op, srgb8_in(space, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
-2844
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
||||
/// The white-balanced camera RGB that `model` (white-balanced camera RGB → linear Rec.2020) renders
|
||||
/// neutral, as bright as it renders `[1, 1, 1]`: what fully clipped highlights are rebuilt to, so they come out
|
||||
/// neutral whatever the colour model does to the camera's own neutral (a look fitted to the camera's JPEG or a
|
||||
/// camera profile often tints it by a few per cent, which any darkening of the highlights would show).
|
||||
/// `[1, 1, 1]` (the camera's own neutral, as before this existed) when the model can't be trusted with it: not
|
||||
/// invertible or nearly so, an answer far from the camera's neutral (a sane colour model moves white by a few per
|
||||
/// cent), or one that isn't neutral through the `f32` matrix the decode applies.
|
||||
pub(crate) fn clipped_white(model: &lightcraft_color::Mat3) -> [f32; 3] {
|
||||
const CAMERA: [f32; 3] = [1.0; 3];
|
||||
/// Largest condition number (max row sum norm) of a model trusted for this.
|
||||
const CONDITION: f64 = 1e3;
|
||||
/// Largest factor between the answer and the camera's neutral, per channel.
|
||||
const SPREAD: f64 = 4.0;
|
||||
let norm = |m: &lightcraft_color::Mat3| m.0.iter().map(|row| row.iter().map(|v| v.abs()).sum::<f64>()).fold(0.0, f64::max);
|
||||
let Some(inverse) = model.inverse() else { return CAMERA };
|
||||
let condition = norm(model) * norm(&inverse);
|
||||
if !condition.is_finite() || condition > CONDITION {
|
||||
return CAMERA;
|
||||
}
|
||||
let luma = |v: [f64; 3]| {
|
||||
let c = model.apply(v);
|
||||
(0..3).map(|i| c[i] * f64::from(lightcraft_color::LUMA_2020[i])).sum::<f64>()
|
||||
};
|
||||
let n = inverse.apply([1.0; 3]);
|
||||
let (target, own) = (luma([1.0; 3]), luma(n));
|
||||
if !(target > 0.0 && own > 0.0 && target.is_finite() && own.is_finite()) {
|
||||
return CAMERA;
|
||||
}
|
||||
let white = n.map(|v| v * target / own);
|
||||
if !white.iter().all(|v| v.is_finite() && (1.0 / SPREAD..=SPREAD).contains(v)) {
|
||||
return CAMERA;
|
||||
}
|
||||
let white = white.map(|v| v as f32);
|
||||
// neutral through the matrix as the decode applies it
|
||||
let m = model.to_f32();
|
||||
let out: [f32; 3] = std::array::from_fn(|i| m[i][0] * white[0] + m[i][1] * white[1] + m[i][2] * white[2]);
|
||||
let (lo, hi) = (out[0].min(out[1]).min(out[2]), out[0].max(out[1]).max(out[2]));
|
||||
if lo > 0.0 && hi.is_finite() && hi - lo <= 1e-3 * hi { white } else { CAMERA }
|
||||
}
|
||||
|
||||
/// The largest block size to bin a raw's mosaic by for a source of at most `max_edge` pixels:
|
||||
/// the binned image must keep at least 90 % of `max_edge` (a 16 MP sensor still bins 2× for the
|
||||
/// 2560 px preview). X-Trans can only bin 3× (its 6×6 pattern), and its full demosaic is ~5× the
|
||||
/// cost of Bayer's, so 3× is accepted down to 75 % (a 24 MP X-Trans preview is then ~2000 px
|
||||
/// instead of a ~1.2 s full demosaic; zooming in still uses the full-size source).
|
||||
/// `None` = demosaic at full size.
|
||||
pub fn bin_factor(raw: &lightcraft_raw::RawImage, max_edge: usize) -> Option<usize> {
|
||||
let c = raw.crop.clipped(raw.active_area.width, raw.active_area.height);
|
||||
let long = if c.width > 1 && c.height > 1 { c.width.max(c.height) } else { raw.active_area.width.max(raw.active_area.height) };
|
||||
let need = (max_edge.saturating_mul(9) / 10).max(1);
|
||||
let need3 = (max_edge.saturating_mul(3) / 4).max(1);
|
||||
[8usize, 6, 4, 3, 2].into_iter().find(|&k| raw.can_bin(k) && (long / k >= need || (k == 3 && !raw.can_bin(2) && long / k >= need3)))
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
use super::load::{load_vec, load_vec_pair, load_vec_reduced};
|
||||
use super::preview::{fit_box, fs_preview_loader, preview_orientation};
|
||||
use super::probe::probe_bytes;
|
||||
use super::*;
|
||||
|
||||
/// The file's first [`lightcraft_raw::PREVIEW_PREFIX`] bytes (or the whole file when it is shorter),
|
||||
/// which is what every format [`lightcraft_raw::bounded_preview`] covers keeps its pointer in.
|
||||
pub(super) fn read_prefix(file: &mut std::fs::File, path: &str, total: u64) -> Result<Vec<u8>, String> {
|
||||
let len = lightcraft_raw::PREVIEW_PREFIX.min(usize::try_from(total).unwrap_or(usize::MAX));
|
||||
read_prefix_at(file, path, len as u64)
|
||||
}
|
||||
|
||||
/// The file's first `len` bytes, read from the start.
|
||||
pub(super) fn read_prefix_at(file: &mut std::fs::File, path: &str, len: u64) -> Result<Vec<u8>, String> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
let len = usize::try_from(len).map_err(|_| format!("{path}: file too large"))?;
|
||||
let mut prefix = vec![0u8; len];
|
||||
file.seek(SeekFrom::Start(0)).map_err(|e| format!("{path}: {e}"))?;
|
||||
file.read_exact(&mut prefix).map_err(|e| format!("{path}: {e}"))?;
|
||||
Ok(prefix)
|
||||
}
|
||||
|
||||
/// The end of a Fuji RAF's preview block, from the two big-endian u32s every RAF header carries at
|
||||
/// 84 (offset) and 88 (length) — the same fields `lightcraft_raw`'s RAF reader uses, read here
|
||||
/// without the rest of the file so the prefix can be made big enough first.
|
||||
pub(super) fn raf_preview_extent(prefix: &[u8]) -> Option<u64> {
|
||||
if !prefix.starts_with(b"FUJIFILMCCD-RAW") {
|
||||
return None;
|
||||
}
|
||||
let u32_at = |at: usize| prefix.get(at..at + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]])).map(u64::from);
|
||||
let (offset, len) = (u32_at(84)?, u32_at(88)?);
|
||||
(offset > 0 && len > 0).then(|| offset.checked_add(len)).flatten()
|
||||
}
|
||||
|
||||
/// The display-ready preview of a raw whose embedded JPEG was already located: the counterpart of
|
||||
/// [`embedded_preview_srgb`] for [`preview_window`], which does not re-read the container.
|
||||
/// `adobe_rgb`: the container declares the preview Adobe RGB ([`PreviewRead::adobe_rgb`]), applied
|
||||
/// as [`decode_raw_preview`] applies it. `None` when the bytes are not a decodable image.
|
||||
pub(super) fn quick_image_srgb(header: &[u8], window: &[u8], adobe_rgb: bool, max_edge: usize) -> Option<lightcraft_raster::Rgba8> {
|
||||
let decoded = if adobe_rgb && window.starts_with(&[0xff, 0xd8]) {
|
||||
lightcraft_codecs::decode_jpeg_with_fallback(window, fit_box(max_edge), lightcraft_codecs::NamedSpace::AdobeRgb)
|
||||
} else {
|
||||
lightcraft_codecs::decode(window, fit_box(max_edge))
|
||||
};
|
||||
let mut d = decoded.ok()?;
|
||||
if d.image.width.max(d.image.height) > max_edge {
|
||||
d.image = fit(&d.image, max_edge, max_edge, Filter::Box);
|
||||
d.alpha = None;
|
||||
}
|
||||
// The JPEG's own EXIF orientation, else the raw's (from its header), as the whole-file path does
|
||||
Some(d.to_srgb8().oriented(preview_orientation(header, d.orientation)))
|
||||
}
|
||||
|
||||
/// The filesystem-backed [`PairLoader`]: the file is read and decoded once, and developed as usual and from the photo's
|
||||
/// denoised picture. It holds two pictures at once, so it counts for more at the memory gate than a plain load.
|
||||
pub fn fs_pair_loader() -> PairLoader {
|
||||
Arc::new(|path: &str, max_edge: usize, spec: &DenoiseSpec| {
|
||||
let len = std::fs::metadata(path).map(|m| m.len() as usize).unwrap_or(0);
|
||||
let weight = len * if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 4 } else { 10 };
|
||||
let gate = crate::memory::work_gate();
|
||||
let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) };
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let r = load_vec_pair(bytes, max_edge, spec);
|
||||
crate::memory::release();
|
||||
r
|
||||
})
|
||||
}
|
||||
|
||||
/// Filesystem-backed hooks (native). On the web the host installs bytes-based hooks instead.
|
||||
///
|
||||
/// Their working memory is bounded by [`crate::memory::work_gate`]: background loads (grid
|
||||
/// thumbnails, neighbour prefetch: [`crate::memory::in_background`]) and import probes wait while
|
||||
/// too much is in flight, each counting its file's size times the expansion of decoding it;
|
||||
/// interactive loads (the loupe, exports) never wait — they are counted, so background work
|
||||
/// yields to them.
|
||||
pub fn fs_hooks() -> (FileLoader, FileProbe) {
|
||||
let loader: FileLoader = Arc::new(|path: &str, max_edge: usize| fs_load(path, max_edge, |bytes| load_vec(bytes, max_edge)));
|
||||
let probe: FileProbe = Arc::new(|path: &str| {
|
||||
let len = std::fs::metadata(path).map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).unwrap_or(0);
|
||||
let _permit = crate::memory::work_gate().acquire(len);
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let mut info = probe_bytes(path, &bytes)?;
|
||||
info.file_modified = file_modified(path);
|
||||
Ok(info)
|
||||
});
|
||||
(loader, probe)
|
||||
}
|
||||
|
||||
/// The filesystem [`ReducedLoader`]: [`load_vec_reduced`] of the file, gated like [`fs_hooks`]' loader.
|
||||
pub fn fs_reduced_loader() -> ReducedLoader {
|
||||
Arc::new(|path: &str, max_edge: usize| fs_load(path, max_edge, |bytes| load_vec_reduced(bytes, max_edge)))
|
||||
}
|
||||
|
||||
/// Read `path` and `load` it, waiting on [`crate::memory::work_gate`] as [`fs_hooks`] explains.
|
||||
fn fs_load<T>(path: &str, max_edge: usize, load: impl FnOnce(Vec<u8>) -> Result<T, String>) -> Result<T, String> {
|
||||
let len = std::fs::metadata(path).map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).unwrap_or(0);
|
||||
let weight = len.saturating_mul(if max_edge <= crate::media::SourceLevel::Thumb.max_edge() { 3 } else { 6 });
|
||||
let gate = crate::memory::work_gate();
|
||||
let _permit = if crate::memory::is_background() { gate.acquire(weight) } else { gate.acquire_urgent(weight) };
|
||||
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let r = load(bytes);
|
||||
// the file, the samples and the intermediate images are gone: give their pages back
|
||||
crate::memory::release();
|
||||
r
|
||||
}
|
||||
|
||||
/// `path`'s modification time as ISO 8601 (see [`ProbeInfo::file_modified`]); `None` when the
|
||||
/// filesystem doesn't say or the time is before 1970.
|
||||
fn file_modified(path: &str) -> Option<String> {
|
||||
let t = std::fs::metadata(path).ok()?.modified().ok()?;
|
||||
let secs = i64::try_from(t.duration_since(std::time::UNIX_EPOCH).ok()?.as_secs()).ok()?;
|
||||
Some(crate::import::civil(secs))
|
||||
}
|
||||
|
||||
impl crate::Session {
|
||||
/// Install the filesystem file hooks (desktop, CLI, MCP headless), and on macOS the Apple Photos
|
||||
/// runner ([`crate::apple_photos::osascript`]; installed, not run).
|
||||
pub fn with_fs(mut self) -> Self {
|
||||
let (l, p) = fs_hooks();
|
||||
self.media.file_loader = Some(l);
|
||||
self.media.reduced_loader = Some(fs_reduced_loader());
|
||||
self.media.file_probe = Some(p);
|
||||
self.media.preview_loader = Some(fs_preview_loader());
|
||||
self.media.denoise.loader = Some(fs_pair_loader());
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
self.apple_photos = Some(crate::apple_photos::osascript());
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
use super::colour::bin_factor;
|
||||
use super::preview::{fit_box, load_embedded_preview};
|
||||
use super::probe::preview_reason;
|
||||
use super::*;
|
||||
|
||||
/// Decode a file into a linear Rec.2020 image no larger than `max_edge`, oriented.
|
||||
///
|
||||
/// Runs on a rayon worker: its many short parallel loops then start on the worker's own queue
|
||||
/// instead of each one waking the pool from outside and waiting for it (which costs more than the
|
||||
/// loops themselves when the machine is busy).
|
||||
pub fn load_bytes(bytes: &[u8], max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> {
|
||||
rayon::scope(|_| load_bytes_now(std::borrow::Cow::Borrowed(bytes), max_edge, None, false).map(|(img, _, info, _)| (img, info)))
|
||||
}
|
||||
|
||||
/// [`load_bytes`] taking the file's bytes: a raw file's bytes are freed as soon as it is decoded
|
||||
/// (less memory held while it is developed).
|
||||
pub fn load_vec(bytes: Vec<u8>, max_edge: usize) -> Result<(Rgb32f, SourceInfo), String> {
|
||||
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, false).map(|(img, _, info, _)| (img, info)))
|
||||
}
|
||||
|
||||
/// [`load_vec`] for a thumbnail: a DNG that keeps reduced-resolution copies of its raw image (Lightroom's HDR and
|
||||
/// panorama merges) develops the smallest that covers `max_edge` instead of the whole image. The flag says whether
|
||||
/// it did: such a picture is not the full image, and an export never renders from it.
|
||||
pub fn load_vec_reduced(bytes: Vec<u8>, max_edge: usize) -> Result<(Rgb32f, SourceInfo, bool), String> {
|
||||
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, None, true).map(|(img, _, info, reduced)| (img, info, reduced)))
|
||||
}
|
||||
|
||||
/// [`load_vec`] that also develops the photo's cached denoised picture (`spec`) from the same decode: the plain
|
||||
/// picture, the denoised one (`None` when it cannot be read or does not fit this raw: the plain one is then all
|
||||
/// there is) and the source facts. Both pictures are the same size.
|
||||
pub fn load_vec_pair(bytes: Vec<u8>, max_edge: usize, spec: &DenoiseSpec) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo), String> {
|
||||
rayon::scope(move |_| load_bytes_now(std::borrow::Cow::Owned(bytes), max_edge, Some(spec), false).map(|(img, twin, info, _)| (img, twin, info)))
|
||||
}
|
||||
|
||||
/// The denoised camera RGB of `raw` from its cached product, as the plain development would have it: the default
|
||||
/// crop, and `factor` × `factor` blocks averaged into one pixel when the plain one was binned (plain means: the
|
||||
/// plain development's clip mask tells highlight reconstruction which of them held clipped samples). `None` when
|
||||
/// the product is missing, damaged, made from something else or not the size of this raw's active area.
|
||||
fn denoised_camera_rgb(raw: &lightcraft_raw::RawImage, spec: &DenoiseSpec, factor: usize) -> Option<Rgb32f> {
|
||||
use lightcraft_denoise::product::{self, Window};
|
||||
let a = raw.active_area;
|
||||
let header = product::read_header_at(&spec.product).ok()?;
|
||||
if header.key != spec.key || (header.width, header.height) != (a.width, a.height) {
|
||||
return None;
|
||||
}
|
||||
if raw.opcodes.list3.is_empty() {
|
||||
let c = raw.develop_crop(a.width, a.height);
|
||||
let window = Window { x: c.x, y: c.y, width: c.width, height: c.height };
|
||||
product::read_window(&spec.product, &spec.key, Some(window), factor, None).ok()
|
||||
} else {
|
||||
// (the plain development is not binned either when the file has opcodes of this kind: `factor` is 1)
|
||||
let whole = product::read(&spec.product, &spec.key, 1).ok()?;
|
||||
Some(raw.finish_demosaiced(whole))
|
||||
}
|
||||
}
|
||||
|
||||
fn load_bytes_now(
|
||||
bytes: std::borrow::Cow<'_, [u8]>,
|
||||
max_edge: usize,
|
||||
denoise: Option<&DenoiseSpec>,
|
||||
allow_reduced: bool,
|
||||
) -> Result<(Rgb32f, Option<Rgb32f>, SourceInfo, bool), String> {
|
||||
if lightcraft_raw::probe(&bytes).is_some() {
|
||||
// a thumbnail (`allow_reduced`, never an export) of a DNG that keeps smaller copies of its raw image
|
||||
// (Lightroom's merges) develops the smallest that covers it; a denoised photo's twin needs the full mosaic
|
||||
let reduced = (allow_reduced && denoise.is_none() && max_edge < usize::MAX)
|
||||
.then(|| lightcraft_raw::decode_reduced(&bytes, max_edge).ok().flatten())
|
||||
.flatten();
|
||||
let used_reduced = reduced.is_some();
|
||||
let decoded = match reduced {
|
||||
Some(r) => Ok(r),
|
||||
None => lightcraft_raw::decode(&bytes),
|
||||
};
|
||||
let mut raw = match decoded.map_err(|e| preview_reason(&bytes, e)) {
|
||||
Ok(r) => r,
|
||||
Err(Ok(why)) => {
|
||||
// show the camera's embedded JPEG (rendered, not raw) until the variant is supported
|
||||
return load_embedded_preview(&bytes, max_edge)
|
||||
.map(|(img, info)| (img, None, info, false))
|
||||
.ok_or(format!("unsupported raw ({why}) without an embedded preview"));
|
||||
}
|
||||
Err(Err(e)) => return Err(e),
|
||||
};
|
||||
// Embedded lens corrections are applied by the pipeline ("Enable Profile Corrections"), not baked in
|
||||
// (removed before the camera look's binned sensor proxy too, which needs an empty `OpcodeList3`).
|
||||
let info = raw.info();
|
||||
let lens = crate::lens_profiles::for_raw(&info, || lightcraft_meta::extract(&bytes));
|
||||
// (the camera look still pairs the sensor with the camera JPEG through the warp the camera applied to it)
|
||||
let lens_geometry = crate::camera_preview::lens_geometry(&raw.opcodes.list3);
|
||||
// A DNG's preview already has its lens opcodes applied. Keep them for its single tone fit,
|
||||
// then remove them again: the rendered source leaves those corrections to the pipeline.
|
||||
let dng_lens_ops = (raw.format == lightcraft_raw::RawFormat::Dng && raw.opcodes.list3.iter().any(|op| op.is_lens_correction()))
|
||||
.then(|| raw.opcodes.list3.clone());
|
||||
raw.opcodes.list3.retain(|op| !op.is_lens_correction());
|
||||
// Which scale white balance is edited on, and the as-shot white on it, from the file's own colour tags or
|
||||
// the camera's measured matrices (`Photo::relative_wb` decides the same from the catalog's camera)
|
||||
let scale = WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata);
|
||||
// the source's segmentation mattes (DNG semantic masks), read while the starting colour is fitted
|
||||
let ((xy, t, camera_look), mattes) = rayon::join(
|
||||
|| {
|
||||
let removed = dng_lens_ops.map(|ops| std::mem::replace(&mut raw.opcodes.list3, ops));
|
||||
// With the opcodes restored, the proxy already includes vignetting; do not apply it twice.
|
||||
let embedded = if removed.is_some() { None } else { lens.as_ref() };
|
||||
let colour = crate::camera_preview::starting_colour(&mut raw, &bytes, lens_geometry.as_ref(), embedded);
|
||||
if let Some(ops) = removed {
|
||||
raw.opcodes.list3 = ops;
|
||||
}
|
||||
colour
|
||||
},
|
||||
|| dng_mattes(&bytes, &info),
|
||||
);
|
||||
drop(bytes);
|
||||
// Previews and thumbnails bin the mosaic straight to (about) the size they need; only
|
||||
// larger levels (exports, 1:1) demosaic the whole sensor.
|
||||
let t0 = web_time::Instant::now();
|
||||
let bin = bin_factor(&raw, max_edge);
|
||||
// (binned: block means, and which colours had a clipped sample in each block)
|
||||
let binned = match bin {
|
||||
Some(k) => raw.develop_binned_masked(k, HIGHLIGHT_CLIP).map_err(|e| e.to_string())?,
|
||||
None => None,
|
||||
};
|
||||
let factor = if binned.is_some() { bin.unwrap_or(1) } else { 1 };
|
||||
let (img, clip_mask) = match binned {
|
||||
Some((img, mask)) => (img, Some(mask)),
|
||||
None => {
|
||||
let method = if max_edge <= 600 { lightcraft_raw::Method::Bilinear } else { lightcraft_raw::Method::Ahd };
|
||||
(raw.develop(method).map_err(|e| e.to_string())?, None)
|
||||
}
|
||||
};
|
||||
// the same development from the denoised mosaic, when the photo has been denoised
|
||||
let twin = denoise.and_then(|spec| denoised_camera_rgb(&raw, spec, factor)).filter(|d| d.width == img.width && d.height == img.height);
|
||||
// the samples aren't needed any more (the colour model below reads only the tags)
|
||||
raw.data = lightcraft_raw::RawData::U16(Vec::new());
|
||||
let hue_sat = camera_look.as_ref().and_then(|p| p.hue_sat.as_ref()).and_then(crate::camera_preview::HueSat::new);
|
||||
// A DNG's own profile look (hue/saturation map, look table), DNG spec chapter 6.
|
||||
let tables = lightcraft_raw::profile::ProfileTables::new(&raw.color.profile, lightcraft_raw::color::illuminant_weight(&raw.color, xy));
|
||||
let colour = CameraColourModel {
|
||||
wb: t.wb,
|
||||
matrix: camera_look.as_ref().map(|p| p.matrix.mul(&t.matrix)).unwrap_or(t.matrix),
|
||||
gain: 2f32.powf(t.baseline_exposure as f32),
|
||||
tables: tables.as_ref(),
|
||||
hue_sat: hue_sat.as_ref(),
|
||||
};
|
||||
// camera RGB → what the pipeline takes: clipped highlights rebuilt, white balance and the colour model applied,
|
||||
// fitted to `max_edge` and upright (the same for the plain and the denoised picture)
|
||||
let finish = |mut img: Rgb32f| {
|
||||
let mut stages = vec![("develop", t0.elapsed())];
|
||||
stages.push(("transform", t0.elapsed()));
|
||||
match &clip_mask {
|
||||
Some(mask) => colour.rebuild_highlights_masked(&mut img, mask),
|
||||
None => colour.rebuild_highlights(&mut img),
|
||||
}
|
||||
stages.push(("highlights", t0.elapsed()));
|
||||
colour.apply(&mut img);
|
||||
stages.push(("colour", t0.elapsed()));
|
||||
// a full-size render keeps the picture (fitting it to its own size would copy it, ~390 MB at 33 MP)
|
||||
let img = if img.width.max(img.height) > max_edge { fit(&img, max_edge, max_edge, Filter::Box) } else { img };
|
||||
stages.push(("fit", t0.elapsed()));
|
||||
let img = img.into_oriented(raw.orientation);
|
||||
stages.push(("orient", t0.elapsed()));
|
||||
(img, stages)
|
||||
};
|
||||
let (img, stages) = finish(img);
|
||||
if lightcraft_pipeline::profiling() {
|
||||
let mut prev = std::time::Duration::ZERO;
|
||||
let parts: Vec<String> = stages
|
||||
.iter()
|
||||
.map(|(n, t)| {
|
||||
let d = *t - prev;
|
||||
prev = *t;
|
||||
format!("{n} {:.1}", d.as_secs_f64() * 1e3)
|
||||
})
|
||||
.collect();
|
||||
eprintln!("[profile] raw source {}×{} (max {max_edge}, ms after decode): {}", img.width, img.height, parts.join(", "));
|
||||
}
|
||||
let twin = twin.map(|picture| finish(picture).0);
|
||||
// White balance re-evaluates the file's own colour model (when it has one and no file-local look matrix sits
|
||||
// on top of it). A model's measured matrices never do: they only give the Kelvin scale its numbers, and the
|
||||
// picture is adapted from the as-shot white as every fitted look is (so settings from before that scale
|
||||
// existed render exactly as they did, `lightcraft_pipeline::local::legacy_white`).
|
||||
let camera_color = (scale.own_matrix && !t.matrix_is_fallback && (camera_look.is_none() || raw.format == lightcraft_raw::RawFormat::Dng))
|
||||
.then(|| {
|
||||
let tags = lightcraft_raw::ColorData { profile: Default::default(), ..raw.color.clone() };
|
||||
Arc::new(lightcraft_pipeline::CameraColor { tags, developed_for: xy })
|
||||
});
|
||||
let camera_tone = camera_look.as_ref().map(|p| p.tone).or_else(|| raw.color.profile.tone_curve.as_ref().and_then(dng_tone_curve));
|
||||
let local_tone = local_tone(&raw);
|
||||
let (temp, tint) = scale.as_shot(xy);
|
||||
return Ok((
|
||||
img,
|
||||
twin,
|
||||
SourceInfo {
|
||||
raw: true,
|
||||
as_shot_temp: temp,
|
||||
as_shot_tint: tint,
|
||||
lens,
|
||||
relative_wb: scale.relative,
|
||||
legacy_relative_wb: scale.legacy_relative,
|
||||
camera_color,
|
||||
camera_tone,
|
||||
mattes,
|
||||
local_tone,
|
||||
// (the catalog knows the original's size: `media::source_info`)
|
||||
native_long: None,
|
||||
},
|
||||
used_reduced,
|
||||
));
|
||||
}
|
||||
let d = lightcraft_codecs::decode(&bytes, fit_box(max_edge)).map_err(|e| e.to_string())?;
|
||||
drop(bytes);
|
||||
let img = d.to_working();
|
||||
let img = if img.width.max(img.height) > max_edge { fit(&img, max_edge, max_edge, Filter::Mitchell) } else { img };
|
||||
Ok((img.into_oriented(Orientation::from_exif(d.orientation)), None, SourceInfo::default(), false))
|
||||
}
|
||||
|
||||
/// Which white-balance scale a raw is edited on, decided from the file alone, the way the catalog decides it from
|
||||
/// the photo's format and camera (`lightcraft_catalog::relative_wb_camera`; a test keeps the two in step).
|
||||
///
|
||||
/// A file with colour matrices of its own (DNG) has an absolute scale from its tags. A file without
|
||||
/// (`camera_preview::file_local_look`) has one when its camera's matrices are measured
|
||||
/// (`lightcraft_raw::spectral`), else when its camera's white-balance presets give one
|
||||
/// (`lightcraft_raw::kelvin_presets`): either turns its as-shot multipliers into Kelvin and tint, nothing else — the
|
||||
/// look stays the file's fit. Any other raw is edited relative to its as-shot look (6500 K / 0 means as shot).
|
||||
pub(crate) struct WbScaleOf {
|
||||
pub(super) own_matrix: bool,
|
||||
pub(super) relative: bool,
|
||||
/// Kelvin through the camera's measured matrices or presets: edited on the relative scale before those were used.
|
||||
pub(super) legacy_relative: bool,
|
||||
/// The as-shot white through the measured matrices or the presets, when that is where the scale comes from.
|
||||
pub(super) scale_white: Option<lightcraft_color::Xy>,
|
||||
/// The camera's measured matrices, when they give the scale.
|
||||
camera: Option<&'static lightcraft_raw::spectral::Camera>,
|
||||
}
|
||||
|
||||
/// The white balance a DNG of a raw's camera RGB (Photo Merge) declares so that it shows as its source does
|
||||
/// ([`WbScaleOf::dng_white`]).
|
||||
pub(crate) enum DngWhite {
|
||||
/// Colour tags with the camera's measured matrices: the DNG reads every white through them, as the source does.
|
||||
Matrices(Box<lightcraft_raw::ColorData>),
|
||||
/// The white the source's scale shows at As Shot.
|
||||
At(lightcraft_color::Xy),
|
||||
}
|
||||
|
||||
impl WbScaleOf {
|
||||
pub(crate) fn new(
|
||||
format: lightcraft_raw::RawFormat,
|
||||
color: &lightcraft_raw::ColorData,
|
||||
wb_multipliers: Option<[f32; 3]>,
|
||||
meta: &lightcraft_meta::Metadata,
|
||||
) -> Self {
|
||||
let own_matrix = lightcraft_raw::color::has_matrix(color);
|
||||
let fitted = crate::camera_preview::file_local_look(format) && !own_matrix;
|
||||
let model = meta.model.as_deref().filter(|_| fitted);
|
||||
let camera = model.and_then(|model| lightcraft_raw::spectral::find(meta.make.as_deref(), model));
|
||||
let presets = camera.is_none() && model.is_some_and(|model| lightcraft_raw::kelvin_presets::covers(meta.make.as_deref(), model));
|
||||
let scale_white = match camera {
|
||||
Some(c) => lightcraft_raw::spectral::as_shot_white_through(c, color, wb_multipliers),
|
||||
None if presets => lightcraft_raw::kelvin_presets::as_shot_white(color, wb_multipliers),
|
||||
None => None,
|
||||
};
|
||||
let covered = camera.is_some() || presets;
|
||||
WbScaleOf { own_matrix, relative: fitted && !covered, legacy_relative: fitted && covered, scale_white, camera }
|
||||
}
|
||||
|
||||
/// What a DNG of this raw's camera RGB declares so that it shows the white balance as this scale does: the
|
||||
/// camera's measured matrices when they give the scale, else the white the scale shows at As Shot (the presets'
|
||||
/// reading; 6500 K / 0 on the relative scale; else `own`, the white the file's tags give).
|
||||
pub(crate) fn dng_white(&self, color: &lightcraft_raw::ColorData, own: lightcraft_color::Xy) -> DngWhite {
|
||||
if let Some(camera) = self.camera {
|
||||
let mut c = lightcraft_raw::ColorData { profile: Default::default(), kelvin_presets: None, ..color.clone() };
|
||||
if camera.fill(&mut c) {
|
||||
return DngWhite::Matrices(Box::new(c));
|
||||
}
|
||||
}
|
||||
if self.relative {
|
||||
return DngWhite::At(lightcraft_color::cct::temp_tint_to_xy(6500.0, 0.0));
|
||||
}
|
||||
DngWhite::At(self.scale_white.unwrap_or(own))
|
||||
}
|
||||
/// The as-shot temperature and tint on the file's scale: the relative scale's reference, the white through
|
||||
/// the measured matrices or the presets, else `own` (the white the file's own tags give). Whole numbers, as the
|
||||
/// catalog keeps them. A covered camera whose file names no white (no multipliers, or no presets) falls back to
|
||||
/// `own`, D65.
|
||||
pub(super) fn as_shot(&self, own: lightcraft_color::Xy) -> (f64, f64) {
|
||||
if self.relative {
|
||||
return (6500.0, 0.0);
|
||||
}
|
||||
let (t, tint) = xy_to_temp_tint(self.scale_white.unwrap_or(own));
|
||||
(t.round(), tint.round())
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw's gain table map with where its developed picture (the default crop, oriented) sits in
|
||||
/// the active area: rendered when the photo's "Camera local tone mapping" option is on.
|
||||
fn local_tone(raw: &lightcraft_raw::RawImage) -> Option<Arc<lightcraft_pipeline::local_tone::LocalTone>> {
|
||||
let map = raw.color.profile.gain_table_map.clone()?;
|
||||
let a = raw.active_area;
|
||||
let (aw, ah) = (a.width.max(1) as f64, a.height.max(1) as f64);
|
||||
let c = raw.develop_crop(a.width, a.height);
|
||||
let rect = [c.x as f64 / aw, c.y as f64 / ah, c.width as f64 / aw, c.height as f64 / ah];
|
||||
let placement = lightcraft_raw::gaintable::SourcePlacement { rect, orientation: raw.orientation };
|
||||
Some(Arc::new(lightcraft_pipeline::local_tone::LocalTone { map, placement }))
|
||||
}
|
||||
|
||||
/// The semantic masks of a DNG that AI masks understand, over the developed image (default crop,
|
||||
/// oriented like it). Person mattes without a confidently selected pixel are left out (the
|
||||
/// Subject mask then falls back to its heuristic); a sky matte counts even when empty (no sky).
|
||||
fn dng_mattes(bytes: &[u8], raw: &lightcraft_raw::RawInfo) -> Option<Arc<lightcraft_pipeline::masks::Mattes>> {
|
||||
use lightcraft_pipeline::masks::{MatteKind, Mattes};
|
||||
if raw.format != lightcraft_raw::RawFormat::Dng {
|
||||
return None;
|
||||
}
|
||||
let mut mattes = Mattes::default();
|
||||
for m in lightcraft_raw::semantic_masks(bytes) {
|
||||
let Some(kind) = matte_kind(&m.name) else { continue };
|
||||
let Some(img) = m.developed(raw.active_area, raw.crop) else { continue };
|
||||
if kind != MatteKind::Sky && !img.data.iter().any(|&v| v >= 128) {
|
||||
continue;
|
||||
}
|
||||
mattes.push(kind, img.into_oriented(raw.orientation));
|
||||
}
|
||||
(!mattes.is_empty()).then(|| Arc::new(mattes))
|
||||
}
|
||||
|
||||
/// What a semantic mask selects, by its `SemanticName`: Apple's (iPhone ProRAW) are named after
|
||||
/// their auxiliary image types, `urn:com:apple:photo:<year>:aux:<type>`. Other names: `None`.
|
||||
fn matte_kind(name: &str) -> Option<lightcraft_pipeline::masks::MatteKind> {
|
||||
use lightcraft_pipeline::masks::MatteKind::*;
|
||||
let kind = name.strip_prefix("urn:com:apple:photo:")?.rsplit(':').next()?;
|
||||
Some(match kind {
|
||||
"semanticskymatte" => Sky,
|
||||
"semanticskinmatte" => Skin,
|
||||
"semantichairmatte" => Hair,
|
||||
"semanticteethmatte" => Teeth,
|
||||
"semanticglassesmatte" => Glasses,
|
||||
"portraiteffectsmatte" => Person,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A DNG `ProfileToneCurve` (linear in, linear out, 1.0 = white after exposure compensation) as the
|
||||
/// finish stage's camera tone curve: 32 knots, log-spaced over 12 stops below white; above white
|
||||
/// the camera tone's shoulder continues it.
|
||||
pub(crate) fn dng_tone_curve(curve: &lightcraft_raw::profile::ToneCurve) -> Option<lightcraft_pipeline::tone::CameraTone> {
|
||||
let knots: [[f32; 2]; 32] = std::array::from_fn(|i| {
|
||||
let x = 2f32.powf(-12.0 + 12.0 * i as f32 / 31.0);
|
||||
[x, curve.eval(x).min(0.9995)]
|
||||
});
|
||||
lightcraft_pipeline::tone::CameraTone::new(knots)
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
use super::fs::{quick_image_srgb, raf_preview_extent, read_prefix, read_prefix_at};
|
||||
use super::*;
|
||||
|
||||
/// Orientation for an embedded preview: its own EXIF orientation when it has one, else the raw file's.
|
||||
pub(super) fn preview_orientation(raw_bytes: &[u8], jpeg_orientation: u16) -> Orientation {
|
||||
if jpeg_orientation > 1 {
|
||||
return Orientation::from_exif(jpeg_orientation);
|
||||
}
|
||||
lightcraft_meta::extract(raw_bytes).orientation.unwrap_or(Orientation::Normal)
|
||||
}
|
||||
|
||||
/// What stands in for a raw file we can't decode: its largest embedded JPEG (with `covering`, the smallest one that is
|
||||
/// at least that big, [`lightcraft_raw::embedded_preview_covering`]), else, for a TIFF-based raw, the file's own first
|
||||
/// image when the TIFF reader can show it (a reduced RGB copy: the only preview some containers carry). Returns image
|
||||
/// bytes for [`lightcraft_codecs::decode`].
|
||||
fn stand_in_image(bytes: &[u8], covering: Option<usize>) -> Option<std::borrow::Cow<'_, [u8]>> {
|
||||
let jpeg = match covering {
|
||||
Some(edge) => lightcraft_raw::embedded_preview_covering(bytes, u32::try_from(edge).unwrap_or(u32::MAX)),
|
||||
None => lightcraft_raw::embedded_preview(bytes),
|
||||
};
|
||||
if let Some(jpeg) = jpeg {
|
||||
return Some(std::borrow::Cow::Owned(jpeg));
|
||||
}
|
||||
let undecodable = lightcraft_raw::probe(bytes).is_some_and(|f| !f.is_supported());
|
||||
(undecodable && lightcraft_codecs::sniff(bytes).is_some_and(|f| f == lightcraft_codecs::Format::Tiff))
|
||||
.then_some(std::borrow::Cow::Borrowed(bytes))
|
||||
}
|
||||
|
||||
/// Shared colour interpretation for quick previews, unsupported RAW fallback and camera-look fitting (`covering`: see
|
||||
/// [`stand_in_image`]).
|
||||
pub(crate) fn decode_raw_preview(
|
||||
bytes: &[u8],
|
||||
opts: lightcraft_codecs::DecodeOptions,
|
||||
covering: Option<usize>,
|
||||
) -> Option<lightcraft_codecs::Decoded> {
|
||||
let jpeg = stand_in_image(bytes, covering)?;
|
||||
// the colour space is a property of the JPEG; a TIFF stand-in (the file itself, or a Hasselblad RGB preview
|
||||
// wrapped as a TIFF) and a JPEG XL preview are read by their own decoders
|
||||
let is_jpeg = jpeg.starts_with(&[0xff, 0xd8]);
|
||||
match lightcraft_raw::embedded_preview_color_space(bytes).filter(|_| is_jpeg) {
|
||||
Some(space) => {
|
||||
let space = match space {
|
||||
lightcraft_raw::PreviewColorSpace::Srgb => lightcraft_codecs::NamedSpace::Srgb,
|
||||
lightcraft_raw::PreviewColorSpace::AdobeRgb => lightcraft_codecs::NamedSpace::AdobeRgb,
|
||||
};
|
||||
lightcraft_codecs::decode_jpeg_with_fallback(&jpeg, opts, space).ok()
|
||||
}
|
||||
None => lightcraft_codecs::decode(&jpeg, opts).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Oriented size of the embedded preview of a raw file.
|
||||
pub(super) fn embedded_preview_size(bytes: &[u8]) -> Option<(u32, u32)> {
|
||||
let jpeg = stand_in_image(bytes, None)?;
|
||||
// headers only, as for other images (issue #367): decoding a full-size preview just for its
|
||||
// size took about a second per file in an import; a decode remains the fallback
|
||||
let (mut w, mut h, orientation) = match lightcraft_codecs::read_header(&jpeg) {
|
||||
Ok(header) => (header.width, header.height, header.orientation),
|
||||
Err(_) => {
|
||||
let d = lightcraft_codecs::decode(&jpeg, lightcraft_codecs::DecodeOptions::fit(64, 64)).ok()?;
|
||||
(d.source_width, d.source_height, d.orientation)
|
||||
}
|
||||
};
|
||||
if preview_orientation(bytes, orientation).swaps_axes() {
|
||||
std::mem::swap(&mut w, &mut h);
|
||||
}
|
||||
Some((w, h))
|
||||
}
|
||||
|
||||
/// The embedded preview of a raw file as a working-space image no larger than `max_edge`, oriented.
|
||||
pub fn load_embedded_preview(bytes: &[u8], max_edge: usize) -> Option<(Rgb32f, SourceInfo)> {
|
||||
// always the largest JPEG: a source's geometry must not depend on its size level (previews match exports)
|
||||
let d = decode_raw_preview(bytes, fit_box(max_edge), None)?;
|
||||
let img = d.to_working();
|
||||
let img = if img.width.max(img.height) > max_edge { fit(&img, max_edge, max_edge, Filter::Mitchell) } else { img };
|
||||
Some((img.oriented(preview_orientation(bytes, d.orientation)), SourceInfo::default()))
|
||||
}
|
||||
|
||||
/// The embedded preview of a raw file for display (sRGB, oriented, no larger than `max_edge`): the
|
||||
/// loupe and grid show it until the raw itself has been developed ([`crate::media::QuickJob`]). The smallest
|
||||
/// embedded JPEG that covers `max_edge` is decoded, not the largest.
|
||||
pub fn embedded_preview_srgb(bytes: &[u8], max_edge: usize) -> Option<lightcraft_raster::Rgba8> {
|
||||
let mut d = decode_raw_preview(bytes, fit_box(max_edge), Some(max_edge))?;
|
||||
if d.image.width.max(d.image.height) > max_edge {
|
||||
d.image = fit(&d.image, max_edge, max_edge, Filter::Box);
|
||||
d.alpha = None;
|
||||
}
|
||||
let o = preview_orientation(bytes, d.orientation);
|
||||
Some(d.to_srgb8().oriented(o))
|
||||
}
|
||||
|
||||
/// Decode options fitting into a `max_edge` square; `usize::MAX` (a full-size load) or any edge past
|
||||
/// `u32::MAX` asks for the largest box rather than wrapping to a small one.
|
||||
pub(super) fn fit_box(max_edge: usize) -> lightcraft_codecs::DecodeOptions {
|
||||
let e = u32::try_from(max_edge).unwrap_or(u32::MAX);
|
||||
lightcraft_codecs::DecodeOptions::fit(e, e)
|
||||
}
|
||||
|
||||
/// Filesystem-backed embedded-preview hook (native).
|
||||
///
|
||||
/// The quick path reads the file's header and its embedded preview and nothing else (see
|
||||
/// [`preview_window`]); a container the header cannot point into is planned from its tags
|
||||
/// (`lightcraft_raw::sparse::preview_plan`, the same module the import path probes with), and only a
|
||||
/// file the planner cannot describe falls back to the whole-file path. The memory gate still counts
|
||||
/// the whole file, which is what the decode of one can hold.
|
||||
pub fn fs_preview_loader() -> PreviewLoader {
|
||||
Arc::new(|path: &str, max_edge: usize| {
|
||||
let len = std::fs::metadata(path).map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)).unwrap_or(0);
|
||||
let gate = crate::memory::work_gate();
|
||||
let _permit = if crate::memory::is_background() { gate.acquire(len.saturating_mul(2)) } else { gate.acquire_urgent(len.saturating_mul(2)) };
|
||||
if let Some(image) = preview_window(path, max_edge)
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|(header, window, read)| quick_image_srgb(&header, &window, read.adobe_rgb, max_edge))
|
||||
{
|
||||
return Some(image);
|
||||
}
|
||||
embedded_preview_srgb(&std::fs::read(path).ok()?, max_edge)
|
||||
})
|
||||
}
|
||||
|
||||
/// What [`preview_window`] read from a file, so a caller can see what a preview cost.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PreviewRead {
|
||||
/// Bytes read.
|
||||
pub read: u64,
|
||||
/// The file's size.
|
||||
pub total: u64,
|
||||
/// Whether the preview came from a bounded read (`false`: the whole file was read, which is what
|
||||
/// every preview cost before the header path existed).
|
||||
pub header_path: bool,
|
||||
/// Whether the sparse planner named the ranges, rather than a format's own header fields: the
|
||||
/// path a Canon CR3 and the TIFF raws whose preview tag sits past the prefix take (`false` on
|
||||
/// the header path, and on the whole-file fallback).
|
||||
pub planned: bool,
|
||||
/// Adobe RGB when the container says the preview is in it and the JPEG doesn't say otherwise
|
||||
/// (`decode_raw_preview` applies the same declaration): the quick decode applies it too.
|
||||
pub adobe_rgb: bool,
|
||||
}
|
||||
|
||||
impl PreviewRead {
|
||||
/// The share of the file that was read, `0.0`..=`1.0`.
|
||||
pub fn fraction(self) -> f64 {
|
||||
if self.total == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
(self.read as f64 / self.total as f64).clamp(0.0, 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// The file's header and its embedded preview, read without the rest of the file: `(header bytes,
|
||||
/// preview bytes, what was read)`. `None` when the header points at no preview this build can find,
|
||||
/// which is the caller's cue to read the file whole. `max_edge` is the size the preview is for: where a file keeps
|
||||
/// several JPEGs (the plan route), the window is the one [`embedded_preview_srgb`] decodes for that size, the smallest
|
||||
/// that covers it ([`lightcraft_raw::embedded_preview_covering`]).
|
||||
///
|
||||
/// Why it exists: a 56 MB Fuji RAF keeps its JPEG in the first 5.6 MB (measured: `DSCF9492.RAF`),
|
||||
/// so reading the file whole to extract it costs ten times the bytes — and on a network share ten
|
||||
/// times the wait (measured on that file: 2.5 s local against 25.6 s over SMB). `embedded_preview`
|
||||
/// still needs the whole container, so the header comes back with the window; for a preview taken
|
||||
/// out of a container that carries no preview colour space of its own (Nikon's maker note) the
|
||||
/// whole-file fallback stays in charge.
|
||||
pub fn preview_window(path: &str, max_edge: usize) -> Result<Option<(Vec<u8>, Vec<u8>, PreviewRead)>, String> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
|
||||
let mut file = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;
|
||||
let total = file.metadata().map_err(|e| format!("{path}: {e}"))?.len();
|
||||
let mut prefix = read_prefix(&mut file, path, total)?;
|
||||
|
||||
// What the header itself declares, before the container reader is asked: it clamps a slice to
|
||||
// the buffer it was given, so a prefix that stops inside the declared preview yields a
|
||||
// self-consistently short range that looks trustworthy (measured on a real 56 MB DSCF9492.RAF:
|
||||
// a 4 KiB prefix reports 3948 bytes where the file holds 5.6 MB). Reading the declared extent
|
||||
// first costs nothing — it lives in the first bytes of every format covered here.
|
||||
if let Some(extent) = raf_preview_extent(&prefix)
|
||||
&& extent > prefix.len() as u64
|
||||
{
|
||||
prefix = read_prefix_at(&mut file, path, extent.min(total))?;
|
||||
}
|
||||
let Some(range) = lightcraft_raw::bounded_preview(&prefix) else {
|
||||
// The header carries no pointer this path reads — a Canon CR3's boxes, a TIFF raw whose
|
||||
// preview tag sits past the prefix, the containers whose preview only a scan finds: ask the
|
||||
// sparse planner which ranges `embedded_preview` reads before handing the caller the
|
||||
// whole-file fallback.
|
||||
return planned_preview(&mut file, path, total, max_edge);
|
||||
};
|
||||
// A preview at the file's end may have been padded past it: clamp rather than fail.
|
||||
let end = range.offset.saturating_add(range.window_len).min(total);
|
||||
let len = usize::try_from(end.saturating_sub(range.offset)).map_err(|_| format!("{path}: preview too large"))?;
|
||||
// When the prefix already covers the range (the usual case: the prefix was grown to the declared
|
||||
// extent), take the window out of it. Reading those bytes twice would double a 5.6 MB preview.
|
||||
let prefix_len = prefix.len() as u64;
|
||||
let from_prefix = usize::try_from(range.offset).ok().and_then(|start| prefix.get(start..start.checked_add(len)?)).map(<[u8]>::to_vec);
|
||||
let (window, bytes_read) = match from_prefix {
|
||||
Some(window) => (window, prefix_len),
|
||||
None => {
|
||||
let mut window = vec![0u8; len];
|
||||
file.seek(SeekFrom::Start(range.offset)).map_err(|e| format!("{path}: {e}"))?;
|
||||
file.read_exact(&mut window).map_err(|e| format!("{path}: {e}"))?;
|
||||
(window, prefix_len + len as u64)
|
||||
}
|
||||
};
|
||||
|
||||
// A lying pointer must not cost the user their preview: hand the caller the whole-file fallback.
|
||||
if lightcraft_raw::embedded_preview_from_range(&window, range).is_none() {
|
||||
return Ok(None);
|
||||
}
|
||||
let read = PreviewRead { read: bytes_read, total, header_path: true, planned: false, adobe_rgb: false };
|
||||
// On a network share the bytes are the wait, so say what this preview actually cost. A window
|
||||
// taken from the prefix cost nothing beyond the prefix itself.
|
||||
if lightcraft_pipeline::profiling() {
|
||||
eprintln!("[profile] preview {path}: read {} of {} bytes (header {}, window {})", read.read, total, prefix_len, window.len());
|
||||
}
|
||||
Ok(Some((prefix, window, read)))
|
||||
}
|
||||
|
||||
/// The most times the sparse planner may name ranges before the preview gives up: the plan is
|
||||
/// monotone (it never asks for a range twice), so a real file needs a handful.
|
||||
const MAX_PREVIEW_PLAN_ROUNDS: usize = 8;
|
||||
|
||||
/// Tenths of a file the planner may have read before the preview gives up and the whole-file path
|
||||
/// takes over. The import path bounds its own loop the same way; a "preview" that wants most of the
|
||||
/// file has stopped being one.
|
||||
const MAX_PREVIEW_PLAN_SHARE: u64 = 6;
|
||||
|
||||
/// The largest file the planner path builds its buffer for. The raws it serves are far below this;
|
||||
/// a file past it is read whole as before rather than allocating its length up front.
|
||||
const MAX_PREVIEW_PLAN_BYTES: u64 = 1 << 30;
|
||||
|
||||
/// The header the quick path is handed on the planner route. The header route grows its prefix to
|
||||
/// the preview's declared extent, so `quick_image_srgb` can read the file's own EXIF orientation out
|
||||
/// of it when the preview JPEG carries none; this route reads a bounded prefix instead, big enough
|
||||
/// for IFD0 (which is where that tag lives) and for a CR3's metadata boxes.
|
||||
pub(super) const PLAN_PREFIX: u64 = 64 * 1024;
|
||||
|
||||
/// The preview of a container the header-only path cannot answer for, from the byte ranges
|
||||
/// [`lightcraft_raw::sparse::preview_plan`] says [`lightcraft_raw::embedded_preview`] reads.
|
||||
///
|
||||
/// The planner is asked about a buffer of the file's whole length in which only the ranges named so
|
||||
/// far hold bytes, and only those ranges are read: the sensor data in the bulk ranges is not. The
|
||||
/// buffer is the file's length, which the loader's memory gate already counts, and its untouched
|
||||
/// pages stay zero and are never written — though on macOS a freed buffer of that size may stay in
|
||||
/// the allocator's cache rather than going back to the OS (measured on a 38k-photo import, #832), so
|
||||
/// this path's cost is the bytes read, not a promise about RSS.
|
||||
///
|
||||
/// `None` — the caller's cue to read the file whole, exactly as when the header declines — when the
|
||||
/// planner says it cannot describe the file (NEF, ORF and PEF probe from samples; a structure it
|
||||
/// does not trust), when the ranges it names do not fit the buffer or want most of the file, or when
|
||||
/// the quick path could not reproduce what the whole-file path shows (the two container facts
|
||||
/// below). The planner's contract is the one its corpus test asserts over real files (what it loaded
|
||||
/// gives what the whole file gives), so a window that still fails to decode ends in the same
|
||||
/// whole-file fallback in [`fs_preview_loader`], never in a wrong picture.
|
||||
fn planned_preview(file: &mut std::fs::File, path: &str, total: u64, max_edge: usize) -> Result<Option<(Vec<u8>, Vec<u8>, PreviewRead)>, String> {
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
|
||||
if total > MAX_PREVIEW_PLAN_BYTES {
|
||||
return Ok(None);
|
||||
}
|
||||
let Ok(len) = usize::try_from(total) else { return Ok(None) };
|
||||
let mut buf = vec![0u8; len];
|
||||
let header = read_prefix_at(file, path, PLAN_PREFIX.min(total))?;
|
||||
let Some(head) = buf.get_mut(..header.len()) else { return Ok(None) };
|
||||
head.copy_from_slice(&header);
|
||||
let mut loaded = lightcraft_raw::sparse::Ranges::new();
|
||||
loaded.insert(0, header.len() as u64);
|
||||
for _ in 0..MAX_PREVIEW_PLAN_ROUNDS {
|
||||
match lightcraft_raw::sparse::preview_plan(&buf, &loaded) {
|
||||
lightcraft_raw::sparse::HeaderPlan::Need(ranges) => {
|
||||
let wanted = loaded.total().saturating_add(ranges.total());
|
||||
if wanted.saturating_mul(10) > total.saturating_mul(MAX_PREVIEW_PLAN_SHARE) {
|
||||
return Ok(None);
|
||||
}
|
||||
for &(start, end) in ranges.spans() {
|
||||
let (Ok(a), Ok(b)) = (usize::try_from(start), usize::try_from(end)) else { return Ok(None) };
|
||||
let Some(dst) = buf.get_mut(a..b) else { return Ok(None) };
|
||||
file.seek(SeekFrom::Start(start)).map_err(|e| format!("{path}: {e}"))?;
|
||||
file.read_exact(dst).map_err(|e| format!("{path}: {e}"))?;
|
||||
loaded.insert(start, end);
|
||||
}
|
||||
}
|
||||
lightcraft_raw::sparse::HeaderPlan::Ready => {
|
||||
// the plan loads every preview's strips, so the JPEG picked for `max_edge` is the whole file's pick
|
||||
let edge = u32::try_from(max_edge).unwrap_or(u32::MAX);
|
||||
let Some(window) = lightcraft_raw::embedded_preview_covering(&buf, edge) else { return Ok(None) };
|
||||
// The quick path hands the JPEG to the decoder alone, so what the *container* says
|
||||
// about the preview has to be something the bytes it is handed can show. Two container
|
||||
// facts change the pixels and are not in the JPEG: the preview's colour space (which
|
||||
// the whole-file path applies through `decode_raw_preview`) and, when the JPEG carries
|
||||
// no orientation of its own, the file's EXIF orientation. The colour space is read
|
||||
// here and handed on ([`PreviewRead::adobe_rgb`]: a Sony α1 writes Adobe RGB previews,
|
||||
// which used to send each of them to the whole-file path, issue #1440); a container
|
||||
// that says sRGB agrees with the JPEG-only decode (its own declaration, else sRGB).
|
||||
// Where the orientation is present and the header cannot answer for it, the
|
||||
// whole-file path keeps the preview.
|
||||
let adobe_rgb = lightcraft_raw::embedded_preview_color_space(&buf) == Some(lightcraft_raw::PreviewColorSpace::AdobeRgb);
|
||||
// `extract` copies a TIFF's bytes to hand on its Exif block, so ask the cheap side
|
||||
// first: a JPEG that carries its own orientation needs nothing from the container.
|
||||
if lightcraft_meta::extract(&window).orientation.is_none()
|
||||
&& lightcraft_meta::extract(&header).orientation.is_none()
|
||||
&& lightcraft_meta::extract(&buf).orientation.is_some()
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let read = PreviewRead { read: loaded.total(), total, header_path: true, planned: true, adobe_rgb };
|
||||
// A plan-driven preview is the one that used to cost the whole file, so it is worth
|
||||
// saying what it cost now too.
|
||||
if lightcraft_pipeline::profiling() {
|
||||
eprintln!("[profile] preview {path}: read {} of {} bytes (plan, window {})", read.read, total, window.len());
|
||||
}
|
||||
// The planner's buffer is the file's length, so give its pages back the way a decode
|
||||
// does (see `fs_pair_loader`).
|
||||
drop(buf);
|
||||
crate::memory::release();
|
||||
return Ok(Some((header, window, read)));
|
||||
}
|
||||
lightcraft_raw::sparse::HeaderPlan::Whole(_) => return Ok(None),
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
use super::load::WbScaleOf;
|
||||
use super::preview::embedded_preview_size;
|
||||
use super::*;
|
||||
|
||||
pub(super) fn meta_of(m: &lightcraft_meta::Metadata) -> (Meta, Option<String>) {
|
||||
let shutter = m.exposure_time.map(|t| if t >= 1.0 { format!("{t:.0}") } else { format!("1/{:.0}", 1.0 / t) }).unwrap_or_default();
|
||||
let camera = [m.make.clone().unwrap_or_default(), m.model.clone().unwrap_or_default()].join(" ").trim().to_string();
|
||||
let meta = Meta {
|
||||
camera,
|
||||
// (a camera that writes no lens name, like Nikon's DSLRs, still says what range the lens covers)
|
||||
lens: m.lens_model.clone().or_else(|| m.lens_spec.and_then(lightcraft_meta::lens_spec_name)).unwrap_or_default(),
|
||||
focal_mm: m.focal_length.map(|f| f as f32),
|
||||
aperture: m.f_number.map(|f| f as f32),
|
||||
shutter,
|
||||
iso: m.iso,
|
||||
location: m.sublocation.clone().unwrap_or_default(),
|
||||
city: m.city.clone().unwrap_or_default(),
|
||||
state: m.state.clone().unwrap_or_default(),
|
||||
country: m.country.clone().unwrap_or_default(),
|
||||
alt_text: m.alt_text.clone().unwrap_or_default(),
|
||||
extended_description: m.extended_description.clone().unwrap_or_default(),
|
||||
gps: m.gps.as_ref().map(|g| (g.latitude, g.longitude)),
|
||||
title: m.title.clone().unwrap_or_default(),
|
||||
caption: m.caption.clone().unwrap_or_default(),
|
||||
copyright: m.copyright.clone().unwrap_or_default(),
|
||||
copyright_status: lightcraft_catalog::CopyrightStatus::from_marked(m.copyright_marked),
|
||||
usage_terms: m.usage_terms.clone().unwrap_or_default(),
|
||||
copyright_url: m.copyright_url.clone().unwrap_or_default(),
|
||||
creator: m.artist.clone().unwrap_or_default(),
|
||||
// paths from `lr:hierarchicalSubject`, names from `dc:subject` that aren't their levels
|
||||
keywords: lightcraft_catalog::keywords::from_file(&m.keywords, &m.hierarchical_keywords),
|
||||
regions: m.regions.clone(),
|
||||
focus: m.focus.clone(),
|
||||
};
|
||||
(meta, m.capture_time.as_ref().map(|d| d.to_iso()))
|
||||
}
|
||||
|
||||
/// Lens corrections embedded in a raw's `OpcodeList3` (`WarpRectilinear`, `WarpRectilinear2`, `FixVignetteRadial`: a DNG's own, or the
|
||||
/// raw reader's equivalent of the camera's correction, e.g. Panasonic / Leica RW2 distortion), re-expressed for the
|
||||
/// default-cropped, EXIF-oriented image. These are the only "profile" corrections LightCraft applies.
|
||||
pub fn embedded_lens(raw: &lightcraft_raw::RawInfo) -> Option<lightcraft_develop::EmbeddedLens> {
|
||||
use lightcraft_develop::{EmbeddedLens, EmbeddedVignette, EmbeddedWarp, EmbeddedWarpStage, WARP_STAGES};
|
||||
use lightcraft_geom::Point;
|
||||
use lightcraft_raw::Opcode;
|
||||
let (aw, ah) = (raw.active_area.width as f64, raw.active_area.height as f64);
|
||||
if aw < 2.0 || ah < 2.0 {
|
||||
return None;
|
||||
}
|
||||
let c = raw.crop.clipped(raw.active_area.width, raw.active_area.height);
|
||||
let (cx0, cy0, cw, ch) =
|
||||
if c.width == 0 || c.height == 0 { (0.0, 0.0, aw, ah) } else { (c.x as f64, c.y as f64, c.width as f64, c.height as f64) };
|
||||
let long = cw.max(ch);
|
||||
// opcode centres are relative to the (uncropped) active area, in pixel-index units
|
||||
let centre = |rel: [f64; 2]| -> (Point, f64) {
|
||||
let (px, py) = (rel[0] * (aw - 1.0), rel[1] * (ah - 1.0));
|
||||
let m = [(0.0, 0.0), (aw - 1.0, 0.0), (0.0, ah - 1.0), (aw - 1.0, ah - 1.0)]
|
||||
.iter()
|
||||
.map(|&(x, y)| (x - px).hypot(y - py))
|
||||
.fold(0.0, f64::max)
|
||||
.max(1e-9);
|
||||
(Point::new((px + 0.5 - cx0) / cw, (py + 0.5 - cy0) / ch), m / long)
|
||||
};
|
||||
let mut lens = EmbeddedLens::default();
|
||||
// opcodes in list order, minus the ones the DNG 1.6 skip rule drops (a WarpRectilinear that follows an optional
|
||||
// WarpRectilinear2)
|
||||
let ops: Vec<&Opcode> = lightcraft_raw::opcodes::applied_ops(&raw.opcodes.list3).collect();
|
||||
// A DNG with a WarpRectilinear2 keeps every warp opcode as a chain of stages (each warps the one before's output);
|
||||
// without one the first WarpRectilinear is the lens warp, as it always was.
|
||||
let chain = ops.iter().any(|op| matches!(op, Opcode::WarpRectilinear2 { .. }));
|
||||
let mut stages = Vec::new();
|
||||
for op in ops {
|
||||
match op {
|
||||
Opcode::WarpRectilinear2 { planes, center, reciprocal, .. } if !planes.is_empty() => {
|
||||
let (center, radius) = centre(*center);
|
||||
let p = |i: usize| planes[i.min(planes.len() - 1)];
|
||||
stages.push(EmbeddedWarpStage { planes: [p(0), p(1), p(2)], center, radius, reciprocal: *reciprocal });
|
||||
}
|
||||
Opcode::WarpRectilinear { planes, center } if chain && !planes.is_empty() => {
|
||||
// WarpRectilinear is the even-power case: kr0 + kr1 r² + kr2 r⁴ + kr3 r⁶, no radius limit
|
||||
let (center, radius) = centre(*center);
|
||||
let p = |i: usize| {
|
||||
let k = planes[i.min(planes.len() - 1)];
|
||||
let mut s = [0.0; lightcraft_raw::opcodes::WR2_LEN];
|
||||
s[0] = k[0];
|
||||
s[2] = k[1];
|
||||
s[4] = k[2];
|
||||
s[6] = k[3];
|
||||
s[15] = k[4];
|
||||
s[16] = k[5];
|
||||
s[18] = 1e6;
|
||||
s
|
||||
};
|
||||
stages.push(EmbeddedWarpStage { planes: [p(0), p(1), p(2)], center, radius, reciprocal: false });
|
||||
}
|
||||
Opcode::WarpRectilinear { planes, center } if !chain && !planes.is_empty() && lens.warp.is_none() => {
|
||||
let (center, radius) = centre(*center);
|
||||
let p = |i: usize| planes[i.min(planes.len() - 1)];
|
||||
lens.warp = Some(EmbeddedWarp { planes: [p(0), p(1), p(2)], center, radius });
|
||||
}
|
||||
Opcode::FixVignetteRadial { k, center } if lens.vignette.is_none() => {
|
||||
let (center, radius) = centre(*center);
|
||||
lens.vignette = Some(EmbeddedVignette { k: *k, center, radius });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// (more stages than a lens keeps: the first ones; real files carry two)
|
||||
for (slot, st) in lens.stages.iter_mut().zip(stages.into_iter().take(WARP_STAGES)) {
|
||||
*slot = Some(st);
|
||||
}
|
||||
if lens.warp.is_none() && lens.vignette.is_none() && !lens.has_stages() {
|
||||
return None;
|
||||
}
|
||||
Some(lightcraft_pipeline::optics::reorient_lens(&lens, raw.orientation, cw, ch))
|
||||
}
|
||||
|
||||
fn ext_upper(name: &str) -> String {
|
||||
std::path::Path::new(name).extension().map(|e| e.to_string_lossy().to_uppercase()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Probe a file's bytes: kind, dimensions (oriented), metadata. No pixel data is decompressed:
|
||||
/// raws are described from their headers ([`lightcraft_raw::probe_info`]), other images too
|
||||
/// ([`lightcraft_codecs::read_header`], which refuses truncated files but can't see damage inside
|
||||
/// compressed data that is all there: such a file imports and shows as unreadable when rendered).
|
||||
pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result<ProbeInfo, String> {
|
||||
let content_hash = Some(lightcraft_preview::hash_bytes(bytes).to_string());
|
||||
let m = lightcraft_meta::extract(bytes);
|
||||
let (meta, captured) = meta_of(&m);
|
||||
if lightcraft_raw::probe(bytes).is_some() {
|
||||
let raw = match lightcraft_raw::probe_info(bytes).map_err(|e| preview_reason(bytes, e)) {
|
||||
Ok(r) => r,
|
||||
Err(Ok(why)) => {
|
||||
// a raw variant we can't decode yet: describe it from its embedded preview
|
||||
let (w, h) = embedded_preview_size(bytes).ok_or(format!("unsupported raw ({why}) without an embedded preview"))?;
|
||||
return Ok(ProbeInfo {
|
||||
width: w,
|
||||
height: h,
|
||||
format: ext_upper(name),
|
||||
kind: MediaKind::Raw,
|
||||
file_size: bytes.len() as u64,
|
||||
captured,
|
||||
meta,
|
||||
as_shot_wb: None,
|
||||
content_hash,
|
||||
xmp: lightcraft_meta::embedded(bytes).xmp,
|
||||
preview_only: Some(why),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
Err(Err(e)) => return Err(e),
|
||||
};
|
||||
let (w, h) = raw.developed_size();
|
||||
let (mut w, mut h) = (w.max(1) as u32, h.max(1) as u32);
|
||||
if raw.orientation.swaps_axes() {
|
||||
std::mem::swap(&mut w, &mut h);
|
||||
}
|
||||
let scale = WbScaleOf::new(raw.format, &raw.color, raw.wb_multipliers, &raw.metadata);
|
||||
let as_shot_wb = Some(scale.as_shot(lightcraft_raw::color::as_shot_white_xy_of(&raw)));
|
||||
let embedded_lens = crate::lens_profiles::for_raw(&raw, || m.clone());
|
||||
return Ok(ProbeInfo {
|
||||
embedded_lens,
|
||||
width: w,
|
||||
height: h,
|
||||
format: ext_upper(name),
|
||||
kind: MediaKind::Raw,
|
||||
file_size: bytes.len() as u64,
|
||||
captured,
|
||||
file_modified: None,
|
||||
meta,
|
||||
as_shot_wb,
|
||||
content_hash,
|
||||
xmp: lightcraft_meta::embedded(bytes).xmp,
|
||||
preview_only: None,
|
||||
});
|
||||
}
|
||||
let fmt = lightcraft_codecs::sniff(bytes).ok_or("unrecognized file format")?;
|
||||
if let Some(why) = fmt.not_decodable() {
|
||||
// e.g. "Heif files can't be opened: HEIC/HEIF support isn't included in this build of LightCraft"
|
||||
return Err(format!("{fmt:?} files can't be opened: {why}"));
|
||||
}
|
||||
// headers only (issue #367: decoding the pixels was nearly all of an import's CPU time)
|
||||
let header = lightcraft_codecs::read_header(bytes).map_err(|e| e.to_string())?;
|
||||
let o = Orientation::from_exif(header.orientation);
|
||||
let (mut w, mut h) = (header.width, header.height);
|
||||
if o.swaps_axes() {
|
||||
std::mem::swap(&mut w, &mut h);
|
||||
}
|
||||
let format = match ext_upper(name).as_str() {
|
||||
"JPG" | "JPEG" => "JPEG".to_string(),
|
||||
"" => format!("{fmt:?}").to_uppercase(),
|
||||
e => e.to_string(),
|
||||
};
|
||||
Ok(ProbeInfo {
|
||||
width: w,
|
||||
height: h,
|
||||
format,
|
||||
kind: MediaKind::Image,
|
||||
file_size: bytes.len() as u64,
|
||||
captured,
|
||||
file_modified: None,
|
||||
meta,
|
||||
as_shot_wb: None,
|
||||
content_hash,
|
||||
embedded_lens: None,
|
||||
xmp: None,
|
||||
preview_only: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Why a raw that failed to decode should show its embedded preview instead (`Ok`), or the error
|
||||
/// to report (`Err`). Variants we can't decode yet always fall back. So does any CR3 error: the CRX
|
||||
/// decoder is verified on few bodies, and every CR3 opened from its embedded JPEG before it existed.
|
||||
/// So does any other failure of a recognised raw (damaged or oversized raw data, unreadable TIFF
|
||||
/// structure): its preview may still be intact. Only a file that is not a raw reports an error.
|
||||
pub(super) fn preview_reason(bytes: &[u8], e: lightcraft_raw::RawError) -> Result<String, String> {
|
||||
use lightcraft_raw::RawError;
|
||||
match e {
|
||||
RawError::Unsupported(why) => Ok(why),
|
||||
e if lightcraft_raw::probe(bytes) == Some(lightcraft_raw::RawFormat::Cr3) => Ok(format!("CR3 {e}")),
|
||||
RawError::NotRaw => Err(RawError::NotRaw.to_string()),
|
||||
e => Ok(e.to_string()),
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 532 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user