Compare commits

..
9 Commits
Author SHA1 Message Date
dtourolle 2c947430e6 Release 0.19.3
Benchmarks / CPU and I/O (per commit) (push) Successful in 5m26s
Benchmarks / Frame budget (on demand) (push) Skipped
Traceability / Requirement traces (push) Successful in 1m9s
Build and test / Android (aarch64) (push) Successful in 30m44s
Build and test / android-image (push) Successful in 3s
🐳 Android image / Build and push (push) Successful in 2s
Build and test / Desktop (Linux) (push) Successful in 49m45s
Build and test / windows-image (push) Successful in 1s
🐳 Windows image / Build and push (push) Successful in 1s
Build and test / Layer separation (push) Successful in 35s
Build and test / Windows (x86_64, cross) (push) Successful in 36m12s
Build and test / Publish the release (push) Successful in 1m12s
2026-09-30 22:46:17 -04:00
dtourolle 36556729f1 Let Back close the presets menu instead of the application
The presets menu at the foot of the tool rail is a PopupWindow, and
showing a popup takes focus off the develop view until it closes. The
menu held nothing focusable, so Android's Back gesture, pressed to
dismiss it, found no focus item, went unanswered, and the platform
closed the application. Slint closes a popup on Escape by itself but
not on Back.

The menu now holds a key scope, as the film list does, that closes it
on Back or Escape. The next Back leaves develop for the grid.
2026-09-30 22:11:51 -04:00
dtourolle 6f33517b35 Cut panorama overlaps along seams instead of averaging them
The merge weighted every overlap pixel by its distance from each frame's
edge, a 200 px linear cross-fade. Anything the frames disagreed on —
parallax in the near foreground, grass in the wind, a walker — came out
twice at half strength: a soft double edge at 1:1.

dr_pano::seam picks, per output texel at proxy resolution, which frame a
pixel comes from. Where a new frame overlaps the composite the cost is the
gain-corrected difference plus local detail plus nearness to either
frame's edge, taken as the worst over a small window, and the cut is a
dynamic-programming path across the overlap. merge.wgsl weights each frame
by its tent-filtered share of that map, a 64 px blend that follows the
seam, with the edge feather kept as the fallback. The page's preview uses
the same map, and examples/merge.rs takes --feather-only for comparison.
2026-09-30 21:57:44 -04:00
dtourolle 1d7115437b Date a photograph from its name when its header has none
WhatsApp strips every EXIF tag and names the file "WhatsApp Image
2023-06-15 at 07.00.42.jpeg"; Windows Phone, Android cameras and
darktable's import put the date in the name too. Those images sorted
after everything else and were absent from the timeline.

name_dates reads a date (and a time, when one follows) from the file
name, then from the innermost folder that states one. A sequence number
after a date is not read as a time, and a bare year folder is not a date.
EXIF always wins: only examined rows still undated are filled.

The sweep and the metadata repair fill as they mark an image examined,
and the open backfill fills catalogs examined by earlier builds. On the
reference library that takes 274 undated images to 10; the no-op case is
a seek on images_captured, 0.6 ms an open.
2026-09-30 21:45:54 -04:00
dtourolle caae65c78d Import from an SD card or card reader on Android
Import was switched off on Android: `imports_supported` was true only for
`target_os = "linux"`, and its comment said Android has no path to read a
card by and nowhere to write the copies. Neither holds. With "all files
access" (MANAGE_EXTERNAL_STORAGE, API 30) an app reads the root of an SD
card or a USB card reader by path, `/storage/9C33-6BBD`, and the importer
only ever writes into its own staging directory, which is a plain
directory on Android too. So the engine runs unchanged; what was missing
was finding the card and the permission.

- The manifest declares MANAGE_EXTERNAL_STORAGE, and
  READ_EXTERNAL_STORAGE up to API 29 with requestLegacyExternalStorage,
  which is the same access on 28 and 29.
- Cards.java lists the mounted non-primary volumes through
  StorageManager and opens the system "All files access" page for this
  app. dr_ui::cards is the JNI bridge, through saf's helpers.
- The import page on Android asks for the permission with an "Allow
  access" button until it has it, rather than showing an empty list that
  reads as "no card", and watches for the grant so the list fills in when
  the user comes back from settings.

Google Play restricts this permission to file managers and the like;
DarkRoom is sideloaded, so that does not apply.
2026-09-30 21:30:09 -04:00
dtourolle fcccc2c2e0 Release 0.19.2
Benchmarks / CPU and I/O (per commit) (push) Successful in 5m29s
Benchmarks / Frame budget (on demand) (push) Skipped
Traceability / Requirement traces (push) Successful in 1m4s
Build and test / Android (aarch64) (push) Successful in 31m8s
Build and test / android-image (push) Successful in 2s
🐳 Android image / Build and push (push) Successful in 2s
Build and test / Desktop (Linux) (push) Successful in 50m33s
Build and test / windows-image (push) Successful in 3s
🐳 Windows image / Build and push (push) Successful in 2s
Build and test / Layer separation (push) Successful in 33s
Build and test / Windows (x86_64, cross) (push) Successful in 36m27s
Build and test / Publish the release (push) Successful in 59s
2026-09-29 21:31:58 -04:00
dtourolle 1bc04870c3 Let a crop be trimmed from one edge
Four bar handles at the midpoints of the sides, each moving only its
own side along the axis across it. The overlay reports an edge as 0.5
on the axis it does not move, so the anchor Rust takes is the middle
of the far side.

Under a ratio lock the dragged axis leads. with_aspect grew the short
axis onto the ratio, which for an edge pulled inward made the untouched
axis the leader and pushed the edge straight back out.
2026-09-29 21:31:27 -04:00
dtourolle 4da2ec39b3 Fit the photograph clear of the roll and the floating row while composing
A crop handle straddles the picture's edge. With the photograph fitted
to the whole canvas, the bottom handles sat in the photo roll's band,
whose swipe handler takes every press inside it, and the bottom-left
one under the "Done Composing" row, which is declared after the overlay
and whose buttons press 44px tall. Both were drawn and could not be
grabbed: on a laptop-shaped window, one or the other for nearly any
photograph.

While composing, the canvas box is inset 16px from its clip and stops
above the band, the row's margin and the row's hit height. The band is
measured once, on the canvas, and the row reads it from there.
2026-09-29 21:31:27 -04:00
dtourolle 9558b77759 Say how to build and install from source, not only how to run it
The README gave cargo run and nothing else. A binary run from target/
finds no models and, in a release build, no manual, because both are
looked up only where an install puts them. Spell out the Arch package,
a /usr/local install mirroring the PKGBUILD, the Windows installer
cross-build and where it lands, and the Android APK.
2026-09-29 21:29:17 -04:00
33 changed files with 2407 additions and 262 deletions
Generated
+25 -25
View File
@@ -1265,7 +1265,7 @@ checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
[[package]] [[package]]
name = "darkroom-android" name = "darkroom-android"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"android_logger", "android_logger",
"dr-plat", "dr-plat",
@@ -1278,7 +1278,7 @@ dependencies = [
[[package]] [[package]]
name = "darkroom-desktop" name = "darkroom-desktop"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"dr-plat", "dr-plat",
@@ -1454,7 +1454,7 @@ checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
[[package]] [[package]]
name = "dr-bench" name = "dr-bench"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"dr-catalog", "dr-catalog",
@@ -1471,7 +1471,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-catalog" name = "dr-catalog"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"dr-face", "dr-face",
"dr-plat", "dr-plat",
@@ -1486,7 +1486,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-decode" name = "dr-decode"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"dr-types", "dr-types",
"env_logger", "env_logger",
@@ -1500,7 +1500,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-export" name = "dr-export"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"dr-decode", "dr-decode",
"dr-gpu", "dr-gpu",
@@ -1519,7 +1519,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-face" name = "dr-face"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"dr-inference-engine", "dr-inference-engine",
"env_logger", "env_logger",
@@ -1532,7 +1532,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-film" name = "dr-film"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"log", "log",
"serde", "serde",
@@ -1541,7 +1541,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-gpu" name = "dr-gpu"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"dr-decode", "dr-decode",
@@ -1559,7 +1559,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-inference-engine" name = "dr-inference-engine"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"env_logger", "env_logger",
"libloading", "libloading",
@@ -1574,7 +1574,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-ingest" name = "dr-ingest"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"dr-plat", "dr-plat",
"dr-types", "dr-types",
@@ -1586,7 +1586,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-lens" name = "dr-lens"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"lensfun", "lensfun",
"log", "log",
@@ -1594,7 +1594,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-pano" name = "dr-pano"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"dr-decode", "dr-decode",
"dr-inference-engine", "dr-inference-engine",
@@ -1608,7 +1608,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-pipeline" name = "dr-pipeline"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"dr-types", "dr-types",
"log", "log",
@@ -1617,7 +1617,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-plat" name = "dr-plat"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"android-native-keyring-store", "android-native-keyring-store",
"dr-types", "dr-types",
@@ -1633,7 +1633,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-preset-xmp" name = "dr-preset-xmp"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"dr-pipeline", "dr-pipeline",
"log", "log",
@@ -1643,7 +1643,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-segment" name = "dr-segment"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"dr-inference-engine", "dr-inference-engine",
"env_logger", "env_logger",
@@ -1656,7 +1656,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-sync" name = "dr-sync"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"dr-plat", "dr-plat",
@@ -1670,7 +1670,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-sync-folder" name = "dr-sync-folder"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"dr-sync", "dr-sync",
@@ -1682,7 +1682,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-sync-nextcloud" name = "dr-sync-nextcloud"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"dr-decode", "dr-decode",
@@ -1704,7 +1704,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-thumbs" name = "dr-thumbs"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"dr-types", "dr-types",
"jpeg-encoder", "jpeg-encoder",
@@ -1716,7 +1716,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-types" name = "dr-types"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
@@ -1725,7 +1725,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-ui" name = "dr-ui"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
@@ -1773,7 +1773,7 @@ dependencies = [
[[package]] [[package]]
name = "dr-xmp" name = "dr-xmp"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"dr-types", "dr-types",
"log", "log",
@@ -7107,7 +7107,7 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]] [[package]]
name = "traceability" name = "traceability"
version = "0.19.1" version = "0.19.3"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"proc-macro2", "proc-macro2",
+1 -1
View File
@@ -32,7 +32,7 @@ members = [
exclude = ["third_party"] exclude = ["third_party"]
[workspace.package] [workspace.package]
version = "0.19.1" version = "0.19.3"
edition = "2021" edition = "2021"
rust-version = "1.92" rust-version = "1.92"
license = "GPL-3.0-or-later" license = "GPL-3.0-or-later"
+103 -6
View File
@@ -83,28 +83,125 @@ texture directly — no readback between the GPU and the screen.
| Windows | `DarkRoom-<version>-x86_64-setup.exe`, cross-built by CI ([windows.md](docs/dev/windows.md)) | Verified under Wine only; unsigned | | Windows | `DarkRoom-<version>-x86_64-setup.exe`, cross-built by CI ([windows.md](docs/dev/windows.md)) | Verified under Wine only; unsigned |
| Flatpak | [`packaging/flatpak/`](packaging/flatpak/) | Manifest in tree; folders are chosen through the portal, but no Flatpak has been built to prove it | | Flatpak | [`packaging/flatpak/`](packaging/flatpak/) | Manifest in tree; folders are chosen through the portal, but no Flatpak has been built to prove it |
Or build it. Git LFS is required for the model weights, and the toolchain ## Building from source
pins itself to 1.92.0:
**Before anything.** Git LFS holds the model weights and the manual's
pictures; a clone without it has ~130-byte pointers in their place, and every
packager below refuses to ship one. The Rust toolchain pins itself to 1.92.0
through `rust-toolchain.toml`, so rustup is all you install. Slint needs a few
system headers, and the app needs a Vulkan driver at runtime:
```bash ```bash
git clone https://gitea.tourolle.paris/dtourolle/DarkRoom.git && cd DarkRoom
git lfs install && git lfs pull git lfs install && git lfs pull
# Debian / Ubuntu
sudo apt-get install pkg-config libfontconfig1-dev libxkbcommon-dev libvulkan1
# Arch
sudo pacman -S --needed pkgconf fontconfig libxkbcommon vulkan-icd-loader
```
**To try it** from the checkout, without installing anything:
```bash
cargo run --release -p darkroom-desktop cargo run --release -p darkroom-desktop
``` ```
Android, through the containerised toolchain ([docker/android](docker/android/README.md)): This is for development. The binary under `target/` finds no face, scene or
panorama-fill models, and a release build does not find the manual either:
it looks for all of them in the system data directories an install creates
(`$XDG_DATA_DIRS/darkroom`, by default `/usr/local/share/darkroom` and
`/usr/share/darkroom`), never in the checkout. Those features show as
unavailable until it is installed.
### Linux: build and install
**On Arch**, build a package from the checkout and install it with pacman,
so it can be upgraded and removed like any other:
```bash ```bash
./docker/android/build.sh cargo ndk -t arm64-v8a build --release cd packaging && makepkg -si
``` ```
[CONTRIBUTING.md](CONTRIBUTING.md) has the system packages, the four **Elsewhere**, build the release binary and install it under `/usr/local`
by hand. These are the same files, in the same places, as the Arch package
([`packaging/PKGBUILD`](packaging/PKGBUILD)'s `package()` is the reference):
```bash
cargo build --release --locked -p darkroom-desktop
# -> target/release/darkroom-desktop
P=/usr/local
sudo install -Dm755 target/release/darkroom-desktop $P/bin/darkroom-desktop
# The models: faces and eye state, scene categories, panorama border fill
sudo install -d $P/share/darkroom/models
sudo install -m644 models/face/*.onnx models/scene/* models/inpaint/*.onnx \
$P/share/darkroom/models/
# The offline manual the Help menu opens
sudo install -Dm644 docs/manual/index.html $P/share/darkroom/manual/index.html
sudo install -Dm644 -t $P/share/darkroom/manual/media docs/manual/media/*
# Launcher entry, icon and software-centre description
sudo install -Dm644 packaging/paris.tourolle.darkroom.desktop \
$P/share/applications/paris.tourolle.darkroom.desktop
sudo install -Dm644 ui/dr-ui/ui/app-icon.png \
$P/share/icons/hicolor/256x256/apps/paris.tourolle.darkroom.png
sudo install -Dm644 packaging/paris.tourolle.darkroom.metainfo.xml \
$P/share/metainfo/paris.tourolle.darkroom.metainfo.xml
```
Then run `darkroom-desktop`, or open it from the application menu. To
uninstall, remove those files and `/usr/local/share/darkroom`. Your catalog,
settings and thumbnails live in `darkroom/` under your own XDG data, config
and cache directories (`~/.local/share`, `~/.config`, `~/.cache`) and are
not touched by either.
Optional at runtime: `gnome-keyring` or `kwallet` to remember Nextcloud
credentials, and an ONNX Runtime in `/usr/lib` (CPU, or ROCm on an AMD GPU) to
run the models on every core rather than on the built-in engine.
### Windows: build the installer
The `.exe` is cross-built from Linux in a container (podman or docker), with
no Windows machine involved. Two steps — the executable, then the NSIS
installer that carries it with its models and manual:
```bash
./docker/windows/build.sh cargo build --release --target x86_64-pc-windows-gnu -p darkroom-desktop
./docker/windows/build.sh docker/windows/package.sh
```
Both land in the container's cache on the host, `~/.cache/darkroom-windows/target/`:
the bare executable under `x86_64-pc-windows-gnu/release/darkroom-desktop.exe`,
the installer under `installer/DarkRoom-<version>-x86_64-setup.exe`.
Copy that to the Windows machine and run it — it installs per user, needs no
administrator rights, and adds an uninstaller. Run on its own, the bare
`.exe` looks for `models\` and `manual\` beside itself, so use the installer.
[docker/windows](docker/windows/README.md) has the details.
### Android: build the APK
Also containerised ([docker/android](docker/android/README.md)). This
builds, packages and debug-signs the APK, and with `--install` puts it on a
device connected over adb:
```bash
./docker/android/package.sh --install
```
A debug-signed APK cannot replace one installed from a release; uninstall
that first.
[CONTRIBUTING.md](CONTRIBUTING.md) has the four
commands CI runs against what you send, and the shortest useful commands CI runs against what you send, and the shortest useful
contribution — a develop operation is one YAML file, and it arrives with its contribution — a develop operation is one YAML file, and it arrives with its
controls, its place in the chain and its tests. controls, its place in the chain and its tests.
## Where it stands ## Where it stands
**0.19.1**, thirty tagged releases in. 193 numbered requirements in **0.19.3**, thirty-two tagged releases in. 193 numbered requirements in
scope, 85% of them claimed by code and [traced to it](docs/dev/traceability.md); scope, 85% of them claimed by code and [traced to it](docs/dev/traceability.md);
the rest are written down rather than merely absent. the rest are written down rather than merely absent.
@@ -4,9 +4,10 @@
Deliberately minimal: this packages the viewer for on-device testing (spike Deliberately minimal: this packages the viewer for on-device testing (spike
S2 needs Adreno and Mali hardware, which no emulator represents). Nothing S2 needs Adreno and Mali hardware, which no emulator represents). Nothing
here is a distribution manifest yet. Only network access is declared: file here is a distribution manifest yet. The library grid needs no storage
access needs no manifest permission because the library grid reads through permission, because it reads through SAF, which grants per-tree at runtime
SAF, which grants per-tree at runtime (ARCH §6.9). (ARCH §6.9); the one storage permission declared is for importing from a
camera card, which is read by path.
Minimal is not the same as empty, and the entries below that are not the Minimal is not the same as empty, and the entries below that are not the
activity are the difference. A manifest is the only place a component can be activity are the difference. A manifest is the only place a component can be
@@ -21,13 +22,29 @@
WebDAV listing, thumbnail and image fetches. Without it Android refuses WebDAV listing, thumbnail and image fetches. Without it Android refuses
socket creation outright, and the failure is invisible — no panic to socket creation outright, and the failure is invisible — no panic to
catch, no log line, just a worker thread that stops. Storage is the catch, no log line, just a worker thread that stops. Storage is the
separate case that genuinely needs no permission here, because SAF separate case: the library and album folders need no permission
grants per-tree at runtime (ARCH §6.9). --> here, because SAF grants per-tree at runtime (ARCH §6.9). -->
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<!-- Read before deciding whether a sync may run: FR-NC-6 gates background <!-- Read before deciding whether a sync may run: FR-NC-6 gates background
work on unmetered-and-charging, which means knowing the network type. --> work on unmetered-and-charging, which means knowing the network type. -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- FR-CAT-10: importing from a camera card. The importer reads the card
as files, and "all files access" is what makes an SD card or a USB
card reader readable by path on API 30 and up (see Cards.java). It is
granted on a system settings page, not a dialog; the import page
sends the user there when it is missing. READ_EXTERNAL_STORAGE is the
same thing for API 28 and 29, and means nothing above them; on 29 it
reads by path only with requestLegacyExternalStorage, which is why
<application> carries that flag.
Google Play limits MANAGE_EXTERNAL_STORAGE to a short list of app
kinds. DarkRoom is not distributed through Play. -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="29" />
<!-- Vulkan 1.1 is what wgpu needs; the API 28 floor is where support is <!-- Vulkan 1.1 is what wgpu needs; the API 28 floor is where support is
dependable (NFR-COMPAT-1). Marked required so an unsupported device dependable (NFR-COMPAT-1). Marked required so an unsupported device
fails at install rather than at first frame. --> fails at install rather than at first frame. -->
@@ -53,6 +70,7 @@
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:hasCode="true" android:hasCode="true"
android:allowBackup="false" android:allowBackup="false"
android:requestLegacyExternalStorage="true"
android:supportsRtl="true"> android:supportsRtl="true">
<!-- NativeActivity rather than a Kotlin Activity: android-activity's <!-- NativeActivity rather than a Kotlin Activity: android-activity's
@@ -0,0 +1,150 @@
package paris.tourolle.darkroom;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.provider.Settings;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Finding a camera card, and the permission that makes it readable (FR-CAT-10).
*
* <p>An import reads the card as files: the survey walks it, the probe reads
* each header and the copy streams each original, all through the same
* {@code std::fs} code the desktop uses. Android hands out such paths —
* {@code /storage/9C33-6BBD/DCIM} — to an app holding "all files access"
* ({@code MANAGE_EXTERNAL_STORAGE}, API 30), which covers the root of an SD
* card and of a USB card reader. Below API 30 the same paths are readable
* with {@code READ_EXTERNAL_STORAGE}.
*
* <p>Not the folder picker {@link FolderPicker} uses for albums. A tree
* granted through SAF is {@code content://} URIs, not paths, and since API 30
* the picker refuses the root of a card outright; reading a card through it
* would mean a second storage implementation under the importer, where this
* needs none.
*
* <p>Google Play restricts this permission to file managers and the like.
* DarkRoom is not distributed through Play, so the restriction does not
* apply; it would need revisiting if that changed.
*/
public final class Cards {
private static final String TAG = "DarkRoom";
private Cards() {
}
/** Whether this app may read a card's files by path. */
public static boolean hasAccess(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
return Environment.isExternalStorageManager();
}
return context.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED;
}
/**
* Open the system page where the user grants it.
*
* <p>A settings page rather than a permission dialog because there is no
* dialog for this one on API 30 and up: the user flips "Allow access to
* manage all files" for this app. Below 30 the context is the application
* context, which cannot raise a runtime permission request (that needs an
* Activity's result), so the app's own settings page is the route there
* too. Either way the app learns of the grant by asking
* {@link #hasAccess} again.
*/
public static void requestAccess(Context context) {
Uri self = Uri.parse("package:" + context.getPackageName());
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, self);
} else {
intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, self);
}
// The context is not an Activity; see FolderPicker.start.
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (RuntimeException e) {
// Some builds ship without the per-app page; the list of every
// app holding the permission is the fallback that always exists.
Log.w(TAG, "no per-app all-files page; opening the list", e);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
Intent list = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
list.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(list);
}
}
}
/**
* Every mounted volume other than the device's own storage.
*
* <p>One string per volume, {@code path \t description \t removable},
* where removable is {@code 1} or {@code 0}: the reason {@link Intents}
* gives for keeping the JNI surface to strings. The primary volume is left
* out — it is the device's internal storage, never a card — and so is
* anything not mounted, which is a card being ejected or one the system
* could not read.
*/
public static String[] volumes(Context context) {
List<String> out = new ArrayList<String>();
StorageManager manager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
if (manager == null) {
return new String[0];
}
for (StorageVolume volume : manager.getStorageVolumes()) {
if (volume.isPrimary()) {
continue;
}
String state = volume.getState();
if (!Environment.MEDIA_MOUNTED.equals(state)
&& !Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
continue;
}
String path = path(volume);
if (path == null) {
Log.w(TAG, "a mounted volume with no path: " + volume);
continue;
}
String description = volume.getDescription(context);
if (description == null) {
description = new File(path).getName();
}
out.add(path + "\t" + description.replace('\t', ' ') + "\t"
+ (volume.isRemovable() ? "1" : "0"));
}
return out.toArray(new String[0]);
}
/**
* Where the volume is mounted.
*
* <p>{@code getDirectory} is API 30. Below it the same answer is the
* hidden {@code getPath}, which every release from 24 to 29 has, reached by
* reflection because android.jar does not declare it.
*/
private static String path(StorageVolume volume) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
File dir = volume.getDirectory();
return dir == null ? null : dir.getPath();
}
try {
Object path = StorageVolume.class.getMethod("getPath").invoke(volume);
return path == null ? null : path.toString();
} catch (ReflectiveOperationException e) {
Log.w(TAG, "StorageVolume.getPath", e);
return null;
}
}
}
+4 -1
View File
@@ -27,7 +27,7 @@
use std::path::PathBuf; use std::path::PathBuf;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use dr_catalog::{keywords, rating, schema, Catalog}; use dr_catalog::{keywords, name_dates, rating, schema, Catalog};
fn main() { fn main() {
let mut args: Vec<String> = std::env::args().skip(1).collect(); let mut args: Vec<String> = std::env::args().skip(1).collect();
@@ -108,6 +108,9 @@ fn main() {
time(" keywords::adopt_orphan_terms", 20, || { time(" keywords::adopt_orphan_terms", 20, || {
keywords::adopt_orphan_terms(conn).unwrap(); keywords::adopt_orphan_terms(conn).unwrap();
}); });
time(" name_dates::fill", 20, || {
name_dates::fill(conn, None).unwrap();
});
interactive(conn); interactive(conn);
+1
View File
@@ -50,6 +50,7 @@ pub mod faces;
pub mod jobs; pub mod jobs;
pub mod keywords; pub mod keywords;
pub mod merge; pub mod merge;
pub mod name_dates;
pub mod query; pub mod query;
pub mod rating; pub mod rating;
pub mod recovery; pub mod recovery;
+387
View File
@@ -0,0 +1,387 @@
//! TRACES: FR-CAT-5
//! A capture time read from the file's name, for an image whose header has
//! none.
//!
//! # Why
//!
//! A photograph with no EXIF date sorts after everything else, so it is lost
//! at the end of the grid and absent from the timeline. The files that end up
//! there are rarely without a date — they are without *EXIF*: WhatsApp strips
//! every tag and names the file `WhatsApp Image 2023-06-15 at 07.00.42.jpeg`,
//! a Windows Phone wrote `WP_20140922_14_16_27_Pro.jpg`, a phone camera
//! `IMG_20190812_153012.jpg`, and darktable's import renames to
//! `20230629_0001.jpeg`. On the reference library 250 of 274 undated images
//! carried their date in the name or in the folder above it.
//!
//! # What is accepted
//!
//! A date is `YYYYMMDD` as a whole run of digits, or `YYYY`, `MM` and `DD`
//! joined by `-`, `_` or `.`. A time may follow it — `HHMMSS` as one run (or
//! nine digits, milliseconds appended), or three two-digit runs joined by
//! `-`, `_`, `.` or `:` — after `_`, `-`, `.`, `T`, a space or ` at `.
//! Anything else after the date leaves it at midnight: `_0059` in
//! `20230628_0059` is a sequence number, not 00:59, and reading it as a time
//! would invent one.
//!
//! The name is tried first and then each folder above it, innermost first —
//! `2016/2016-11-11/IMG_7910.jpg` is dated by its folder. A bare year folder
//! is not a date: putting a photograph at 1 January is a wrong answer, and an
//! undated one at least says it does not know.
//!
//! The reading is wall-clock time with no zone, stored as EXIF's is
//! (`dr_decode::parse_exif_datetime`), and EXIF always wins: this only fills
//! rows whose `captured_at` is still empty.
use rusqlite::Connection;
use crate::CatalogError;
/// The capture time a path's name states, as wall-clock Unix seconds.
pub fn date_from_path(source_ref: &str) -> Option<i64> {
let mut parts = source_ref.rsplit(['/', '\\']);
let name = parts.next()?;
let stem = name.rsplit_once('.').map_or(name, |(stem, _)| stem);
date_in(stem).or_else(|| parts.find_map(date_in))
}
/// Date every examined, undated image whose name states one.
///
/// `only` limits the pass to the images just examined — what the sweep hands
/// in — and `None` visits every undated image, which is the backfill's case.
/// Both read the undated side alone (`images_captured` answers
/// `captured_at IS NULL` with a seek), never the library.
///
/// Returns how many images were dated.
pub fn fill(conn: &Connection, only: Option<&[i64]>) -> Result<usize, CatalogError> {
let rows: Vec<(i64, String)> = match only {
None => {
let mut stmt = conn.prepare(
"SELECT id, source_ref FROM images
WHERE captured_at IS NULL AND metadata_state >= 2",
)?;
let rows = stmt
.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect::<Result<_, _>>()?;
rows
}
Some(ids) => {
let mut stmt = conn.prepare_cached(
"SELECT source_ref FROM images
WHERE id = ?1 AND captured_at IS NULL AND metadata_state >= 2",
)?;
let mut rows = Vec::new();
for &id in ids {
let mut q = stmt.query([id])?;
if let Some(r) = q.next()? {
rows.push((id, r.get(0)?));
}
}
rows
}
};
let dated: Vec<(i64, i64)> = rows
.iter()
.filter_map(|(id, path)| date_from_path(path).map(|at| (*id, at)))
.collect();
if dated.is_empty() {
return Ok(0);
}
// A savepoint rather than a transaction, so a caller already inside one
// can still call this: the backfill's 250 rows are one commit, not 250.
conn.execute_batch("SAVEPOINT name_dates")?;
let written = (|| {
let mut stmt = conn.prepare_cached(
"UPDATE images SET captured_at = ?2 WHERE id = ?1 AND captured_at IS NULL",
)?;
let mut n = 0;
for (id, at) in &dated {
n += stmt.execute(rusqlite::params![id, at])?;
}
Ok::<_, CatalogError>(n)
})();
match written {
Ok(n) => {
conn.execute_batch("RELEASE name_dates")?;
Ok(n)
}
Err(e) => {
let _ = conn.execute_batch("ROLLBACK TO name_dates; RELEASE name_dates");
Err(e)
}
}
}
/// The first date, with its time if one follows, in one name component.
fn date_in(s: &str) -> Option<i64> {
let b = s.as_bytes();
let mut i = 0;
while i < b.len() {
// Only at the start of a run of digits: a date inside a longer number
// is a coincidence, not a date.
if b[i].is_ascii_digit() && (i == 0 || !b[i - 1].is_ascii_digit()) {
if let Some(at) = date_at(b, i) {
return Some(at);
}
}
i += 1;
}
None
}
/// A date starting at `i`, and the time after it if there is one.
fn date_at(b: &[u8], i: usize) -> Option<i64> {
let run = digits(b, i);
let ((y, mo, d), after) = match run.len() {
// YYYYMMDD, or YYYYMMDDHHMMSS written as one number.
8 | 14 => ((num(&run[..4]), num(&run[4..6]), num(&run[6..8])), i + 8),
4 => {
let sep = |at: usize| matches!(b.get(at), Some(b'-' | b'_' | b'.'));
let mo_at = i + 4 + 1;
let d_at = mo_at + 2 + 1;
if !(sep(i + 4) && digits(b, mo_at).len() == 2 && sep(mo_at + 2))
|| digits(b, d_at).len() != 2
{
return None;
}
(
(num(run), num(&b[mo_at..mo_at + 2]), num(&b[d_at..d_at + 2])),
d_at + 2,
)
}
_ => return None,
};
let day = civil_days(y, mo, d)?;
let time = if run.len() == 14 {
hms(num(&run[8..10]), num(&run[10..12]), num(&run[12..14]))
} else {
time_at(b, after)
};
Some(day * 86_400 + time.unwrap_or(0))
}
/// The time following a date that ends at `i`, as seconds into the day.
fn time_at(b: &[u8], i: usize) -> Option<i64> {
let rest = &b[i..];
let start = if rest.starts_with(b" at ") {
i + 4
} else if matches!(rest.first(), Some(b'_' | b'-' | b'.' | b'T' | b' ')) {
i + 1
} else {
return None;
};
let run = digits(b, start);
match run.len() {
// HHMMSS, or with milliseconds appended (Pixel's PXL_…_123456789).
6 | 9 => hms(num(&run[..2]), num(&run[2..4]), num(&run[4..6])),
2 => {
let sep = |at: usize| matches!(b.get(at), Some(b'-' | b'_' | b'.' | b':'));
let (m_at, s_at) = (start + 3, start + 6);
if !(sep(start + 2) && digits(b, m_at).len() == 2 && sep(m_at + 2))
|| digits(b, s_at).len() != 2
{
return None;
}
hms(num(run), num(&b[m_at..m_at + 2]), num(&b[s_at..s_at + 2]))
}
_ => None,
}
}
/// The run of ASCII digits starting at `i`.
fn digits(b: &[u8], i: usize) -> &[u8] {
let rest = b.get(i..).unwrap_or(&[]);
let n = rest.iter().take_while(|c| c.is_ascii_digit()).count();
&rest[..n]
}
fn num(d: &[u8]) -> i64 {
d.iter().fold(0, |n, c| n * 10 + i64::from(c - b'0'))
}
fn hms(h: i64, m: i64, s: i64) -> Option<i64> {
((0..24).contains(&h) && (0..60).contains(&m) && (0..61).contains(&s))
.then_some(h * 3_600 + m * 60 + s)
}
/// Days since 1970-01-01 for a valid civil date, `None` for anything else.
///
/// The year range is EXIF's (`parse_exif_datetime`): wide enough for scanned
/// film, narrow enough that a counter such as `12345678` is not a date.
fn civil_days(y: i64, mo: i64, d: i64) -> Option<i64> {
let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
let month_len = match mo {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => return None,
};
if !(1900..=2200).contains(&y) || !(1..=month_len).contains(&d) {
return None;
}
let y_adj = if mo <= 2 { y - 1 } else { y };
let era = y_adj.div_euclid(400);
let yoe = y_adj - era * 400;
let mp = (mo + 9) % 12;
let doy = (153 * mp + 2) / 5 + d - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
Some(era * 146_097 + doe - 719_468)
}
#[cfg(test)]
mod tests {
use super::*;
/// Wall-clock seconds for a date and time, the expected side of each case.
fn at(y: i64, mo: i64, d: i64, h: i64, mi: i64, s: i64) -> Option<i64> {
Some(civil_days(y, mo, d).unwrap() * 86_400 + h * 3_600 + mi * 60 + s)
}
#[test]
fn the_names_in_the_reference_library_are_read() {
// Every shape here is a file that sat undated at the end of the grid.
for (path, want) in [
(
"PhotosRaw/alps trip/alps whatsapp/WhatsApp Image 2023-06-15 at 07.00.42.jpeg",
at(2023, 6, 15, 7, 0, 42),
),
(
"PhotosRaw/alps trip/alps whatsapp/WhatsApp Image 2023-06-17 at 12.45.52 (1).jpeg",
at(2023, 6, 17, 12, 45, 52),
),
(
"PhotosRaw/WP_20140922_14_16_27_Pro.jpg",
at(2014, 9, 22, 14, 16, 27),
),
// A sequence number after the date is not a time.
(
"PhotosRaw/Darktable/20230629_no_name/20230629_0001.jpeg",
at(2023, 6, 29, 0, 0, 0),
),
("PhotosRaw/20230628_0059.jpg", at(2023, 6, 28, 0, 0, 0)),
(
"PhotosRaw/backdrops/IMG_20130625_0021.jpg",
at(2013, 6, 25, 0, 0, 0),
),
(
"PhotosRaw/alps trip/20230628_0641 - 20230628_0661.jpg",
at(2023, 6, 28, 0, 0, 0),
),
] {
assert_eq!(date_from_path(path), want, "{path}");
}
}
#[test]
fn common_camera_and_app_names_are_read() {
for (path, want) in [
("IMG_20190812_153012.jpg", at(2019, 8, 12, 15, 30, 12)),
("PXL_20210101_123456789.jpg", at(2021, 1, 1, 12, 34, 56)),
(
"Screenshot_2021-03-04-12-30-45.png",
at(2021, 3, 4, 12, 30, 45),
),
(
"Screenshot from 2021-03-04 12-30-45.png",
at(2021, 3, 4, 12, 30, 45),
),
("IMG-20210304-WA0001.jpg", at(2021, 3, 4, 0, 0, 0)),
("20210304143012.jpg", at(2021, 3, 4, 14, 30, 12)),
("2019.12.25 party.jpg", at(2019, 12, 25, 0, 0, 0)),
("signal-2022-01-02-101112.jpg", at(2022, 1, 2, 10, 11, 12)),
("2022-01-02T10:11:12.jpg", at(2022, 1, 2, 10, 11, 12)),
] {
assert_eq!(date_from_path(path), want, "{path}");
}
}
#[test]
fn a_folder_dates_a_name_that_does_not() {
assert_eq!(
date_from_path("PhotosRaw/2016/2016-11-11/IMG_7910.jpg"),
at(2016, 11, 11, 0, 0, 0)
);
// The innermost folder that states a date wins.
assert_eq!(
date_from_path("2016-01-01 trip/2016-01-03/_MG_1.jpg"),
at(2016, 1, 3, 0, 0, 0)
);
// The name beats its folder.
assert_eq!(
date_from_path("2016-11-11/IMG_20161112_080000.jpg"),
at(2016, 11, 12, 8, 0, 0)
);
}
#[test]
fn numbers_that_are_not_dates_are_left_alone() {
for path in [
"PhotosRaw/_MG_9002.jpg",
"PhotosRaw/scanning/fau_2.jpg",
// A year folder is not a day.
"PhotosRaw/2016/_MG_1.jpg",
"IMG_1999.jpg",
"DSC_12345678.jpg", // month 56
"20230230_0001.jpg", // 30 February
"120230615.jpg", // the date is inside a longer number
"1612345678901.jpg", // a millisecond epoch, not a civil date
"2023-6-15.jpg", // a one-digit month is too loose to trust
] {
assert_eq!(date_from_path(path), None, "{path}");
}
}
#[test]
fn a_time_that_cannot_be_is_dropped_and_the_date_kept() {
assert_eq!(
date_from_path("20230615_256199.jpg"),
at(2023, 6, 15, 0, 0, 0)
);
}
#[test]
fn fill_dates_only_examined_undated_rows_and_never_overrides_exif() {
let c = Connection::open_in_memory().unwrap();
crate::schema::migrate(&c).unwrap();
c.execute(
"INSERT INTO roots(id, kind, label) VALUES (1, 'remote', 'lib')",
[],
)
.unwrap();
// (id, name, captured_at, metadata_state)
for (id, name, captured, state) in [
(1i64, "IMG_20190812_153012.jpg", None, 2i64),
// EXIF already answered; the name disagrees and loses.
(2, "IMG_20190812_153012b.jpg", Some(42i64), 2),
// Not yet examined: EXIF may still come, so the name waits.
(3, "IMG_20190813_000000.jpg", None, 1),
(4, "_MG_9002.jpg", None, 2),
] {
c.execute(
"INSERT INTO images(id, root_id, source_ref, captured_at, metadata_state, added_at)
VALUES (?1, 1, ?2, ?3, ?4, 0)",
rusqlite::params![id, name, captured, state],
)
.unwrap();
}
let captured = |id: i64| -> Option<i64> {
c.query_row("SELECT captured_at FROM images WHERE id = ?1", [id], |r| {
r.get(0)
})
.unwrap()
};
assert_eq!(fill(&c, Some(&[2, 3, 4])).unwrap(), 0);
assert_eq!(fill(&c, None).unwrap(), 1);
assert_eq!(captured(1), at(2019, 8, 12, 15, 30, 12));
assert_eq!(captured(2), Some(42));
assert_eq!(captured(3), None);
assert_eq!(captured(4), None);
// Nothing left to do is a no-op, not a rewrite.
assert_eq!(fill(&c, None).unwrap(), 0);
}
}
+9
View File
@@ -356,6 +356,15 @@ pub fn backfill(conn: &Connection) -> Result<Vec<(&'static str, usize)>, Catalog
out.push(("keyword_terms", n)); out.push(("keyword_terms", n));
} }
// TRACES: FR-CAT-5
// A date from the file's name for every examined image EXIF left undated.
// The sweep does this as it examines each image; this is for the images
// examined by a build that did not, and reads the undated side alone.
let n = crate::name_dates::fill(conn, None)?;
if n > 0 {
out.push(("dates_from_names", n));
}
Ok(out) Ok(out)
} }
+109 -8
View File
@@ -30,18 +30,27 @@
//! are the caller's to provide and cache — `source` is asked for frame `k` //! are the caller's to provide and cache — `source` is asked for frame `k`
//! as it is needed, and a caller short of memory may demosaic on demand. //! as it is needed, and a caller short of memory may demosaic on demand.
//! //!
//! # The blend
//!
//! With a seam map (`dr_pano::seam`), a frame's weight at a pixel is its
//! share of the map about that pixel — whole on its own side of a seam,
//! nothing on the other, and a ramp across a window `seam_blend` pixels
//! wide that follows the seam. Without one, or where the map has nothing
//! to say, the weight is the distance to the frame's edge over `feather`,
//! which hides exposure steps and does not hide parallax: the average draws
//! anything the frames disagree on twice.
//!
//! # What is not here yet //! # What is not here yet
//! //!
//! A feathered blend, not seams and a Laplacian pyramid: the weight is the //! A Laplacian pyramid, which would let the seam's blend be narrow for
//! distance to the frame's edge, which hides exposure steps and small //! detail and wide for exposure at once. Gain is a scalar per frame the
//! misalignments and does not hide parallax. Gain is a scalar per frame //! caller supplies.
//! the caller supplies. Both are panorama.md §10's step 5, after the path
//! writes a file end to end.
use std::sync::Arc; use std::sync::Arc;
use dr_pano::bundle::Cameras; use dr_pano::bundle::Cameras;
use dr_pano::projection::{Bounds, Projection}; use dr_pano::projection::{Bounds, Projection};
use dr_pano::seam::SeamMap;
use wgpu::util::DeviceExt; use wgpu::util::DeviceExt;
use crate::readback::await_mapping; use crate::readback::await_mapping;
@@ -58,7 +67,7 @@ pub struct MergeFrame {
} }
/// The output the merge produces. /// The output the merge produces.
#[derive(Debug, Clone, Copy, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct MergeOutput { pub struct MergeOutput {
pub projection: Projection, pub projection: Projection,
/// The projection's scale in output pixels: the cylinder's radius, the /// The projection's scale in output pixels: the cylinder's radius, the
@@ -69,6 +78,11 @@ pub struct MergeOutput {
pub bounds: Bounds, pub bounds: Bounds,
/// Pixels over which a frame's weight ramps up from its edge. /// Pixels over which a frame's weight ramps up from its edge.
pub feather: f32, pub feather: f32,
/// Which frame each part of the output is taken from, laid out at the
/// proxies' scale; `None` for the feathered average everywhere.
pub seams: Option<Arc<SeamMap>>,
/// The width, in output pixels, of the blend across a seam.
pub seam_blend: f32,
/// Chunk size: the unit of GPU work and of memory. /// Chunk size: the unit of GPU work and of memory.
pub chunk: (u32, u32), pub chunk: (u32, u32),
/// Multiplies a normalised sample (1.0 = white) to the sensor's scale. /// Multiplies a normalised sample (1.0 = white) to the sensor's scale.
@@ -115,6 +129,12 @@ struct WarpParams {
feather: f32, feather: f32,
clip_onset: f32, clip_onset: f32,
balance: [f32; 4], balance: [f32; 4],
seam_origin: [f32; 2],
seam_size: [u32; 2],
seam_px: f32,
seam_radius: f32,
frame_index: u32,
seam_on: u32,
} }
#[repr(C)] #[repr(C)]
@@ -182,6 +202,16 @@ impl MergePass {
count: None, count: None,
}, },
storage(2, false), storage(2, false),
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Uint,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
], ],
}); });
let resolve_layout = let resolve_layout =
@@ -279,6 +309,32 @@ impl MergePass {
let mut band_cov = vec![false; (out_w * ch) as usize]; let mut band_cov = vec![false; (out_w * ch) as usize];
let mut chunk_px: Vec<u32> = Vec::new(); let mut chunk_px: Vec<u32> = Vec::new();
// The seam map, once for the whole output, and where it sits in
// this output's coordinates. A one-texel stand-in when there is
// none, because the binding is not optional.
let (seam_tex, seam_origin, seam_px, seam_radius, seam_size) = match &output.seams {
Some(m) => {
let ((ou, ov), px) = m.at_scale(output.scale);
let radius = m.blend_radius(output.scale, f64::from(output.seam_blend));
(
self.label_texture(m.width as u32, m.height as u32, &m.labels),
[ou as f32, ov as f32],
px as f32,
radius as f32,
[m.width as u32, m.height as u32],
)
}
None => (
self.label_texture(1, 1, &[dr_pano::seam::NONE]),
[0.0; 2],
1.0,
1.0,
[1, 1],
),
};
let seam_view = seam_tex.create_view(&Default::default());
let seam_on = u32::from(output.seams.is_some());
let mut y = 0u32; let mut y = 0u32;
while y < out_h { while y < out_h {
let rows = ch.min(out_h - y); let rows = ch.min(out_h - y);
@@ -346,8 +402,14 @@ impl MergePass {
output.balance[2].max(1e-3), output.balance[2].max(1e-3),
0.0, 0.0,
], ],
seam_origin,
seam_size,
seam_px,
seam_radius,
frame_index: k as u32,
seam_on,
}; };
self.accumulate(&params, tile); self.accumulate(&params, tile, &seam_view);
} }
self.resolve_chunk((cols, rows), output.sample_scale, &mut chunk_px)?; self.resolve_chunk((cols, rows), output.sample_scale, &mut chunk_px)?;
@@ -385,7 +447,42 @@ impl MergePass {
self.ctx.queue.submit(Some(enc.finish())); self.ctx.queue.submit(Some(enc.finish()));
} }
fn accumulate(&mut self, params: &WarpParams, tile: &wgpu::Texture) { /// The seam map's labels as an `r8uint` texture.
fn label_texture(&self, width: u32, height: u32, labels: &[u8]) -> wgpu::Texture {
let size = wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
};
let tex = self.ctx.device.create_texture(&wgpu::TextureDescriptor {
label: Some("merge-seams"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R8Uint,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
self.ctx.queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &tex,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
labels,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(width),
rows_per_image: Some(height),
},
size,
);
tex
}
fn accumulate(&mut self, params: &WarpParams, tile: &wgpu::Texture, seams: &wgpu::TextureView) {
let chunk = (params.chunk_size[0], params.chunk_size[1]); let chunk = (params.chunk_size[0], params.chunk_size[1]);
let uniforms = self let uniforms = self
.ctx .ctx
@@ -417,6 +514,10 @@ impl MergePass {
binding: 2, binding: 2,
resource: acc.as_entire_binding(), resource: acc.as_entire_binding(),
}, },
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(seams),
},
], ],
}); });
let mut enc = self.ctx.device.create_command_encoder(&Default::default()); let mut enc = self.ctx.device.create_command_encoder(&Default::default());
+85 -3
View File
@@ -5,8 +5,9 @@
// pixel it asks which direction that pixel looks along, turns the // pixel it asks which direction that pixel looks along, turns the
// direction into the frame's camera, projects it to a source pixel, and // direction into the frame's camera, projects it to a source pixel, and
// if that pixel is inside the tile that was rendered for this chunk, // if that pixel is inside the tile that was rendered for this chunk,
// samples it and adds it — weighted by its distance from the frame's edge // samples it and adds it — weighted by the frame's share of the seam map
// — into the accumulator. `resolve` runs once per chunk after every frame // there, or by its distance from the frame's edge where there is no map —
// into the accumulator. `resolve` runs once per chunk after every frame
// has been added: divides the sums by the weights and packs the result as // has been added: divides the sums by the weights and packs the result as
// sixteen-bit samples at the sensor's scale (FR-MRG-3). // sixteen-bit samples at the sensor's scale (FR-MRG-3).
// //
@@ -50,12 +51,83 @@ struct Params {
// white balance the composite will be developed with. // white balance the composite will be developed with.
clip_onset: f32, clip_onset: f32,
balance: vec4<f32>, balance: vec4<f32>,
// The seam map (`dr_pano::seam`): where its texel (0, 0)'s corner sits
// in this output's centred coordinates, its size, output pixels per
// texel, the blend's radius in texels, which frame this dispatch is,
// and whether there is a map at all.
seam_origin: vec2<f32>,
seam_size: vec2<u32>,
seam_px: f32,
seam_radius: f32,
frame_index: u32,
seam_on: u32,
}; };
@group(0) @binding(0) var<uniform> p: Params; @group(0) @binding(0) var<uniform> p: Params;
@group(0) @binding(1) var tile: texture_2d<f32>; @group(0) @binding(1) var tile: texture_2d<f32>;
// rgb·w summed, then w: four floats per chunk pixel. // rgb·w summed, then w: four floats per chunk pixel.
@group(0) @binding(2) var<storage, read_write> acc: array<vec4<f32>>; @group(0) @binding(2) var<storage, read_write> acc: array<vec4<f32>>;
// One frame index per texel, 255 for none.
@group(0) @binding(3) var seams: texture_2d<u32>;
const NO_FRAME: u32 = 255u;
fn label(i: i32, j: i32) -> u32 {
if (i < 0 || j < 0 || i >= i32(p.seam_size.x) || j >= i32(p.seam_size.y)) {
return NO_FRAME;
}
return textureLoad(seams, vec2<i32>(i, j), 0).r;
}
// This frame's share of the seam map about output point (u, v): the
// tent-weighted fraction of the texels within the radius that it owns, and
// the weight of the texels owned by anyone (zero where the map has nothing
// to say). `SeamMap::share` verbatim.
fn seam_share(u: f32, v: f32) -> vec2<f32> {
let x = (u - p.seam_origin.x) / p.seam_px - 0.5;
let y = (v - p.seam_origin.y) / p.seam_px - 0.5;
let r = max(p.seam_radius, 1.0);
let x0 = i32(ceil(x - r));
let x1 = i32(floor(x + r));
let y0 = i32(ceil(y - r));
let y1 = i32(floor(y + r));
// Most pixels are nowhere near a seam: if the window's corners, edge
// midpoints and centre agree, so does the window. A seam crossing it
// has to cross its border, between two of those.
let xm = i32(round(x));
let ym = i32(round(y));
let c = label(xm, ym);
if (label(x0, y0) == c && label(x1, y0) == c && label(x0, y1) == c && label(x1, y1) == c
&& label(xm, y0) == c && label(xm, y1) == c && label(x0, ym) == c && label(x1, ym) == c) {
if (c == NO_FRAME) {
return vec2<f32>(0.0, 0.0);
}
return vec2<f32>(select(0.0, 1.0, c == p.frame_index), 1.0);
}
var mine = 0.0;
var owned = 0.0;
for (var j = y0; j <= y1; j = j + 1) {
let wy = 1.0 - abs(y - f32(j)) / r;
if (wy <= 0.0) {
continue;
}
for (var i = x0; i <= x1; i = i + 1) {
let wx = 1.0 - abs(x - f32(i)) / r;
let l = label(i, j);
if (wx <= 0.0 || l == NO_FRAME) {
continue;
}
owned = owned + wx * wy;
if (l == p.frame_index) {
mine = mine + wx * wy;
}
}
}
if (owned <= 0.0) {
return vec2<f32>(0.0, 0.0);
}
return vec2<f32>(mine / owned, 1.0);
}
fn to_direction(u: f32, v: f32) -> vec3<f32> { fn to_direction(u: f32, v: f32) -> vec3<f32> {
let s = p.proj_scale; let s = p.proj_scale;
@@ -98,7 +170,17 @@ fn warp(@builtin(global_invocation_id) gid: vec3<u32>) {
if (edge <= 0.0) { if (edge <= 0.0) {
return; return;
} }
let w = clamp(edge / max(p.feather, 1.0), 0.0, 1.0); var w = clamp(edge / max(p.feather, 1.0), 0.0, 1.0);
// With seams, the share of the map scales it. The small floor keeps
// the feather underneath as the answer wherever no frame that reaches
// this pixel owns it — the map is coarser than the output, so at the
// frames' outer edges it can name a frame that falls just short.
if (p.seam_on != 0u) {
let s = seam_share(u, v);
if (s.y > 0.0) {
w = w * (s.x + 1e-4);
}
}
// Into the tile. // Into the tile.
let tx = sx - p.tile_origin.x; let tx = sx - p.tile_origin.x;
let ty = sy - p.tile_origin.y; let ty = sy - p.tile_origin.y;
+3
View File
@@ -22,6 +22,7 @@
//! - [`align`] — the whole thing, from features to cameras, honest about //! - [`align`] — the whole thing, from features to cameras, honest about
//! what it could not place. //! what it could not place.
//! - [`projection`] — perspective, cylindrical, spherical. //! - [`projection`] — perspective, cylindrical, spherical.
//! - [`seam`] — which frame each output pixel is taken from.
//! - [`linalg`] — the small dense algebra all of it uses. //! - [`linalg`] — the small dense algebra all of it uses.
//! //!
//! # What it depends on //! # What it depends on
@@ -43,6 +44,7 @@ pub mod matching;
#[cfg(feature = "xfeat")] #[cfg(feature = "xfeat")]
pub mod migan; pub mod migan;
pub mod projection; pub mod projection;
pub mod seam;
#[cfg(feature = "xfeat")] #[cfg(feature = "xfeat")]
pub mod xfeat; pub mod xfeat;
@@ -52,6 +54,7 @@ pub use features::{Features, Keypoint};
pub use fill::{fill_border, Inpainter, Observer, Params as FillParams}; pub use fill::{fill_border, Inpainter, Observer, Params as FillParams};
pub use image::Gray; pub use image::Gray;
pub use projection::Projection; pub use projection::Projection;
pub use seam::{SeamMap, SeamOptions};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum PanoError { pub enum PanoError {
+691
View File
@@ -0,0 +1,691 @@
//! TRACES: FR-MRG-10
//! Where each frame gives way to the next.
//!
//! The first merges averaged every overlap: each frame weighted by its
//! distance from its own edge, so that across two hundred pixels one frame
//! faded into the other. That hides an exposure step and does not hide
//! anything that differs between the frames — parallax on a near slope, a
//! walker, a branch in the wind — which the average draws twice, half as
//! bright, a soft double edge at 1:1.
//!
//! A seam answers it the way every stitcher does: in an overlap, each output
//! pixel is taken from *one* frame, and the line where the choice changes is
//! put where the frames agree and the picture is smooth — through sky,
//! along a shadow, round the walker rather than through him — and away from
//! either frame's edge, where vignetting and the lens correction's fringe
//! live. The blend is then narrow and only across that line.
//!
//! # How
//!
//! At proxy resolution, on the output surface, which fits (panorama.md §5:
//! "it is a mask, not an image"):
//!
//! 1. Frames are laid down one at a time, each next to one already placed.
//! The composite so far is a label per texel and the value its owner saw.
//! 2. Where a new frame overlaps the composite, a cost per texel: the
//! difference between the two (after the gains), how much detail either
//! has there, and how near either frame's edge it is — smoothed over a
//! few texels, because "agree" means locally, not at one pixel.
//! 3. The cut is a path across the overlap, perpendicular to the line from
//! the composite's frames to the new one, found by dynamic programming
//! one row at a time: the per-column seam panorama.md §4 chose over a
//! graph cut because it is the GPU-friendly shape. Texels on the new
//! frame's side of the path become its own.
//!
//! What the merge reads is [`SeamMap::share`]: the fraction of a small
//! window about a point that is labelled with a frame, tent-weighted, which
//! is a narrow blend that follows the seam. `merge.wgsl` computes the same
//! thing on the GPU from the same labels.
use crate::bundle::Cameras;
use crate::image::Gray;
use crate::projection::{self, Projection};
/// No frame owns this texel.
pub const NONE: u8 = 255;
/// The most frames a map can label: one less than [`NONE`].
pub const MAX_FRAMES: usize = NONE as usize;
/// Which frame each texel of the output takes its pixels from.
#[derive(Debug, Clone, PartialEq)]
pub struct SeamMap {
pub width: usize,
pub height: usize,
/// The projection scale the map was laid out at: the proxies' focal
/// length. Output coordinates at any other scale are this times the
/// ratio of the scales.
pub scale: f64,
/// Centred output coordinates, at `scale`, of texel (0, 0)'s top-left
/// corner.
pub origin: (f64, f64),
/// Output units per texel, at `scale`.
pub px: f64,
/// Row-major, one per texel: the frame's index, or [`NONE`].
pub labels: Vec<u8>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SeamOptions {
/// The widest the map is laid out, in texels. Wider than the proxies'
/// own resolution buys nothing.
pub max_width: usize,
/// How much detail costs against disagreement: a seam through texture
/// shows even where the frames agree, because the blend across it
/// softens it.
pub detail: f32,
/// How much a frame's edge costs, and how far in from it the cost
/// reaches, in proxy pixels. Frame edges are where vignetting is
/// darkest and the lens correction ran out of sensor.
pub edge: f32,
pub edge_margin: f32,
/// The radius, in texels, a texel's cost looks about it for the worst
/// of its neighbours: at least the radius the merge blends across.
pub smoothing: usize,
}
impl Default for SeamOptions {
fn default() -> Self {
SeamOptions {
max_width: 2048,
detail: 0.5,
edge: 0.5,
edge_margin: 24.0,
smoothing: 4,
}
}
}
/// The most texels a blend reaches either side of a seam. The merge's
/// shader loads the square of twice this per pixel per frame near a seam.
pub const MAX_BLEND_RADIUS: f64 = 4.0;
/// Cost of a texel outside the overlap: high enough that the path keeps to
/// the overlap wherever there is one, finite so that a row with a gap in it
/// still has an answer.
const OUTSIDE: f32 = 1.0e3;
impl SeamMap {
/// The map's origin and texel size in the coordinates of an output
/// laid out at `scale` (the full-resolution focal length, or a fraction
/// of it).
pub fn at_scale(&self, scale: f64) -> ((f64, f64), f64) {
let r = scale / self.scale;
((self.origin.0 * r, self.origin.1 * r), self.px * r)
}
/// The radius, in texels, of a blend `blend_px` output pixels wide in an
/// output laid out at `scale`: what [`Self::share`] and the shader are
/// given, so that the preview and the merge blend alike.
pub fn blend_radius(&self, scale: f64, blend_px: f64) -> f64 {
let (_, px) = self.at_scale(scale);
(blend_px / 2.0 / px).clamp(1.0, MAX_BLEND_RADIUS)
}
/// The share frame `k` has of output point `(u, v)` given at `scale`:
/// the tent-weighted fraction of the texels within `radius` (in texels)
/// that it owns. `None` where no texel in reach is owned at all — the
/// map has nothing to say there, and the caller falls back to its
/// feather.
///
/// This is the function `merge.wgsl`'s `seam_share` repeats; the two
/// must agree.
pub fn share(&self, k: usize, u: f64, v: f64, scale: f64, radius: f64) -> Option<f32> {
let ((ou, ov), px) = self.at_scale(scale);
let x = (u - ou) / px - 0.5;
let y = (v - ov) / px - 0.5;
let r = radius.max(1.0);
let (x0, x1) = ((x - r).ceil() as i64, (x + r).floor() as i64);
let (y0, y1) = ((y - r).ceil() as i64, (y + r).floor() as i64);
let (mut mine, mut all) = (0.0f64, 0.0f64);
for j in y0.max(0)..=y1.min(self.height as i64 - 1) {
let wy = 1.0 - (y - j as f64).abs() / r;
if wy <= 0.0 {
continue;
}
for i in x0.max(0)..=x1.min(self.width as i64 - 1) {
let wx = 1.0 - (x - i as f64).abs() / r;
if wx <= 0.0 {
continue;
}
let l = self.labels[j as usize * self.width + i as usize];
if l == NONE {
continue;
}
all += wx * wy;
if usize::from(l) == k {
mine += wx * wy;
}
}
}
(all > 0.0).then(|| (mine / all) as f32)
}
}
/// One frame warped onto the map: its gain-corrected value and its distance
/// from its own edge (in proxy pixels) per texel, NaN where it does not
/// reach.
struct Warped {
value: Vec<f32>,
edge: Vec<f32>,
}
/// Lay seams across the overlaps of `proxies`, aligned by `cameras` (at the
/// proxies' scale), with `gains` the linear multipliers the merge will
/// apply. `None` if the frames project nowhere or there are more than
/// [`MAX_FRAMES`].
pub fn find(
proxies: &[&Gray],
cameras: &Cameras,
gains: &[f32],
projection: Projection,
opts: &SeamOptions,
) -> Option<SeamMap> {
let n = proxies.len();
if n == 0 || n > MAX_FRAMES || cameras.rotations.len() != n || gains.len() != n {
return None;
}
let (fw, fh) = (proxies[0].width as f64, proxies[0].height as f64);
let scale = cameras.focal;
let bounds = projection::bounds(projection, scale, cameras, (fw, fh))?;
let width = opts.max_width.min(bounds.width().ceil() as usize).max(1);
let px = bounds.width() / width as f64;
let height = ((bounds.height() / px).ceil() as usize).max(1);
let mut map = SeamMap {
width,
height,
scale,
origin: (bounds.min_u, bounds.min_v),
px,
labels: vec![NONE; width * height],
};
// Where each frame's centre lands, in texels: what orders the frames
// and orients each cut.
let centres: Vec<(f64, f64)> = (0..n)
.map(|k| {
let d = cameras.bearing(k, (0.0, 0.0));
projection
.from_direction(scale, d)
.map(|(u, v)| ((u - bounds.min_u) / px, (v - bounds.min_v) / px))
.unwrap_or((width as f64 / 2.0, height as f64 / 2.0))
})
.collect();
// The composite so far: what its owner saw, and how far from the
// owner's edge.
let mut value = vec![f32::NAN; width * height];
let mut edge = vec![f32::NAN; width * height];
for k in order(&centres, (width as f64 / 2.0, height as f64 / 2.0)) {
let w = warp(&map, proxies[k], cameras, k, gains[k], projection);
let overlap: Vec<usize> = (0..width * height)
.filter(|&i| map.labels[i] != NONE && !w.value[i].is_nan())
.collect();
// Texels nobody owns yet are the new frame's without a cut.
let mut take: Vec<bool> = map
.labels
.iter()
.zip(&w.value)
.map(|(&l, v)| l == NONE && !v.is_nan())
.collect();
if !overlap.is_empty() {
cut(
&map, &value, &edge, &w, &overlap, &centres, k, opts, &mut take,
);
}
for i in 0..width * height {
if take[i] {
map.labels[i] = k as u8;
value[i] = w.value[i];
edge[i] = w.edge[i];
}
}
}
Some(map)
}
/// The order frames are laid down in: the one nearest the middle first,
/// then always the unplaced frame nearest any placed one, so that each new
/// frame meets the composite along an overlap rather than across a gap.
fn order(centres: &[(f64, f64)], middle: (f64, f64)) -> Vec<usize> {
let d2 = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).powi(2) + (a.1 - b.1).powi(2);
let n = centres.len();
let mut placed = vec![false; n];
let mut out = Vec::with_capacity(n);
let first = (0..n)
.min_by(|&a, &b| d2(centres[a], middle).total_cmp(&d2(centres[b], middle)))
.expect("at least one frame");
placed[first] = true;
out.push(first);
while out.len() < n {
let next = (0..n)
.filter(|&k| !placed[k])
.min_by(|&a, &b| {
let near = |k: usize| {
out.iter()
.map(|&p| d2(centres[k], centres[p]))
.fold(f64::MAX, f64::min)
};
near(a).total_cmp(&near(b))
})
.expect("an unplaced frame");
placed[next] = true;
out.push(next);
}
out
}
/// Frame `k` sampled at every texel's centre, bilinearly. The proxy is
/// gamma-encoded grey, so the gain (linear) becomes `gain^(1/2.2)` on it.
fn warp(
map: &SeamMap,
g: &Gray,
cameras: &Cameras,
k: usize,
gain: f32,
projection: Projection,
) -> Warped {
let (fw, fh) = (g.width as f64, g.height as f64);
let gain = gain.max(1e-6).powf(1.0 / 2.2);
let mut value = vec![f32::NAN; map.width * map.height];
let mut edge = vec![f32::NAN; map.width * map.height];
for ty in 0..map.height {
let v = map.origin.1 + (ty as f64 + 0.5) * map.px;
for tx in 0..map.width {
let u = map.origin.0 + (tx as f64 + 0.5) * map.px;
let d = projection.to_direction(map.scale, u, v);
let Some((x, y)) = cameras.project(k, d) else {
continue;
};
let (x, y) = (x + fw / 2.0 - 0.5, y + fh / 2.0 - 0.5);
let e = x.min(fw - 1.0 - x).min(y).min(fh - 1.0 - y);
if e < 0.0 {
continue;
}
let (x0, y0) = (x.floor() as usize, y.floor() as usize);
let (x1, y1) = ((x0 + 1).min(g.width - 1), (y0 + 1).min(g.height - 1));
let (ax, ay) = ((x - x0 as f64) as f32, (y - y0 as f64) as f32);
let at = |xx: usize, yy: usize| g.data[yy * g.width + xx];
let top = at(x0, y0) * (1.0 - ax) + at(x1, y0) * ax;
let bot = at(x0, y1) * (1.0 - ax) + at(x1, y1) * ax;
let i = ty * map.width + tx;
value[i] = (top * (1.0 - ay) + bot * ay) * gain;
edge[i] = e as f32;
}
}
Warped { value, edge }
}
/// Central-difference gradient magnitude of `plane` at texel `i`, from the
/// neighbours that exist.
fn detail(plane: &[f32], width: usize, height: usize, i: usize) -> f32 {
let (x, y) = (i % width, i / width);
let c = plane[i];
let mut g = 0.0f32;
let mut diff = |j: usize| {
let n = plane[j];
if !n.is_nan() {
g = g.max((n - c).abs());
}
};
if x > 0 {
diff(i - 1);
}
if x + 1 < width {
diff(i + 1);
}
if y > 0 {
diff(i - width);
}
if y + 1 < height {
diff(i + width);
}
g
}
/// Cut the overlap between the composite and frame `k`, marking in `take`
/// the overlap texels that go to `k`.
#[allow(clippy::too_many_arguments)]
fn cut(
map: &SeamMap,
value: &[f32],
edge: &[f32],
new: &Warped,
overlap: &[usize],
centres: &[(f64, f64)],
k: usize,
opts: &SeamOptions,
take: &mut [bool],
) {
let (w, h) = (map.width, map.height);
// The raw cost per overlap texel.
let mut raw = vec![f32::NAN; w * h];
let margin = opts.edge_margin.max(1.0);
for &i in overlap {
let differ = (value[i] - new.value[i]).abs();
let detail = detail(value, w, h, i).max(detail(&new.value, w, h, i));
let near = (1.0 - edge[i].min(new.edge[i]) / margin).max(0.0);
raw[i] = differ + opts.detail * detail + opts.edge * near * near + 1e-3;
}
// The worst over a small window: a texel is only cheap if its whole
// neighbourhood agrees, so the path keeps at least the blend's radius
// clear of a difference rather than threading the one lucky texel
// beside it — the blend straddles the path by that much and would
// otherwise reach the difference anyway.
let r = opts.smoothing as isize;
let mut cost = vec![OUTSIDE; w * h];
for &i in overlap {
let (x, y) = ((i % w) as isize, (i / w) as isize);
let mut worst = 0.0f32;
for dy in -r..=r {
for dx in -r..=r {
let (xx, yy) = (x + dx, y + dy);
if xx < 0 || yy < 0 || xx >= w as isize || yy >= h as isize {
continue;
}
let c = raw[yy as usize * w + xx as usize];
if !c.is_nan() {
worst = worst.max(c);
}
}
}
cost[i] = worst;
}
// The axis the cut crosses: from the composite's frames, weighted by how
// much of the overlap each owns, to the new frame.
let mut from = (0.0f64, 0.0f64);
for &i in overlap {
let c = centres[usize::from(map.labels[i])];
from = (from.0 + c.0, from.1 + c.1);
}
let m = overlap.len() as f64;
from = (from.0 / m, from.1 / m);
let to = centres[k];
let (mut ax, mut ay) = (to.0 - from.0, to.1 - from.1);
let len = (ax * ax + ay * ay).sqrt();
if len < 1e-6 {
(ax, ay) = (1.0, 0.0);
} else {
(ax, ay) = (ax / len, ay / len);
}
// Along the cut: perpendicular to the axis.
let (bx, by) = (-ay, ax);
// The overlap's extent in (s along the cut, t across it).
let st = |i: usize| {
let (x, y) = ((i % w) as f64 + 0.5, (i / w) as f64 + 0.5);
(x * bx + y * by, x * ax + y * ay)
};
let (mut s0, mut s1, mut t0, mut t1) = (f64::MAX, f64::MIN, f64::MAX, f64::MIN);
for &i in overlap {
let (s, t) = st(i);
s0 = s0.min(s);
s1 = s1.max(s);
t0 = t0.min(t);
t1 = t1.max(t);
}
let rows = (s1 - s0).round() as usize + 1;
let cols = (t1 - t0).round() as usize + 1;
// The grid in (s, t), each cell sampled from the texel it falls in, so
// that a rotated overlap has no holes.
let mut grid = vec![OUTSIDE; rows * cols];
let mut any = vec![false; rows];
for si in 0..rows {
for ti in 0..cols {
let (s, t) = (s0 + si as f64, t0 + ti as f64);
let x = s * bx + t * ax;
let y = s * by + t * ay;
if x < 0.0 || y < 0.0 {
continue;
}
let (x, y) = (x as usize, y as usize);
if x >= w || y >= h {
continue;
}
let c = cost[y * w + x];
if c < OUTSIDE {
grid[si * cols + ti] = c;
any[si] = true;
}
}
}
// Dynamic programming down the rows: the path moves at most one column
// per row, and starts afresh after a row with no overlap in it.
let mut acc = grid.clone();
let mut from_col = vec![0u32; rows * cols];
for si in 1..rows {
if !any[si] {
continue;
}
let prev = &acc[(si - 1) * cols..si * cols].to_vec();
if !any[si - 1] {
continue;
}
for ti in 0..cols {
let mut best = (prev[ti], ti);
if ti > 0 && prev[ti - 1] < best.0 {
best = (prev[ti - 1], ti - 1);
}
if ti + 1 < cols && prev[ti + 1] < best.0 {
best = (prev[ti + 1], ti + 1);
}
acc[si * cols + ti] += best.0;
from_col[si * cols + ti] = best.1 as u32;
}
}
// Back up from the end of each run of rows with overlap.
let mut seam = vec![usize::MAX; rows];
let mut si = rows;
while si > 0 {
si -= 1;
if !any[si] {
continue;
}
let row = &acc[si * cols..(si + 1) * cols];
let mut t = (0..cols)
.min_by(|&a, &b| row[a].total_cmp(&row[b]))
.unwrap_or(0);
loop {
seam[si] = t;
if si == 0 || !any[si - 1] {
break;
}
t = from_col[si * cols + t] as usize;
si -= 1;
}
}
// The new frame takes the side of the path its centre is on.
for &i in overlap {
let (s, t) = st(i);
let si = ((s - s0).round() as usize).min(rows - 1);
let ti = (t - t0).round();
if seam[si] != usize::MAX && ti >= seam[si] as f64 {
take[i] = true;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::linalg::{Mat3, Vec3};
/// A scene as a function of direction, and frames of it rendered by the
/// same cameras the seam reads.
fn render(
cameras: &Cameras,
k: usize,
size: (usize, usize),
scene: impl Fn(Vec3) -> f32,
) -> Gray {
let (w, h) = size;
let mut data = vec![0.0; w * h];
for y in 0..h {
for x in 0..w {
let p = (
x as f64 + 0.5 - w as f64 / 2.0,
y as f64 + 0.5 - h as f64 / 2.0,
);
data[y * w + x] = scene(cameras.bearing(k, p));
}
}
Gray {
width: w,
height: h,
data,
}
}
fn yaw(a: f64) -> Mat3 {
let (s, c) = a.sin_cos();
Mat3([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]])
}
/// Smooth, with a little texture: what a sky over a slope looks like to
/// the cost.
fn landscape(d: Vec3) -> f32 {
let (x, y) = (d.x() / d.z(), d.y() / d.z());
let texture = if y > 0.1 { 0.1 * (y * 40.0).sin() } else { 0.0 };
(0.5 + 0.2 * (x * 3.0).sin() + texture).clamp(0.0, 1.0) as f32
}
fn pair() -> Cameras {
Cameras {
rotations: vec![Mat3::IDENTITY, yaw(0.35)],
focal: 300.0,
}
}
#[test]
fn one_frame_owns_everything_it_reaches() {
let cameras = Cameras {
rotations: vec![Mat3::IDENTITY],
focal: 300.0,
};
let g = render(&cameras, 0, (320, 240), landscape);
let map = find(
&[&g],
&cameras,
&[1.0],
Projection::Perspective,
&Default::default(),
)
.unwrap();
let owned = map.labels.iter().filter(|&&l| l == 0).count();
assert!(owned as f64 > 0.95 * (map.width * map.height) as f64);
}
#[test]
fn each_frame_keeps_its_own_side() {
let cameras = pair();
let frames: Vec<Gray> = (0..2)
.map(|k| render(&cameras, k, (320, 240), landscape))
.collect();
let refs: Vec<&Gray> = frames.iter().collect();
let map = find(
&refs,
&cameras,
&[1.0, 1.0],
Projection::Cylindrical,
&Default::default(),
)
.unwrap();
let mid = map.height / 2 * map.width;
assert_eq!(map.labels[mid + 2], 0, "the left edge is frame 0's alone");
assert_eq!(
map.labels[mid + map.width - 3],
1,
"the right edge is frame 1's"
);
// One change of owner along every row that both frames cross.
for y in 0..map.height {
let row = &map.labels[y * map.width..(y + 1) * map.width];
let owned: Vec<u8> = row.iter().copied().filter(|&l| l != NONE).collect();
let changes = owned.windows(2).filter(|p| p[0] != p[1]).count();
assert!(changes <= 1, "row {y} changes owner {changes} times");
}
}
#[test]
fn the_seam_goes_round_what_only_one_frame_saw() {
// Frame 1 saw something frame 0 did not — a figure that walked into
// the overlap — in the middle of where the two meet.
let cameras = pair();
let figure = Vec3::new(0.175f64.sin(), 0.0, 0.175f64.cos());
let walker = |d: Vec3| {
let near = (d.x() - figure.x()).abs() < 0.04 && (d.y() - figure.y()).abs() < 0.15;
if near {
0.95
} else {
landscape(d)
}
};
let frames = [
render(&cameras, 0, (320, 240), landscape),
render(&cameras, 1, (320, 240), walker),
];
let refs: Vec<&Gray> = frames.iter().collect();
let map = find(
&refs,
&cameras,
&[1.0, 1.0],
Projection::Cylindrical,
&Default::default(),
)
.unwrap();
// Every texel of the figure is taken from the same frame, with a
// blend radius of room to spare, so it is either all there or not at
// all — never half.
let (u, v) = Projection::Cylindrical
.from_direction(map.scale, figure)
.unwrap();
let mut owners = std::collections::HashSet::new();
// The figure's extent on the surface, plus the blend's radius.
let radius = 3.0;
let reach = |half: f64| half * map.scale + radius * map.px;
let (ru, rv) = (reach(0.04), reach(0.15));
let mut dv = -rv;
while dv <= rv {
let mut du = -ru;
while du <= ru {
let s = map.share(1, u + du, v + dv, map.scale, radius);
owners.insert((s.unwrap() * 100.0).round() as i32);
du += map.px;
}
dv += map.px;
}
assert_eq!(owners.len(), 1, "the figure is split: shares {owners:?}");
}
#[test]
fn share_is_a_blend_across_the_seam_and_whole_away_from_it() {
let map = SeamMap {
width: 8,
height: 1,
scale: 1.0,
origin: (0.0, 0.0),
px: 1.0,
labels: vec![0, 0, 0, 0, 1, 1, 1, 1],
};
assert_eq!(map.share(0, 1.5, 0.5, 1.0, 2.0), Some(1.0));
assert_eq!(map.share(1, 6.5, 0.5, 1.0, 2.0), Some(1.0));
let at_seam = map.share(0, 4.0, 0.5, 1.0, 2.0).unwrap();
assert!((at_seam - 0.5).abs() < 1e-6, "{at_seam}");
// And at twice the scale, the same point is twice as far out.
assert_eq!(
map.share(0, 8.0, 1.0, 2.0, 2.0),
map.share(0, 4.0, 0.5, 1.0, 2.0)
);
let empty = SeamMap {
labels: vec![NONE; 8],
..map
};
assert_eq!(empty.share(0, 4.0, 0.5, 1.0, 2.0), None);
}
}
+53 -4
View File
@@ -260,8 +260,9 @@ impl CropRect {
/// ///
/// `anchor` is the point of the rect that stays put, in the rect's own /// `anchor` is the point of the rect that stays put, in the rect's own
/// `0..1` coordinates: `(1.0, 1.0)` while the top-left handle is dragged, /// `0..1` coordinates: `(1.0, 1.0)` while the top-left handle is dragged,
/// so the far corner is the one that does not move, and `(0.5, 0.5)` when /// so the far corner is the one that does not move, `(0.0, 0.5)` while
/// a ratio is chosen and the composition should stay where it is. /// the right-hand edge is dragged, and `(0.5, 0.5)` when a ratio is
/// chosen and the composition should stay where it is.
/// ///
/// **The rect grows onto the ratio rather than shrinking onto it.** The /// **The rect grows onto the ratio rather than shrinking onto it.** The
/// axis that is short is extended; the long one is never trimmed. Fitting /// axis that is short is extended; the long one is never trimmed. Fitting
@@ -269,6 +270,7 @@ impl CropRect {
/// along one axis alone would be immediately clamped back by the other, /// along one axis alone would be immediately clamped back by the other,
/// and the handle would simply refuse to move. The result is then scaled /// and the handle would simply refuse to move. The result is then scaled
/// down, both axes together, only as far as the frame's edge demands. /// down, both axes together, only as far as the frame's edge demands.
/// The exception is an edge: see the note in the body.
pub fn with_aspect(self, frame_w: u32, frame_h: u32, ratio: f32, anchor: (f32, f32)) -> Self { pub fn with_aspect(self, frame_w: u32, frame_h: u32, ratio: f32, anchor: (f32, f32)) -> Self {
let rect = self.normalised(); let rect = self.normalised();
let ratio = finite(ratio, 0.0); let ratio = finite(ratio, 0.0);
@@ -286,8 +288,19 @@ impl CropRect {
let px = rect.x + ax * rect.width; let px = rect.x + ax * rect.width;
let py = rect.y + ay * rect.height; let py = rect.y + ay * rect.height;
let mut w = rect.width.max(rect.height * r); // An anchor in the middle of one side is an *edge* being dragged, and
let mut h = w / r; // then the axis across that edge leads: it is the only one the user
// moved. Growing the short axis instead would take the other side
// for the leader whenever the edge went inward, and the edge would be
// pushed straight back out — a handle that only ever grows the crop.
let (mut w, mut h) = if ax == 0.5 && ay != 0.5 {
(rect.height * r, rect.height)
} else if ay == 0.5 && ax != 0.5 {
(rect.width, rect.width / r)
} else {
let w = rect.width.max(rect.height * r);
(w, w / r)
};
// Scaled to fit, never clamped to fit: clamping one axis against the // Scaled to fit, never clamped to fit: clamping one axis against the
// frame would break the very ratio this exists to hold. // frame would break the very ratio this exists to hold.
@@ -2255,6 +2268,42 @@ mod tests {
assert!((c.y - start.y).abs() < 1e-5, "{c:?}"); assert!((c.y - start.y).abs() < 1e-5, "{c:?}");
} }
#[test]
fn a_locked_edge_leads_and_the_far_side_stays_put() {
// An edge dragged inward under a lock must narrow the crop. With the
// short axis leading, the untouched height would win and push the
// edge straight back out.
let start = CropRect {
x: 0.2,
y: 0.2,
width: 0.4,
height: 0.6,
};
// Right edge held, dragged in: the left side and the vertical
// centre stay, the width is what was asked for.
let c = start.with_aspect(4000, 4000, 1.0, (0.0, 0.5));
assert!((c.x - start.x).abs() < 1e-5, "{c:?}");
assert!((c.width - start.width).abs() < 1e-5, "{c:?}");
assert!((c.height - start.width).abs() < 1e-5, "{c:?}");
assert!(
(c.y + c.height / 2.0 - (start.y + start.height / 2.0)).abs() < 1e-5,
"{c:?}"
);
// Top edge held: the bottom and the horizontal centre stay, the
// height is what was asked for.
let c = start.with_aspect(4000, 4000, 1.0, (0.5, 1.0));
assert!(
(c.y + c.height - (start.y + start.height)).abs() < 1e-5,
"{c:?}"
);
assert!((c.width - c.height).abs() < 1e-5, "{c:?}");
assert!(
(c.x + c.width / 2.0 - (start.x + start.width / 2.0)).abs() < 1e-5,
"{c:?}"
);
}
#[test] #[test]
fn a_locked_rect_grows_onto_the_ratio_rather_than_shrinking_onto_it() { fn a_locked_rect_grows_onto_the_ratio_rather_than_shrinking_onto_it() {
// Shrinking to fit makes a one-axis drag do nothing at all: the other // Shrinking to fit makes a one-axis drag do nothing at all: the other
+35 -4
View File
@@ -367,7 +367,7 @@ Built, on branch `merge/panorama`, in the order §10 gave:
| The camera-space tap | `OutputMode::CameraLinear`, `AdjustPass::render_camera_linear` | Done, `rgba32float`, tiles by view rect | | The camera-space tap | `OutputMode::CameraLinear`, `AdjustPass::render_camera_linear` | Done, `rgba32float`, tiles by view rect |
| Linear DNG writer, streamed | `dr_export::write_linear_dng` | Done; rawler reads it back | | Linear DNG writer, streamed | `dr_export::write_linear_dng` | Done; rawler reads it back |
| A three-sample `RawImage` re-entering the pipeline | `dr-decode`, `DemosaicedImage::from_linear_rgb16` | Done | | A three-sample `RawImage` re-entering the pipeline | `dr-decode`, `DemosaicedImage::from_linear_rgb16` | Done |
| Warp, accumulate, resolve, chunk by chunk | `dr_gpu::MergePass`, `merge.wgsl` | Done; feathered blend, scalar gain | | Warp, accumulate, resolve, chunk by chunk | `dr_gpu::MergePass`, `merge.wgsl` | Done; seams (§11.1) over a feather, scalar gain |
| The job: load, proxies, align, gains, confirm, merge, provenance | `dr_ui::merge` | Done; `examples/merge.rs` drives it headless | | The job: load, proxies, align, gains, confirm, merge, provenance | `dr_ui::merge` | Done; `examples/merge.rs` drives it headless |
| The page: table, preview, projection, Merge/Stop/Back; the grid's button | `merge.slint`, `merge_ui.rs` | Done; `DARKROOM_START_MERGE=a.CR2,b.CR2` lands on it | | The page: table, preview, projection, Merge/Stop/Back; the grid's button | `merge.slint`, `merge_ui.rs` | Done; `DARKROOM_START_MERGE=a.CR2,b.CR2` lands on it |
| Placement beside the sources through the outbox, rescan | `merge_ui.rs` | Done, untested against a server | | Placement beside the sources through the outbox, rescan | `merge_ui.rs` | Done, untested against a server |
@@ -385,9 +385,11 @@ half.
the file carries the black border. The largest inscribed rectangle over the file carries the black border. The largest inscribed rectangle over
the coverage, then the DNG's `DefaultCropOrigin`/`DefaultCropSize`, so the coverage, then the DNG's `DefaultCropOrigin`/`DefaultCropSize`, so
nothing is thrown away and the develop view opens on the picture. nothing is thrown away and the develop view opens on the picture.
2. **Seams and the pyramid** (§10 step 5). The feather hides exposure and 2. **The pyramid** (§10 step 5). Seams landed 2026-09-30 (§11.1); the
small misalignment; parallax on the near slope will show as a soft blend across them is one width for every frequency, so an exposure step
double edge at 1:1. the gains leave is narrowed to the seam's 64 px rather than hidden over
the old 200. A Laplacian pyramid would blend low frequencies wide and
detail narrow.
3. **Vignetting in the tap.** The lens profile's distortion is applied 3. **Vignetting in the tap.** The lens profile's distortion is applied
before the fetch; its vignetting is an operation and is not. Frame edges before the fetch; its vignetting is an operation and is not. Frame edges
are darker than their centres by the lens's falloff, and the feather are darker than their centres by the lens's falloff, and the feather
@@ -402,6 +404,35 @@ half.
catalog's `content_hash` is null for most images most of the time. The catalog's `content_hash` is null for most images most of the time. The
hash can join it when the catalog has one. hash can join it when the catalog has one.
### 11.1 Seams — 2026-09-30
The feather averaged every overlap over 200 px, so anything the frames
disagreed on — parallax on the near slope, a walker, wind in a branch — came
out twice at half strength: a soft double edge at 1:1, reported as a glitch.
`dr_pano::seam` now chooses, per output texel at proxy resolution, which
frame it is taken from. Frames are laid down nearest-first; where a new one
overlaps the composite, each texel costs the gain-corrected difference
between the two, plus the detail either has there, plus nearness to either
frame's edge (vignetting, the lens correction's fringe), taken as the
**worst** over a 4-texel window so the path stays a blend radius clear of a
difference rather than grazing it. The cut is a dynamic-programming path
across the overlap, perpendicular to the line from the composite's frames to
the new one: §4's per-column seam, not a graph cut. The map is computed per
projection, for the page's preview and again for the merge.
`merge.wgsl` weights a frame by its tent-filtered share of the label map
about each pixel (`SeamMap::share`, repeated verbatim), over a window
`seam_blend_px` wide (64, capped at 4 texels either side). The edge feather
remains underneath as a factor and, with a 1e-4 floor, as the answer where
the map names no frame that reaches the pixel. `--feather-only` on
`examples/merge.rs` merges the old way, for comparison.
Known limits: one axis per new frame, so in a multi-row set a frame
overlapping its left neighbour and the row above is cut along a compromise
direction; the cost reads grey proxies, so a difference in hue alone is
invisible to it.
## 12. Filling the border instead of cropping it — MI-GAN, read and measured 2026-09-19 ## 12. Filling the border instead of cropping it — MI-GAN, read and measured 2026-09-19
Raised after the first merges: the ragged border a cylinder leaves could be Raised after the first merges: the ragged border a cylinder leaves could be
File diff suppressed because one or more lines are too long
+24 -24
View File
@@ -39,7 +39,7 @@ The list is longer than it is tall, so a way to walk it that cannot be lost to t
Anchored on the fingers' midpoint, and on the pointer, so the gesture reads as magnifying the picture rather than sliding it about. Double-tap is the way to an exact 1:1; this is the way to everything in between. Past 1:1 the pixels are shown as they are, square and unsmoothed; below it, filtered. Anchored on the fingers' midpoint, and on the pointer, so the gesture reads as magnifying the picture rather than sliding it about. Double-tap is the way to an exact 1:1; this is the way to everything in between. Past 1:1 the pixels are shown as they are, square and unsmoothed; below it, filtered.
<sub>`ui/dr-ui/ui/app.slint:1982`</sub> <sub>`ui/dr-ui/ui/app.slint:2029`</sub>
### Move a magnified photograph about ### Move a magnified photograph about
@@ -50,7 +50,7 @@ Anchored on the fingers' midpoint, and on the pointer, so the gesture reads as m
Only once there is something outside the viewport to reach, which is why the cursor becomes a hand exactly then. The view is clamped to the frame: panning past the edge would show undefined area beside the photograph, and that reads as a rendering fault rather than as the end of the picture. Only once there is something outside the viewport to reach, which is why the cursor becomes a hand exactly then. The view is clamped to the frame: panning past the edge would show undefined area beside the photograph, and that reads as a rendering fault rather than as the end of the picture.
<sub>`ui/dr-ui/ui/app.slint:2078`</sub> <sub>`ui/dr-ui/ui/app.slint:2125`</sub>
### Paint a mask by hand ### Paint a mask by hand
@@ -60,7 +60,7 @@ Only once there is something outside the viewport to reach, which is why the cur
A model's mask stops inside a shoulder and leaks into the hair, and no single edge control fixes two errors that go opposite ways. The whole stroke is one step in the history, so taking a mark back costs one press however long it took to make. A model's mask stops inside a shoulder and leaks into the hair, and no single edge control fixes two errors that go opposite ways. The whole stroke is one step in the history, so taking a mark back costs one press however long it took to make.
<sub>`ui/dr-ui/ui/app.slint:2169`</sub> <sub>`ui/dr-ui/ui/app.slint:2216`</sub>
### Open this list ### Open this list
@@ -70,7 +70,7 @@ A model's mask stops inside a shoulder and leaks into the hair, and no single ed
Most of the keys are develop's, and a reference that could only be opened from the grid had to be looked up before opening the photograph they were wanted for. Most of the keys are develop's, and a reference that could only be opened from the grid had to be looked up before opening the photograph they were wanted for.
<sub>`ui/dr-ui/ui/app.slint:2395`</sub> <sub>`ui/dr-ui/ui/app.slint:2442`</sub>
### Take back the last change ### Take back the last change
@@ -81,7 +81,7 @@ Most of the keys are develop's, and a reference that could only be opened from t
A whole drag is one step, so undo takes back a decision rather than a frame of a gesture. The list is there because arriving six steps back costs what arriving from one does. A whole drag is one step, so undo takes back a decision rather than a frame of a gesture. The list is there because arriving six steps back costs what arriving from one does.
<sub>`ui/dr-ui/ui/app.slint:2425`</sub> <sub>`ui/dr-ui/ui/app.slint:2472`</sub>
### Do it again after taking it back ### Do it again after taking it back
@@ -90,7 +90,7 @@ A whole drag is one step, so undo takes back a decision rather than a frame of a
- **Keyboard** — `Ctrl+Shift+Z`, or `Ctrl+Y` - **Keyboard** — `Ctrl+Shift+Z`, or `Ctrl+Y`
- **See it** — [in the manual](manual/README.md#history-snapshots-presets) - **See it** — [in the manual](manual/README.md#history-snapshots-presets)
<sub>`ui/dr-ui/ui/app.slint:2439`</sub> <sub>`ui/dr-ui/ui/app.slint:2486`</sub>
### Remove a repair ### Remove a repair
@@ -98,7 +98,7 @@ A whole drag is one step, so undo takes back a decision rather than a frame of a
- **Pointer** — Click it, then Delete Repair - **Pointer** — Click it, then Delete Repair
- **Keyboard** — `Delete` or `Backspace`, while repairing - **Keyboard** — `Delete` or `Backspace`, while repairing
<sub>`ui/dr-ui/ui/app.slint:2459`</sub> <sub>`ui/dr-ui/ui/app.slint:2506`</sub>
### Copy the settings from this photograph ### Copy the settings from this photograph
@@ -109,7 +109,7 @@ A whole drag is one step, so undo takes back a decision rather than a frame of a
The button is the copy that has to work: a tablet has no modifier key to hold and no menu bar to hang the action from. The shortcut is an accelerator for a control that is on screen either way. The button is the copy that has to work: a tablet has no modifier key to hold and no menu bar to hang the action from. The shortcut is an accelerator for a control that is on screen either way.
<sub>`ui/dr-ui/ui/app.slint:2478`</sub> <sub>`ui/dr-ui/ui/app.slint:2525`</sub>
### Paste the settings onto this photograph ### Paste the settings onto this photograph
@@ -120,7 +120,7 @@ The button is the copy that has to work: a tablet has no modifier key to hold an
The button names what would be pasted — "3 adjustments", and whether the crop is coming with it — which the shortcut cannot say. Both paste the same scope. The button names what would be pasted — "3 adjustments", and whether the crop is coming with it — which the shortcut cannot say. Both paste the same scope.
<sub>`ui/dr-ui/ui/app.slint:2491`</sub> <sub>`ui/dr-ui/ui/app.slint:2538`</sub>
### Choose which kinds of edit a copy carries ### Choose which kinds of edit a copy carries
@@ -131,7 +131,7 @@ The button names what would be pasted — "3 adjustments", and whether the crop
Lightroom's Copy Settings. Pasting a look across a shoot usually means leaving each frame's crop and rotation alone, and that is a choice to make at the moment of copying. Lightroom's Copy Settings. Pasting a look across a shoot usually means leaving each frame's crop and rotation alone, and that is a choice to make at the moment of copying.
<sub>`ui/dr-ui/ui/app.slint:2509`</sub> <sub>`ui/dr-ui/ui/app.slint:2556`</sub>
### Export this photograph as the last one was ### Export this photograph as the last one was
@@ -142,7 +142,7 @@ Lightroom's Copy Settings. Pasting a look across a shoot usually means leaving e
Every export runs on the defaults in Settings, so "as the last one was" is what the button already does. The chord is Lightroom's and darktable's, kept so hands that learned it there need not learn it again. Every export runs on the defaults in Settings, so "as the last one was" is what the button already does. The chord is Lightroom's and darktable's, kept so hands that learned it there need not learn it again.
<sub>`ui/dr-ui/ui/app.slint:2534`</sub> <sub>`ui/dr-ui/ui/app.slint:2581`</sub>
### Choose how to export, then export ### Choose how to export, then export
@@ -153,7 +153,7 @@ Every export runs on the defaults in Settings, so "as the last one was" is what
The export sheet is the export defaults alone with an Export button. What is chosen there is kept, so it is also what the next Ctrl+Shift+E uses. The export sheet is the export defaults alone with an Export button. What is chosen there is kept, so it is also what the next Ctrl+Shift+E uses.
<sub>`ui/dr-ui/ui/app.slint:2547`</sub> <sub>`ui/dr-ui/ui/app.slint:2594`</sub>
### Keep a crop that leaves a mask outside ### Keep a crop that leaves a mask outside
@@ -161,7 +161,7 @@ The export sheet is the export defaults alone with an Export button. What is cho
- **Pointer** — Press "Keep crop" on the notice, or "Undo crop" to take it back - **Pointer** — Press "Keep crop" on the notice, or "Undo crop" to take it back
- **Keyboard** — `Enter` keeps it; `Ctrl+Z` takes the crop back, like any other step - **Keyboard** — `Enter` keeps it; `Ctrl+Z` takes the crop back, like any other step
<sub>`ui/dr-ui/ui/app.slint:2612`</sub> <sub>`ui/dr-ui/ui/app.slint:2659`</sub>
### Go back to the grid ### Go back to the grid
@@ -171,7 +171,7 @@ The export sheet is the export defaults alone with an Export button. What is cho
Lightroom's key for the grid. Escape gets there too, but a step at a time — out of a mode, then out of a zoom — where this goes straight back. Lightroom's key for the grid. Escape gets there too, but a step at a time — out of a mode, then out of a zoom — where this goes straight back.
<sub>`ui/dr-ui/ui/app.slint:2629`</sub> <sub>`ui/dr-ui/ui/app.slint:2676`</sub>
### Nudge the control last moved ### Nudge the control last moved
@@ -181,7 +181,7 @@ Lightroom's key for the grid. Escape gets there too, but a step at a time — ou
Lightroom's keys for the selected slider. There is no focus ring on a slider here, so "selected" is the last one moved — the same control `R` puts back — which covers the framing sliders, perspective included, as well as the adjustments. Lightroom's keys for the selected slider. There is no focus ring on a slider here, so "selected" is the last one moved — the same control `R` puts back — which covers the framing sliders, perspective included, as well as the adjustments.
<sub>`ui/dr-ui/ui/app.slint:2658`</sub> <sub>`ui/dr-ui/ui/app.slint:2705`</sub>
### Change which group of adjustments is on screen ### Change which group of adjustments is on screen
@@ -192,7 +192,7 @@ Lightroom's keys for the selected slider. There is no focus ring on a slider her
The groups are whatever the operation set declares itself to be about, so there are as many as the pipeline has and no key can be assigned to one of them by name. Stepping is the binding that survives a node being added. The groups are whatever the operation set declares itself to be about, so there are as many as the pipeline has and no key can be assigned to one of them by name. Stepping is the binding that survives a node being added.
<sub>`ui/dr-ui/ui/app.slint:2686`</sub> <sub>`ui/dr-ui/ui/app.slint:2733`</sub>
### Look at the photograph at 1:1 ### Look at the photograph at 1:1
@@ -203,7 +203,7 @@ The groups are whatever the operation set declares itself to be about, so there
Noise reduction and capture sharpening are judgements about single pixels, and a fitted view averages several of the file's into each one on screen — so the frame looks softer than it is and the correction goes too far. The point and the magnification survive opening the next photograph, which is what makes checking the same eye across forty portraits forty keystrokes rather than forty pans. From 1:1 on the photograph is drawn as its own pixels, each a hard-edged square, rather than smoothed into a blur. Noise reduction and capture sharpening are judgements about single pixels, and a fitted view averages several of the file's into each one on screen — so the frame looks softer than it is and the correction goes too far. The point and the magnification survive opening the next photograph, which is what makes checking the same eye across forty portraits forty keystrokes rather than forty pans. From 1:1 on the photograph is drawn as its own pixels, each a hard-edged square, rather than smoothed into a blur.
<sub>`ui/dr-ui/ui/app.slint:2722`</sub> <sub>`ui/dr-ui/ui/app.slint:2769`</sub>
### Rate this photograph ### Rate this photograph
@@ -211,7 +211,7 @@ Noise reduction and capture sharpening are judgements about single pixels, and a
- **Pointer** — Click a star in the top bar - **Pointer** — Click a star in the top bar
- **Keyboard** — `0`–`5` - **Keyboard** — `0`–`5`
<sub>`ui/dr-ui/ui/app.slint:2779`</sub> <sub>`ui/dr-ui/ui/app.slint:2826`</sub>
### Pick or reject this photograph ### Pick or reject this photograph
@@ -221,7 +221,7 @@ Noise reduction and capture sharpening are judgements about single pixels, and a
The grid's keys, on the photograph that is open (FR-UI-5, 2026-09-19). Judging here does not move on to the next frame: that belongs to culling, and in develop the photograph in front of you is the one being worked on. The grid's keys, on the photograph that is open (FR-UI-5, 2026-09-19). Judging here does not move on to the next frame: that belongs to culling, and in develop the photograph in front of you is the one being worked on.
<sub>`ui/dr-ui/ui/app.slint:2785`</sub> <sub>`ui/dr-ui/ui/app.slint:2832`</sub>
### Give this photograph a colour label ### Give this photograph a colour label
@@ -232,7 +232,7 @@ The grid's keys, on the photograph that is open (FR-UI-5, 2026-09-19). Judging h
The grid's keys, on the photograph that is open, so labelling while stepping through a folder is one hand's work. The bar names the label in words beside its mark. The grid's keys, on the photograph that is open, so labelling while stepping through a folder is one hand's work. The bar names the label in words beside its mark.
<sub>`ui/dr-ui/ui/app.slint:2815`</sub> <sub>`ui/dr-ui/ui/app.slint:2862`</sub>
### Move to the next or previous photograph ### Move to the next or previous photograph
@@ -243,7 +243,7 @@ The grid's keys, on the photograph that is open, so labelling while stepping thr
The edit on screen is saved on the way out, so stepping through a folder is as much a departure as going back to the grid and loses nothing. A and D as well as the arrows, so the left hand steps along the roll while the right stays on the mouse. The edit on screen is saved on the way out, so stepping through a folder is as much a departure as going back to the grid and loses nothing. A and D as well as the arrows, so the left hand steps along the roll while the right stays on the mouse.
<sub>`ui/dr-ui/ui/app.slint:2840`</sub> <sub>`ui/dr-ui/ui/app.slint:2887`</sub>
### See the photograph before you edited it ### See the photograph before you edited it
@@ -254,7 +254,7 @@ The edit on screen is saved on the way out, so stepping through a folder is as m
Held rather than toggled, and no split screen: a split halves the working image on the tablet the column was sized for, and the comparison photographers describe making is a flick back and forth. It takes no history step, so checking whether a frame is overcooked costs nothing to undo afterwards. Held rather than toggled, and no split screen: a split halves the working image on the tablet the column was sized for, and the comparison photographers describe making is a flick back and forth. It takes no history step, so checking whether a frame is overcooked costs nothing to undo afterwards.
<sub>`ui/dr-ui/ui/app.slint:2970`</sub> <sub>`ui/dr-ui/ui/app.slint:3012`</sub>
### Put one control back to its default ### Put one control back to its default
@@ -338,7 +338,7 @@ The question a correction raises is whether it did what it was for — whether t
One key for "up one", innermost first: a question before the sheet under it, a sheet before the view, a view before the library. Nothing is left behind a dialogue that the key walked straight past. One key for "up one", innermost first: a question before the sheet under it, a sheet before the view, a view before the library. Nothing is left behind a dialogue that the key walked straight past.
<sub>`ui/dr-ui/ui/app.slint:1024`</sub> <sub>`ui/dr-ui/ui/app.slint:1026`</sub>
### Do what a sheet offers ### Do what a sheet offers
@@ -346,7 +346,7 @@ One key for "up one", innermost first: a question before the sheet under it, a s
- **Pointer** — Press its button — Export, or Copy - **Pointer** — Press its button — Export, or Copy
- **Keyboard** — `Enter`, on the export and copy sheets - **Keyboard** — `Enter`, on the export and copy sheets
<sub>`ui/dr-ui/ui/app.slint:1034`</sub> <sub>`ui/dr-ui/ui/app.slint:1036`</sub>
### Scroll by the scrollbar ### Scroll by the scrollbar
+1 -1
View File
@@ -4,7 +4,7 @@
# makes `makepkg -si` in this directory install what you are actually working # makes `makepkg -si` in this directory install what you are actually working
# on. Swap `source` for a tagged tarball when there is something to release. # on. Swap `source` for a tagged tarball when there is something to release.
pkgname=darkroom pkgname=darkroom
pkgver=0.19.1 pkgver=0.19.3
# Back to 1 with the version: a new pkgver is a new archive name, so there is # Back to 1 with the version: a new pkgver is a new archive name, so there is
# nothing for makepkg to reuse and nothing for a release number to disambiguate. # nothing for makepkg to reuse and nothing for a release number to disambiguate.
pkgrel=1 pkgrel=1
+18 -19
View File
@@ -4,7 +4,7 @@
//! FR-CAT-10 asks for removable-volume insertion to be detected "where the //! FR-CAT-10 asks for removable-volume insertion to be detected "where the
//! platform permits", which is a careful phrase and this module is why. There //! platform permits", which is a careful phrase and this module is why. There
//! is no portable answer: Linux has a mount table and a sysfs flag, Android //! is no portable answer: Linux has a mount table and a sysfs flag, Android
//! has neither and hands out a document tree the user picked (ARCH §6.9). //! has neither and lists its volumes through a Java service (`dr_ui::cards`).
//! So this reports what it can and returns an empty list where it cannot, //! So this reports what it can and returns an empty list where it cannot,
//! and every caller must still offer the user a way to say where the card is. //! and every caller must still offer the user a way to say where the card is.
//! //!
@@ -67,22 +67,18 @@ impl Volume {
/// where it is mounted. `false` here means the operation cannot be performed /// where it is mounted. `false` here means the operation cannot be performed
/// however hard the user tries, and the interface should not offer it. /// however hard the user tries, and the interface should not offer it.
/// ///
/// It is `false` on Android, for two reasons that both have to be fixed before /// It is `true` on Linux and on Android. On Android the card is read by
/// it can change: /// path too — `/storage/9C33-6BBD` — once the user has granted "all files
/// access", but finding it takes the platform's `StorageManager`, which is
/// Java. So [`volumes`] still answers empty there, and `dr_ui::cards` lists
/// the volumes and asks for the permission instead.
/// ///
/// - There is no mount table to read and no path to type. Storage is reached /// The engine above this takes storage traits and never a path, and the
/// through a tree the user granted, and a removable volume appears there or /// importer only ever *writes* into its own staging directory, which is a
/// not at all (ARCH §6.9). /// plain directory on every platform. So what this gates is whether a card
/// - Nothing implements [`WritableStorage`](crate::WritableStorage) except /// can be *read*, nothing more.
/// [`LocalStorage`](crate::LocalStorage), so there is no destination to write
/// into even once a source is named.
///
/// The engine above this is already portable — it takes storage traits and
/// never a path — so what this gates is the *interface*, and it stops being
/// `false` when a SAF implementation lands rather than when the importer is
/// rewritten.
pub const fn imports_supported() -> bool { pub const fn imports_supported() -> bool {
cfg!(target_os = "linux") cfg!(any(target_os = "linux", target_os = "android"))
} }
/// Every mounted volume that might hold photographs. /// Every mounted volume that might hold photographs.
@@ -130,9 +126,9 @@ fn platform_volumes() -> Vec<Volume> {
/// Everywhere else: no answer, and saying so is the honest result. /// Everywhere else: no answer, and saying so is the honest result.
/// ///
/// On Android the question is not merely unanswerable but wrong — storage is /// On Android there is no readable mount table either; the volumes come from
/// reached through a tree the user granted, and a card appears there or not at /// `StorageManager` through `dr_ui::cards`, which needs the JNI this crate
/// all (ARCH §6.9, FR-PLAT-AND-1). /// does not have.
#[cfg(not(target_os = "linux"))] #[cfg(not(target_os = "linux"))]
fn platform_volumes() -> Vec<Volume> { fn platform_volumes() -> Vec<Volume> {
Vec::new() Vec::new()
@@ -358,7 +354,10 @@ tmpfs /run/user/1000 tmpfs rw,nosuid 0 0
// The two are different claims: an empty list means "plug one in", // The two are different claims: an empty list means "plug one in",
// `false` here means "this cannot be done here". An interface that // `false` here means "this cannot be done here". An interface that
// conflated them would offer a page that can never be used. // conflated them would offer a page that can never be used.
assert_eq!(imports_supported(), cfg!(target_os = "linux")); assert_eq!(
imports_supported(),
cfg!(any(target_os = "linux", target_os = "android"))
);
if !imports_supported() { if !imports_supported() {
assert!(volumes().is_empty()); assert!(volumes().is_empty());
} }
+9
View File
@@ -6,6 +6,9 @@
//! cargo run -p dr-ui --example merge --release -- --leave-out 3 fixtures/pano/2025-08-05/*.CR2 //! cargo run -p dr-ui --example merge --release -- --leave-out 3 fixtures/pano/2025-08-05/*.CR2
//! ``` //! ```
//! //!
//! `--feather-only` merges without seams — every overlap the feathered
//! average — for comparing the two on the same set.
//!
//! `--leave-out N` unticks frame `N` once the first alignment is in, as the //! `--leave-out N` unticks frame `N` once the first alignment is in, as the
//! page's box would, so the job aligns again without it. //! page's box would, so the job aligns again without it.
//! //!
@@ -25,6 +28,7 @@ fn main() {
let mut fill = false; let mut fill = false;
let mut wait_engines = false; let mut wait_engines = false;
let mut leave_out: Option<usize> = None; let mut leave_out: Option<usize> = None;
let mut seams = true;
loop { loop {
match args.first().map(String::as_str) { match args.first().map(String::as_str) {
Some("--out") => { Some("--out") => {
@@ -39,6 +43,10 @@ fn main() {
args.remove(0); args.remove(0);
leave_out = args.remove(0).parse().ok(); leave_out = args.remove(0).parse().ok();
} }
Some("--feather-only") => {
args.remove(0);
seams = false;
}
Some("--wait-engines") => { Some("--wait-engines") => {
args.remove(0); args.remove(0);
wait_engines = true; wait_engines = true;
@@ -101,6 +109,7 @@ fn main() {
dr_ui::merge::MergeRequest::new(frames, dr_ui::merge::MergeDestination::Local(dir)); dr_ui::merge::MergeRequest::new(frames, dr_ui::merge::MergeDestination::Local(dir));
// The filler from the shared models directory, as the app finds it. // The filler from the shared models directory, as the app finds it.
request.inpaint_model = dr_ui::merge::inpaint_model_path(); request.inpaint_model = dr_ui::merge::inpaint_model_path();
request.seams = seams;
let (tx, rx) = std::sync::mpsc::channel(); let (tx, rx) = std::sync::mpsc::channel();
let (decide, decision) = std::sync::mpsc::channel(); let (decide, decision) = std::sync::mpsc::channel();
let cancel = dr_ui::merge::Cancel::default(); let cancel = dr_ui::merge::Cancel::default();
+160
View File
@@ -0,0 +1,160 @@
//! TRACES: FR-CAT-10 | NFR-PORT-1
//! Finding a camera card on Android, and the permission that makes it readable.
//!
//! `dr_plat::volumes` reads the mount table, which Android does not let an
//! app read; the volumes are listed by `StorageManager`, which is Java. So
//! this is the Android half of "where is the card": `Cards.java` does the
//! asking and this is the JNI bridge to it, through the helpers `saf` already
//! has.
//!
//! What comes back is an ordinary path — `/storage/9C33-6BBD` — and the rest
//! of the import reads it exactly as it reads `/run/media/…` on the desktop.
//! That only works once the user has granted "all files access", which is
//! [`has_access`] and [`request_access`].
use std::path::PathBuf;
/// Whether the app may read a card's files by path.
#[cfg(target_os = "android")]
pub fn has_access() -> bool {
crate::saf::call("checking card access", |env, context| {
let cls = crate::saf::class(env, context, jni::jni_str!("paris.tourolle.darkroom.Cards"))?;
env.call_static_method(
&cls,
jni::jni_str!("hasAccess"),
jni::jni_sig!("(Landroid/content/Context;)Z"),
&[context.into()],
)?
.z()
})
.unwrap_or_else(|e| {
log::warn!("{e}");
false
})
}
/// Open the system page where the user grants it.
#[cfg(target_os = "android")]
pub fn request_access() {
let opened = crate::saf::call("asking for card access", |env, context| {
let cls = crate::saf::class(env, context, jni::jni_str!("paris.tourolle.darkroom.Cards"))?;
env.call_static_method(
&cls,
jni::jni_str!("requestAccess"),
jni::jni_sig!("(Landroid/content/Context;)V"),
&[context.into()],
)?;
Ok(())
});
if let Err(e) = opened {
log::warn!("{e}");
}
}
/// Every mounted volume that is not the device's own storage.
///
/// Empty when there is none, and when the platform could not be asked — the
/// page says "insert a card" either way, which is the thing to do in both.
#[cfg(target_os = "android")]
pub fn volumes() -> Vec<dr_plat::Volume> {
let lines = crate::saf::call("listing storage volumes", |env, context| {
let cls = crate::saf::class(env, context, jni::jni_str!("paris.tourolle.darkroom.Cards"))?;
let value = env
.call_static_method(
&cls,
jni::jni_str!("volumes"),
jni::jni_sig!("(Landroid/content/Context;)[Ljava/lang/String;"),
&[context.into()],
)?
.l()?;
if value.is_null() {
return Ok(Vec::new());
}
let array = env.cast_local::<jni::objects::JObjectArray>(value)?;
let count = array.len(env)?;
let mut out = Vec::with_capacity(count);
for i in 0..count {
let element = array.get_element(env, i)?;
if let Some(line) = crate::saf::text(env, element)? {
out.push(line);
}
}
Ok(out)
})
.unwrap_or_else(|e| {
log::warn!("{e}");
Vec::new()
});
let mut found: Vec<dr_plat::Volume> = lines
.iter()
.filter_map(|line| parse(line))
.map(|(path, label, removable)| dr_plat::Volume {
has_dcim: path.join("DCIM").is_dir(),
label,
removable,
path,
})
.collect();
// The order `dr_plat::volumes` gives: likely cards first, then by name.
found.sort_by(|a, b| {
b.is_likely_card()
.cmp(&a.is_likely_card())
.then_with(|| a.label.cmp(&b.label))
});
found
}
/// One line from `Cards.volumes`: `path \t description \t removable`.
///
/// `None` for a line that does not have the three fields, which would be a
/// mismatch between the two halves rather than anything a device does.
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
fn parse(line: &str) -> Option<(PathBuf, String, bool)> {
let mut fields = line.split('\t');
let path = fields.next().filter(|p| !p.is_empty())?;
let label = fields.next()?;
let removable = fields.next()? == "1";
if fields.next().is_some() {
return None;
}
Some((PathBuf::from(path), label.to_string(), removable))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_volume_line_is_read_as_cards_java_writes_it() {
// The format is a contract between two files in two languages, and
// only a device would otherwise notice it break.
let java = include_str!(
"../../../apps/darkroom-android/android/java/paris/tourolle/darkroom/Cards.java"
);
assert!(
java.contains(r#"out.add(path + "\t" + description.replace('\t', ' ') + "\t""#),
"Cards.volumes no longer writes the line this parses"
);
assert_eq!(
parse("/storage/9C33-6BBD\tSanDisk SD card\t1"),
Some((
PathBuf::from("/storage/9C33-6BBD"),
"SanDisk SD card".to_string(),
true
))
);
assert_eq!(
parse("/storage/1234-ABCD\tUSB drive\t0").map(|v| v.2),
Some(false)
);
}
#[test]
fn a_malformed_line_is_dropped_rather_than_guessed_at() {
assert_eq!(parse(""), None);
assert_eq!(parse("/storage/9C33-6BBD"), None);
assert_eq!(parse("\tlabel\t1"), None);
assert_eq!(parse("/a\tb\t1\textra"), None);
}
}
+4 -3
View File
@@ -1042,9 +1042,10 @@ fn wire_zoom_pan_crop(
width, width,
height, height,
}; };
// The overlay reports the corner it is *holding*; the point // The overlay reports the handle it is *holding*; the point
// that must not move is the opposite one. A move reports no // that must not move is the opposite one — the far corner, or
// corner at all, and keeps the shape it already has — there is // for an edge the middle of the far side. A move reports no
// handle at all, and keeps the shape it already has — there is
// nothing to reshape, and reshaping about a centre would drag // nothing to reshape, and reshaping about a centre would drag
// an over-moved rect smaller instead of sliding it along the // an over-moved rect smaller instead of sliding it along the
// edge. // edge.
+100 -1
View File
@@ -68,6 +68,13 @@ pub struct ImportController {
selected: Cell<i32>, selected: Cell<i32>,
/// The source. Typed or chosen; a card the app did not find is still a card. /// The source. Typed or chosen; a card the app did not find is still a card.
card: RefCell<String>, card: RefCell<String>,
/// Android only: the user has not granted "all files access", so no card
/// can be read and the page asks for it instead of listing volumes.
needs_access: Cell<bool>,
/// Android only: watches for that grant after the settings page has been
/// opened, so the list fills in when the user comes back.
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
access_watch: RefCell<Option<slint::Timer>>,
/// What the last survey found, `None` before one has run. /// What the last survey found, `None` before one has run.
survey: RefCell<Option<(usize, u64)>>, survey: RefCell<Option<(usize, u64)>>,
@@ -106,6 +113,8 @@ impl ImportController {
volumes: RefCell::new(Vec::new()), volumes: RefCell::new(Vec::new()),
selected: Cell::new(-1), selected: Cell::new(-1),
card: RefCell::new(String::new()), card: RefCell::new(String::new()),
needs_access: Cell::new(false),
access_watch: RefCell::new(None),
survey: RefCell::new(None), survey: RefCell::new(None),
surveying: Cell::new(false), surveying: Cell::new(false),
upload_target: RefCell::new(String::new()), upload_target: RefCell::new(String::new()),
@@ -137,7 +146,7 @@ impl ImportController {
/// Look for cards. Cheap, and safe to call whenever the page is shown. /// Look for cards. Cheap, and safe to call whenever the page is shown.
fn refresh_volumes(&self) { fn refresh_volumes(&self) {
let found = dr_plat::volumes(); let found = self.find_volumes();
// Keep a typed path: a refresh must not discard what the user entered // Keep a typed path: a refresh must not discard what the user entered
// because the app happened to find three other volumes. // because the app happened to find three other volumes.
if self.card.borrow().is_empty() { if self.card.borrow().is_empty() {
@@ -160,6 +169,34 @@ impl ImportController {
*self.volumes.borrow_mut() = found; *self.volumes.borrow_mut() = found;
} }
/// The mount table, on the desktop.
#[cfg(not(target_os = "android"))]
fn find_volumes(&self) -> Vec<dr_plat::Volume> {
dr_plat::volumes()
}
/// `StorageManager`, on Android, once the user has allowed the app to read
/// a card at all (see [`crate::cards`]).
///
/// The path cannot be typed here — the field is hidden on Android — so a
/// remembered path whose card has been taken out is dropped rather than
/// left selected with no way to change it.
#[cfg(target_os = "android")]
fn find_volumes(&self) -> Vec<dr_plat::Volume> {
let granted = crate::cards::has_access();
self.needs_access.set(!granted);
let found = if granted {
crate::cards::volumes()
} else {
Vec::new()
};
let card = self.card.borrow().clone();
if !found.iter().any(|v| v.path.display().to_string() == card) {
self.card.borrow_mut().clear();
}
found
}
/// The transfer options a run is started with. /// The transfer options a run is started with.
fn ingest_options(&self) -> Options { fn ingest_options(&self) -> Options {
let stored = self.options(); let stored = self.options();
@@ -239,6 +276,7 @@ pub fn render(window: &AppWindow, ctl: &Rc<ImportController>) {
!card.is_empty() && import::looks_like_a_card(std::path::Path::new(&card)), !card.is_empty() && import::looks_like_a_card(std::path::Path::new(&card)),
); );
window.set_import_card_path(card.into()); window.set_import_card_path(card.into());
window.set_import_needs_access(ctl.needs_access.get());
window.set_import_surveying(ctl.surveying.get()); window.set_import_surveying(ctl.surveying.get());
window.set_import_survey_summary( window.set_import_survey_summary(
@@ -428,6 +466,20 @@ where
render(&w, &ctl); render(&w, &ctl);
}); });
} }
{
let weak = window.as_weak();
let ctl = ctl.clone();
let context = context.clone();
window.on_import_grant_access(move || {
#[cfg(target_os = "android")]
watch_for_access(&weak, &ctl, &context);
// Nothing to grant elsewhere; the control is shown only when
// `needs_access` is set, which only Android sets.
#[cfg(not(target_os = "android"))]
let _ = (&weak, &ctl, &context);
});
}
} }
/// Options. /// Options.
@@ -567,6 +619,53 @@ fn wire_running<C, F>(
/// Take a source the user named — typed, or chosen in the dialogue — rather /// Take a source the user named — typed, or chosen in the dialogue — rather
/// than one from the volume list, and count what is on it. /// than one from the volume list, and count what is on it.
/// Send the user to the system page that grants "all files access", and
/// fill the page in once they have.
///
/// The grant is a settings switch, not a dialog with an answer, and nothing
/// tells the app when it flips. So the page asks again twice a second until
/// it has it, or for five minutes — long enough to find the switch, short
/// enough that a user who walked away is not polled for ever. Coming back to
/// the page later re-checks anyway (`import_open`).
#[cfg(target_os = "android")]
fn watch_for_access<C>(weak: &slint::Weak<AppWindow>, ctl: &Rc<ImportController>, context: &Rc<C>)
where
C: Fn() -> Option<Context> + 'static,
{
crate::cards::request_access();
let since = std::time::Instant::now();
let (weak, held, context) = (weak.clone(), ctl.clone(), context.clone());
let timer = slint::Timer::default();
timer.start(
slint::TimerMode::Repeated,
std::time::Duration::from_millis(500),
move || {
let granted = crate::cards::has_access();
if !granted && since.elapsed() < std::time::Duration::from_secs(300) {
return;
}
if let Some(t) = held.access_watch.borrow().as_ref() {
t.stop();
}
// Released outside its own callback, as `saf::pick_tree` does: a
// timer dropped from inside the closure it is running is dropping
// that closure mid-call.
let release = held.clone();
slint::Timer::single_shot(std::time::Duration::ZERO, move || {
release.access_watch.borrow_mut().take();
});
if granted {
let Some(w) = weak.upgrade() else { return };
held.refresh_volumes();
survey(&w, &held, &context);
render(&w, &held);
}
},
);
*ctl.access_watch.borrow_mut() = Some(timer);
}
fn set_card( fn set_card(
w: &AppWindow, w: &AppWindow,
ctl: &Rc<ImportController>, ctl: &Rc<ImportController>,
+1
View File
@@ -24,6 +24,7 @@ mod albums_ui;
#[cfg(all(feature = "automation", unix))] #[cfg(all(feature = "automation", unix))]
mod automation; mod automation;
mod bursts; mod bursts;
mod cards;
mod collections_ui; mod collections_ui;
#[cfg(test)] #[cfg(test)]
mod decoder_seam; mod decoder_seam;
+6 -1
View File
@@ -522,11 +522,16 @@ pub(super) fn flush_sweep(catalog: &Catalog, found: &mut Vec<MetadataFound>) {
.filter(|m| m.captured_at.is_none()) .filter(|m| m.captured_at.is_none())
.map(|m| m.image_id) .map(|m| m.image_id)
.collect(); .collect();
for id in ids { for &id in &ids {
let _ = catalog let _ = catalog
.connection() .connection()
.execute("UPDATE images SET metadata_state = 2 WHERE id = ?1", [id]); .execute("UPDATE images SET metadata_state = 2 WHERE id = ?1", [id]);
} }
// A header with no date is not a photograph with no date: WhatsApp and
// most re-exports strip EXIF and keep the date in the name.
if let Err(e) = dr_catalog::name_dates::fill(catalog.connection(), Some(&ids)) {
log::warn!("sweep: dating from names: {e}");
}
found.clear(); found.clear();
} }
+74 -11
View File
@@ -42,7 +42,7 @@ use dr_gpu::{
}; };
use dr_pano::bundle::Cameras; use dr_pano::bundle::Cameras;
use dr_pano::projection::{self, Projection}; use dr_pano::projection::{self, Projection};
use dr_pano::{Alignment, Gray}; use dr_pano::{Alignment, Gray, SeamMap};
use dr_pipeline::EditGraph; use dr_pipeline::EditGraph;
pub use crate::export::Cancel; pub use crate::export::Cancel;
@@ -103,8 +103,14 @@ pub struct MergeRequest {
pub destination: MergeDestination, pub destination: MergeDestination,
/// `None` for the projection the field of view suggests. /// `None` for the projection the field of view suggests.
pub projection: Option<Projection>, pub projection: Option<Projection>,
/// Pixels over which a frame's weight ramps up from its edge. /// Pixels over which a frame's weight ramps up from its edge, where no
/// seam says which frame a pixel is taken from.
pub feather_px: f32, pub feather_px: f32,
/// Whether overlaps are cut along seams (`dr_pano::seam`) or averaged
/// across `feather_px` everywhere.
pub seams: bool,
/// The width, in output pixels, of the blend across a seam.
pub seam_blend_px: f32,
/// GPU work unit; also the DNG strip height. /// GPU work unit; also the DNG strip height.
pub chunk: (u32, u32), pub chunk: (u32, u32),
/// The border filler's weights, if the device has them (FR-MRG-4). /// The border filler's weights, if the device has them (FR-MRG-4).
@@ -122,6 +128,8 @@ impl MergeRequest {
destination, destination,
projection: None, projection: None,
feather_px: 200.0, feather_px: 200.0,
seams: true,
seam_blend_px: 64.0,
chunk: (2048, 512), chunk: (2048, 512),
inpaint_model: None, inpaint_model: None,
decoder: dr_decode::default(), decoder: dr_decode::default(),
@@ -478,11 +486,20 @@ fn run_inner(
let preview = match s.alignment.is_complete() { let preview = match s.alignment.is_complete() {
false => None, false => None,
true => { true => {
let map = request
.seams
.then(|| seams(&proxies, &s.alignment, &s.gains, projection))
.flatten();
let blend = map.as_deref().map(|m| {
let full = m.scale * s.focal_full / s.alignment.focal;
(m, m.blend_radius(full, f64::from(request.seam_blend_px)))
});
let (w, h, mut rgb, mut known) = preview_planes( let (w, h, mut rgb, mut known) = preview_planes(
&colour, &colour,
&proxies, &proxies,
&s.alignment, &s.alignment,
&s.gains, &s.gains,
blend,
projection, projection,
first_raw, first_raw,
1600, 1600,
@@ -605,6 +622,13 @@ fn run_inner(
} }
}; };
// The seams, on the surface chosen, over the frames kept.
let seam_map = request.seams.then(|| {
let kept: Vec<&Gray> = solved.keep.iter().map(|&k| &proxies[k]).collect();
seams(&kept, &solved.alignment, &solved.gains, projection)
});
let seam_map = seam_map.flatten();
// From here on only the kept frames exist, indexed as the alignment // From here on only the kept frames exist, indexed as the alignment
// indexes them. // indexes them.
let Solved { let Solved {
@@ -704,6 +728,8 @@ fn run_inner(
scale: focal_full, scale: focal_full,
bounds, bounds,
feather: request.feather_px, feather: request.feather_px,
seams: seam_map.clone(),
seam_blend: request.seam_blend_px,
chunk: request.chunk, chunk: request.chunk,
sample_scale: white_level as f32, sample_scale: white_level as f32,
balance, balance,
@@ -746,6 +772,8 @@ fn run_inner(
max_v: bounds.max_v / q, max_v: bounds.max_v / q,
}, },
feather: request.feather_px, feather: request.feather_px,
seams: seam_map.clone(),
seam_blend: request.seam_blend_px / q as f32,
chunk: request.chunk, chunk: request.chunk,
sample_scale: white_level as f32, sample_scale: white_level as f32,
balance, balance,
@@ -1227,21 +1255,51 @@ fn solve(
}) })
} }
/// Which frame each part of the composite comes from (`dr_pano::seam`), on
/// `projection` at the proxies' scale. `None` when the alignment is not
/// complete — the merge then falls back to the feathered average.
fn seams(
proxies: &[&Gray],
alignment: &Alignment,
gains: &[f32],
projection: Projection,
) -> Option<Arc<SeamMap>> {
if !alignment.is_complete() {
return None;
}
let t = Instant::now();
let map = dr_pano::seam::find(
proxies,
&alignment.cameras(),
gains,
projection,
&dr_pano::SeamOptions::default(),
);
log::info!(
"merge: seams over {} frames in {:?}",
proxies.len(),
t.elapsed()
);
map.map(Arc::new)
}
/// The aligned set on its surface, in colour, for the page. /// The aligned set on its surface, in colour, for the page.
/// ///
/// A quick look, not the pipeline: the first frame's white balance and /// A quick look, not the pipeline: the first frame's white balance and
/// matrix, a gamma, and the frames averaged where they overlap with their /// matrix, a gamma, and the frames joined along the same seams the merge
/// gains applied. Ghosting here is the alignment's error and banding is /// will use, with their gains applied. Ghosting here is the alignment's
/// the gains', which is exactly what the photographer is being asked to /// error and banding is the gains', which is exactly what the photographer
/// look at. Fitted to 1600 px across. /// is being asked to look at. Fitted to 1600 px across.
/// The aligned set on its surface, in colour, as planes: `(w, h, rgb 0..1, /// The aligned set on its surface, in colour, as planes: `(w, h, rgb 0..1,
/// known)`. Display-ish space — the first frame's white balance and matrix, /// known)`. Display-ish space — the first frame's white balance and matrix,
/// a gamma — which is also what the border filler was trained on. /// a gamma — which is also what the border filler was trained on.
#[allow(clippy::too_many_arguments)]
fn preview_planes( fn preview_planes(
colour: &[&[f32]], colour: &[&[f32]],
proxies: &[&Gray], proxies: &[&Gray],
alignment: &Alignment, alignment: &Alignment,
gains: &[f32], gains: &[f32],
seams: Option<(&SeamMap, f64)>,
projection: Projection, projection: Projection,
first: &RawImage, first: &RawImage,
max_width: usize, max_width: usize,
@@ -1264,7 +1322,7 @@ fn preview_planes(
let v = bounds.min_v + (oy as f64 + 0.5) * px; let v = bounds.min_v + (oy as f64 + 0.5) * px;
let d = projection.to_direction(scale, u, v); let d = projection.to_direction(scale, u, v);
let mut sum = [0.0f32; 3]; let mut sum = [0.0f32; 3];
let mut n = 0u32; let mut n = 0.0f32;
for (k, g) in proxies.iter().enumerate() { for (k, g) in proxies.iter().enumerate() {
let Some((x, y)) = cameras.project(k, d) else { let Some((x, y)) = cameras.project(k, d) else {
continue; continue;
@@ -1276,16 +1334,21 @@ fn preview_planes(
let i = (y as usize * g.width + x as usize) * 3; let i = (y as usize * g.width + x as usize) * 3;
let cam = let cam =
grey_if_blown([colour[k][i], colour[k][i + 1], colour[k][i + 2]], look.wb); grey_if_blown([colour[k][i], colour[k][i + 1], colour[k][i + 2]], look.wb);
// The seam's share, as the merge weighs it, with the same
// floor under it; an even average where there is no map.
let w = seams
.and_then(|(m, radius)| m.share(k, u, v, scale, radius))
.map_or(1.0, |s| s + 1e-4);
for c in 0..3 { for c in 0..3 {
sum[c] += cam[c] * gains[k]; sum[c] += cam[c] * gains[k] * w;
} }
n += 1; n += w;
} }
if n == 0 { if n <= 0.0 {
continue; continue;
} }
let o = oy * out_w + ox; let o = oy * out_w + ox;
let d = look.to_display([sum[0] / n as f32, sum[1] / n as f32, sum[2] / n as f32]); let d = look.to_display([sum[0] / n, sum[1] / n, sum[2] / n]);
rgb[o * 3..o * 3 + 3].copy_from_slice(&d); rgb[o * 3..o * 3 + 3].copy_from_slice(&d);
known[o] = true; known[o] = true;
} }
+3
View File
@@ -740,6 +740,9 @@ fn metadata(
[target.image.0 as i64], [target.image.0 as i64],
) )
.map_err(|e| Failure::Other(e.to_string()))?; .map_err(|e| Failure::Other(e.to_string()))?;
// The name, when the header had no date — as the sweep does.
dr_catalog::name_dates::fill(catalog.connection(), Some(&[target.image.0 as i64]))
.map_err(|e| Failure::Other(e.to_string()))?;
} }
Ok(1) Ok(1)
} }
+3 -3
View File
@@ -26,7 +26,7 @@ use jni::strings::JNIStr;
/// Run `body` with the application context ndk_context holds, on whatever /// Run `body` with the application context ndk_context holds, on whatever
/// thread this is. It is a `Context`, not the activity — see /// thread this is. It is a `Context`, not the activity — see
/// `FolderPicker.start` for what that changes. /// `FolderPicker.start` for what that changes.
fn call<T>( pub(crate) fn call<T>(
what: &str, what: &str,
body: impl FnOnce(&mut jni::Env, &JObject) -> jni::errors::Result<T>, body: impl FnOnce(&mut jni::Env, &JObject) -> jni::errors::Result<T>,
) -> Result<T, String> { ) -> Result<T, String> {
@@ -62,7 +62,7 @@ fn call<T>(
/// or the application context behind it) the boot loader defined, and the /// or the application context behind it) the boot loader defined, and the
/// boot loader has never heard of anything in this APK. Loading through it fails with "class not found", /// boot loader has never heard of anything in this APK. Loading through it fails with "class not found",
/// which is what the first build on the tablet did. /// which is what the first build on the tablet did.
fn class<'local>( pub(crate) fn class<'local>(
env: &mut jni::Env<'local>, env: &mut jni::Env<'local>,
activity: &JObject, activity: &JObject,
name: &JNIStr, name: &JNIStr,
@@ -80,7 +80,7 @@ fn class<'local>(
} }
/// A Java string result, or `None` for null. /// A Java string result, or `None` for null.
fn text(env: &mut jni::Env, value: JObject) -> jni::errors::Result<Option<String>> { pub(crate) fn text(env: &mut jni::Env, value: JObject) -> jni::errors::Result<Option<String>> {
if value.is_null() { if value.is_null() {
return Ok(None); return Ok(None);
} }
@@ -0,0 +1,69 @@
// TRACES: FR-UI-5
//! Back closes the presets menu, and the next Back returns to the grid.
//!
//! The menu at the foot of the tool rail is a `PopupWindow`, and showing a
//! popup takes focus off the develop view until it closes. The menu had
//! nothing focusable of its own, so a Back pressed while it was up had no
//! focus item to bubble from, went unanswered, and on Android an unanswered
//! Back is the platform's: it closed the application from develop. Dismissing
//! a menu with the back gesture is the ordinary thing to do, which is why this
//! was seen often.
//!
//! Runs on Slint's testing backend, as `film_list_reaches_every_stock` does.
#![cfg(debug_assertions)]
use std::cell::Cell;
use std::rc::Rc;
use dr_ui::{AppWindow, Develop};
use i_slint_backend_testing::{init_no_event_loop, ElementHandle};
use slint::platform::{Key, PointerEventButton, WindowEvent};
use slint::{ComponentHandle, SharedString};
const MANAGE: &str = "Save or manage…";
fn key(app: &AppWindow, k: Key) {
let text: SharedString = k.into();
app.window()
.dispatch_event(WindowEvent::KeyPressed { text: text.clone() });
app.window()
.dispatch_event(WindowEvent::KeyReleased { text });
}
fn menu_open(app: &AppWindow) -> bool {
ElementHandle::find_by_accessible_label(app, MANAGE)
.next()
.is_some()
}
#[test]
fn back_closes_the_presets_menu_then_leaves_develop() {
init_no_event_loop();
let app = AppWindow::new().expect("the window builds on the testing backend");
app.window().set_size(slint::LogicalSize::new(1600., 1200.));
app.global::<Develop>().set_enabled(true);
// The rail offers presets only with a photograph to apply them to.
app.set_total(3);
let asked = Rc::new(Cell::new(0));
app.on_back_requested({
let asked = asked.clone();
move || {
asked.set(asked.get() + 1);
true
}
});
app.show().unwrap();
ElementHandle::find_by_accessible_label(&app, "Presets")
.next()
.expect("the tool rail's presets entry is on screen")
.mock_single_click(PointerEventButton::Left);
assert!(menu_open(&app), "clicking Presets opens the menu");
key(&app, Key::Back);
assert!(!menu_open(&app), "Back closes the menu");
assert_eq!(asked.get(), 0, "closing the menu is the whole step");
key(&app, Key::Back);
assert_eq!(asked.get(), 1, "the next Back reaches the shell");
}
+59 -17
View File
@@ -569,6 +569,7 @@ export component AppWindow inherits Window {
in property <int> import-volume-selected: -1; in property <int> import-volume-selected: -1;
in property <string> import-card-path: ""; in property <string> import-card-path: "";
in property <bool> import-card-looks-right: false; in property <bool> import-card-looks-right: false;
in property <bool> import-needs-access: false;
in property <bool> import-surveying: false; in property <bool> import-surveying: false;
in property <string> import-survey-summary: ""; in property <string> import-survey-summary: "";
in property <string> import-upload-target: ""; in property <string> import-upload-target: "";
@@ -630,6 +631,7 @@ export component AppWindow inherits Window {
callback import-card-path-changed(string); callback import-card-path-changed(string);
callback import-choose-card(); callback import-choose-card();
callback import-refresh-volumes(); callback import-refresh-volumes();
callback import-grant-access();
callback import-template-changed(string); callback import-template-changed(string);
callback import-mode-picked(int); callback import-mode-picked(int);
callback import-duplicate-picked(int); callback import-duplicate-picked(int);
@@ -1122,6 +1124,7 @@ in property <bool> panel-visible: true;
volume-selected: root.import-volume-selected; volume-selected: root.import-volume-selected;
card-path: root.import-card-path; card-path: root.import-card-path;
card-looks-right: root.import-card-looks-right; card-looks-right: root.import-card-looks-right;
needs-access: root.import-needs-access;
surveying: root.import-surveying; surveying: root.import-surveying;
survey-summary: root.import-survey-summary; survey-summary: root.import-survey-summary;
upload-target: root.import-upload-target; upload-target: root.import-upload-target;
@@ -1145,6 +1148,7 @@ in property <bool> panel-visible: true;
card-path-changed(t) => { root.import-card-path-changed(t); } card-path-changed(t) => { root.import-card-path-changed(t); }
choose-card => { root.import-choose-card(); } choose-card => { root.import-choose-card(); }
refresh-volumes() => { root.import-refresh-volumes(); } refresh-volumes() => { root.import-refresh-volumes(); }
grant-access() => { root.import-grant-access(); }
template-changed(t) => { root.import-template-changed(t); } template-changed(t) => { root.import-template-changed(t); }
mode-picked(i) => { root.import-mode-picked(i); } mode-picked(i) => { root.import-mode-picked(i); }
duplicate-picked(i) => { root.import-duplicate-picked(i); } duplicate-picked(i) => { root.import-duplicate-picked(i); }
@@ -1823,8 +1827,10 @@ in property <bool> panel-visible: true;
clip: true; clip: true;
canvas-image := Image { canvas-image := Image {
width: 100%; x: parent.fit-x;
height: 100%; y: parent.fit-y;
width: parent.fit-w;
height: parent.fit-h;
source: root.canvas; source: root.canvas;
image-fit: contain; image-fit: contain;
// TRACES: FR-UI-4 // TRACES: FR-UI-4
@@ -1872,8 +1878,10 @@ in property <bool> panel-visible: true;
// original straight away, and the last draft of the edit // original straight away, and the last draft of the edit
// fades out over it rather than vanishing. // fades out over it rather than vanishing.
previous-frame := Image { previous-frame := Image {
width: 100%; x: canvas-image.x;
height: 100%; y: canvas-image.y;
width: canvas-image.width;
height: canvas-image.height;
source: root.canvas-previous; source: root.canvas-previous;
image-fit: contain; image-fit: contain;
image-rendering: canvas-image.image-rendering; image-rendering: canvas-image.image-rendering;
@@ -1941,15 +1949,54 @@ in property <bool> panel-visible: true;
// The overlay is placed against *this*, not against the whole // The overlay is placed against *this*, not against the whole
// area — otherwise the crop rect drifts off the picture on any // area — otherwise the crop rect drifts off the picture on any
// window whose shape differs from the image's. // window whose shape differs from the image's.
//
// **While composing, the box is inset and stops above the
// photo roll.** A crop handle straddles the picture's edge,
// half of it outside, and a photograph fitted to the full
// box puts that half under this area's clip — and, along
// the bottom, under the roll's band, whose swipe handler
// takes every press inside it (see `PhotoRoll`). The bottom
// corners were drawn there, lit up, and could not be
// grabbed. Fitting the picture clear of both is the only
// fix: the handler has to be where it is, and moving the
// handles inward would leave them off the corner they
// move.
property <length> roll-band:
Library.library-total > 0
? (root.roll-open
? Theme.roll-strip + Theme.roll-reach
: Theme.roll-reach)
: 0px;
// The roll's own travel, so what stands on it rises with
// the strip rather than jumping ahead of it.
animate roll-band { duration: 180ms; easing: ease-out; }
//
// The floating "Done Composing" row stands on that band,
// and is declared after the crop overlay so it takes a
// press first: a photograph filling the width put the
// bottom-left handle under it. So the reserve is the band,
// the row's 12px margin, and the row's hit height — a
// `Button`'s press area is the touch target, not its ink.
// Every other side keeps half a handle and a finger's
// slop clear of this area's clip.
property <length> fit-inset: Develop.cropping ? 16px : 0px;
property <length> fit-below: Develop.cropping
? self.roll-band + 12px + Theme.touch-target
: 0px;
property <length> fit-x: self.fit-inset;
property <length> fit-y: self.fit-inset;
property <length> fit-w: max(1px, self.width - 2 * self.fit-inset);
property <length> fit-h: max(1px, self.height - 2 * self.fit-inset - self.fit-below);
property <float> src-w: root.canvas.width > 0 ? root.canvas.width : 1; property <float> src-w: root.canvas.width > 0 ? root.canvas.width : 1;
property <float> src-h: root.canvas.height > 0 ? root.canvas.height : 1; property <float> src-h: root.canvas.height > 0 ? root.canvas.height : 1;
property <float> box-w: self.width / 1px; property <float> box-w: self.fit-w / 1px;
property <float> box-h: self.height / 1px; property <float> box-h: self.fit-h / 1px;
property <float> fit-scale: min(self.box-w / self.src-w, self.box-h / self.src-h); property <float> fit-scale: min(self.box-w / self.src-w, self.box-h / self.src-h);
property <length> shown-w: self.src-w * self.fit-scale * 1px; property <length> shown-w: self.src-w * self.fit-scale * 1px;
property <length> shown-h: self.src-h * self.fit-scale * 1px; property <length> shown-h: self.src-h * self.fit-scale * 1px;
property <length> shown-x: (self.width - self.shown-w) / 2; property <length> shown-x: self.fit-x + (self.fit-w - self.shown-w) / 2;
property <length> shown-y: (self.height - self.shown-h) / 2; property <length> shown-y: self.fit-y + (self.fit-h - self.shown-h) / 2;
// Empty and error states say what happened rather than // Empty and error states say what happened rather than
// showing a blank canvas. // showing a blank canvas.
@@ -2904,15 +2951,10 @@ in property <bool> panel-visible: true;
// the thing that could not be reached. They stack // the thing that could not be reached. They stack
// instead — the controls ride on top of the roll's // instead — the controls ride on top of the roll's
// band, at whatever height it currently stands. // band, at whatever height it currently stands.
property <length> roll-clear: // The canvas's measure of the band, animated there
Library.library-total > 0 // with the roll's own travel so these rise with the
? (root.roll-open // strip rather than jumping ahead of it.
? Theme.roll-strip + Theme.roll-reach property <length> roll-clear: canvas-area.roll-band;
: Theme.roll-reach)
: 0px;
// The roll's own travel, so they rise with the strip
// rather than jumping ahead of it.
animate roll-clear { duration: 180ms; easing: ease-out; }
x: 12px; x: 12px;
y: parent.height - self.preferred-height - 12px y: parent.height - self.preferred-height - 12px
+61 -36
View File
@@ -37,15 +37,17 @@ export component CropOverlay inherits Rectangle {
in property <float> crop-w: 1.0; in property <float> crop-w: 1.0;
in property <float> crop-h: 1.0; in property <float> crop-h: 1.0;
/// A dragged crop rect — `x`, `y`, `width`, `height`, then the corner the /// A dragged crop rect — `x`, `y`, `width`, `height`, then the handle the
/// drag is holding as a `0`/`1` pair, or `-1, -1` where the whole rect is /// drag is holding as a point of the rect: a `0`/`1` pair for a corner,
/// being moved and its shape must not be touched. /// `0.5` on the axis an edge does not move, or `-1, -1` where the whole
/// rect is being moved and its shape must not be touched.
/// ///
/// The corner is what an aspect lock needs and cannot infer: reshaping a /// The handle is what an aspect lock needs and cannot infer: reshaping a
/// rect onto a ratio has to know which of its corners is nailed down, and /// rect onto a ratio has to know which point of it is nailed down, and
/// only the handle that took the press knows that. It is reported as the /// only the handle that took the press knows that. It is reported as the
/// held corner rather than as the fixed one because that is what is /// held point rather than as the fixed one because that is what is
/// written here — Rust takes the opposite corner. /// written here — Rust takes the opposite one, which for an edge is the
/// middle of the far side.
callback crop-changed(float, float, float, float, float, float); callback crop-changed(float, float, float, float, float, float);
/// TRACES: FR-DEV-17 /// TRACES: FR-DEV-17
@@ -189,24 +191,43 @@ export component CropOverlay inherits Rectangle {
} }
} }
// Corner handles. Each drags one corner while the opposite // Handles: the four edges, then the four corners.
// stays put, which is the only behaviour that lets a crop //
// be shaped rather than merely moved. // A corner drags one corner while the opposite stays put, which is the
for corner in [ // only behaviour that lets a crop be shaped rather than merely moved. An
// edge drags that one side along the axis across it and leaves the other
// three where they are — the way to trim a strip off one side without
// disturbing the corner you had already placed.
//
// Each is a point of the rect in its own `0..1` coordinates; `0.5` on an
// axis is an edge's midpoint and means "this axis does not move". The
// edges come first because among overlapping siblings the last declared
// takes the press, and on a rect dragged small the corners are the ones
// that must stay reachable.
for handle in [
{ hx: 0.5, hy: 0.0 },
{ hx: 0.5, hy: 1.0 },
{ hx: 0.0, hy: 0.5 },
{ hx: 1.0, hy: 0.5 },
{ hx: 0.0, hy: 0.0 }, { hx: 0.0, hy: 0.0 },
{ hx: 1.0, hy: 0.0 }, { hx: 1.0, hy: 0.0 },
{ hx: 0.0, hy: 1.0 }, { hx: 0.0, hy: 1.0 },
{ hx: 1.0, hy: 1.0 }, { hx: 1.0, hy: 1.0 },
]: Rectangle { ]: Rectangle {
property <length> size: 18px; property <bool> across: handle.hx == 0.5;
x: parent.rx + corner.hx * parent.rw - self.size / 2; property <bool> along: handle.hy == 0.5;
y: parent.ry + corner.hy * parent.rh - self.size / 2; // A corner is a square; an edge is a bar lying along its side, with
width: self.size; // a hit area as long as the bar and as deep as a corner's.
height: self.size; property <length> grip: 18px;
property <length> reach: 36px;
width: self.across ? self.reach : self.grip;
height: self.along ? self.reach : self.grip;
x: parent.rx + handle.hx * parent.rw - self.width / 2;
y: parent.ry + handle.hy * parent.rh - self.height / 2;
Rectangle { Rectangle {
width: 12px; width: parent.across ? 24px : (parent.along ? 5px : 12px);
height: 12px; height: parent.along ? 24px : (parent.across ? 5px : 12px);
background: #ffffff; background: #ffffff;
border-radius: 2px; border-radius: 2px;
} }
@@ -214,9 +235,13 @@ export component CropOverlay inherits Rectangle {
TouchArea { TouchArea {
width: 100%; width: 100%;
height: 100%; height: 100%;
mouse-cursor: (corner.hx == corner.hy) mouse-cursor: parent.across
? MouseCursor.nwse-resize ? MouseCursor.ns-resize
: MouseCursor.nesw-resize; : parent.along
? MouseCursor.ew-resize
: (handle.hx == handle.hy)
? MouseCursor.nwse-resize
: MouseCursor.nesw-resize;
property <float> ox; property <float> ox;
property <float> oy; property <float> oy;
@@ -246,27 +271,27 @@ export component CropOverlay inherits Rectangle {
} }
} }
// Movement as a fraction of the frame, live while // Movement as a fraction of the frame, live while the handle is
// the handle is held. // held — and nothing along an axis the handle does not move, so
property <float> dx: self.fraction-x(self.mouse-x) - self.from-x; // an edge dragged at a slant still only moves its own side.
property <float> dy: self.fraction-y(self.mouse-y) - self.from-y; property <float> dx: parent.across ? 0 : self.fraction-x(self.mouse-x) - self.from-x;
property <float> dy: parent.along ? 0 : self.fraction-y(self.mouse-y) - self.from-y;
moved => { moved => {
if (!self.pressed) { if (!self.pressed) {
return; return;
} }
// Dragging a left/top handle moves the origin // Dragging a left/top handle moves the origin and shrinks the
// and shrinks the extent by the same amount; // extent by the same amount; a right/bottom handle moves only
// a right/bottom handle moves only the extent. // the extent. Rust clamps the result, so an over-drag slides
// Rust clamps the result, so an over-drag // rather than inverting.
// slides rather than inverting.
root.crop-changed( root.crop-changed(
corner.hx == 0 ? self.ox + self.dx : self.ox, handle.hx == 0 ? self.ox + self.dx : self.ox,
corner.hy == 0 ? self.oy + self.dy : self.oy, handle.hy == 0 ? self.oy + self.dy : self.oy,
corner.hx == 0 ? self.ow - self.dx : self.ow + self.dx, handle.hx == 0 ? self.ow - self.dx : self.ow + self.dx,
corner.hy == 0 ? self.oh - self.dy : self.oh + self.dy, handle.hy == 0 ? self.oh - self.dy : self.oh + self.dy,
corner.hx, handle.hx,
corner.hy, handle.hy,
); );
} }
} }
+24 -2
View File
@@ -75,12 +75,17 @@ export component ImportPage inherits Rectangle {
/// Whether the source holds a DCIM folder. Advisory: plenty of legitimate /// Whether the source holds a DCIM folder. Advisory: plenty of legitimate
/// sources do not, so this informs and never blocks. /// sources do not, so this informs and never blocks.
in property <bool> card-looks-right: false; in property <bool> card-looks-right: false;
/// Android: the app may not read a card until the user allows "all files
/// access", which is a switch in the system settings, not a dialog.
in property <bool> needs-access: false;
callback volume-picked(int); callback volume-picked(int);
callback card-path-changed(string); callback card-path-changed(string);
/// Browse for the source with the platform's dialogue. /// Browse for the source with the platform's dialogue.
callback choose-card(); callback choose-card();
callback refresh-volumes(); callback refresh-volumes();
/// Open the system page where that switch is.
callback grant-access();
// --- what is on it --------------------------------------------------- // --- what is on it ---------------------------------------------------
in property <bool> surveying: false; in property <bool> surveying: false;
@@ -222,10 +227,27 @@ export component ImportPage inherits Rectangle {
Panel { Panel {
PanelHeading { text: "From"; } PanelHeading { text: "From"; }
if root.volume-labels.length == 0: Caption { // Android, before the grant. Said once, with the one
// control that fixes it, instead of an empty list that
// would read as "no card inserted".
if root.needs-access: Caption {
text: "To read a camera card, DarkRoom needs \"All files access\". Allow it on the next screen, then come back here.";
wrap: word-wrap;
}
if root.needs-access: HorizontalLayout {
Button {
text: "Allow access";
primary: true;
enabled: !root.running;
clicked => { root.grant-access(); }
}
Rectangle { horizontal-stretch: 1; }
}
if !root.needs-access && root.volume-labels.length == 0: Caption {
text: Pickers.local-paths text: Pickers.local-paths
? "No removable volume found. Browse to where the card is mounted, or plug it in and refresh." ? "No removable volume found. Browse to where the card is mounted, or plug it in and refresh."
: "No removable volume found. Type where the card is mounted, or plug it in and refresh."; : "No SD card or card reader found. Insert one and press Refresh.";
wrap: word-wrap; wrap: word-wrap;
} }
+25
View File
@@ -55,6 +55,7 @@ import { Icon } from "icons.slint";
import { ViewMode } from "session.slint"; import { ViewMode } from "session.slint";
import { PresetRow, PresetOrigin, PresetFolderRow } from "presets.slint"; import { PresetRow, PresetOrigin, PresetFolderRow } from "presets.slint";
import { Label, ScrollBar } from "widgets.slint"; import { Label, ScrollBar } from "widgets.slint";
import { Keys } from "keys.slint";
// One tool. A struct rather than four parallel arrays so a row cannot be // One tool. A struct rather than four parallel arrays so a row cannot be
// half-added — the compiler will not let a new entry omit its icon. // half-added — the compiler will not let a new entry omit its icon.
@@ -522,6 +523,30 @@ export component ToolRail inherits Rectangle {
root.height - Theme.gap); root.height - Theme.gap);
close-policy: PopupClosePolicy.close-on-click-outside; close-policy: PopupClosePolicy.close-on-click-outside;
// Somewhere for Back to start from while the menu is up.
//
// A popup is its own focus tree: showing it takes focus off the
// develop view, and Slint hands it back only when the popup
// closes. With nothing focusable in here, Android's Back gesture
// — the natural way to dismiss a menu — found no focus item,
// went unanswered, and the platform closed the application.
// Slint closes a popup on Escape by itself but knows nothing of
// Back, so both are answered here, as the film list does.
FocusScope {
width: 0px;
height: 0px;
init => { self.focus(); }
// KEYMAP: Develop
key-pressed(event) => {
if (Keys.chord(event) == "Escape" || Keys.chord(event) == "Back") {
preset-menu.close();
return accept;
}
return reject;
}
}
Rectangle { Rectangle {
background: Theme.surface; background: Theme.surface;
border-radius: Theme.radius; border-radius: Theme.radius;