mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge main into fix/red-eye-outside-selection-silent-13096
This commit is contained in:
commit
d74a2937bd
1707 files changed
+91948
-36873
No files matched your search
+2526
-2183
File diff suppressed because it is too large.
Load diff
+45
-6
@@ -21,11 +21,24 @@ nextest-version = "0.9.150"
|
||||
# parallelism.
|
||||
[test-groups]
|
||||
gpu = { max-threads = 4 }
|
||||
# mcp_wait builds a 6000x6000 document and a radius-1000 Gaussian Blur so the
|
||||
# waited command runs long enough to cancel. On the artcraft k8s gate pods that
|
||||
# often fails with "not enough working memory" when it shares the shard with
|
||||
# the rest of the suite; hosted ubuntu-24.04 stays green. A bridged jobs.list
|
||||
# poll can also miss its 300ms test timeout under that load (run 45136461883).
|
||||
# Run these alone: the group caps them at one, and threads-required keeps the
|
||||
# rest of the shard off the machine while they run.
|
||||
heavy-filter = { max-threads = 1 }
|
||||
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(photocraft-gpu) | test(/(^|::|_)gpu_tests::/)'
|
||||
test-group = 'gpu'
|
||||
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(photocraft-automation) & test(/^mcp_wait::/)'
|
||||
test-group = 'heavy-filter'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
# CI (`--profile ci`, .github/workflows/ci.yml). Collect all failures in one integration run
|
||||
# instead of exposing one regression per rebuild. A hanging test still terminates, and every
|
||||
# failure is repeated at the end of the log. The default profile's GPU override still applies.
|
||||
@@ -43,6 +56,23 @@ archive.include = [
|
||||
{ path = "gate-shards.json", relative-to = "target", depth = 0, on-missing = "ignore" },
|
||||
]
|
||||
|
||||
# panic_hunt drives every command with adversarial parameters and exists to find hangs, so a hang
|
||||
# must cost seconds, not the profile's 10 minutes. Hosted ubuntu-24.04 is about 18 s and Windows
|
||||
# about 26 s. On artcraft-k8s-main it is typically 31-33 s, and under memory pressure it has
|
||||
# timed out at 45 s after nearly finishing the registry (run 45127595159). The first slow
|
||||
# warning still comes at 15 s; a run past 90 s is terminated.
|
||||
[[profile.ci.overrides]]
|
||||
filter = 'binary(panic_hunt)'
|
||||
slow-timeout = { period = "15s", terminate-after = 6 }
|
||||
|
||||
# Content-Aware Move solves on rayon across every core. On the Windows runner the GPU tests draw
|
||||
# on the CPU-backed adapter, so two of these beside a GPU test starve it until its device poll
|
||||
# times out. Each runs alone there.
|
||||
[[profile.ci.overrides]]
|
||||
platform = 'cfg(target_os = "windows")'
|
||||
filter = '(package(photocraft-engine-core) | package(photocraft-engine-paint) | package(photocraft-engine)) & test(/content_aware_move/)'
|
||||
threads-required = "num-test-threads"
|
||||
|
||||
# Keep phase timings for the remaining expensive Windows GPU regressions visible. This does
|
||||
# not relax their timeout, isolate failures differently or remove any test cases.
|
||||
# Page eviction and budget borrowing redraw multi-effect documents. On the Windows
|
||||
@@ -62,6 +92,15 @@ success-output = "immediate"
|
||||
# All cases and the 60-second warning remain unchanged.
|
||||
threads-required = 2
|
||||
|
||||
# The slowest UI GPU tests start together (priority below) and redraw the whole app per frame on
|
||||
# the Windows software GPU. Four at once starve one frame past egui_kittest's 10-second device
|
||||
# poll (`PollError: ... Wait timed out`, live_stroke_canvas part_0, twice in a row in #16529).
|
||||
# Two slots each keep at most two of them on the adapter at a time; no case or timeout changes.
|
||||
[[profile.ci.overrides]]
|
||||
platform = 'cfg(target_os = "windows")'
|
||||
filter = 'package(photocraft-ui-egui) & test(/gpu_tests::(live_stroke_canvas::the_canvas_shows_the_committed_stroke_part_|checker_canvas::pixel_grid_is_solid_and_visible_|full_res_preview::)/)'
|
||||
threads-required = 2
|
||||
|
||||
# Slowest tests start first. nextest starts higher-priority tests first, so a long test no longer
|
||||
# begins at the end of the run and extends the job. Every test that took over 60 s on the Windows
|
||||
# runner in the cold run of #15474 (unit and integration legs); the same tests are the slowest on
|
||||
@@ -82,23 +121,23 @@ priority = 100
|
||||
# 60 to 200 s
|
||||
filter = '''
|
||||
(package(photocraft-gpu) & test(=camera_raw::clarity_texture_and_dehaze_with_shadows_highlights_and_per_pixel_stages)) |
|
||||
(package(photocraft-engine) & test(=cmd::retouch_cmds::content_aware_move::tests::a_coarse_preview_keeps_a_faint_sparse_selection)) |
|
||||
(package(photocraft-engine-paint) & test(=cmd::retouch_cmds::content_aware_move::tests::a_coarse_preview_keeps_a_faint_sparse_selection)) |
|
||||
(package(photocraft-engine) & test(=crop_content_aware_layers::unmeasured_active_targets_and_delete_off_keep_the_legacy_target)) |
|
||||
(package(photocraft-engine) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_flat_patch_matches_the_new_surroundings_at_color_ten)) |
|
||||
(package(photocraft-engine-paint) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_flat_patch_matches_the_new_surroundings_at_color_ten)) |
|
||||
(package(photocraft-ui-egui) & test(=tools::type_tool::canvas_tests::every_paragraph_box_handle_resizes_the_box_with_snapping_on)) |
|
||||
(package(photocraft-ui-egui) & test(=gpu_tests::checker_canvas::pixel_grid_is_solid_and_visible_gpu_2x)) |
|
||||
(package(photocraft-engine) & test(=cmd::retouch_cmds::tests::content_aware_move_coarse_preview_handles_transform_extend_and_limits)) |
|
||||
(package(photocraft-engine-paint) & test(=cmd::retouch_cmds::tests::content_aware_move_coarse_preview_handles_transform_extend_and_limits)) |
|
||||
(package(photocraft-ui-egui) & test(=gpu_tests::checker_canvas::pixel_grid_is_solid_and_visible_cpu_2x)) |
|
||||
(package(photocraft-ui-egui) & test(=gpu_tests::drag_preview_canvas::marquee_previews_show_while_dragging_on_white_and_black_at_1x_and_2x)) |
|
||||
(package(photocraft-gpu) & test(=camera_raw::shadows_and_highlights_with_per_pixel_stages)) |
|
||||
(package(photocraft-engine) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_brightness_change_shifts_the_middle_only_past_color_five)) |
|
||||
(package(photocraft-engine) & test(=cmd::retouch_cmds::tests::content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths)) |
|
||||
(package(photocraft-engine-paint) & test(=cmd::retouch_cmds::content_aware_move::color_tests::a_brightness_change_shifts_the_middle_only_past_color_five)) |
|
||||
(package(photocraft-engine-paint) & test(=cmd::retouch_cmds::tests::content_aware_move_previews_large_selections_coarse_then_exact_at_all_depths)) |
|
||||
(package(photocraft-ui-egui) & test(=gpu_tests::live_stroke_canvas::live_tool_camera_navigation_is_visible_in_the_input_frame)) |
|
||||
(package(photocraft-ui-egui) & test(=gpu_tests::live_stroke_canvas::the_canvas_shows_the_committed_stroke_part_0)) |
|
||||
(package(photocraft-ui-egui) & test(=gpu_tests::full_res_preview::adjustment_layer_drag_previews_at_full_resolution_when_low_res_is_off)) |
|
||||
(package(photocraft-ui-egui) & test(=input::hold_keys::tests::cmd_gives_the_move_tool_only_where_the_tool_does_not_take_cmd)) |
|
||||
(package(photocraft-ui-egui) & test(=guide_cursor_tests::command_over_a_guide_takes_it_where_command_is_the_move_tool)) |
|
||||
(package(photocraft-gpu) & test(=parity::documents_larger_than_the_texture_limit)) |
|
||||
(package(photocraft-engine) & test(=cmd::retouch_cmds::content_aware_move::tests::a_preview_within_the_full_resolution_budget_is_the_plain_solve_bit_for_bit))
|
||||
(package(photocraft-engine-paint) & test(=cmd::retouch_cmds::content_aware_move::tests::a_preview_within_the_full_resolution_budget_is_the_plain_solve_bit_for_bit))
|
||||
'''
|
||||
priority = 50
|
||||
@@ -2,3 +2,10 @@
|
||||
self-hosted-runner:
|
||||
labels:
|
||||
- macos-release # org larger runner (M2 Pro), used by release.yml
|
||||
|
||||
# actionlint 1.7.12 predates GitHub's queue key. Only this exact false positive is
|
||||
# suppressed; Packaging lint's independent source-contract job enforces the values.
|
||||
paths:
|
||||
.github/workflows/nightly-sign.yml:
|
||||
ignore:
|
||||
- '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$'
|
||||
@@ -0,0 +1,16 @@
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
mDMEaulK1xYJKwYBBAHaRw8BAQdAqHJeDCjY6Hx5FTn/hW+aqu6V394ubLk0Zj3C
|
||||
bftDwFm0IkFydENyYWZ0IExpbnV4IFJlbGVhc2UgU2lnbmluZyBLZXmIkwQTFgoA
|
||||
OxYhBCt2dBtBSq1s0z5jEhOgBcC518PtBQJq6UrXAhsBBQsJCAcCAiICBhUKCQgL
|
||||
AgQWAgMBAh4HAheAAAoJEBOgBcC518PtGeUA/RjvULBTLlccc+2wtJkfjSnCV+cf
|
||||
PUMEGmW7XkZWkk51AP9w2A/WLv+79nREWEpZzI8LGK5EjrNazP+sY0l7j5rFCLgz
|
||||
BGrpStcWCSsGAQQB2kcPAQEHQPl7XkQ1gWsvSPf/T9b4m/UHcjJjBpSOtpYlWR56
|
||||
er5RiO8EGBYKACAWIQQrdnQbQUqtbNM+YxIToAXAudfD7QUCaulK1wIbAgCBCRAT
|
||||
oAXAudfD7XYgBBkWCgAdFiEEVo3B9o+Prsx5fzx7AG2va7DvM04FAmrpStcACgkQ
|
||||
AG2va7DvM07taQEA4d2VFkKRIP0g9TrE86KpnuXPap+LKqe0tfIxpdf9YxIA/0Wo
|
||||
9H/iG8nH++nxC087p3HE0S+0UovxqkhXJLSr8B4JDOoA/iLRpqTdYmk6fVXMyPJo
|
||||
SkOVuwZIGS6VgBdSQP0e2P2YAP41L5OoSvwdQIG3/uNrM+ieqpYeM597/hCLFs5A
|
||||
ga/qCA==
|
||||
=3wGQ
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
@@ -0,0 +1,318 @@
|
||||
{
|
||||
"schema": "craft-nightly-release-policy/v3",
|
||||
"repository": "storytold/photocraft",
|
||||
"repository_id": 1398080271,
|
||||
"producer_workflow_id": 428462603,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "8389cad8b849ea6bdb5e15fbce16772c3457565a",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "8389cad8b849ea6bdb5e15fbce16772c3457565a",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
"dylanmtaylor",
|
||||
"echelon",
|
||||
"FredApps",
|
||||
"skylartaylor"
|
||||
],
|
||||
"max_age_seconds": 86400,
|
||||
"candidate_policy": {
|
||||
"schema": "craft-nightly-candidate-policy/v3",
|
||||
"epoch": "photocraft-nightly-20261124-sonar-19880b44",
|
||||
"repository": "storytold/photocraft",
|
||||
"branch": "main",
|
||||
"required_workflows": [
|
||||
{
|
||||
"workflow_id": 371199934,
|
||||
"workflow_path": ".github/workflows/ci.yml",
|
||||
"jobs": [
|
||||
{
|
||||
"name": "gate / build (artcraft-k8s-main)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / lint (artcraft-k8s-main)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 1/4 (artcraft-k8s-main)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 2/4 (artcraft-k8s-main)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 3/4 (artcraft-k8s-main)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / test 4/4 (artcraft-k8s-main)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "gate / gate (artcraft-k8s-main)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "windows / build (windows-latest)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "windows / lint (windows-latest)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "windows / test 1/6 (windows-latest)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "windows / test 2/6 (windows-latest)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "windows / test 3/6 (windows-latest)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "windows / test 4/6 (windows-latest)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "windows / test 5/6 (windows-latest)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "windows / test 6/6 (windows-latest)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "windows / gate (windows-latest)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "test (without heif)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "web build and wasm size gate",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
},
|
||||
{
|
||||
"name": "git-sources / Git dependencies come from storytold",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"sonar": {
|
||||
"organization": "storytold",
|
||||
"project": "storytold_photocraft",
|
||||
"app_id": 12526,
|
||||
"check_name": "SonarCloud Code Analysis",
|
||||
"details_url": "https://sonarcloud.io/dashboard?id=storytold_photocraft&branch=main",
|
||||
"issue_types": [
|
||||
"VULNERABILITY"
|
||||
],
|
||||
"accepted_conditions": [
|
||||
{
|
||||
"metric": "new_security_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1",
|
||||
"maximum": "5"
|
||||
}
|
||||
],
|
||||
"required_conditions": [
|
||||
{
|
||||
"metric": "new_reliability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_maintainability_rating",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "1"
|
||||
},
|
||||
{
|
||||
"metric": "new_coverage",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "80"
|
||||
},
|
||||
{
|
||||
"metric": "new_duplicated_lines_density",
|
||||
"comparator": "GT",
|
||||
"error_threshold": "3"
|
||||
},
|
||||
{
|
||||
"metric": "new_security_hotspots_reviewed",
|
||||
"comparator": "LT",
|
||||
"error_threshold": "100"
|
||||
}
|
||||
],
|
||||
"debt": [
|
||||
{
|
||||
"key": "AaH1WeAcw8X7W_XJjFL4",
|
||||
"rule": "pythonsecurity:S8705",
|
||||
"component": "storytold_photocraft:scripts/engine_split/table_fragments.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "ea661b416fc9e77cc01a1cd666c7aba7"
|
||||
},
|
||||
{
|
||||
"key": "AaH2gwW4UgvRZIAygJFb",
|
||||
"rule": "pythonsecurity:S8705",
|
||||
"component": "storytold_photocraft:scripts/engine_split/install_tables.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "487390be64dd83ce33912f980c863775"
|
||||
},
|
||||
{
|
||||
"key": "AaH2uKhnARfBzs_vH5to",
|
||||
"rule": "pythonsecurity:S2083",
|
||||
"component": "storytold_photocraft:scripts/ci-test-times.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "BLOCKER",
|
||||
"hash": "49be67b6e92adfd1925fe265def3f32f"
|
||||
},
|
||||
{
|
||||
"key": "AaH2uKhnARfBzs_vH5tp",
|
||||
"rule": "pythonsecurity:S8705",
|
||||
"component": "storytold_photocraft:scripts/ci-test-times.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "6a6738fcb83ed1ea94deed5a43a29fd7"
|
||||
},
|
||||
{
|
||||
"key": "AaHqp1duL-O9RuIeaDi5",
|
||||
"rule": "pythonsecurity:S8705",
|
||||
"component": "storytold_photocraft:scripts/ci-windows-gpu-tests.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "10901e814d7d4924eaa841ec13d856aa"
|
||||
},
|
||||
{
|
||||
"key": "AaHw0Xe3UBxgr8mqv_tO",
|
||||
"rule": "pythonsecurity:S8705",
|
||||
"component": "storytold_photocraft:scripts/ci-gpu-lavapipe.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "cfd2441d77cd3d2583f62e26cd1693e0"
|
||||
},
|
||||
{
|
||||
"key": "AaIFcrPcNZCHnXHFAj7e",
|
||||
"rule": "pythonsecurity:S8705",
|
||||
"component": "storytold_photocraft:scripts/engine_split/rust_source.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "487390be64dd83ce33912f980c863775"
|
||||
},
|
||||
{
|
||||
"key": "AaIHa6n2yYr6oFqv42Kk",
|
||||
"rule": "pythonsecurity:S8705",
|
||||
"component": "storytold_photocraft:scripts/engine_split/rust_source.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "ccba4e415c24601f3c90259cda892a5f"
|
||||
},
|
||||
{
|
||||
"key": "AaIKwgPdp41A3KPnYjkm",
|
||||
"rule": "pythonsecurity:S8707",
|
||||
"component": "storytold_photocraft:scripts/engine_split/rust_source.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "1e3597d53ca2697cd24474f23f3dd9df"
|
||||
},
|
||||
{
|
||||
"key": "AaIKwgSHp41A3KPnYjkn",
|
||||
"rule": "pythonsecurity:S8707",
|
||||
"component": "storytold_photocraft:scripts/engine_split/engine_cut.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "8d5b0e969b98008acf17068d5f1f7f29"
|
||||
},
|
||||
{
|
||||
"key": "AaIKwgSHp41A3KPnYjko",
|
||||
"rule": "pythonsecurity:S8707",
|
||||
"component": "storytold_photocraft:scripts/engine_split/engine_cut.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "8d5b0e969b98008acf17068d5f1f7f29"
|
||||
},
|
||||
{
|
||||
"key": "AaIKwgSHp41A3KPnYjkp",
|
||||
"rule": "pythonsecurity:S8707",
|
||||
"component": "storytold_photocraft:scripts/engine_split/engine_cut.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "652c184165d354f1c10afab33097fd11"
|
||||
},
|
||||
{
|
||||
"key": "AaIKwgSHp41A3KPnYjkq",
|
||||
"rule": "pythonsecurity:S8707",
|
||||
"component": "storytold_photocraft:scripts/engine_split/engine_cut.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "2dc7df4b6ee7f1302d680852231f2836"
|
||||
},
|
||||
{
|
||||
"key": "AaIKwgSRp41A3KPnYjkw",
|
||||
"rule": "pythonsecurity:S8707",
|
||||
"component": "storytold_photocraft:scripts/engine_split/move_tests.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "ff32a731f85beee97a8bf8c7b1ccaa92"
|
||||
},
|
||||
{
|
||||
"key": "AaIKwgSRp41A3KPnYjkx",
|
||||
"rule": "pythonsecurity:S8707",
|
||||
"component": "storytold_photocraft:scripts/engine_split/move_tests.py",
|
||||
"type": "VULNERABILITY",
|
||||
"severity": "MAJOR",
|
||||
"hash": "d6d2642646179ec403ab491e0cbcd899"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"max_artifact_bytes": 2147483648,
|
||||
"automatic_signer_actors": [],
|
||||
"platforms": {
|
||||
"windows-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
|
||||
"trust": {
|
||||
"publisher_subject": "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"
|
||||
}
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
"trust": {
|
||||
"apple_team_id": "DJ6XS33FX8"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ jobs:
|
||||
# A fork's pull request from a branch named main also matches `branches`.
|
||||
if: github.event.workflow_run.event != 'pull_request'
|
||||
timeout-minutes: 10
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-24.04' }}
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
|
||||
+140
-75
@@ -2,7 +2,7 @@ name: CI
|
||||
|
||||
# Quality gates for every push to main and every pull request. The Linux and Windows tests run
|
||||
# through the suite's shared gate workflow in craft-common-actions (`cargo xtask ci`, split over the
|
||||
# gate's jobs); the test variant and the corpus, web and fuzz jobs are PhotoCraft's own. Every night
|
||||
# gate's jobs); the test variant, web and fuzz jobs are PhotoCraft's own. Every night
|
||||
# the Linux gate alone runs a cold build: the safety net for the workspace crates it keeps between
|
||||
# runs (`cache-workspace-crates`), and a fresh start for that cache entry.
|
||||
on:
|
||||
@@ -16,7 +16,7 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
full_sweep:
|
||||
description: "Run every testkit sweep case (runtime comparison and integration validation)"
|
||||
description: "Run every testkit sweep case and every corpus file, as the nightly run does (runtime comparison and integration validation)"
|
||||
type: boolean
|
||||
default: false
|
||||
color_range:
|
||||
@@ -58,7 +58,9 @@ permissions:
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: 1
|
||||
PHOTOCRAFT_FULL_SWEEP: ${{ inputs.full_sweep && '1' || '0' }}
|
||||
# Every case of the long test sweeps and every corpus file (photocraft-testkit `full_sweep`): the
|
||||
# nightly run and manual runs with `full_sweep`. Other runs take a sweep part and the corpus samples.
|
||||
PHOTOCRAFT_FULL_SWEEP: ${{ (inputs.full_sweep || github.event_name == 'schedule') && '1' || '0' }}
|
||||
# No test or fuzz run may print a page: the engine refuses to spool, and if something ever
|
||||
# bypasses that, lp fails loudly on a printer that does not exist.
|
||||
PHOTOCRAFT_NO_PRINT: "1"
|
||||
@@ -87,17 +89,20 @@ jobs:
|
||||
# Pull requests run them only when they change the GPU crate, a workspace crate it builds on, any
|
||||
# package manifest, or a file outside the workspace packages other than documentation
|
||||
# (scripts/ci-windows-gpu-tests.py, #15247); the Linux gate runs them on every pull request, and main runs them on Windows too.
|
||||
# `linux_skip`: the packages the Linux gate leaves out of its test build because nothing a pull request changes
|
||||
# reaches them (same rule, every package but photocraft-gpu); empty on main, the nightly run and `full-ci`.
|
||||
# `windows_skip`: the platform-neutral packages whose Windows tests a pull request skips because nothing it
|
||||
# changes reaches them (same script); empty on main and `full-ci`.
|
||||
platforms:
|
||||
if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci')
|
||||
timeout-minutes: 10
|
||||
name: select platforms
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }}
|
||||
outputs:
|
||||
windows: ${{ steps.pick.outputs.windows }}
|
||||
windows_gpu: ${{ steps.pick.outputs.windows_gpu }}
|
||||
windows_skip: ${{ steps.pick.outputs.windows_skip }}
|
||||
linux_skip: ${{ steps.pick.outputs.linux_skip }}
|
||||
web: ${{ steps.pick.outputs.web }}
|
||||
steps:
|
||||
- name: Harden runner
|
||||
@@ -119,6 +124,7 @@ jobs:
|
||||
echo "windows=true"
|
||||
echo "windows_gpu=true"
|
||||
echo "windows_skip="
|
||||
echo "linux_skip="
|
||||
echo "web=true"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
@@ -142,6 +148,11 @@ jobs:
|
||||
if [ "$gpu" = false ]; then
|
||||
echo "::notice::photocraft-gpu's tests are skipped on Windows: this pull request changes nothing they are built from (the Linux gate still runs them)."
|
||||
fi
|
||||
linux_skip=$(python3 scripts/ci-windows-gpu-tests.py --skip-linux "$BASE")
|
||||
echo "linux_skip=$linux_skip" >> "$GITHUB_OUTPUT"
|
||||
if [ -n "$linux_skip" ]; then
|
||||
echo "::notice::Tests of packages the pull request does not reach are skipped on Linux (main runs them all): $linux_skip"
|
||||
fi
|
||||
skip=$(python3 scripts/ci-windows-gpu-tests.py --skip-neutral "$BASE")
|
||||
echo "windows_skip=$skip" >> "$GITHUB_OUTPUT"
|
||||
if [ -n "$skip" ]; then
|
||||
@@ -163,10 +174,17 @@ jobs:
|
||||
# the newest one. The lint legs keep no cache (`lint-cache: false`): a cold lint leg costs
|
||||
# minutes, and their entries (~1 GB per OS) would not fit the 10 GB cache budget.
|
||||
gate:
|
||||
if: github.event.action != 'labeled' || github.event.label.name == 'full-ci'
|
||||
# `platforms` is skipped on the nightly run, which tests everything. When it fails, its outputs
|
||||
# are empty (`linux_skip` included), so the gate still runs and tests everything.
|
||||
needs: platforms
|
||||
if: ${{ !cancelled() && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') }}
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
os: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && '["artcraft-k8s-main"]' || '["ubuntu-24.04"]' }}
|
||||
# On the cluster runners sccache uses the shared cluster cache, which main runs fill for
|
||||
# every app; PR runs on hosted runners can't reach it, so they leave it off.
|
||||
sccache: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' }}
|
||||
# egui/winit/rfd.
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
@@ -174,16 +192,20 @@ jobs:
|
||||
# The tests build with the optional craft-fonts input (crates/text/build.rs), so the
|
||||
# Japanese font tests that skip without it run. Same commit as release.yml.
|
||||
craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
|
||||
# Every .rs file is reached by a mod, #[path] or include!; a new unreached file fails the lint leg.
|
||||
unreached-rs-mode: strict
|
||||
# CI test binaries carry no debuginfo and no symbols (CARGO_PROFILE_TEST_STRIP below): a
|
||||
# test build drops from ~19 to ~6.5 GB. A panic still names its file and line; only
|
||||
# backtrace frames lose names and lines. Local builds keep Cargo.toml's line tables.
|
||||
dev-debug: "0"
|
||||
cache-version: v2
|
||||
env: |
|
||||
PHOTOCRAFT_FULL_SWEEP=${{ inputs.full_sweep && '1' || '0' }}
|
||||
PHOTOCRAFT_FULL_SWEEP=${{ (inputs.full_sweep || github.event_name == 'schedule') && '1' || '0' }}
|
||||
PHOTOCRAFT_NO_PRINT=1
|
||||
LPDEST=photocraft-no-such-printer
|
||||
CARGO_PROFILE_TEST_STRIP=symbols
|
||||
PHOTOCRAFT_CI_EXCLUDE=${{ needs.platforms.outputs.linux_skip }}
|
||||
PHOTOCRAFT_CORPUS_TESTS=1
|
||||
timeout-minutes: 100
|
||||
cache-workspace-crates: true
|
||||
lint-cache: false
|
||||
@@ -191,7 +213,7 @@ jobs:
|
||||
# fmt, egui-fork, clippy, layers, panel-commands, scorecard, the wasm32 check and the
|
||||
# missing-translations report (`cargo xtask ci lint`, xtask/src/main.rs), and the CI scripts'
|
||||
# own tests.
|
||||
lint-command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && python3 scripts/test-ci-test-times.py && cargo xtask ci lint
|
||||
lint-command: python3 scripts/test-ci-gpu-lavapipe.py && python3 scripts/test-ci-windows-gpu-tests.py && python3 scripts/test-ci-test-times.py && python3 scripts/test-ci-toolchain-bump.py && python3 scripts/test-ci-clear-rolling-cache.py && cargo xtask ci lint
|
||||
archive-command: cargo xtask-gate archive --gpu-shard
|
||||
after-archive-command: cargo xtask-gate doctest
|
||||
test-shards: 4
|
||||
@@ -234,7 +256,7 @@ jobs:
|
||||
# identical-code folding and PDBs; the link arguments in build.rs (/DELAYLOAD, delayimp.lib)
|
||||
# are lld-link options too.
|
||||
env: |
|
||||
PHOTOCRAFT_FULL_SWEEP=${{ inputs.full_sweep && '1' || '0' }}
|
||||
PHOTOCRAFT_FULL_SWEEP=${{ (inputs.full_sweep || github.event_name == 'schedule') && '1' || '0' }}
|
||||
PHOTOCRAFT_NO_PRINT=1
|
||||
LPDEST=photocraft-no-such-printer
|
||||
CARGO_TARGET_DIR=D:\t
|
||||
@@ -253,7 +275,7 @@ jobs:
|
||||
# budget and GitHub never evicts an entry a run still needs (an evicted Windows entry makes the
|
||||
# Windows build cold, about 60 instead of 21 minutes). It runs beside the run's jobs and prunes
|
||||
# each time a job that saves an entry finishes: the gate's build jobs (the Linux rolling entry,
|
||||
# about 4 GB, and the Windows dependency entry), web and corpus. A skipped job is listed under its
|
||||
# about 4 GB, and the Windows dependency entry) and web. A skipped job is listed under its
|
||||
# own name (a skipped reusable-workflow call under the caller job's), so a run that skips one
|
||||
# still ends. No `needs`: the gate is one reusable call, and waiting for it would leave the
|
||||
# replaced entry in place until every shard has run. A failed prune warns instead of failing the
|
||||
@@ -264,7 +286,7 @@ jobs:
|
||||
# A cold Windows build takes about an hour, and the watch ends when it does; `watch-minutes`
|
||||
# ends it before this limit.
|
||||
timeout-minutes: 120
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-24.04' }}
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
@@ -278,12 +300,35 @@ jobs:
|
||||
with:
|
||||
watch: true
|
||||
watch-minutes: 110
|
||||
content-keys: corpus
|
||||
saving-jobs: |
|
||||
^gate( / build \(.*\))?$
|
||||
^windows( / build \(.*\))?$
|
||||
^web build and wasm size gate$
|
||||
^corpus tests$
|
||||
|
||||
# The nightly cold run never restores the rolling crates entry, so the old entry is only overlap
|
||||
# while the cold run saves its own: two entries of about 4 GB, which with the others go over the
|
||||
# 10 GB cache limit and get the Windows, web and corpus entries evicted. This deletes the old
|
||||
# entries when the build job starts saving (scripts/ci-clear-rolling-cache.py).
|
||||
cold-cache-clear:
|
||||
name: cold cache clear
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 110
|
||||
continue-on-error: true
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Delete the old rolling entries before the save
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: python3 scripts/ci-clear-rolling-cache.py
|
||||
|
||||
# The same codecs without the optional decoder: HEIC must stay a clear "not in this build" error
|
||||
# for distributors who leave it out. Runs beside the gate and restores the gate's newest rolling
|
||||
@@ -295,7 +340,7 @@ jobs:
|
||||
timeout-minutes: 60
|
||||
name: test (without heif)
|
||||
# The gate's runner: its cache entry is keyed on the OS.
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-24.04' }}
|
||||
env:
|
||||
# The gate sets these; rust-cache hashes CARGO_* and RUST* variables into its key.
|
||||
CARGO_INCREMENTAL: 0
|
||||
@@ -323,9 +368,13 @@ jobs:
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
|
||||
# The gate's own key (the shared action computes it), restore only. The toolchain action
|
||||
# exports CARGO_HOME, which the gate's legs do not have; align-environment leaves it out of
|
||||
@@ -343,57 +392,13 @@ jobs:
|
||||
|
||||
- name: Test without heif
|
||||
run: cargo nextest run -p photocraft-io --locked --profile ci
|
||||
|
||||
corpus:
|
||||
if: github.event_name != 'schedule' && (github.event.action != 'labeled' || github.event.label.name == 'full-ci')
|
||||
timeout-minutes: 30
|
||||
# Real-file corpus tests (cargo feature `corpus`), on every PR and on main. The corpora are
|
||||
# pinned in xtask/src/corpus_pins.rs and sha256-verified (xtask/*.sha256) after both a cache
|
||||
# restore and a download; a missing corpus fails the tests. The cache key changes only when a
|
||||
# pin or manifest does, so normally this restores in seconds (fork PRs read the base cache).
|
||||
name: corpus tests
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
# test-corpus builds with --release, but here without the release profile's thin LTO and
|
||||
# single codegen unit: they ran LTO over the dependency graph for each of the ~95 corpus test
|
||||
# binaries, so building took 23.5 of the job's 37 minutes while the tests ran for 1.5.
|
||||
# Turning them off builds 2.7x faster; the code under test is the same.
|
||||
CARGO_PROFILE_RELEASE_LTO: "false"
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: "16"
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
prefix-key: v1-rust
|
||||
key: corpus
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
cache-on-failure: true
|
||||
- name: Restore test corpora
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: corpus/
|
||||
key: corpus-${{ hashFiles('xtask/src/corpus_pins.rs', 'xtask/*.sha256') }}
|
||||
- name: Fetch and verify corpora
|
||||
run: cargo xtask corpus --all
|
||||
- name: Corpus tests
|
||||
run: cargo xtask test-corpus
|
||||
|
||||
web:
|
||||
timeout-minutes: 60
|
||||
name: web build and wasm size gate
|
||||
# PRs run it only when web-relevant files change (see `platforms`); main always does.
|
||||
needs: platforms
|
||||
if: needs.platforms.outputs.web == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }}
|
||||
env:
|
||||
# Match release.yml so PR results reflect what would actually ship.
|
||||
TRUNK_VERSION: 0.21.14
|
||||
@@ -411,10 +416,13 @@ jobs:
|
||||
- name: Check out craft-i18n
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
targets: wasm32-unknown-unknown
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
prefix-key: v1-rust
|
||||
@@ -458,7 +466,10 @@ jobs:
|
||||
name: fuzz (${{ matrix.target.crate }}/${{ matrix.target.name }})
|
||||
# Placeholder: manual trigger only until a nightly schedule is enabled.
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.fuzz
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }}
|
||||
env:
|
||||
# cargo-fuzz needs nightly; the checkout's rust-toolchain.toml would pick the pinned release.
|
||||
RUSTUP_TOOLCHAIN: nightly
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -512,7 +523,7 @@ jobs:
|
||||
|
||||
color-range-performance:
|
||||
if: inputs.color_range == true
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }}
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
@@ -530,13 +541,17 @@ jobs:
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
- name: Compare exact outputs and release timings on 24 MP
|
||||
run: |
|
||||
set -o pipefail
|
||||
cargo test --release -p photocraft-engine --lib color_range_release_comparison -- --ignored --nocapture | tee color-range-perf.txt
|
||||
cargo test --release -p photocraft-engine-core --lib color_range_release_comparison -- --ignored --nocapture | tee color-range-perf.txt
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
@@ -545,7 +560,7 @@ jobs:
|
||||
|
||||
selection-morphology:
|
||||
if: inputs.selection_morphology == true
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }}
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
@@ -563,9 +578,13 @@ jobs:
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
- name: Compare exact outputs and release timings on 36 MP
|
||||
run: |
|
||||
set -o pipefail
|
||||
@@ -573,7 +592,7 @@ jobs:
|
||||
- name: Compare cropped command reads and writeback on 36 MP
|
||||
run: |
|
||||
set -o pipefail
|
||||
cargo test --release -p photocraft-engine --lib sparse_modify_release_comparison -- --ignored --nocapture | tee -a selection-morphology-perf.txt
|
||||
cargo test --release -p photocraft-engine-core --lib sparse_modify_release_comparison -- --ignored --nocapture | tee -a selection-morphology-perf.txt
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
@@ -595,9 +614,13 @@ jobs:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
# perf-nightly.yml's entry (same key and runner); only that job saves it.
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
@@ -616,7 +639,7 @@ jobs:
|
||||
|
||||
selection-combining:
|
||||
if: inputs.selection_combining == true
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }}
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
@@ -628,9 +651,13 @@ jobs:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
- name: Compare exact outputs and release timings on 36 MP
|
||||
run: |
|
||||
set -o pipefail
|
||||
@@ -643,7 +670,7 @@ jobs:
|
||||
|
||||
brush-tip:
|
||||
if: inputs.brush_tip == true
|
||||
runs-on: ubuntu-24.04
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-24.04' }}
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
@@ -661,9 +688,13 @@ jobs:
|
||||
persist-credentials: false
|
||||
ref: ${{ inputs.brush_tip_base }}
|
||||
path: before
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
- name: Build the same benchmark against both versions
|
||||
run: |
|
||||
cp after/crates/paint/examples/big_dab_bench.rs before/crates/paint/examples/big_dab_bench.rs
|
||||
@@ -687,7 +718,7 @@ jobs:
|
||||
path: brush-tip.txt
|
||||
dry-mixer:
|
||||
if: inputs.dry_mixer == true
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }}
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
RAYON_NUM_THREADS: "4"
|
||||
@@ -712,9 +743,13 @@ jobs:
|
||||
git worktree add --detach "$RUNNER_TEMP/photocraft-baseline" "$base"
|
||||
mkdir -p "$RUNNER_TEMP/photocraft-baseline/crates/engine/examples"
|
||||
cp crates/engine/examples/bench_dry_mixer.rs "$RUNNER_TEMP/photocraft-baseline/crates/engine/examples/bench_dry_mixer.rs"
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
- name: Install Linux build dependencies
|
||||
uses: storytold/craft-common-actions/actions/install-apt-packages@main
|
||||
with:
|
||||
@@ -747,3 +782,33 @@ jobs:
|
||||
with:
|
||||
name: dry-mixer-performance
|
||||
path: dry-mixer-perf.txt
|
||||
|
||||
# After the nightly cold run passes, a warning (annotation and job summary) says when a newer stable
|
||||
# Rust release than rust-toolchain.toml's exists. It needs no permission and changes nothing: a bump
|
||||
# is a pull request that changes the file's `channel` by hand.
|
||||
toolchain-check:
|
||||
name: toolchain check
|
||||
needs: gate
|
||||
if: github.event_name == 'schedule' && needs.gate.result == 'success'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Compare the pinned release with stable
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version=$(python3 scripts/ci-toolchain-bump.py)
|
||||
if [ -z "$version" ]; then
|
||||
echo "rust-toolchain.toml is current"
|
||||
exit 0
|
||||
fi
|
||||
msg="Rust $version is the newest stable release; rust-toolchain.toml pins an older one. Change its channel in a pull request to move."
|
||||
echo "::warning title=Newer Rust release::$msg"
|
||||
echo "$msg" >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -31,6 +31,7 @@ jobs:
|
||||
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
|
||||
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
|
||||
with:
|
||||
os: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && '["artcraft-k8s-main"]' || '["ubuntu-24.04"]' }}
|
||||
timeout-minutes: 15
|
||||
# The book needs mdBook only: no craft-fonts, apt packages, wasm target or nextest.
|
||||
craft-fonts-ref: ""
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
name: Dispatch release-ref nightly
|
||||
|
||||
# Transport only, never authorization. No checkout, payload parsing or release environment.
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [PhotoCraft unsigned nightly]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
dispatch:
|
||||
# SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification.
|
||||
if: >-
|
||||
false && github.repository == 'storytold/photocraft' &&
|
||||
github.event_name == 'workflow_run'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
actions: write
|
||||
steps:
|
||||
- name: Dispatch only the exact completed producer run and attempt
|
||||
shell: python
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
def require(value, message):
|
||||
if not value:
|
||||
raise RuntimeError(message)
|
||||
|
||||
# These filters reduce noise; the protected signer-branch validator repeats admission
|
||||
# against authenticated API metadata and required attestation/quality evidence.
|
||||
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/photocraft', 'wrong repository')
|
||||
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
|
||||
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
|
||||
event = json.load(stream)
|
||||
require(event.get('action') == 'completed', 'producer is not complete')
|
||||
require(event.get('repository', {}).get('full_name') == 'storytold/photocraft', 'wrong event repository')
|
||||
producer = event.get('workflow_run', {})
|
||||
require(producer.get('head_repository', {}).get('full_name') == 'storytold/photocraft', 'foreign producer')
|
||||
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
|
||||
require(producer.get('head_branch') == 'main', 'wrong producer branch')
|
||||
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
|
||||
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
|
||||
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
|
||||
run_id, attempt = producer.get('id'), producer.get('run_attempt')
|
||||
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
|
||||
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
|
||||
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
|
||||
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
|
||||
}}).encode('utf-8')
|
||||
request = urllib.request.Request(
|
||||
'https://api.github.com/repos/storytold/photocraft/actions/workflows/nightly-sign.yml/dispatches',
|
||||
data=body, method='POST', headers={
|
||||
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'User-Agent': 'photocraft-nightly-dispatch'
|
||||
})
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise RuntimeError('dispatch redirects are forbidden')
|
||||
# One bounded request, no retry: duplicate transport is not publication authority.
|
||||
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
|
||||
require(response.status == 204, 'dispatch was not accepted')
|
||||
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
|
||||
@@ -0,0 +1,91 @@
|
||||
name: Nightly macOS build
|
||||
|
||||
# Builds the unsigned Apple-silicon PhotoCraft Nightly (packaging/macos/nightly.sh) on a hosted macOS
|
||||
# runner and checks the archive as the Launcher unpacks it, ending with the bundle's version query
|
||||
# (packaging/macos/nightly-verify.sh --expect unsigned). No secrets and no environment: the real Nightly
|
||||
# is signed and notarized by the shared release-ref signer (craft-common-actions), which calls
|
||||
# packaging/macos/nightly-sign.sh.
|
||||
on:
|
||||
# macOS runners are shared with release builds: pull requests run this only with the `full-ci`
|
||||
# label (as ci.yml's Windows legs), never by changed paths. `labeled` so adding it starts a run.
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, labeled]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A newer push to a labelled PR cancels its older run. Any event that will not build (no `full-ci`
|
||||
# label, or another label added) gets a group of its own, so it never cancels a real build.
|
||||
concurrency:
|
||||
group: nightly-macos-${{ github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'full-ci') && (github.event.action != 'labeled' || github.event.label.name == 'full-ci') && github.ref || github.run_id }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Nightly .app (aarch64, unsigned)
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(contains(github.event.pull_request.labels.*.name, 'full-ci') &&
|
||||
(github.event.action != 'labeled' || github.event.label.name == 'full-ci'))
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
# The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build.
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
ref: cc9269cd8d8258785dac603fba3122e5d2556795
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
with:
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
# A version of the prepared Nightly form for this commit; the real one comes from the feed's
|
||||
# identity job. Only nightly.sh's input checks read it.
|
||||
- name: Prepare a Nightly identity for this commit
|
||||
run: |
|
||||
set -euo pipefail
|
||||
base="$(python3 -c 'import tomllib; print(tomllib.load(open("Cargo.toml", "rb"))["workspace"]["package"]["version"].split("-")[0])')"
|
||||
sha="$(git rev-parse HEAD)"
|
||||
date="$(date -u +%Y-%m-%d)"
|
||||
{
|
||||
echo "PHOTOCRAFT_BUILD_SHA=$sha"
|
||||
echo "PHOTOCRAFT_BUILD_DATE=$date"
|
||||
echo "PHOTOCRAFT_VERSION=$base-nightly.${date//-/}.$GITHUB_RUN_NUMBER.$GITHUB_RUN_ATTEMPT.g${sha:0:12}"
|
||||
} >>"$GITHUB_ENV"
|
||||
- name: Build the unsigned Nightly bundle
|
||||
env:
|
||||
PHOTOCRAFT_BUILD_CHANNEL: nightly-v1
|
||||
CARGO_TARGET_DIR: ${{ runner.temp }}/nightly-targets
|
||||
DIST: ${{ runner.temp }}/nightly-dist
|
||||
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
|
||||
CRAFT_FONTS_REQUIRED: "1"
|
||||
run: bash packaging/macos/nightly.sh --arch aarch64
|
||||
- name: Check the archive and the bundle's version
|
||||
run: bash packaging/macos/nightly-verify.sh --expect unsigned --input "$RUNNER_TEMP/nightly-dist/photocraft-$PHOTOCRAFT_VERSION-macos-aarch64-nightly.zip"
|
||||
# Keeps the verified unsigned zip briefly for keyless signer tests and hand testing. Unsigned only.
|
||||
- name: Keep the unsigned archive
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: photocraft-nightly-macos-aarch64-unsigned
|
||||
path: ${{ runner.temp }}/nightly-dist/photocraft-${{ env.PHOTOCRAFT_VERSION }}-macos-aarch64-nightly.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
@@ -0,0 +1,46 @@
|
||||
name: PhotoCraft release-ref nightly signer
|
||||
|
||||
# Enabled for supervised manual dispatch on the dedicated nightly-signer branch, which only ever
|
||||
# fast-forwards to reviewed main commits (never the stable release branch).
|
||||
# A reusable callee does not change context; this must be a real top-level signer-branch dispatch.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
producer_run_id:
|
||||
description: Exact untrusted producer Actions run ID
|
||||
required: true
|
||||
type: string
|
||||
producer_run_attempt:
|
||||
description: Exact untrusted producer Actions run attempt
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: photocraft-nightly-release
|
||||
cancel-in-progress: false
|
||||
queue: max
|
||||
|
||||
jobs:
|
||||
release:
|
||||
# Actual context guards: official repository, manual dispatch, real nightly-signer branch.
|
||||
if: >-
|
||||
github.repository == 'storytold/photocraft' &&
|
||||
github.event_name == 'workflow_dispatch' &&
|
||||
github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'
|
||||
permissions:
|
||||
contents: write
|
||||
actions: read
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a
|
||||
with:
|
||||
tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a
|
||||
app-name: photocraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the existing release environment (which trusts release and
|
||||
# nightly-signer) and export keys in its signing step.
|
||||
@@ -0,0 +1,33 @@
|
||||
name: PhotoCraft unsigned nightly
|
||||
|
||||
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
|
||||
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
unsigned:
|
||||
# Actual context guards only; no inherited/platform secrets.
|
||||
if: >-
|
||||
github.repository == 'storytold/photocraft' &&
|
||||
github.ref == 'refs/heads/main' && github.ref_type == 'branch' &&
|
||||
(github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
|
||||
# Maximum for the reusable workflow. Its compiler narrows to contents/actions read;
|
||||
# no OIDC, attestation write, release environment or platform secrets in compilation.
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@8389cad8b849ea6bdb5e15fbce16772c3457565a
|
||||
with:
|
||||
tooling-revision: 8389cad8b849ea6bdb5e15fbce16772c3457565a
|
||||
app-name: photocraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
|
||||
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
|
||||
# craft-common-actions main commit that merged #371 (built-commit Sonar admission), on #370.
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
@@ -5,9 +5,9 @@ name: Packaging lint
|
||||
on:
|
||||
push:
|
||||
branches: [main, release]
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md"]
|
||||
paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md", "docs/nightly-signing-policy.example.json", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
|
||||
pull_request:
|
||||
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md"]
|
||||
paths: [".github/workflows/**", ".github/actionlint.yaml", "packaging/**", "assets/app-icon/**", "docs/mcp.md", "docs/control-protocol.md", "docs/nightly-signing-policy.example.json", ".github/nightly-signing-policy.json", ".github/nightly-linux-signing-key.asc", "sonar-project.properties"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
verified-appimage-inputs:
|
||||
timeout-minutes: 10
|
||||
name: Verified AppImage inputs
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ github.ref == 'refs/heads/main' && github.event_name != 'pull_request' && 'artcraft-k8s-main' || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
@@ -63,3 +63,20 @@ jobs:
|
||||
- name: Build and check non-executable installer fixtures
|
||||
shell: pwsh
|
||||
run: ./packaging/windows/test-install-policy.ps1 -OutputDirectory (Join-Path $env:RUNNER_TEMP 'craft-install-policy-tests')
|
||||
|
||||
nightly-source-contract:
|
||||
name: Nightly source contracts (no build or signing)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Enforce nightly serialization and synthetic packaging contracts
|
||||
run: python3 packaging/nightly-tests.py
|
||||
@@ -51,9 +51,13 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
|
||||
with:
|
||||
toolchain: stable
|
||||
toolchain: ${{ steps.rust.outputs.toolchain }}
|
||||
targets: ${{ steps.rust.outputs.targets }}
|
||||
components: ${{ steps.rust.outputs.components }}
|
||||
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
|
||||
@@ -56,3 +56,4 @@ jobs:
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
ARTCRAFT_SERVICES_DISPATCH_TOKEN: ${{ secrets.ARTCRAFT_SERVICES_DISPATCH_TOKEN }}
|
||||
@@ -23,4 +23,6 @@ jobs:
|
||||
fonts-ref: cc9269cd8d8258785dac603fba3122e5d2556795
|
||||
# The coverage build's ~1.3 GB cache would not fit the repository's 10 GB cache budget.
|
||||
build-cache: false
|
||||
python-coverage-source: packaging
|
||||
python-coverage-script: packaging/nightly-tests.py
|
||||
secrets: inherit
|
||||
@@ -11,3 +11,8 @@ target/
|
||||
/craft-fonts
|
||||
*.log
|
||||
__pycache__/
|
||||
|
||||
# Checked out inside the workspace by the shared nightly workflows (craft-common-actions).
|
||||
/.nightly-tools
|
||||
/.nightly-input
|
||||
/craft-i18n
|
||||
@@ -88,7 +88,7 @@ Conventions and paths:
|
||||
|
||||
- `unsafe` is allowed only in `crates/tablet/src/macos.rs` and `windows.rs`; the workspace sets `unsafe_code = "forbid"`. The example plug-in in `examples/plugins/` is outside the workspace and uses `unsafe` for the WebAssembly host calls. Every new crate sets `[lints] workspace = true`.
|
||||
- Attribution file: `ATTRIBUTION.md`. Fonts come from storytold/craft-fonts through `CRAFT_FONTS_DIR` (`docs/development.md` > Fonts).
|
||||
- Test corpora: storytold/photocraft-corpus, fetched into `corpus/` by `cargo xtask corpus --all` at the pins in `xtask/src/corpus_pins.rs`.
|
||||
- Test corpora: storytold/photocraft-corpus, fetched into `corpus/` by `cargo xtask corpus --all` at the pins in `xtask/src/corpus_pins.rs`. `cargo xtask test-corpus` runs each directory's fixed sample; `PHOTOCRAFT_FULL_SWEEP=1` runs every file (CI: samples on pull requests and main, every file nightly).
|
||||
- Feature names are recorded in `docs/feature-names.md`.
|
||||
- Contributor credits: `docs/contributors.md`.
|
||||
- Dev log: `log/devlog.md` (local, gitignored). `plan/` is an optional local notebook.
|
||||
|
||||
@@ -22,6 +22,8 @@ next to them.
|
||||
| `assets/icons/history-brush.svg` | History Brush tool glyph: Lucide `brush` plus counter-clockwise history rewind arrow | Lucide Icons and Contributors; arrow by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
|
||||
| `assets/dict/en_US-scowl-50.txt.gz` | English word list for Check Spelling (SCOWL 2020.12.07, size 50, en_US; 72,403 words) | Kevin Atkinson and the SCOWL contributors | <http://wordlist.aspell.net/> | SCOWL license (permissive, keep the notice), [`assets/dict/LICENSE-SCOWL.txt`](assets/dict/LICENSE-SCOWL.txt), which also has the build recipe |
|
||||
| `assets/app-icon/` (all files) | PhotoCraft app icon (nine-tailed kitsune) | The project owner (drawn in ArtCraft, vectorised) | Original work, see [`assets/app-icon/README.md`](assets/app-icon/README.md) | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) |
|
||||
| `assets/app-icon/photocraft-nightly.png`, `photocraft-nightly-1024.png`, `photocraft-nightly.ico`, `photocraft-nightly.icns` | PhotoCraft nightly deep-background derivatives | @skylartaylor | Original project-owned256 and padded1024 masters at the revision and hashes in [`nightly-provenance.json`](assets/app-icon/nightly-provenance.json); code-generated background-contribution change only, preserving foreground/alpha; no badge or crescent | MIT OR Apache-2.0, [`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt) |
|
||||
| `packaging/nightly-archive-tests.py` (runtime-generated temporary files) | Synthetic flat-archive inventory and exclusive-output fixtures; regular-file payloads, not real image/executable validity | @skylartaylor | Original test-generated strings/files and symlinks from the committed script; no external media or user documents | MIT OR Apache-2.0 |
|
||||
| `packaging/macos/dmg/` (all files) | PhotoCraft DMG window background and layout | @XusBadia, from the PhotoCraft app icon | Original work, see [`packaging/macos/dmg/README.md`](packaging/macos/dmg/README.md) | MIT OR Apache-2.0, like the code |
|
||||
| `crates/ui-egui/src/theme.rs` (Solarized Dark palette) | Solarized colour scheme used by the Solarized Dark theme | Ethan Schoonover | <https://ethanschoonover.com/solarized/> | MIT, [`LICENSE-solarized.txt`](crates/ui-egui/src/LICENSE-solarized.txt) |
|
||||
| `crates/ui-egui/src/theme.rs` (Breeze Light and Breeze Dark themes) | The Breeze Light and Breeze Dark themes are original colour values on PhotoCraft's Studio layout, chosen to look close to KDE Plasma's Breeze (cool blue-greys, blue accent, 5 px frame radius) so the app blends into a Plasma desktop. None of Breeze's colour values, files or code are copied; the values are a few levels away from its schemes and tuned for text contrast | PhotoCraft contributors | Inspired by the look of KDE Breeze, <https://invent.kde.org/plasma/breeze> (its colour schemes are LGPL-2.0-or-later) | Original work |
|
||||
@@ -132,3 +134,7 @@ longer used or shipped.
|
||||
| Dependency | Authors | Source | License and notices |
|
||||
|---|---|---|---|
|
||||
| `jpeg-encoder` 0.6.1, through `craft-image-codecs` | Upstream jpeg-encoder, IJG and SIMD authors named in the notices | [Published crate](https://crates.io/crates/jpeg-encoder/0.6.1) | `(MIT OR Apache-2.0) AND IJG`; complete notices in [NOTICE](NOTICE), source texts and checksums in [licenses/jpeg-encoder-0.6.1](licenses/jpeg-encoder-0.6.1) |
|
||||
|
||||
Mac Nightly metadata tests (`packaging/macos/nightly_plist_tests.py`) generate plist dictionaries and owned sentinel bytes from this repository's app-owned Info.plist template. They use no native binaries, signing credentials, external products or archives; @skylartaylor.
|
||||
|
||||
Windows nightly signing-policy tests generate dummy environment values, signature-status objects and owned sentinel bytes. They never contain signing material or invoke a compiler, signing tool or network; @skylartaylor.
|
||||
Generated
+363
-136
File diff suppressed because it is too large.
Load diff
+68
-57
@@ -12,21 +12,21 @@ rust-version = "1.95"
|
||||
[workspace.dependencies]
|
||||
# The craft framework through its facade (`craft::ui::…`). The egui `[patch]` below must match
|
||||
# `craft::egui_fork::REV` (checked by `cargo xtask ci`).
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90", default-features = false }
|
||||
craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", default-features = false }
|
||||
craft-tracked = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-ui-macros = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
# internal
|
||||
photocraft-geom = { path = "crates/geom" }
|
||||
photocraft-color = { path = "crates/color" }
|
||||
photocraft-raster = { path = "crates/raster" }
|
||||
photocraft-doc = { path = "crates/doc" }
|
||||
photocraft-ops = { path = "crates/ops" }
|
||||
craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] }
|
||||
craft-plist = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
photocraft-codecs = { package = "craft-image-codecs", git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
photocraft-formats = { package = "craft-file-formats", git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["raster-codecs", "pdf", "svg", "ora", "kra", "xcf", "pdn", "raw", "psd", "affinity", "pcraft"] }
|
||||
photocraft-raw = { path = "crates/raw" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
photocraft-compose = { path = "crates/compose" }
|
||||
photocraft-gpu = { path = "crates/gpu" }
|
||||
photocraft-paint = { path = "crates/paint" }
|
||||
@@ -38,6 +38,9 @@ photocraft-format = { path = "crates/format" }
|
||||
photocraft-automation = { path = "crates/automation" }
|
||||
photocraft-plugins = { path = "crates/plugins" }
|
||||
photocraft-engine = { path = "crates/engine" }
|
||||
photocraft-engine-core = { path = "crates/engine-core" }
|
||||
photocraft-engine-paint = { path = "crates/engine-paint" }
|
||||
photocraft-engine-vector = { path = "crates/engine-vector" }
|
||||
photocraft-ui-egui = { path = "crates/ui-egui" }
|
||||
photocraft-testkit = { path = "crates/testkit" }
|
||||
photocraft-tablet = { path = "crates/tablet" }
|
||||
@@ -45,34 +48,36 @@ photocraft-ipp = { path = "crates/ipp" }
|
||||
|
||||
# external
|
||||
# ICC colour management: the shared crate (replaces crates/cms; craft-libs#779).
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
# HEIC/HEIF: the shared decoder (replaces crates/heif; craft-libs#784).
|
||||
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90", features = ["raster", "write-raster"] }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-heif = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["raster", "write-raster"] }
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-pcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-pcraft-bundle = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-ora = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-kra = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-xcf = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-pdn = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
# Keep the shared embedded-image validation API until the framework revision includes it.
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90", features = ["tree-render", "tree-render-system-fonts"] }
|
||||
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["tree-render", "tree-render-system-fonts"] }
|
||||
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
# Camera-field EXIF reader/writer, shared prerequisite craft-libs#1563.
|
||||
craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-metadata = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-crs = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
craft-develop-model = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
# Interface translations: lookup, fallback, CLDR plurals and language names over the craft-i18n
|
||||
# catalogs that `crates/ui-egui/build.rs` embeds from `CRAFT_I18N_DIR` (storytold/craft-i18n, at
|
||||
# the commit in `craft-i18n.rev`). Already in the tree through craft.
|
||||
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90", features = ["ui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2", features = ["ui"] }
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = "1"
|
||||
@@ -118,7 +123,7 @@ todo = "warn"
|
||||
# Every cl command selects these packages: each brings features the others lack, so a command that drops one
|
||||
# builds a second copy of egui, photocraft-io or craft-affinity and of everything above them.
|
||||
selection = [
|
||||
"photocraft-ui-egui", "photocraft-engine", "photocraft", "photocraft-algo", "photocraft-automation",
|
||||
"photocraft-ui-egui", "photocraft-engine", "photocraft-engine-core", "photocraft-engine-paint", "photocraft-engine-vector", "photocraft", "photocraft-algo", "photocraft-automation",
|
||||
"photocraft-text", "photocraft-tablet", "photocraft-cli", "photocraft-paint", "photocraft-io", "photocraft-gpu",
|
||||
]
|
||||
# Crates whose new builds cl names after a command, besides the framework's.
|
||||
@@ -147,7 +152,9 @@ craft-imaging = ["default", "screen-testing", "ui"]
|
||||
[workspace.metadata.cl.default_seconds]
|
||||
"photocraft-ui-egui/photocraft_ui_egui" = 389.0
|
||||
"photocraft-ui-egui/it" = 221.0
|
||||
"photocraft-engine/photocraft_engine" = 97.0
|
||||
"photocraft-engine-core/photocraft_engine_core" = 62.0
|
||||
"photocraft-engine-paint/photocraft_engine_paint" = 35.0
|
||||
"photocraft-engine-vector/photocraft_engine_vector" = 6.0
|
||||
|
||||
# Dependencies carry no debug info: their frames in a backtrace lose file:line, and the target dir
|
||||
# and link times shrink. The test profile inherits both settings.
|
||||
@@ -177,6 +184,12 @@ opt-level = 0
|
||||
# the dev profile's 1.
|
||||
[profile.test.package.photocraft-engine]
|
||||
opt-level = 0
|
||||
[profile.test.package.photocraft-engine-core]
|
||||
opt-level = 0
|
||||
[profile.test.package.photocraft-engine-paint]
|
||||
opt-level = 0
|
||||
[profile.test.package.photocraft-engine-vector]
|
||||
opt-level = 0
|
||||
|
||||
# Only the exhaustive rounding proof needs maximum optimization; algo stays at its usual level.
|
||||
[profile.test.package.photocraft-oil-round-proof]
|
||||
@@ -337,30 +350,28 @@ opt-level = 3
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
|
||||
[patch.crates-io]
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
vello_common = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "683fe06031224725b913c8ad3697d8e8bfec6c90" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
hayro = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
vello_common = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
vello_cpu = { git = "https://github.com/storytold/craft-libs", rev = "a46af76c7c74dd8dd375d694baaef00d5ae836a2" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ WORKDIR /src/apps/photocraft-web
|
||||
# memory than the release zip's fat LTO; retain the profile's other optimizations.
|
||||
ARG CARGO_PROFILE_WASM_RELEASE_LTO=thin
|
||||
ARG CARGO_BUILD_JOBS=1
|
||||
# Optional build provenance shown in About and `--version` (crates/engine/src/build_info.rs).
|
||||
# Optional build provenance shown in About and `--version` (crates/engine-core/src/build_info.rs).
|
||||
# .git is not in the build context, so pass it in, e.g.
|
||||
# --build-arg PHOTOCRAFT_BUILD_SHA=$(git rev-parse HEAD) --build-arg PHOTOCRAFT_BUILD_DATE=$(date -u +%F)
|
||||
# Left empty, the build reports itself as a dev build.
|
||||
|
||||
@@ -185,8 +185,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%" valign="top">
|
||||
<h4>🧰 69 tools</h4>
|
||||
Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Star · Line · Custom Shape · Hand · Rotate View · Zoom
|
||||
<h4>🧰 70 tools</h4>
|
||||
Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Adjustment Brush · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Star · Line · Custom Shape · Hand · Rotate View · Zoom
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
<h4>🖌️ A real brush engine</h4>
|
||||
@@ -353,7 +353,6 @@ sha256-verified. Fetch them with `cargo xtask corpus --all` and run the tests wi
|
||||
|---|---|---|
|
||||
| x64 (64-bit Intel/AMD) | `photocraft-<ver>-windows-x64.msi` | `photocraft-<ver>-windows-x64-portable.zip` |
|
||||
| arm64 (Snapdragon and other ARM PCs) | `photocraft-<ver>-windows-arm64.msi` | `photocraft-<ver>-windows-arm64-portable.zip` |
|
||||
| x86 (32-bit) | `photocraft-<ver>-windows-x86.msi` | `photocraft-<ver>-windows-x86-portable.zip` |
|
||||
|
||||
Installers and executables are code-signed.
|
||||
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ PhotoCraft processes complex document and image formats and exposes CLI, JSON co
|
||||
|
||||
Please give the repository maintainers a reasonable opportunity to investigate and coordinate a fix before publishing exploitable details, proof-of-concept code, or weaponized files.
|
||||
|
||||
This repository does not currently document a dedicated private security email or private reporting channel. Contact the repository maintainers through the repository owner/maintainer channels already listed in the project, provide only a minimal non-exploitable summary in public, and ask for an appropriate private transfer method before sharing sensitive details. Do not open a public issue containing a working exploit, secret, sensitive crash dump, or malicious attachment.
|
||||
Report vulnerabilities through [GitHub private vulnerability reporting](https://github.com/storytold/photocraft/security/advisories/new). If you cannot access that channel, contact the repository maintainers through the repository owner/maintainer channels already listed in the project, provide only a minimal non-exploitable summary in public, and ask for an appropriate private transfer method before sharing sensitive details. Do not open a public issue containing a working exploit, secret, sensitive crash dump, or malicious attachment.
|
||||
|
||||
If no private channel can be established, withhold weaponized material and report the smallest safe description that allows maintainers to make contact.
|
||||
|
||||
|
||||
@@ -90,7 +90,8 @@ pub fn load_actions_file(path: &Path, name: Option<&str>) -> Result<(Steps, Vec<
|
||||
let is_atn = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("atn")) || matches!(bytes.get(..4), Some([0, 0, 0, 12 | 16]));
|
||||
if !is_atn {
|
||||
let text = String::from_utf8(bytes).map_err(|source| ActionsError::Utf8 { path: path.to_path_buf(), source })?;
|
||||
let (steps, set) = load_actions(&text, name)?;
|
||||
let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
|
||||
let (steps, set) = load_actions(text, name)?;
|
||||
return Ok((steps, set, Vec::new()));
|
||||
}
|
||||
let imp = photocraft_engine::atn_cmds::import(&bytes).map_err(|message| ActionsError::Atn { path: path.to_path_buf(), message })?;
|
||||
@@ -114,3 +115,23 @@ pub fn load_actions_file(path: &Path, name: Option<&str>) -> Result<(Steps, Vec<
|
||||
let play = vec![("actions.play".to_string(), json!({"action": action.name}))];
|
||||
Ok((play, imp.actions, warnings))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn load_actions_file_accepts_utf8_bom() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("actions.json");
|
||||
|
||||
std::fs::write(&path, b"\xEF\xBB\xBF[\"image.adjustments.invert\"]").unwrap();
|
||||
let (steps, set, warnings) = load_actions_file(&path, None).unwrap();
|
||||
assert_eq!(steps, vec![("image.adjustments.invert".to_owned(), json!({}))]);
|
||||
assert!(set.is_empty());
|
||||
assert!(warnings.is_empty());
|
||||
|
||||
std::fs::write(&path, b"\xEF\xBB\xBF[").unwrap();
|
||||
assert!(matches!(load_actions_file(&path, None), Err(ActionsError::Json(_))));
|
||||
}
|
||||
}
|
||||
@@ -308,6 +308,7 @@ pub(crate) struct McpArgs {
|
||||
/// Each request is a JSON line {"id", "method", "params"}. Methods: engine.execute,
|
||||
/// jobs.list/cancel, engine.commands,
|
||||
/// doc.open/new/place/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close,
|
||||
/// doc.replaceSmartObject,
|
||||
/// session.list, batch, methods (docs/control-protocol.md#headless-server). The token flags require
|
||||
/// --port (or PHOTOCRAFT_CONTROL_PORT); stdio needs no control token.
|
||||
#[derive(Args)]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use photocraft_engine::actions_cmds::ActionsExt;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -21,10 +22,12 @@ fn same_dir(a: &Path, b: &Path) -> bool {
|
||||
|
||||
pub(crate) fn is_input(p: &Path) -> bool {
|
||||
let known = |e: &str| {
|
||||
matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "kra" | "krz" | "af" | "afdesign" | "afphoto" | "afpub")
|
||||
matches!(e, "pcraft" | "psd" | "psb" | "pdn" | "ora" | "kra" | "krz" | "af" | "afdesign" | "afphoto" | "afpub" | "xcf" | "xcfgz")
|
||||
|| photocraft_codecs::from_extension(e).is_some_and(|f| photocraft_codecs::caps(f).read)
|
||||
};
|
||||
p.is_file() && p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase()))
|
||||
// Only GIMP's compound suffix is an image; an arbitrary .gz is not a batch input.
|
||||
let gzipped_xcf = p.file_name().is_some_and(|name| name.to_string_lossy().to_ascii_lowercase().ends_with(".xcf.gz"));
|
||||
p.is_file() && (gzipped_xcf || p.extension().is_some_and(|e| known(&e.to_string_lossy().to_ascii_lowercase())))
|
||||
}
|
||||
|
||||
/// Drops the Save and view steps the desktop records from `action` (Batch saves each result
|
||||
@@ -70,7 +73,8 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
|
||||
for entry in entries {
|
||||
let path = entry.map_err(|source| CliError::ReadDir { path: in_dir.to_path_buf(), source })?.path();
|
||||
if is_input(&path) {
|
||||
images.push(photocraft_engine::file_cmds::BatchInput { path: path.to_string_lossy().into_owned(), rel_dir: String::new() });
|
||||
let input = path.to_str().ok_or_else(|| CliError::BatchOption(format!("batch input path must be valid UTF-8: {path:?}")))?;
|
||||
images.push(photocraft_engine::file_cmds::BatchInput { path: input.to_owned(), rel_dir: String::new() });
|
||||
}
|
||||
}
|
||||
// The tree listing already holds the engine's order (each folder's files, then its
|
||||
@@ -104,6 +108,9 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
|
||||
photocraft_engine::file_cmds::validate_flat_outputs(&plan).map_err(|error| CliError::Naming(error.to_string()))?;
|
||||
if let Some(log) = &a.error_log {
|
||||
let same = |path: &Path| photocraft_engine::file_cmds::same_destination(log, path);
|
||||
if same(&a.actions) {
|
||||
return Err(CliError::BatchOption("--error-log must not replace the --actions file".into()));
|
||||
}
|
||||
if inputs.iter().any(|input| same(Path::new(&input.path))) || targets.iter().any(|target| same(target)) {
|
||||
return Err(CliError::BatchOption("--error-log must not replace an input or batch output".into()));
|
||||
}
|
||||
@@ -126,7 +133,7 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
|
||||
}
|
||||
// Steps that play another action find it in the set; the session's playback stack
|
||||
// stops an action that calls itself.
|
||||
h.session.actions.list = ActionList::from_file(ActionsFile::new(set.clone(), Vec::new()));
|
||||
h.session.actions_mut().list = ActionList::from_file(ActionsFile::new(set.clone(), Vec::new()));
|
||||
h.open_with_approval(input, a.approve_high_memory)?;
|
||||
for (id, p) in &actions {
|
||||
if photocraft_engine::actions_cmds::shell_view_command(id)
|
||||
@@ -295,6 +302,59 @@ mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
#[test]
|
||||
fn batch_inputs_recognize_gimp_xcf_names_but_not_arbitrary_gzip() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["plain.xcf", "upper.XCF", "alias.xcfgz", "upper-alias.XCFGZ", "compressed.xcf.gz", "upper-compressed.XCF.GZ", "ordinary.PNG"] {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, b"").unwrap();
|
||||
assert!(is_input(&path), "{name} should be selected");
|
||||
}
|
||||
for name in ["notes.txt.gz", "archive.tar.gz", "backup.xcf.gz.tmp", "notes.txt"] {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, b"").unwrap();
|
||||
assert!(!is_input(&path), "{name} should be skipped");
|
||||
}
|
||||
let directory = dir.path().join("folder.xcf.gz");
|
||||
std::fs::create_dir(&directory).unwrap();
|
||||
assert!(!is_input(&directory), "a directory is not an input image");
|
||||
assert!(!is_input(&dir.path().join("missing.xcf.gz")), "a missing file is not an input image");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let path = dir.path().join(std::ffi::OsString::from_vec(b"non-utf8-\xff.XCF.GZ".to_vec()));
|
||||
std::fs::write(&path, b"").unwrap();
|
||||
assert!(is_input(&path), "a non-UTF8 filename can still have the compound suffix");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn flat_batch_rejects_non_utf8_input_before_writing_output() {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let input = dir.path().join("in");
|
||||
std::fs::create_dir(&input).unwrap();
|
||||
let original = input.join(std::ffi::OsString::from_vec(b"photo-\xff.xcf".to_vec()));
|
||||
let alias = input.join("photo-\u{fffd}.xcf");
|
||||
std::fs::write(&original, b"original file").unwrap();
|
||||
std::fs::write(&alias, b"replacement-character file").unwrap();
|
||||
let actions = dir.path().join("actions.json");
|
||||
std::fs::write(&actions, "[]").unwrap();
|
||||
let output = dir.path().join("out");
|
||||
let crate::test_support::Invoke { code, stdout, stderr } =
|
||||
crate::test_support::invoke(&["batch", "--actions", actions.to_str().unwrap(), "--in", input.to_str().unwrap(), "--out", output.to_str().unwrap()]);
|
||||
|
||||
assert_eq!(code, 1, "{stdout}{stderr}");
|
||||
assert!(stderr.contains("batch input path must be valid UTF-8"), "{stderr}");
|
||||
assert!(stderr.contains(&format!("{original:?}")), "the diagnostic must distinguish the invalid bytes from the valid alias: {stderr}");
|
||||
assert!(stdout.is_empty(), "discovery must fail before processing any input: {stdout}");
|
||||
assert!(!output.exists(), "discovery must fail before creating the output directory");
|
||||
assert_eq!(std::fs::read(&original).unwrap(), b"original file");
|
||||
assert_eq!(std::fs::read(&alias).unwrap(), b"replacement-character file");
|
||||
}
|
||||
|
||||
struct RecordingRenderer {
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
@@ -40,6 +40,16 @@ where
|
||||
T: Into<OsString>,
|
||||
{
|
||||
let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
|
||||
// nightly-v1 is a desktop-only contract. Never let GUI profile arguments fall through
|
||||
// to stable CLI/MCP directory and credential discovery.
|
||||
if args.iter().take_while(|arg| arg.as_os_str() != std::ffi::OsStr::new("--")).any(|arg| {
|
||||
let text = arg.to_string_lossy();
|
||||
text == "--launch-profile" || text == "--profile-root" || text.starts_with("--launch-profile=") || text.starts_with("--profile-root=")
|
||||
}) {
|
||||
let _ = writeln!(err, "nightly-v1 is supported only by the PhotoCraft desktop launcher protocol");
|
||||
return 2;
|
||||
}
|
||||
|
||||
// Help and `--version` (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too,
|
||||
// for `out`, exit 0: the subcommand never runs.
|
||||
let cli = match parse(&args) {
|
||||
@@ -84,3 +94,14 @@ pub(crate) mod test_support {
|
||||
Invoke { code, stdout: String::from_utf8(stdout).unwrap(), stderr: String::from_utf8(stderr).unwrap() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod nightly_protocol_tests {
|
||||
#[test]
|
||||
fn gui_profile_protocol_is_refused_before_any_cli_command() {
|
||||
let result = super::test_support::invoke(&["--launch-profile", "nightly-v1", "--profile-root", "a-private-root", "--", "file.psd"]);
|
||||
assert_eq!(result.code, 2);
|
||||
assert!(result.stdout.is_empty());
|
||||
assert!(result.stderr.contains("desktop launcher protocol"));
|
||||
}
|
||||
}
|
||||
@@ -715,6 +715,22 @@ fn batch_with(d: &Path, input: &Path, name: &str, actions: &str, extra: &[&str])
|
||||
bin().args(["batch", "--actions"]).arg(&file).arg("--in").arg(input).arg("--out").arg(d.join(name)).args(extra).output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_error_log_cannot_replace_its_actions_file() {
|
||||
let d = tmp("batch-log-actions-collision");
|
||||
let input = d.join("in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
let actions = r#"[{"command":"image.adjustments.invert"}]"#;
|
||||
let log = input.join("../actions.json");
|
||||
|
||||
let result = batch_with(&d, &input, "actions", actions, &["--error-log", &log.to_string_lossy()]);
|
||||
let error = String::from_utf8_lossy(&result.stderr);
|
||||
assert!(!result.status.success(), "{error}");
|
||||
assert!(error.contains("--error-log") && error.contains("--actions"), "{error}");
|
||||
assert_eq!(std::fs::read(d.join("actions.json")).unwrap(), actions.as_bytes());
|
||||
assert!(!d.join("actions").exists(), "the output folder must not be created");
|
||||
}
|
||||
|
||||
/// #489: `batch --actions` takes `[id, params]` steps and a droplet's steps, with the same results
|
||||
/// as the object form; a malformed step fails before anything is written.
|
||||
#[test]
|
||||
@@ -1411,6 +1427,7 @@ fn a_non_unicode_path_is_taken_and_non_unicode_text_is_a_usage_error() {
|
||||
#[test]
|
||||
fn batch_plays_a_photoshop_actions_file() {
|
||||
use photocraft_engine::actions_cmds::{Action, ActionStep};
|
||||
photocraft_engine::install().unwrap();
|
||||
let d = tmp("atn");
|
||||
let input = d.join("in");
|
||||
std::fs::create_dir_all(&input).unwrap();
|
||||
|
||||
@@ -26,10 +26,16 @@
|
||||
#photocraft_stopped a { color: #ffffff; }
|
||||
#photocraft_stopped_detail { color: #b8b8b8; }
|
||||
</style>
|
||||
<noscript>
|
||||
<style>#photocraft_loading > p { display: none; }</style>
|
||||
</noscript>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="photocraft_canvas"></canvas>
|
||||
<div id="photocraft_loading">
|
||||
<noscript>
|
||||
<p>PhotoCraft needs JavaScript to run. Allow JavaScript for this site, then <a href="">Reload</a> to start.</p>
|
||||
</noscript>
|
||||
<p>Loading PhotoCraft…</p>
|
||||
<p id="photocraft_stalled">This is taking longer than usual. If PhotoCraft doesn't start, its files may have failed to
|
||||
download or come from a different version of this page. <a href="">Reload</a> to try again; the browser
|
||||
|
||||
@@ -26,10 +26,16 @@
|
||||
#photocraft_stopped a { color: #ffffff; }
|
||||
#photocraft_stopped_detail { color: #b8b8b8; }
|
||||
</style>
|
||||
<noscript>
|
||||
<style>#photocraft_loading > p { display: none; }</style>
|
||||
</noscript>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="photocraft_canvas"></canvas>
|
||||
<div id="photocraft_loading">
|
||||
<noscript>
|
||||
<p>PhotoCraft needs JavaScript to run. Allow JavaScript for this site, then <a href="">Reload</a> to start.</p>
|
||||
</noscript>
|
||||
<p>Loading PhotoCraft…</p>
|
||||
<p id="photocraft_stalled">This is taking longer than usual. If PhotoCraft doesn't start, its files may have failed to
|
||||
download or come from a different version of this page. <a href="">Reload</a> to try again; the browser
|
||||
|
||||
@@ -39,9 +39,26 @@ pub fn take_panic() -> Option<String> {
|
||||
pub fn is_trap(name: &str, message: &str) -> bool {
|
||||
let message = message.to_ascii_lowercase();
|
||||
name == "RuntimeError"
|
||||
|| ["unreachable", "memory access out of bounds", "maximum call stack", "could not allocate memory", "out of memory"]
|
||||
.iter()
|
||||
.any(|m| message.contains(m))
|
||||
// A failed request can call its host "unreachable" without stopping the module.
|
||||
|| matches!(
|
||||
message.trim(),
|
||||
"unreachable"
|
||||
| "error: unreachable"
|
||||
| "runtimeerror: unreachable"
|
||||
| "uncaught error: unreachable"
|
||||
| "uncaught runtimeerror: unreachable"
|
||||
| "uncaught (in promise) runtimeerror: unreachable"
|
||||
)
|
||||
|| [
|
||||
"unreachable executed",
|
||||
"unreachable code should not be executed",
|
||||
"memory access out of bounds",
|
||||
"maximum call stack",
|
||||
"could not allocate memory",
|
||||
"out of memory",
|
||||
]
|
||||
.iter()
|
||||
.any(|m| message.contains(m))
|
||||
}
|
||||
|
||||
/// Trap messages (lowercase, matched ignoring case) that mean an allocation failed:
|
||||
@@ -109,13 +126,38 @@ mod tests {
|
||||
fn only_traps_count() {
|
||||
assert!(is_trap("RuntimeError", "unreachable"));
|
||||
assert!(is_trap("RuntimeError", ""));
|
||||
assert!(is_trap("RuntimeError", "divide by zero"));
|
||||
for message in [
|
||||
"unreachable",
|
||||
"Error: unreachable",
|
||||
"RuntimeError: unreachable",
|
||||
"Uncaught Error: unreachable",
|
||||
"Uncaught RuntimeError: unreachable",
|
||||
"Uncaught (in promise) RuntimeError: unreachable",
|
||||
"RuntimeError: unreachable executed",
|
||||
] {
|
||||
assert!(is_trap("", message), "{message}");
|
||||
}
|
||||
assert!(is_trap("RangeError", "Maximum call stack size exceeded"));
|
||||
assert!(is_trap("RangeError", "WebAssembly.Memory(): could not allocate memory"));
|
||||
// Matched ignoring case: Safari's wording, reported without the RuntimeError name.
|
||||
assert!(is_trap("Error", "Unreachable code should not be executed"));
|
||||
assert!(is_trap("Error", "Unreachable code should not be executed (evaluating 'module.run()')"));
|
||||
assert!(is_trap("Error", "Out of memory"));
|
||||
assert!(!is_trap("TypeError", "Failed to fetch"));
|
||||
assert!(!is_trap("Error", "ResizeObserver loop completed"));
|
||||
for (name, message) in [
|
||||
("Error", "server unreachable"),
|
||||
("TypeError", "Failed to fetch: host unreachable"),
|
||||
("", "Error: endpoint unreachable"),
|
||||
("Error", "unreachable resource"),
|
||||
("Error", "Uncaught Error: server unreachable"),
|
||||
("Error", "network unreachable"),
|
||||
("", "server: unreachable"),
|
||||
("", "NetworkError: unreachable"),
|
||||
] {
|
||||
assert!(!is_trap(name, message), "unrelated error classified as a trap: {name}: {message}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
//! Synchronous engine boundary for asynchronous browser storage. No browser handles cross the
|
||||
//! engine's `Send` boundary. Byte buffers are shared with the single in-flight transaction.
|
||||
use photocraft_engine::actions_cmds::ActionsExt;
|
||||
use photocraft_engine::prefs::SavedPrefsExt;
|
||||
use photocraft_engine::preset_store::PresetStoreExt;
|
||||
use photocraft_engine::presets::PresetsExt;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
|
||||
@@ -534,7 +538,7 @@ mod tests {
|
||||
bridge.load_action_keys(2, keys.clone());
|
||||
let (session, warnings) = session(bridge.clone());
|
||||
assert!(!warnings.is_empty());
|
||||
assert!(session.actions.list.actions().is_empty());
|
||||
assert!(session.actions().list.actions().is_empty());
|
||||
assert!(session.tools.presets.iter().any(|preset| preset.name == "Browser seam brush"));
|
||||
assert_eq!(bridge.committed_action_keys(), None);
|
||||
assert_eq!(bridge.read(ACTIONS_FILE, 1024).unwrap(), malformed);
|
||||
@@ -750,7 +754,7 @@ mod tests {
|
||||
let (mut loaded, _) = session(b);
|
||||
loaded.load_prefs_json(&prefs).unwrap();
|
||||
assert_eq!(loaded.tools.presets, s.tools.presets);
|
||||
assert_eq!(loaded.presets.gradients, s.presets.gradients);
|
||||
assert!(loaded.presets.gradients.iter().any(|g| g.name == "Browser gradients"));
|
||||
assert_eq!(loaded.presets().gradients, s.presets().gradients);
|
||||
assert!(loaded.presets().gradients.iter().any(|g| g.name == "Browser gradients"));
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The browser shell: web `Services`, drag-and-drop, and the eframe web runner.
|
||||
|
||||
use photocraft_engine::actions_cmds::ActionsExt;
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
@@ -100,11 +101,11 @@ pub fn start() {
|
||||
let served: Served = Arc::default();
|
||||
load_font_manifest(served.clone(), cc.egui_ctx.clone());
|
||||
let (session, warnings) = crate::preset_bridge::session(presets.clone());
|
||||
let actions_revision = session.actions.list.revision();
|
||||
let actions_revision = session.actions().list.revision();
|
||||
preset_warnings.extend(warnings);
|
||||
let drag = listen_drag(&pen_target);
|
||||
let mut services = services(inbox.clone(), place_inbox.clone(), drag_pos_service(pen_target.clone(), drag));
|
||||
let mut initial = Some(load_initial_preferences(&presets, database.is_some() && !session.actions.list.actions().is_empty()));
|
||||
let mut initial = Some(load_initial_preferences(&presets, database.is_some() && !session.actions().list.actions().is_empty()));
|
||||
services.load_prefs = Some(Box::new(move || initial.take().unwrap_or_else(stored_preferences)));
|
||||
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), session, services);
|
||||
if !preset_warnings.is_empty() {
|
||||
@@ -381,11 +382,11 @@ struct WebShell {
|
||||
impl WebShell {
|
||||
fn save_presets(&mut self, ctx: &egui::Context) {
|
||||
let session = &self.app.session;
|
||||
if self.actions_revision != session.actions.list.revision() {
|
||||
if self.actions_revision != session.actions().list.revision() {
|
||||
// The engine can reject an oversized definition before calling the backend.
|
||||
// Never stage that edit's keys with the last successfully queued definitions.
|
||||
self.presets.verify_action_definitions(&session.actions);
|
||||
self.actions_revision = session.actions.list.revision();
|
||||
self.presets.verify_action_definitions(session.actions());
|
||||
self.actions_revision = session.actions().list.revision();
|
||||
}
|
||||
let prefs_revision = session.prefs.rev();
|
||||
if self.prefs_revision != Some(prefs_revision) {
|
||||
|
||||
@@ -53,6 +53,11 @@ open = "5"
|
||||
ron = "0.12"
|
||||
# Background release checks; HTTPS with Rust TLS, no async runtime.
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# The process allocator on Windows (main.rs): the system heap's alloc and free were about 14 % of the UI
|
||||
# thread in a frame (#15493). MIT.
|
||||
mimalloc = { version = "0.1", default-features = false }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# Safe CoreGraphics bindings, compatible with the existing macOS 11 deployment target.
|
||||
# `event` (CGEventSource) is used for the Caps Lock poll (#1758).
|
||||
@@ -70,7 +75,7 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = ["
|
||||
objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSApplicationScripting", "NSEvent", "NSGraphics", "NSResponder", "NSView", "NSWindow"] }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { version = "=1.1.5", features = ["fs"] }
|
||||
rustix = { version = "=1.1.6", features = ["fs"] }
|
||||
# Reads CFBundleExecutable from a chosen macOS application bundle's Info.plist (XML or binary) for
|
||||
# external vector editing. Already in Cargo.lock (craft-update); built on every Unix so Linux CI
|
||||
# compiles and tests the bundle checks. The event-stream reader (behind plist's "unstable"
|
||||
@@ -111,7 +116,7 @@ winit = { version = "=0.30.13", default-features = false, features = ["wayland-c
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
# Safe Windows screen-capture bindings; Linux uses the pure-Rust X11 client/portal.
|
||||
xcap = "=0.9.8"
|
||||
winsafe = { version = "=0.0.29", default-features = false, features = ["user"] }
|
||||
winsafe = { version = "=0.0.29", default-features = false, features = ["user", "shell"] }
|
||||
|
||||
|
||||
[build-dependencies]
|
||||
|
||||
@@ -4,11 +4,43 @@
|
||||
//! cross-compile from macOS or Linux still links, unless `PHOTOCRAFT_REQUIRE_WINRES=1` (set by the
|
||||
//! release workflow) turns it into an error.
|
||||
|
||||
#[path = "src/build_channel.rs"]
|
||||
mod build_channel;
|
||||
|
||||
/// Embeds the Windows resources and delay-loads the print-only system DLLs (#5884, #8272).
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
println!("cargo:rerun-if-env-changed=PHOTOCRAFT_BUILD_CHANNEL");
|
||||
println!("cargo:rustc-check-cfg=cfg(photocraft_nightly_v1)");
|
||||
let nightly = match std::env::var("PHOTOCRAFT_BUILD_CHANNEL").as_deref() {
|
||||
Ok("nightly-v1") => {
|
||||
println!("cargo:rustc-cfg=photocraft_nightly_v1");
|
||||
true
|
||||
}
|
||||
// An empty value (an unset CI input) means the default stable build.
|
||||
Ok("stable" | "") | Err(std::env::VarError::NotPresent) => false,
|
||||
_ => {
|
||||
eprintln!("unsupported PHOTOCRAFT_BUILD_CHANNEL (expected stable or nightly-v1)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft.ico");
|
||||
println!("cargo:rerun-if-changed=../../assets/app-icon/photocraft-nightly.ico");
|
||||
println!("cargo:rerun-if-env-changed=PHOTOCRAFT_REQUIRE_WINRES");
|
||||
println!("cargo:rerun-if-env-changed=PHOTOCRAFT_VERSION");
|
||||
let built_version = if nightly {
|
||||
match std::env::var("PHOTOCRAFT_VERSION") {
|
||||
Ok(version) if build_channel::is_nightly_version(&version) => version,
|
||||
_ => {
|
||||
eprintln!("nightly-v1 requires an explicit PHOTOCRAFT_VERSION feed identity");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std::env::var("CARGO_PKG_VERSION").unwrap_or_default()
|
||||
};
|
||||
println!("cargo:rustc-env=PHOTOCRAFT_BUILT_VERSION={built_version}");
|
||||
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
@@ -23,13 +55,17 @@ fn main() {
|
||||
println!("cargo:rustc-link-arg-bins=delayimp.lib");
|
||||
}
|
||||
let mut res = winresource::WindowsResource::new();
|
||||
res.set_icon("../../assets/app-icon/photocraft.ico")
|
||||
.set("ProductName", "PhotoCraft")
|
||||
.set("FileDescription", "PhotoCraft image editor")
|
||||
res.set_icon(build_channel::windows_icon_path(nightly))
|
||||
.set("ProductName", if nightly { "PhotoCraft Nightly" } else { "PhotoCraft" })
|
||||
.set("FileDescription", if nightly { "PhotoCraft Nightly image editor" } else { "PhotoCraft image editor" })
|
||||
.set("CompanyName", "Learning Machines LLC")
|
||||
.set("LegalCopyright", "Copyright (c) the PhotoCraft authors. MIT OR Apache-2.0.")
|
||||
.set("OriginalFilename", "photocraft.exe")
|
||||
.set("InternalName", "photocraft");
|
||||
if nightly {
|
||||
// Launcher verifies the PE ProductVersion against the exact feed identity, not FileVersion.
|
||||
res.set("ProductVersion", &built_version);
|
||||
}
|
||||
if let Err(e) = res.compile() {
|
||||
if std::env::var_os("PHOTOCRAFT_REQUIRE_WINRES").is_some() {
|
||||
panic!("embedding Windows resources failed: {e}");
|
||||
|
||||
@@ -31,7 +31,10 @@ pub fn current() -> &'static DataDir {
|
||||
static DIR: OnceLock<DataDir> = OnceLock::new();
|
||||
DIR.get_or_init(|| {
|
||||
let exe = std::env::current_exe().ok();
|
||||
let d = resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent));
|
||||
let d = match crate::launch_profile::current().root() {
|
||||
Some(root) => DataDir { dir: Some(root.to_path_buf()), mode: Mode::Override, warning: None },
|
||||
None => resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent)),
|
||||
};
|
||||
if let Some(w) = &d.warning {
|
||||
log::warn!("{w}");
|
||||
eprintln!("photocraft: {w}");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The app icon, everywhere Windows, macOS and Linux show one (#248).
|
||||
//!
|
||||
//! - **Executable:** `build.rs` embeds `assets/app-icon/photocraft.ico` (16–256 px) as icon
|
||||
//! - **Executable:** `build.rs` selects the stable or nightly-only `.ico` (16–256 px) as icon
|
||||
//! resource 1, which Explorer, Alt+Tab and an unpinned taskbar button fall back to.
|
||||
//! - **Window:** [`window_icon`] sets the title-bar and taskbar icon at runtime (`WM_SETICON` on
|
||||
//! Windows, `_NET_WM_ICON` on X11, the Dock when running unbundled on macOS).
|
||||
@@ -9,15 +9,16 @@
|
||||
//! shortcut's icon under its `<Icon Id>`, so that id must carry the target's `.exe` extension
|
||||
//! (ICE50); an extensionless id showed a blank page on the taskbar. The tests below check it.
|
||||
//!
|
||||
//! The process keeps Windows' implicit AppUserModelID (derived from the executable path), which
|
||||
//! is what makes that matching work for both the MSI shortcut and the portable exe. An explicit
|
||||
//! ID would need a Win32 call (`unsafe`, which the workspace forbids) and would then also have to
|
||||
//! be stamped on the shortcut, or the taskbar would stop matching the two.
|
||||
//! Stable keeps Windows' implicit AppUserModelID (derived from the executable path), which
|
||||
//! is what makes that matching work for both the MSI shortcut and the portable exe. Changing
|
||||
//! stable's ID would also require changing its matching shortcut policy. Nightly is separate:
|
||||
//! its app bootstrap uses the existing safe Windows bindings to set its persistent channel
|
||||
//! identity before any native window.
|
||||
|
||||
/// Window, taskbar and (when running unbundled) Dock icon. macOS gets the padded 1024 px render
|
||||
/// on Apple's icon grid; elsewhere the 256 px hicolor render of the full tile.
|
||||
pub fn window_icon() -> egui::IconData {
|
||||
match eframe::icon_data::from_png_bytes(PNG) {
|
||||
match eframe::icon_data::from_png_bytes(icon_png(crate::build_flavor::COMPILED, cfg!(target_os = "macos"))) {
|
||||
Ok(icon) => icon,
|
||||
Err(e) => {
|
||||
log::warn!("app icon: {e}");
|
||||
@@ -26,6 +27,16 @@ pub fn window_icon() -> egui::IconData {
|
||||
}
|
||||
}
|
||||
|
||||
fn icon_png(flavor: crate::build_flavor::BuildFlavor, macos: bool) -> &'static [u8] {
|
||||
if flavor != crate::build_flavor::BuildFlavor::NightlyV1 {
|
||||
PNG
|
||||
} else if macos {
|
||||
include_bytes!("../../../assets/app-icon/photocraft-nightly-1024.png")
|
||||
} else {
|
||||
include_bytes!("../../../assets/app-icon/photocraft-nightly.png")
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the window gets [`window_icon`] at runtime: everywhere except inside a macOS app
|
||||
/// bundle. There the Dock shows the bundle's `PhotoCraft.icns` (`CFBundleIconFile`), which macOS
|
||||
/// renders in its own style (Liquid Glass and its tinted and dark variants); a runtime PNG
|
||||
@@ -60,6 +71,41 @@ const PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn nightly_uses_each_platforms_distinct_nonblank_native_size_icon() {
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
assert_eq!(icon_png(BuildFlavor::Stable, true), PNG);
|
||||
assert_eq!(icon_png(BuildFlavor::Stable, false), PNG);
|
||||
for (macos, expected_size) in [(false, 256), (true, 1024)] {
|
||||
let nightly = icon_png(BuildFlavor::NightlyV1, macos);
|
||||
assert_ne!(nightly, PNG);
|
||||
let icon = eframe::icon_data::from_png_bytes(nightly).unwrap();
|
||||
assert_eq!((icon.width, icon.height), (expected_size, expected_size));
|
||||
assert!(icon.rgba.chunks(4).any(|pixel| pixel[3] > 0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_executable_icon_retains_all_six_shell_sizes() {
|
||||
let ico = include_bytes!("../../../assets/app-icon/photocraft-nightly.ico");
|
||||
assert_ne!(ico.as_slice(), ICO);
|
||||
assert_eq!((u16_at(ico, 0), u16_at(ico, 2)), (0, 1));
|
||||
let mut sizes = Vec::new();
|
||||
for i in 0..u16_at(ico, 4) {
|
||||
let entry = 6 + 16 * i;
|
||||
let width = if ico[entry] == 0 { 256 } else { usize::from(ico[entry]) };
|
||||
let height = if ico[entry + 1] == 0 { 256 } else { usize::from(ico[entry + 1]) };
|
||||
assert_eq!(width, height);
|
||||
let image = &ico[u32_at(ico, entry + 12)..][..u32_at(ico, entry + 8)];
|
||||
assert!(image.starts_with(b"\x89PNG\r\n\x1a\n"));
|
||||
let decoded = eframe::icon_data::from_png_bytes(image).unwrap();
|
||||
assert_eq!((decoded.width as usize, decoded.height as usize), (width, height));
|
||||
sizes.push(width);
|
||||
}
|
||||
for expected in [16, 24, 32, 48, 64, 256] {
|
||||
assert!(sizes.contains(&expected), "missing nightly icon size {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
const ICO: &[u8] = include_bytes!("../../../assets/app-icon/photocraft.ico");
|
||||
const WXS: &str = include_str!("../../../packaging/windows/photocraft.wxs");
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! The build-time nightly identity shared by the build script and its pure regression tests.
|
||||
pub fn is_nightly_version(version: &str) -> bool {
|
||||
let Some((base, suffix)) = version.split_once("-nightly.") else { return false };
|
||||
let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
|
||||
let base: Vec<_> = base.split('.').collect();
|
||||
let parts: Vec<_> = suffix.split('.').collect();
|
||||
base.len() == 3
|
||||
&& base.iter().all(|s| digits(s))
|
||||
&& parts.len() == 4
|
||||
&& parts[0].len() == 8
|
||||
&& digits(parts[0])
|
||||
&& digits(parts[1])
|
||||
&& digits(parts[2])
|
||||
&& parts[3].strip_prefix('g').is_some_and(|sha| sha.len() == 12 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
|
||||
}
|
||||
pub fn windows_icon_path(nightly: bool) -> &'static str {
|
||||
if nightly { "../../assets/app-icon/photocraft-nightly.ico" } else { "../../assets/app-icon/photocraft.ico" }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn windows_resource_uses_the_flavor_specific_icon_without_changing_stable() {
|
||||
assert_eq!(windows_icon_path(false), "../../assets/app-icon/photocraft.ico");
|
||||
assert_eq!(windows_icon_path(true), "../../assets/app-icon/photocraft-nightly.ico");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_feed_identity_is_required_for_a_nightly_build() {
|
||||
assert!(is_nightly_version("0.23.1-nightly.20261120.17.1.gabcdef012345"));
|
||||
for invalid in [
|
||||
"",
|
||||
"0.23.1",
|
||||
"0.23.1-nightly",
|
||||
"0.23.1-nightly.20261120",
|
||||
"0.23.1-nightly.20261120.17.1.gABCDEF012345",
|
||||
"0.23.1-nightly.20261120.17.1.gabcdef012345\n",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid), "{invalid:?}");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn version_cannot_inject_a_path_or_an_extra_build_directive() {
|
||||
for invalid in [
|
||||
"../0.23.1-nightly.20261120.1.1.gabcdef012345",
|
||||
"0.23.1-nightly.20261120.1.1.gabcdef012345/other",
|
||||
"0.23.1-nightly.20261120.1.1.gabcdef012345\ncargo:rustc-cfg=other",
|
||||
] {
|
||||
assert!(!is_nightly_version(invalid));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
//! Build-time channel is distinct from a launch selector. A runtime environment cannot promote a stable build.
|
||||
use crate::launch_profile::Profile;
|
||||
use std::ffi::OsString;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum BuildFlavor {
|
||||
Stable,
|
||||
NightlyV1,
|
||||
}
|
||||
|
||||
pub const COMPILED: BuildFlavor = if cfg!(photocraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
|
||||
|
||||
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
|
||||
match (flavor, profile.is_nightly()) {
|
||||
(BuildFlavor::NightlyV1, false) => Err("Open PhotoCraft Nightly from ArtCraft Launcher".into()),
|
||||
(BuildFlavor::Stable, true) => Err("This is a stable PhotoCraft build; nightly-v1 requires the nightly build".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
|
||||
desktop_session && flavor == BuildFlavor::NightlyV1
|
||||
}
|
||||
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
matches!(args, [arg] if arg == "--version" || arg == "-V")
|
||||
}
|
||||
|
||||
pub fn version(flavor: BuildFlavor, stable: &str) -> String {
|
||||
match flavor {
|
||||
BuildFlavor::Stable => stable.to_owned(),
|
||||
BuildFlavor::NightlyV1 => format!("{stable} (nightly-v1)"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
|
||||
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
|
||||
assert!(!needs_native_error(BuildFlavor::NightlyV1, false));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, true));
|
||||
assert!(!needs_native_error(BuildFlavor::Stable, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_build_without_a_profile_is_refused_before_startup() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
|
||||
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
|
||||
assert!(!started.get());
|
||||
}
|
||||
#[test]
|
||||
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
|
||||
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
|
||||
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
|
||||
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
|
||||
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
|
||||
assert_eq!(version(BuildFlavor::Stable, "0.23.1"), "0.23.1");
|
||||
assert_eq!(version(BuildFlavor::NightlyV1, "0.23.1"), "0.23.1 (nightly-v1)");
|
||||
assert!(version_query(&["--version".into()]));
|
||||
assert!(version_query(&["-V".into()]));
|
||||
assert!(!version_query(&["--".into(), "--version".into()]));
|
||||
assert!(!version_query(&[]));
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,15 @@
|
||||
//! [`service`] builds the pointer-position service for the app's window, `None` where it can't
|
||||
//! be read.
|
||||
|
||||
pub use platform::service;
|
||||
pub use platform::{primary_down_service, service};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod platform {
|
||||
/// Not read here: the title-bar move of a floating document window reaches the app as a press and a release.
|
||||
pub fn primary_down_service() -> Option<photocraft_ui_egui::PrimaryDownFn> {
|
||||
None
|
||||
}
|
||||
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_app_kit::{NSApplication, NSEvent, NSWindow};
|
||||
use photocraft_ui_egui::CursorPosFn;
|
||||
@@ -45,6 +50,11 @@ mod platform {
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod platform {
|
||||
/// Not read here: the title-bar move of a floating document window reaches the app as a press and a release.
|
||||
pub fn primary_down_service() -> Option<photocraft_ui_egui::PrimaryDownFn> {
|
||||
None
|
||||
}
|
||||
|
||||
use eframe::wgpu::rwh::{HasWindowHandle, RawWindowHandle};
|
||||
use photocraft_ui_egui::CursorPosFn;
|
||||
use x11rb::protocol::xproto::ConnectionExt;
|
||||
@@ -81,7 +91,17 @@ mod platform {
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod platform {
|
||||
use photocraft_ui_egui::CursorPosFn;
|
||||
use photocraft_ui_egui::{CursorPosFn, PrimaryDownFn};
|
||||
|
||||
/// The physical left button (`GetAsyncKeyState`): a floating document window's title-bar move runs in the OS, which
|
||||
/// tells the app nothing when it ends (#16415).
|
||||
pub fn primary_down_service() -> Option<PrimaryDownFn> {
|
||||
// `GetAsyncKeyState` reads the physical button: with the buttons swapped, the primary one is the right.
|
||||
Some(Box::new(|| {
|
||||
let swapped = winsafe::GetSystemMetrics(winsafe::co::SM::SWAPBUTTON) != 0;
|
||||
winsafe::GetAsyncKeyState(if swapped { winsafe::co::VK::RBUTTON } else { winsafe::co::VK::LBUTTON })
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn service(_cc: &eframe::CreationContext<'_>) -> Option<CursorPosFn> {
|
||||
Some(Box::new(|ctx: &egui::Context| {
|
||||
@@ -104,6 +124,11 @@ fn client_points(screen_px: egui::Pos2, inner_min: egui::Pos2, ppp: f32) -> egui
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
|
||||
mod platform {
|
||||
/// Not read here: the title-bar move of a floating document window reaches the app as a press and a release.
|
||||
pub fn primary_down_service() -> Option<photocraft_ui_egui::PrimaryDownFn> {
|
||||
None
|
||||
}
|
||||
|
||||
use photocraft_ui_egui::CursorPosFn;
|
||||
|
||||
pub fn service(_cc: &eframe::CreationContext<'_>) -> Option<CursorPosFn> {
|
||||
|
||||
@@ -152,6 +152,13 @@ pub(crate) fn command() -> Command {
|
||||
.mut_args(blank_env_is_unset)
|
||||
}
|
||||
|
||||
/// Nightly has no control server. Its unused inherited port must not prevent a window from
|
||||
/// opening; Stable retains its existing environment/usage-error behavior.
|
||||
pub(crate) fn command_for_profile(nightly: bool) -> Command {
|
||||
let command = command();
|
||||
if nightly { command.mut_arg("control", |arg| arg.env(None::<&str>)) } else { command }
|
||||
}
|
||||
|
||||
/// Parse the launch arguments (without the binary name) with `cmd`, from [`command`]. Old macOS
|
||||
/// passes a process serial number (`-psn_…`) when launched from Finder: it is dropped first, unless
|
||||
/// it comes after `--`. A bad value from a variable is a usage error naming the variable.
|
||||
@@ -216,6 +223,37 @@ mod tests {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_ignores_only_the_unused_control_port_environment() {
|
||||
const CHILD: &str = "PHOTOCRAFT_TEST_CONTROL_PORT_CHILD";
|
||||
if let Ok(profile) = std::env::var(CHILD) {
|
||||
let nightly = profile == "nightly";
|
||||
let result = parse(command_for_profile(nightly), Vec::<OsString>::new());
|
||||
if nightly {
|
||||
assert!(result.is_ok(), "unused invalid control-port environment must not block Nightly");
|
||||
assert!(result.unwrap().control.is_none());
|
||||
assert!(parse(command_for_profile(true), ["--control", "70000"].map(OsString::from)).is_err(), "explicit invalid values remain invalid");
|
||||
} else {
|
||||
assert_eq!(result.err().unwrap().exit_code(), 2, "Stable preserves its invalid-environment error");
|
||||
}
|
||||
return;
|
||||
}
|
||||
for profile in ["stable", "nightly"] {
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "launch_args::tests::nightly_ignores_only_the_unused_control_port_environment", "--nocapture"])
|
||||
.env(CHILD, profile)
|
||||
.env("PHOTOCRAFT_CONTROL_PORT", "not-a-port")
|
||||
.env_remove("PHOTOCRAFT_CONTROL_TOKEN")
|
||||
.env_remove("PHOTOCRAFT_CONTROL_TOKEN_FILE")
|
||||
.env_remove("PHOTOCRAFT_AUTOMATION_READ_ROOT")
|
||||
.env_remove("PHOTOCRAFT_AUTOMATION_WRITE_ROOT")
|
||||
.env_remove("PHOTOCRAFT_IN_WINDOW_MENUS")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success(), "{profile}: {}", String::from_utf8_lossy(&output.stdout));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_port_rejects_unparseable_values_naming_them() {
|
||||
// Out of range, negative and empty values fail, naming the value (#701); a following
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Launcher-owned nightly-v1 bootstrap. Selected before logging, updates, fonts or saved state.
|
||||
//! Stable launches retain their original arguments and directory policy. No environment mutation.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub const VERSION: &str = "nightly-v1";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Profile {
|
||||
Stable,
|
||||
NightlyV1(PathBuf),
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
pub fn is_nightly(&self) -> bool {
|
||||
matches!(self, Self::NightlyV1(_))
|
||||
}
|
||||
|
||||
pub fn root(&self) -> Option<&Path> {
|
||||
match self {
|
||||
Self::Stable => None,
|
||||
Self::NightlyV1(root) => Some(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Launch {
|
||||
pub profile: Profile,
|
||||
pub args: Vec<OsString>,
|
||||
}
|
||||
|
||||
static PROFILE: OnceLock<Profile> = OnceLock::new();
|
||||
|
||||
pub fn current() -> &'static Profile {
|
||||
PROFILE.get().unwrap_or(&Profile::Stable)
|
||||
}
|
||||
|
||||
pub fn install(profile: Profile) -> Result<(), String> {
|
||||
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into())
|
||||
}
|
||||
|
||||
/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is
|
||||
/// a file, even when it looks like a profile flag. No filesystem or startup hook runs here.
|
||||
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
|
||||
let mut selector = None;
|
||||
let mut root = None;
|
||||
let mut other = Vec::new();
|
||||
let mut files = Vec::new();
|
||||
let mut iter = args.iter();
|
||||
let mut delimiter = false;
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg == "--" {
|
||||
delimiter = true;
|
||||
files.extend(iter.cloned());
|
||||
break;
|
||||
}
|
||||
if arg == "--launch-profile" || arg == "--profile-root" {
|
||||
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
|
||||
if slot.is_some() {
|
||||
return Err("the profile selector and root must each occur exactly once".into());
|
||||
}
|
||||
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
|
||||
if value.to_string_lossy().starts_with("--") {
|
||||
return Err("the profile selector/root needs a value".into());
|
||||
}
|
||||
*slot = Some(value.clone());
|
||||
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
|
||||
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
|
||||
} else {
|
||||
other.push(arg.clone());
|
||||
}
|
||||
}
|
||||
match (selector, root) {
|
||||
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
|
||||
(Some(version), Some(root)) if version == VERSION => {
|
||||
if !delimiter || !other.is_empty() {
|
||||
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
|
||||
}
|
||||
let root = PathBuf::from(root);
|
||||
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
|
||||
}
|
||||
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
|
||||
}
|
||||
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
|
||||
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
|
||||
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
|
||||
/// validated or touched, and `-- --version` stays a file name.
|
||||
pub fn version_query(args: &[OsString]) -> bool {
|
||||
let Some((last, pair)) = args.split_last() else { return false };
|
||||
if last != "--version" && last != "-V" {
|
||||
return false;
|
||||
}
|
||||
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
|
||||
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
|
||||
}
|
||||
|
||||
/// The existing renderer retry is signalled by its process-local failure marker. Ordinary
|
||||
/// Launcher calls still use the strict selector/root protocol; this is not authentication.
|
||||
pub fn parse_startup(args: Vec<OsString>, compatibility_retry: bool) -> Result<Launch, String> {
|
||||
if !compatibility_retry || args.first().is_none_or(|arg| arg != "--safe-gpu") {
|
||||
return parse(args);
|
||||
}
|
||||
let mut launch = parse(args[1..].to_vec())?;
|
||||
if launch.profile.is_nightly() {
|
||||
launch.args.insert(0, OsString::from("--safe-gpu"));
|
||||
Ok(launch)
|
||||
} else {
|
||||
// Stable's argument order and parser remain unchanged.
|
||||
parse(args)
|
||||
}
|
||||
}
|
||||
|
||||
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
|
||||
/// root validator, so its old portable/config resolution stays unchanged.
|
||||
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
|
||||
if let Profile::NightlyV1(root) = &launch.profile {
|
||||
launch.profile = Profile::NightlyV1(validate(root)?);
|
||||
}
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Resolve the selected private root before the caller's first startup effect.
|
||||
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
|
||||
let stable_agent = craft::control::agents::default_folder(crate::AGENT_APP_NAME);
|
||||
crate::profile_root::validate(root, env, exe, stable_agent.as_deref(), photocraft_automation::app_dirs::ensure_writable)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
fn args(values: &[&str]) -> Vec<OsString> {
|
||||
values.iter().map(OsString::from).collect()
|
||||
}
|
||||
fn absolute() -> &'static str {
|
||||
if cfg!(windows) { r"C:\NightlyData\profiles\photocraft" } else { "/nightly-data/profiles/photocraft" }
|
||||
}
|
||||
fn nightly() -> Vec<OsString> {
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_cpu_retry_preserves_the_nightly_root_and_literal_files() {
|
||||
let mut argv = args(&["--safe-gpu"]);
|
||||
argv.extend(nightly());
|
||||
argv.extend(args(&["document with spaces.psd", "--safe-gpu", "--profile-root"]));
|
||||
let launch = parse_startup(argv.clone(), true).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--safe-gpu", "--", "document with spaces.psd", "--safe-gpu", "--profile-root"]));
|
||||
assert!(parse_startup(argv, false).is_err(), "an ordinary invocation must not gain extra protocol flags");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_cannot_bypass_invalid_profiles_or_change_stable_arguments() {
|
||||
let stable = args(&["--safe-gpu", "--new-instance", "stable.psd"]);
|
||||
assert_eq!(parse_startup(stable.clone(), true).unwrap(), Launch { profile: Profile::Stable, args: stable });
|
||||
let mut duplicate = args(&["--safe-gpu", "--safe-gpu"]);
|
||||
duplicate.extend(nightly());
|
||||
assert!(parse_startup(duplicate, true).is_err());
|
||||
assert!(parse_startup(args(&["--safe-gpu", "--launch-profile", VERSION, "--profile-root", "relative", "--"]), true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_arguments_and_directory_policy_are_unchanged() {
|
||||
for argv in [args(&[]), args(&["--new-instance", "a.psd"]), args(&["--", "--launch-profile", "file.psd"])] {
|
||||
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
|
||||
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() {
|
||||
let mut argv = nightly();
|
||||
argv.extend(args(&["--profile-root", "image with spaces.psd"]));
|
||||
let launch = parse(argv).unwrap();
|
||||
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
|
||||
assert_eq!(launch.args, args(&["--", "--profile-root", "image with spaces.psd"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
|
||||
for argv in [
|
||||
args(&["--launch-profile", VERSION]),
|
||||
args(&["--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
] {
|
||||
assert!(parse(argv).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
|
||||
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
|
||||
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
|
||||
for flag in ["--version", "-V"] {
|
||||
for form in [pair, reversed] {
|
||||
let mut argv = args(form);
|
||||
argv.push(flag.into());
|
||||
assert!(version_query(&argv), "{argv:?}");
|
||||
}
|
||||
}
|
||||
for argv in [
|
||||
args(&["--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--new-instance", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
|
||||
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
|
||||
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--version"]),
|
||||
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
|
||||
] {
|
||||
assert!(!version_query(&argv), "{argv:?}");
|
||||
}
|
||||
// Outside the query the strict protocol still refuses the version flag.
|
||||
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
|
||||
let reached = Cell::new(false);
|
||||
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
|
||||
assert!(result.is_err());
|
||||
assert!(!reached.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
|
||||
let checked = PathBuf::from(absolute()).join("checked");
|
||||
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
|
||||
assert_eq!(launch.profile.root(), Some(checked.as_path()));
|
||||
assert!(launch.profile.is_nightly());
|
||||
}
|
||||
}
|
||||
@@ -227,7 +227,14 @@ pub fn missing_message(session: DisplaySession, missing: &[AnyOf], distro: Distr
|
||||
|
||||
/// Library directories to search: `LD_LIBRARY_PATH`, then the usual system and Flatpak paths.
|
||||
fn search_dirs(ld_library_path: Option<&str>) -> Vec<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = ld_library_path.unwrap_or("").split(':').filter(|d| !d.is_empty()).map(PathBuf::from).collect();
|
||||
// ld.so accepts either separator; an empty entry in a nonempty list means the current directory.
|
||||
// An unset or entirely empty variable adds no directories.
|
||||
let mut dirs: Vec<PathBuf> = ld_library_path
|
||||
.filter(|value| !value.is_empty())
|
||||
.into_iter()
|
||||
.flat_map(|value| value.split([':', ';']))
|
||||
.map(|dir| PathBuf::from(if dir.is_empty() { "." } else { dir }))
|
||||
.collect();
|
||||
let triplet = if cfg!(target_arch = "aarch64") {
|
||||
"aarch64-linux-gnu"
|
||||
} else if cfg!(target_arch = "riscv64") {
|
||||
@@ -398,7 +405,8 @@ mod tests {
|
||||
fn library_dirs_count_and_unread_cache_is_inconclusive() {
|
||||
let dirs = search_dirs(Some("/opt/x/lib::/nix/store/abc/lib"));
|
||||
assert_eq!(dirs[0], PathBuf::from("/opt/x/lib"));
|
||||
assert_eq!(dirs[1], PathBuf::from("/nix/store/abc/lib"));
|
||||
assert_eq!(dirs[1], PathBuf::from("."));
|
||||
assert_eq!(dirs[2], PathBuf::from("/nix/store/abc/lib"));
|
||||
// Found by file in a directory (no ldconfig, as on NixOS).
|
||||
let probe = Probe { ldconfig: None, dirs: vec![PathBuf::from("/nix/lib")] };
|
||||
let present = ["/nix/lib/libwayland-client.so.0", "/nix/lib/libxkbcommon.so.0", "/nix/lib/libEGL.so.1"];
|
||||
@@ -412,6 +420,44 @@ mod tests {
|
||||
assert!(msg.contains("dnf install libwayland-client libxkbcommon vulkan-loader"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_path_separators_and_empty_entries_follow_the_loader() {
|
||||
let defaults = search_dirs(None);
|
||||
assert_eq!(search_dirs(Some("")), defaults, "an entirely empty variable adds no directories");
|
||||
for (value, entries) in [
|
||||
("/opt/a:/opt/b", &["/opt/a", "/opt/b"][..]),
|
||||
("/opt/a;/opt/b", &["/opt/a", "/opt/b"][..]),
|
||||
("/opt/a;/opt/b:/opt/c", &["/opt/a", "/opt/b", "/opt/c"][..]),
|
||||
(":/opt/b", &[".", "/opt/b"][..]),
|
||||
("/opt/a:", &["/opt/a", "."][..]),
|
||||
("/opt/a::/opt/b", &["/opt/a", ".", "/opt/b"][..]),
|
||||
("/opt/a;;/opt/b", &["/opt/a", ".", "/opt/b"][..]),
|
||||
(":", &[".", "."][..]),
|
||||
(";", &[".", "."][..]),
|
||||
(" /opt/a ;relative/lib", &[" /opt/a ", "relative/lib"][..]),
|
||||
(" ", &[" "][..]),
|
||||
] {
|
||||
let mut expected: Vec<PathBuf> = entries.iter().map(PathBuf::from).collect();
|
||||
expected.extend(defaults.iter().cloned());
|
||||
assert_eq!(search_dirs(Some(value)), expected, "LD_LIBRARY_PATH={value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loader_search_paths_prevent_false_startup_errors() {
|
||||
let soname = "libxkbcommon-x11.so.0";
|
||||
let names: Vec<&str> = ALL_X11.iter().copied().filter(|name| *name != soname).collect();
|
||||
let probe = Probe { ldconfig: Some(cache_for_this_arch(&names)), dirs: search_dirs(None) };
|
||||
let missing = check(DisplaySession::X11, &probe, |_| false);
|
||||
assert!(decide(DisplaySession::X11, missing, || Distro::Debian).is_err(), "a genuinely missing library still blocks startup");
|
||||
for (value, directory) in [("/opt/a;/opt/b", "/opt/b"), (":/opt/a", "."), ("/opt/a:", ".")] {
|
||||
let probe = Probe { ldconfig: Some(cache_for_this_arch(&names)), dirs: search_dirs(Some(value)) };
|
||||
let present = Path::new(directory).join(soname);
|
||||
let verdict = check(DisplaySession::X11, &probe, |path| path == present);
|
||||
assert_eq!(decide(DisplaySession::X11, verdict, || Distro::Debian), Ok(()), "LD_LIBRARY_PATH={value:?}, library at {}", present.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_cache_never_warns_or_fails() {
|
||||
// Issue #1144: Alpine (musl) has no `ldconfig -p`, so a library that exists was reported missing.
|
||||
|
||||
@@ -219,7 +219,7 @@ fn prune_instance_logs(dir: &Path) {
|
||||
// A missing lock file means nobody holds it; an unknown lock state counts as running.
|
||||
let running = match OpenOptions::new().read(true).write(true).open(instance_lock(dir, pid)) {
|
||||
Ok(lock) => !try_hold(&lock).unwrap_or(false),
|
||||
Err(_) => false,
|
||||
Err(e) => e.kind() != std::io::ErrorKind::NotFound,
|
||||
};
|
||||
if !running {
|
||||
let modified = entry.metadata().and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH);
|
||||
@@ -542,6 +542,15 @@ mod tests {
|
||||
let held = File::create(instance_lock(&dir, 5)).expect("lock file");
|
||||
held.try_lock().expect("hold");
|
||||
|
||||
// An older log whose lock cannot be opened has an unknown owner, so keep it too.
|
||||
let unknown = instance_log(&dir, 6);
|
||||
std::fs::write(&unknown, "unknown owner").expect("write");
|
||||
File::options().write(true).open(&unknown).expect("open").set_modified(now - Duration::from_secs(1000)).expect("mtime");
|
||||
let unknown_lock = instance_lock(&dir, 6);
|
||||
std::fs::create_dir(&unknown_lock).expect("unusable lock path");
|
||||
let error = OpenOptions::new().read(true).write(true).open(&unknown_lock).expect_err("a directory is not a lock file");
|
||||
assert_ne!(error.kind(), std::io::ErrorKind::NotFound);
|
||||
|
||||
let second = rotate(&dir).expect("second start");
|
||||
assert_eq!(second.path, instance_log(&dir, std::process::id()));
|
||||
// The newest KEEP finished ones stay, the rest go with their lock files.
|
||||
@@ -549,6 +558,8 @@ mod tests {
|
||||
assert!(!instance_log(&dir, 2).exists() && !instance_log(&dir, 1).exists());
|
||||
assert!(!instance_lock(&dir, 2).exists());
|
||||
assert_eq!(read(&live), "live");
|
||||
assert_eq!(read(&unknown), "unknown owner");
|
||||
assert!(unknown_lock.is_dir());
|
||||
drop((first, second, held));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
+272
-35
@@ -33,13 +33,19 @@ mod app_dirs;
|
||||
mod app_icon;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod apple_events;
|
||||
#[cfg(test)]
|
||||
mod build_channel;
|
||||
mod build_flavor;
|
||||
mod caps_lock;
|
||||
mod crash_guard;
|
||||
mod cursor;
|
||||
mod gpu_startup;
|
||||
mod launch_args;
|
||||
mod launch_profile;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac_window;
|
||||
mod process_identity;
|
||||
mod profile_root;
|
||||
// Pure logic is tested on every platform; only Linux runs the check.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod external_svg;
|
||||
@@ -47,6 +53,7 @@ mod external_svg;
|
||||
mod linux_libs;
|
||||
mod logging;
|
||||
mod monitor_profile;
|
||||
mod nightly_session;
|
||||
mod photoshop_settings;
|
||||
mod presentation;
|
||||
// The print portal needs the session bus (zbus, Linux only); its pure helpers are tested everywhere.
|
||||
@@ -63,11 +70,13 @@ mod ui_state;
|
||||
mod window_frame;
|
||||
|
||||
use photocraft_engine::Session;
|
||||
#[cfg(target_os = "linux")]
|
||||
use photocraft_engine::print_cmds::PrintExt;
|
||||
use photocraft_ui_egui::PhotocraftApp;
|
||||
use photocraft_ui_egui::Prefix;
|
||||
use photocraft_ui_egui::window_policy::{self, Backend, Frame, TitleBarPref};
|
||||
|
||||
use photocraft_ui_egui::os_window::APP_ID;
|
||||
use photocraft_ui_egui::os_window;
|
||||
|
||||
/// The smallest the main window may be, in points.
|
||||
const MIN_WINDOW_SIZE: [f32; 2] = [760.0, 480.0];
|
||||
@@ -81,8 +90,9 @@ fn title_bar_pref(prefs: &photocraft_engine::prefs::Preferences) -> TitleBarPref
|
||||
|
||||
/// The automation roots: `--automation-read-root` / `--automation-write-root` (or their
|
||||
/// variables) win; a direction without one takes Preferences › AI Integrations' folder, and with
|
||||
/// that empty too the default agent folder `Documents/ArtCraft/Agents/PhotoCraft`, created when
|
||||
/// first used (`AgentSettings::folders`). A flag's
|
||||
/// that empty too the channel's default agent folder: stable uses
|
||||
/// `Documents/ArtCraft/Agents/PhotoCraft`; Nightly uses its private profile's `AgentFiles`.
|
||||
/// It is created only when first used (`AgentSettings::folders_with`). A flag's
|
||||
/// root that can't be opened stops the launch (exit status 2) as before. A preference's root that
|
||||
/// can't be opened, or isn't an absolute path (it would depend on the folder the app was started
|
||||
/// from), is left out, so that direction fails closed, and the warning says why: a folder moved
|
||||
@@ -93,7 +103,20 @@ fn automation_workspace(
|
||||
flags: &photocraft_automation::args::AutomationArgs,
|
||||
prefs: &craft::automation::agents::AgentSettings,
|
||||
) -> Result<(photocraft_automation::workspace::AuthorizedWorkspace, Option<String>), photocraft_automation::AutomationError> {
|
||||
automation_workspace_in(flags, prefs, craft::control::agents::default_folder(AGENT_APP_NAME).as_deref())
|
||||
automation_workspace_for_profile(flags, prefs, launch_profile::current(), || craft::control::agents::default_folder(AGENT_APP_NAME))
|
||||
}
|
||||
|
||||
fn automation_workspace_for_profile(
|
||||
flags: &photocraft_automation::args::AutomationArgs,
|
||||
prefs: &craft::automation::agents::AgentSettings,
|
||||
profile: &launch_profile::Profile,
|
||||
stable_default: impl FnOnce() -> Option<std::path::PathBuf>,
|
||||
) -> Result<(photocraft_automation::workspace::AuthorizedWorkspace, Option<String>), photocraft_automation::AutomationError> {
|
||||
let default = match profile.root() {
|
||||
Some(root) => Some(profile_root::agent_directory(root).map_err(photocraft_automation::AutomationError::BadRequest)?),
|
||||
None => stable_default(),
|
||||
};
|
||||
automation_workspace_in(flags, prefs, default.as_deref())
|
||||
}
|
||||
|
||||
/// The app's name in its default agent folder, `Documents/ArtCraft/Agents/PhotoCraft`.
|
||||
@@ -155,14 +178,18 @@ fn control_port_for(cli: Option<u16>, prefs: &photocraft_engine::prefs::Integrat
|
||||
}
|
||||
|
||||
/// The main window: 1440 × 900 (shrunk to fit the monitor, and maximized on the first frame
|
||||
/// when it still doesn't fit, `work_area::fit_window`), centred on the main monitor. Without
|
||||
/// when it still doesn't fit, `embed::before_ui`), centred on the main monitor. Without
|
||||
/// `centered`, Windows cascades each new window from the top-left corner, so it opened at a
|
||||
/// different offset every launch (#419). A later launch restores the saved position instead
|
||||
/// (`main` turns `centered` off, #4826). Wayland compositors place windows themselves.
|
||||
fn native_options(frame: &Frame) -> eframe::NativeOptions {
|
||||
let viewport = egui::ViewportBuilder::default().with_icon(app_icon::viewport_icon(std::env::current_exe().ok().as_deref()));
|
||||
let viewport =
|
||||
viewport.with_app_id(APP_ID).with_title("PhotoCraft").with_inner_size([1440.0, 900.0]).with_min_inner_size(MIN_WINDOW_SIZE).with_drag_and_drop(true);
|
||||
let viewport = viewport
|
||||
.with_app_id(os_window::app_id())
|
||||
.with_title(os_window::name_for(os_window::identity()))
|
||||
.with_inner_size([1440.0, 900.0])
|
||||
.with_min_inner_size(MIN_WINDOW_SIZE)
|
||||
.with_drag_and_drop(true);
|
||||
eframe::NativeOptions {
|
||||
viewport: window_policy::apply(viewport, frame),
|
||||
centered: true,
|
||||
@@ -225,18 +252,19 @@ fn claim_single_instance(
|
||||
mut launch_options: Vec<launch_args::PerProcess>,
|
||||
) -> std::ops::ControlFlow<(), Option<single_instance::Primary>> {
|
||||
use std::ops::ControlFlow::{Break, Continue};
|
||||
let new_instance_env = std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok();
|
||||
let nightly = launch_profile::current().is_nightly();
|
||||
let new_instance_env = if nightly { None } else { std::env::var("PHOTOCRAFT_NEW_INSTANCE").ok() };
|
||||
// A variable documented as the equivalent of a per-launch flag counts as that flag: a
|
||||
// launch that sets only `PHOTOCRAFT_PRESENT_MODE` (say) has per-process options too, so it
|
||||
// keeps its own process instead of handing its files over and being ignored.
|
||||
launch_options.extend_from_slice(&single_instance::env_launch_options());
|
||||
let context = single_instance::LaunchContext {
|
||||
per_user_settings: app_dirs::current().mode == app_dirs::Mode::Platform,
|
||||
new_instance_flag: new_instance,
|
||||
per_user_settings: launch_profile::current().is_nightly() || app_dirs::current().mode == app_dirs::Mode::Platform,
|
||||
new_instance_flag: new_instance && !nightly,
|
||||
new_instance_env: new_instance_env.as_deref(),
|
||||
control,
|
||||
control: control && !nightly,
|
||||
unreadable_paths,
|
||||
launch_options: &launch_options,
|
||||
launch_options: if nightly { &[] } else { &launch_options },
|
||||
};
|
||||
match (single_instance::skip_reason(&context), services::config_dir()) {
|
||||
(Some(reason), _) => {
|
||||
@@ -388,7 +416,82 @@ fn write_start_marker(sentinel: &gpu_startup::SharedSentinel, plan: &gpu_startup
|
||||
}
|
||||
}
|
||||
|
||||
fn initialize_nightly_process_identity() -> Result<(), process_identity::IdentityError> {
|
||||
process_identity::initialize(build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1, os_window::id_for(os_window::LaunchIdentity::NightlyV1))
|
||||
}
|
||||
|
||||
/// Whether a refusal may also open a native message box. Standard error always carries the reason;
|
||||
/// this only adds a box where one renders without the app's event loop. Never on macOS: rfd's alert
|
||||
/// there needs the AppKit run loop this start has not reached, so a refused nightly launch hangs in
|
||||
/// an invisible modal instead of exiting (GridCraft Mac smoke, 2026-11-26). PhotoCraft's own Mac
|
||||
/// smoke passed, so this is preventive here.
|
||||
fn refusal_dialog(flavor: build_flavor::BuildFlavor, desktop_session: bool, macos: bool) -> bool {
|
||||
build_flavor::needs_native_error(flavor, desktop_session) && !macos
|
||||
}
|
||||
|
||||
fn report_launch_profile_error(error: &str) {
|
||||
eprintln!("PhotoCraft launch profile: {error}");
|
||||
let desktop_session = cfg!(windows)
|
||||
|| cfg!(target_os = "macos")
|
||||
|| (cfg!(target_os = "linux") && ["DISPLAY", "WAYLAND_DISPLAY"].into_iter().any(|key| std::env::var_os(key).is_some_and(|v| !v.is_empty())));
|
||||
if refusal_dialog(build_flavor::COMPILED, desktop_session, cfg!(target_os = "macos")) {
|
||||
if let Err(error) = initialize_nightly_process_identity() {
|
||||
eprintln!("PhotoCraft launch profile: {error}");
|
||||
return;
|
||||
}
|
||||
#[cfg(any(windows, target_os = "linux", target_os = "macos"))]
|
||||
let _ = rfd::MessageDialog::new()
|
||||
.set_title("PhotoCraft Nightly")
|
||||
.set_description(error)
|
||||
.set_level(rfd::MessageLevel::Error)
|
||||
.set_buttons(rfd::MessageButtons::Ok)
|
||||
.show();
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the immutable launch profile before any startup service or side effect.
|
||||
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
// The trusted Launcher protocol is decided before logger/crash/update/font/prefs access.
|
||||
let argv: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
|
||||
// --version`: answered before root validation, process identity, IPC or any window.
|
||||
if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
|
||||
use std::io::Write as _;
|
||||
let _ = writeln!(std::io::stdout(), "PhotoCraft {}", build_flavor::version(build_flavor::COMPILED, env!("PHOTOCRAFT_BUILT_VERSION")));
|
||||
return None;
|
||||
}
|
||||
let early = launch_profile::parse_startup(argv, std::env::var_os("PHOTOCRAFT_GPU_STARTUP_FAILURE").is_some())
|
||||
.and_then(|launch| {
|
||||
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
|
||||
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
|
||||
Ok(launch)
|
||||
})
|
||||
.and_then(|launch| {
|
||||
launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref()))
|
||||
})
|
||||
.unwrap_or_else(|error| {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2)
|
||||
});
|
||||
let identity = if early.profile.is_nightly() { os_window::LaunchIdentity::NightlyV1 } else { os_window::LaunchIdentity::Stable };
|
||||
if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) {
|
||||
report_launch_profile_error(&error);
|
||||
std::process::exit(2);
|
||||
}
|
||||
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
/// The allocator on Windows: mimalloc instead of the system heap. The UI builds and frees many small values every
|
||||
/// frame, and the system heap's alloc and free took about 14 % of the UI thread (#15493). Linux keeps glibc, which
|
||||
/// `malloc_tuning` tunes to give closed documents' memory back (#8743); macOS keeps its system allocator.
|
||||
#[cfg(windows)]
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
let Some(arguments) = prepare_launch() else { return Ok(()) };
|
||||
|
||||
// Before anything starts a thread: may re-execute this process with glibc tuned to return
|
||||
// the memory of closed documents (#8743).
|
||||
photocraft_engine::malloc_tuning::apply();
|
||||
@@ -396,7 +499,9 @@ fn main() -> eframe::Result {
|
||||
let logger = logging::install();
|
||||
crash_guard::install_hook();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(done) = craft_update::self_update::finish(&photocraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
|
||||
if !launch_profile::current().is_nightly()
|
||||
&& let Some(done) = craft_update::self_update::finish(&photocraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::<Vec<_>>())
|
||||
{
|
||||
if let Err(e) = done {
|
||||
eprintln!("PhotoCraft update helper failed: {e}");
|
||||
std::process::exit(1);
|
||||
@@ -407,10 +512,10 @@ fn main() -> eframe::Result {
|
||||
// The system font scan can take seconds (minutes on some Macs): run it off the UI thread.
|
||||
photocraft_ui_egui::type_tool::warm_fonts();
|
||||
// `--help` and `--version` print to standard output and exit 0. A usage error (an unknown
|
||||
// option, a missing or bad value, a bad PHOTOCRAFT_CONTROL_PORT: issues #701, #6429, #6431)
|
||||
// option, a missing or bad value, a bad PHOTOCRAFT_CONTROL_PORT for Stable: issues #701, #6429, #6431)
|
||||
// names the argument on standard error and exits 2, so a launcher sees the failure. Neither
|
||||
// panics when the stream is closed or a pipe (`photocraft --help | head -1`).
|
||||
let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit());
|
||||
let launch = launch_args::parse(launch_args::command_for_profile(launch_profile::current().is_nightly()), arguments).unwrap_or_else(|e| e.exit());
|
||||
let launch_args::FileNames { openable: files, unreadable: unreadable_paths } = launch.file_names();
|
||||
let launch_args::LaunchArgs {
|
||||
files: _,
|
||||
@@ -451,7 +556,12 @@ fn main() -> eframe::Result {
|
||||
let _ = (new_instance, &launch_options);
|
||||
|
||||
// Bind and authenticate the authorized control listener before display/GPU initialization.
|
||||
let ControlSetup { control, warning: control_warning } = control_setup(&prefs.integrations, control_port, auth, &automation);
|
||||
let ControlSetup { control, warning: control_warning } = if launch_profile::current().is_nightly() {
|
||||
// No inherited stable token file/Launcher agent switch is consulted by this first protocol.
|
||||
ControlSetup { control: None, warning: None }
|
||||
} else {
|
||||
control_setup(&prefs.integrations, control_port, auth, &automation)
|
||||
};
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
let native_session = linux_libs::session_from_env(|name| std::env::var(name).ok());
|
||||
@@ -549,8 +659,35 @@ fn main() -> eframe::Result {
|
||||
let app_created = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let created_in_callback = app_created.clone();
|
||||
let started_sentinel = sentinel.clone();
|
||||
// After primary IPC claim, before entering the window loop. Stable and secondaries do not
|
||||
// own a Nightly record. No document names, paths or diagnostic payload is collected.
|
||||
let (nightly_session, session_health_warning) = match nightly_session::Session::begin_with_health(
|
||||
launch_profile::current().root(),
|
||||
photocraft_engine::build_info::VERSION,
|
||||
photocraft_engine::build_info::git_sha(),
|
||||
) {
|
||||
Ok(state) => state,
|
||||
Err(error) => {
|
||||
log::warn!("Nightly session health is unavailable: {error}");
|
||||
(None, true)
|
||||
}
|
||||
};
|
||||
let previous_nightly_unclean = nightly_session.as_ref().is_some_and(nightly_session::Session::previous_unclean);
|
||||
// Set once a window has posted the interruption notice; until then the record must survive.
|
||||
let unclean_notice_shown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let notice_shown_in_callback = unclean_notice_shown.clone();
|
||||
let nightly_session: nightly_session::Shared = std::sync::Arc::new(std::sync::Mutex::new(nightly_session));
|
||||
// The app's exit hook is the controlled return on macOS, where every quit ends the process
|
||||
// inside AppKit's terminate (craft::quit) and `run_native` never returns. Elsewhere the
|
||||
// return path below finishes, as before.
|
||||
#[cfg(target_os = "macos")]
|
||||
let finish_at_exit = {
|
||||
let shared = nightly_session.clone();
|
||||
let shown = unclean_notice_shown.clone();
|
||||
move || nightly_session::finish_once(&shared, shown.load(std::sync::atomic::Ordering::Relaxed))
|
||||
};
|
||||
let result = eframe::run_native(
|
||||
"PhotoCraft",
|
||||
os_window::name_for(os_window::identity()),
|
||||
options,
|
||||
Box::new(move |cc| {
|
||||
created_in_callback.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
@@ -575,14 +712,14 @@ fn main() -> eframe::Result {
|
||||
#[cfg(target_os = "linux")]
|
||||
let session = {
|
||||
let mut session = Session::new();
|
||||
session.print_spooler = print_portal::spooler();
|
||||
*session.print_spooler_mut() = print_portal::spooler();
|
||||
session
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let session = Session::new();
|
||||
// Before the first pass: the one install of the craft runtime must see every pass from
|
||||
// the first (R71); the app then runs on that context.
|
||||
PhotocraftApp::setup_window(&cc.egui_ctx, Default::default(), decision);
|
||||
PhotocraftApp::setup_window(&cc.egui_ctx, Default::default(), decision, services::config_dir().as_deref());
|
||||
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), session, services);
|
||||
app.open_suite(&cc.egui_ctx);
|
||||
app.min_frame_ms = uncapped.then_some(1000.0 / 240.0);
|
||||
@@ -681,21 +818,24 @@ fn main() -> eframe::Result {
|
||||
// switch (Settings › AI agents) is the one consent; without it, as before, a Control
|
||||
// Port saved in the preferences. The launch flags (`--control`) manage the connection
|
||||
// for the whole run instead.
|
||||
app.services.agent_switch = Some(craft::automation::agents::AgentSwitch::watch(photocraft_automation::agent_link::LAUNCHER_APP_ID, {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
}));
|
||||
let link = if let Some((listener, token, _)) = control {
|
||||
let host = craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx);
|
||||
let (requests, server) = craft::automation::server::serve(listener, token, host)?;
|
||||
eprintln!("photocraft: control server listening on {}", server.addr);
|
||||
app = app.with_control(requests);
|
||||
craft::automation::agents::AgentLink::from_launch(server)
|
||||
} else {
|
||||
app.services.agent_automation = Some(Box::new(services::agent_automation));
|
||||
craft::automation::agents::AgentLink::new(services::config_dir(), photocraft_engine::build_info::long_version())
|
||||
};
|
||||
app.services.agent_link = Some(link);
|
||||
if !launch_profile::current().is_nightly() {
|
||||
app.services.agent_switch = Some(craft::automation::agents::AgentSwitch::watch(photocraft_automation::agent_link::LAUNCHER_APP_ID, {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
move || ctx.request_repaint()
|
||||
}));
|
||||
let link = if let Some((listener, token, _)) = control {
|
||||
let host = craft::ui::runtime::windows::WindowHost::of(&cc.egui_ctx);
|
||||
let (requests, server) = craft::automation::server::serve(listener, token, host)?;
|
||||
eprintln!("photocraft: control server listening on {}", server.addr);
|
||||
app = app.with_control(requests);
|
||||
craft::automation::agents::AgentLink::from_launch(server)
|
||||
} else {
|
||||
app.services.agent_automation = Some(Box::new(services::agent_automation));
|
||||
craft::automation::agents::AgentLink::new(services::config_dir(), photocraft_engine::build_info::long_version())
|
||||
};
|
||||
app.services.agent_link = Some(link);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
app.services.os_events = Some(apple_events.connect(&cc.egui_ctx));
|
||||
@@ -713,6 +853,8 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
// Where file drags and drops are (winit 0.30 doesn't say).
|
||||
app.services.cursor_pos = cursor::service(cc);
|
||||
// The physical primary button: it ends a floating document window's OS move by its title bar (#16415).
|
||||
app.services.primary_down = cursor::primary_down_service();
|
||||
// The custom title bar's undecorated window must stay borderless, or its caption and
|
||||
// border offset the content and the pointer on some Windows systems (#2246).
|
||||
app.services.window_frame = window_frame::service(cc, integrated_frame);
|
||||
@@ -750,6 +892,30 @@ fn main() -> eframe::Result {
|
||||
let lines = unreadable_paths.iter().map(|p| i18n::fmt(line, &[("path", p.as_str())])).collect();
|
||||
photocraft_ui_egui::notices::post(&mut app, i18n::t("Could not open"), lines, craft::theme::variant::Tone::Bad, None);
|
||||
}
|
||||
if previous_nightly_unclean || session_health_warning {
|
||||
use photocraft_ui_egui::i18n;
|
||||
let message = if previous_nightly_unclean {
|
||||
i18n::t(
|
||||
"The previous PhotoCraft Nightly session did not finish normally. You can report a problem from About. No diagnostics have been sent.",
|
||||
)
|
||||
} else {
|
||||
i18n::t(
|
||||
"PhotoCraft Nightly could not record session health in its private profile. You can still edit, but abnormal-exit detection is unavailable.",
|
||||
)
|
||||
};
|
||||
photocraft_ui_egui::notices::post(
|
||||
&mut app,
|
||||
i18n::t("PhotoCraft Nightly"),
|
||||
vec![message.to_owned()],
|
||||
craft::theme::variant::Tone::Neutral,
|
||||
None,
|
||||
);
|
||||
notice_shown_in_callback.store(previous_nightly_unclean, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
app.services.at_exit = Some(Box::new(finish_at_exit));
|
||||
}
|
||||
// Portable marker found but its data folder isn't writable (#228): say where settings went.
|
||||
if let Some(w) = &app_dirs::current().warning {
|
||||
photocraft_ui_egui::notices::post(&mut app, "Portable mode is off", vec![w.clone()], craft::theme::variant::Tone::Neutral, None);
|
||||
@@ -762,6 +928,12 @@ fn main() -> eframe::Result {
|
||||
Ok(app)
|
||||
}),
|
||||
);
|
||||
// This is a controlled return, even for a handled startup error or CPU relaunch. Release
|
||||
// health ownership BEFORE primary IPC, so a successor never observes a stale busy owner.
|
||||
// A renderer failure before the window (and so before the CPU retry) has not shown an
|
||||
// earlier interruption: keep that record so the retry, or the next start, still reports it.
|
||||
// On macOS a window that was created has already finished in its exit hook; this is then a no-op.
|
||||
nightly_session::finish_once(&nightly_session, unclean_notice_shown.load(std::sync::atomic::Ordering::Relaxed));
|
||||
// The window is gone: refuse further files and free the lock, so a launch that is waiting (or
|
||||
// the CPU-compatibility relaunch below) becomes the primary instead of handing its files to a
|
||||
// process that is exiting.
|
||||
@@ -838,6 +1010,8 @@ pub(crate) fn no_child_spawns() -> std::sync::RwLockWriteGuard<'static, ()> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use photocraft_engine::prefs::SavedPrefsExt;
|
||||
|
||||
/// Schema-probe `ui.ron` shapes *reconstructed* from the documented 0.14/0.15/0.37 layouts,
|
||||
/// not recorded machine saves: 0.14 and 0.15 both store the flat window entry, which the
|
||||
/// first 0.37 launch rewrites; a 0.37 file is left alone. Keeping all three probes makes a
|
||||
@@ -1094,6 +1268,55 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_agent_workspace_uses_its_private_profile_not_stable_documents() {
|
||||
let dir = temp_dir("nightly-agent-roots");
|
||||
let private = dir.join("nightly profile");
|
||||
let stable = dir.join("redirected Documents/ArtCraft/Agents/PhotoCraft");
|
||||
std::fs::create_dir_all(&private).unwrap();
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("existing-document"), b"stable document bytes").unwrap();
|
||||
let profile = super::launch_profile::Profile::NightlyV1(private.clone());
|
||||
let (ws, warning) = super::automation_workspace_for_profile(&flags(None, None), &craft::automation::agents::AgentSettings::default(), &profile, || {
|
||||
panic!("Nightly must never consult the stable agent-folder fallback")
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(warning, None);
|
||||
let canonical_private = std::fs::canonicalize(&private).unwrap();
|
||||
assert!(ws.read_folders().iter().all(|p| p.starts_with(&canonical_private)));
|
||||
assert!(ws.write_folder().unwrap().starts_with(&canonical_private));
|
||||
ws.write("nightly-document", b"nightly document bytes").unwrap();
|
||||
assert_eq!(ws.read("nightly-document").unwrap(), b"nightly document bytes");
|
||||
assert_eq!(std::fs::read(stable.join("existing-document")).unwrap(), b"stable document bytes");
|
||||
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
|
||||
drop(ws);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_agent_workspace_preserves_the_resolved_default_folder() {
|
||||
let dir = temp_dir("stable-agent-roots");
|
||||
let stable = dir.join("redirected Documents/ArtCraft/Agents/PhotoCraft");
|
||||
let (ws, warning) = super::automation_workspace_for_profile(
|
||||
&flags(None, None),
|
||||
&craft::automation::agents::AgentSettings::default(),
|
||||
&super::launch_profile::Profile::Stable,
|
||||
|| Some(stable.clone()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(warning, None);
|
||||
// These accessors preserve the configured spelling, not Windows' canonical
|
||||
// verbatim prefix or expanded short names. The held capability still opens it.
|
||||
assert_eq!(ws.read_folders(), vec![stable.clone()]);
|
||||
assert_eq!(ws.write_folder(), Some(stable.clone()));
|
||||
ws.write("stable-document", b"stable document bytes").unwrap();
|
||||
assert_eq!(std::fs::read(stable.join("stable-document")).unwrap(), b"stable document bytes");
|
||||
assert_eq!(ws.read("stable-document").unwrap(), b"stable document bytes");
|
||||
assert_eq!(ws.read_with_save_path("stable-document").unwrap().1.as_deref(), Some("stable-document"));
|
||||
drop(ws);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Empty preferences fall back to the default agent folder, created when first used, for
|
||||
/// both directions (one shared capability); a flag or the person's own folder still wins.
|
||||
#[test]
|
||||
@@ -1173,7 +1396,7 @@ mod tests {
|
||||
fn the_desktop_entry_names_the_window_class() {
|
||||
let entry = include_str!("../../../packaging/linux/ai.storyteller.photocraft.desktop");
|
||||
let class = entry.lines().find_map(|line| line.strip_prefix("StartupWMClass="));
|
||||
assert_eq!(class, Some(super::APP_ID));
|
||||
assert_eq!(class, Some(super::os_window::APP_ID));
|
||||
}
|
||||
|
||||
/// Both flatpak manifests build with the craft-i18n commit `craft-i18n.rev` pins: CI and
|
||||
@@ -1196,3 +1419,17 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod refusal_dialog_tests {
|
||||
use super::refusal_dialog;
|
||||
use crate::build_flavor::BuildFlavor;
|
||||
|
||||
#[test]
|
||||
fn a_refusal_never_blocks_on_a_modal_before_the_event_loop_on_macos() {
|
||||
assert!(refusal_dialog(BuildFlavor::NightlyV1, true, false), "a desktop refusal still shows the box where one renders");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, true, true), "macOS has no run loop yet: the modal would hang");
|
||||
assert!(!refusal_dialog(BuildFlavor::NightlyV1, false, false), "a headless session has no box");
|
||||
assert!(!refusal_dialog(BuildFlavor::Stable, true, false), "only a nightly refusal explains itself in a box");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
//! App-private Nightly session health, not telemetry or a Launcher protocol.
|
||||
//! A live owner holds a separate persistent lease; secondary launches never rewrite its record.
|
||||
//! Dropping the guard does not clear the marker. Only the app's controlled return path does.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
const RECORD: &str = "nightly-session.json";
|
||||
const LEASE: &str = "nightly-session.lock";
|
||||
const MAX_METADATA_BYTES: usize = 256;
|
||||
|
||||
pub struct Session {
|
||||
_lease: File,
|
||||
path: PathBuf,
|
||||
own_record: Vec<u8>,
|
||||
previous_unclean: bool,
|
||||
}
|
||||
|
||||
fn regular_or_missing(path: &Path) -> io::Result<bool> {
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) if metadata.file_type().is_file() && !metadata.file_type().is_symlink() => Ok(true),
|
||||
Ok(_) => Err(io::Error::other("Nightly session state must be a regular file, not an alias or directory")),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// The owner's session, shared by the app's exit hook (macOS) and the code after the event loop.
|
||||
/// On macOS every quit ends the process inside AppKit's terminate, after eframe's `on_exit` and
|
||||
/// before `eframe::run_native` could return, so the exit hook finishes it there; the return path
|
||||
/// still runs for a start that created no window.
|
||||
pub type Shared = Arc<Mutex<Option<Session>>>;
|
||||
|
||||
/// The controlled return ([`Session::finish`]) by whichever path comes first; later calls do nothing.
|
||||
pub fn finish_once(shared: &Shared, unclean_notice_shown: bool) {
|
||||
let watch = shared.lock().unwrap_or_else(PoisonError::into_inner).take();
|
||||
if let Some(watch) = watch
|
||||
&& let Err(error) = watch.finish(unclean_notice_shown)
|
||||
{
|
||||
log::warn!("Nightly session state was left intact: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The warning belongs to this window: a busy secondary has no health-record coverage,
|
||||
/// while Stable and a lease-owning Nightly window preserve their existing result.
|
||||
pub fn begin_with_health(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<(Option<Self>, bool)> {
|
||||
let watch = Self::begin(root, version, commit)?;
|
||||
let unavailable = root.is_some() && watch.is_none();
|
||||
Ok((watch, unavailable))
|
||||
}
|
||||
|
||||
/// `None` is stable or another owner of this profile. Neither case touches the record.
|
||||
/// The supplied root must already be the validated private Nightly profile.
|
||||
pub fn begin(root: Option<&Path>, version: &str, commit: Option<&str>) -> io::Result<Option<Self>> {
|
||||
let Some(root) = root else { return Ok(None) };
|
||||
if version.is_empty() || version.len() > MAX_METADATA_BYTES || commit.is_some_and(|value| value.len() > MAX_METADATA_BYTES) {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Nightly session provenance is missing or too large"));
|
||||
}
|
||||
let lease_path = root.join(LEASE);
|
||||
regular_or_missing(&lease_path)?;
|
||||
let lease = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lease_path)?;
|
||||
match lease.try_lock() {
|
||||
Ok(()) => {}
|
||||
Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
|
||||
Err(std::fs::TryLockError::Error(error)) => return Err(error),
|
||||
}
|
||||
let path = root.join(RECORD);
|
||||
let previous_unclean = regular_or_missing(&path)?;
|
||||
let own_record = serde_json::to_vec(&serde_json::json!({
|
||||
"schema_version": 1,
|
||||
"channel": "nightly-v1",
|
||||
"version": version,
|
||||
"commit": commit.filter(|value| !value.is_empty()),
|
||||
}))?;
|
||||
// The app already uses this durable writer; a raced destination link is replaced, not followed.
|
||||
photocraft_format::atomic_write_no_follow(&path, &own_record)?;
|
||||
Ok(Some(Self { _lease: lease, path, own_record, previous_unclean }))
|
||||
}
|
||||
|
||||
pub fn previous_unclean(&self) -> bool {
|
||||
self.previous_unclean
|
||||
}
|
||||
|
||||
/// Controlled return. If an earlier session's interruption was detected but no window showed
|
||||
/// it yet (a renderer failure before the app callback, including the CPU-retry handoff), the
|
||||
/// record is left for the next owner to report; otherwise this is [`Self::complete`].
|
||||
pub fn finish(self, unclean_notice_shown: bool) -> io::Result<()> {
|
||||
if self.previous_unclean && !unclean_notice_shown {
|
||||
return Ok(());
|
||||
}
|
||||
self.complete()
|
||||
}
|
||||
|
||||
/// Controlled event-loop completion includes a handled startup error/CPU handoff, not only
|
||||
/// exit0. Clear before releasing primary IPC so a successor cannot miss record ownership.
|
||||
/// An unwind, abort, forced exit or killed process never calls this method.
|
||||
pub fn complete(self) -> io::Result<()> {
|
||||
if !regular_or_missing(&self.path)? {
|
||||
return Ok(());
|
||||
}
|
||||
let mut current = Vec::new();
|
||||
File::open(&self.path)?.take(self.own_record.len() as u64 + 1).read_to_end(&mut current)?;
|
||||
if current != self.own_record {
|
||||
return Err(io::Error::other("Nightly session state changed; leaving it intact"));
|
||||
}
|
||||
std::fs::remove_file(&self.path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
loop {
|
||||
let path = std::env::temp_dir().join(format!("photo-nightly-session-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&path) {
|
||||
Ok(()) => return Self(path),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn busy_secondary_reports_unavailable_without_replacing_the_owner_record() {
|
||||
let _no_spawns = crate::no_child_spawns();
|
||||
let fixture = Fixture::new();
|
||||
let (stable, warning) = Session::begin_with_health(None, "stable", None).unwrap();
|
||||
assert!(stable.is_none() && !warning);
|
||||
let (first, warning) = Session::begin_with_health(Some(&fixture.0), "nightly", Some("owned-commit")).unwrap();
|
||||
assert!(!warning);
|
||||
let first = first.unwrap();
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
let (secondary, warning) = Session::begin_with_health(Some(&fixture.0), "secondary", None).unwrap();
|
||||
assert!(secondary.is_none() && warning, "a secondary window cannot claim recorded exit/crash coverage");
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record);
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controlled_completion_is_clean_but_an_unfinished_owner_is_reported_next_time() {
|
||||
let _no_spawns = crate::no_child_spawns();
|
||||
let fixture = Fixture::new();
|
||||
let first = Session::begin(Some(&fixture.0), "first", Some("recorded-commit")).unwrap().unwrap();
|
||||
assert!(!first.previous_unclean());
|
||||
let own = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "secondary", None).unwrap().is_none());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), own, "a busy secondary must not replace the owner's record");
|
||||
first.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
let unfinished = Session::begin(Some(&fixture.0), "second", None).unwrap().unwrap();
|
||||
assert!(!unfinished.previous_unclean());
|
||||
drop(unfinished); // Unwind/abnormal-path ownership release, not a controlled completion.
|
||||
let next = Session::begin(Some(&fixture.0), "third", None).unwrap().unwrap();
|
||||
assert!(next.previous_unclean());
|
||||
next.complete().unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interruption_no_window_showed_survives_a_handled_startup_failure() {
|
||||
let _no_spawns = crate::no_child_spawns();
|
||||
let fixture = Fixture::new();
|
||||
drop(Session::begin(Some(&fixture.0), "crashed", None).unwrap().unwrap());
|
||||
// Renderer initialization failed before the app callback: no notice was shown.
|
||||
let failed = Session::begin(Some(&fixture.0), "gpu-failed", None).unwrap().unwrap();
|
||||
assert!(failed.previous_unclean());
|
||||
failed.finish(false).unwrap();
|
||||
// The CPU retry (or the next start) still sees the interruption and shows it.
|
||||
let retry = Session::begin(Some(&fixture.0), "cpu-retry", None).unwrap().unwrap();
|
||||
assert!(retry.previous_unclean());
|
||||
retry.finish(true).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a session that showed the notice clears its record");
|
||||
// Without an earlier interruption, a handled failure still clears normally.
|
||||
let clean = Session::begin(Some(&fixture.0), "clean", None).unwrap().unwrap();
|
||||
assert!(!clean.previous_unclean());
|
||||
clean.finish(false).unwrap();
|
||||
assert!(!fixture.0.join(RECORD).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_hook_and_the_return_path_finish_the_session_once() {
|
||||
let _no_spawns = crate::no_child_spawns();
|
||||
let fixture = Fixture::new();
|
||||
let shared: Shared = Arc::new(Mutex::new(Session::begin(Some(&fixture.0), "quitting", None).unwrap()));
|
||||
// The exit hook (macOS quit: the only path that runs there).
|
||||
finish_once(&shared, false);
|
||||
assert!(!fixture.0.join(RECORD).exists(), "a quit that ran the exit hook is a clean exit");
|
||||
// Elsewhere the return path runs too, by then possibly after a successor took the profile.
|
||||
let successor = Session::begin(Some(&fixture.0), "successor", None).unwrap().unwrap();
|
||||
assert!(!successor.previous_unclean());
|
||||
let record = std::fs::read(fixture.0.join(RECORD)).unwrap();
|
||||
finish_once(&shared, false);
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), record, "the second finish must not touch a successor's record");
|
||||
successor.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_never_removes_an_unknown_changed_record() {
|
||||
let _no_spawns = crate::no_child_spawns();
|
||||
let fixture = Fixture::new();
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
std::fs::write(fixture.0.join(RECORD), b"replacement owned by someone else").unwrap();
|
||||
assert!(watch.complete().is_err());
|
||||
assert_eq!(std::fs::read(fixture.0.join(RECORD)).unwrap(), b"replacement owned by someone else");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provenance_is_bounded_and_never_collects_documents_paths_or_diagnostics() {
|
||||
let _no_spawns = crate::no_child_spawns();
|
||||
let fixture = Fixture::new();
|
||||
assert!(Session::begin(Some(&fixture.0), &"x".repeat(MAX_METADATA_BYTES + 1), None).is_err());
|
||||
assert_eq!(std::fs::read_dir(&fixture.0).unwrap().count(), 0);
|
||||
assert!(Session::begin(None, "", None).unwrap().is_none(), "stable has no session-health side effects");
|
||||
let watch = Session::begin(Some(&fixture.0), "nightly", None).unwrap().unwrap();
|
||||
let data: serde_json::Value = serde_json::from_slice(&std::fs::read(fixture.0.join(RECORD)).unwrap()).unwrap();
|
||||
let fields = data.as_object().unwrap().keys().map(String::as_str).collect::<std::collections::BTreeSet<_>>();
|
||||
assert_eq!(fields, ["schema_version", "channel", "version", "commit"].into_iter().collect());
|
||||
assert!(data["commit"].is_null(), "missing provenance must not be invented");
|
||||
watch.complete().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn reserved_state_aliases_do_not_modify_external_files() {
|
||||
let _no_spawns = crate::no_child_spawns();
|
||||
let fixture = Fixture::new();
|
||||
let external = fixture.0.join("stable-document");
|
||||
std::fs::write(&external, b"stable bytes").unwrap();
|
||||
for name in [LEASE, RECORD] {
|
||||
let alias = fixture.0.join(name);
|
||||
std::os::unix::fs::symlink(&external, &alias).unwrap();
|
||||
assert!(Session::begin(Some(&fixture.0), "nightly", None).is_err());
|
||||
assert_eq!(std::fs::read(&external).unwrap(), b"stable bytes");
|
||||
std::fs::remove_file(alias).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Set the immutable nightly Windows identity before any native window or COM service.
|
||||
//! Stable deliberately leaves its implicit shortcut/path identity unchanged.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
#[derive(Clone, Debug, thiserror::Error)]
|
||||
pub enum IdentityError {
|
||||
#[error("{0}")]
|
||||
Configuration(String),
|
||||
}
|
||||
|
||||
pub fn initialize(nightly: bool, app_id: &str) -> Result<(), IdentityError> {
|
||||
configure(nightly && cfg!(windows), app_id, |id| {
|
||||
static RESULT: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
RESULT
|
||||
.get_or_init(|| {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
winsafe::SetCurrentProcessExplicitAppUserModelID(id).map_err(|error| format!("cannot set the nightly Windows identity: {error}"))?;
|
||||
let actual = winsafe::GetCurrentProcessExplicitAppUserModelID()
|
||||
.map_err(|error| format!("cannot read back the nightly Windows identity: {error}"))?;
|
||||
if actual != id {
|
||||
return Err("the native Windows identity did not match the selected nightly channel".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = id;
|
||||
Ok(())
|
||||
}
|
||||
})
|
||||
.clone()
|
||||
})
|
||||
.map_err(IdentityError::Configuration)
|
||||
}
|
||||
|
||||
fn configure(explicit_nightly: bool, app_id: &str, set: impl FnOnce(&str) -> Result<(), String>) -> Result<(), String> {
|
||||
if explicit_nightly { set(app_id) } else { Ok(()) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn stable_does_not_call_the_explicit_identity_api() {
|
||||
configure(false, "nightly-id", |_| panic!("stable identity must remain implicit")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_applies_the_supplied_identity_once() {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
configure(true, "nightly-id", |id| {
|
||||
assert_eq!(id, "nightly-id");
|
||||
calls.set(calls.get() + 1);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_identity_failure_is_returned_instead_of_starting_a_window() {
|
||||
let started = std::cell::Cell::new(false);
|
||||
let result = configure(true, "nightly-id", |_| Err("native identity refused".into())).map(|()| started.set(true));
|
||||
assert_eq!(result.unwrap_err(), "native identity refused");
|
||||
assert!(!started.get());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,708 @@
|
||||
//! App-owned nightly profile fences; no stable fallback, migration or process environment changes.
|
||||
|
||||
use std::ffi::OsString;
|
||||
|
||||
use photocraft_automation::app_dirs::{PORTABLE_DATA_DIR, portable_marker};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
Linux,
|
||||
Mac,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn current() -> Result<Self, String> {
|
||||
match std::env::consts::OS {
|
||||
"windows" => Ok(Self::Windows),
|
||||
"linux" => Ok(Self::Linux),
|
||||
"macos" => Ok(Self::Mac),
|
||||
_ => Err("nightly-v1 is not defined for this operating system".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn ignores_case(self) -> bool {
|
||||
self != Self::Linux
|
||||
}
|
||||
}
|
||||
|
||||
fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
|
||||
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
|
||||
return Err(format!("{label} must be absolute and contain no parent traversal"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
|
||||
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
|
||||
absolute(PathBuf::from(value), key)
|
||||
}
|
||||
|
||||
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
|
||||
match env(key).filter(|v| !v.is_empty()) {
|
||||
Some(value) => absolute(PathBuf::from(value), key),
|
||||
None => Ok(required_base(env, "HOME")?.join(fallback)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve existing ancestors before creating anything. A dangling link or inaccessible ancestor
|
||||
/// is not a missing directory that may be replaced or followed later.
|
||||
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
|
||||
let mut parent = path;
|
||||
let mut missing = Vec::new();
|
||||
loop {
|
||||
match std::fs::symlink_metadata(parent) {
|
||||
Ok(_) => break,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string());
|
||||
parent = parent.parent().ok_or("the profile root has no existing ancestor")?;
|
||||
}
|
||||
Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")),
|
||||
}
|
||||
}
|
||||
let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?;
|
||||
for part in missing.into_iter().rev() {
|
||||
resolved.push(part);
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
|
||||
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
|
||||
let parts = |p: &Path| {
|
||||
p.components()
|
||||
.map(|c| {
|
||||
let value = c.as_os_str().to_string_lossy().into_owned();
|
||||
if platform.ignores_case() { value.to_lowercase() } else { value }
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
a.starts_with(&b) || b.starts_with(&a)
|
||||
}
|
||||
|
||||
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
|
||||
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
|
||||
if platform == Platform::Mac {
|
||||
// A profile in Resources is still inside the versioned install, not beside MacOS.
|
||||
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
|
||||
return Ok(bundle.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(parent.to_path_buf())
|
||||
}
|
||||
|
||||
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let mut roots = match platform {
|
||||
Platform::Windows => {
|
||||
let mut roots =
|
||||
["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join("Photocraft"))).collect::<Result<Vec<_>, _>>()?;
|
||||
// The MSI's default per-user and per-machine folders (install-policy.wxi). A custom
|
||||
// install folder is not known here; the executable's own folder is fenced below.
|
||||
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("PhotoCraft"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
|
||||
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("PhotoCraft"));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
Platform::Linux => {
|
||||
let mut roots =
|
||||
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
|
||||
.into_iter()
|
||||
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("photocraft")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
roots.extend(["/usr/bin/photocraft", "/usr/local/bin/photocraft", "/opt/photocraft"].map(PathBuf::from));
|
||||
// The stable Flatpak keeps its data in its own per-app folder.
|
||||
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.photocraft"));
|
||||
roots
|
||||
}
|
||||
Platform::Mac => {
|
||||
let home = required_base(env, "HOME")?;
|
||||
let library = home.join("Library");
|
||||
vec![
|
||||
library.join("Application Support/Photocraft"),
|
||||
library.join("Caches/Photocraft"),
|
||||
library.join("Caches/ai.storyteller.photocraft"),
|
||||
library.join("Preferences/Photocraft"),
|
||||
library.join("Preferences/ai.storyteller.photocraft.plist"),
|
||||
library.join("Saved Application State/ai.storyteller.photocraft.savedState"),
|
||||
home.join("Applications/PhotoCraft.app"),
|
||||
PathBuf::from("/Applications/PhotoCraft.app"),
|
||||
]
|
||||
}
|
||||
};
|
||||
roots.push(installation_boundary(platform, exe)?);
|
||||
roots.into_iter().map(|p| canonical_future(&p)).collect()
|
||||
}
|
||||
|
||||
/// The nightly fallback for files made by agents. Resolving it never creates a directory and
|
||||
/// never falls back to the stable Documents folder. The SDK creates it lazily if a default is
|
||||
/// actually needed; explicit user-chosen document roots keep their existing semantics.
|
||||
pub fn agent_directory(root: &Path) -> Result<PathBuf, String> {
|
||||
private_subdirectory(root, "AgentFiles", "default agent folder")
|
||||
}
|
||||
|
||||
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
|
||||
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
|
||||
let child = canonical_future(&chosen.join(name))?;
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
/// Every existing entry directly in the profile (Presets, logs, settings and so on) must resolve
|
||||
/// inside it, so a link there cannot point Nightly's writes at another app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Recognise the shared portable data namespace in both the supplied and resolved path.
|
||||
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
|
||||
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
|
||||
// A folder under a portable copy belongs to that copy too. Above the chosen folder itself, a
|
||||
// marker only counts beside a PhotoCraft executable, so an unrelated portable.txt higher up
|
||||
// (in a user folder or at a drive root) does not refuse the profile.
|
||||
path.ancestors().enumerate().any(|(depth, ancestor)| {
|
||||
portable_marker(ancestor).is_some() && (depth == 0 || ["photocraft.exe", "photocraft"].iter().any(|exe| ancestor.join(exe).is_file()))
|
||||
}) || path.components().any(|component| match component {
|
||||
Component::Normal(name) if platform.ignores_case() => name.to_string_lossy().eq_ignore_ascii_case(PORTABLE_DATA_DIR),
|
||||
Component::Normal(name) => name == PORTABLE_DATA_DIR,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The writable hook is the app's existing exclusive probe. Keeping it injected lets filesystem
|
||||
/// boundary tests exercise the real policy without starting the app or changing global state.
|
||||
pub fn validate(
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
stable_agent: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
validate_for(Platform::current()?, root, env, exe, stable_agent, writable)
|
||||
}
|
||||
|
||||
fn validate_for(
|
||||
platform: Platform,
|
||||
root: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
exe: Option<&Path>,
|
||||
stable_agent: Option<&Path>,
|
||||
writable: impl FnOnce(&Path) -> std::io::Result<()>,
|
||||
) -> Result<PathBuf, String> {
|
||||
absolute(root.to_path_buf(), "the nightly profile root")?;
|
||||
if env("PHOTOCRAFT_CONFIG_DIR").is_some_and(|v| !v.is_empty()) {
|
||||
return Err("nightly-v1 cannot be combined with PHOTOCRAFT_CONFIG_DIR".into());
|
||||
}
|
||||
if platform != Platform::Windows && env("FLATPAK_ID").is_some_and(|v| !v.is_empty()) {
|
||||
// These rows are native tar/app-bundle launches, not a Flatpak package. Inheriting its
|
||||
// runtime socket namespace could point another profile at the stable app's socket.
|
||||
return Err("nightly-v1 native packages cannot inherit a Flatpak instance; launch through the native Launcher".into());
|
||||
}
|
||||
let chosen = canonical_future(root)?;
|
||||
if is_portable_layout(root, platform) || is_portable_layout(&chosen, platform) {
|
||||
return Err("the nightly root must not use a portable PhotoCraft installation or its PhotoCraftData settings folder".into());
|
||||
}
|
||||
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
|
||||
let mut forbidden = forbidden_roots(platform, &env, &exe)?;
|
||||
if let Some(agent) = stable_agent {
|
||||
// Use the SDK-resolved Documents/known-folder location, including redirected Documents.
|
||||
// Do not reconstruct it from HOME or create it just to establish the boundary.
|
||||
forbidden.push(canonical_future(&absolute(agent.to_path_buf(), "the stable default agent folder")?)?);
|
||||
}
|
||||
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
|
||||
return Err("the nightly root must not overlap stable data or an installation".into());
|
||||
}
|
||||
// Existing aliases under the profile must not redirect the default agent workspace elsewhere.
|
||||
agent_directory(&chosen)?;
|
||||
entries_stay_inside(&chosen)?;
|
||||
// Recovery can read, adopt, overwrite and sweep entries. Never let its alias leave this
|
||||
// private profile, including toward a Stable portable directory not in our known roots.
|
||||
private_subdirectory(&chosen, "Recovery", "recovery folder")?;
|
||||
let mut create = std::fs::DirBuilder::new();
|
||||
create.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt as _;
|
||||
create.mode(0o700);
|
||||
}
|
||||
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
|
||||
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
|
||||
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
|
||||
return Err("the nightly profile changed while it was being validated".into());
|
||||
}
|
||||
agent_directory(&confirmed)?;
|
||||
private_subdirectory(&confirmed, "Recovery", "recovery folder")?;
|
||||
entries_stay_inside(&confirmed)?;
|
||||
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
|
||||
Ok(confirmed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
env: BTreeMap<String, OsString>,
|
||||
exe: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = loop {
|
||||
let candidate = std::env::temp_dir().join(format!("photocraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
match std::fs::create_dir(&candidate) {
|
||||
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("cannot create owned fixture: {error}"),
|
||||
}
|
||||
};
|
||||
let home = root.join("home");
|
||||
let exe = root.join("install/photocraft");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&exe, b"fixture executable, never run").unwrap();
|
||||
let env = [("HOME", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into_os_string()))
|
||||
.collect();
|
||||
Self { root, env, exe }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<OsString> {
|
||||
self.env.get(key).cloned()
|
||||
}
|
||||
|
||||
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
|
||||
validate_for(
|
||||
platform,
|
||||
root,
|
||||
|key| self.get(key),
|
||||
Some(&self.exe),
|
||||
None,
|
||||
|dir| {
|
||||
let probe = dir.join("exclusive-test-probe");
|
||||
let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?;
|
||||
drop(file);
|
||||
std::fs::remove_file(probe)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn home(&self) -> PathBuf {
|
||||
PathBuf::from(self.get("HOME").unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
// Only the directory successfully created by this fixture is owned for removal.
|
||||
std::fs::remove_dir_all(&self.root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_settings_from_another_install_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let stable_install = fixture.root.join("stable portable install");
|
||||
let stable_data = stable_install.join(photocraft_automation::app_dirs::PORTABLE_DATA_DIR);
|
||||
std::fs::create_dir_all(&stable_data).unwrap();
|
||||
std::fs::write(stable_install.join("portable.txt"), b"owned portable fixture").unwrap();
|
||||
std::fs::write(stable_data.join("settings.json"), b"stable settings must not change").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for candidate in [&stable_data, &stable_data.join("nested nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
None,
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "a different portable install is not a private Nightly profile");
|
||||
assert!(!probed.get(), "reject portable data before a writable probe");
|
||||
assert!(!stable_data.join("nested nightly").exists());
|
||||
assert_eq!(std::fs::read(stable_data.join("settings.json")).unwrap(), b"stable settings must not change");
|
||||
assert_eq!(std::fs::read_dir(&stable_data).unwrap().count(), 1);
|
||||
}
|
||||
}
|
||||
let private = fixture.root.join("PhotoCraftData-backup-name/nightly");
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "a merely similar name is not a portable settings component");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_aliases_cannot_redirect_to_stable_missing_or_profile_root_data() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".local/state/photocraft/Recovery");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-autosave"), b"stable recovery bytes").unwrap();
|
||||
for (index, target) in [stable.clone(), fixture.root.join("missing recovery target")].into_iter().enumerate() {
|
||||
let private = fixture.root.join(format!("nightly-{index}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&target, private.join("Recovery")).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
None,
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "Recovery must not escape the private profile or follow a dangling alias");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-self");
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&private, private.join("Recovery")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_err(), "Recovery cannot treat all profile settings as recovery entries");
|
||||
assert_eq!(std::fs::read(stable.join("stable-autosave")).unwrap(), b"stable recovery bytes");
|
||||
assert_eq!(std::fs::read_dir(stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recovery_alias_to_a_private_subfolder_keeps_the_profile_usable() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.root.join("nightly-private");
|
||||
let recovery = private.join("private-recovery");
|
||||
std::fs::create_dir_all(&recovery).unwrap();
|
||||
std::os::unix::fs::symlink(&recovery, private.join("Recovery")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok());
|
||||
assert_eq!(std::fs::canonicalize(private.join("Recovery")).unwrap(), recovery);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_default_is_private_lazy_and_preserves_stable_documents() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join("Documents/ArtCraft/Agents/PhotoCraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("existing-document"), b"stable document bytes").unwrap();
|
||||
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly-profile")).unwrap();
|
||||
let agent = agent_directory(&private).unwrap();
|
||||
assert!(agent.starts_with(&private) && agent != private);
|
||||
assert!(!agent.exists(), "resolving the fallback must not create it before use");
|
||||
std::fs::create_dir_all(&agent).unwrap();
|
||||
std::fs::write(agent.join("new-document"), b"nightly document bytes").unwrap();
|
||||
assert_eq!(std::fs::read(stable.join("existing-document")).unwrap(), b"stable document bytes");
|
||||
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
|
||||
assert_eq!(std::fs::read(agent.join("new-document")).unwrap(), b"nightly document bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stable_agent_known_folder_and_overlaps_refuse_before_writable_probe() {
|
||||
let fixture = Fixture::new();
|
||||
// Models redirected Documents/known folders: not assumed to be beneath HOME.
|
||||
let stable = fixture.root.join("redirected documents/ArtCraft/Agents/PhotoCraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("existing-document"), b"stable document bytes").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for root in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
&root,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
Some(&stable),
|
||||
|_| {
|
||||
calls.set(calls.get() + 1);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("overlap"));
|
||||
assert_eq!(calls.get(), 0);
|
||||
}
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("existing-document")).unwrap(), b"stable document bytes");
|
||||
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn agent_default_rejects_existing_and_dangling_escape_aliases_before_writes() {
|
||||
let fixture = Fixture::new();
|
||||
let private = fixture.home().join("nightly-profile");
|
||||
let outside = fixture.home().join("stable-agent-files");
|
||||
std::fs::create_dir_all(&private).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(outside.join("existing-document"), b"stable document bytes").unwrap();
|
||||
for target in [&outside, &outside.join("missing")] {
|
||||
let alias = private.join("AgentFiles");
|
||||
std::os::unix::fs::symlink(target, &alias).unwrap();
|
||||
assert!(agent_directory(&private).is_err());
|
||||
let calls = std::cell::Cell::new(0);
|
||||
assert!(
|
||||
validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
Some(&outside),
|
||||
|_| {
|
||||
calls.set(calls.get() + 1);
|
||||
Ok(())
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(calls.get(), 0);
|
||||
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 1);
|
||||
std::fs::remove_file(alias).unwrap();
|
||||
}
|
||||
assert_eq!(std::fs::read(outside.join("existing-document")).unwrap(), b"stable document bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.home().join("nightly/profiles/photocraft");
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
assert!(overlaps(&root, &root.join("Recovery"), platform));
|
||||
assert!(overlaps(&root.join("Recovery"), &root, platform));
|
||||
assert!(!overlaps(&root, &root.with_file_name("photocraft-other"), platform));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_app_xdg_subtrees_but_allows_launcher_sibling() {
|
||||
let mut fixture = Fixture::new();
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
|
||||
}
|
||||
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("photocraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
|
||||
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
|
||||
}
|
||||
let data = PathBuf::from(fixture.get("XDG_DATA_HOME").unwrap());
|
||||
let nightly = data.join("ArtCraftLauncher/nightly/profiles/photocraft");
|
||||
assert_eq!(fixture.check(Platform::Linux, &nightly).unwrap(), nightly);
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
|
||||
let mut fixture = Fixture::new();
|
||||
fixture.exe = fixture.root.join("install/PhotoCraft Nightly.app/Contents/MacOS/PhotoCraft");
|
||||
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
|
||||
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
|
||||
let library = fixture.home().join("Library");
|
||||
for suffix in [
|
||||
"Application Support/Photocraft",
|
||||
"Caches/Photocraft",
|
||||
"Caches/ai.storyteller.photocraft",
|
||||
"Preferences/Photocraft",
|
||||
"Saved Application State/ai.storyteller.photocraft.savedState",
|
||||
] {
|
||||
let stable = library.join(suffix);
|
||||
assert!(fixture.check(Platform::Mac, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
|
||||
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
|
||||
assert!(!inside_resources.exists());
|
||||
let valid = library.join("Application Support/ArtCraftLauncher/nightly/profiles/photocraft");
|
||||
assert_eq!(fixture.check(Platform::Mac, &valid).unwrap(), valid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_roaming_local_and_install_fences_remain_active() {
|
||||
let fixture = Fixture::new();
|
||||
for key in ["APPDATA", "LOCALAPPDATA"] {
|
||||
let stable = PathBuf::from(fixture.get(key).unwrap()).join("Photocraft");
|
||||
assert!(fixture.check(Platform::Windows, &stable.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!stable.exists());
|
||||
}
|
||||
assert!(fixture.check(Platform::Windows, &fixture.exe.parent().unwrap().join("profile")).is_err());
|
||||
assert!(fixture.check(Platform::Windows, &fixture.root.join("Launcher/profiles/photocraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_default_msi_install_folders_are_fenced() {
|
||||
let mut fixture = Fixture::new();
|
||||
let local = PathBuf::from(fixture.get("LOCALAPPDATA").unwrap());
|
||||
let per_user = local.join("Programs").join("ArtCraft").join("PhotoCraft");
|
||||
assert!(fixture.check(Platform::Windows, &per_user.join("nightly")).unwrap_err().contains("overlap"));
|
||||
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
|
||||
let base = fixture.root.join(format!("machine {key}"));
|
||||
fixture.env.insert(key.into(), base.clone().into_os_string());
|
||||
let machine = base.join("ArtCraft").join("PhotoCraft");
|
||||
assert!(fixture.check(Platform::Windows, &machine.join("nightly")).unwrap_err().contains("overlap"));
|
||||
assert!(!machine.exists());
|
||||
}
|
||||
let sibling = local.join("Programs").join("ArtCraft").join("ArtCraftLauncher").join("nightly").join("photocraft");
|
||||
assert!(fixture.check(Platform::Windows, &sibling).is_ok(), "the Launcher's own Programs sibling is not PhotoCraft's install");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn folders_under_a_stable_portable_copy_are_refused_before_any_probe() {
|
||||
let fixture = Fixture::new();
|
||||
let portable = fixture.root.join("D/PC");
|
||||
std::fs::create_dir_all(&portable).unwrap();
|
||||
std::fs::write(portable.join("portable.txt"), b"stable portable copy").unwrap();
|
||||
std::fs::write(portable.join("photocraft.exe"), b"stable portable executable, never run").unwrap();
|
||||
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
|
||||
for candidate in [portable.join("nightly"), portable.join("deeper/nightly")] {
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
platform,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
None,
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("portable"));
|
||||
assert!(!probed.get());
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
}
|
||||
// A portable.txt that no PhotoCraft executable sits beside is someone else's file.
|
||||
let unrelated = fixture.root.join("user folder");
|
||||
std::fs::create_dir_all(&unrelated).unwrap();
|
||||
std::fs::write(unrelated.join("portable.txt"), b"another app's marker").unwrap();
|
||||
assert!(fixture.check(Platform::Windows, &unrelated.join("Launcher/nightly/photocraft")).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_fences_the_stable_flatpak_data_folder() {
|
||||
let fixture = Fixture::new();
|
||||
let flatpak = fixture.home().join(".var/app/ai.storyteller.photocraft");
|
||||
for candidate in [flatpak.clone(), flatpak.join("data/nightly")] {
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"));
|
||||
}
|
||||
assert!(!flatpak.exists());
|
||||
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn any_profile_entry_alias_must_stay_inside_the_profile() {
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/photocraft/Presets");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("stable-preset"), b"stable preset bytes").unwrap();
|
||||
for name in ["Presets", "logs", "settings.json"] {
|
||||
let private = fixture.root.join(format!("nightly-{name}"));
|
||||
std::fs::create_dir(&private).unwrap();
|
||||
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
|
||||
let probed = std::cell::Cell::new(false);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&private,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
None,
|
||||
|_| {
|
||||
probed.set(true);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
assert!(result.is_err(), "{name} must not lead outside the profile");
|
||||
assert!(!probed.get());
|
||||
}
|
||||
let private = fixture.root.join("nightly-inside");
|
||||
std::fs::create_dir_all(private.join("real-presets")).unwrap();
|
||||
std::fs::write(private.join("settings.json"), b"{}").unwrap();
|
||||
std::os::unix::fs::symlink(private.join("real-presets"), private.join("Presets")).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &private).is_ok(), "regular files and links that stay inside are fine");
|
||||
assert_eq!(std::fs::read(stable.join("stable-preset")).unwrap(), b"stable preset bytes");
|
||||
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
|
||||
let mut fixture = Fixture::new();
|
||||
let candidate = fixture.home().join("nightly/profiles/photocraft");
|
||||
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
|
||||
fixture.env.remove("XDG_CACHE_HOME");
|
||||
fixture.env.insert("PHOTOCRAFT_CONFIG_DIR".into(), fixture.home().join("custom-stable").into_os_string());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("PHOTOCRAFT_CONFIG_DIR"));
|
||||
fixture.env.remove("PHOTOCRAFT_CONFIG_DIR");
|
||||
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.photocraft".into());
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
|
||||
fixture.env.remove("FLATPAK_ID");
|
||||
fixture.env.remove("HOME");
|
||||
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
|
||||
assert!(!candidate.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_directory_and_failed_write_probe_never_fall_back_to_stable() {
|
||||
let fixture = Fixture::new();
|
||||
let file = fixture.home().join("not-a-directory");
|
||||
std::fs::write(&file, b"do not replace me").unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &file).is_err());
|
||||
assert_eq!(std::fs::read(file).unwrap(), b"do not replace me");
|
||||
let candidate = fixture.home().join("nightly");
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let result = validate_for(
|
||||
Platform::Linux,
|
||||
&candidate,
|
||||
|key| fixture.get(key),
|
||||
Some(&fixture.exe),
|
||||
None,
|
||||
|_| {
|
||||
calls.set(calls.get() + 1);
|
||||
Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "injected write refusal"))
|
||||
},
|
||||
);
|
||||
assert!(result.unwrap_err().contains("not writable"));
|
||||
assert_eq!(calls.get(), 1);
|
||||
assert!(!fixture.home().join(".config/photocraft").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlink_and_dangling_aliases_cannot_create_or_modify_stable_data() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let fixture = Fixture::new();
|
||||
let stable = fixture.home().join(".config/photocraft");
|
||||
std::fs::create_dir_all(&stable).unwrap();
|
||||
std::fs::write(stable.join("sentinel"), b"untouched").unwrap();
|
||||
let alias = fixture.home().join("alias");
|
||||
symlink(&stable, &alias).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &alias.join("nightly")).unwrap_err().contains("overlap"));
|
||||
let missing = fixture.home().join("missing-target");
|
||||
let dangling = fixture.home().join("dangling");
|
||||
symlink(&missing, &dangling).unwrap();
|
||||
assert!(fixture.check(Platform::Linux, &dangling.join("nightly")).is_err());
|
||||
assert!(!missing.exists());
|
||||
assert!(!stable.join("nightly").exists());
|
||||
assert_eq!(std::fs::read(stable.join("sentinel")).unwrap(), b"untouched");
|
||||
}
|
||||
}
|
||||
@@ -286,6 +286,113 @@ fn image_from_files(paths: &[PathBuf]) -> Option<(u32, u32, Vec<u8>)> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the X11 clipboard advertises `text/uri-list`, or `None` when arboard uses Wayland,
|
||||
/// with no owner, or when the owner doesn't answer `TARGETS`. Asking an image-only owner for the file list can
|
||||
/// start an INCR transfer that arboard abandons, leaving the owner waiting and the following
|
||||
/// image read unable to start (#10231), so the caller skips that request unless the target list
|
||||
/// says files may be there.
|
||||
///
|
||||
/// x11rb's X11 reply waits are blocking, so the probe runs on its own thread; the paste waits
|
||||
/// at most 250 ms for an answer and leaves a stuck X server to that thread.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn x11_clipboard_has_uri_list() -> Option<bool> {
|
||||
use std::time::{Duration, Instant};
|
||||
let deadline = Instant::now() + Duration::from_millis(250);
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
std::thread::Builder::new()
|
||||
.name("x11-clipboard-targets".into())
|
||||
.spawn(move || {
|
||||
let _ = sender.send(x11_clipboard_has_uri_list_blocking(deadline));
|
||||
})
|
||||
.ok()?;
|
||||
let result = receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())).ok().flatten();
|
||||
log::debug!("X11 clipboard target probe: text/uri-list = {result:?}");
|
||||
result
|
||||
}
|
||||
|
||||
/// The target list reply mapping: only a complete 32-bit atom list says what the clipboard
|
||||
/// offers. A truncated list or a reply of another type leaves the answer unknown.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn x11_target_list_offers_uri_list(reply_type: u32, format: u8, bytes_after: u32, atoms: impl IntoIterator<Item = u32>, uri_list: u32) -> Option<bool> {
|
||||
if bytes_after != 0 || reply_type != u32::from(x11rb::protocol::xproto::AtomEnum::ATOM) || format != 32 {
|
||||
return None;
|
||||
}
|
||||
Some(atoms.into_iter().any(|atom| atom == uri_list))
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn x11_clipboard_has_uri_list_blocking(deadline: std::time::Instant) -> Option<bool> {
|
||||
use std::time::{Duration, Instant};
|
||||
use x11rb::connection::Connection as _;
|
||||
use x11rb::protocol::Event;
|
||||
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt as _, CreateWindowAux, EventMask, WindowClass};
|
||||
|
||||
// arboard tries its Wayland backend only when this same check succeeds, and falls back to
|
||||
// X11 when it doesn't, so the X11 target check still applies in that fallback case.
|
||||
if std::env::var_os("WAYLAND_DISPLAY").is_some() && wl_clipboard_rs::utils::is_primary_selection_supported().is_ok() {
|
||||
return None;
|
||||
}
|
||||
let (conn, screen_num) = x11rb::connect(None).ok()?;
|
||||
let screen = conn.setup().roots.get(screen_num)?;
|
||||
let intern = |name: &[u8]| conn.intern_atom(false, name).ok()?.reply().ok().map(|r| r.atom);
|
||||
let clipboard = intern(b"CLIPBOARD")?;
|
||||
let targets = intern(b"TARGETS")?;
|
||||
let uri_list = intern(b"text/uri-list")?;
|
||||
let property = intern(b"PHOTOCRAFT_CLIPBOARD_TARGETS")?;
|
||||
if conn.get_selection_owner(clipboard).ok()?.reply().ok()?.owner == x11rb::NONE {
|
||||
return None;
|
||||
}
|
||||
let window = conn.generate_id().ok()?;
|
||||
conn.create_window(
|
||||
x11rb::COPY_DEPTH_FROM_PARENT,
|
||||
window,
|
||||
screen.root,
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
1,
|
||||
0,
|
||||
WindowClass::INPUT_OUTPUT,
|
||||
x11rb::COPY_FROM_PARENT,
|
||||
&CreateWindowAux::new().event_mask(EventMask::PROPERTY_CHANGE),
|
||||
)
|
||||
.ok()?;
|
||||
conn.convert_selection(window, clipboard, targets, property, x11rb::CURRENT_TIME).ok()?;
|
||||
conn.flush().ok()?;
|
||||
// The paste is waiting on this, so give a slow owner a moment and fall back to the old
|
||||
// file-list-first read rather than delaying it for long.
|
||||
while Instant::now() < deadline {
|
||||
let Some(event) = conn.poll_for_event().ok()? else {
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
continue;
|
||||
};
|
||||
let Event::SelectionNotify(event) = event else { continue };
|
||||
if event.requestor != window || event.selection != clipboard || event.target != targets {
|
||||
continue;
|
||||
}
|
||||
if event.property == x11rb::NONE {
|
||||
return None;
|
||||
}
|
||||
let reply = conn.get_property(true, window, event.property, AtomEnum::ATOM, 0, 1024).ok()?.reply().ok()?;
|
||||
let (reply_type, format, bytes_after) = (reply.type_, reply.format, reply.bytes_after);
|
||||
let atoms = reply.value32()?;
|
||||
return x11_target_list_offers_uri_list(reply_type, format, bytes_after, atoms, uri_list);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether asking for a file list is worth a request. `None` means the target list couldn't be
|
||||
/// read (Wayland, no owner, or a slow X11 owner), where the old file-list-first read stays.
|
||||
fn should_read_file_list(offers_uri_list: Option<bool>) -> bool {
|
||||
offers_uri_list != Some(false)
|
||||
}
|
||||
|
||||
/// The copied files as [`clipboard_image`] takes them, asking the OS only when the advertised
|
||||
/// targets allow it.
|
||||
fn read_file_list(offers_uri_list: Option<bool>, read: impl FnOnce() -> Result<Vec<PathBuf>, arboard::Error>) -> Result<Option<Vec<PathBuf>>, String> {
|
||||
if should_read_file_list(offers_uri_list) { clipboard_read(read()) } else { Ok(None) }
|
||||
}
|
||||
|
||||
/// Largest clipboard image payload read on Wayland (1 GiB, a 16K × 16K RGBA BMP), so no real
|
||||
/// screenshot is turned away, while a broken or hostile source can't make us allocate without end.
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -358,13 +465,28 @@ fn clipboard_image<C>(
|
||||
Ok(text(clipboard)?.and_then(|text| image_from_svg_text(&text)))
|
||||
}
|
||||
|
||||
/// arboard's X11 backend reports this when the clipboard owner answers a request for a format
|
||||
/// it doesn't offer with the type of the content it does hold. xclip, and the Qt owners behind
|
||||
/// flameshot, do this for image clipboards (#10231), so the read means "format not offered"
|
||||
/// rather than a failure: the next format is tried.
|
||||
const X11_WRONG_PROPERTY_TYPE: &str = "incorrect type received from clipboard";
|
||||
|
||||
/// Whether `error` only says the clipboard has nothing in the format that was asked for.
|
||||
fn no_clipboard_content(error: &arboard::Error) -> bool {
|
||||
match error {
|
||||
arboard::Error::ContentNotAvailable => true,
|
||||
arboard::Error::Unknown { description } => description == X11_WRONG_PROPERTY_TYPE,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One OS clipboard read as [`clipboard_image`] takes it: no content in the format asked for is
|
||||
/// `None`, and any other failure, such as a busy clipboard or a broken pipe on Wayland, is the
|
||||
/// read's error.
|
||||
fn clipboard_read<T>(read: Result<T, arboard::Error>) -> Result<Option<T>, String> {
|
||||
match read {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(arboard::Error::ContentNotAvailable) => Ok(None),
|
||||
Err(error) if no_clipboard_content(&error) => Ok(None),
|
||||
Err(error) => Err(error.to_string()),
|
||||
}
|
||||
}
|
||||
@@ -429,6 +551,9 @@ pub fn automation(workspace: Option<photocraft_automation::AuthorizedWorkspace>)
|
||||
Ok(opened.map(|doc| (name, doc)))
|
||||
}) as photocraft_ui_egui::AutomationOpenPcraftFn
|
||||
});
|
||||
let locate = workspace.clone().map(|workspace| {
|
||||
Box::new(move |path: &str| workspace.location(path).map(|location| location.to_string_lossy().into_owned())) as photocraft_ui_egui::AutomationLocateFn
|
||||
});
|
||||
let save = workspace.clone().map(|workspace| {
|
||||
std::sync::Arc::new(move |doc: &Document, path: &str, settings: &photocraft_ui_egui::ExportSettings, ctl: &photocraft_ui_egui::jobs_ui::SaveCtl| {
|
||||
save_through(doc, path, settings, ctl, |p, encoded, _| workspace.write_stream(p, &mut |w| encoded.write_to(w)).map_err(|e| e.to_string()))
|
||||
@@ -441,7 +566,7 @@ pub fn automation(workspace: Option<photocraft_automation::AuthorizedWorkspace>)
|
||||
photocraft_automation::workspace::authorize_desktop_engine_command(id, params).map_err(|error| error.to_string())
|
||||
}) as photocraft_ui_egui::AutomationCommandFn
|
||||
});
|
||||
photocraft_ui_egui::AutomationServices { read, write, open_pcraft, save, command, authorize }
|
||||
photocraft_ui_egui::AutomationServices { read, write, open_pcraft, locate, save, command, authorize }
|
||||
}
|
||||
|
||||
/// What agent requests may read, write and run with the agent settings' folders
|
||||
@@ -486,6 +611,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>, wa
|
||||
automation_read: automation.read,
|
||||
automation_write: automation.write,
|
||||
automation_open_pcraft: automation.open_pcraft,
|
||||
automation_locate: automation.locate,
|
||||
automation_save: automation.save,
|
||||
automation_command: automation.command,
|
||||
automation_authorize: automation.authorize,
|
||||
@@ -520,9 +646,13 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>, wa
|
||||
slot.insert(opened.map_err(|e| e.to_string())?)
|
||||
}
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
let file_list = x11_clipboard_has_uri_list();
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let file_list = None;
|
||||
clipboard_image(
|
||||
cb,
|
||||
|cb| clipboard_read(cb.get().file_list()),
|
||||
|cb| read_file_list(file_list, || cb.get().file_list()),
|
||||
|cb| match cb.get_image() {
|
||||
Ok(img) => Ok(Some((img.width as u32, img.height as u32, img.bytes.into_owned()))),
|
||||
Err(error) => {
|
||||
@@ -530,10 +660,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>, wa
|
||||
if let Some(image) = wayland_clipboard_image() {
|
||||
return Ok(Some(image));
|
||||
}
|
||||
match error {
|
||||
arboard::Error::ContentNotAvailable => Ok(None),
|
||||
_ => Err(error.to_string()),
|
||||
}
|
||||
clipboard_read::<(u32, u32, Vec<u8>)>(Err(error))
|
||||
}
|
||||
},
|
||||
|cb| clipboard_text(cb.get_text()),
|
||||
|
||||
@@ -245,7 +245,8 @@ fn recovered_documents_survive_a_second_crash_until_saved_or_closed() {
|
||||
let red = index_of(&app, RED);
|
||||
app.run("file.close", json!({"document": red})).unwrap();
|
||||
// Saving marks the revision saved (the file write itself is the save service's job).
|
||||
assert!(app.session.set_active(index_of(&app, BLUE)));
|
||||
let blue = index_of(&app, BLUE);
|
||||
assert!(app.session.set_active(blue));
|
||||
let st = app.session.active_mut().unwrap();
|
||||
st.saved_revision = st.revision;
|
||||
prefs_ui::tick(&mut app, &ctx, std::time::Instant::now());
|
||||
@@ -598,7 +599,9 @@ fn only_missing_content_reads_as_nothing_to_paste() {
|
||||
use arboard::Error;
|
||||
let failures = || [Error::ClipboardOccupied, Error::ClipboardNotSupported, Error::Unknown { description: "broken pipe".to_string() }];
|
||||
assert_eq!(clipboard_read(Ok::<_, Error>(vec![PathBuf::from("a.png")])), Ok(Some(vec![PathBuf::from("a.png")])));
|
||||
assert_eq!(clipboard_read::<Vec<PathBuf>>(Err(Error::ContentNotAvailable)), Ok(None));
|
||||
for missing in [Error::ContentNotAvailable, Error::Unknown { description: "incorrect type received from clipboard".to_string() }] {
|
||||
assert_eq!(clipboard_read::<Vec<PathBuf>>(Err(missing)), Ok(None));
|
||||
}
|
||||
for error in failures().into_iter().chain([Error::ConversionFailure]) {
|
||||
let message = error.to_string();
|
||||
assert_eq!(clipboard_read::<Vec<PathBuf>>(Err(error)), Err(message.clone()), "{message}");
|
||||
@@ -612,6 +615,62 @@ fn only_missing_content_reads_as_nothing_to_paste() {
|
||||
}
|
||||
}
|
||||
|
||||
/// #10231: a large xclip image can answer a file-list request with an INCR transfer arboard
|
||||
/// abandons, so the image read never gets a turn. When the target list says there is no
|
||||
/// `text/uri-list`, the paste must not ask for one at all.
|
||||
#[test]
|
||||
fn an_image_only_target_list_never_asks_for_files() {
|
||||
assert!(should_read_file_list(None), "an unknown target list keeps the old read");
|
||||
assert!(should_read_file_list(Some(true)));
|
||||
assert!(!should_read_file_list(Some(false)));
|
||||
let got = read_file_list(Some(false), || panic!("must not request text/uri-list"));
|
||||
assert_eq!(got, Ok(None));
|
||||
let paths = read_file_list(Some(true), || Ok(vec![PathBuf::from("a.png")]));
|
||||
assert_eq!(paths, Ok(Some(vec![PathBuf::from("a.png")])));
|
||||
}
|
||||
|
||||
/// #10231: a complete X11 `TARGETS` reply without `text/uri-list` must read as an image-only
|
||||
/// clipboard, not as an unknown target list; a truncated or malformed reply stays unknown.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn an_x11_target_list_reply_maps_only_a_complete_atom_list() {
|
||||
let atom_type = u32::from(x11rb::protocol::xproto::AtomEnum::ATOM);
|
||||
let uri_list = 9;
|
||||
assert_eq!(x11_target_list_offers_uri_list(atom_type, 32, 0, [1, 2], uri_list), Some(false));
|
||||
assert_eq!(x11_target_list_offers_uri_list(atom_type, 32, 0, [1, uri_list], uri_list), Some(true));
|
||||
assert_eq!(x11_target_list_offers_uri_list(atom_type, 32, 4, [1, uri_list], uri_list), None, "a truncated list is unknown");
|
||||
assert_eq!(x11_target_list_offers_uri_list(3, 32, 0, [uri_list], uri_list), None, "not an atom list");
|
||||
assert_eq!(x11_target_list_offers_uri_list(atom_type, 8, 0, [uri_list], uri_list), None, "not a 32-bit list");
|
||||
}
|
||||
|
||||
/// #10231: xclip answers a request for a format it doesn't offer (the copied-file list) with
|
||||
/// the image's own type, which arboard reports as an unknown error. The paste still reads the
|
||||
/// image instead of stopping at the missing file list.
|
||||
#[test]
|
||||
fn an_xclip_image_is_read_after_the_missing_file_list() {
|
||||
use arboard::Error;
|
||||
let mismatch = || Error::Unknown { description: "incorrect type received from clipboard".to_string() };
|
||||
let red = (2u32, 2u32, [255u8, 0, 0, 255].repeat(4));
|
||||
let mut text_read = false;
|
||||
let svg_text = |read: &mut bool| -> Result<Option<String>, String> {
|
||||
*read = true;
|
||||
Ok(None)
|
||||
};
|
||||
let got = clipboard_image(&mut text_read, |_| clipboard_read::<Vec<PathBuf>>(Err(mismatch())), |_| clipboard_read(Ok::<_, Error>(red.clone())), svg_text);
|
||||
assert_eq!(got, Ok(Some(red)));
|
||||
assert!(!text_read, "the image is pasted without reading the text");
|
||||
}
|
||||
|
||||
/// The same X11 wrong-type reply to the image request means the clipboard holds no image in
|
||||
/// the format asked for, so a drawing copied as SVG markup is still read.
|
||||
#[test]
|
||||
fn an_x11_wrong_type_image_read_falls_through_to_svg_text() {
|
||||
use arboard::Error;
|
||||
let mismatch = || Error::Unknown { description: "incorrect type received from clipboard".to_string() };
|
||||
let got = clipboard_image(&mut (), |_| Ok(None), |_| clipboard_read::<(u32, u32, Vec<u8>)>(Err(mismatch())), |_| Ok(Some(COPIED_RECTANGLE.to_string())));
|
||||
assert_eq!(got.expect("no read fails").map(|(w, h, _)| (w, h)), Some((121, 81)));
|
||||
}
|
||||
|
||||
/// Edit › Paste with SVG markup as the clipboard's only content adds a new layer that holds the
|
||||
/// drawing's art; other text is still a quiet "nothing to paste".
|
||||
#[test]
|
||||
|
||||
@@ -126,7 +126,12 @@ fn a_launch_waiting_on_a_closing_instance_takes_over() {
|
||||
let primary = primary(&dir);
|
||||
// The UI never drains (it is shutting down, or never came up).
|
||||
let waiting = launch(&dir, &["a.psd"], FAST);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
// Shut down only once the launch has handed its path over and waits for the UI to take it.
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while primary.shared.inbox.lock().unwrap().pending.is_empty() {
|
||||
assert!(Instant::now() < deadline, "the launch never queued its path");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
primary.shutdown();
|
||||
assert!(matches!(waiting.join().unwrap(), Launch::Primary(_)), "the waiting launch becomes the primary");
|
||||
// After shutdown new connections are refused too.
|
||||
|
||||
@@ -44,3 +44,15 @@ details and tests the `.ico` sizes and the WiX icon references.
|
||||
|
||||
Replace `photocraft.svg` (and `photocraft-small.svg`), then run `packaging/icons.sh`. It needs
|
||||
`resvg`, plus `iconutil` on macOS; the `.ico` is packed by `cargo xtask ico`.
|
||||
|
||||
## Nightly channel
|
||||
|
||||
The nightly derivatives keep the foreground artwork, alpha and Mac padding unchanged. Only the
|
||||
background contribution changes from the stable blue to the selected deep background. There is
|
||||
no letter badge or crescent; the app and Launcher also identify the channel in text.
|
||||
|
||||
`photocraft-nightly.png` and its nine-frame ICO use the existing own256 master. The separate
|
||||
`photocraft-nightly-1024.png` and eleven-slot ICNS use the actual padded Mac1024 master, not an
|
||||
upscale. Input/output hashes, the palette-fit recipe and container sizes are recorded in
|
||||
[`nightly-provenance.json`](nightly-provenance.json). Stable source files are not recoloured.
|
||||
The old N-marked private Windows isolation package is separate and is not rebuilt for this art.
|
||||
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"title": "PhotoCraft nightly deep-background icons",
|
||||
"author": "@skylartaylor",
|
||||
"license": "MIT OR Apache-2.0",
|
||||
"source_commit": "06afefff534fb18ca7ea2725a9f476fe477dbd29",
|
||||
"inputs": [
|
||||
{
|
||||
"path": "assets/app-icon/hicolor/256x256/apps/ai.storyteller.photocraft.png",
|
||||
"sha256": "efd02e0b8ea76c59fbc3a9692ddc21faae6064cc9f9492898df1facec3b5b57d",
|
||||
"purpose": "Windows/Linux native256 master"
|
||||
},
|
||||
{
|
||||
"path": "assets/app-icon/photocraft-1024.png",
|
||||
"sha256": "00a39c5ccbcb2b5f144573b1cedb6c387c4416ad06fd1cf2865b0737458ee704",
|
||||
"purpose": "native padded Mac1024 master; not upscaled from256"
|
||||
}
|
||||
],
|
||||
"method": {
|
||||
"kind": "original code-generated derivative of the project-owned icon",
|
||||
"original_palette": {
|
||||
"ink": "#0b0b0c",
|
||||
"paper": "#efe9dc",
|
||||
"background": "#2f7bf5"
|
||||
},
|
||||
"nightly_background": "#22395d",
|
||||
"transform": "Fit background contribution in the existing ink/paper/background palette and change only that contribution. Preserve alpha/padding and neutral foreground/detail RGBA. Derive native-size frames separately from their corresponding unchanged-resolution masters and pack PNG frames into ICO/ICNS. No crescent, letter or badge.",
|
||||
"generator_sha256": "a04dcbba501985de729d37d352597de6ffb2ad993f1596eced6b12bffc114d85"
|
||||
},
|
||||
"outputs": {
|
||||
"assets/app-icon/photocraft-nightly.png": "7a79aff027f9f95cef0edc0a84ce3791af302b6351ebca4d0e736477e3b3f031",
|
||||
"assets/app-icon/photocraft-nightly.ico": "87f67bc7b9ce18f54ab62769d7e6849d9ed0fd2658fce7db1a1eb05140fad2f4",
|
||||
"assets/app-icon/photocraft-nightly-1024.png": "8de1e42f70720c7b8c66f40f443e7f7a423690cfcb062725d2e563c5f8fd51b1",
|
||||
"assets/app-icon/photocraft-nightly.icns": "9ceecf811014509cc1444f44aaa0d31715a1e2439e943aec77c510dd4b2bf8f0"
|
||||
},
|
||||
"ico_frame_sizes": [
|
||||
16,
|
||||
20,
|
||||
24,
|
||||
32,
|
||||
40,
|
||||
48,
|
||||
64,
|
||||
128,
|
||||
256
|
||||
],
|
||||
"icns_png_slots": {
|
||||
"icp4": 16,
|
||||
"icp5": 32,
|
||||
"ic11": 32,
|
||||
"icp6": 64,
|
||||
"ic12": 64,
|
||||
"ic07": 128,
|
||||
"ic08": 256,
|
||||
"ic13": 256,
|
||||
"ic09": 512,
|
||||
"ic14": 512,
|
||||
"ic10": 1024
|
||||
},
|
||||
"validation": "Source/input/output hashes, PNG CRC/dimensions and exact container members checked; supplied generator pixel proof preserves foreground/alpha. Visual comparison reviewed. Native Explorer/Finder/iconutil/app-package qualification remains unrun."
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 208 KiB |
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 84 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 33 KiB |
@@ -18,8 +18,9 @@ The control and headless TCP listeners are restricted to loopback addresses. Std
|
||||
|
||||
Loopback is not authentication. TCP transports require a bearer token and enforce request-byte,
|
||||
batch-step, and active-connection limits. Remote file methods use an `AuthorizedWorkspace` with
|
||||
independent read and write directory capabilities; paths are relative to a configured root and
|
||||
fail closed when the applicable root is absent. General per-method scopes, client identity,
|
||||
independent read and write directory capabilities; paths may be relative or absolute beneath an
|
||||
applicable granted root. File methods fail closed when the applicable read or write authority is
|
||||
absent. General per-method scopes, client identity,
|
||||
encryption, and operation budgets are not implemented. See the
|
||||
[Automation security model](../automation/security-model.md) and
|
||||
[Automation security](../security/automation-security.md) before exposing or extending these
|
||||
|
||||
@@ -84,7 +84,7 @@ layers because that would lose their group's blending semantics.
|
||||
|
||||
Paths supplied to the current CLI are ordinary operating-system paths. The CLI does not restrict them to a workspace root. Batch output creates the requested output directory, and save operations may create parent directories. `batch` refuses an output directory that is its input directory (the results would replace the originals) unless `--in-place` is given. Run untrusted action files only in an appropriately isolated account or environment.
|
||||
|
||||
CLI parsing checks the flags and their values before any work starts. A flag the subcommand doesn't take (a typo such as `--fromat`), a flag given twice (only `--cmd` and `--params` may repeat), a value out of range (`--quality 0`), malformed `--new` or `--params` JSON, `<FILE>` together with `--new`, and `--control-token` together with `--control-token-file` are all usage errors (exit status 2), rather than being ignored or failing later. A value flag never takes the next flag as its value, so a value starting with `-` is written with `=` (`--out=-image.png`) or as `./-image.png`; negative numbers such as `--filter -1` still work. A path that is not valid Unicode reaches the command instead of being a usage error: `convert` reads and writes it, while `info`, `run` and `batch` open files through the automation layer, which still needs UTF-8 paths and fails with exit status 1 (`droplet` takes its arguments as text, so it refuses such a path as a usage error). `photocraft-cli --version` (or `-V`) prints the version; there is no `version` subcommand.
|
||||
CLI parsing checks the flags and their values before any work starts. A flag the subcommand doesn't take (a typo such as `--fromat`), a flag given twice (`--cmd`, `--params` and `--automation-read-root` may repeat), a value out of range (`--quality 0`), malformed `--new` or `--params` JSON, `<FILE>` together with `--new`, and `--control-token` together with `--control-token-file` are all usage errors (exit status 2), rather than being ignored or failing later. A value flag never takes the next flag as its value, so a value starting with `-` is written with `=` (`--out=-image.png`) or as `./-image.png`; negative numbers such as `--filter -1` still work. A path that is not valid Unicode reaches the command instead of being a usage error: `convert` reads and writes it, while `info`, `run` and `batch` open files through the automation layer, which still needs UTF-8 paths and fails with exit status 1 (`droplet` takes its arguments as text, so it refuses such a path as a usage error). `photocraft-cli --version` (or `-V`) prints the version; there is no `version` subcommand.
|
||||
|
||||
`mcp` and `serve` reject positional arguments, empty values and options for the wrong mode before
|
||||
starting a server. Explicit control-token flags require `mcp --bridge` or `serve --port` (or
|
||||
|
||||
@@ -24,16 +24,21 @@ socket I/O and handler waits use timeouts; MCP and headless batches are limited
|
||||
JSON-lines replies and encoded MCP tool results are capped at 8 MiB, with aggregate batch reply
|
||||
budgets. Headless previews have source-pixel, requested-edge, and encoded-PNG ceilings. The
|
||||
bridge bounds incoming reply frames and screenshot decoding.
|
||||
Automation file methods require separately configured read and write roots. Request paths are
|
||||
relative, and absolute, traversal, alternate-separator, device-name, and link-escape paths are
|
||||
rejected before file effects.
|
||||
Automation file methods require separately configured read and write roots. Request paths may be
|
||||
relative or absolute beneath the canonical or configured spelling of the applicable granted root.
|
||||
Absolute paths outside that root are rejected. Accepted absolute paths are translated to relative
|
||||
paths and resolved through the held directory capability. Relative requests reject empty or `.`
|
||||
components and alternate separators. Absolute requests are split into native path components
|
||||
before checking the root-relative remainder, so repeated separators and interior `.` components
|
||||
are normalized. Both forms reject parent traversal in the remainder, disallowed component names
|
||||
and link escapes before file effects.
|
||||
|
||||
**Known limitations:** the token is a bearer credential and grants the complete non-filesystem
|
||||
control surface. There is no encryption, client identity, general per-method capability check,
|
||||
explicit JSON-depth policy, aggregate session-memory accounting, or command-duration/cancellation
|
||||
budget. Desktop capture/encoding and import/export still need their own operation budgets.
|
||||
The listener creates one thread per authenticated
|
||||
active connection, within the connection cap. Trusted one-shot CLI operations and interactive
|
||||
The listener creates one thread per accepted active connection, including clients that are still
|
||||
authenticating, within the connection cap. Trusted one-shot CLI operations and interactive
|
||||
desktop file pickers retain the launching user's normal filesystem authority.
|
||||
|
||||
Use a private token file, enable `--control` only for a trusted local automation session, and never proxy the unencrypted protocol beyond loopback. See [Automation security](../security/automation-security.md) for the remaining gateway work.
|
||||
@@ -29,8 +29,8 @@ client's launch directory. In bridge mode the roots are configured on the deskto
|
||||
flags on `photocraft-cli mcp --bridge` are rejected. Explicit `--control-token` and
|
||||
`--control-token-file` flags require `--bridge` (or `PHOTOCRAFT_CONTROL_PORT`) and are mutually
|
||||
exclusive; bridge credentials can also come from `PHOTOCRAFT_CONTROL_TOKEN` or
|
||||
`PHOTOCRAFT_CONTROL_TOKEN_FILE`. Each launch option
|
||||
except `--help`/`-h` takes one non-empty value and cannot be repeated. Stray positional arguments,
|
||||
`PHOTOCRAFT_CONTROL_TOKEN_FILE`. `--headless`, `--gpu`, `--no-gpu` and `--help`/`-h` take no value. Other launch options
|
||||
take one non-empty value; only `--automation-read-root` may repeat, adding ordered read directories. Stray positional arguments,
|
||||
missing values and options for the wrong mode are usage errors (exit 2) reported on stderr before
|
||||
the server starts.
|
||||
|
||||
|
||||
@@ -24,11 +24,15 @@ The manifest is versioned and describes the document tree. Tiles and blobs are c
|
||||
|
||||
Default `LoadOptions` apply these maximums:
|
||||
|
||||
| Limit | Default |
|
||||
|---|---:|
|
||||
| `manifest.json` | 256 MiB |
|
||||
| One decompressed blob | 1 GiB |
|
||||
| Total decompressed tiles and blobs | 16 GiB |
|
||||
| Limit | Desktop | Browser |
|
||||
|---|---:|---:|
|
||||
| `manifest.json` | 256 MiB | 256 MiB |
|
||||
| One decompressed blob | 1 GiB | 512 MiB |
|
||||
| Total decompressed tiles and blobs | Up to 16 GiB | 1 GiB |
|
||||
|
||||
On desktop, the total-byte budget is lowered to the available RAM plus remaining scratch-disk
|
||||
capacity, with a 1 GiB floor and a 16 GiB cap. If neither figure is available, the 16 GiB cap
|
||||
applies. These are decoded tile and blob bytes, not a limit on the process's total memory.
|
||||
|
||||
Layer groups may nest at most 100 levels (`MAX_GROUP_DEPTH`). Saving a deeper document fails with an error instead of writing a bundle that can't be opened, and a manifest whose JSON nesting goes beyond what that depth needs is rejected before it is parsed, so a hostile file can't exhaust the stack.
|
||||
|
||||
|
||||
@@ -43,9 +43,13 @@ Automation is a privilege boundary because requests can cause filesystem access,
|
||||
- A save without a `path` (MCP `doc_save`, `serve` `doc.save`, the control channel's `app.save`)
|
||||
writes back only to the document's own PSD, PSB or `.pcraft` file in its own format; any other
|
||||
save needs an explicit `path`, so automation never flattens or converts over the file it opened.
|
||||
- Automation paths must be relative beneath the applicable root. Absolute paths, parent
|
||||
traversal, alternate separators, Windows device names, malformed components, and link escapes
|
||||
are rejected before file effects.
|
||||
- Automation paths may be relative or absolute beneath the canonical or configured spelling of
|
||||
the applicable granted root. Absolute paths outside that root are rejected. Accepted absolute
|
||||
paths are translated to relative paths and resolved through the held directory capability.
|
||||
Relative requests reject empty or `.` components and alternate separators. Absolute requests
|
||||
are split into native path components before checking the root-relative remainder, so repeated
|
||||
separators and interior `.` components are normalized. Both forms reject parent traversal in
|
||||
the remainder, disallowed component names and link escapes before file effects.
|
||||
- Engine commands that still use ambient paths fail closed at the automation boundary. Synthetic
|
||||
UI input reaches the same command policy, and automation-triggered file hooks do not run
|
||||
user-configured script-event paths. The policy also covers every command a command runs on its
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Secure file handling
|
||||
|
||||
PhotoCraft reads and writes documents in the desktop app, CLI, headless RPC server, and MCP server.
|
||||
Remote automation paths are untrusted relative names resolved beneath explicitly granted roots.
|
||||
Remote automation paths are untrusted names resolved beneath explicitly granted roots.
|
||||
|
||||
## Implemented
|
||||
|
||||
@@ -11,11 +11,15 @@ Remote automation paths are untrusted relative names resolved beneath explicitly
|
||||
- Native `.pcraft` saves use temporary-file/rename patterns in relevant store paths.
|
||||
- `AuthorizedWorkspace` holds independent read and write directory capabilities for remote
|
||||
automation.
|
||||
- Absolute paths, parent traversal, alternate separators, drive/device/stream prefixes, reserved
|
||||
Windows device names, empty or dot components, and link escapes are rejected before file
|
||||
effects.
|
||||
- Non-existent output files are supported when their parent already exists beneath the write
|
||||
root. Automation does not create caller-selected directory trees.
|
||||
- Absolute paths beneath the canonical or configured spelling of the applicable granted root
|
||||
are translated to relative paths and resolved through the held directory capability. Absolute
|
||||
paths outside that root are rejected.
|
||||
- Relative requests reject empty or `.` components and alternate separators. Absolute requests
|
||||
are split into native path components before checking the root-relative remainder, so repeated
|
||||
separators and interior `.` components are normalized. Both forms reject parent traversal in
|
||||
the remainder, disallowed component names and link escapes before file effects.
|
||||
- Ordinary single-file writes support non-existent output files when their parent already exists
|
||||
beneath the write root; they do not create caller-selected directory trees.
|
||||
- Filesystem-bearing engine commands that have not migrated to capability I/O fail closed for
|
||||
automation. Trusted local CLI subcommands and user-driven desktop file pickers keep their
|
||||
intended ambient authority.
|
||||
@@ -40,9 +44,15 @@ AuthorizedWorkspace
|
||||
```
|
||||
|
||||
The handle is created from an explicit launch-time grant, preserves separate read/write
|
||||
permissions, rejects absolute and escaping paths, and performs operations relative to the held
|
||||
directory capability. New files require an existing in-root parent because a non-existent target
|
||||
cannot be canonicalized safely.
|
||||
permissions, checks absolute paths against the granted root and rejects escaping paths. File
|
||||
contents are read and written through the held directory capability. On Windows UNC write roots,
|
||||
directory creation and atomic-save renames use guarded ambient paths beneath the canonical root,
|
||||
with each ancestor verified through its parent handle and held open. See
|
||||
[Windows UNC write roots](../automation/security-model.md#windows-unc-write-roots) for the
|
||||
provider and WSL limitations.
|
||||
Ordinary single-file writes require an existing in-root parent. Capability-scoped multi-file
|
||||
exports create their required export directory and missing ancestors beneath the write root
|
||||
before writing files.
|
||||
|
||||
## Design requirements
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
The repository-level [`SECURITY.md`](https://github.com/storytold/photocraft/blob/main/SECURITY.md) is the authoritative reporting policy.
|
||||
|
||||
Do not publish exploit details, weaponized files, secrets, or sensitive crash data before maintainers have had a reasonable opportunity to review and coordinate a fix. The repository currently documents no dedicated private security email or private reporting address.
|
||||
Do not publish exploit details, weaponized files, secrets, or sensitive crash data before maintainers have had a reasonable opportunity to review and coordinate a fix. Use [GitHub private vulnerability reporting](https://github.com/storytold/photocraft/security/advisories/new); if you cannot access it, follow the fallback in `SECURITY.md`.
|
||||
|
||||
A useful report identifies affected versions or commits, platform/build configuration, impact, exact reproduction steps, expected versus actual behavior, and relevant logs or backtraces. For a malicious test file, first provide a minimal description, hash, format, and safe transfer requirements; do not attach it publicly when it could harm users or contains non-redistributable data.
|
||||
|
||||
|
||||
@@ -355,3 +355,6 @@ real_name = "Sven Lafebre"
|
||||
|
||||
[people.kirubhakaran12]
|
||||
sync_github_name = true
|
||||
|
||||
[people.MMexicann]
|
||||
display_name = "mexicann"
|
||||
@@ -10,11 +10,14 @@ rust-version.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-develop = { workspace = true }
|
||||
craft-develop-model = { workspace = true }
|
||||
craft-metadata = { workspace = true }
|
||||
photocraft-geom = { workspace = true }
|
||||
photocraft-color = { workspace = true }
|
||||
photocraft-raster = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
rustfft = "6.4.1"
|
||||
# `craft::imaging::fold_order`, `RawDevelopSettings` and `WideAngleSession`; the facade's `ui` stays off, so algo is egui-free.
|
||||
craft = { workspace = true, features = ["imaging"] }
|
||||
@@ -25,7 +28,6 @@ rayon = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
photocraft-testkit = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
criterion = { workspace = true }
|
||||
|
||||
[[bench]]
|
||||
|
||||
+152
-1244
File diff suppressed because it is too large.
Load diff
@@ -1,658 +0,0 @@
|
||||
//! Shadows and Highlights as a local Laplacian filter.
|
||||
//!
|
||||
//! Adobe has said Camera Raw's process version 2012 rests on local Laplacian filters (S. Paris,
|
||||
//! S. W. Hasinoff, J. Kautz, *Local Laplacian Filters: Edge-aware Image Processing with a
|
||||
//! Laplacian Pyramid*, SIGGRAPH 2011). This follows that paper, in its fast form (M. Aubry et
|
||||
//! al., *Fast Local Laplacian Filters*, ACM TOG 2014: the remapping sampled at a few reference
|
||||
//! values, each pyramid coefficient interpolated between them), on the log2 luminance:
|
||||
//!
|
||||
//! - **Shadows** raises pixels darker than their surroundings, by an amount set by their own and
|
||||
//! their surroundings' place in the image's range (1st to 99th percentile); **Highlights**
|
||||
//! pulls pixels brighter than their surroundings toward them. Differences under a threshold
|
||||
//! are left alone, so fine detail stays.
|
||||
//! - Shadows then keeps the image's 99th percentile, Highlights its 1st (Photoshop keeps the
|
||||
//! brightest content under Shadows and the darkest under Highlights).
|
||||
//! - A uniform image is unchanged, edges keep no halo, and the result does not depend on the
|
||||
//! image size.
|
||||
//!
|
||||
//! The strengths were fitted to Photoshop 25.4's Camera Raw Filter on ten public-domain photos
|
||||
//! (black-box measurements, no Adobe code or data). It is an approximation: on those photos the
|
||||
//! mean error against Photoshop is 2.8–9.4 levels (of 255) where the previous heuristic's was
|
||||
//! 3.7–14.3.
|
||||
|
||||
use super::{Encoding, luma, quantile_rank};
|
||||
use crate::photo_util::par_rows;
|
||||
|
||||
/// Spacing of the fast filter's reference values in stops. Its remapping changes within about
|
||||
/// half a stop, and coefficients interpolated across wider gaps show as contour lines on smooth
|
||||
/// gradients (12 references over a whole raw's range left visible steps; at an eighth of a stop a
|
||||
/// ramp's slope varies by under a third, as the remapping itself makes it).
|
||||
pub const REF_STEP: f32 = 0.125;
|
||||
/// Most reference values one filter uses.
|
||||
pub const MAX_REFS: usize = 96;
|
||||
/// The lowest reference sits at this quantile of the log luminance: the deepest 0.1 % (noise down
|
||||
/// to the floor) share it instead of stretching the spacing.
|
||||
pub const REF_LOW_QUANTILE: f32 = 0.001;
|
||||
/// The filter works on `log2(luminance + LOG_FLOOR)`.
|
||||
pub const LOG_FLOOR: f32 = 1.0 / 65536.0;
|
||||
/// The filter runs on a copy at most this many pixels across; the change it makes is brought back
|
||||
/// to full size by a guided upsampling, so a preview and the full image agree.
|
||||
pub const WORK_SIDE: usize = 1600;
|
||||
/// The image range the strengths are placed in: these quantiles of the log luminance averaged
|
||||
/// over cells of a copy at most [`RANGE_SIDE`] pixels across.
|
||||
pub const RANGE_QUANTILES: [f32; 2] = [0.01, 0.99];
|
||||
/// See [`RANGE_QUANTILES`].
|
||||
pub const RANGE_SIDE: usize = 256;
|
||||
/// Knots of the strength curves over the surroundings' place in the image range (0 … 1).
|
||||
pub const KNOTS: usize = 5;
|
||||
|
||||
/// Shadows: how far a pixel darker than its surroundings rises, in stops per unit slider, as
|
||||
/// a function of its own place in the image range (`own`) times a factor of its surroundings'
|
||||
/// place (`around`); it rises fully once it is `sigma` stops below them. The lift depends on
|
||||
/// the pixel's tone, not on the size of the difference, so it is the same at every pyramid
|
||||
/// level and a big edge keeps no halo. Lowering (negative values) is `down` times as strong.
|
||||
const SHADOWS: Lift = Lift { own: [-0.017, 0.466, 0.886, 1.221, -0.081], around: [4.566, 4.067, 1.088, 0.149, 0.878], sigma: 0.571, down: 0.808 };
|
||||
const HIGHLIGHTS: Side = Side { pull: [0.179, 0.141, 0.196, 0.629, 2.07], push: [0.156, 0.08, 0.175, 0.049, 1.261], sigma: 0.05 };
|
||||
|
||||
/// See [`SHADOWS`].
|
||||
struct Lift {
|
||||
own: [f32; KNOTS],
|
||||
around: [f32; KNOTS],
|
||||
sigma: f32,
|
||||
down: f32,
|
||||
}
|
||||
|
||||
/// Highlights: strengths per unit slider over the surroundings' place in the image range, for
|
||||
/// lowering (`pull`, toward the surroundings) and raising (`push`), and the detail threshold in
|
||||
/// stops.
|
||||
struct Side {
|
||||
pull: [f32; KNOTS],
|
||||
push: [f32; KNOTS],
|
||||
sigma: f32,
|
||||
}
|
||||
|
||||
/// Which remapping a [`TonePass`] uses.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ToneKind {
|
||||
/// Pixels brighter than their surroundings move toward them (or away, for positive values)
|
||||
/// by the part of the difference past `sigma`.
|
||||
Highlights,
|
||||
/// Pixels darker than their surroundings rise (or sink) by an amount set by their own and
|
||||
/// their surroundings' place in the image range.
|
||||
Shadows,
|
||||
}
|
||||
|
||||
/// One pass of the filter resolved for a slider value: everything its remapping reads.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TonePass {
|
||||
pub kind: ToneKind,
|
||||
/// Highlights: the slider / 100. Shadows: its strength (the slider / 100, times `down` when
|
||||
/// negative).
|
||||
pub amount: f32,
|
||||
/// Highlights: the strengths for the slider's direction, then an unused row. Shadows: the
|
||||
/// curves over the pixel's own (`own`) and its surroundings' (`around`) place.
|
||||
pub knots: [[f32; KNOTS]; 2],
|
||||
/// The detail threshold in stops.
|
||||
pub sigma: f32,
|
||||
/// The quantile of the log luminance the pass puts back where it was.
|
||||
pub keep: f32,
|
||||
}
|
||||
|
||||
/// Shadows and Highlights resolved: Highlights runs first, then Shadows on its result.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LocalTone {
|
||||
pub passes: Vec<TonePass>,
|
||||
}
|
||||
|
||||
impl LocalTone {
|
||||
/// The passes for the sliders (−100 … 100); `None` when both are 0.
|
||||
pub fn new(shadows: f32, highlights: f32) -> Option<Self> {
|
||||
let mut passes = Vec::new();
|
||||
if highlights != 0.0 {
|
||||
let amount = highlights.clamp(-100.0, 100.0) / 100.0;
|
||||
let strengths = if amount < 0.0 { HIGHLIGHTS.pull } else { HIGHLIGHTS.push };
|
||||
// Then the darkest content is put back where it was.
|
||||
passes.push(TonePass { kind: ToneKind::Highlights, amount, knots: [strengths, [0.0; KNOTS]], sigma: HIGHLIGHTS.sigma, keep: 0.01 });
|
||||
}
|
||||
if shadows != 0.0 {
|
||||
let amount = shadows.clamp(-100.0, 100.0) / 100.0;
|
||||
let k = if amount > 0.0 { amount } else { amount * SHADOWS.down };
|
||||
// Keep the brightest content.
|
||||
passes.push(TonePass { kind: ToneKind::Shadows, amount: k, knots: [SHADOWS.own, SHADOWS.around], sigma: SHADOWS.sigma, keep: 0.99 });
|
||||
}
|
||||
(!passes.is_empty()).then_some(LocalTone { passes })
|
||||
}
|
||||
}
|
||||
|
||||
impl TonePass {
|
||||
/// The remapping of log luminance `x` around the reference `g`, in an image range that
|
||||
/// starts at `lo` and is `span` stops wide.
|
||||
pub fn remap(&self, x: f32, g: f32, lo: f32, span: f32) -> f32 {
|
||||
match self.kind {
|
||||
ToneKind::Highlights => x + knot((g - lo) / span, &self.knots[0]) * self.amount * excess((x - g).max(0.0), self.sigma),
|
||||
ToneKind::Shadows => {
|
||||
let below = ((g - x) / self.sigma).clamp(0.0, 1.0);
|
||||
if below == 0.0 {
|
||||
return x;
|
||||
}
|
||||
let w = below * below * (3.0 - 2.0 * below);
|
||||
x + self.amount * knot((x - lo) / span, &self.knots[0]) * knot((g - lo) / span, &self.knots[1]) * w
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pass on the log luminance `u`: the filter, then the kept quantile put back.
|
||||
fn run(&self, u: &Plane) -> Plane {
|
||||
let (lo, hi) = range(u);
|
||||
let span = (hi - lo).max(1.0);
|
||||
let o = llf(u, |x, g| self.remap(x, g, lo, span));
|
||||
let shift = quantile(&u.v, self.keep) - quantile(&o.v, self.keep);
|
||||
Plane { w: o.w, h: o.h, v: o.v.iter().map(|v| v + shift).collect() }
|
||||
}
|
||||
}
|
||||
|
||||
/// One channel, `w × h`.
|
||||
struct Plane {
|
||||
w: usize,
|
||||
h: usize,
|
||||
v: Vec<f32>,
|
||||
}
|
||||
|
||||
/// Mirrors `i` into `0..n` (the edge sample is not repeated).
|
||||
fn mirror(i: isize, n: usize) -> usize {
|
||||
let n = n as isize;
|
||||
if n == 1 {
|
||||
return 0;
|
||||
}
|
||||
let p = 2 * (n - 1);
|
||||
let m = i.rem_euclid(p);
|
||||
(if m >= n { p - m } else { m }) as usize
|
||||
}
|
||||
|
||||
/// The pyramid's binomial kernel.
|
||||
pub const TAPS: [f32; 5] = [1.0 / 16.0, 4.0 / 16.0, 6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0];
|
||||
|
||||
/// Planes smaller than this run their rows on one thread: the filter builds a whole pyramid per
|
||||
/// reference (up to 96), and splitting its small levels into one-row tasks cost more in rayon's
|
||||
/// scheduling than the rows themselves (a fifth of a Shadows render on 36 MP, measured).
|
||||
const PAR_MIN: usize = 1 << 15;
|
||||
|
||||
/// [`par_rows`] for a plane, on one thread when it is small (see [`PAR_MIN`]).
|
||||
fn rows(buf: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32]) + Sync + Send) {
|
||||
if buf.len() < PAR_MIN {
|
||||
buf.chunks_mut(w.max(1)).enumerate().for_each(|(y, row)| f(y, row));
|
||||
} else {
|
||||
par_rows(buf, w, 1, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// The binomial 5-tap blur, sampled every `step` pixels from 0 (1 = full resolution).
|
||||
fn blur_step(p: &Plane, step: usize) -> Plane {
|
||||
let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step));
|
||||
// Columns first at the kept rows, then rows at the kept columns. Each sum adds the same terms
|
||||
// in the same order as a `mirror` per tap would, so the result is bit for bit the same; the
|
||||
// source rows are found once per row and the columns mirrored only near the edges.
|
||||
let mut tmp = vec![0.0f32; p.w * h2];
|
||||
rows(&mut tmp, p.w, |y2, row| {
|
||||
let y = (y2 * step) as isize;
|
||||
let src: [&[f32]; 5] = std::array::from_fn(|k| {
|
||||
let r = mirror(y + k as isize - 2, p.h);
|
||||
&p.v[r * p.w..(r + 1) * p.w]
|
||||
});
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
*o = (0..5).map(|k| TAPS[k] * src[k][x]).sum();
|
||||
}
|
||||
});
|
||||
let mut out = vec![0.0f32; w2 * h2];
|
||||
rows(&mut out, w2, |y2, row| {
|
||||
let src = &tmp[y2 * p.w..(y2 + 1) * p.w];
|
||||
for (x2, o) in row.iter_mut().enumerate() {
|
||||
let x = x2 * step;
|
||||
*o = if x >= 2 && x + 2 < p.w {
|
||||
let s = &src[x - 2..x + 3];
|
||||
(0..5).map(|k| TAPS[k] * s[k]).sum()
|
||||
} else {
|
||||
(0..5).map(|k| TAPS[k] * src[mirror(x as isize + k as isize - 2, p.w)]).sum()
|
||||
};
|
||||
}
|
||||
});
|
||||
Plane { w: w2, h: h2, v: out }
|
||||
}
|
||||
|
||||
/// The next coarser level.
|
||||
fn down(p: &Plane) -> Plane {
|
||||
blur_step(p, 2)
|
||||
}
|
||||
|
||||
/// `p` brought up to `w × h`: zeros between samples, then the blur times four.
|
||||
///
|
||||
/// Three samples in four are zero, so their taps are skipped instead of blurring a zero-filled
|
||||
/// plane: the nonzero terms are added in the same order (skipping `+0.0` terms changes at most the
|
||||
/// sign of a zero, and the filter only adds and exponentiates these values).
|
||||
fn up(p: &Plane, w: usize, h: usize) -> Plane {
|
||||
let (lh, lw) = (p.h.min(h.div_ceil(2)), p.w.min(w.div_ceil(2)));
|
||||
// The source sample behind index `i` of a zero-stuffed axis of length `n` holding `lim` samples.
|
||||
let src = |i: isize, n: usize, lim: usize| {
|
||||
let m = mirror(i, n);
|
||||
(m.is_multiple_of(2) && m / 2 < lim).then_some(m / 2)
|
||||
};
|
||||
// Columns first, only at the even columns (the odd ones are all zero).
|
||||
let mut tmp = vec![0.0f32; lw * h];
|
||||
if lw > 0 {
|
||||
rows(&mut tmp, lw, |y, row| {
|
||||
let taps: [Option<&[f32]>; 5] = std::array::from_fn(|k| src(y as isize + k as isize - 2, h, lh).map(|r| &p.v[r * p.w..r * p.w + lw]));
|
||||
for (j, o) in row.iter_mut().enumerate() {
|
||||
*o = (0..5).filter_map(|k| taps[k].map(|s| TAPS[k] * (s[j] * 4.0))).sum();
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut out = vec![0.0f32; w * h];
|
||||
rows(&mut out, w, |y, row| {
|
||||
let t = &tmp[y * lw..(y + 1) * lw];
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
*o = if x >= 2 && x + 2 < w {
|
||||
// Away from the edges no tap mirrors.
|
||||
(0..5)
|
||||
.filter_map(|k| {
|
||||
let i = x + k - 2;
|
||||
(i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * t[i / 2])
|
||||
})
|
||||
.sum()
|
||||
} else {
|
||||
(0..5).filter_map(|k| src(x as isize + k as isize - 2, w, lw).map(|j| TAPS[k] * t[j])).sum()
|
||||
};
|
||||
}
|
||||
});
|
||||
Plane { w, h, v: out }
|
||||
}
|
||||
|
||||
/// The source rows of [`up`]`(p, w, h)` at output row `y`, one per tap (`None` where the
|
||||
/// zero-stuffed row is all zeros).
|
||||
fn up_rows(p: &Plane, h: usize, y: usize) -> [Option<usize>; 5] {
|
||||
let lh = p.h.min(h.div_ceil(2));
|
||||
std::array::from_fn(|k| {
|
||||
let m = mirror(y as isize + k as isize - 2, h);
|
||||
(m.is_multiple_of(2) && m / 2 < lh).then_some(m / 2)
|
||||
})
|
||||
}
|
||||
|
||||
/// One sample of [`up`]`(p, w, h)`: column `x` of the output row whose [`up_rows`] are `rows`.
|
||||
/// It adds the same terms in the same order as `up`, so it gives the same bits.
|
||||
fn up_at(p: &Plane, w: usize, rows: &[Option<usize>; 5], x: usize) -> f32 {
|
||||
let lw = p.w.min(w.div_ceil(2));
|
||||
let col = |j: usize| -> f32 { (0..5).filter_map(|k| rows[k].map(|r| TAPS[k] * (p.v[r * p.w + j] * 4.0))).sum() };
|
||||
if x >= 2 && x + 2 < w {
|
||||
// Away from the edges no tap mirrors.
|
||||
(0..5)
|
||||
.filter_map(|k| {
|
||||
let i = x + k - 2;
|
||||
(i.is_multiple_of(2) && i / 2 < lw).then(|| TAPS[k] * col(i / 2))
|
||||
})
|
||||
.sum()
|
||||
} else {
|
||||
(0..5)
|
||||
.filter_map(|k| {
|
||||
let m = mirror(x as isize + k as isize - 2, w);
|
||||
(m.is_multiple_of(2) && m / 2 < lw).then(|| TAPS[k] * col(m / 2))
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// Levels down to about 2 pixels on the short side.
|
||||
fn depth(w: usize, h: usize) -> usize {
|
||||
let mut s = w.min(h);
|
||||
let mut n = 1;
|
||||
while s > 2 {
|
||||
s = s.div_ceil(2);
|
||||
n += 1;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn gaussian(p: Plane, n: usize) -> Vec<Plane> {
|
||||
let mut g = vec![p];
|
||||
for _ in 1..n {
|
||||
let next = down(&g[g.len() - 1]);
|
||||
g.push(next);
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
/// The local Laplacian filter of `u` with `remap(value, reference)`; the coarsest level is kept.
|
||||
fn llf(u: &Plane, remap: impl Fn(f32, f32) -> f32 + Sync) -> Plane {
|
||||
let n = depth(u.w, u.h);
|
||||
let g = gaussian(Plane { w: u.w, h: u.h, v: u.v.clone() }, n);
|
||||
// References span the image's tones (see `REF_LOW_QUANTILE`).
|
||||
let hi = u.v.iter().fold(f32::NEG_INFINITY, |a, &v| a.max(v));
|
||||
let lo = quantile(&u.v, REF_LOW_QUANTILE).min(hi);
|
||||
if hi - lo <= 1e-6 || (hi - lo).is_nan() {
|
||||
return Plane { w: u.w, h: u.h, v: u.v.clone() };
|
||||
}
|
||||
let refs = (((hi - lo) / REF_STEP).ceil() as usize + 1).clamp(2, MAX_REFS);
|
||||
let step = (hi - lo) / (refs - 1) as f32;
|
||||
let mut lap: Vec<Vec<f32>> = g[..n - 1].iter().map(|p| vec![0.0; p.v.len()]).collect();
|
||||
for k in 0..refs {
|
||||
let r = lo + step * k as f32;
|
||||
let mut m = Plane { w: u.w, h: u.h, v: u.v.clone() };
|
||||
rows(&mut m.v, u.w, |_, row| {
|
||||
for v in row.iter_mut() {
|
||||
*v = remap(*v, r);
|
||||
}
|
||||
});
|
||||
let gr = gaussian(m, n);
|
||||
for l in 0..n - 1 {
|
||||
let (gl, fine, lw, lh, coarse) = (&g[l].v, &gr[l].v, g[l].w, g[l].h, &gr[l + 1]);
|
||||
rows(&mut lap[l], lw, |y, row| {
|
||||
let taps = up_rows(coarse, lh, y);
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
let i = y * lw + x;
|
||||
let wgt = (1.0 - (gl[i].clamp(lo, hi) - r).abs() / step).max(0.0);
|
||||
if wgt > 0.0 {
|
||||
*o += wgt * (fine[i] - up_at(coarse, lw, &taps, x));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut o = Plane { w: g[n - 1].w, h: g[n - 1].h, v: g[n - 1].v.clone() };
|
||||
for l in (0..n - 1).rev() {
|
||||
let mut next = up(&o, g[l].w, g[l].h);
|
||||
for (a, b) in next.v.iter_mut().zip(&lap[l]) {
|
||||
*a += b;
|
||||
}
|
||||
o = next;
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// The `q` quantile (0 … 1) of `v`.
|
||||
fn quantile(v: &[f32], q: f32) -> f32 {
|
||||
let mut s = v.to_vec();
|
||||
// Selecting the one element is linear, a full sort is not (5 sorts of the work copy were a
|
||||
// fifteenth of a render). `total_cmp` ties are bit-identical, so it is the sorted element.
|
||||
let i = quantile_rank(s.len(), q);
|
||||
*s.select_nth_unstable_by(i, f32::total_cmp).1
|
||||
}
|
||||
|
||||
/// The image range: [`RANGE_QUANTILES`] of the log luminance on a copy at most [`RANGE_SIDE`]
|
||||
/// pixels across.
|
||||
fn range(u: &Plane) -> (f32, f32) {
|
||||
let f = u.w.max(u.h).div_ceil(RANGE_SIDE).max(1);
|
||||
let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f));
|
||||
let mut sum = vec![(0.0f64, 0u32); sw * sh];
|
||||
for y in 0..u.h {
|
||||
for x in 0..u.w {
|
||||
let c = &mut sum[(y / f) * sw + x / f];
|
||||
c.0 += f64::from(u.v[y * u.w + x]);
|
||||
c.1 += 1;
|
||||
}
|
||||
}
|
||||
let cells: Vec<f32> = sum.iter().filter(|c| c.1 > 0).map(|c| (c.0 / f64::from(c.1)) as f32).collect();
|
||||
(quantile(&cells, RANGE_QUANTILES[0]), quantile(&cells, RANGE_QUANTILES[1]))
|
||||
}
|
||||
|
||||
/// `d` past the detail threshold: about 0 below `sigma`, `d − sigma` well above it.
|
||||
fn excess(d: f32, sigma: f32) -> f32 {
|
||||
d - sigma * (d / sigma).tanh()
|
||||
}
|
||||
|
||||
fn knot(t: f32, k: &[f32; KNOTS]) -> f32 {
|
||||
let x = t.clamp(0.0, 1.0) * (KNOTS - 1) as f32;
|
||||
let i = (x as usize).min(KNOTS - 2);
|
||||
k[i] + (k[i + 1] - k[i]) * (x - i as f32)
|
||||
}
|
||||
|
||||
/// Applies Shadows and Highlights (−100 … 100) to straight RGBA pixels encoded with `enc`
|
||||
/// (`Encoding::of(DevelopInputs::encoding_gamma)`). The filter is deterministic, so it reads no grain seed.
|
||||
pub(crate) fn apply(px: &mut [[f32; 4]], w: usize, h: usize, shadows: f32, highlights: f32, enc: Encoding) {
|
||||
let Some(tone) = LocalTone::new(shadows, highlights) else { return };
|
||||
if w < 2 || h < 2 {
|
||||
return;
|
||||
}
|
||||
let u = Plane { w, h, v: px.iter().map(|q| (luma([0, 1, 2].map(|c| enc.decode(q[c]))).max(0.0) + LOG_FLOOR).log2()).collect() };
|
||||
// The filter on a copy at most WORK_SIDE across (box-averaged in log).
|
||||
let f = w.max(h).div_ceil(WORK_SIDE).max(1);
|
||||
let small = if f == 1 { Plane { w, h, v: u.v.clone() } } else { shrink(&u, f) };
|
||||
let mut o = Plane { w: small.w, h: small.h, v: small.v.clone() };
|
||||
for pass in &tone.passes {
|
||||
o = pass.run(&o);
|
||||
}
|
||||
// The change in log luminance, at full size.
|
||||
let change: Vec<f32> = if f == 1 {
|
||||
o.v.iter().zip(&u.v).map(|(a, b)| a - b).collect()
|
||||
} else {
|
||||
let d: Vec<f32> = o.v.iter().zip(&small.v).map(|(a, b)| a - b).collect();
|
||||
guided_upsample(&small, &d, &u)
|
||||
};
|
||||
par_rows(px, w, 1, |y, row| {
|
||||
for (x, q) in row.iter_mut().enumerate() {
|
||||
let gain = change[y * w + x].exp2();
|
||||
for c in 0..3 {
|
||||
q[c] = enc.encode(enc.decode(q[c]) * gain);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// `u` averaged over `f × f` blocks.
|
||||
fn shrink(u: &Plane, f: usize) -> Plane {
|
||||
let (sw, sh) = (u.w.div_ceil(f), u.h.div_ceil(f));
|
||||
let mut v = vec![0.0f32; sw * sh];
|
||||
par_rows(&mut v, sw, 1, |y, row| {
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
let (x0, y0) = (x * f, y * f);
|
||||
let (x1, y1) = ((x0 + f).min(u.w), (y0 + f).min(u.h));
|
||||
let mut s = 0.0f64;
|
||||
for yy in y0..y1 {
|
||||
for xx in x0..x1 {
|
||||
s += f64::from(u.v[yy * u.w + xx]);
|
||||
}
|
||||
}
|
||||
*o = (s / ((x1 - x0) * (y1 - y0)) as f64) as f32;
|
||||
}
|
||||
});
|
||||
Plane { w: sw, h: sh, v }
|
||||
}
|
||||
|
||||
/// The change `d` computed on `small` brought to the size of `full`, following its edges: a local
|
||||
/// linear model of the change against the log luminance (the guided filter of K. He, J. Sun,
|
||||
/// *Fast Guided Filter*, 2015), fitted on the small copy and evaluated on the full one.
|
||||
fn guided_upsample(small: &Plane, d: &[f32], full: &Plane) -> Vec<f32> {
|
||||
let (sw, sh) = (small.w, small.h);
|
||||
let r = 2;
|
||||
let eps = 0.01;
|
||||
let mean = |v: &[f32]| super::box_mean(v, sw, sh, r);
|
||||
let ud: Vec<f32> = small.v.iter().zip(d).map(|(a, b)| a * b).collect();
|
||||
let uu: Vec<f32> = small.v.iter().map(|a| a * a).collect();
|
||||
let (mu, md, mud, muu) = (mean(&small.v), mean(d), mean(&ud), mean(&uu));
|
||||
let a: Vec<f32> = (0..sw * sh).map(|i| (mud[i] - mu[i] * md[i]) / (muu[i] - mu[i] * mu[i] + eps)).collect();
|
||||
let b: Vec<f32> = (0..sw * sh).map(|i| md[i] - a[i] * mu[i]).collect();
|
||||
let (ma, mb) = (mean(&a), mean(&b));
|
||||
let (fx, fy) = (sw as f32 / full.w as f32, sh as f32 / full.h as f32);
|
||||
let mut out = vec![0.0f32; full.w * full.h];
|
||||
par_rows(&mut out, full.w, 1, |y, row| {
|
||||
let sy = (y as f32 + 0.5) * fy - 0.5;
|
||||
for (x, o) in row.iter_mut().enumerate() {
|
||||
let sx = (x as f32 + 0.5) * fx - 0.5;
|
||||
let av = crate::photo_util::bilinear(&ma, sw, sh, 1, 0, sx, sy);
|
||||
let bv = crate::photo_util::bilinear(&mb, sw, sh, 1, 0, sx, sy);
|
||||
*o = av * full.v[y * full.w + x] + bv;
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SRGB: Encoding = Encoding(0.0);
|
||||
|
||||
/// The plain blur: a `mirror` per tap over the whole plane, the reference for [`blur_step`].
|
||||
fn blur_step_reference(p: &Plane, step: usize) -> Plane {
|
||||
let (w2, h2) = (p.w.div_ceil(step), p.h.div_ceil(step));
|
||||
let mut tmp = vec![0.0f32; p.w * h2];
|
||||
for y2 in 0..h2 {
|
||||
for x in 0..p.w {
|
||||
tmp[y2 * p.w + x] = (0..5).map(|k| TAPS[k] * p.v[mirror((y2 * step) as isize + k as isize - 2, p.h) * p.w + x]).sum();
|
||||
}
|
||||
}
|
||||
let mut out = vec![0.0f32; w2 * h2];
|
||||
for y2 in 0..h2 {
|
||||
for x2 in 0..w2 {
|
||||
out[y2 * w2 + x2] = (0..5).map(|k| TAPS[k] * tmp[y2 * p.w + mirror((x2 * step) as isize + k as isize - 2, p.w)]).sum();
|
||||
}
|
||||
}
|
||||
Plane { w: w2, h: h2, v: out }
|
||||
}
|
||||
|
||||
/// The plain upsampling: a zero-stuffed plane blurred whole, the reference for [`up`].
|
||||
fn up_reference(p: &Plane, w: usize, h: usize) -> Plane {
|
||||
let mut z = Plane { w, h, v: vec![0.0; w * h] };
|
||||
for y in 0..p.h.min(h.div_ceil(2)) {
|
||||
for x in 0..p.w.min(w.div_ceil(2)) {
|
||||
z.v[2 * y * w + 2 * x] = p.v[y * p.w + x] * 4.0;
|
||||
}
|
||||
}
|
||||
blur_step_reference(&z, 1)
|
||||
}
|
||||
|
||||
fn noise_plane(w: usize, h: usize, seed: u32) -> Plane {
|
||||
let mut s = seed.wrapping_mul(2_654_435_761).max(1);
|
||||
let v = (0..w * h)
|
||||
.map(|_| {
|
||||
s ^= s << 13;
|
||||
s ^= s >> 17;
|
||||
s ^= s << 5;
|
||||
(s % 20_000) as f32 / 1000.0 - 16.0
|
||||
})
|
||||
.collect();
|
||||
Plane { w, h, v }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fast_pyramid_matches_the_plain_one_exactly() {
|
||||
// Odd, even, tiny and large-enough-to-run-in-parallel sizes, as the pyramid's levels are.
|
||||
for (i, (w, h)) in [(1, 1), (1, 7), (2, 2), (3, 5), (5, 3), (8, 6), (37, 23), (64, 64), (301, 211)].into_iter().enumerate() {
|
||||
let p = noise_plane(w, h, i as u32 + 1);
|
||||
for step in [1, 2] {
|
||||
assert_eq!(blur_step(&p, step).v, blur_step_reference(&p, step).v, "blur {w}×{h} step {step}");
|
||||
}
|
||||
for (uw, uh) in [(w * 2, h * 2), (w * 2 - 1, h * 2 - 1), (w * 2, h * 2 - 1), (w.max(2) * 2 - 3, h * 2)] {
|
||||
let full = up(&p, uw, uh);
|
||||
assert_eq!(full.v, up_reference(&p, uw, uh).v, "up {w}×{h} → {uw}×{uh}");
|
||||
// The filter samples `up` one pixel at a time; every sample has the same bits.
|
||||
for y in 0..uh {
|
||||
let taps = up_rows(&p, uh, y);
|
||||
for x in 0..uw {
|
||||
assert_eq!(up_at(&p, uw, &taps, x).to_bits(), full.v[y * uw + x].to_bits(), "up_at {w}×{h} → {uw}×{uh} at {x},{y}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantile_is_the_sorted_element() {
|
||||
let p = noise_plane(301, 211, 9);
|
||||
let mut v = p.v.clone();
|
||||
// Ties and signed zeros, which `total_cmp` orders by their bits.
|
||||
v.extend([0.0, -0.0, 0.0, -0.0, 3.5, 3.5, f32::MIN_POSITIVE]);
|
||||
let mut sorted = v.clone();
|
||||
sorted.sort_by(f32::total_cmp);
|
||||
for q in [0.0, 0.001, 0.01, 0.25, 0.5, 0.99, 1.0] {
|
||||
let want = sorted[((sorted.len() - 1) as f32 * q).round() as usize];
|
||||
assert_eq!(quantile(&v, q).to_bits(), want.to_bits(), "q {q}");
|
||||
}
|
||||
}
|
||||
|
||||
fn grey(w: usize, h: usize, f: impl Fn(usize, usize) -> f32) -> Vec<[f32; 4]> {
|
||||
(0..w * h).map(|i| f(i % w, i / w)).map(|v| [v, v, v, 1.0]).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flat_image_is_unchanged() {
|
||||
let mut px = grey(64, 48, |_, _| 0.4);
|
||||
apply(&mut px, 64, 48, 100.0, -100.0, SRGB);
|
||||
assert!(px.iter().all(|q| (q[0] - 0.4).abs() < 1e-5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadows_raise_a_dark_area_without_a_halo() {
|
||||
// A 0.1 | 0.6 step (the dark half is the image's black point, which Photoshop barely
|
||||
// moves either): the bright half stays, and no halo forms on either side of the edge.
|
||||
let (w, h) = (256, 128);
|
||||
let mut px = grey(w, h, |x, _| if x < w / 2 { 0.1 } else { 0.6 });
|
||||
apply(&mut px, w, h, 100.0, 0.0, SRGB);
|
||||
let row = &px[64 * w..65 * w];
|
||||
assert!((row[w / 2 + 1][0] - 0.6).abs() < 0.002 && (row[w - 5][0] - 0.6).abs() < 0.002);
|
||||
let (far, near) = (row[10][0], row[w / 2 - 1][0]);
|
||||
assert!((far - 0.1).abs() < 0.004 && (far - near).abs() < 0.004, "{far} {near}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grey_moves_as_in_photoshop() {
|
||||
// Mid-grey with 1 % black (0.015) and white (0.97) corners, Photoshop 25.4: Shadows +100
|
||||
// takes the grey from 127.5 to 165.3, Highlights −100 to 89.6 (of 255).
|
||||
let n = 256;
|
||||
let image = |c: f32| {
|
||||
grey(n, n, |x, y| {
|
||||
if x >= n - 26 && y >= n - 26 {
|
||||
0.97
|
||||
} else if x >= n - 26 && y < 26 {
|
||||
0.015
|
||||
} else {
|
||||
c
|
||||
}
|
||||
})
|
||||
};
|
||||
for (s, hl, want) in [(100.0, 0.0, 165.3), (0.0, -100.0, 89.6)] {
|
||||
let mut px = image(0.5);
|
||||
apply(&mut px, n, n, s, hl, SRGB);
|
||||
let got = px[175 * n + 100][0] * 255.0;
|
||||
assert!((got - want).abs() < 5.0, "{s} {hl}: {got} vs {want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlights_lower_a_bright_area_and_keep_the_darkest() {
|
||||
let (w, h) = (192, 192);
|
||||
let mut px = grey(w, h, |x, y| if (64..128).contains(&x) && (64..128).contains(&y) { 0.8 } else { 0.2 });
|
||||
apply(&mut px, w, h, 0.0, -100.0, SRGB);
|
||||
assert!(px[96 * w + 96][0] < 0.75, "{}", px[96 * w + 96][0]);
|
||||
assert!((px[5 * w + 5][0] - 0.2).abs() < 0.01, "{}", px[5 * w + 5][0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_gradients_stay_smooth() {
|
||||
// A soft ramp over eight stops, as in an out-of-focus background. Coefficients interpolated
|
||||
// between references too far apart drew contour lines across such ramps (Shadows +100 on
|
||||
// a D4 raw): the output must rise steadily, without ripples.
|
||||
let (w, h) = (640, 48);
|
||||
let mut px = grey(w, h, |x, _| crate::photo_util::linear_to_srgb((x as f32 / (w - 1) as f32 * 8.0 - 9.0).exp2()));
|
||||
for (s, hl) in [(100.0, 0.0), (0.0, -100.0), (-100.0, 100.0)] {
|
||||
let mut p = px.clone();
|
||||
apply(&mut p, w, h, s, hl, SRGB);
|
||||
let row: Vec<f32> = (0..w).map(|x| crate::photo_util::srgb_to_linear(p[24 * w + x][0]).max(1e-6).log2()).collect();
|
||||
let steps: Vec<f32> = row.windows(2).map(|d| d[1] - d[0]).collect();
|
||||
assert!(steps.iter().all(|d| *d > 0.0), "{s} {hl}: the ramp reverses");
|
||||
let jumps: Vec<f32> = steps.windows(2).map(|d| (d[1] - d[0]).abs()).collect();
|
||||
let ripple = jumps[16..jumps.len() - 16].iter().fold(0.0f32, |a, b| a.max(*b));
|
||||
// The ramp rises 0.0125 stops per pixel; its slope may change by a third at most.
|
||||
assert!(ripple < 0.004, "{s} {hl}: slope jumps by {ripple} stops per pixel");
|
||||
}
|
||||
px.clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_result_does_not_depend_on_the_image_size() {
|
||||
let at = |n: usize| {
|
||||
let mut px = grey(n, n, |x, y| if x < n / 3 || y < n / 4 { 0.08 } else { 0.7 });
|
||||
apply(&mut px, n, n, 70.0, -60.0, SRGB);
|
||||
[px[(n / 8) * n + n / 8][0], px[(3 * n / 4) * n + 3 * n / 4][0]]
|
||||
};
|
||||
let (a, b) = (at(96), at(384));
|
||||
assert!((a[0] - b[0]).abs() < 0.02 && (a[1] - b[1]).abs() < 0.02, "{a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
@@ -1,284 +0,0 @@
|
||||
//! Develop's stages resolved for one image: every constant and table the per-pixel ones use, so
|
||||
//! another implementation of them (the GPU preview, `photocraft_gpu::CameraRawDevelop`) runs the
|
||||
//! same maths. [`develop`](super::develop) builds its own constants with the same functions.
|
||||
//! The spatial stages other than Detail come as their parameters: Dehaze, Clarity and Texture
|
||||
//! (see [`spatial`](super::spatial)), Shadows and Highlights as a [`LocalTone`].
|
||||
|
||||
use super::local_tone::{LocalTone, WORK_SIDE};
|
||||
use super::spatial::{Clarity, Dehaze, Texture};
|
||||
use super::{
|
||||
CameraRaw, DevelopInputs, Encoding, Wheel, calibration_neutral, curve_lut, grade_neutral, hsl_neutral, hsv_to_rgb, is_linear, luma, parametric_lut,
|
||||
white_balance_gains, whites_blacks,
|
||||
};
|
||||
use craft::imaging::raw::VignetteStyle as StoredStyle;
|
||||
|
||||
pub use whites_blacks::Model as WhitesBlacksModel;
|
||||
|
||||
/// Entries of the tone curve tables (parametric and point curves).
|
||||
pub const CURVE_LUT: usize = 1024;
|
||||
/// Samples of a Whites or Blacks curve row: grey levels 0, 1/32, …, 1.
|
||||
pub const WB_STEPS: usize = whites_blacks::STEPS;
|
||||
|
||||
/// White balance and exposure: channel gains in linear light, when the stage is on.
|
||||
pub(crate) fn gains(p: &CameraRaw) -> Option<[f32; 3]> {
|
||||
if p.temperature == 0.0 && p.tint == 0.0 && p.exposure == 0.0 {
|
||||
return None;
|
||||
}
|
||||
let g = white_balance_gains(p.temperature, p.tint);
|
||||
let norm = luma(g);
|
||||
Some(g.map(|v| v / norm * 2f32.powf(p.exposure)))
|
||||
}
|
||||
|
||||
/// Contrast's strength, when Contrast is set (with or without Texture and Clarity).
|
||||
fn contrast(p: &CameraRaw) -> Option<f32> {
|
||||
(p.contrast != 0.0).then_some(p.contrast / 100.0 * 0.6)
|
||||
}
|
||||
|
||||
/// Whites and Blacks' tables, for an implementation that measures the image's points itself.
|
||||
pub fn whites_blacks_model() -> WhitesBlacksModel {
|
||||
whites_blacks::model()
|
||||
}
|
||||
|
||||
/// Whites and Blacks as two curve rows for the image's amounts.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct WhitesBlacks {
|
||||
/// The Whites curve over grey levels 0, 1/32, …, 1, when Whites is set.
|
||||
pub whites: Option<[f32; WB_STEPS]>,
|
||||
/// The Blacks curve, applied after Whites.
|
||||
pub blacks: Option<[f32; WB_STEPS]>,
|
||||
/// The clipping directions (Whites up, Blacks down) curve each channel; the others scale the
|
||||
/// pixel by the change of its luminance.
|
||||
pub per_channel: bool,
|
||||
}
|
||||
|
||||
/// Color Grading's wheels resolved.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Grade {
|
||||
/// Colour offsets of the shadows, midtones, highlights and global wheels.
|
||||
pub tints: [[f32; 3]; 4],
|
||||
/// Luminance of the same wheels (slider units).
|
||||
pub lums: [f32; 4],
|
||||
pub blend: f32,
|
||||
pub balance: f32,
|
||||
}
|
||||
|
||||
impl Grade {
|
||||
pub(crate) fn new(p: &CameraRaw) -> Self {
|
||||
let tint = |wh: &Wheel| -> [f32; 3] {
|
||||
let c = hsv_to_rgb(wh.hue, 1.0, 1.0);
|
||||
let l = luma(c);
|
||||
[c[0] - l, c[1] - l, c[2] - l].map(|v| v * wh.sat / 100.0 * 0.3)
|
||||
};
|
||||
Grade {
|
||||
tints: [tint(&p.grade_shadows), tint(&p.grade_midtones), tint(&p.grade_highlights), tint(&p.grade_global)],
|
||||
lums: [p.grade_shadows.lum, p.grade_midtones.lum, p.grade_highlights.lum, p.grade_global.lum],
|
||||
blend: 0.15 + p.grade_blending.clamp(0.0, 100.0) / 100.0 * 0.35,
|
||||
balance: p.grade_balance.clamp(-100.0, 100.0) / 100.0 * 0.25,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The vignette's `vignette_style`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum VignetteStyle {
|
||||
HighlightPriority,
|
||||
ColorPriority,
|
||||
PaintOverlay,
|
||||
}
|
||||
|
||||
/// The post-crop vignette's shape on a `w × h` frame.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Vignette {
|
||||
/// −1 … 1.
|
||||
pub amount: f32,
|
||||
/// 0 … 1.
|
||||
pub highlights: f32,
|
||||
pub style: VignetteStyle,
|
||||
/// Frame centre (pixels).
|
||||
pub centre: [f32; 2],
|
||||
/// Half axes of the shape (pixels).
|
||||
pub axes: [f32; 2],
|
||||
/// Exponent of the superellipse.
|
||||
pub power: f32,
|
||||
/// The mask's smoothstep edges in normalised radius.
|
||||
pub edges: [f32; 2],
|
||||
}
|
||||
|
||||
impl Vignette {
|
||||
pub(crate) fn new(w: usize, h: usize, p: &CameraRaw) -> Self {
|
||||
let mid = p.vignette_midpoint.clamp(0.0, 100.0) / 100.0;
|
||||
let feather = p.vignette_feather.clamp(0.0, 100.0) / 100.0;
|
||||
let round = p.vignette_roundness.clamp(-100.0, 100.0) / 100.0;
|
||||
let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0);
|
||||
// Roundness: 0 follows the frame's aspect, +1 a circle, −1 a rounded rectangle.
|
||||
let (ax, ay) = if round >= 0.0 {
|
||||
let r = cx.min(cy) + (cx.max(cy) - cx.min(cy)) * (1.0 - round);
|
||||
(if cx >= cy { r } else { cx }, if cy > cx { r } else { cy })
|
||||
} else {
|
||||
(cx, cy)
|
||||
};
|
||||
let inner = 1.0 - mid * 0.8;
|
||||
Vignette {
|
||||
amount: p.vignette_amount / 100.0,
|
||||
highlights: p.vignette_highlights.clamp(0.0, 100.0) / 100.0,
|
||||
style: match p.vignette_style {
|
||||
StoredStyle::PaintOverlay => VignetteStyle::PaintOverlay,
|
||||
StoredStyle::ColorPriority => VignetteStyle::ColorPriority,
|
||||
_ => VignetteStyle::HighlightPriority,
|
||||
},
|
||||
centre: [cx, cy],
|
||||
axes: [ax, ay],
|
||||
power: 2.0 + (-round).max(0.0) * 6.0,
|
||||
edges: [inner - feather * 0.5 * inner, inner + feather * 0.5 * (1.4 - inner) + 0.02],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Grain: value noise sampled in full-resolution coordinates.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Grain {
|
||||
/// Noise cell size (full-resolution pixels).
|
||||
pub cell: f32,
|
||||
/// Weight of the finer octave.
|
||||
pub roughness: f32,
|
||||
pub amount: f32,
|
||||
pub seed: u64,
|
||||
/// Full-resolution pixels per pixel (`1 / pixel_scale`).
|
||||
pub scale: f32,
|
||||
}
|
||||
|
||||
impl Grain {
|
||||
pub(crate) fn new(p: &CameraRaw, inputs: &DevelopInputs) -> Self {
|
||||
Grain {
|
||||
cell: 1.0 + p.grain_size / 25.0,
|
||||
roughness: p.grain_roughness / 100.0,
|
||||
amount: p.grain_amount / 100.0 * 0.12,
|
||||
seed: u64::from(inputs.seed),
|
||||
scale: 1.0 / inputs.pixel_scale.clamp(0.01, 1.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Develop's per-pixel stages for one image and settings, in order. `None` stages are off.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PerPixel {
|
||||
/// 1. White balance and exposure gains in linear light (sRGB-decoded values).
|
||||
pub gains: Option<[f32; 3]>,
|
||||
/// 2. Dehaze.
|
||||
pub dehaze: Option<Dehaze>,
|
||||
/// 3. Shadows and Highlights: a local Laplacian filter of the whole frame, then each pixel's
|
||||
/// light scaled by the change of its log luminance.
|
||||
pub local_tone: Option<LocalTone>,
|
||||
/// 3. Clarity and Texture on the luminance clipped to 1, before Contrast.
|
||||
pub clarity: Option<Clarity>,
|
||||
pub texture: Option<Texture>,
|
||||
/// 3. Contrast's strength.
|
||||
pub contrast: Option<f32>,
|
||||
/// 3b. Whites and Blacks, in the document's encoding.
|
||||
pub whites_blacks: Option<WhitesBlacks>,
|
||||
/// 3b. Whites and Blacks to measure the image's points for (the sliders, −100 … 100), when a
|
||||
/// spatial stage is set: the points then depend on its output, so whatever runs it
|
||||
/// measures them and picks the curves from [`whites_blacks_model`]. `whites_blacks` is
|
||||
/// then `None`.
|
||||
pub measure_whites_blacks: Option<[f32; 2]>,
|
||||
/// The document's transfer curve: 0 for sRGB's, else a power-law gamma.
|
||||
pub encoding: f32,
|
||||
/// 4. Vibrance and Saturation (slider / 100).
|
||||
pub presence: Option<[f32; 2]>,
|
||||
/// 5. The parametric tone curve, [`CURVE_LUT`] entries over 0 … 1.
|
||||
pub parametric: Option<Vec<f32>>,
|
||||
/// 5. Point curves: master, red, green, blue.
|
||||
pub point: [Option<Vec<f32>>; 4],
|
||||
/// 6. Color Mixer hue, saturation and luminance per band.
|
||||
pub hsl: Option<[[f32; 8]; 3]>,
|
||||
/// 7. Color Grading.
|
||||
pub grade: Option<Grade>,
|
||||
/// 9. Vignette.
|
||||
pub vignette: Option<Vignette>,
|
||||
/// 9. Grain.
|
||||
pub grain: Option<Grain>,
|
||||
/// Clip RGB to 0 … 1 at the end (all but 32-bit documents).
|
||||
pub clamp: bool,
|
||||
}
|
||||
|
||||
/// Whether developing needs a stage that reads neighbouring pixels: Dehaze, Shadows and
|
||||
/// Highlights, Texture, Clarity, sharpening or noise reduction.
|
||||
pub fn spatial(p: &CameraRaw) -> bool {
|
||||
p.dehaze != 0.0 || [p.highlights, p.shadows, p.texture, p.clarity].iter().any(|v| *v != 0.0) || detail_on(p)
|
||||
}
|
||||
|
||||
/// Whether developing needs Detail: sharpening or noise reduction.
|
||||
fn detail_on(p: &CameraRaw) -> bool {
|
||||
p.sharpen_amount > 0.0 || p.noise_luminance > 0.0 || p.noise_color > 0.0
|
||||
}
|
||||
|
||||
/// The image's black and white points that Whites and Blacks adapt to, for `px` (`w × h`,
|
||||
/// display-encoded) developed per pixel with `p`: what [`develop`](super::develop) measures
|
||||
/// after white balance and Contrast. `None` when Whites and Blacks are 0 or `p` needs a
|
||||
/// spatial stage.
|
||||
pub fn white_black_points(px: &[[f32; 4]], w: usize, h: usize, p: &CameraRaw, inputs: &DevelopInputs) -> Option<(f32, f32)> {
|
||||
if (p.whites == 0.0 && p.blacks == 0.0) || spatial(p) || px.len() != w.saturating_mul(h) {
|
||||
return None;
|
||||
}
|
||||
let enc = Encoding::of(inputs.encoding_gamma);
|
||||
let (g, k_con) = (gains(p), contrast(p));
|
||||
Some(super::luminance_points(px, w, h, enc, |q| {
|
||||
let q = g.map_or(q, |g| super::balance(q, g));
|
||||
k_con.map_or(q, |k| super::contrast(q, k))
|
||||
}))
|
||||
}
|
||||
|
||||
/// Develop's stages for settings without Detail or Calibration, on a `w × h` image; `points` are
|
||||
/// the image's [`white_black_points`]. `None` when `p` needs Detail or Calibration (these stages
|
||||
/// run neither), Shadows or Highlights on a frame wider than the filter's working copy (the
|
||||
/// develop then filters a reduced copy) or only 2 pixels on its short side, or Whites or Blacks
|
||||
/// without a spatial stage and without `points`. The points themselves leave Calibration out, so a
|
||||
/// caller may cache them across Calibration changes.
|
||||
pub fn per_pixel(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize, float: bool, points: Option<(f32, f32)>) -> Option<PerPixel> {
|
||||
if detail_on(p) || !calibration_neutral(p) {
|
||||
return None;
|
||||
}
|
||||
// The develop leaves frames under 2 pixels on a side alone.
|
||||
let local_tone = if w >= 2 && h >= 2 { LocalTone::new(p.shadows, p.highlights) } else { None };
|
||||
// At 2 pixels on the short side the GPU pass's pyramid has one level, so the CPU develops it.
|
||||
if local_tone.is_some() && (w.max(h) > WORK_SIDE || w.min(h) <= 2) {
|
||||
return None;
|
||||
}
|
||||
let (dehaze, clarity, texture) = (Dehaze::new(p, w, h), Clarity::new(p, w, h), Texture::new(p, inputs, w, h));
|
||||
let spatial = local_tone.is_some() || dehaze.is_some() || clarity.is_some() || texture.is_some();
|
||||
let identity = p.is_identity();
|
||||
let wb_on = p.whites != 0.0 || p.blacks != 0.0;
|
||||
let measure_whites_blacks = (wb_on && spatial).then(|| [p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0)]);
|
||||
let whites_blacks = if wb_on && measure_whites_blacks.is_none() {
|
||||
let (bp, wp) = points?;
|
||||
let (xw, xb) = whites_blacks::amounts(p.whites.clamp(-100.0, 100.0), p.blacks.clamp(-100.0, 100.0), bp, wp);
|
||||
(xw != 0.0 || xb != 0.0).then(|| WhitesBlacks {
|
||||
whites: (xw != 0.0).then(|| whites_blacks::whites_row(xw)),
|
||||
blacks: (xb != 0.0).then(|| whites_blacks::blacks_row(xb)),
|
||||
per_channel: xw > 0.0 || xb < 0.0,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let parametric_on = !(p.curve_highlights == 0.0 && p.curve_lights == 0.0 && p.curve_darks == 0.0 && p.curve_shadows == 0.0);
|
||||
let pts = |c: &Vec<[f32; 2]>| (!is_linear(c)).then(|| curve_lut(c, CURVE_LUT));
|
||||
Some(PerPixel {
|
||||
gains: gains(p),
|
||||
dehaze,
|
||||
local_tone,
|
||||
clarity,
|
||||
texture,
|
||||
contrast: contrast(p),
|
||||
whites_blacks,
|
||||
measure_whites_blacks,
|
||||
encoding: Encoding::of(inputs.encoding_gamma).0,
|
||||
presence: (p.vibrance != 0.0 || p.saturation != 0.0).then_some([p.vibrance / 100.0, p.saturation / 100.0]),
|
||||
parametric: parametric_on.then(|| parametric_lut(p, CURVE_LUT)),
|
||||
point: [pts(&p.point_curve), pts(&p.point_curve_red), pts(&p.point_curve_green), pts(&p.point_curve_blue)],
|
||||
hsl: (!hsl_neutral(p)).then_some([p.hsl_hue, p.hsl_sat, p.hsl_lum]),
|
||||
grade: (!grade_neutral(p)).then(|| Grade::new(p)),
|
||||
vignette: (p.vignette_amount != 0.0).then(|| Vignette::new(w, h, p)),
|
||||
grain: (p.grain_amount > 0.0).then(|| Grain::new(p, inputs)),
|
||||
clamp: !float && !identity,
|
||||
})
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
//! Dehaze, Clarity and Texture resolved for one frame: the sizes, radii and constants their
|
||||
//! filters use, so another implementation of them (the GPU preview,
|
||||
//! `photocraft_gpu::CameraRawDevelop`) runs the same filters. [`develop`](super::develop) builds
|
||||
//! its own from the same constructors.
|
||||
//!
|
||||
//! - **Dehaze** follows the dark channel prior (K. He, J. Sun, X. Tang, *Single Image Haze Removal
|
||||
//! Using Dark Channel Prior*, CVPR 2009) on a box-averaged copy at most [`DEHAZE_SIDE`] pixels
|
||||
//! across, with the transmission refined by a guided filter (K. He, J. Sun, X. Tang, *Guided
|
||||
//! Image Filtering*, ECCV 2010) and brought back to full size bilinearly.
|
||||
//! - **Clarity** raises the luminance's difference from a fast guided filter of itself (K. He,
|
||||
//! J. Sun, *Fast Guided Filter*, arXiv 2015), weighted toward the midtones.
|
||||
//! - **Texture** raises its difference from a Gaussian blur (three box passes), limited to
|
||||
//! ±[`TEXTURE_LIMIT`].
|
||||
|
||||
use super::{CameraRaw, DevelopInputs};
|
||||
|
||||
/// Dehaze measures the haze on a copy at most this many pixels across.
|
||||
pub const DEHAZE_SIDE: usize = 768;
|
||||
/// The dark channel's minimum filter has a radius of the copy's long side over this, at least
|
||||
/// [`DEHAZE_MIN_RADIUS`].
|
||||
pub const DEHAZE_RADIUS_DIVISOR: usize = 60;
|
||||
/// See [`DEHAZE_RADIUS_DIVISOR`].
|
||||
pub const DEHAZE_MIN_RADIUS: usize = 2;
|
||||
/// The atmospheric light is the mean colour of the brightest 1 / this of the dark channel (at
|
||||
/// least one cell).
|
||||
pub const DEHAZE_AIR_FRACTION: usize = 1000;
|
||||
/// Each channel of the atmospheric light is at least this.
|
||||
pub const DEHAZE_AIR_FLOOR: f32 = 0.2;
|
||||
/// The share of the haze the raw transmission removes (the paper's ω).
|
||||
pub const DEHAZE_OMEGA: f32 = 0.95;
|
||||
/// The guided filter's regularisation for the transmission.
|
||||
pub const DEHAZE_EPS: f32 = 1e-3;
|
||||
/// The transmission is at least this.
|
||||
pub const DEHAZE_T_FLOOR: f32 = 0.1;
|
||||
/// Clarity's guided filter regularisation.
|
||||
pub const CLARITY_EPS: f32 = 0.005;
|
||||
/// Texture moves the luminance by at most this.
|
||||
pub const TEXTURE_LIMIT: f32 = 0.1;
|
||||
|
||||
/// Dehaze on a `w × h` frame.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Dehaze {
|
||||
/// The slider / 100 (−1 … 1).
|
||||
pub amount: f32,
|
||||
/// The copy averages `factor × factor` blocks.
|
||||
pub factor: usize,
|
||||
/// The copy's size.
|
||||
pub size: [usize; 2],
|
||||
/// The minimum filter's radius.
|
||||
pub radius: usize,
|
||||
/// The guided filter's radius.
|
||||
pub guide_radius: usize,
|
||||
/// How many of the copy's cells the atmospheric light averages.
|
||||
pub top: usize,
|
||||
}
|
||||
|
||||
impl Dehaze {
|
||||
/// Dehaze for `p` on a `w × h` frame; `None` when it is off.
|
||||
pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option<Self> {
|
||||
if p.dehaze == 0.0 {
|
||||
return None;
|
||||
}
|
||||
let factor = w.max(h).div_ceil(DEHAZE_SIDE).max(1);
|
||||
let size = [w.div_ceil(factor), h.div_ceil(factor)];
|
||||
let radius = (size[0].max(size[1]) / DEHAZE_RADIUS_DIVISOR).max(DEHAZE_MIN_RADIUS);
|
||||
Some(Dehaze { amount: p.dehaze / 100.0, factor, size, radius, guide_radius: radius * 2, top: (size[0] * size[1] / DEHAZE_AIR_FRACTION).max(1) })
|
||||
}
|
||||
|
||||
/// The copy the haze is measured on, for `px` (`w × h`, display-encoded) before white balance
|
||||
/// and exposure (`gains`, as in [`PerPixel`](super::PerPixel)): `size` cells in rows, each the
|
||||
/// mean light of its block, clipped to 0 … 1. These are exactly the cells
|
||||
/// [`develop`](super::develop) uses: the brightest of them set the atmospheric light, and a
|
||||
/// tie between them decides which, so another implementation that computes stage 1 to a few
|
||||
/// ulps should start from these. Empty when `px` isn't `w × h`.
|
||||
pub fn cells(&self, px: &[[f32; 4]], w: usize, h: usize, gains: Option<[f32; 3]>) -> Vec<[f32; 3]> {
|
||||
if px.len() != w.saturating_mul(h) || w.div_ceil(self.factor) != self.size[0] || h.div_ceil(self.factor) != self.size[1] {
|
||||
return Vec::new();
|
||||
}
|
||||
super::haze_cells(px, w, h, self, |q| gains.map_or(q, |g| super::balance(q, g)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Clarity on a `w × h` frame.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Clarity {
|
||||
/// The strength: the slider / 100 × 0.8.
|
||||
pub amount: f32,
|
||||
/// The guided filter's radius at full size.
|
||||
pub radius: usize,
|
||||
/// The fast guided filter works on `subsample × subsample` block means…
|
||||
pub subsample: usize,
|
||||
/// …with this radius…
|
||||
pub sub_radius: usize,
|
||||
/// …at this size.
|
||||
pub sub_size: [usize; 2],
|
||||
}
|
||||
|
||||
impl Clarity {
|
||||
/// Clarity for `p` on a `w × h` frame; `None` when it is off.
|
||||
pub fn new(p: &CameraRaw, w: usize, h: usize) -> Option<Self> {
|
||||
if p.clarity == 0.0 {
|
||||
return None;
|
||||
}
|
||||
let radius = ((w.max(h) as f32 * 0.02) as usize).max(3);
|
||||
let (subsample, sub_radius) = fast_guided_steps(radius);
|
||||
Some(Clarity { amount: p.clarity / 100.0 * 0.8, radius, subsample, sub_radius, sub_size: [w.div_ceil(subsample), h.div_ceil(subsample)] })
|
||||
}
|
||||
}
|
||||
|
||||
/// The fast guided filter's subsampling and its radius there, for radius `r` at full size. A
|
||||
/// subsampling of 1 is the plain guided filter at radius `r`.
|
||||
pub fn fast_guided_steps(r: usize) -> (usize, usize) {
|
||||
let s = (r / 8).clamp(1, 8);
|
||||
(s, if s == 1 { r } else { (r / s).max(1) })
|
||||
}
|
||||
|
||||
/// Texture on a `w × h` frame.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Texture {
|
||||
/// The strength: the slider / 100 × 0.9.
|
||||
pub amount: f32,
|
||||
/// The blur's box radii, in order; empty when the blur is too small to change anything.
|
||||
pub radii: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Texture {
|
||||
/// Texture for `p` on a `w × h` frame; `None` when it is off.
|
||||
pub fn new(p: &CameraRaw, inputs: &DevelopInputs, w: usize, h: usize) -> Option<Self> {
|
||||
if p.texture == 0.0 {
|
||||
return None;
|
||||
}
|
||||
let ps = inputs.pixel_scale.clamp(0.01, 1.0);
|
||||
let sigma = (w.max(h) as f32 * 0.002).max(1.5 * ps);
|
||||
Some(Texture { amount: p.texture / 100.0 * 0.9, radii: gauss_radii(sigma) })
|
||||
}
|
||||
}
|
||||
|
||||
/// The box radii of develop's Gaussian of `sigma`: none below 0.3.
|
||||
pub(crate) fn gauss_radii(sigma: f32) -> Vec<usize> {
|
||||
if sigma < 0.3 {
|
||||
return Vec::new();
|
||||
}
|
||||
crate::fxutil::gauss_box_radii(sigma).to_vec()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `CameraRaw` with the named fields set (the type is `#[non_exhaustive]`, so no struct expression), or a copy of a base with them set.
|
||||
macro_rules! cr {
|
||||
($($f:ident : $v:expr),* $(,)?) => {{
|
||||
let mut s = CameraRaw::default();
|
||||
$(s.$f = $v;)*
|
||||
s
|
||||
}};
|
||||
($base:expr => $($f:ident : $v:expr),* $(,)?) => {{
|
||||
let mut s: CameraRaw = $base;
|
||||
$(s.$f = $v;)*
|
||||
s
|
||||
}};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stages_resolve_for_the_dialogs_proxy_and_are_off_at_zero() {
|
||||
let p = cr! { dehaze: 40.0, clarity: -50.0, texture: 50.0};
|
||||
let scale = |pixel_scale| DevelopInputs { pixel_scale, ..Default::default() };
|
||||
let d = Dehaze::new(&p, 858, 572).unwrap();
|
||||
assert_eq!((d.factor, d.size, d.radius, d.guide_radius, d.top), (2, [429, 286], 7, 14, 122));
|
||||
let c = Clarity::new(&p, 858, 572).unwrap();
|
||||
assert_eq!((c.radius, c.subsample, c.sub_radius, c.sub_size), (17, 2, 8, [429, 286]));
|
||||
assert!((c.amount + 0.4).abs() < 1e-6);
|
||||
assert_eq!(Texture::new(&p, &scale(0.143), 858, 572).unwrap().radii, [1, 1, 2]);
|
||||
// Small frames: the plain guided filter, a blur too narrow to change anything.
|
||||
assert_eq!(fast_guided_steps(3), (1, 3));
|
||||
assert!(Texture::new(&cr! { texture: 10.0}, &scale(0.1), 64, 48).unwrap().radii.is_empty());
|
||||
let off = CameraRaw::default();
|
||||
assert!(Dehaze::new(&off, 858, 572).is_none() && Clarity::new(&off, 858, 572).is_none() && Texture::new(&off, &scale(1.0), 858, 572).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dehaze_cells_average_blocks_after_white_balance_and_refuse_a_wrong_size() {
|
||||
let d = Dehaze::new(&cr! { dehaze: 10.0}, 3, 1).unwrap();
|
||||
let px = [[0.2, 0.4, 1.5, 1.0], [0.4, 0.0, 0.5, 1.0], [0.9, 0.9, 0.9, 1.0]];
|
||||
assert_eq!(d.cells(&px, 3, 1, None), vec![[0.2, 0.4, 1.0], [0.4, 0.0, 0.5], [0.9, 0.9, 0.9]]);
|
||||
let brighter = d.cells(&px, 3, 1, Some([2.0, 2.0, 2.0]));
|
||||
assert!(brighter[0][0] > 0.2 && brighter[2] == [1.0; 3]);
|
||||
assert!(d.cells(&px[..2], 3, 1, None).is_empty());
|
||||
assert!(d.cells(&px, 1, 3, None).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,494 +0,0 @@
|
||||
//! Whites and Blacks as Adobe Camera Raw (process version 2012) applies them.
|
||||
//!
|
||||
//! Measured as a black box on the Camera Raw Filter of Photoshop 25.4: grey blocks with chosen
|
||||
//! histograms went through the filter by script and came back exactly; no Adobe code or data
|
||||
//! was used.
|
||||
//!
|
||||
//! - Both are global curves of the grey level, applied after Shadows and Highlights, Whites
|
||||
//! first. On an image whose darkest and lightest percent reach black and white the curve of a
|
||||
//! slider value `x` is the measured row at `x` of [`WHITES`] or [`BLACKS`].
|
||||
//! - The direction that only compresses (Whites down, Blacks up) is that fixed curve on every
|
||||
//! image. The direction that clips (Whites up, Blacks down) adapts: the row used is
|
||||
//! `x · A(BP, WP)`. On the block images BP and WP are their darkest and lightest levels; on
|
||||
//! photographs Photoshop's amounts follow best with BP the 3rd percentile of the luminance and
|
||||
//! WP the 99.5th of the brightest channel, and Blacks at least 1.2 times. A low
|
||||
//! white point makes Whites +100 stronger (up to 2.7 times), a raised black point Blacks
|
||||
//! (up to 1.45 times at −40). Whites rows past +100 come from images where `A > 1`.
|
||||
//! - Not reproduced: past −40 Photoshop's Blacks grows faster on images with a raised black
|
||||
//! point (on one spanning 0.6–1 its −100 blacks out everything below 0.74, here below about
|
||||
//! 0.15); its curves there are not rows of the full-range family.
|
||||
//! - Colour: the clipping directions act on each channel, the compressing ones scale the pixel
|
||||
//! by the curve's change of its luminance (closest to Photoshop on saturated colours).
|
||||
|
||||
use super::Encoding;
|
||||
use crate::photo_util::par_rows;
|
||||
|
||||
/// Grey levels the curves are sampled at: 0, 1/32, …, 1 (sRGB-encoded).
|
||||
pub(crate) const STEPS: usize = 33;
|
||||
/// The first row's internal amount; rows are [`ROW_STEP`] apart.
|
||||
const WHITES_FROM: f32 = -100.0;
|
||||
const BLACKS_FROM: f32 = -100.0;
|
||||
const ROW_STEP: f32 = 10.0;
|
||||
/// The image's points are measured on cells of a copy at most this many pixels across.
|
||||
pub(crate) const POINTS_SIDE: usize = 256;
|
||||
/// The black point's quantile of the cells' luminance, the white point's of their brightest
|
||||
/// channel.
|
||||
pub(crate) const POINT_QUANTILES: [f32; 2] = [0.03, 0.995];
|
||||
/// Internal amounts the sliders reach: Whites, then Blacks.
|
||||
const WHITES_RANGE: [f32; 2] = [-100.0, 270.0];
|
||||
const BLACKS_RANGE: [f32; 2] = [-100.0, 100.0];
|
||||
|
||||
/// Whites and Blacks' tables and how an image's points choose from them, for another
|
||||
/// implementation (the GPU preview measures the points after Shadows and Highlights itself).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Model {
|
||||
/// Whites curves over grey levels 0, 1/32, …, 1, at internal amounts `whites_from`,
|
||||
/// `whites_from + row_step`, ….
|
||||
pub whites: &'static [[f32; STEPS]],
|
||||
pub whites_from: f32,
|
||||
/// Blacks curves, likewise.
|
||||
pub blacks: &'static [[f32; STEPS]],
|
||||
pub blacks_from: f32,
|
||||
pub row_step: f32,
|
||||
/// Black points and white points of the adaptation tables' rows and columns.
|
||||
pub black_points: &'static [f32],
|
||||
pub white_points: &'static [f32],
|
||||
/// How much the clipping directions adapt (Whites up, Blacks down), by black and white point.
|
||||
pub whites_adapt: &'static [[f32; 8]; 9],
|
||||
pub blacks_adapt: &'static [[f32; 8]; 9],
|
||||
/// The least Blacks adaptation on photographs.
|
||||
pub photo_blacks: f32,
|
||||
/// Internal amounts the Whites and Blacks sliders reach.
|
||||
pub whites_range: [f32; 2],
|
||||
pub blacks_range: [f32; 2],
|
||||
/// See [`POINTS_SIDE`] and [`POINT_QUANTILES`].
|
||||
pub points_side: usize,
|
||||
pub point_quantiles: [f32; 2],
|
||||
}
|
||||
|
||||
/// The tables [`amounts`], [`whites_row`] and [`blacks_row`] read.
|
||||
pub(crate) fn model() -> Model {
|
||||
Model {
|
||||
whites: &WHITES,
|
||||
whites_from: WHITES_FROM,
|
||||
blacks: &BLACKS,
|
||||
blacks_from: BLACKS_FROM,
|
||||
row_step: ROW_STEP,
|
||||
black_points: &BPS,
|
||||
white_points: &WPS,
|
||||
whites_adapt: &AW,
|
||||
blacks_adapt: &AB,
|
||||
photo_blacks: PHOTO_BLACKS,
|
||||
whites_range: WHITES_RANGE,
|
||||
blacks_range: BLACKS_RANGE,
|
||||
points_side: POINTS_SIDE,
|
||||
point_quantiles: POINT_QUANTILES,
|
||||
}
|
||||
}
|
||||
// Measured levels; some happen to lie near π/8 and π/4.
|
||||
/// Whites curves at internal amounts -100, -90, …, 270 (rows) over grey levels 0, 1/32, …, 1.
|
||||
#[allow(clippy::approx_constant)]
|
||||
static WHITES: [[f32; 33]; 38] = [
|
||||
[
|
||||
0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1523, 0.1817, 0.2107, 0.2391, 0.2671, 0.2946, 0.3215, 0.3480, 0.3738, 0.3995, 0.4256, 0.4517, 0.4774, 0.5028,
|
||||
0.5278, 0.5524, 0.5768, 0.6008, 0.6245, 0.6482, 0.6717, 0.6957, 0.7207, 0.7483, 0.7814, 0.8263, 0.8949, 0.9999,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1523, 0.1817, 0.2107, 0.2392, 0.2672, 0.2947, 0.3217, 0.3482, 0.3742, 0.4000, 0.4263, 0.4526, 0.4785, 0.5042,
|
||||
0.5296, 0.5548, 0.5797, 0.6044, 0.6291, 0.6539, 0.6789, 0.7046, 0.7317, 0.7617, 0.7969, 0.8425, 0.9074, 0.9999,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1524, 0.1818, 0.2108, 0.2393, 0.2673, 0.2950, 0.3221, 0.3487, 0.3748, 0.4008, 0.4274, 0.4540, 0.4803, 0.5064,
|
||||
0.5323, 0.5580, 0.5837, 0.6093, 0.6350, 0.6610, 0.6875, 0.7149, 0.7438, 0.7756, 0.8122, 0.8576, 0.9184, 0.9999,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1524, 0.1818, 0.2109, 0.2395, 0.2677, 0.2954, 0.3227, 0.3495, 0.3759, 0.4022, 0.4291, 0.4561, 0.4828, 0.5094,
|
||||
0.5360, 0.5624, 0.5888, 0.6154, 0.6423, 0.6695, 0.6973, 0.7261, 0.7566, 0.7897, 0.8271, 0.8716, 0.9280, 0.9999,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0298, 0.0621, 0.0926, 0.1226, 0.1525, 0.1820, 0.2111, 0.2398, 0.2682, 0.2961, 0.3237, 0.3508, 0.3775, 0.4042, 0.4317, 0.4591, 0.4864, 0.5136,
|
||||
0.5408, 0.5680, 0.5953, 0.6229, 0.6508, 0.6791, 0.7082, 0.7382, 0.7698, 0.8037, 0.8412, 0.8843, 0.9365, 0.9999,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0298, 0.0621, 0.0927, 0.1227, 0.1527, 0.1822, 0.2116, 0.2404, 0.2690, 0.2972, 0.3251, 0.3527, 0.3799, 0.4071, 0.4351, 0.4630, 0.4910, 0.5189,
|
||||
0.5469, 0.5749, 0.6031, 0.6316, 0.6605, 0.6899, 0.7199, 0.7509, 0.7832, 0.8174, 0.8544, 0.8958, 0.9439, 0.9999,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0298, 0.0621, 0.0927, 0.1229, 0.1529, 0.1827, 0.2122, 0.2414, 0.2702, 0.2989, 0.3272, 0.3553, 0.3831, 0.4110, 0.4396, 0.4682, 0.4968, 0.5254,
|
||||
0.5542, 0.5830, 0.6121, 0.6414, 0.6712, 0.7014, 0.7322, 0.7637, 0.7964, 0.8305, 0.8668, 0.9062, 0.9503, 0.9999,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0298, 0.0622, 0.0928, 0.1231, 0.1534, 0.1834, 0.2132, 0.2427, 0.2720, 0.3011, 0.3300, 0.3587, 0.3872, 0.4160, 0.4452, 0.4745, 0.5038, 0.5332,
|
||||
0.5627, 0.5923, 0.6221, 0.6522, 0.6826, 0.7134, 0.7447, 0.7765, 0.8092, 0.8429, 0.8781, 0.9155, 0.9559, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0298, 0.0623, 0.0930, 0.1236, 0.1541, 0.1844, 0.2145, 0.2445, 0.2744, 0.3041, 0.3337, 0.3632, 0.3925, 0.4221, 0.4520, 0.4820, 0.5120, 0.5421,
|
||||
0.5723, 0.6026, 0.6330, 0.6636, 0.6946, 0.7257, 0.7572, 0.7890, 0.8214, 0.8545, 0.8885, 0.9237, 0.9608, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0298, 0.0624, 0.0934, 0.1242, 0.1551, 0.1858, 0.2164, 0.2470, 0.2775, 0.3080, 0.3383, 0.3687, 0.3989, 0.4293, 0.4600, 0.4906, 0.5213, 0.5520,
|
||||
0.5827, 0.6136, 0.6445, 0.6755, 0.7067, 0.7380, 0.7694, 0.8011, 0.8330, 0.8652, 0.8978, 0.9310, 0.9651, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0312, 0.0625, 0.0938, 0.1250, 0.1562, 0.1875, 0.2188, 0.2500, 0.2812, 0.3125, 0.3438, 0.3750, 0.4062, 0.4375, 0.4688, 0.5000, 0.5312, 0.5625,
|
||||
0.5938, 0.6250, 0.6562, 0.6875, 0.7188, 0.7500, 0.7812, 0.8125, 0.8438, 0.8750, 0.9062, 0.9375, 0.9688, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0299, 0.0626, 0.0940, 0.1253, 0.1567, 0.1881, 0.2195, 0.2510, 0.2825, 0.3140, 0.3456, 0.3772, 0.4089, 0.4405, 0.4720, 0.5036, 0.5351, 0.5667,
|
||||
0.5983, 0.6298, 0.6613, 0.6929, 0.7244, 0.7559, 0.7874, 0.8189, 0.8503, 0.8816, 0.9128, 0.9438, 0.9742, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0299, 0.0627, 0.0941, 0.1257, 0.1573, 0.1890, 0.2208, 0.2526, 0.2846, 0.3167, 0.3488, 0.3811, 0.4134, 0.4456, 0.4777, 0.5098, 0.5419, 0.5741,
|
||||
0.6062, 0.6383, 0.6704, 0.7025, 0.7345, 0.7664, 0.7983, 0.8301, 0.8617, 0.8931, 0.9241, 0.9543, 0.9829, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0299, 0.0628, 0.0944, 0.1262, 0.1582, 0.1903, 0.2225, 0.2550, 0.2876, 0.3204, 0.3534, 0.3867, 0.4200, 0.4529, 0.4858, 0.5186, 0.5516, 0.5845,
|
||||
0.6174, 0.6502, 0.6830, 0.7157, 0.7482, 0.7807, 0.8131, 0.8451, 0.8769, 0.9082, 0.9385, 0.9673, 0.9928, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0299, 0.0629, 0.0948, 0.1269, 0.1594, 0.1920, 0.2249, 0.2582, 0.2917, 0.3256, 0.3597, 0.3942, 0.4289, 0.4628, 0.4966, 0.5305, 0.5644, 0.5983,
|
||||
0.6321, 0.6658, 0.6994, 0.7327, 0.7660, 0.7989, 0.8316, 0.8639, 0.8956, 0.9263, 0.9553, 0.9815, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0299, 0.0631, 0.0953, 0.1280, 0.1610, 0.1944, 0.2282, 0.2625, 0.2973, 0.3325, 0.3683, 0.4045, 0.4407, 0.4758, 0.5109, 0.5460, 0.5811, 0.6161,
|
||||
0.6510, 0.6857, 0.7201, 0.7541, 0.7879, 0.8213, 0.8543, 0.8864, 0.9175, 0.9468, 0.9733, 0.9950, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0299, 0.0633, 0.0961, 0.1293, 0.1632, 0.1976, 0.2327, 0.2684, 0.3048, 0.3419, 0.3798, 0.4183, 0.4562, 0.4928, 0.5294, 0.5660, 0.6024, 0.6387,
|
||||
0.6748, 0.7104, 0.7456, 0.7803, 0.8145, 0.8480, 0.8807, 0.9121, 0.9417, 0.9684, 0.9907, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0300, 0.0637, 0.0971, 0.1313, 0.1663, 0.2020, 0.2387, 0.2763, 0.3149, 0.3546, 0.3952, 0.4365, 0.4763, 0.5149, 0.5532, 0.5914, 0.6294, 0.6670,
|
||||
0.7041, 0.7406, 0.7763, 0.8113, 0.8456, 0.8788, 0.9104, 0.9401, 0.9667, 0.9888, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0300, 0.0641, 0.0984, 0.1338, 0.1703, 0.2079, 0.2468, 0.2870, 0.3286, 0.3717, 0.4161, 0.4602, 0.5024, 0.5430, 0.5833, 0.6232, 0.6627, 0.7015,
|
||||
0.7394, 0.7764, 0.8123, 0.8472, 0.8808, 0.9126, 0.9420, 0.9681, 0.9896, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0302, 0.0647, 0.1003, 0.1374, 0.1760, 0.2160, 0.2579, 0.3016, 0.3472, 0.3949, 0.4436, 0.4908, 0.5355, 0.5784, 0.6207, 0.6622, 0.7029, 0.7424,
|
||||
0.7806, 0.8176, 0.8530, 0.8868, 0.9185, 0.9474, 0.9726, 0.9926, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0304, 0.0656, 0.1029, 0.1423, 0.1837, 0.2271, 0.2731, 0.3215, 0.3726, 0.4262, 0.4791, 0.5294, 0.5769, 0.6220, 0.6660, 0.7086, 0.7498, 0.7893,
|
||||
0.8272, 0.8631, 0.8969, 0.9281, 0.9560, 0.9795, 0.9967, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0305, 0.0679, 0.1094, 0.1509, 0.1968, 0.2459, 0.2956, 0.3510, 0.4094, 0.4680, 0.5248, 0.5781, 0.6278, 0.6742, 0.7195, 0.7624, 0.8031, 0.8417,
|
||||
0.8779, 0.9113, 0.9414, 0.9675, 0.9886, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0306, 0.0702, 0.1160, 0.1623, 0.2144, 0.2709, 0.3243, 0.3885, 0.4556, 0.5199, 0.5807, 0.6369, 0.6884, 0.7355, 0.7799, 0.8217, 0.8606, 0.8964,
|
||||
0.9288, 0.9570, 0.9803, 0.9958, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0308, 0.0725, 0.1225, 0.1737, 0.2320, 0.2960, 0.3641, 0.4393, 0.5133, 0.5825, 0.6460, 0.7032, 0.7544, 0.8003, 0.8426, 0.8817, 0.9168, 0.9475,
|
||||
0.9733, 0.9924, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0322, 0.0751, 0.1303, 0.1918, 0.2594, 0.3348, 0.4189, 0.5044, 0.5841, 0.6565, 0.7208, 0.7771, 0.8262, 0.8692, 0.9074, 0.9408, 0.9686, 0.9900,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0331, 0.0818, 0.1482, 0.2171, 0.2977, 0.3892, 0.4865, 0.5779, 0.6602, 0.7322, 0.7943, 0.8470, 0.8915, 0.9286, 0.9600, 0.9844, 0.9996, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0340, 0.0884, 0.1661, 0.2544, 0.3540, 0.4658, 0.5729, 0.6681, 0.7496, 0.8183, 0.8748, 0.9208, 0.9568, 0.9832, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.3356, 0.5799, 0.6166, 0.6166, 0.6166, 0.6166, 0.6624, 0.7556, 0.8321, 0.8935, 0.9411, 0.9755, 0.9970, 0.9998, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.5007, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.1655, 0.1655, 0.2972, 0.4728, 0.6327, 0.7616, 0.8598, 0.9317, 0.9790, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0457, 0.1830, 0.3836, 0.5790, 0.7379, 0.8549, 0.9360, 0.9869, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0520, 0.2329, 0.4864, 0.6989, 0.8449, 0.9403, 0.9884, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0773, 0.3027, 0.6040, 0.8058, 0.9302, 0.9930, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.1454, 0.4738, 0.7615, 0.9074, 0.9908, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0964, 0.5416, 0.8589, 0.9897, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.1538, 0.1538, 0.7080, 0.9596, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.8439, 0.8439, 0.8439, 0.9993, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
[
|
||||
0.9228, 0.9228, 0.9228, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
|
||||
],
|
||||
];
|
||||
/// Blacks curves at internal amounts -100, …, 100 in steps of 10.
|
||||
#[allow(clippy::approx_constant)]
|
||||
static BLACKS: [[f32; 33]; 21] = [
|
||||
[
|
||||
0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0290, 0.0572, 0.0879, 0.1222, 0.1580, 0.1935, 0.2287, 0.2636, 0.2988, 0.3355, 0.3741, 0.4151, 0.4571,
|
||||
0.4990, 0.5406, 0.5818, 0.6226, 0.6631, 0.7031, 0.7424, 0.7811, 0.8192, 0.8568, 0.8937, 0.9300, 0.9655, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0000, 0.0000, 0.0000, 0.0015, 0.0363, 0.0640, 0.0956, 0.1300, 0.1651, 0.2000, 0.2345, 0.2686, 0.3026, 0.3369, 0.3727, 0.4105, 0.4495, 0.4885,
|
||||
0.5272, 0.5657, 0.6039, 0.6419, 0.6796, 0.7169, 0.7538, 0.7903, 0.8264, 0.8621, 0.8974, 0.9322, 0.9664, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0000, 0.0000, 0.0000, 0.0346, 0.0625, 0.0934, 0.1271, 0.1616, 0.1959, 0.2298, 0.2635, 0.2969, 0.3301, 0.3638, 0.3990, 0.4357, 0.4727, 0.5094,
|
||||
0.5460, 0.5824, 0.6187, 0.6547, 0.6906, 0.7262, 0.7615, 0.7965, 0.8313, 0.8657, 0.8998, 0.9336, 0.9671, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0000, 0.0000, 0.0235, 0.0554, 0.0850, 0.1175, 0.1514, 0.1852, 0.2187, 0.2519, 0.2849, 0.3178, 0.3505, 0.3837, 0.4183, 0.4537, 0.4891, 0.5243,
|
||||
0.5594, 0.5944, 0.6292, 0.6639, 0.6985, 0.7329, 0.7671, 0.8010, 0.8347, 0.8683, 0.9016, 0.9347, 0.9676, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0000, 0.0020, 0.0438, 0.0724, 0.1035, 0.1365, 0.1699, 0.2030, 0.2359, 0.2686, 0.3011, 0.3336, 0.3659, 0.3986, 0.4327, 0.4669, 0.5011, 0.5352,
|
||||
0.5692, 0.6031, 0.6369, 0.6706, 0.7043, 0.7378, 0.7711, 0.8043, 0.8373, 0.8702, 0.9029, 0.9355, 0.9679, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0000, 0.0230, 0.0567, 0.0865, 0.1182, 0.1510, 0.1839, 0.2164, 0.2489, 0.2812, 0.3133, 0.3455, 0.3775, 0.4100, 0.4433, 0.4767, 0.5100, 0.5433,
|
||||
0.5765, 0.6096, 0.6426, 0.6756, 0.7086, 0.7414, 0.7741, 0.8067, 0.8392, 0.8716, 0.9039, 0.9361, 0.9682, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0000, 0.0368, 0.0670, 0.0976, 0.1294, 0.1619, 0.1943, 0.2265, 0.2586, 0.2906, 0.3225, 0.3544, 0.3862, 0.4184, 0.4512, 0.4839, 0.5166, 0.5492,
|
||||
0.5818, 0.6144, 0.6469, 0.6793, 0.7117, 0.7441, 0.7763, 0.8085, 0.8406, 0.8727, 0.9046, 0.9365, 0.9683, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0000, 0.0444, 0.0749, 0.1058, 0.1377, 0.1699, 0.2020, 0.2339, 0.2657, 0.2975, 0.3292, 0.3609, 0.3926, 0.4245, 0.4568, 0.4891, 0.5213, 0.5535,
|
||||
0.5857, 0.6179, 0.6499, 0.6820, 0.7140, 0.7460, 0.7779, 0.8098, 0.8416, 0.8734, 0.9052, 0.9368, 0.9685, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0086, 0.0511, 0.0817, 0.1128, 0.1445, 0.1763, 0.2080, 0.2397, 0.2713, 0.3029, 0.3344, 0.3660, 0.3975, 0.4292, 0.4611, 0.4930, 0.5249, 0.5567,
|
||||
0.5886, 0.6204, 0.6522, 0.6839, 0.7157, 0.7475, 0.7791, 0.8108, 0.8424, 0.8740, 0.9056, 0.9371, 0.9686, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0198, 0.0564, 0.0874, 0.1186, 0.1501, 0.1817, 0.2133, 0.2447, 0.2762, 0.3076, 0.3390, 0.3705, 0.4018, 0.4333, 0.4649, 0.4965, 0.5281, 0.5597,
|
||||
0.5912, 0.6227, 0.6543, 0.6858, 0.7173, 0.7488, 0.7802, 0.8117, 0.8431, 0.8745, 0.9059, 0.9373, 0.9686, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0312, 0.0625, 0.0938, 0.1250, 0.1562, 0.1875, 0.2188, 0.2500, 0.2812, 0.3125, 0.3438, 0.3750, 0.4062, 0.4375, 0.4688, 0.5000, 0.5312, 0.5625,
|
||||
0.5938, 0.6250, 0.6562, 0.6875, 0.7188, 0.7500, 0.7812, 0.8125, 0.8438, 0.8750, 0.9062, 0.9375, 0.9688, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0313, 0.0650, 0.0979, 0.1303, 0.1624, 0.1942, 0.2260, 0.2576, 0.2891, 0.3206, 0.3520, 0.3833, 0.4146, 0.4455, 0.4763, 0.5070, 0.5378, 0.5684,
|
||||
0.5991, 0.6298, 0.6605, 0.6912, 0.7219, 0.7526, 0.7833, 0.8141, 0.8450, 0.8758, 0.9067, 0.9377, 0.9688, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0326, 0.0677, 0.1022, 0.1357, 0.1686, 0.2010, 0.2332, 0.2652, 0.2969, 0.3286, 0.3601, 0.3915, 0.4227, 0.4532, 0.4835, 0.5138, 0.5440, 0.5741,
|
||||
0.6042, 0.6344, 0.6645, 0.6946, 0.7248, 0.7550, 0.7853, 0.8156, 0.8461, 0.8766, 0.9072, 0.9380, 0.9689, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0341, 0.0706, 0.1066, 0.1413, 0.1749, 0.2079, 0.2405, 0.2728, 0.3048, 0.3366, 0.3682, 0.3996, 0.4307, 0.4608, 0.4906, 0.5203, 0.5500, 0.5796,
|
||||
0.6092, 0.6387, 0.6683, 0.6979, 0.7276, 0.7573, 0.7871, 0.8170, 0.8472, 0.8773, 0.9077, 0.9382, 0.9690, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0354, 0.0736, 0.1113, 0.1472, 0.1814, 0.2149, 0.2479, 0.2805, 0.3127, 0.3446, 0.3763, 0.4077, 0.4385, 0.4681, 0.4974, 0.5267, 0.5558, 0.5849,
|
||||
0.6139, 0.6429, 0.6720, 0.7011, 0.7303, 0.7595, 0.7889, 0.8184, 0.8481, 0.8780, 0.9081, 0.9384, 0.9690, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0368, 0.0768, 0.1162, 0.1531, 0.1881, 0.2221, 0.2554, 0.2882, 0.3206, 0.3527, 0.3843, 0.4158, 0.4461, 0.4753, 0.5041, 0.5328, 0.5615, 0.5900,
|
||||
0.6185, 0.6470, 0.6755, 0.7041, 0.7328, 0.7616, 0.7906, 0.8197, 0.8491, 0.8787, 0.9085, 0.9386, 0.9691, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0381, 0.0802, 0.1214, 0.1593, 0.1949, 0.2293, 0.2630, 0.2961, 0.3286, 0.3607, 0.3924, 0.4236, 0.4536, 0.4823, 0.5106, 0.5388, 0.5669, 0.5949,
|
||||
0.6229, 0.6509, 0.6789, 0.7070, 0.7352, 0.7636, 0.7922, 0.8209, 0.8500, 0.8793, 0.9089, 0.9388, 0.9691, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0394, 0.0837, 0.1267, 0.1656, 0.2018, 0.2367, 0.2707, 0.3039, 0.3365, 0.3686, 0.4003, 0.4314, 0.4608, 0.4890, 0.5168, 0.5445, 0.5721, 0.5996,
|
||||
0.6271, 0.6546, 0.6822, 0.7098, 0.7375, 0.7655, 0.7937, 0.8221, 0.8509, 0.8799, 0.9092, 0.9390, 0.9692, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0407, 0.0875, 0.1322, 0.1720, 0.2088, 0.2441, 0.2784, 0.3118, 0.3444, 0.3765, 0.4082, 0.4389, 0.4679, 0.4955, 0.5229, 0.5501, 0.5771, 0.6042,
|
||||
0.6312, 0.6582, 0.6853, 0.7124, 0.7398, 0.7673, 0.7952, 0.8233, 0.8517, 0.8804, 0.9096, 0.9391, 0.9692, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0421, 0.0915, 0.1379, 0.1786, 0.2160, 0.2516, 0.2861, 0.3196, 0.3523, 0.3844, 0.4159, 0.4462, 0.4747, 0.5019, 0.5287, 0.5554, 0.5820, 0.6085,
|
||||
0.6351, 0.6616, 0.6882, 0.7149, 0.7419, 0.7690, 0.7965, 0.8243, 0.8524, 0.8810, 0.9099, 0.9393, 0.9693, 1.0000,
|
||||
],
|
||||
[
|
||||
0.0000, 0.0436, 0.0957, 0.1438, 0.1853, 0.2232, 0.2592, 0.2938, 0.3274, 0.3601, 0.3922, 0.4235, 0.4533, 0.4813, 0.5080, 0.5343, 0.5605, 0.5866, 0.6127,
|
||||
0.6387, 0.6648, 0.6910, 0.7173, 0.7439, 0.7707, 0.7978, 0.8253, 0.8532, 0.8815, 0.9102, 0.9394, 0.9693, 1.0000,
|
||||
],
|
||||
];
|
||||
const BPS: [f32; 9] = [0.0000, 0.0200, 0.0500, 0.1000, 0.2000, 0.3000, 0.4500, 0.6000, 0.8000];
|
||||
const WPS: [f32; 8] = [0.1000, 0.2000, 0.3000, 0.4500, 0.6000, 0.8000, 0.9000, 1.0000];
|
||||
static AW: [[f32; 8]; 9] = [
|
||||
[1.7750, 2.3875, 2.4000, 2.1625, 1.9438, 1.6125, 1.3875, 1.0000],
|
||||
[1.8125, 2.5250, 2.3937, 2.1688, 1.9375, 1.6062, 1.3938, 0.9875],
|
||||
[2.7000, 2.4688, 2.2750, 2.0688, 1.8875, 1.6000, 1.3875, 0.9938],
|
||||
[2.3250, 2.3250, 2.1875, 1.9750, 1.7937, 1.5188, 1.3250, 1.0437],
|
||||
[2.0187, 2.0187, 2.0187, 1.8625, 1.7063, 1.4062, 1.2250, 0.9250],
|
||||
[1.7500, 1.7500, 1.7500, 1.7500, 1.6438, 1.3562, 1.1687, 0.8625],
|
||||
[1.4937, 1.4937, 1.4937, 1.4937, 1.4937, 1.2875, 1.1000, 0.7875],
|
||||
[1.1687, 1.1687, 1.1687, 1.1687, 1.1687, 1.1687, 1.0375, 0.7562],
|
||||
[0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.8250, 0.7562],
|
||||
];
|
||||
static AB: [[f32; 8]; 9] = [
|
||||
[0.9938, 0.9812, 1.0000, 1.0125, 0.9563, 0.9688, 1.0437, 1.0000],
|
||||
[1.0437, 1.0250, 1.0125, 1.0000, 1.0000, 1.0375, 1.0000, 0.9938],
|
||||
[1.2312, 1.2063, 1.1875, 1.1625, 1.1438, 1.1438, 1.1375, 1.1250],
|
||||
[1.2500, 1.2500, 1.2312, 1.2125, 1.2125, 1.2375, 1.2375, 1.2375],
|
||||
[1.1750, 1.1750, 1.1750, 1.1750, 1.2063, 1.2688, 1.3125, 1.3375],
|
||||
[1.1812, 1.1812, 1.1812, 1.1812, 1.2125, 1.2812, 1.3313, 1.4125],
|
||||
[1.2375, 1.2375, 1.2375, 1.2375, 1.2375, 1.3062, 1.3562, 1.4375],
|
||||
[1.3250, 1.3250, 1.3250, 1.3250, 1.3250, 1.3250, 1.3687, 1.4500],
|
||||
[1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.3938, 1.4312],
|
||||
];
|
||||
|
||||
/// A curve row at a fractional internal amount `x`, at grey level `v` (both interpolated).
|
||||
fn curve(rows: &[[f32; STEPS]], from: f32, x: f32, v: f32) -> f32 {
|
||||
if v >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32);
|
||||
let i = (r as usize).min(rows.len() - 2);
|
||||
let t = r - i as f32;
|
||||
let at = |row: &[f32; STEPS]| {
|
||||
let p = v.max(0.0) * (STEPS - 1) as f32;
|
||||
let j = (p as usize).min(STEPS - 2);
|
||||
let s = p - j as f32;
|
||||
row[j] + (row[j + 1] - row[j]) * s
|
||||
};
|
||||
at(&rows[i]) * (1.0 - t) + at(&rows[i + 1]) * t
|
||||
}
|
||||
|
||||
/// The curve at a fractional internal amount `x` as one row: `curve(rows, from, x, v)` is this
|
||||
/// row interpolated at `v`, because both interpolations are linear.
|
||||
fn row_at(rows: &[[f32; STEPS]], from: f32, x: f32) -> [f32; STEPS] {
|
||||
let r = ((x - from) / ROW_STEP).clamp(0.0, (rows.len() - 1) as f32);
|
||||
let i = (r as usize).min(rows.len() - 2);
|
||||
let t = r - i as f32;
|
||||
std::array::from_fn(|j| rows[i][j] * (1.0 - t) + rows[i + 1][j] * t)
|
||||
}
|
||||
|
||||
/// The Whites curve at internal amount `x` as a row over grey levels 0, 1/32, …, 1.
|
||||
pub(crate) fn whites_row(x: f32) -> [f32; STEPS] {
|
||||
row_at(&WHITES, WHITES_FROM, x)
|
||||
}
|
||||
|
||||
/// The Blacks curve at internal amount `x` as a row over grey levels 0, 1/32, …, 1.
|
||||
pub(crate) fn blacks_row(x: f32) -> [f32; STEPS] {
|
||||
row_at(&BLACKS, BLACKS_FROM, x)
|
||||
}
|
||||
|
||||
/// Whites at internal amount `x` (−100 … 270) of grey level `v`.
|
||||
pub(crate) fn whites(v: f32, x: f32) -> f32 {
|
||||
curve(&WHITES, WHITES_FROM, x, v)
|
||||
}
|
||||
|
||||
/// Blacks at internal amount `x` (−100 … 100) of grey level `v`.
|
||||
pub(crate) fn blacks(v: f32, x: f32) -> f32 {
|
||||
curve(&BLACKS, BLACKS_FROM, x, v)
|
||||
}
|
||||
|
||||
/// The least Blacks adaptation on photographs.
|
||||
const PHOTO_BLACKS: f32 = 1.2;
|
||||
|
||||
/// Bilinear lookup of an adaptation table at black point `bp` and white point `wp`.
|
||||
fn adapt(table: &[[f32; 8]; 9], bp: f32, wp: f32) -> f32 {
|
||||
let idx = |grid: &[f32], v: f32| {
|
||||
let v = v.clamp(grid[0], grid[grid.len() - 1]);
|
||||
let i = grid.windows(2).position(|w| v <= w[1]).unwrap_or(grid.len() - 2);
|
||||
(i, (v - grid[i]) / (grid[i + 1] - grid[i]))
|
||||
};
|
||||
let (i, s) = idx(&BPS, bp);
|
||||
let (j, t) = idx(&WPS, wp);
|
||||
let row = |i: usize| table[i][j] * (1.0 - t) + table[i][j + 1] * t;
|
||||
row(i) * (1.0 - s) + row(i + 1) * s
|
||||
}
|
||||
|
||||
/// The internal amounts of the Whites and Blacks sliders (−100 … 100) for an image whose 1st
|
||||
/// and 99th luminance percentiles are the grey levels `bp` and `wp` (sRGB-encoded).
|
||||
pub(crate) fn amounts(whites: f32, blacks: f32, bp: f32, wp: f32) -> (f32, f32) {
|
||||
let w = if whites > 0.0 { whites * adapt(&AW, bp, wp) } else { whites };
|
||||
// On photographs Photoshop's Blacks is about 1.2 times the block images' amount even where
|
||||
// their black point is 0 (ten public-domain photos: 1.08–1.36).
|
||||
let b = if blacks < 0.0 { blacks * adapt(&AB, bp, wp).max(PHOTO_BLACKS) } else { blacks };
|
||||
(w.clamp(WHITES_RANGE[0], WHITES_RANGE[1]), b.clamp(BLACKS_RANGE[0], BLACKS_RANGE[1]))
|
||||
}
|
||||
|
||||
/// Applies Whites and Blacks (internal amounts `w`, `b`) to straight RGBA pixels (`width` per
|
||||
/// row) encoded with `enc`. Values above 1 (float documents) keep their excess.
|
||||
pub(crate) fn apply(px: &mut [[f32; 4]], width: usize, w: f32, b: f32, enc: Encoding) {
|
||||
if w == 0.0 && b == 0.0 {
|
||||
return;
|
||||
}
|
||||
// A grey level's new level, both sRGB-encoded.
|
||||
let grey = |v: f32| {
|
||||
let v = if w != 0.0 { whites(v, w) } else { v };
|
||||
if b != 0.0 { blacks(v, b) } else { v }
|
||||
};
|
||||
let per_channel = w > 0.0 || b < 0.0;
|
||||
par_rows(px, width, 1, |_, row| {
|
||||
for q in row.iter_mut() {
|
||||
let lin = [0, 1, 2].map(|c| enc.decode(q[c]));
|
||||
if per_channel {
|
||||
for c in 0..3 {
|
||||
let over = (lin[c] - 1.0).max(0.0);
|
||||
q[c] = enc.encode(super::srgb_to_linear(grey(super::linear_to_srgb(lin[c].min(1.0)))) + over);
|
||||
}
|
||||
} else {
|
||||
let y = super::luma_linear(lin).max(0.0);
|
||||
if y <= 1e-7 {
|
||||
continue;
|
||||
}
|
||||
let y2 = super::srgb_to_linear(grey(super::linear_to_srgb(y.min(1.0)))) + (y - 1.0).max(0.0);
|
||||
let k = y2 / y;
|
||||
for c in 0..3 {
|
||||
q[c] = enc.encode(lin[c] * k);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn full_range_rows_match_photoshop() {
|
||||
// Photoshop 25.4 on a 64-level block image spanning black to white (sRGB levels).
|
||||
assert!((whites(97.1 / 255.0, 100.0) * 255.0 - 137.4).abs() < 0.6);
|
||||
assert!((whites(194.3 / 255.0, -100.0) * 255.0 - 167.6).abs() < 0.6);
|
||||
assert!((blacks(97.1 / 255.0, -100.0) * 255.0 - 60.0).abs() < 0.6);
|
||||
assert!((blacks(48.6 / 255.0, 100.0) * 255.0 - 67.0).abs() < 0.6);
|
||||
// The compressing directions keep black and white.
|
||||
assert_eq!(whites(1.0, -100.0), 1.0);
|
||||
assert_eq!(blacks(0.0, 100.0), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipping_directions_adapt_to_the_image() {
|
||||
// A dark, low-contrast image needs more: Whites +50 acts like +94.5 on [0.05, 0.6].
|
||||
let (w, _) = amounts(50.0, 0.0, 0.05, 0.6);
|
||||
assert!((w - 94.5).abs() < 2.0, "{w}");
|
||||
// A raised black point strengthens Blacks −40 to −58 on [0.6, 1].
|
||||
let (_, b) = amounts(0.0, -40.0, 0.6, 1.0);
|
||||
assert!((b + 58.0).abs() < 1.0, "{b}");
|
||||
// Never below the photographs' 1.2.
|
||||
assert!((amounts(0.0, -50.0, 0.0, 1.0).1 + 60.0).abs() < 1e-3);
|
||||
// The compressing directions never adapt.
|
||||
assert_eq!(amounts(-50.0, 50.0, 0.3, 0.6), (-50.0, 50.0));
|
||||
}
|
||||
}
|
||||
@@ -722,11 +722,14 @@ fn thin_band(w: usize, h: usize, hole: &[bool]) -> f32 {
|
||||
if 4.0 * thickness <= extent { thickness.max(1.5) } else { 1.5 }
|
||||
}
|
||||
|
||||
/// The Patch Tool's and the Content-Aware Move Tool's Color option (0–10) as the colour adaptation
|
||||
/// of the copied content. Measured on Photoshop 25.4 with content brighter than its new place: 0
|
||||
/// keeps it as it is; 3 moves it about 0.12 (32 of 42 levels, and 31 of 102: a limit, not a
|
||||
/// fraction), 6 about 80 % of 42 levels, 10 most of the way (35 of 42, 95 of 102). So the shift is
|
||||
/// limited to about `0.04 · color`, the contrast change likewise widening.
|
||||
/// Colour adaptation of the copies for a Color option of 0–10: the Content-Aware Move Tool's
|
||||
/// edge band (`content_aware_move`) and the Patch Tool's Content-Aware fill (`patch`). Measured
|
||||
/// on Photoshop 25.4 with content brighter than its new place: 0 keeps it as it is; 3 moves it
|
||||
/// about 0.12 (32 of 42 levels, and 31 of 102: a limit, not a fraction), 6 about 80 % of 42
|
||||
/// levels, 10 most of the way (35 of 42, 95 of 102). So the shift is limited to about
|
||||
/// `0.04 · color`, the contrast change likewise widening. Those were measurements of fitted,
|
||||
/// pasted content; Content-Aware Move's kept middle follows its own rule (above Color 5 it
|
||||
/// closes a brightness difference the whole way at 10) rather than this limit.
|
||||
pub fn color_amount(color: u8) -> Adapt {
|
||||
if color == 0 {
|
||||
return Adapt::NONE;
|
||||
@@ -737,7 +740,9 @@ pub fn color_amount(color: u8) -> Adapt {
|
||||
|
||||
/// Gain and bias per channel taking the samples `from` to the level and contrast of the samples
|
||||
/// `to` (both interleaved, `ch` per sample), within `a`: how copied content is fitted to its new
|
||||
/// surroundings.
|
||||
/// surroundings. Since #12118 no engine command calls it (the Patch Tool fills content-aware
|
||||
/// instead of pasting content to fit, and Content-Aware Move fits its middle through its own
|
||||
/// rule); it is kept as the measured fit, still covered by its tests.
|
||||
pub fn level_transform(ch: usize, from: &[f32], to: &[f32], a: Adapt) -> Vec<(f32, f32)> {
|
||||
let moments = |v: &[f32], c: usize| {
|
||||
let (mut s, mut s2, mut n) = (0.0f64, 0.0f64, 0.0f64);
|
||||
|
||||
@@ -67,14 +67,11 @@ fn window_buffers() -> (Vec<f32>, Vec<bool>, usize) {
|
||||
(img, hole, ww)
|
||||
}
|
||||
|
||||
/// Fill the measured document the way the command does with `opts` and Auto or Rectangular
|
||||
/// sampling, and return the filled window.
|
||||
fn fill_measured_document(sampling: &str, opts: &FillOptions) -> Vec<f32> {
|
||||
/// Fill the measured document the way the command does with `opts` and Auto sampling, and return
|
||||
/// the filled window.
|
||||
fn fill_measured_document(opts: &FillOptions) -> Vec<f32> {
|
||||
let (img, hole, ww) = window_buffers();
|
||||
let source = match sampling {
|
||||
"auto" => auto_sampling(ww, 400, 3, &img, &hole),
|
||||
_ => hole.iter().map(|h| !h).collect(),
|
||||
};
|
||||
let source = auto_sampling(ww, 400, 3, &img, &hole);
|
||||
fill(ww, 400, 3, &img, &hole, &source, opts)
|
||||
}
|
||||
|
||||
@@ -169,49 +166,29 @@ fn boundary_mismatches(out: &[f32]) -> (usize, usize) {
|
||||
(green_above, cold_below)
|
||||
}
|
||||
|
||||
/// The measured fill, computed once: Auto and Rectangular give `fill` the same area on this
|
||||
/// document ([`measured_auto_area_is_the_rectangular_one`]), so one fill stands for both. The
|
||||
/// checks are collected first, so a failure reports every one that is off.
|
||||
#[test]
|
||||
fn auto_fill_continues_the_bands_and_stripes_at_the_measured_samples() {
|
||||
fn measured_fill_continues_the_bands_and_stripes_and_keeps_the_boundary_at_y_200() {
|
||||
assert_eq!(window(), Rect::new(100, 0, 500, 400), "the sampling window #14191 measured");
|
||||
let out = fill_measured_document("auto", &FillOptions::default());
|
||||
let out = fill_measured_document(&FillOptions::default());
|
||||
let mut failures = Vec::new();
|
||||
let off = samples_off(&out);
|
||||
assert!(off.is_empty(), "Auto sampling: {} of 9 samples off\n{}", off.len(), off.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangular_fill_continues_the_bands_and_stripes_at_the_measured_samples() {
|
||||
let out = fill_measured_document("rectangular", &FillOptions::default());
|
||||
let off = samples_off(&out);
|
||||
assert!(off.is_empty(), "Rectangular sampling: {} of 9 samples off\n{}", off.len(), off.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_fill_keeps_the_blue_green_boundary_at_y_200() {
|
||||
let out = fill_measured_document("auto", &FillOptions::default());
|
||||
if !off.is_empty() {
|
||||
failures.push(format!("{} of 9 samples off\n{}", off.len(), off.join("\n")));
|
||||
}
|
||||
let (green_above, cold_below) = boundary_mismatches(&out);
|
||||
assert_eq!(green_above, 0, "pixels above y 200 that took a colour of the green half");
|
||||
assert_eq!(cold_below, 0, "pixels below y 200 that took a colour of the blue half");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangular_fill_keeps_the_blue_green_boundary_at_y_200() {
|
||||
let out = fill_measured_document("rectangular", &FillOptions::default());
|
||||
let (green_above, cold_below) = boundary_mismatches(&out);
|
||||
assert_eq!(green_above, 0, "pixels above y 200 that took a colour of the green half");
|
||||
assert_eq!(cold_below, 0, "pixels below y 200 that took a colour of the blue half");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_fill_keeps_the_band_and_stripe_phase_across_the_whole_hole() {
|
||||
let out = fill_measured_document("auto", &FillOptions::default());
|
||||
if (green_above, cold_below) != (0, 0) {
|
||||
failures.push(format!(
|
||||
"the blue / green boundary moved: {green_above} pixels above y 200 took a colour of the green half, {cold_below} below it one of the blue half"
|
||||
));
|
||||
}
|
||||
let (worst, within, n) = phase_through_the_hole(&out);
|
||||
assert_eq!((within, n), (10_000, 10_000), "{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangular_fill_keeps_the_band_and_stripe_phase_across_the_whole_hole() {
|
||||
let out = fill_measured_document("rectangular", &FillOptions::default());
|
||||
let (worst, within, n) = phase_through_the_hole(&out);
|
||||
assert_eq!((within, n), (10_000, 10_000), "{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})");
|
||||
if within != n {
|
||||
failures.push(format!("{within} of {n} hole pixels carry the document's own colour within 12 levels (worst {worst})"));
|
||||
}
|
||||
assert!(failures.is_empty(), "{}", failures.join("\n"));
|
||||
}
|
||||
|
||||
/// Per-channel slack for the unmeasured pins below. The exact values hold bit for bit on Windows
|
||||
@@ -273,7 +250,7 @@ fn unmeasured_geometric_adaptation() -> Vec<(&'static str, FillOptions, [i32; 27
|
||||
}
|
||||
|
||||
fn check_unmeasured(what: &str, opts: &FillOptions, want: &[i32; 27]) {
|
||||
let out = fill_measured_document("auto", opts);
|
||||
let out = fill_measured_document(opts);
|
||||
let got: Vec<i32> = SAMPLES.iter().flat_map(|((x, y), _)| filled_at(&out, *x, *y)).collect();
|
||||
let off: Vec<String> = SAMPLES
|
||||
.iter()
|
||||
@@ -307,8 +284,8 @@ fn unmeasured_geometric_adaptation_keeps_todays_fill() {
|
||||
|
||||
#[test]
|
||||
fn measured_auto_area_is_the_rectangular_one() {
|
||||
// What the measured Auto and Rectangular fills above rest on: on this document Auto keeps the
|
||||
// whole window, as in the reference application.
|
||||
// What the measured fill above rests on: on this document Auto keeps the whole window, as in
|
||||
// the reference application, so the Auto fill is the Rectangular one.
|
||||
let (img, hole, ww) = window_buffers();
|
||||
assert_eq!(auto_sampling(ww, 400, 3, &img, &hole), hole.iter().map(|h| !h).collect::<Vec<bool>>());
|
||||
}
|
||||
|
||||
@@ -385,7 +385,8 @@ pub fn tone_map(px: &mut [[f32; 4]], w: usize, h: usize, method: &ToneMethod) {
|
||||
q[c] *= k;
|
||||
}
|
||||
}
|
||||
crate::tone::hdr_toning(px, w, h, p);
|
||||
// Today's merge radiance keeps the mean-anchored map until #14023 moves it (#14723).
|
||||
crate::tone::hdr_toning_mean_anchored(px, w, h, p);
|
||||
for q in px.iter_mut() {
|
||||
for c in 0..3 {
|
||||
q[c] = linear_to_srgb(q[c].clamp(0.0, 1.0));
|
||||
|
||||
@@ -326,6 +326,7 @@ impl Rng {
|
||||
}
|
||||
|
||||
/// Integer hash → `0..1` (position-keyed noise, independent of tiling).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn hash01(x: i64, y: i64, seed: u64) -> f32 {
|
||||
let mut z = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F) ^ seed.wrapping_mul(0x1656_67B1_9E37_79F9);
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
@@ -337,6 +338,7 @@ pub(crate) fn hash01(x: i64, y: i64, seed: u64) -> f32 {
|
||||
pub(crate) use photocraft_color::convert::{linear_to_srgb, srgb_to_linear};
|
||||
|
||||
/// Bilinear sample of channel `c` of a `w × h × ch` buffer, clamped to the edges.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn bilinear(buf: &[f32], w: usize, h: usize, ch: usize, c: usize, x: f32, y: f32) -> f32 {
|
||||
let x = x.clamp(0.0, (w - 1) as f32);
|
||||
let y = y.clamp(0.0, (h - 1) as f32);
|
||||
|
||||
@@ -89,9 +89,11 @@ pub fn web_palette() -> Vec<Rgb8> {
|
||||
v
|
||||
}
|
||||
|
||||
/// Classic Mac OS system palette: the web cube plus 10-step red, green, blue and gray ramps.
|
||||
/// Classic Mac OS system palette: the web cube plus 10-step red, green, blue and gray ramps. The
|
||||
/// table runs from white down through the cube (FFFFFF, FFFFCC, FFFF99, …), then the four ramps,
|
||||
/// and ends with black (#14344).
|
||||
pub fn mac_palette() -> Vec<Rgb8> {
|
||||
let mut v = web_palette();
|
||||
let mut v: Vec<Rgb8> = web_palette().into_iter().skip(1).rev().collect();
|
||||
// Ramps use the values between cube steps (17-unit spacing, skipping multiples of 51).
|
||||
let steps: Vec<u8> = (1..=15u8).map(|k| k * 17).filter(|x| x % 51 != 0).collect();
|
||||
for &s in steps.iter().rev() {
|
||||
@@ -106,11 +108,13 @@ pub fn mac_palette() -> Vec<Rgb8> {
|
||||
for &s in steps.iter().rev() {
|
||||
v.push([s, s, s]);
|
||||
}
|
||||
v.push([0, 0, 0]);
|
||||
v.truncate(256);
|
||||
v
|
||||
}
|
||||
|
||||
/// Windows default palette: the 20 static system colours plus the web cube and a gray ramp.
|
||||
/// Windows default palette: the 20 static system colours plus the web cube and a gray ramp. The
|
||||
/// table starts with black and the static colours and ends with white (#14344).
|
||||
pub fn windows_palette() -> Vec<Rgb8> {
|
||||
let mut v: Vec<Rgb8> = vec![
|
||||
[0, 0, 0],
|
||||
@@ -132,20 +136,21 @@ pub fn windows_palette() -> Vec<Rgb8> {
|
||||
[0, 0, 255],
|
||||
[255, 0, 255],
|
||||
[0, 255, 255],
|
||||
[255, 255, 255],
|
||||
];
|
||||
const WHITE: Rgb8 = [255, 255, 255];
|
||||
for c in web_palette() {
|
||||
if !v.contains(&c) {
|
||||
if c != WHITE && !v.contains(&c) {
|
||||
v.push(c);
|
||||
}
|
||||
}
|
||||
let mut g = 8u8;
|
||||
while v.len() < 256 {
|
||||
while v.len() < 255 {
|
||||
if !v.contains(&[g, g, g]) {
|
||||
v.push([g, g, g]);
|
||||
}
|
||||
g = g.wrapping_add(12);
|
||||
}
|
||||
v.push(WHITE);
|
||||
v
|
||||
}
|
||||
|
||||
@@ -404,6 +409,11 @@ pub fn build_palette(px: &[[f32; 4]], kind: PaletteKind, colors: usize, forced:
|
||||
if hist.len() > 256 {
|
||||
return Err(format!("the image has {} colours; Exact needs 256 or fewer", hist.len()));
|
||||
}
|
||||
// Forced entries absent from the image still consume palette slots.
|
||||
let required = hist.len() + pal.iter().filter(|color| !hist.iter().any(|(existing, _)| existing == *color)).count();
|
||||
if required > 256 {
|
||||
return Err(format!("the image and forced colours need {required} entries; Exact needs 256 or fewer"));
|
||||
}
|
||||
hist.iter().map(|h| h.0).collect()
|
||||
}
|
||||
PaletteKind::SystemMac => mac_palette(),
|
||||
|
||||
@@ -270,6 +270,34 @@ fn exact_palette_and_failure() {
|
||||
assert!(build_palette(&gradient(64, 64), PaletteKind::Exact, 256, Forced::None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_palette_counts_forced_colours_without_dropping_image_colours() {
|
||||
let pixels = |count: u16| (0..count).map(|r| [f32::from(r) / 255.0, 42.0 / 255.0, 7.0 / 255.0, 1.0]).collect::<Vec<_>>();
|
||||
let px = pixels(256);
|
||||
let error = build_palette(&px, PaletteKind::Exact, 256, Forced::BlackWhite).unwrap_err();
|
||||
assert!(error.contains("258") && error.contains("forced"), "{error}");
|
||||
|
||||
let boundary = pixels(254);
|
||||
let palette = build_palette(&boundary, PaletteKind::Exact, 256, Forced::BlackWhite).unwrap();
|
||||
assert_eq!(palette.len(), 256);
|
||||
assert_eq!(&palette[..2], &[[0, 0, 0], [255, 255, 255]], "forced colours retain their order");
|
||||
for r in 0..254u8 {
|
||||
assert!(palette.contains(&[r, 42, 7]), "the source colour {r} was dropped");
|
||||
}
|
||||
|
||||
let mut overlap = boundary;
|
||||
overlap.extend([[0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0]]);
|
||||
let palette = build_palette(&overlap, PaletteKind::Exact, 256, Forced::BlackWhite).unwrap();
|
||||
assert_eq!(palette.len(), 256, "forced colours already in the image count only once");
|
||||
for colors in [2, 256] {
|
||||
let palette = build_palette(&px, PaletteKind::Exact, colors, Forced::None).unwrap();
|
||||
assert_eq!(palette.len(), 256, "Exact still retains every image colour regardless of the requested count");
|
||||
for r in 0..=255u8 {
|
||||
assert!(palette.contains(&[r, 42, 7]), "the source colour {r} was dropped");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adaptive_and_perceptual_respect_count_and_forced() {
|
||||
let px = gradient(40, 40);
|
||||
|
||||
+202
-11
@@ -1,5 +1,6 @@
|
||||
//! High-quality separable resampling of surfaces (Image Size).
|
||||
|
||||
use photocraft_color::{PixelFormat, SampleType};
|
||||
use photocraft_geom::{Rect, TILE_SIZE};
|
||||
use photocraft_raster::Surface;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -388,6 +389,7 @@ pub fn resize_surface_with_interrupt(
|
||||
|
||||
fn resize_controlled(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Option<Rect>, budget: usize, ctl: &photocraft_raster::Interrupt) -> Surface {
|
||||
let mut cur: Option<Surface> = None;
|
||||
let canvas_in = canvas;
|
||||
let mut canvas = canvas;
|
||||
for p in plan(filter, sx, sy) {
|
||||
if ctl.cancelled() {
|
||||
@@ -397,23 +399,206 @@ fn resize_controlled(s: &Surface, sx: f64, sy: f64, filter: Resample, canvas: Op
|
||||
canvas = canvas.map(|c| scaled_rect(c, p.sx, p.sy));
|
||||
cur = Some(next);
|
||||
}
|
||||
let mut out = preserve_details(cur.unwrap_or_else(|| s.clone()), filter, sx, sy);
|
||||
let mut out = preserve_details(cur.unwrap_or_else(|| s.clone()), Some((s, canvas_in)), filter, sx, sy);
|
||||
out.prune();
|
||||
out
|
||||
}
|
||||
|
||||
/// Preserve Details' light sharpening of an enlargement (Lanczos's output, for the other filters
|
||||
/// nothing).
|
||||
fn preserve_details(mut out: Surface, filter: Resample, sx: f64, sy: f64) -> Surface {
|
||||
if filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0) {
|
||||
let dst = out.content_bounds();
|
||||
let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 };
|
||||
let area = crate::output_area(&p, dst, dst, None);
|
||||
out = crate::apply(&out, &p, area, dst, None);
|
||||
/// Whether `filter` at `(sx, sy)` ends with Preserve Details' sharpening of an enlargement.
|
||||
fn sharpens(filter: Resample, sx: f64, sy: f64) -> bool {
|
||||
filter == Resample::PreserveDetails && (sx > 1.0 || sy > 1.0)
|
||||
}
|
||||
|
||||
/// Whether Preserve Details' enlargement of `fmt` at `(sx, sy)` is the case #14794 measured
|
||||
/// against the reference application, an 8-bit image enlarged 2x on both axes, and so gets
|
||||
/// [`dering`] and the fitted sharpening. The issue keeps every case it didn't measure (other
|
||||
/// scales, 16 and 32 bits) as it was.
|
||||
fn derings(fmt: PixelFormat, filter: Resample, sx: f64, sy: f64) -> bool {
|
||||
sharpens(filter, sx, sy) && fmt.sample == SampleType::U8 && sx == 2.0 && sy == 2.0
|
||||
}
|
||||
|
||||
/// Preserve Details' sharpening of an enlargement (Lanczos's output `out` of `src`, read with
|
||||
/// `canvas`; for the other filters nothing): an Unsharp Mask that steepens edges. In the measured
|
||||
/// case (see [`derings`]) every sample is kept within the source pixels around it before and after
|
||||
/// it, so the edges get no ringing halo (#14794); elsewhere it is the light 30 % mask as before.
|
||||
/// `src` is only needed in the measured case.
|
||||
fn preserve_details(mut out: Surface, src: Option<(&Surface, Option<Rect>)>, filter: Resample, sx: f64, sy: f64) -> Surface {
|
||||
if !sharpens(filter, sx, sy) {
|
||||
return out;
|
||||
}
|
||||
let dering_src = src.filter(|_| derings(out.format(), filter, sx, sy));
|
||||
if let Some((src, canvas)) = dering_src {
|
||||
dering(&mut out, src, sx, sy, canvas);
|
||||
}
|
||||
let (amount, radius) = match dering_src {
|
||||
Some(_) => (PD_AMOUNT, (PD_RADIUS * sx.max(sy)) as f32),
|
||||
None => (30.0, 0.6 * sx.max(sy) as f32),
|
||||
};
|
||||
let dst = out.content_bounds();
|
||||
let p = crate::FilterParams::UnsharpMask { amount, radius, threshold: 0.0 };
|
||||
let area = crate::output_area(&p, dst, dst, None);
|
||||
out = crate::apply(&out, &p, area, dst, None);
|
||||
if let Some((src, canvas)) = dering_src {
|
||||
dering(&mut out, src, sx, sy, canvas);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Preserve Details' Unsharp Mask amount (%) in the measured case and radius (per unit of
|
||||
/// scale), fitted to the reference application's 2x enlargement of a hard edge (#14794).
|
||||
pub(crate) const PD_AMOUNT: f32 = 127.0;
|
||||
pub(crate) const PD_RADIUS: f64 = 0.6;
|
||||
|
||||
/// Keeps each sample of `out` (a resize of `src` by `(sx, sy)`) within the range of the two by
|
||||
/// two source pixels around its source position, channel by channel. Colour channels only count
|
||||
/// the source pixels that are not fully transparent. Source positions are clamped into the area
|
||||
/// the resize reads: with `canvas` the content and the canvas, whose edges repeat outwards;
|
||||
/// without, the content and one pixel around it, since beyond the content the resize reads the
|
||||
/// default pixel (so an opaque layer's partly transparent fringe stays so).
|
||||
///
|
||||
/// Source rows are read one at a time, whatever the scale, and bands of output rows are written
|
||||
/// a group at a time, like [`resize_pass`], so memory stays bounded.
|
||||
pub(crate) fn dering(out: &mut Surface, src: &Surface, sx: f64, sy: f64, canvas: Option<Rect>) {
|
||||
let dst = out.content_bounds();
|
||||
let content = src.content_bounds();
|
||||
let area = match canvas {
|
||||
Some(c) => content.union(&c),
|
||||
None if content.is_empty() => content,
|
||||
None => content.inflate(1),
|
||||
};
|
||||
if dst.is_empty() || area.is_empty() || !(sx > 0.0 && sy > 0.0) {
|
||||
return;
|
||||
}
|
||||
let fmt = out.format();
|
||||
let n = fmt.channels();
|
||||
let alpha = fmt.alpha;
|
||||
// The two source samples around output sample `o`, as indices into `lo..=hi`.
|
||||
let pair = |o: i32, scale: f64, lo: i32, hi: i32| -> (usize, usize) {
|
||||
let u = ((o as f64 + 0.5) / scale - 0.5).floor();
|
||||
let i0 = (u.clamp(f64::from(lo), f64::from(hi)) as i32 - lo) as usize;
|
||||
let i1 = ((u + 1.0).clamp(f64::from(lo), f64::from(hi)) as i32 - lo) as usize;
|
||||
(i0, i1)
|
||||
};
|
||||
let mut xs: Vec<(usize, usize)> = (dst.x0..dst.x1).map(|o| pair(o, sx, area.x0, area.x1 - 1)).collect();
|
||||
// Only the source columns the output reads (a small layer on a wide canvas reads a few), with
|
||||
// `xs` rebased to them.
|
||||
let c0 = xs.iter().map(|&(a, _)| a).min().unwrap_or(0);
|
||||
let c1 = xs.iter().map(|&(_, b)| b + 1).max().unwrap_or(c0);
|
||||
for (a, b) in &mut xs {
|
||||
(*a, *b) = (*a - c0, *b - c0);
|
||||
}
|
||||
let sw = (c1 - c0) * n;
|
||||
let x0 = area.x0.saturating_add(i32::try_from(c0).unwrap_or(i32::MAX));
|
||||
let x1 = area.x0.saturating_add(i32::try_from(c1).unwrap_or(i32::MAX));
|
||||
// Source row `k` of the area (as `pair` indexes it), columns `c0..c1`, into `buf`.
|
||||
let read_row = |k: usize, buf: &mut Vec<f32>| {
|
||||
let y = area.y0.saturating_add(i32::try_from(k).unwrap_or(i32::MAX));
|
||||
let r = Rect::new(x0, y, x1, y.saturating_add(1));
|
||||
#[cfg(test)]
|
||||
DERING_MAX_READ_ROWS.fetch_max(r.height() as usize, std::sync::atomic::Ordering::Relaxed);
|
||||
#[cfg(test)]
|
||||
DERING_READ_COLUMNS.with(|c| c.set(c.get().max(r.width() as usize)));
|
||||
src.read_region_into(r, buf);
|
||||
};
|
||||
let band = |out: &Surface, b: usize| -> (Rect, Vec<f32>) {
|
||||
let y0 = dst.y0.saturating_add(i32::try_from(b * BAND).unwrap_or(i32::MAX)).min(dst.y1);
|
||||
let r = Rect::new(dst.x0, y0, dst.x1, y0.saturating_add(BAND as i32).min(dst.y1));
|
||||
let ys: Vec<(usize, usize)> = (r.y0..r.y1).map(|o| pair(o, sy, area.y0, area.y1 - 1)).collect();
|
||||
let mut data = out.read_region(r);
|
||||
// The two source rows of the current pair, with their indices: a row shared with the
|
||||
// previous pair is kept instead of read again.
|
||||
let (mut ra, mut rb): (SourceRow, SourceRow) = ((None, Vec::new()), (None, Vec::new()));
|
||||
// The range of each source column over the current pair of rows: colour channels of
|
||||
// transparent pixels count as nothing (an empty range, `lo > hi`).
|
||||
let (mut vlo, mut vhi) = (vec![0.0f32; sw], vec![0.0f32; sw]);
|
||||
let mut rows = None;
|
||||
for (&(y0, y1), row) in ys.iter().zip(data.chunks_exact_mut(dst.width() as usize * n)) {
|
||||
if rows != Some((y0, y1)) {
|
||||
rows = Some((y0, y1));
|
||||
if rb.0 == Some(y0) {
|
||||
std::mem::swap(&mut ra, &mut rb);
|
||||
}
|
||||
if ra.0 != Some(y0) {
|
||||
read_row(y0, &mut ra.1);
|
||||
ra.0 = Some(y0);
|
||||
}
|
||||
if rb.0 != Some(y1) {
|
||||
read_row(y1, &mut rb.1);
|
||||
rb.0 = Some(y1);
|
||||
}
|
||||
for (((pa, pb), lo), hi) in ra.1.chunks_exact(n).zip(rb.1.chunks_exact(n)).zip(vlo.chunks_exact_mut(n)).zip(vhi.chunks_exact_mut(n)) {
|
||||
let seen = |p: &[f32]| !alpha || p.last().is_some_and(|&v| v > 0.0);
|
||||
let (sa, sb) = (seen(pa), seen(pb));
|
||||
for (c, (((&va, &vb), l), h)) in pa.iter().zip(pb).zip(lo.iter_mut()).zip(hi.iter_mut()).enumerate() {
|
||||
let all = alpha && c == n - 1;
|
||||
let (ia, ib) = (sa || all, sb || all);
|
||||
*l = match (ia, ib) {
|
||||
(true, true) => va.min(vb),
|
||||
(true, false) => va,
|
||||
(false, true) => vb,
|
||||
(false, false) => f32::INFINITY,
|
||||
};
|
||||
*h = match (ia, ib) {
|
||||
(true, true) => va.max(vb),
|
||||
(true, false) => va,
|
||||
(false, true) => vb,
|
||||
(false, false) => f32::NEG_INFINITY,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
for (&(x0, x1), px) in xs.iter().zip(row.chunks_exact_mut(n)) {
|
||||
let (l0, l1, h0, h1) = (vlo.get(x0 * n..), vlo.get(x1 * n..), vhi.get(x0 * n..), vhi.get(x1 * n..));
|
||||
let (Some(l0), Some(l1), Some(h0), Some(h1)) = (l0, l1, h0, h1) else { continue };
|
||||
for ((((v, &l0), &l1), &h0), &h1) in px.iter_mut().zip(l0).zip(l1).zip(h0).zip(h1) {
|
||||
let (lo, hi) = (l0.min(l1), h0.max(h1));
|
||||
if lo <= hi {
|
||||
*v = v.clamp(lo, hi);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(r, data)
|
||||
};
|
||||
let bands: Vec<usize> = (0..(dst.height() as usize).div_ceil(BAND)).collect();
|
||||
// Bands read disjoint output rows, so each group is written before the next is computed, and
|
||||
// the `f32` rows held at once are bounded by the group (#1544).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let group = rayon::current_num_threads().max(1) * 2;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let group = 1;
|
||||
for chunk in bands.chunks(group) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let parts: Vec<(Rect, Vec<f32>)> = {
|
||||
use rayon::prelude::*;
|
||||
let o: &Surface = out;
|
||||
chunk.par_iter().map(|&b| band(o, b)).collect()
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let parts: Vec<(Rect, Vec<f32>)> = chunk.iter().map(|&b| band(out, b)).collect();
|
||||
#[cfg(test)]
|
||||
DERING_MAX_HELD_BANDS.fetch_max(parts.len(), std::sync::atomic::Ordering::Relaxed);
|
||||
for (r, d) in parts {
|
||||
out.write_region(r, &d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A source row read by [`dering`]: its index (if any yet) and samples.
|
||||
type SourceRow = (Option<usize>, Vec<f32>);
|
||||
|
||||
/// The most source rows one read of [`dering`] has spanned, and the most bands it has held
|
||||
/// before writing them, so tests can check both stay bounded.
|
||||
#[cfg(test)]
|
||||
pub(crate) static DERING_MAX_READ_ROWS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The most source columns one read of [`dering`] has spanned on this thread.
|
||||
pub(crate) static DERING_READ_COLUMNS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) static DERING_MAX_HELD_BANDS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
|
||||
/// Output rows computed together by [`PassState::band`].
|
||||
const BAND: usize = 64;
|
||||
|
||||
@@ -607,6 +792,8 @@ pub struct ResizeSteps {
|
||||
canvas: Option<Rect>,
|
||||
filter: Resample,
|
||||
scale: (f64, f64),
|
||||
/// The input and its canvas, kept for Preserve Details' closing sharpening.
|
||||
orig: Option<(Surface, Option<Rect>)>,
|
||||
run: Option<PassRun>,
|
||||
/// Final pruning must yield too: sparse output can contain many default-filled tiles.
|
||||
prune: Option<photocraft_raster::PruneCursor>,
|
||||
@@ -625,7 +812,8 @@ impl ResizeSteps {
|
||||
/// or [`resize_surface_in_canvas`] does.
|
||||
pub fn new(src: Surface, sx: f64, sy: f64, filter: Resample, canvas: Option<Rect>) -> Self {
|
||||
let passes = plan(filter, sx, sy);
|
||||
Self { src, total: passes.len(), passes: passes.into_iter(), canvas, filter, scale: (sx, sy), run: None, prune: None }
|
||||
let orig = derings(src.format(), filter, sx, sy).then(|| (src.clone(), canvas));
|
||||
Self { src, total: passes.len(), passes: passes.into_iter(), canvas, filter, scale: (sx, sy), orig, run: None, prune: None }
|
||||
}
|
||||
|
||||
/// How far along it is, `0.0..=1.0`: whole passes plus the bands done of the current one.
|
||||
@@ -677,7 +865,8 @@ impl ResizeSteps {
|
||||
if self.prune.is_none() {
|
||||
let placeholder = Surface::new(self.src.format());
|
||||
let out = std::mem::replace(&mut self.src, placeholder);
|
||||
self.src = preserve_details(out, self.filter, self.scale.0, self.scale.1);
|
||||
let orig = self.orig.take();
|
||||
self.src = preserve_details(out, orig.as_ref().map(|(o, c)| (o, *c)), self.filter, self.scale.0, self.scale.1);
|
||||
self.prune = Some(self.src.prune_cursor());
|
||||
}
|
||||
let cursor = self.prune.as_mut()?;
|
||||
@@ -704,5 +893,7 @@ pub fn crop_surface(s: &Surface, keep: Rect) -> Surface {
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod preserve_details_edge_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,239 @@
|
||||
//! Preserve Details enlarges hard edges without a ringing halo (#14794).
|
||||
|
||||
use super::*;
|
||||
use photocraft_color::{ColorMode, PixelFormat, SampleType};
|
||||
|
||||
const CANVAS: Rect = Rect { x0: 0, y0: 0, x1: 400, y1: 300 };
|
||||
|
||||
/// The issue's flattened document: white, a red square at (0,0), a blue one at (300,200) and a
|
||||
/// green one at (175,125), each opaque.
|
||||
fn document(sample: SampleType, alpha: bool) -> Surface {
|
||||
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, alpha));
|
||||
let px = |r: f32, g: f32, b: f32| if alpha { vec![r, g, b, 1.0] } else { vec![r, g, b] };
|
||||
s.fill_rect(CANVAS, &px(1.0, 1.0, 1.0));
|
||||
s.fill_rect(Rect::new(0, 0, 100, 100), &px(1.0, 0.0, 0.0));
|
||||
s.fill_rect(Rect::new(300, 200, 400, 300), &px(0.0, 0.0, 1.0));
|
||||
s.fill_rect(Rect::new(175, 125, 225, 175), &px(0.0, 1.0, 0.0));
|
||||
s
|
||||
}
|
||||
|
||||
/// The green channel at y, x in `xs`, in 8-bit levels.
|
||||
fn green(s: &Surface, y: i32, xs: std::ops::Range<i32>) -> Vec<i32> {
|
||||
xs.map(|x| (s.pixel(x, y)[1] * 255.0).round() as i32).collect()
|
||||
}
|
||||
|
||||
fn within(actual: &[i32], expected: &[i32], tol: i32) -> bool {
|
||||
actual.len() == expected.len() && actual.iter().zip(expected).all(|(a, e)| (a - e).abs() <= tol)
|
||||
}
|
||||
|
||||
/// The reference application enlarges the red/white edge 2x to `0,0,0,8,247,255,255,255,255`
|
||||
/// (green channel, y=20, x 196..204) with Preserve Details: no overshoot on either side, a
|
||||
/// steep edge. Measured at 8 bits only (16 and 32 bits keep the previous result, see
|
||||
/// [`unmeasured_enlargements_keep_the_previous_sharpening`]).
|
||||
#[test]
|
||||
fn enlarging_a_hard_edge_does_not_ring() {
|
||||
let reference = [0, 0, 0, 8, 247, 255, 255, 255, 255];
|
||||
for alpha in [false, true] {
|
||||
let o = resize_surface_in_canvas(&document(SampleType::U8, alpha), 2.0, 2.0, Resample::PreserveDetails, CANVAS);
|
||||
let row = green(&o, 20, 196..205);
|
||||
assert!(within(&row, &reference, 2), "alpha={alpha}: {row:?}, reference {reference:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Reducing with Preserve Details stays Bicubic Sharper: `0,0,0,13,242,255,255,255` at 200x150.
|
||||
#[test]
|
||||
fn reducing_stays_bicubic_sharper() {
|
||||
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let s = document(sample, false);
|
||||
let pd = resize_surface_in_canvas(&s, 0.5, 0.5, Resample::PreserveDetails, CANVAS);
|
||||
let sharper = resize_surface_in_canvas(&s, 0.5, 0.5, Resample::BicubicSharper, CANVAS);
|
||||
let r = Rect::new(0, 0, 200, 150);
|
||||
assert_eq!(pd.read_region(r), sharper.read_region(r), "{sample:?}");
|
||||
if sample == SampleType::U8 {
|
||||
assert_eq!(green(&pd, 10, 46..54), [0, 0, 0, 13, 242, 255, 255, 255]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The other methods enlarge the edge as before (#14794 changes Preserve Details only).
|
||||
#[test]
|
||||
fn other_methods_keep_their_edge() {
|
||||
let s = document(SampleType::U8, false);
|
||||
let cases: [(Resample, [i32; 9]); 7] = [
|
||||
(Resample::Nearest, ROWS[0]),
|
||||
(Resample::Bilinear, ROWS[1]),
|
||||
(Resample::Bicubic, ROWS[2]),
|
||||
(Resample::BicubicSmoother, ROWS[3]),
|
||||
(Resample::BicubicSharper, ROWS[4]),
|
||||
(Resample::BicubicAutomatic, ROWS[5]),
|
||||
(Resample::Lanczos, ROWS[6]),
|
||||
];
|
||||
for (f, expected) in cases {
|
||||
let o = resize_surface_in_canvas(&s, 2.0, 2.0, f, CANVAS);
|
||||
assert_eq!(green(&o, 20, 196..205), expected, "{f:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows main 406ac677e1 gives, for [`other_methods_keep_their_edge`].
|
||||
const ROWS: [[i32; 9]; 7] = [
|
||||
[0, 0, 0, 0, 255, 255, 255, 255, 255],
|
||||
[0, 0, 0, 64, 191, 255, 255, 255, 255],
|
||||
[0, 0, 0, 58, 197, 255, 255, 255, 255],
|
||||
[0, 0, 0, 66, 189, 255, 255, 255, 255],
|
||||
[0, 0, 0, 66, 189, 255, 255, 255, 255],
|
||||
[0, 0, 0, 66, 189, 255, 255, 255, 255],
|
||||
[8, 0, 0, 54, 201, 255, 255, 247, 253],
|
||||
];
|
||||
|
||||
/// The measured enlargement (8 bits, 2x) stays within the source's levels: no halo darker than
|
||||
/// the red or brighter than the white, and flat areas stay flat.
|
||||
#[test]
|
||||
fn the_measured_enlargement_never_overshoots() {
|
||||
let s = document(SampleType::U8, true);
|
||||
let o = resize_surface_in_canvas(&s, 2.0, 2.0, Resample::PreserveDetails, CANVAS);
|
||||
let dst = scaled_rect(CANVAS, 2.0, 2.0);
|
||||
assert_eq!(o.content_bounds(), dst);
|
||||
for v in o.read_region(dst) {
|
||||
assert!((0.0..=1.0).contains(&v), "{v}");
|
||||
}
|
||||
// Inside the red square, away from its edge.
|
||||
assert_eq!(o.pixel(100, 100), vec![1.0, 0.0, 0.0, 1.0]);
|
||||
}
|
||||
|
||||
/// A layer smaller than the canvas, on transparency: in the measured case the clamp doesn't pull
|
||||
/// its colour towards the transparent pixels, and at any scale and depth the stepped resize gives
|
||||
/// the same pixels as the one-shot one.
|
||||
#[test]
|
||||
fn transparent_surroundings_and_steps_match() {
|
||||
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
|
||||
s.fill_rect(Rect::new(10, 10, 30, 30), &[0.2, 0.6, 1.0, 1.0]);
|
||||
for k in [2.0, 2.5] {
|
||||
let o = resize_surface_in_canvas(&s, k, k, Resample::PreserveDetails, CANVAS);
|
||||
if sample == SampleType::U8 && k == 2.0 {
|
||||
// On the layer's edge the colour stays the layer's.
|
||||
let edge = o.pixel(20, 40);
|
||||
assert!(edge[3] > 0.0 && edge[3] < 1.0, "{edge:?}");
|
||||
let off = edge.iter().take(3).zip([0.2, 0.6, 1.0]).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
|
||||
assert!(off < 0.01, "{edge:?}");
|
||||
}
|
||||
let mut steps = ResizeSteps::new(s.clone(), k, k, Resample::PreserveDetails, Some(CANVAS));
|
||||
let stepped = loop {
|
||||
if let Some(out) = steps.step(&mut || true) {
|
||||
break out;
|
||||
}
|
||||
};
|
||||
let r = o.content_bounds().union(&stepped.content_bounds());
|
||||
assert_eq!(stepped.read_region(r), o.read_region(r), "{sample:?} {k}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve Details before #14794: Lanczos, then an Unsharp Mask of 30 % at radius 0.6 x scale.
|
||||
fn lanczos_and_unsharp_mask(s: &Surface, sx: f64, sy: f64) -> Surface {
|
||||
let out = resize_surface(s, sx, sy, Resample::Lanczos);
|
||||
let dst = out.content_bounds();
|
||||
let p = crate::FilterParams::UnsharpMask { amount: 30.0, radius: 0.6 * sx.max(sy) as f32, threshold: 0.0 };
|
||||
let area = crate::output_area(&p, dst, dst, None);
|
||||
let mut out = crate::apply(&out, &p, area, dst, None);
|
||||
out.prune();
|
||||
out
|
||||
}
|
||||
|
||||
/// The issue measured only 8-bit 2x enlargements; other scales and 16/32-bit documents keep
|
||||
/// Preserve Details' previous result (#14794, "not measured ... keep today's behaviour").
|
||||
#[test]
|
||||
fn unmeasured_enlargements_keep_the_previous_sharpening() {
|
||||
let cases = [
|
||||
(SampleType::U8, 1.37, 1.37),
|
||||
(SampleType::U8, 3.0, 3.0),
|
||||
(SampleType::U8, 2.0, 1.5),
|
||||
(SampleType::U8, 1.0, 2.0),
|
||||
(SampleType::U16, 2.0, 2.0),
|
||||
(SampleType::F32, 2.0, 2.0),
|
||||
];
|
||||
for (sample, sx, sy) in cases {
|
||||
let s = document(sample, false);
|
||||
let actual = resize_surface(&s, sx, sy, Resample::PreserveDetails);
|
||||
let expected = lanczos_and_unsharp_mask(&s, sx, sy);
|
||||
let r = actual.content_bounds().union(&expected.content_bounds());
|
||||
assert!(actual.read_region(r) == expected.read_region(r), "{sample:?} {sx}x{sy}: differs from Lanczos + Unsharp Mask 30 %");
|
||||
}
|
||||
}
|
||||
|
||||
/// One axis shrinking and the other growing: the columns black, black, black, white reduced to a
|
||||
/// quarter keep the white averaged in by the reduction instead of being clamped back to black.
|
||||
#[test]
|
||||
fn mixed_axis_resize_keeps_reduced_detail() {
|
||||
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));
|
||||
for x in 0..64 {
|
||||
let v = if x % 4 == 3 { 1.0 } else { 0.0 };
|
||||
s.fill_rect(Rect::new(x, 0, x + 1, 16), &[v, v, v, 1.0]);
|
||||
}
|
||||
let o = resize_surface(&s, 0.25, 2.0, Resample::PreserveDetails);
|
||||
let v = o.pixel(8, 16)[1];
|
||||
assert!(v > 0.1, "{sample:?}: green {v} at (8,16), the white columns were clamped away");
|
||||
let expected = lanczos_and_unsharp_mask(&s, 0.25, 2.0);
|
||||
let r = o.content_bounds().union(&expected.content_bounds());
|
||||
assert!(o.read_region(r) == expected.read_region(r), "{sample:?}: differs from Lanczos + Unsharp Mask 30 %");
|
||||
}
|
||||
}
|
||||
|
||||
/// A band of output rows that spans thousands of source rows (6000x4000 at 2 x 0.01 spans about
|
||||
/// 3900 per band) reads them a row at a time, so a read stays within the read budget.
|
||||
#[test]
|
||||
fn dering_reads_a_bounded_number_of_source_rows() {
|
||||
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, false));
|
||||
s.fill_rect(Rect::new(0, 0, 8, 4000), &[0.5, 0.5, 0.5]);
|
||||
let mut o = resize_surface(&s, 2.0, 0.01, Resample::Lanczos);
|
||||
dering(&mut o, &s, 2.0, 0.01, None);
|
||||
let rows = DERING_MAX_READ_ROWS.load(std::sync::atomic::Ordering::Relaxed);
|
||||
assert!(rows <= 1, "one dering read spanned {rows} source rows");
|
||||
}
|
||||
|
||||
/// Dering writes its bands a group at a time, like `resize_pass`, instead of holding them all.
|
||||
#[test]
|
||||
fn dering_holds_a_bounded_group_of_bands() {
|
||||
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, false));
|
||||
s.fill_rect(Rect::new(0, 0, 2, 6400), &[0.5, 0.5, 0.5]);
|
||||
let mut o = resize_surface(&s, 2.0, 2.0, Resample::Lanczos);
|
||||
dering(&mut o, &s, 2.0, 2.0, None);
|
||||
let held = DERING_MAX_HELD_BANDS.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let group = rayon::current_num_threads().max(1) * 2;
|
||||
assert!(held <= group, "dering held {held} of {} bands at once (group {group})", 12800usize.div_ceil(BAND));
|
||||
}
|
||||
|
||||
/// Without a canvas, positions outside the content read the default pixel, as the resize does:
|
||||
/// an opaque square on transparency keeps its partly transparent fringe instead of the clamp
|
||||
/// making it opaque, and the result equals the one in a canvas of transparency around it.
|
||||
#[test]
|
||||
fn enlarging_without_a_canvas_keeps_the_transparent_fringe() {
|
||||
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
|
||||
s.fill_rect(Rect::new(10, 10, 30, 30), &[0.2, 0.6, 1.0, 1.0]);
|
||||
let o = resize_surface(&s, 2.0, 2.0, Resample::PreserveDetails);
|
||||
// The square's first output column: Lanczos leaves it partly transparent (about 0.79).
|
||||
let fringe = o.pixel(20, 40)[3];
|
||||
assert!(fringe > 0.0 && fringe < 1.0, "alpha {fringe} on the square's edge");
|
||||
let framed = resize_surface_in_canvas(&s, 2.0, 2.0, Resample::PreserveDetails, CANVAS);
|
||||
let r = o.content_bounds().union(&framed.content_bounds());
|
||||
assert!(o.read_region(r) == framed.read_region(r), "differs from the same square in a transparent canvas");
|
||||
}
|
||||
|
||||
/// With a canvas much wider than the layer, dering reads only the source columns the output
|
||||
/// samples use, not the whole canvas width.
|
||||
#[test]
|
||||
fn dering_reads_only_the_columns_it_uses() {
|
||||
let mut s = Surface::new(PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
|
||||
s.fill_rect(Rect::new(1000, 10, 1020, 30), &[0.2, 0.6, 1.0, 1.0]);
|
||||
let canvas = Rect::new(0, 0, 20_000, 40);
|
||||
let mut o = resize_surface_in_canvas(&s, 2.0, 2.0, Resample::Lanczos, canvas);
|
||||
// One worker thread, so the thread-local counter sees every read.
|
||||
let pool = rayon::ThreadPoolBuilder::new().num_threads(1).build().unwrap();
|
||||
let cols = pool.install(|| {
|
||||
DERING_READ_COLUMNS.with(|c| c.set(0));
|
||||
dering(&mut o, &s, 2.0, 2.0, Some(canvas));
|
||||
DERING_READ_COLUMNS.with(std::cell::Cell::get)
|
||||
});
|
||||
assert!(cols <= 40, "one dering read spanned {cols} source columns");
|
||||
}
|
||||
@@ -84,6 +84,12 @@ pub fn grabcut_with(img: &RgbImage, trimap: &mut [u8], iters: usize, ctl: &Inter
|
||||
Ok(models)
|
||||
}
|
||||
|
||||
/// Pass cap for [`object_select`]. Only the ring outside the rectangle seeds the background
|
||||
/// model, so on a backdrop lit brighter towards the subject each pass gives up just the next
|
||||
/// brightness band of it; a cap of 8 stopped half way and selected a straight-edged patch of
|
||||
/// backdrop (#6975). Cuts that settle earlier stop at `grabcut_with`'s change check.
|
||||
const OBJECT_SELECT_ITERS: usize = 30;
|
||||
|
||||
/// Object Selection (rectangle mode): GrabCut initialised from `rect` (outside = background,
|
||||
/// inside = probable foreground). Runs on a working copy of about `work_px` pixels, then re-cuts
|
||||
/// the boundary at full resolution. `canvas` bounds the analysis.
|
||||
@@ -124,7 +130,7 @@ pub fn object_select(sampler: &dyn Sampler, canvas: Rect, rect: Rect, work_px: u
|
||||
}
|
||||
}
|
||||
}
|
||||
let (fg, bg) = grabcut(&img, &mut trimap, 8)?;
|
||||
let (fg, bg) = grabcut(&img, &mut trimap, OBJECT_SELECT_ITERS)?;
|
||||
let low: Vec<bool> = trimap.iter().map(|t| is_fg(*t)).collect();
|
||||
let low = super::clean_mask(&low, lw, lh, 0.1, 0.0);
|
||||
// Every enclosed hole, however small, fills only when it looks like the object, so background seen through it stays open.
|
||||
|
||||
@@ -380,6 +380,71 @@ fn object_select_downsampled_with_band_refinement() {
|
||||
assert!(far_wrong < 300, "{far_wrong} pixels wrong away from the edge");
|
||||
}
|
||||
|
||||
/// A standing figure on a grey studio backdrop whose light falls off towards the corners
|
||||
/// (0.61 in the centre, 0.55 at the edge midpoints, 0.49 in the corners). Laid out on a
|
||||
/// 2000 x 3000 reference frame and scaled to `w` x `h`. Returns (image, truth).
|
||||
fn backdrop_falloff_scene(w: usize, h: usize, noise: f32, seed: u64) -> (RgbImage, Vec<bool>) {
|
||||
let mut rng = Rng::new(seed);
|
||||
let mut truth = vec![false; w * h];
|
||||
let (sx, sy) = (w as f32 / 2000.0, h as f32 / 3000.0);
|
||||
let img = RgbImage::from_fn(w, h, |x, y| {
|
||||
let (fx, fy) = (x as f32 / sx, y as f32 / sy);
|
||||
let n = noise * rng.normal();
|
||||
let e = |cx: f32, cy: f32, rx: f32, ry: f32| ((fx - cx) / rx).powi(2) + ((fy - cy) / ry).powi(2) <= 1.0;
|
||||
let hair = e(1000.0, 760.0, 125.0, 150.0);
|
||||
let face = e(1000.0, 820.0, 100.0, 130.0);
|
||||
let neck = (960.0..1040.0).contains(&fx) && (930.0..1000.0).contains(&fy);
|
||||
let half = 170.0 + (fy - 1000.0).max(0.0) * 0.1;
|
||||
let torso = (1000.0..2100.0).contains(&fy) && (fx - 1000.0).abs() <= half;
|
||||
let arm = (1000.0..1750.0).contains(&fy)
|
||||
&& ((760.0..820.0).contains(&(fx - (fy - 1000.0) * 0.02)) || (1180.0..1240.0).contains(&(fx + (fy - 1000.0) * 0.02)));
|
||||
let leg = (2100.0..2750.0).contains(&fy) && ((900.0..970.0).contains(&fx) || (1030.0..1100.0).contains(&fx));
|
||||
let tex = ((fx * 0.15).sin() * (fy * 0.11).cos()) * 0.04;
|
||||
let c = if face || neck {
|
||||
[0.86, 0.66, 0.56]
|
||||
} else if hair {
|
||||
[0.20, 0.14, 0.10]
|
||||
} else if arm || leg {
|
||||
[0.82, 0.62, 0.52]
|
||||
} else if torso {
|
||||
[0.10 + tex, 0.10 + tex, 0.12 + tex]
|
||||
} else {
|
||||
let (dx, dy) = ((fx - 1000.0) / 1000.0, (fy - 1500.0) / 1500.0);
|
||||
let g = 0.55 + 0.06 * (1.0 - dx * dx - dy * dy);
|
||||
[g, g, g * 0.99]
|
||||
};
|
||||
truth[y * w + x] = face || neck || hair || arm || leg || torso;
|
||||
c.map(|v| (v + n).clamp(0.0, 1.0))
|
||||
});
|
||||
(img, truth)
|
||||
}
|
||||
|
||||
/// Backdrop pixels Object Selection takes with a loose rectangle (the central 80 % of the frame).
|
||||
fn loose_rect_backdrop_px(w: usize, h: usize, work_px: usize) -> usize {
|
||||
let (img, truth) = backdrop_falloff_scene(w, h, 0.003, 7);
|
||||
let s = ImageSampler { img: &img, origin: (0, 0) };
|
||||
let canvas = Rect::new(0, 0, w as i32, h as i32);
|
||||
let rect = Rect::new((w / 10) as i32, (h / 10) as i32, (w * 9 / 10) as i32, (h * 9 / 10) as i32);
|
||||
let reg = grabcut::object_select(&s, canvas, rect, work_px).unwrap();
|
||||
(0..h).flat_map(|y| (0..w).map(move |x| (x, y))).filter(|&(x, y)| reg.at(x as i32, y as i32) >= 0.5 && !truth[y * w + x]).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_select_loose_rect_on_a_backdrop_with_light_falloff_leaves_the_backdrop_out() {
|
||||
// #6975: only the ring outside the rectangle seeds the background model, and it is darker
|
||||
// than the lit backdrop beside the figure, so each pass gives up just the next brightness
|
||||
// band. Stopping after 8 passes selected 21041 backdrop pixels here (the figure is 14209).
|
||||
let backdrop = loose_rect_backdrop_px(286, 429, 1_000_000);
|
||||
assert!(backdrop < 200, "{backdrop} backdrop pixels selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_select_loose_rect_on_a_lit_backdrop_downsampled_leaves_the_backdrop_out() {
|
||||
// The same at step 2 with the full-resolution band re-cut: 81534 backdrop pixels at 8 passes.
|
||||
let backdrop = loose_rect_backdrop_px(572, 858, 160_000);
|
||||
assert!(backdrop < 800, "{backdrop} backdrop pixels selected");
|
||||
}
|
||||
|
||||
// ---------- Quick selection ----------
|
||||
|
||||
/// Left: textured warm region; right: cool region; strong vertical edge at x = 60.
|
||||
|
||||
+62
-8
@@ -250,11 +250,48 @@ fn curve_eval(pts: &[(f32, f32)], x: f32) -> f32 {
|
||||
pts[pts.len() - 1].1
|
||||
}
|
||||
|
||||
/// The tone of a sample whose f32 exposure, gamma and shadow/highlight arithmetic overflowed (a
|
||||
/// low Gamma or a strong local contrast): the same curve evaluated in f64. A cap beyond every
|
||||
/// control's polynomial crossover keeps cubing finite; those values saturate at the display
|
||||
/// clamp. Both HDR Toning paths use it, so they stay equal.
|
||||
pub(crate) fn wide_range_tone(new_log: f32, exposure: f32, gamma: f32, shadow: f32, highlight: f32) -> f32 {
|
||||
let log_value = (f64::from(new_log) + f64::from(exposure) * std::f64::consts::LN_2) / f64::from(gamma);
|
||||
let value = log_value.exp().min(1e100);
|
||||
let shadow = f64::from(shadow) / 200.;
|
||||
let highlight = f64::from(highlight) / 200.;
|
||||
let mapped = ((-(shadow + highlight) * value + 3. * shadow) * value + (1. - 3. * shadow)) * value + shadow;
|
||||
mapped.clamp(0., 1.) as f32
|
||||
}
|
||||
|
||||
/// Local adaptation tone mapping (Durand–Dorsey style base/detail split in log luminance): the
|
||||
/// blurred log luminance (radius) is the base layer, compressed toward its mean by `strength`;
|
||||
/// detail is boosted; then exposure, gamma, shadow/highlight lift, the toning curve, and
|
||||
/// vibrance/saturation. Like Photoshop the result is a flattened, low-dynamic-range image.
|
||||
/// blurred log luminance (radius) is the base layer, compressed by `strength` toward its brightest
|
||||
/// value, which becomes white, so an ordinary image is stretched to the full range and its dark
|
||||
/// tones are lifted (#14723); the detail (log luminance less the base, boosted by `detail`) is
|
||||
/// compressed with it, so a darker tone never comes out brighter on a smooth gradient; then
|
||||
/// exposure, gamma, shadow/highlight lift, the toning curve, and vibrance/saturation. Like
|
||||
/// Photoshop the result is a flattened, low-dynamic-range image.
|
||||
pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) {
|
||||
local_adaptation(px, w, h, p, Anchor::White);
|
||||
}
|
||||
|
||||
/// Merge to HDR Pro's Local Adaptation until the merge moves to the reference's radiance and
|
||||
/// [`hdr_toning`] (#14023, #14021): the base is compressed toward its mean, which stays put, and
|
||||
/// the detail is not compressed. On today's merge radiance this is closer to the reference than
|
||||
/// the white-anchored map (#14723).
|
||||
pub(crate) fn hdr_toning_mean_anchored(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) {
|
||||
local_adaptation(px, w, h, p, Anchor::Mean);
|
||||
}
|
||||
|
||||
/// The log luminance a Local Adaptation base is compressed toward.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Anchor {
|
||||
/// The brightest visible base, which becomes white.
|
||||
White,
|
||||
/// The mean visible base, which stays put.
|
||||
Mean,
|
||||
}
|
||||
|
||||
fn local_adaptation(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning, anchor: Anchor) {
|
||||
if px.is_empty() {
|
||||
return;
|
||||
}
|
||||
@@ -265,10 +302,18 @@ pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) {
|
||||
});
|
||||
let mut base = logl.clone();
|
||||
gauss_blur_n(&mut base, w, h, 1, p.radius.max(1.0) / 2.0);
|
||||
let n = px.iter().filter(|q| q[3] > 0.0).count().max(1) as f64;
|
||||
// Match the checked path: narrow sums lose log-luminance samples on large scenes.
|
||||
let mean = (base.iter().zip(px.iter()).filter(|(_, q)| q[3] > 0.0).map(|(b, _)| f64::from(*b)).sum::<f64>() / n) as f32;
|
||||
let compress = 1.0 / (1.0 + p.strength.max(0.0));
|
||||
// Only visible pixels are toned, so only they set the anchor.
|
||||
let visible = || base.iter().zip(px.iter()).filter(|(_, q)| q[3] > 0.0).map(|(b, _)| *b);
|
||||
let (anchor_log, compress) = match anchor {
|
||||
// Fitted to the reference application's samples (#14723): Strength 0.5296 compresses the
|
||||
// base's log range to about 0.39 of its span.
|
||||
Anchor::White => (visible().fold(f32::NEG_INFINITY, f32::max), 1.0 / (1.0 + 3.0 * p.strength.max(0.0))),
|
||||
Anchor::Mean => {
|
||||
let n = visible().count().max(1) as f64;
|
||||
// Match the checked path: narrow sums lose log-luminance samples on large scenes.
|
||||
((visible().map(f64::from).sum::<f64>() / n) as f32, 1.0 / (1.0 + p.strength.max(0.0)))
|
||||
}
|
||||
};
|
||||
let detail = 1.0 + p.detail / 100.0;
|
||||
let exposure = 2f32.powf(p.exposure);
|
||||
let gamma = p.gamma.clamp(0.1, 4.0);
|
||||
@@ -283,11 +328,17 @@ pub fn hdr_toning(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning) {
|
||||
}
|
||||
let c = [q[0], q[1], q[2]];
|
||||
let l0 = luma(c).max(0.0) + EPS;
|
||||
let new_log = mean + (base[i] - mean) * compress + (logl[i] - base[i]) * detail;
|
||||
let new_log = match anchor {
|
||||
Anchor::White => ((base[i] - anchor_log) + (logl[i] - base[i]) * detail) * compress,
|
||||
Anchor::Mean => anchor_log + (base[i] - anchor_log) * compress + (logl[i] - base[i]) * detail,
|
||||
};
|
||||
// The contract is "lower = more contrast", i.e. gamma is the divisor of
|
||||
// the exponent, matching the crate's other gamma controls (hdr.rs, proof_sim.rs).
|
||||
let mut l1 = (new_log.exp() * exposure).max(0.0).powf(1.0 / gamma);
|
||||
l1 += p.shadow / 100.0 * (1.0 - l1).powi(3) * 0.5 - p.highlight / 100.0 * l1.powi(3) * 0.5;
|
||||
if !l1.is_finite() {
|
||||
l1 = wide_range_tone(new_log, p.exposure, gamma, p.shadow, p.highlight);
|
||||
}
|
||||
l1 = curve_eval(&sorted, l1.clamp(0.0, 1.0));
|
||||
let ratio = l1 / l0;
|
||||
let mut out = c.map(|v| v * ratio);
|
||||
@@ -383,3 +434,6 @@ mod tests {
|
||||
assert!(luma([px[2][0], px[2][1], px[2][2]]) > luma([px[38][0], px[38][1], px[38][2]]));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod hdr_toning_range_tests;
|
||||
@@ -166,19 +166,16 @@ pub fn process_with(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning, ctl:
|
||||
})?;
|
||||
let mut scratch = zeroes(w.max(h), 0f32, ctl)?;
|
||||
blur(&mut base, w, h, &mut scratch, p.radius / 2., ctl)?;
|
||||
// F32 loses successive log-luminance additions on ordinary megapixel images.
|
||||
let mut total = 0f64;
|
||||
let mut visible = 0usize;
|
||||
// The brightest base of the visible pixels becomes white (#14723).
|
||||
let mut white = f32::NEG_INFINITY;
|
||||
for (qs, bs) in px.chunks(2048).zip(base.chunks(2048)) {
|
||||
check(ctl)?;
|
||||
for (q, b) in qs.iter().zip(bs) {
|
||||
if q[3] > 0. {
|
||||
total += f64::from(*b);
|
||||
visible += 1;
|
||||
white = white.max(*b);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mean = (total / visible.max(1) as f64) as f32;
|
||||
let mut curve = zeroes(p.curve.len(), (0f32, 0f32), ctl)?;
|
||||
curve.copy_from_slice(&p.curve);
|
||||
// Stable bounded in-place insertion avoids slice::sort's infallible temporary allocation.
|
||||
@@ -190,7 +187,7 @@ pub fn process_with(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning, ctl:
|
||||
j -= 1;
|
||||
}
|
||||
}
|
||||
let compress = 1. / (1. + p.strength);
|
||||
let compress = 1. / (1. + 3. * p.strength);
|
||||
let detail = 1. + p.detail / 100.;
|
||||
let exposure = 2f32.powf(p.exposure);
|
||||
independent_chunks(px, |start, qs| {
|
||||
@@ -203,19 +200,13 @@ pub fn process_with(px: &mut [[f32; 4]], w: usize, h: usize, p: &HdrToning, ctl:
|
||||
}
|
||||
let c = [q[0], q[1], q[2]];
|
||||
let l0 = luma(c).max(0.) + 1e-4;
|
||||
let new_log = mean + (*b - mean) * compress + (*l - *b) * detail;
|
||||
let new_log = ((*b - white) + (*l - *b) * detail) * compress;
|
||||
let mut l1 = (new_log.exp() * exposure).max(0.).powf(1. / p.gamma);
|
||||
l1 += p.shadow / 100. * (1. - l1).powi(3) * 0.5 - p.highlight / 100. * l1.powi(3) * 0.5;
|
||||
if !l1.is_finite() {
|
||||
// Preserve ordinary native arithmetic, but evaluate extreme valid HDR in a
|
||||
// wider domain. A cap beyond every f32 control's polynomial crossover keeps
|
||||
// cubing finite; those values already saturate at the final display clamp.
|
||||
let log_value = (f64::from(new_log) + f64::from(p.exposure) * std::f64::consts::LN_2) / f64::from(p.gamma);
|
||||
let value = log_value.exp().min(1e100);
|
||||
let shadow = f64::from(p.shadow) / 200.;
|
||||
let highlight = f64::from(p.highlight) / 200.;
|
||||
let mapped = ((-(shadow + highlight) * value + 3. * shadow) * value + (1. - 3. * shadow)) * value + shadow;
|
||||
l1 = mapped.clamp(0., 1.) as f32;
|
||||
// wider domain.
|
||||
l1 = super::wide_range_tone(new_log, p.exposure, p.gamma, p.shadow, p.highlight);
|
||||
if !l1.is_finite() {
|
||||
return Err(Error::NonFiniteSample);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
//! #14723: HDR Toning's Local Adaptation stretches an ordinary image to the full range (white
|
||||
//! stays white, dark tones are lifted) instead of compressing it towards its mean, and keeps the
|
||||
//! order of the tones for every Radius and Strength.
|
||||
|
||||
use super::*;
|
||||
use crate::hdr::{MergeOptions, ToneMethod, merge, tone_map};
|
||||
use crate::photo_util::{linear_to_srgb, srgb_to_linear};
|
||||
|
||||
/// The reference application's factory Radius and Strength, passed explicitly so the samples
|
||||
/// don't depend on the defaults (#14720).
|
||||
fn reference(radius: f32, strength: f32) -> HdrToning {
|
||||
HdrToning { radius, strength, ..Default::default() }
|
||||
}
|
||||
|
||||
const RADIUS: f32 = 7.68;
|
||||
const STRENGTH: f32 = 0.5296;
|
||||
|
||||
/// A grey 8-bit level as a pixel.
|
||||
fn grey(v: u32) -> [f32; 4] {
|
||||
let v = v as f32 / 255.0;
|
||||
[v, v, v, 1.0]
|
||||
}
|
||||
|
||||
/// The issue's 512 x 256 document: a ramp (rows 0-63, column x is level x/2), eight flat grey
|
||||
/// patches (rows 64-127), a 40 | 200 step edge at x 256 (rows 128-191) and eight colour patches
|
||||
/// (rows 192-255).
|
||||
fn document() -> (Vec<[f32; 4]>, usize, usize) {
|
||||
const COLOURS: [[u32; 3]; 8] = [[60, 20, 20], [20, 60, 20], [40, 40, 90], [120, 60, 30], [200, 60, 60], [60, 200, 60], [220, 200, 120], [230, 180, 200]];
|
||||
let (w, h) = (512, 256);
|
||||
let px = (0..w * h)
|
||||
.map(|i| {
|
||||
let (x, y) = (i % w, i / w);
|
||||
match y {
|
||||
0..64 => grey(x as u32 / 2),
|
||||
64..128 => grey(PATCHES[x / 64]),
|
||||
128..192 => grey(if x < 256 { 40 } else { 200 }),
|
||||
_ => {
|
||||
let c = COLOURS[x / 64].map(|v| v as f32 / 255.0);
|
||||
[c[0], c[1], c[2], 1.0]
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
(px, w, h)
|
||||
}
|
||||
|
||||
const PATCHES: [u32; 8] = [0, 16, 48, 80, 128, 176, 224, 255];
|
||||
|
||||
/// The issue's dark 256 x 64 document: a ramp 0..63 at 4 px per level (rows 0-31) and a 30 | 90
|
||||
/// step edge at x 128 (rows 32-63).
|
||||
fn dark_document() -> (Vec<[f32; 4]>, usize, usize) {
|
||||
let (w, h) = (256, 64);
|
||||
let px = (0..w * h).map(|i| if i / w < 32 { grey((i % w) as u32 / 4) } else { grey(if i % w < 128 { 30 } else { 90 }) }).collect();
|
||||
(px, w, h)
|
||||
}
|
||||
|
||||
/// The grey level of pixel `(x, y)`.
|
||||
fn level(px: &[[f32; 4]], w: usize, x: usize, y: usize) -> f32 {
|
||||
let q = px[y * w + x];
|
||||
luma([q[0], q[1], q[2]]) * 255.0
|
||||
}
|
||||
|
||||
fn toned((mut px, w, h): (Vec<[f32; 4]>, usize, usize), p: &HdrToning) -> (Vec<[f32; 4]>, usize) {
|
||||
hdr_toning(&mut px, w, h, p);
|
||||
(px, w)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_image_is_stretched_to_white_with_its_dark_tones_lifted() {
|
||||
let (px, w) = toned(document(), &reference(RADIUS, STRENGTH));
|
||||
let patches = [0.0, 93.0, 131.0, 158.0, 191.0, 217.0, 240.0, 253.0];
|
||||
for (i, want) in patches.into_iter().enumerate() {
|
||||
let got = level(&px, w, i * 64 + 32, 96);
|
||||
assert!((got - want).abs() <= 12.0, "grey patch {}: {got:.1}, the reference gives {want}", PATCHES[i]);
|
||||
}
|
||||
for (v, want) in [(15, 91.0), (120, 186.0), (255, 254.0)] {
|
||||
let got = level(&px, w, 2 * v + 1, 32);
|
||||
assert!((got - want).abs() <= 12.0, "ramp {v}: {got:.1}, the reference gives {want}");
|
||||
}
|
||||
assert!(level(&px, w, 511, 32) > 240.0 && level(&px, w, 255 * 2, 96) > 240.0, "white stays white");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dark_image_is_stretched_to_fill_the_range() {
|
||||
let (px, w) = toned(dark_document(), &reference(RADIUS, STRENGTH));
|
||||
for (v, want) in [(8, 105.0), (56, 203.0)] {
|
||||
let got = level(&px, w, 4 * v + 2, 16);
|
||||
assert!((got - want).abs() <= 15.0, "ramp {v}: {got:.1}, the reference gives {want}");
|
||||
}
|
||||
for (x, v, want) in [(64, 30, 157.0), (192, 90, 253.0)] {
|
||||
let got = level(&px, w, x, 48);
|
||||
assert!((got - want).abs() <= 15.0, "edge {v}: {got:.1}, the reference gives {want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_darker_ramp_level_never_comes_out_brighter() {
|
||||
// The ramp alone, sampled every 15 levels: the blur at a large radius sees nothing else.
|
||||
// The issue's document at its three ramp samples: there the patches below the ramp fall
|
||||
// inside a large blur.
|
||||
let (w, h) = (512, 64);
|
||||
let ramp = (0..w * h).map(|i| grey((i % w) as u32 / 2)).collect::<Vec<_>>();
|
||||
for radius in [1.0, RADIUS, 100.0] {
|
||||
for strength in [0.1, 0.53, 4.0] {
|
||||
let (px, w) = toned((ramp.clone(), w, h), &reference(radius, strength));
|
||||
let samples: Vec<f32> = (1..=17).map(|k| level(&px, w, 2 * 15 * k + 1, 32)).collect();
|
||||
assert!(samples.windows(2).all(|p| p[0] <= p[1]), "ramp, radius {radius}, strength {strength}: levels 15, 30, .. 255 give {samples:?}");
|
||||
let (px, w) = toned(document(), &reference(radius, strength));
|
||||
let samples = [15, 120, 255].map(|v| level(&px, w, 2 * v + 1, 32));
|
||||
assert!(samples[0] <= samples[1] && samples[1] <= samples[2], "document, radius {radius}, strength {strength}: ramp 15/120/255 give {samples:?}");
|
||||
// The reference keeps the flat greys in order even at Radius 100 and Strength 4.
|
||||
let patches: Vec<f32> = (0..8).map(|i| level(&px, w, i * 64 + 32, 96)).collect();
|
||||
assert!(patches.windows(2).all(|p| p[0] <= p[1]), "document, radius {radius}, strength {strength}: grey patches give {patches:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_stays_black_and_results_stay_in_range_at_every_depth() {
|
||||
// 8- and 16-bit documents arrive as 0..1; a 32-bit one can hold values far above 1.
|
||||
let (doc, w, h) = document();
|
||||
let bright: Vec<[f32; 4]> = doc.iter().map(|q| [q[0] * 40.0, q[1] * 40.0, q[2] * 40.0, 1.0]).collect();
|
||||
for px in [doc, bright] {
|
||||
let (px, w) = toned((px, w, h), &reference(RADIUS, STRENGTH));
|
||||
assert!(px.iter().all(|q| q[..3].iter().all(|v| (0.0..=1.0).contains(v))), "every channel in 0..1");
|
||||
assert_eq!(level(&px, w, 32, 96), 0.0, "black stays 0");
|
||||
}
|
||||
}
|
||||
|
||||
/// A 4 x 1 strip of flat 64 x 64 areas with the given linear values, as Merge to HDR Pro hands
|
||||
/// its radiance to the tone map.
|
||||
fn strip(values: [f32; 4]) -> Vec<[f32; 4]> {
|
||||
(0..256 * 64)
|
||||
.map(|i| {
|
||||
let v = values[i % 256 / 64];
|
||||
[v, v, v, 1.0]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn this_tone_map_reaches_the_reference_merge_from_the_reference_radiance() {
|
||||
// The reference application's own 32-bit merge of #14023's scene (#14021): grey 128, ramp 26,
|
||||
// ramp 246 and the white patch. Its 16-bit Local Adaptation result of that merge (#14023):
|
||||
// 35725, 14858 and 63103. Merge to HDR Pro keys the scene to middle grey, tones it and encodes
|
||||
// it (`hdr::tone_map`); here with this tone map, which #14023 will move the merge to.
|
||||
let mut px = strip([0.0531, 0.00074, 1.130, 1.341]);
|
||||
let log_mean = (px.iter().map(|q| f64::from(luma([q[0], q[1], q[2]]).max(1e-6)).ln()).sum::<f64>() / px.len() as f64).exp() as f32;
|
||||
for q in &mut px {
|
||||
q[..3].iter_mut().for_each(|v| *v *= 0.18 / log_mean);
|
||||
}
|
||||
hdr_toning(&mut px, 256, 64, &reference(6.0, 0.53));
|
||||
for q in &mut px {
|
||||
q[..3].iter_mut().for_each(|v| *v = linear_to_srgb(v.clamp(0.0, 1.0)));
|
||||
}
|
||||
for (i, name, want) in [(0, "grey 128", 35725.0), (1, "ramp 26", 14858.0), (2, "ramp 246", 63103.0)] {
|
||||
let got = px[32 * 256 + i * 64 + 32][1] * 65535.0;
|
||||
assert!((got - want).abs() <= 0.08 * 65535.0, "{name}: {got:.0}, the reference gives {want}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_strong_local_contrast_at_a_low_gamma_stays_finite() {
|
||||
// A bright pixel between dark ones with Detail 300 and Gamma 0.1 tones far past f32 before the
|
||||
// shadow and highlight curve; the result is still a colour, and the checked replay agrees.
|
||||
let p = HdrToning {
|
||||
radius: 100.0,
|
||||
strength: 0.1,
|
||||
gamma: 0.1,
|
||||
exposure: 0.0,
|
||||
detail: 300.0,
|
||||
shadow: 0.0,
|
||||
highlight: 0.0,
|
||||
vibrance: 0.0,
|
||||
saturation: 0.0,
|
||||
curve: Vec::new(),
|
||||
};
|
||||
let input = vec![[0.01, 0.01, 0.01, 1.0], [0.9, 0.9, 0.9, 1.0], [0.01, 0.01, 0.01, 1.0]];
|
||||
let mut px = input.clone();
|
||||
hdr_toning(&mut px, 3, 1, &p);
|
||||
assert!(px.iter().all(|q| q.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v))), "{px:?}");
|
||||
let mut checked = input;
|
||||
checked_hdr::process_with(&mut checked, 3, 1, &p, &photocraft_raster::Interrupt::NONE).unwrap();
|
||||
assert!(px.iter().flatten().zip(checked.iter().flatten()).all(|(a, b)| (a - b).abs() < 1e-6), "{px:?} vs {checked:?}");
|
||||
}
|
||||
|
||||
/// #14023's scene: 300 x 200, a grey ramp in 10 px steps (rows 0-99, level round(x0 / 290 * 255)),
|
||||
/// a grey 128 band (rows 100-119) and red, green, blue, white and black 60 px patches (rows
|
||||
/// 120-179), shot at `ev` stops in 8 bits.
|
||||
fn hdr_scene_shot(ev: f32) -> Vec<[f32; 4]> {
|
||||
let (w, h) = (300, 200);
|
||||
(0..w * h)
|
||||
.map(|i| {
|
||||
let (x, y) = (i % w, i / w);
|
||||
let level = |v: f32| v / 255.0;
|
||||
let c = match y {
|
||||
0..100 => [level((((x / 10 * 10) as f32) / 290.0 * 255.0).round()); 3],
|
||||
100..120 => [level(128.0); 3],
|
||||
120..180 => [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 1.0, 1.0], [0.0, 0.0, 0.0]][x / 60],
|
||||
_ => [0.0; 3],
|
||||
};
|
||||
let shot = c.map(|v| (linear_to_srgb((srgb_to_linear(v) * 2f32.powf(ev)).clamp(0.0, 1.0)) * 255.0).round() / 255.0);
|
||||
[shot[0], shot[1], shot[2], 1.0]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_to_hdr_local_adaptation_gets_no_worse_on_todays_merge() {
|
||||
// Merge to HDR Pro keeps the mean-anchored tone map until #14023 moves it to the reference's
|
||||
// radiance (#14723): on today's merge of #14023's scene its worst sample stays within main's
|
||||
// 11530 levels of the reference at 16 bits (11435 here); the white-anchored map's is 17001.
|
||||
let (w, h) = (300, 200);
|
||||
let shots: Vec<Vec<[f32; 4]>> = [-2.0, 0.0, 2.0].map(hdr_scene_shot).into();
|
||||
let refs: Vec<&[[f32; 4]]> = shots.iter().map(Vec::as_slice).collect();
|
||||
let options = MergeOptions { exposures: vec![0.25, 1.0, 4.0], remove_ghosts: false, ghost_base: None, response: None };
|
||||
let mut px = merge(w, h, &refs, &options).px;
|
||||
let p = HdrToning { radius: 6.0, strength: 0.53, ..Default::default() };
|
||||
tone_map(&mut px, w, h, &ToneMethod::LocalAdaptation(p));
|
||||
// (x, y, the reference's 16-bit green) for ramp 0, 26, 62, 123, 185, 246, grey 128 and black.
|
||||
let samples = [
|
||||
(5, 50, 1538.0),
|
||||
(35, 50, 14858.0),
|
||||
(75, 50, 21840.0),
|
||||
(145, 50, 33663.0),
|
||||
(215, 50, 48003.0),
|
||||
(285, 50, 63103.0),
|
||||
(150, 110, 35725.0),
|
||||
(270, 150, 1538.0),
|
||||
];
|
||||
let error = |&(x, y, want): &(usize, usize, f32)| {
|
||||
let error = (px[y * w + x][1] * 65535.0 - want).abs();
|
||||
assert!(error.is_finite(), "({x}, {y}) is not a colour: {:?}", px[y * w + x]);
|
||||
error
|
||||
};
|
||||
let worst = samples.iter().map(error).fold(0.0, f32::max);
|
||||
assert!(worst <= 11530.0, "the worst sample is {worst:.0} levels off the reference");
|
||||
}
|
||||
@@ -5,6 +5,11 @@
|
||||
//! settings folder, and `photocraft-cli mcp` ([`crate::live`]) reads that file on every tool call,
|
||||
//! so MCP client configurations never hold a port or a token. Adding PhotoCraft to MCP clients is
|
||||
//! the ArtCraft Launcher's job (one entry for every Craft app).
|
||||
//!
|
||||
//! PhotoCraft's bridge uses challenge authentication: the listener proves it holds the token
|
||||
//! before the client sends its own proof, and the token itself is never sent. The connection's
|
||||
//! process id identifies the publisher and distinguishes restarts; it does not authenticate the
|
||||
//! listener. See [`crate::bridge::BridgeClient`] and `docs/control-protocol.md`.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
|
||||
@@ -72,7 +72,9 @@ pub fn platform_dir(env: &impl Fn(&str) -> Option<OsString>) -> Option<PathBuf>
|
||||
if cfg!(windows) {
|
||||
return env("APPDATA").filter(|a| !a.is_empty()).map(|a| PathBuf::from(a).join("Photocraft"));
|
||||
}
|
||||
env("XDG_CONFIG_HOME").filter(|x| !x.is_empty()).map(PathBuf::from).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft"))
|
||||
// XDG requires absolute paths. With Windows handled above, a root is sufficient,
|
||||
// including on wasm where is_absolute does not recognize rooted paths.
|
||||
env("XDG_CONFIG_HOME").map(PathBuf::from).filter(|x| x.has_root()).or_else(|| home.map(|h| h.join(".config"))).map(|c| c.join("photocraft"))
|
||||
}
|
||||
|
||||
/// The first portable marker file in `exe_dir`, if any.
|
||||
@@ -112,3 +114,64 @@ pub fn from_env() -> DataDir {
|
||||
let exe = std::env::current_exe().ok();
|
||||
resolve(|k| std::env::var_os(k), exe.as_deref().and_then(Path::parent))
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(windows), not(target_os = "macos")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn relative_xdg_config_home_is_ignored() {
|
||||
for xdg in ["relative/config", ".", "~/config"] {
|
||||
for (home, expected) in [(Some("/home/test"), Some("/home/test/.config/photocraft")), (None, None), (Some(""), None)] {
|
||||
let env = |key: &str| {
|
||||
match key {
|
||||
"HOME" => home,
|
||||
"XDG_CONFIG_HOME" => Some(xdg),
|
||||
_ => None,
|
||||
}
|
||||
.map(OsString::from)
|
||||
};
|
||||
assert_eq!(platform_dir(&env), expected.map(PathBuf::from), "HOME={home:?}, XDG_CONFIG_HOME={xdg:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_and_default_xdg_config_home_still_work() {
|
||||
for (xdg, home, expected) in [
|
||||
(Some("/config"), Some("/home/test"), Some("/config/photocraft")),
|
||||
(Some("/config"), None, Some("/config/photocraft")),
|
||||
(None, Some("/home/test"), Some("/home/test/.config/photocraft")),
|
||||
(Some(""), Some("/home/test"), Some("/home/test/.config/photocraft")),
|
||||
(None, None, None),
|
||||
(Some(""), None, None),
|
||||
] {
|
||||
let env = |key: &str| {
|
||||
match key {
|
||||
"HOME" => home,
|
||||
"XDG_CONFIG_HOME" => xdg,
|
||||
_ => None,
|
||||
}
|
||||
.map(OsString::from)
|
||||
};
|
||||
assert_eq!(platform_dir(&env), expected.map(PathBuf::from), "HOME={home:?}, XDG_CONFIG_HOME={xdg:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_config_override_still_accepts_relative_paths() {
|
||||
let env = |key: &str| {
|
||||
match key {
|
||||
"PHOTOCRAFT_CONFIG_DIR" => Some("custom/config"),
|
||||
"XDG_CONFIG_HOME" => Some("/config"),
|
||||
"HOME" => Some("/home/test"),
|
||||
_ => None,
|
||||
}
|
||||
.map(OsString::from)
|
||||
};
|
||||
let result = resolve(env, None);
|
||||
assert_eq!(result.dir, Some(PathBuf::from("custom/config")));
|
||||
assert_eq!(result.mode, Mode::Override);
|
||||
assert!(result.warning.is_none());
|
||||
}
|
||||
}
|
||||
@@ -146,7 +146,11 @@ pub fn save_with_renderer_keeping(
|
||||
.or_else(|| path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()))
|
||||
.ok_or_else(|| AutomationError::BadRequest(format!("cannot tell the format of `{}`; pass a format", path.display())))?;
|
||||
if ext == photocraft_format::EXTENSION {
|
||||
let named = named_for_output(doc, &path.to_string_lossy());
|
||||
let mut named = doc.clone();
|
||||
// Native filenames may contain a literal backslash on Unix.
|
||||
if let Some(name) = path.file_name() {
|
||||
named.name = name.to_string_lossy().into_owned();
|
||||
}
|
||||
let mut local = PcraftWriter::new();
|
||||
let w = writer.unwrap_or(&mut local);
|
||||
w.save_path(&named, path, &native_options(&named, opts)?)?;
|
||||
|
||||
@@ -441,9 +441,7 @@ impl Headless {
|
||||
if ext.as_deref().is_some_and(|e| file_cmds::holds(&doc, e)) {
|
||||
// Saving by index must not retarget the next automation command.
|
||||
self.on_doc(Some(i), |this| {
|
||||
if let Some(st) = this.session.active_mut() {
|
||||
st.saved_to(target.to_string_lossy().into_owned());
|
||||
}
|
||||
this.session.saved_to(target.to_string_lossy().into_owned());
|
||||
// History Options › Automatically Create New Snapshot When Saving (#2966).
|
||||
photocraft_engine::history_options_cmds::snapshot_on_save(&mut this.session);
|
||||
Ok(())
|
||||
|
||||
@@ -167,6 +167,15 @@ impl Headless {
|
||||
}
|
||||
"doc.new" => self.command_run("file.new", p),
|
||||
"doc.save" => {
|
||||
// A malformed Save As request must not become an implicit save to the stored path.
|
||||
if !p.is_object() {
|
||||
return Err(bad("doc.save params must be an object"));
|
||||
}
|
||||
for key in ["path", "format"] {
|
||||
if p.get(key).is_some_and(|value| !value.is_null() && !value.is_string()) {
|
||||
return Err(bad(format!("`{key}` must be a string")));
|
||||
}
|
||||
}
|
||||
let tga_bits = photocraft_engine::file_cmds::tga_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?;
|
||||
let pdf_spot_plates = photocraft_engine::file_cmds::pdf_spot_plates_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?;
|
||||
let mut opts = photocraft_io::ExportOptions {
|
||||
@@ -223,6 +232,15 @@ impl Headless {
|
||||
}
|
||||
"doc.inspect" => self.inspect(index_of(&p)?),
|
||||
"doc.render" => {
|
||||
// Invalid file requests must not fall back to a base64 response.
|
||||
if !p.is_object() {
|
||||
return Err(bad("doc.render params must be an object"));
|
||||
}
|
||||
let path = match p.get("path") {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(Value::String(path)) => Some(path.as_str()),
|
||||
Some(_) => return Err(bad("`path` must be a string")),
|
||||
};
|
||||
let max = match p.get("maxSide") {
|
||||
None => 1024,
|
||||
Some(value) => {
|
||||
@@ -232,7 +250,7 @@ impl Headless {
|
||||
let png = self.render_png(index_of(&p)?, max)?;
|
||||
// A GPU to CPU fallback is reported with this reply, not on the next save.
|
||||
let warnings = self.drain_diagnostics();
|
||||
let mut reply = match str_of(&p, "path") {
|
||||
let mut reply = match path {
|
||||
Some(path) => {
|
||||
self.write_render(&PathBuf::from(path), &png)?;
|
||||
json!({"path": path, "bytes": png.len()})
|
||||
@@ -253,7 +271,13 @@ impl Headless {
|
||||
let i = index_of(&p)?.ok_or_else(|| bad("doc.select needs `index`"))?;
|
||||
self.select(i)
|
||||
}
|
||||
"doc.close" => self.close(index_of(&p)?),
|
||||
"doc.close" => {
|
||||
// A non-object would look like a missing index and close the active document.
|
||||
if !p.is_object() {
|
||||
return Err(bad("doc.close params must be an object"));
|
||||
}
|
||||
self.close(index_of(&p)?)
|
||||
}
|
||||
"batch" => self.batch(&p),
|
||||
"methods" => Ok(json!(METHODS)),
|
||||
other => Err(bad(format!("{} (try `methods`)", photocraft_engine::command_hints::unknown_method(other, METHODS)))),
|
||||
|
||||
@@ -176,6 +176,32 @@ fn batch_rejects_too_many_steps() {
|
||||
assert!(error.to_string().contains("maximum is 256"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_rejects_malformed_requests_and_keeps_missing_or_null_path_behavior() {
|
||||
let h = session();
|
||||
let mut g = h.lock().unwrap();
|
||||
g.handle("doc.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
let before = g.inspect(None).unwrap();
|
||||
for params in [json!([]), json!([0]), json!(123), json!(false), json!("out.png")] {
|
||||
let error = g.handle("doc.render", params.clone()).unwrap_err();
|
||||
assert!(matches!(&error, AutomationError::BadRequest(_)), "{params}: {error}");
|
||||
assert!(error.to_string().contains("doc.render params must be an object"), "{params}: {error}");
|
||||
assert_eq!(g.inspect(None).unwrap(), before, "invalid params {params} changed the document");
|
||||
}
|
||||
for path in [json!(123), json!(false), json!([]), json!({})] {
|
||||
let error = g.handle("doc.render", json!({"path": path})).unwrap_err();
|
||||
assert!(matches!(&error, AutomationError::BadRequest(_)), "{path}: {error}");
|
||||
assert!(error.to_string().contains("`path` must be a string"), "{path}: {error}");
|
||||
assert_eq!(g.inspect(None).unwrap(), before, "invalid path {path} changed the document");
|
||||
}
|
||||
for params in [Value::Null, json!({}), json!({"path": null})] {
|
||||
let reply = g.handle("doc.render", params.clone()).unwrap();
|
||||
assert_eq!(reply["mime"], "image/png", "{params}: {reply}");
|
||||
let png = base64::engine::general_purpose::STANDARD.decode(reply["base64"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(photocraft_codecs::decode(&png).unwrap().dimensions(), (8, 8));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_to_file_and_base64() {
|
||||
let h = session();
|
||||
@@ -598,9 +624,12 @@ fn doc_export_layers_writes_only_beneath_the_write_root() {
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap());
|
||||
h.handle("doc.new", json!({"width": 12, "height": 8, "background": "white", "name": "card"})).unwrap();
|
||||
h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Badge"}})).unwrap();
|
||||
|
||||
let out = root.join("out");
|
||||
let refused = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(refused.contains("Layers to Files needs a document with multiple layers."), "{refused}");
|
||||
assert!(!out.exists() || std::fs::read_dir(&out).unwrap().next().is_none(), "the refusal wrote no files");
|
||||
|
||||
h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Badge"}})).unwrap();
|
||||
let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": "png", "prefix": "card"})).unwrap();
|
||||
assert_eq!(exported["count"].as_u64(), Some(2), "{exported}");
|
||||
let mut names: Vec<String> = std::fs::read_dir(&out).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
||||
@@ -1186,3 +1215,85 @@ fn doc_place_forwards_high_memory_approval() {
|
||||
drop(t);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_save_rejects_malformed_requests_without_writing_the_stored_path() {
|
||||
let dir = std::env::temp_dir().join(format!("pc-rpc-save-path-{}", std::process::id()));
|
||||
std::fs::create_dir(&dir).unwrap();
|
||||
let workspace = crate::AuthorizedWorkspace::new(Some(&dir), Some(&dir)).unwrap();
|
||||
let mut h = Headless::with_workspace(workspace);
|
||||
h.handle("doc.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
h.handle("doc.save", json!({"path": "saved.pcraft"})).unwrap();
|
||||
let path = dir.join("saved.pcraft");
|
||||
let original = std::fs::read(&path).unwrap();
|
||||
h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Unsaved"}})).unwrap();
|
||||
let unsaved = h.inspect(None).unwrap();
|
||||
|
||||
for field in ["path", "format"] {
|
||||
for value in [json!(123), json!(false), json!([]), json!({})] {
|
||||
let mut params = json!({});
|
||||
params[field] = value.clone();
|
||||
let error = h.handle("doc.save", params).unwrap_err().to_string();
|
||||
assert!(error.contains(field), "{field} {value}: {error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), original, "invalid {field} {value} wrote the stored file");
|
||||
assert_eq!(h.inspect(None).unwrap(), unsaved, "invalid {field} {value} changed the document");
|
||||
}
|
||||
}
|
||||
for params in [json!(123), json!(false), json!([]), json!("saved.pcraft")] {
|
||||
let error = h.handle("doc.save", params.clone()).unwrap_err().to_string();
|
||||
assert!(error.contains("object"), "{params}: {error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), original, "invalid params {params} wrote the stored file");
|
||||
assert_eq!(h.inspect(None).unwrap(), unsaved, "invalid params {params} changed the document");
|
||||
}
|
||||
|
||||
let mut previous = original;
|
||||
for params in [json!({}), json!({"path": null}), json!({"format": null}), Value::Null] {
|
||||
h.handle("engine.execute", json!({"command": "layer.new.layer"})).unwrap();
|
||||
let saved = h.handle("doc.save", params).unwrap();
|
||||
assert_eq!(saved["path"], "saved.pcraft");
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
assert_ne!(bytes, previous, "an implicit save did not write the edited document");
|
||||
previous = bytes;
|
||||
}
|
||||
let saved = h.handle("doc.save", json!({"path": "copy.pcraft", "format": "pcraft"})).unwrap();
|
||||
assert_eq!(saved["path"], "copy.pcraft");
|
||||
assert!(dir.join("copy.pcraft").is_file());
|
||||
drop(h);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doc_close_rejects_non_object_params_without_closing_documents() {
|
||||
let h = session();
|
||||
for _ in 0..2 {
|
||||
assert_eq!(respond(&h, r#"{"method":"doc.new","params":{"width":8,"height":8}}"#)["ok"], true);
|
||||
}
|
||||
let before = h.lock().unwrap().session_list();
|
||||
for params in [json!([]), json!([0]), json!(true), json!(false), json!(1), json!("0")] {
|
||||
let reply = respond(&h, &json!({"method": "doc.close", "params": params}).to_string());
|
||||
assert_eq!(reply["ok"], false, "{params}: {reply}");
|
||||
assert!(reply["error"].as_str().unwrap().contains("doc.close params must be an object"), "{reply}");
|
||||
assert_eq!(h.lock().unwrap().session_list(), before, "invalid params {params} changed the session");
|
||||
}
|
||||
|
||||
// Missing/null params and indices close the active document; an explicit index selects its target.
|
||||
for (params, remaining_index) in
|
||||
[(None, 0), (Some(Value::Null), 0), (Some(json!({})), 0), (Some(json!({"index": null})), 0), (Some(json!({"index": 0})), 1)]
|
||||
{
|
||||
let h = session();
|
||||
for width in [8, 16] {
|
||||
let request = json!({"method": "doc.new", "params": {"width": width, "height": 8}});
|
||||
assert_eq!(respond(&h, &request.to_string())["ok"], true);
|
||||
}
|
||||
let mut expected = h.lock().unwrap().session_list()["documents"][remaining_index].clone();
|
||||
expected["index"] = json!(0);
|
||||
let mut request = json!({"method": "doc.close"});
|
||||
if let Some(params) = params {
|
||||
request["params"] = params;
|
||||
}
|
||||
let reply = respond(&h, &request.to_string());
|
||||
assert_eq!(reply["ok"], true, "{request}: {reply}");
|
||||
assert_eq!(reply["result"]["documents"], json!([expected]), "{request}: {reply}");
|
||||
assert_eq!(reply["result"]["active"], 0, "{reply}");
|
||||
}
|
||||
}
|
||||
@@ -392,7 +392,8 @@ pub struct UiSetParams {
|
||||
/// combine, subtract, intersect or exclude: how the next Pen path joins the selected shape
|
||||
/// layer or path), shapeStroke (an object patching width, align, cap, join, miterLimit,
|
||||
/// dashes, dashOffset and opacity; null disables the stroke). Shape stroke fields use
|
||||
/// `shape.edit` names and units; colour comes from `tools.setColors`. frameShape (rectangle,
|
||||
/// `shape.edit` names and units; colour comes from `tools.setColors`. useAlignedRendering
|
||||
/// (boolean, the shape and Pen tools' Align Edges preference). frameShape (rectangle,
|
||||
/// ellipse, triangle, polygon or custom: the Frame tool's shape), frameSides (3..100, the
|
||||
/// polygon's sides), frameTarget (frame, content or both: what the selected frame's handles
|
||||
/// edit). camTransformOnDrop (bool,
|
||||
@@ -1580,14 +1581,29 @@ mod tests {
|
||||
let before = mcp.headless_op(|h| h.inspect(None)).await.unwrap().unwrap();
|
||||
let Backend::Headless(session) = &*mcp.backend else { panic!("headless") };
|
||||
let session = session.clone();
|
||||
// A call holds clones of the session until it returns. A waited start holds exactly three
|
||||
// once its blocking closure is queued on `spawn_blocking` (from where it can only wait for
|
||||
// the lock): `step`'s, `headless_wait`'s target, and `headless_op`'s, taken last, right
|
||||
// before the closure is queued. The wait below matches that count exactly, so a call path
|
||||
// that takes one more clone times out here instead of letting the test go on with only
|
||||
// one start queued.
|
||||
let idle = Arc::strong_count(&session);
|
||||
let held = session.clone();
|
||||
let (locked, acquired) = std::sync::mpsc::channel();
|
||||
let (release, released) = std::sync::mpsc::channel();
|
||||
let holder = std::thread::spawn(move || {
|
||||
let _held = session.lock().unwrap();
|
||||
let _held = held.lock().unwrap();
|
||||
locked.send(()).unwrap();
|
||||
released.recv().unwrap();
|
||||
});
|
||||
acquired.recv().unwrap();
|
||||
async fn until(what: &str, done: impl Fn() -> bool) {
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
|
||||
while !done() {
|
||||
assert!(std::time::Instant::now() < deadline, "timed out waiting until {what}");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
let (mut input, server_in) = tokio::io::duplex(65536);
|
||||
let (server_out, output) = tokio::io::duplex(65536);
|
||||
@@ -1606,7 +1622,8 @@ mod tests {
|
||||
)
|
||||
.await;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
// The holder's clone, and three for each start.
|
||||
until("both starts are queued", || Arc::strong_count(&session) == idle + 1 + 2 * 3).await;
|
||||
for id in [2, 3] {
|
||||
send(&mut input, json!({"jsonrpc":"2.0", "method":"notifications/cancelled", "params":{"requestId":id}})).await;
|
||||
}
|
||||
@@ -1619,8 +1636,9 @@ mod tests {
|
||||
}
|
||||
release.send(()).unwrap();
|
||||
holder.join().unwrap();
|
||||
// Let both blocked starts acquire the mutex before inspecting their effects.
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
// Both blocked starts took the lock and returned (their replies are dropped, as cancelled)
|
||||
// before their effects are inspected.
|
||||
until("both starts returned", || Arc::strong_count(&session) == idle).await;
|
||||
let (after, jobs) = mcp.headless_op(|h| Ok((h.inspect(None)?, h.session.jobs_with_recent()))).await.unwrap().unwrap();
|
||||
assert_eq!(after, before);
|
||||
assert!(jobs.is_empty(), "cancelled queued job started: {jobs:?}");
|
||||
|
||||
@@ -103,6 +103,18 @@ impl AuthorizedWorkspace {
|
||||
Ok((bytes, save_path))
|
||||
}
|
||||
|
||||
/// Where the file or `.pcraft` folder that `path` names is on disk: below the first read
|
||||
/// root that holds it (the root `read` and `open_pcraft` pick), as that root was configured
|
||||
/// at launch. Open Recent lists this, since the person reopens the file outside automation,
|
||||
/// where a root-relative request path names nothing. It grants no access.
|
||||
pub fn location(&self, path: &str) -> Option<PathBuf> {
|
||||
self.read.iter().find_map(|root| {
|
||||
let relative = scoped_path(path, root).ok()??;
|
||||
root.dir.metadata(&relative).ok()?;
|
||||
Some(root.configured_path.join(relative))
|
||||
})
|
||||
}
|
||||
|
||||
fn open_read(&self, path: &str) -> Result<(cap_std::fs::File, &RootCapability), AutomationError> {
|
||||
if self.read.is_empty() {
|
||||
return Err(AutomationError::BadRequest(format!("{DENIED}: read authority is absent")));
|
||||
@@ -276,7 +288,7 @@ fn holds_image(dir: &Dir, relative: &Path) -> bool {
|
||||
let Ok(mut file) = dir.open(relative) else { return false };
|
||||
let Ok(n) = file.read(&mut head) else { return false };
|
||||
let head = &head[..n];
|
||||
head.starts_with(b"8BPS") || photocraft_codecs::detect(head).is_some_and(|format| format.caps().write)
|
||||
photocraft_io::is_psd(head) || photocraft_codecs::detect(head).is_some_and(|format| format.caps().write)
|
||||
}
|
||||
|
||||
fn read_to_observed_length(reader: &mut impl Read, observed_length: u64) -> Result<Vec<u8>, AutomationError> {
|
||||
|
||||
@@ -64,6 +64,25 @@ fn read_growth_is_rejected_at_the_observed_length() {
|
||||
assert!(read_to_observed_length(&mut empty, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn location_names_the_file_below_the_root_that_holds_it() {
|
||||
let (library, work, _) = roots("location");
|
||||
std::fs::create_dir_all(work.join("shots")).unwrap();
|
||||
std::fs::write(work.join("shots/a.png"), b"a").unwrap();
|
||||
std::fs::write(library.join("same.png"), b"first").unwrap();
|
||||
std::fs::write(work.join("same.png"), b"second").unwrap();
|
||||
let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap();
|
||||
// A root-relative request names the file below the root that holds it, as an absolute path.
|
||||
assert_eq!(workspace.location("shots/a.png"), Some(work.join("shots").join("a.png")));
|
||||
// The first root that holds the name wins, as for `read`.
|
||||
assert_eq!(workspace.location("same.png"), Some(library.join("same.png")));
|
||||
// An absolute request below a root keeps naming that file.
|
||||
assert_eq!(workspace.location(&work.join("same.png").to_string_lossy()), Some(work.join("same.png")));
|
||||
assert_eq!(workspace.location("missing.png"), None);
|
||||
assert_eq!(workspace.location("../outside.png"), None, "a path escaping the roots has no location");
|
||||
assert_eq!(AuthorizedWorkspace::default().location("shots/a.png"), None, "no read root, no location");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_pcraft_loads_a_directory_below_the_read_root() {
|
||||
let (inside, _, workspace) = roots("pcraft-dir");
|
||||
@@ -1050,6 +1069,7 @@ fn documents_filesystem_path_params(id: &str, params: &str) -> bool {
|
||||
| "path.addAnchor"
|
||||
| "path.deleteAnchor"
|
||||
| "path.deleteSegment"
|
||||
| "path.deleteComponents"
|
||||
| "path.mergeShapeComponents"
|
||||
| "path.setOperation"
|
||||
| "path.clippingPath.set"
|
||||
@@ -1064,6 +1084,7 @@ fn documents_filesystem_path_params(id: &str, params: &str) -> bool {
|
||||
| "layer.vectorMask.add"
|
||||
| "layer.vectorMask.edit"
|
||||
| "layer.vectorMask.info"
|
||||
| "layer.vectorMask.currentPath"
|
||||
| "paint.symmetryFromPath"
|
||||
| "edit.defineCustomShape"
|
||||
// `"as":"path"` pastes the clipboard as a vector path (#10694).
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Each task uses only MCP tools (`doc_*`, `command_run`) the way an agent would, and checks the
|
||||
//! outcome through `doc_inspect`, `document.pixel` or the exported files, never engine internals.
|
||||
|
||||
use photocraft_engine::actions_cmds::ActionsExt;
|
||||
use std::io::Write;
|
||||
|
||||
use photocraft_automation::{AuthorizedWorkspace, PhotocraftMcp};
|
||||
@@ -330,7 +331,7 @@ async fn agent_play_refuses_a_recorded_file_open() {
|
||||
use photocraft_engine::actions_cmds::ActionStep;
|
||||
headless
|
||||
.session
|
||||
.actions
|
||||
.actions_mut()
|
||||
.list
|
||||
.push(photocraft_engine::actions_cmds::Action {
|
||||
name: "Open".into(),
|
||||
|
||||
@@ -13,6 +13,7 @@ mod gpu_tests {
|
||||
|
||||
use photocraft_automation::workspace::AuthorizedWorkspace;
|
||||
use photocraft_automation::{GpuRenderer, Headless};
|
||||
use photocraft_engine::color_cmds::ColorExt;
|
||||
|
||||
fn make_test_doc(w: u32, h: u32, depth: SampleType) -> Document {
|
||||
let mut doc = Document::with_background("test_doc", Size::new(w, h), ColorMode::Rgb, depth, Color::WHITE);
|
||||
|
||||
@@ -546,16 +546,21 @@ async fn headless_doc_save_takes_maximize_compatibility() {
|
||||
async fn headless_doc_export_layers_takes_maximize_compatibility() {
|
||||
let dir = tmp("export-layers-maximize-compat");
|
||||
let client = connect(headless_in(&dir)).await;
|
||||
call(&client, "doc_new", json!({"width": 16, "height": 16, "background": "white", "name": "card"})).await;
|
||||
json_of(&call(&client, "doc_new", json!({"width": 16, "height": 16, "background": "white", "name": "card"})).await);
|
||||
json_of(&call(&client, "command_run", json!({"id": "layer.new.layer", "params": {"name": "Ink"}})).await);
|
||||
for (sub, params, real) in
|
||||
[("on", json!({"dir": "on", "format": "psd"}), true), ("off", json!({"dir": "off", "format": "psd", "maximizeCompatibility": false}), false)]
|
||||
{
|
||||
let result = json_of(&call(&client, "doc_export_layers", params.clone()).await);
|
||||
assert_eq!(result["count"], 1, "{params}: {result}");
|
||||
let file = result["files"][0].as_str().unwrap();
|
||||
assert!(file.starts_with(sub), "{file}");
|
||||
let bytes = std::fs::read(dir.join(file)).unwrap();
|
||||
assert_eq!(craft_psd::PsdFile::from_bytes(&bytes).unwrap().has_real_merged_data(), Some(real), "{params}");
|
||||
assert_eq!(result["count"], 2, "{params}: {result}");
|
||||
let files = result["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), 2, "{params}: {result}");
|
||||
for file in files {
|
||||
let file = file.as_str().unwrap();
|
||||
assert!(file.starts_with(sub), "{file}");
|
||||
let bytes = std::fs::read(dir.join(file)).unwrap();
|
||||
assert_eq!(craft_psd::PsdFile::from_bytes(&bytes).unwrap().has_real_merged_data(), Some(real), "{params}: {file}");
|
||||
}
|
||||
}
|
||||
let r = call(&client, "doc_export_layers", json!({"dir": "bad", "format": "psd", "maximizeCompatibility": "no"})).await;
|
||||
assert_eq!(r.is_error, Some(true), "{}", text(&r));
|
||||
@@ -924,10 +929,18 @@ async fn doc_exports_and_data_set_import_are_capability_scoped() {
|
||||
.await,
|
||||
);
|
||||
|
||||
let layers = call(&client, "doc_export_layers", json!({"dir": "layers", "prefix": "card"})).await;
|
||||
let params = json!({"dir": "layers", "prefix": "card"});
|
||||
let refused = call(&client, "doc_export_layers", params.clone()).await;
|
||||
assert_eq!(refused.is_error, Some(true), "{}", text(&refused));
|
||||
assert!(text(&refused).contains("Layers to Files needs a document with multiple layers."), "{}", text(&refused));
|
||||
let layers_dir = root.join("layers");
|
||||
assert!(!layers_dir.exists() || std::fs::read_dir(&layers_dir).unwrap().next().is_none());
|
||||
|
||||
json_of(&call(&client, "command_run", json!({"id": "layer.new.layer", "params": {"name": "Ink"}})).await);
|
||||
let layers = call(&client, "doc_export_layers", params).await;
|
||||
assert_ne!(layers.is_error, Some(true), "{}", text(&layers));
|
||||
assert_eq!(json_of(&layers)["count"], 1, "{}", text(&layers));
|
||||
assert_eq!(std::fs::read_dir(root.join("layers")).unwrap().count(), 1);
|
||||
assert_eq!(json_of(&layers)["count"], 2, "{}", text(&layers));
|
||||
assert_eq!(std::fs::read_dir(layers_dir).unwrap().count(), 2);
|
||||
let sets = call(&client, "doc_export_data_sets", json!({"dir": "sets", "format": "png"})).await;
|
||||
assert_ne!(sets.is_error, Some(true), "{}", text(&sets));
|
||||
assert_eq!(json_of(&sets)["count"], 2, "{}", text(&sets));
|
||||
|
||||
@@ -149,7 +149,11 @@ async fn a_waited_command_reports_progress_serves_other_calls_and_cancels_cleanl
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cancelling_a_batch_cancels_its_waited_step_and_runs_no_later_step() {
|
||||
let mut wire = Wire::start(PhotocraftMcp::headless()).await;
|
||||
let session = Arc::new(Mutex::new(photocraft_automation::headless::Headless::new()));
|
||||
let mut wire = Wire::start(PhotocraftMcp::with_backend(Backend::Headless(session.clone()))).await;
|
||||
// Every call holds a clone of the session until it returns, and a batch holds one for its
|
||||
// whole run (the target it pinned), so the count is back here once no call is running.
|
||||
let idle = Arc::strong_count(&session);
|
||||
wire.big_document().await;
|
||||
let before = wire.history(4).await;
|
||||
|
||||
@@ -158,8 +162,13 @@ async fn cancelling_a_batch_cancels_its_waited_step_and_runs_no_later_step() {
|
||||
assert!(wire.first_progress(5, "batch", 2.0).await < 1.0, "still in the first step");
|
||||
wire.cancel(5).await;
|
||||
wire.settle(6, 5).await;
|
||||
// Give a (wrongly) continuing batch time to start its next step.
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
// The cancelled batch never answers, so its end is not visible on the wire: wait until it
|
||||
// has returned, after which a (wrongly) continuing batch has run its next step.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while Arc::strong_count(&session) != idle {
|
||||
assert!(Instant::now() < deadline, "the cancelled batch never returned");
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
assert_eq!(wire.history(1000).await, before, "neither the blur nor the later step ran");
|
||||
wire.finish().await;
|
||||
}
|
||||
|
||||
@@ -38,3 +38,28 @@ fn workspace_encoded_native_bundle_uses_requested_name_without_mutating_source()
|
||||
assert_eq!(reopened.name, "Renamed.pcraft");
|
||||
assert_eq!(doc.name, "Original", "a copy should not retarget the open document");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn native_save_preserves_backslashes_in_the_written_filename() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"pc-native-backslash-name-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let filename = r"Renamed\Copy.pcraft";
|
||||
let path = dir.join(filename);
|
||||
let mut headless = Headless::trusted_local();
|
||||
headless.handle("doc.new", json!({"width": 8, "height": 8, "name": "Original"})).unwrap();
|
||||
let doc = &headless.session.active().unwrap().doc;
|
||||
|
||||
files::save(doc, &path, None, &Default::default(), None).unwrap();
|
||||
|
||||
let manifest = photocraft_format::read_manifest(&std::fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!(manifest.document.name, filename);
|
||||
assert_eq!(files::open(&path).unwrap().document.name, filename);
|
||||
assert_eq!(doc.name, "Original", "saving a snapshot must not rename the source");
|
||||
drop(headless);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
Loaded 100 of 1707 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user