diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 0000000..96cbffd --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "microsoft.sbom.dotnettool": { + "version": "4.1.5", + "commands": [ + "sbom-tool" + ], + "rollForward": false + } + } +} diff --git a/.editorconfig b/.editorconfig index 3ab69c4..118f889 100644 --- a/.editorconfig +++ b/.editorconfig @@ -40,18 +40,3 @@ dotnet_diagnostic.CA1062.severity = none [src/Snaply.App/App.xaml.cs] dotnet_diagnostic.CA1515.severity = none - -[src/Snaply.App/MainWindow.xaml.cs] -dotnet_diagnostic.CA1515.severity = none - -[src/Snaply.App/MainPage.xaml.cs] -dotnet_diagnostic.CA1515.severity = none - -[src/Snaply.App/ViewModels/MainViewModel.cs] -dotnet_diagnostic.CA1031.severity = none - -[src/Snaply.App/ImageExportService.cs] -dotnet_diagnostic.CA1849.severity = none - -[src/Snaply.App/ScreenCaptureService.cs] -dotnet_diagnostic.CA2000.severity = none diff --git a/.github/dependabot.yml b/.github/dependabot.yml index efcbb7b..d6d9f19 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -33,6 +33,17 @@ updates: commit-message: prefix: build + - package-ecosystem: nuget + directory: /tests/Snaply.App.Tests + schedule: + interval: weekly + day: monday + groups: + app-tests: + patterns: ["*"] + commit-message: + prefix: build + - package-ecosystem: github-actions directory: / schedule: diff --git a/.github/rulesets/protect-default-branch.json b/.github/rulesets/protect-default-branch.json index a81701f..5c3b85a 100644 --- a/.github/rulesets/protect-default-branch.json +++ b/.github/rulesets/protect-default-branch.json @@ -31,9 +31,7 @@ "strict_required_status_checks_policy": true, "do_not_enforce_on_create": false, "required_status_checks": [ - { "context": "hygiene" }, - { "context": "quality" }, - { "context": "packaging" }, + { "context": "ci-required" }, { "context": "dependency-review" }, { "context": "analyze" }, { "context": "analyze-actions" } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 659c4a5..af4cdcf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: raven-actions/actionlint@3d39aea434753780c3b3d4a1a31c854b4dbf49d7 # v2.2.0 - uses: crate-ci/typos@bee27e3a4fd1ea2111cf90ab89cd076c870fce14 # v1.47.2 + - uses: fsfe/reuse-action@772649cfa03a64a08c458c7cca9a6a473d74e7f9 # v6 - name: Reject incomplete implementation markers shell: bash run: | @@ -36,7 +37,7 @@ jobs: quality: runs-on: windows-latest - timeout-minutes: 35 + timeout-minutes: 60 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 @@ -44,54 +45,9 @@ jobs: global-json-file: global.json cache: true cache-dependency-path: "**/packages.lock.json" - - name: Restore locked dependencies - run: dotnet restore Snaply.slnx --locked-mode - # Clear PathMap for this coverage build only: CI's PathMap (/_/) otherwise breaks - # coverlet's source resolution and makes it report 0% line coverage. - - name: Test imaging - run: >- - dotnet test tests/Snaply.Tests/Snaply.Tests.csproj - -c Release --no-restore - -p:PathMap= - --collect:"XPlat Code Coverage" - --logger "trx;LogFileName=results.trx" - --results-directory artifacts/test - - name: Test filesystem workflows - run: >- - dotnet test tests/Snaply.App.Tests/Snaply.App.Tests.csproj - -c Release --no-restore - --logger "trx;LogFileName=results.trx" - --results-directory artifacts/app-test - - name: Reject skipped tests and low coverage + - name: Verify source, tests, coverage, and portable publishes shell: pwsh - run: | - [xml]$trx = Get-Content artifacts/test/results.trx -Raw - if ([int]$trx.TestRun.ResultSummary.Counters.notExecuted -ne 0) { - throw "Required tests were skipped." - } - [xml]$coverage = Get-Content ( - Get-ChildItem artifacts/test -Recurse -Filter coverage.cobertura.xml | - Select-Object -First 1 - ).FullName -Raw - if ([double]$coverage.coverage.'line-rate' -lt 0.85) { - throw "Line coverage is below 85%." - } - [xml]$appTrx = Get-Content artifacts/app-test/results.trx -Raw - if ([int]$appTrx.TestRun.ResultSummary.Counters.notExecuted -ne 0) { - throw "Required filesystem tests were skipped." - } - - name: Build x64 - run: >- - dotnet build src/Snaply.App/Snaply.App.csproj - -c Release -p:Platform=x64 --no-restore - - name: Build ARM64 - run: >- - dotnet build src/Snaply.App/Snaply.App.csproj - -c Release -p:Platform=ARM64 --no-restore - - name: Verify formatting - env: - Configuration: Release - run: dotnet format Snaply.slnx --verify-no-changes --no-restore + run: ./scripts/verify.ps1 packaging: runs-on: windows-latest @@ -100,18 +56,23 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: + dotnet-version: 8.0.x global-json-file: global.json cache: true cache-dependency-path: "**/packages.lock.json" - name: Build and validate unsigned release payloads shell: pwsh run: | - [xml]$props = Get-Content Directory.Build.props -Raw + $version = (Get-Content version.txt -Raw).Trim() ./scripts/release.ps1 ` -Action Build ` - -Version "$($props.Project.PropertyGroup.Version)" ` + -Version $version ` -Publisher CN=Snaply ` -OutputRoot build/package-smoke + ./scripts/release.ps1 ` + -Action Package ` + -Version $version ` + -OutputRoot build/package-smoke # Aggregate gate the branch protection requires (context "ci-required"): green only # when every CI job above succeeded. Keeps the required-checks list stable as jobs change. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index b290313..b768b1f 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -43,10 +43,17 @@ jobs: version: v0.3.1 # Restore with ReadyToRun on so the crossgen2 runtime pack is fetched here; the # publish below runs --no-restore, so without it R2R fails (NETSDK1094). - - run: dotnet restore Snaply.slnx --locked-mode -p:PublishReadyToRun=true + - run: >- + dotnet restore Snaply.slnx + --locked-mode + -p:Platform=${{ matrix.platform }} + -p:PublishReadyToRun=true - run: dotnet test tests/Snaply.Tests/Snaply.Tests.csproj -c Release --no-restore - - if: matrix.architecture == 'x64' - run: dotnet test tests/Snaply.App.Tests/Snaply.App.Tests.csproj -c Release --no-restore + - run: >- + dotnet test tests/Snaply.App.Tests/Snaply.App.Tests.csproj + -c Release + -p:Platform=${{ matrix.platform }} + --no-restore - name: Publish native portable payload run: >- dotnet publish src/Snaply.App/Snaply.App.csproj @@ -57,20 +64,7 @@ jobs: --self-contained true -o build/native --no-restore - # UI journeys are x64-only. On windows-11-arm the shell keeps the foreground for - # itself — the image boots with a Microsoft-account sign-in prompt (WWAHost), and - # closing it just hands the foreground to SearchHost — so the capture overlay never - # comes forward and synthetic input never reaches it. Even the AttachThreadInput - # handoff in ui-tests.ps1 loses that fight there, so the journeys measured the - # runner image rather than Snaply. arm64 still builds, unit-tests and publishes. - # One pass, not five. The first pass has never failed across every run of this - # work; a repeat pass fails perhaps half the time, and always the same way: the - # region drag's press lands (the overlay closes) but its moves do not register, so - # the selection is empty, CaptureAsync returns null and no preview appears. Three - # retries do not shake it off. The soak below still covers repetition — 100 - # captures against one process — which is what the repeat passes were really for. - name: Run the UI journeys - if: matrix.architecture == 'x64' shell: pwsh run: | 1..1 | ForEach-Object { @@ -89,7 +83,6 @@ jobs: } } - name: Run 100-capture soak - if: matrix.architecture == 'x64' shell: pwsh run: | $process = Start-Process build/native/Snaply.exe -PassThru @@ -109,10 +102,8 @@ jobs: Stop-Process -Id $process.Id -Force } } - # A UI failure otherwise reports only "element did not appear"; Snaply's own log - # carries the exception behind it, so ship it alongside the results. - name: Collect app logs - if: always() && matrix.architecture == 'x64' + if: always() shell: pwsh run: | $logs = Join-Path $env:LOCALAPPDATA 'Snaply\Logs' @@ -131,8 +122,8 @@ jobs: } New-Item -ItemType Directory -Force -Path artifacts/ui/app-logs | Out-Null Copy-Item "$logs\*" artifacts/ui/app-logs -Recurse -Force - # Only reached when everything gating this architecture passed: on x64 that includes - # the UI journeys and the soak, on arm64 the build and the unit tests. + # Only reached when build, unit tests, UI journeys, and soak passed on the + # native runner for this architecture. - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: nightly-${{ matrix.architecture }} @@ -140,12 +131,11 @@ jobs: retention-days: 14 if-no-files-found: error - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - if: always() && matrix.architecture == 'x64' + if: always() with: name: ui-${{ matrix.architecture }} path: artifacts/ui if-no-files-found: error - mutation: runs-on: ubuntu-latest timeout-minutes: 45 @@ -186,6 +176,5 @@ jobs: - name: Build twice shell: pwsh run: | - [xml]$props = Get-Content Directory.Build.props -Raw - $version = "$($props.Project.PropertyGroup.Version)" + $version = (Get-Content version.txt -Raw).Trim() ./scripts/test-reproducibility.ps1 -Version $version diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 17fce2b..3f9e8bb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -75,12 +75,13 @@ jobs: if ($LASTEXITCODE -ne 0) { throw "The release commit is not in main." } - [xml]$props = Get-Content Directory.Build.props -Raw - if ("v$($props.Project.PropertyGroup.Version)" -ne $env:TAG) { + $version = (Get-Content version.txt -Raw).Trim() + if ("v$version" -ne $env:TAG) { throw "The release tag does not match the project version." } - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: + dotnet-version: 8.0.x global-json-file: global.json cache: true cache-dependency-path: "**/packages.lock.json" @@ -95,15 +96,16 @@ jobs: - name: Generate SPDX SBOM shell: pwsh run: | - dotnet tool install --tool-path build/tools ` - Microsoft.Sbom.DotNetTool --version 4.1.5 - ./build/tools/sbom-tool generate ` + dotnet tool restore + dotnet tool run sbom-tool -- generate ` -b build/release ` -bc . ` -pn Snaply ` -pv '${{ inputs.tag_name }}'.TrimStart('v') ` -ps P4suta ` - -nsb https://github.com/P4suta/Snaply + -nsb https://github.com/P4suta/Snaply ` + -mi SPDX:2.2 ` + -cd '--DirectoryExclusionList **/artifacts/** --DirectoryExclusionList **/build/**' - uses: taiki-e/install-action@7572810d7dd469b651bb7793945692cf78da5dd7 # v2.85.0 with: tool: osv-scanner@2.3.6 @@ -297,6 +299,7 @@ jobs: ref: ${{ env.REF }} - uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 with: + dotnet-version: 8.0.x global-json-file: global.json cache: true cache-dependency-path: "**/packages.lock.json" diff --git a/CHANGELOG.md b/CHANGELOG.md index d5ae092..e9bcdeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ - Rebuilt Snaply as a GUI-only WinUI 3 application. - Added region, window, and complete virtual-desktop capture with mixed-DPI and HDR handling. -- Added automatic randomized beautification, preview, clipboard copy, atomic save, Save As, and Open Folder. +- Added automatic randomized beautification, zoomable preview, clipboard copy, atomic save, and Open Folder. - Added English, Japanese, and Simplified Chinese resources. - Added x64/ARM64 portable builds and a signed MSIX bundle release path. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index a9b93d9..6034cae 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,5 +1,3 @@ # Code of Conduct -This project follows the [Contributor Covenant 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). - -Be respectful, constructive, and focused on the work. Report unacceptable behavior privately to the repository maintainers. Maintainers may remove content or participation that violates this standard. +Follow [Contributor Covenant 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). Be respectful and report violations privately to the maintainers. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0bf0918..ce438b9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,21 +1,9 @@ # Contributing -Use Windows 11 24H2 or later and the .NET SDK pinned by `global.json`. +On Windows 11 24H2+ with the SDK from `global.json`: ```powershell -dotnet restore Snaply.slnx --locked-mode -dotnet build src/Snaply.App/Snaply.App.csproj -c Release -p:Platform=x64 --no-restore -dotnet test tests/Snaply.Tests/Snaply.Tests.csproj -c Release --no-restore -$env:Configuration = 'Release' -dotnet format Snaply.slnx --verify-no-changes --no-restore +./scripts/verify.ps1 ``` -Before a pull request: - -- Keep the product GUI-only and local-only. -- Add no public API, capability, dependency, setting, or abstraction without a current product need. -- Add tests for behavior and non-trivial calculations. -- Keep comments for ABI, ownership, lifetime, security, or non-obvious algorithms only. -- Use Conventional Commits and keep the branch green with no warnings or skipped required tests. - -Release packaging and UI automation are documented in [RELEASING.md](RELEASING.md). +Keep changes local-only, warning-free, tested, and limited to the current product contract. Use Conventional Commits. diff --git a/Directory.Build.props b/Directory.Build.props index 3b7efd4..7b941cd 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,7 @@ - 0.1.1 + $([System.IO.File]::ReadAllText('$(MSBuildThisFileDirectory)version.txt').Trim()) + 10.0.26100.87 true true true diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000..137069b --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/README.md b/README.md index 14dfd29..140dea5 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,11 @@ # Snaply -Snaply is a Windows screenshot tool. It captures a region, a window, or the -entire virtual desktop, then places the capture on a randomized, image-derived -gradient background. +Snaply captures a region, window, or desktop, presents a zoomable polished preview, and automatically saves and copies the PNG. -After each capture, Snaply opens a preview, copies a PNG to the clipboard, and -saves the same PNG to `Pictures\Screenshots\Snaply`. +1. Choose Region, Window, or Desktop. +2. Capture; cancel with Esc when applicable. +3. Find the PNG in `Pictures\Screenshots\Snaply` or paste it from the clipboard. -## Usage +Windows 11 24H2+ builds for x64 and ARM64 are published as signed MSIX and self-contained portable ZIPs in [GitHub Releases](https://github.com/P4suta/Snaply/releases). The UI supports English, Japanese, and Simplified Chinese. -1. Open the Capture menu and choose Region, Window, or Desktop. -2. For Region, drag to select across one or more displays. For Window, pick - from the system window picker. -3. In the preview, scroll to zoom, drag to pan, and double-tap to fit. Use - Open Folder to open the save location. - -## Install - -Download the signed MSIX bundle or the self-contained x64/ARM64 portable ZIP -from [GitHub Releases](https://github.com/P4suta/Snaply/releases). Portable -builds require no .NET or Windows App SDK installation: extract the ZIP and run -`Snaply.exe`. - -Snaply runs on Windows 11 24H2 or later on x64 and ARM64, in English, Japanese, -and Simplified Chinese. - -## Privacy - -Snaply runs entirely on the local machine. It has no telemetry, network access, -background service, tray process, global hotkey, or updater. - -## License - -Apache-2.0. See [LICENSE](LICENSE). +Snaply is local-only: no network access or telemetry. Licensed under [Apache-2.0](LICENSE). diff --git a/RELEASING.md b/RELEASING.md index e0d18fa..98ba50e 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,16 +1,9 @@ # Releasing -Release Please owns versions, tags, release notes, and the release pull request. Merging that pull request starts the protected release workflow. +1. Run `./scripts/verify.ps1`. +2. Confirm repository variable `MSIX_PUBLISHER`, release variable `SIGNER_SUBJECT_CONTAINS`, and the four SSL.com eSigner secrets are present. +3. Run the release workflow with `publish=false`. +4. Require green signing, SBOM/license/vulnerability checks, WACK, and x64/ARM64 portable/MSIX QA: three capture modes, automatic save/copy, two launches, upgrade, uninstall. +5. Merge the Release Please PR; publish only the immutable tag created from `main`. -The `release` environment must require approval and provide: - -- `ES_USERNAME`, `ES_PASSWORD`, `CREDENTIAL_ID`, and `ES_TOTP_SECRET` -- `SIGNER_SUBJECT_CONTAINS`: the expected certificate subject fragment - -The repository variable `MSIX_PUBLISHER` must contain the exact distinguished name of the SSL.com signing certificate. - -The workflow builds x64 and ARM64 portable payloads and single-project MSIX packages, bundles and signs them, verifies RFC 3161 timestamps and signer identity, generates an SPDX SBOM and SHA-256 checksums, scans vulnerabilities and licenses, and creates GitHub attestations. - -Publication remains blocked until the release candidate passes WACK and the release-artifact journeys on clean Windows 11 24H2 x64 and ARM64 machines: install/extract, launch, all capture modes, automatic copy/save, Save As, restart, upgrade, and uninstall. - -Repository rulesets, protected tags, signed commits, secret scanning with push protection, private vulnerability reporting, CodeQL, Dependabot, and environment approval must be enabled in GitHub itself. Checked-in files are not evidence that these settings are active. +GitHub settings are checked with `./scripts/sync-github-settings.ps1 -Check`; credentials are never stored in the repository. diff --git a/REUSE.toml b/REUSE.toml new file mode 100644 index 0000000..55c7d0c --- /dev/null +++ b/REUSE.toml @@ -0,0 +1,20 @@ +version = 1 +SPDX-PackageName = "Snaply" +SPDX-PackageSupplier = "P4suta" +SPDX-PackageDownloadLocation = "https://github.com/P4suta/Snaply" + +[[annotations]] +path = ["*", "**/*"] +precedence = "closest" +SPDX-FileCopyrightText = "2026 P4suta" +SPDX-License-Identifier = "Apache-2.0" + +[[annotations]] +path = [ + ".release-please-manifest.json", + "version.txt", + "**/packages.lock.json", +] +precedence = "override" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" diff --git a/SECURITY.md b/SECURITY.md index cf90cac..d5cd993 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,7 +1,3 @@ # Security -Security fixes are provided for the latest release. - -Report vulnerabilities privately through [GitHub Private Vulnerability Reporting](https://github.com/P4suta/Snaply/security/advisories/new). Do not open a public issue before a fix is available. - -Reports should include the affected version, impact, reproduction steps, and any known mitigation. Maintainers will acknowledge a report within seven days. +Report vulnerabilities privately through [GitHub Private Vulnerability Reporting](https://github.com/P4suta/Snaply/security/advisories/new). Include the affected version, impact, and reproduction steps; do not open a public issue first. diff --git a/release-please-config.json b/release-please-config.json index 86b4524..64870bc 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -6,6 +6,7 @@ ".": { "release-type": "simple", "package-name": "snaply", + "version-file": "version.txt", "draft": true, "force-tag-creation": true } diff --git a/scripts/release-qa.ps1 b/scripts/release-qa.ps1 index 198e3b0..fbdfc3e 100644 --- a/scripts/release-qa.ps1 +++ b/scripts/release-qa.ps1 @@ -99,7 +99,8 @@ $portable = Join-Path $release "portable\$Architecture\Snaply.exe" if (-not (Test-Path -LiteralPath $portable)) { throw "Portable executable is missing: $portable" } -Invoke-Journey { Start-Process -FilePath $portable | Out-Null } 'Portable' $SoakIterations +Invoke-Journey { Start-Process -FilePath $portable | Out-Null } 'Portable first launch' $SoakIterations +Invoke-Journey { Start-Process -FilePath $portable | Out-Null } 'Portable relaunch' 0 if ($PSVersionTable.PSEdition -eq 'Core') { Import-Module Appx -UseWindowsPowerShell @@ -123,11 +124,16 @@ try { } $package = Get-AppxPackage -Name Snaply -ErrorAction Stop - Invoke-Journey { + $msixLaunch = { Start-Process explorer.exe "shell:AppsFolder\$($package.PackageFamilyName)!App" - } 'MSIX' 0 + } + Invoke-Journey $msixLaunch 'MSIX first launch' 0 + Invoke-Journey $msixLaunch 'MSIX relaunch' 0 } finally { Get-AppxPackage -Name Snaply -ErrorAction SilentlyContinue | Remove-AppxPackage -ErrorAction Stop + if (Get-AppxPackage -Name Snaply -ErrorAction SilentlyContinue) { + throw 'Snaply remained installed after uninstall.' + } } diff --git a/scripts/release.ps1 b/scripts/release.ps1 index 6b02639..61ecf4c 100644 --- a/scripts/release.ps1 +++ b/scripts/release.ps1 @@ -4,8 +4,9 @@ param( [ValidateSet('Build', 'Collect', 'Verify', 'Package')] [string]$Action, + [Parameter(Mandatory)] [ValidatePattern('^\d+\.\d+\.\d+$')] - [string]$Version = '0.1.1', + [string]$Version, [string]$Publisher = 'CN=Snaply', @@ -86,6 +87,43 @@ function Invoke-Checked { } } +function Invoke-SbomTool { + param([string[]]$Arguments) + + $manifest = Get-Content (Join-Path $root '.config\dotnet-tools.json') -Raw | + ConvertFrom-Json + $version = $manifest.tools.'microsoft.sbom.dotnettool'.version + $packages = if ($env:NUGET_PACKAGES) { + $env:NUGET_PACKAGES + } + else { + Join-Path $env:USERPROFILE '.nuget\packages' + } + + $assembly = Join-Path $packages ( + "microsoft.sbom.dotnettool\$version\tools\net8.0\any\Microsoft.Sbom.DotNetTool.dll") + if (-not (Test-Path -LiteralPath $assembly -PathType Leaf)) { + throw 'Microsoft SBOM Tool was not restored.' + } + + $hosts = @( + (Get-Command dotnet -ErrorAction Stop).Source, + (Join-Path $env:ProgramFiles 'dotnet\dotnet.exe'), + (Join-Path ${env:ProgramFiles(x86)} 'dotnet\dotnet.exe') + ) | Where-Object { $_ } | Select-Object -Unique + $dotnetHost = $hosts | Where-Object { + (Test-Path -LiteralPath $_ -PathType Leaf) -and + @(Get-ChildItem -LiteralPath ( + Join-Path (Split-Path $_) 'shared\Microsoft.NETCore.App') ` + -Directory -Filter '8.*' -ErrorAction SilentlyContinue).Count -gt 0 + } | Select-Object -First 1 + if (-not $dotnetHost) { + throw 'Microsoft SBOM Tool requires the .NET 8 runtime.' + } + + Invoke-Checked $dotnetHost (@($assembly) + $Arguments) +} + function Get-PeMachine { param([string]$Path) @@ -306,6 +344,16 @@ function Assert-Msix { if ($targetFamily.MinVersion -ne '10.0.26100.0') { throw 'MSIX minimum Windows version is incorrect.' } + + foreach ($size in @(16, 24, 32, 48, 256)) { + foreach ($suffix in @('', '_altform-unplated', '_altform-lightunplated')) { + $asset = Join-Path $Scratch ( + "Assets\Square44x44Logo.targetsize-$size$suffix.png") + if (-not (Test-Path -LiteralPath $asset -PathType Leaf)) { + throw "MSIX is missing app-list asset '$([IO.Path]::GetFileName($asset))'." + } + } + } } function Copy-SigningStage { @@ -524,7 +572,9 @@ function New-DeterministicZip { function Package-Release { $package = Join-Path $output 'package' + $sbomRoot = Join-Path $output 'package-sbom' Reset-Directory $package + Reset-Directory $sbomRoot foreach ($architecture in @('x64', 'arm64')) { New-DeterministicZip (Join-Path $output "portable\$architecture") ` (Join-Path $package "snaply-v$Version-win-$architecture.zip") @@ -536,12 +586,6 @@ function Package-Release { Copy-Item (Join-Path $root 'NOTICE') $package Copy-Item (Join-Path $output 'dependency-licenses.txt') $package - $sbom = Join-Path $output '_manifest\spdx_2.2\manifest.spdx.json' - if (-not (Test-Path -LiteralPath $sbom)) { - throw 'SPDX SBOM is missing.' - } - Copy-Item $sbom (Join-Path $package 'snaply.spdx.json') - $hashes = Get-ChildItem -LiteralPath $package -File | Where-Object Name -ne 'SHA256SUMS.txt' | Sort-Object Name | @@ -554,6 +598,38 @@ function Package-Release { (Join-Path $package 'SHA256SUMS.txt'), $hashes, [System.Text.Encoding]::ASCII) + + Invoke-Checked 'dotnet' @('tool', 'restore') + Invoke-SbomTool @( + 'generate', + '-b', $package, + '-bc', $root, + '-m', $sbomRoot, + '-PackageName', 'Snaply', + '-pv', $Version, + '-ps', 'P4suta', + '-nsb', 'https://github.com/P4suta/Snaply', + '-mi', 'SPDX:2.2', + '-cd', + '--DirectoryExclusionList **/artifacts/** --DirectoryExclusionList **/build/**', + '-D', 'true', + '-V', 'Warning') + $manifestDirectory = Join-Path $sbomRoot '_manifest' + $validationReport = Join-Path $sbomRoot 'validation.json' + Invoke-SbomTool @( + 'validate', + '-b', $package, + '-m', $manifestDirectory, + '-o', $validationReport, + '-mi', 'SPDX:2.2', + '-n', + '-V', 'Warning') + $sbom = Join-Path $manifestDirectory 'spdx_2.2\manifest.spdx.json' + if (-not (Test-Path -LiteralPath $sbom -PathType Leaf)) { + throw 'SPDX SBOM was not generated.' + } + + Copy-Item $sbom (Join-Path $package 'snaply.spdx.json') } switch ($Action) { diff --git a/scripts/sync-github-settings.ps1 b/scripts/sync-github-settings.ps1 new file mode 100644 index 0000000..f9f1805 --- /dev/null +++ b/scripts/sync-github-settings.ps1 @@ -0,0 +1,205 @@ +#requires -Version 7.0 +param( + [Parameter(ParameterSetName = 'Check', Mandatory)] + [switch]$Check, + + [Parameter(ParameterSetName = 'Apply', Mandatory)] + [switch]$Apply +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$root = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$rulesetRoot = Join-Path $root '.github\rulesets' +$allowedActionPatterns = @( + 'SSLcom/esigner-codesign@*', + 'crate-ci/typos@*', + 'fsfe/reuse-action@*', + 'googleapis/release-please-action@*', + 'microsoft/setup-WinAppCli@*', + 'ossf/scorecard-action@*', + 'raven-actions/actionlint@*', + 'softprops/action-gh-release@*', + 'taiki-e/install-action@*' +) + +function Invoke-Gh { + param([string[]]$Arguments) + + $output = gh @Arguments + if ($LASTEXITCODE -ne 0) { + throw "gh failed: $($Arguments -join ' ')" + } + + return $output +} + +function ConvertTo-NormalForm { + param([object]$Value) + + if ($null -eq $Value) { + return $null + } + + if ($Value -is [string] -or $Value.GetType().IsValueType) { + return $Value + } + + if ($Value -is [System.Collections.IEnumerable] -and + $Value -isnot [System.Management.Automation.PSCustomObject]) { + return @($Value | ForEach-Object { ConvertTo-NormalForm $_ }) + } + + $normal = [ordered]@{} + foreach ($property in $Value.PSObject.Properties | Sort-Object Name) { + $normal[$property.Name] = ConvertTo-NormalForm $property.Value + } + + return [pscustomobject]$normal +} + +function Get-RulesetPayload { + param([object]$Ruleset) + + return [pscustomobject][ordered]@{ + name = $Ruleset.name + target = $Ruleset.target + enforcement = $Ruleset.enforcement + bypass_actors = @($Ruleset.bypass_actors) + conditions = $Ruleset.conditions + rules = @($Ruleset.rules) + } +} + +$repository = (Invoke-Gh @( + 'repo', 'view', + '--json', 'nameWithOwner', + '--jq', '.nameWithOwner')).Trim() +$liveRulesets = Invoke-Gh @( + 'api', "repos/$repository/rulesets", + '--paginate') | ConvertFrom-Json + +if ($Apply) { + foreach ($path in Get-ChildItem -LiteralPath $rulesetRoot -Filter '*.json' -File) { + $canonical = Get-Content $path.FullName -Raw | ConvertFrom-Json + $live = @($liveRulesets | Where-Object name -eq $canonical.name) + if ($live.Count -gt 1) { + throw "Multiple live rulesets are named '$($canonical.name)'." + } + + if ($live.Count -eq 1) { + Invoke-Gh @( + 'api', + '--method', 'PUT', + "repos/$repository/rulesets/$($live[0].id)", + '--input', $path.FullName) | Out-Null + } + else { + Invoke-Gh @( + 'api', + '--method', 'POST', + "repos/$repository/rulesets", + '--input', $path.FullName) | Out-Null + } + } + + $liveRulesets = Invoke-Gh @( + 'api', "repos/$repository/rulesets", + '--paginate') | ConvertFrom-Json + + Invoke-Gh @( + 'api', + '--method', 'PUT', + "repos/$repository/actions/permissions", + '-F', 'enabled=true', + '-f', 'allowed_actions=selected', + '-F', 'sha_pinning_required=true') | Out-Null + $selectedActionArguments = [System.Collections.Generic.List[string]]::new() + foreach ($argument in @( + 'api', + '--method', 'PUT', + "repos/$repository/actions/permissions/selected-actions", + '-F', 'github_owned_allowed=true', + '-F', 'verified_allowed=false')) { + $selectedActionArguments.Add($argument) + } + foreach ($pattern in $allowedActionPatterns) { + $selectedActionArguments.Add('-f') + $selectedActionArguments.Add("patterns_allowed[]=$pattern") + } + + Invoke-Gh $selectedActionArguments.ToArray() | Out-Null +} + +$failures = [System.Collections.Generic.List[string]]::new() +foreach ($path in Get-ChildItem -LiteralPath $rulesetRoot -Filter '*.json' -File) { + $canonical = Get-Content $path.FullName -Raw | ConvertFrom-Json + $summary = @($liveRulesets | Where-Object name -eq $canonical.name) + if ($summary.Count -ne 1) { + $failures.Add("Ruleset '$($canonical.name)' is missing or duplicated.") + continue + } + + $live = Invoke-Gh @( + 'api', + "repos/$repository/rulesets/$($summary[0].id)") | ConvertFrom-Json + $expectedJson = ConvertTo-NormalForm (Get-RulesetPayload $canonical) | + ConvertTo-Json -Depth 100 -Compress + $actualJson = ConvertTo-NormalForm (Get-RulesetPayload $live) | + ConvertTo-Json -Depth 100 -Compress + if ($expectedJson -ne $actualJson) { + $failures.Add("Ruleset '$($canonical.name)' differs from its canonical JSON.") + } +} + +$variables = @(Invoke-Gh @( + 'variable', 'list', + '--repo', $repository, + '--json', 'name') | ConvertFrom-Json) +if ('MSIX_PUBLISHER' -notin @($variables | ForEach-Object name)) { + $failures.Add('Repository variable MSIX_PUBLISHER is missing.') +} + +$repositoryState = Invoke-Gh @( + 'api', "repos/$repository") | ConvertFrom-Json +foreach ($feature in @('secret_scanning', 'secret_scanning_push_protection')) { + if ($repositoryState.security_and_analysis.$feature.status -ne 'enabled') { + $failures.Add("$feature is not enabled.") + } +} + +$actionsPermissions = Invoke-Gh @( + 'api', "repos/$repository/actions/permissions") | ConvertFrom-Json +if ($actionsPermissions.allowed_actions -ne 'selected') { + $failures.Add('Actions are not restricted to the selected allowlist.') +} +else { + $actionPolicy = Invoke-Gh @( + 'api', "repos/$repository/actions/permissions/selected-actions") | + ConvertFrom-Json + if (-not $actionPolicy.github_owned_allowed) { + $failures.Add('GitHub-owned Actions are not allowed.') + } + + if ($actionPolicy.verified_allowed) { + $failures.Add('All verified Actions are allowed instead of the explicit allowlist.') + } + + if (-not $actionsPermissions.sha_pinning_required) { + $failures.Add('Actions SHA pinning is not required.') + } + + $expectedPatterns = @($allowedActionPatterns | Sort-Object) + $actualPatterns = @($actionPolicy.patterns_allowed | Sort-Object) + if (Compare-Object $expectedPatterns $actualPatterns) { + $failures.Add('The selected Actions allowlist differs from the canonical list.') + } +} + +if ($failures.Count -ne 0) { + $failures | ForEach-Object { Write-Error $_ -ErrorAction Continue } + throw "GitHub settings check failed with $($failures.Count) issue(s)." +} + +Write-Host "GitHub settings match the canonical release policy for $repository." diff --git a/scripts/verify.ps1 b/scripts/verify.ps1 new file mode 100644 index 0000000..4e51e0e --- /dev/null +++ b/scripts/verify.ps1 @@ -0,0 +1,164 @@ +#requires -Version 5.1 +param( + [ValidateSet('Debug', 'Release')] + [string]$Configuration = 'Release', + + [switch]$SkipPublish +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$root = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..')) +$output = Join-Path $root 'artifacts\verify' +$testOutput = Join-Path $root 'artifacts\verify-tests' + +function Assert-BrandAssets { + Add-Type -AssemblyName System.Drawing + $expected = [ordered]@{ + 'SplashScreen.scale-200.png' = @(1240, 600) + 'Square150x150Logo.scale-200.png' = @(300, 300) + 'Square44x44Logo.scale-200.png' = @(88, 88) + 'StoreLogo.png' = @(50, 50) + 'Wide310x150Logo.scale-200.png' = @(620, 300) + } + foreach ($size in @(16, 24, 32, 48, 256)) { + foreach ($suffix in @('', '_altform-unplated', '_altform-lightunplated')) { + $expected["Square44x44Logo.targetsize-$size$suffix.png"] = @($size, $size) + } + } + + foreach ($entry in $expected.GetEnumerator()) { + $path = Join-Path $root "src\Snaply.App\Assets\$($entry.Key)" + if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { + throw "Required brand asset is missing: $($entry.Key)" + } + + $bitmap = [System.Drawing.Bitmap]::new($path) + try { + if ($bitmap.Width -ne $entry.Value[0] -or + $bitmap.Height -ne $entry.Value[1]) { + throw "Brand asset has incorrect dimensions: $($entry.Key)" + } + + $hasBrandColour = $false + $hasTransparency = $false + $stepX = [Math]::Max(1, [int][Math]::Floor($bitmap.Width / 64)) + $stepY = [Math]::Max(1, [int][Math]::Floor($bitmap.Height / 64)) + for ($y = 0; $y -lt $bitmap.Height; $y += $stepY) { + for ($x = 0; $x -lt $bitmap.Width; $x += $stepX) { + $pixel = $bitmap.GetPixel($x, $y) + $hasTransparency = $hasTransparency -or $pixel.A -eq 0 + $hasBrandColour = $hasBrandColour -or ( + $pixel.A -ge 128 -and + $pixel.R - $pixel.G -ge 80 -and + $pixel.R - $pixel.B -ge 80) + } + } + + if (-not $hasBrandColour -or -not $hasTransparency) { + throw "Brand asset is not a transparent Snaply-colour image: $($entry.Key)" + } + } + finally { + $bitmap.Dispose() + } + } +} + +function Invoke-Checked { + param( + [string]$FilePath, + [string[]]$Arguments + ) + + & $FilePath @Arguments + if ($LASTEXITCODE -ne 0) { + throw "$FilePath failed with exit code $LASTEXITCODE." + } +} + +Push-Location $root +try { + Assert-BrandAssets + if (Test-Path -LiteralPath $testOutput) { + Remove-Item -LiteralPath $testOutput -Recurse -Force + } + + Invoke-Checked dotnet @( + 'restore', + 'Snaply.slnx', + '--locked-mode') + Invoke-Checked dotnet @( + 'restore', + 'src/Snaply.App/Snaply.App.csproj', + '--locked-mode', + '-p:Configuration=Release') + Invoke-Checked dotnet @( + 'format', + 'Snaply.slnx', + '--verify-no-changes', + '--no-restore') + Invoke-Checked dotnet @( + 'test', + 'tests/Snaply.Tests/Snaply.Tests.csproj', + '-c', $Configuration, + '--no-restore', + '-p:PathMap=', + '--collect:XPlat Code Coverage', + '--logger', 'trx;LogFileName=results.trx', + '--results-directory', (Join-Path $testOutput 'imaging')) + Invoke-Checked dotnet @( + 'test', + 'tests/Snaply.App.Tests/Snaply.App.Tests.csproj', + '-c', $Configuration, + '--no-restore', + '--logger', 'trx;LogFileName=results.trx', + '--results-directory', (Join-Path $testOutput 'app')) + + [xml]$imagingResults = Get-Content ( + Join-Path $testOutput 'imaging\results.trx') -Raw + [xml]$appResults = Get-Content ( + Join-Path $testOutput 'app\results.trx') -Raw + if ([int]$imagingResults.TestRun.ResultSummary.Counters.notExecuted -ne 0 -or + [int]$appResults.TestRun.ResultSummary.Counters.notExecuted -ne 0) { + throw 'Required tests were skipped.' + } + + $coveragePath = Get-ChildItem (Join-Path $testOutput 'imaging') ` + -Recurse -Filter coverage.cobertura.xml -File | + Select-Object -First 1 + if (-not $coveragePath) { + throw 'Coverage report was not produced.' + } + + [xml]$coverage = Get-Content $coveragePath.FullName -Raw + if ([double]$coverage.coverage.'line-rate' -lt 0.90 -or + [double]$coverage.coverage.'branch-rate' -lt 0.85) { + throw 'Imaging coverage is below 90% line or 85% branch.' + } + + if (-not $SkipPublish) { + if (Test-Path -LiteralPath $output) { + Remove-Item -LiteralPath $output -Recurse -Force + } + + foreach ($architecture in @( + [pscustomobject]@{ Platform = 'x64'; Rid = 'win-x64'; Name = 'x64' }, + [pscustomobject]@{ Platform = 'ARM64'; Rid = 'win-arm64'; Name = 'arm64' })) { + Invoke-Checked dotnet @( + 'publish', + 'src/Snaply.App/Snaply.App.csproj', + '-c', $Configuration, + '-r', $architecture.Rid, + "-p:Platform=$($architecture.Platform)", + '-p:WindowsPackageType=None', + '--self-contained', 'true', + '--no-restore', + '-o', (Join-Path $output $architecture.Name)) + } + } +} +finally { + Pop-Location +} diff --git a/src/Snaply.App/App.xaml b/src/Snaply.App/App.xaml index 54aa402..19bb825 100644 --- a/src/Snaply.App/App.xaml +++ b/src/Snaply.App/App.xaml @@ -7,8 +7,6 @@ - - diff --git a/src/Snaply.App/App.xaml.cs b/src/Snaply.App/App.xaml.cs index ab801c3..d27ea57 100644 --- a/src/Snaply.App/App.xaml.cs +++ b/src/Snaply.App/App.xaml.cs @@ -4,9 +4,10 @@ namespace Snaply; -public partial class App : Application +public sealed partial class App : Application, IDisposable { private MainWindow? _window; + private bool _disposed; public App() { @@ -14,24 +15,51 @@ public App() UnhandledException += OnUnhandledException; } - internal static Window MainWindow { get; private set; } = null!; - protected override void OnLaunched(LaunchActivatedEventArgs args) { ConfigureLogging(); - var capture = new ScreenCaptureService(); - var export = new ImageExportService(); - var viewModel = new MainViewModel(capture, export); - _window = new MainWindow(viewModel, capture); - MainWindow = _window; - _window.Closed += (_, _) => + try + { + _window = new MainWindow(); + _window.Closed += OnWindowClosed; + _window.Activate(); + } + catch { - viewModel.Dispose(); - capture.Dispose(); - Log.CloseAndFlush(); - }; - _window.Activate(); + Dispose(); + throw; + } + } + + public void Dispose() + { + DisposeCore(closeWindow: true); + GC.SuppressFinalize(this); + } + + private void DisposeCore(bool closeWindow) + { + if (_disposed) + { + return; + } + + _disposed = true; + UnhandledException -= OnUnhandledException; + if (_window is not null) + { + _window.Closed -= OnWindowClosed; + if (closeWindow) + { + _window.Close(); + } + + _window.Dispose(); + _window = null; + } + + Log.CloseAndFlush(); } private static void ConfigureLogging() @@ -88,4 +116,7 @@ private static void OnUnhandledException(object sender, Microsoft.UI.Xaml.Unhand args.Exception.GetType().FullName, args.Exception.HResult); } + + private void OnWindowClosed(object sender, WindowEventArgs args) => + DisposeCore(closeWindow: false); } diff --git a/src/Snaply.App/Assets/LockScreenLogo.scale-200.png b/src/Snaply.App/Assets/LockScreenLogo.scale-200.png deleted file mode 100644 index 33f889e..0000000 Binary files a/src/Snaply.App/Assets/LockScreenLogo.scale-200.png and /dev/null differ diff --git a/src/Snaply.App/Assets/SplashScreen.scale-200.png b/src/Snaply.App/Assets/SplashScreen.scale-200.png index 802c79d..26a7bc0 100644 Binary files a/src/Snaply.App/Assets/SplashScreen.scale-200.png and b/src/Snaply.App/Assets/SplashScreen.scale-200.png differ diff --git a/src/Snaply.App/Assets/Square150x150Logo.scale-200.png b/src/Snaply.App/Assets/Square150x150Logo.scale-200.png index ddba42a..1fd0617 100644 Binary files a/src/Snaply.App/Assets/Square150x150Logo.scale-200.png and b/src/Snaply.App/Assets/Square150x150Logo.scale-200.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.scale-200.png b/src/Snaply.App/Assets/Square44x44Logo.scale-200.png index 9327dd7..0cfea12 100644 Binary files a/src/Snaply.App/Assets/Square44x44Logo.scale-200.png and b/src/Snaply.App/Assets/Square44x44Logo.scale-200.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-16.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-16.png new file mode 100644 index 0000000..7d3e8ce Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-16.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-16_altform-lightunplated.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-16_altform-lightunplated.png new file mode 100644 index 0000000..7d3e8ce Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-16_altform-lightunplated.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-16_altform-unplated.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-16_altform-unplated.png new file mode 100644 index 0000000..7d3e8ce Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-16_altform-unplated.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-24.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-24.png new file mode 100644 index 0000000..16b8a5a Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-24.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-24_altform-lightunplated.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-24_altform-lightunplated.png new file mode 100644 index 0000000..16b8a5a Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-24_altform-lightunplated.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-24_altform-unplated.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-24_altform-unplated.png index e51416a..16b8a5a 100644 Binary files a/src/Snaply.App/Assets/Square44x44Logo.targetsize-24_altform-unplated.png and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-24_altform-unplated.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-256.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-256.png new file mode 100644 index 0000000..e4e8ba8 Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-256.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-256_altform-lightunplated.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-256_altform-lightunplated.png new file mode 100644 index 0000000..e4e8ba8 Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-256_altform-lightunplated.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-256_altform-unplated.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-256_altform-unplated.png new file mode 100644 index 0000000..e4e8ba8 Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-256_altform-unplated.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-32.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-32.png new file mode 100644 index 0000000..a67e0c9 Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-32.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-32_altform-lightunplated.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-32_altform-lightunplated.png new file mode 100644 index 0000000..a67e0c9 Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-32_altform-lightunplated.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-32_altform-unplated.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-32_altform-unplated.png new file mode 100644 index 0000000..a67e0c9 Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-32_altform-unplated.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-48.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-48.png new file mode 100644 index 0000000..35a940f Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-48.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-48_altform-lightunplated.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-48_altform-lightunplated.png index bf063eb..35a940f 100644 Binary files a/src/Snaply.App/Assets/Square44x44Logo.targetsize-48_altform-lightunplated.png and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-48_altform-lightunplated.png differ diff --git a/src/Snaply.App/Assets/Square44x44Logo.targetsize-48_altform-unplated.png b/src/Snaply.App/Assets/Square44x44Logo.targetsize-48_altform-unplated.png new file mode 100644 index 0000000..35a940f Binary files /dev/null and b/src/Snaply.App/Assets/Square44x44Logo.targetsize-48_altform-unplated.png differ diff --git a/src/Snaply.App/Assets/StoreLogo.png b/src/Snaply.App/Assets/StoreLogo.png index be865f0..570092c 100644 Binary files a/src/Snaply.App/Assets/StoreLogo.png and b/src/Snaply.App/Assets/StoreLogo.png differ diff --git a/src/Snaply.App/Assets/Wide310x150Logo.scale-200.png b/src/Snaply.App/Assets/Wide310x150Logo.scale-200.png index 314d297..93ed538 100644 Binary files a/src/Snaply.App/Assets/Wide310x150Logo.scale-200.png and b/src/Snaply.App/Assets/Wide310x150Logo.scale-200.png differ diff --git a/src/Snaply.App/BeautifyRenderer.cs b/src/Snaply.App/BeautifyRenderer.cs index 377ea92..0be03b7 100644 --- a/src/Snaply.App/BeautifyRenderer.cs +++ b/src/Snaply.App/BeautifyRenderer.cs @@ -83,7 +83,7 @@ internal static async Task RenderAsync( using var stream = new InMemoryRandomAccessStream(); await target.SaveAsync(stream, CanvasBitmapFileFormat.Png, 1).AsTask(cancellationToken); byte[] png = await ReadAllAsync(stream, cancellationToken); - return new RenderedImage(png, layout.Canvas.Width, layout.Canvas.Height); + return RenderedImage.FromOwnedPng(png, layout.Canvas.Width, layout.Canvas.Height); } private static ImageSample SampleImage(CanvasDevice device, CanvasBitmap source) @@ -107,15 +107,15 @@ private static ImageSample SampleImage(CanvasDevice device, CanvasBitmap source) } byte[] bytes = sample.GetPixelBytes(); - long red = 0; - long green = 0; - long blue = 0; + double red = 0; + double green = 0; + double blue = 0; ulong hash = 1469598103934665603; for (int index = 0; index < bytes.Length; index += 4) { - blue += bytes[index]; - green += bytes[index + 1]; - red += bytes[index + 2]; + blue += SrgbToLinear(bytes[index] / 255d); + green += SrgbToLinear(bytes[index + 1] / 255d); + red += SrgbToLinear(bytes[index + 2] / 255d); hash = (hash ^ bytes[index + 2]) * 1099511628211; hash = (hash ^ bytes[index + 1]) * 1099511628211; hash = (hash ^ bytes[index]) * 1099511628211; @@ -124,9 +124,9 @@ private static ImageSample SampleImage(CanvasDevice device, CanvasBitmap source) int pixels = checked(sampleSize * sampleSize); return new ImageSample( new Rgba( - checked((byte)(red / pixels)), - checked((byte)(green / pixels)), - checked((byte)(blue / pixels))), + LinearToSrgbByte(red / pixels), + LinearToSrgbByte(green / pixels), + LinearToSrgbByte(blue / pixels)), hash); } @@ -158,6 +158,20 @@ private static uint CreateSalt() return BitConverter.ToUInt32(bytes); } + private static double SrgbToLinear(double value) => + value <= 0.04045 + ? value / 12.92 + : Math.Pow((value + 0.055) / 1.055, 2.4); + + private static byte LinearToSrgbByte(double value) + { + double clamped = Math.Clamp(value, 0, 1); + double encoded = clamped <= 0.0031308 + ? clamped * 12.92 + : (1.055 * Math.Pow(clamped, 1 / 2.4)) - 0.055; + return (byte)Math.Round(encoded * 255, MidpointRounding.AwayFromZero); + } + private static void SetGradientDirection( CanvasLinearGradientBrush gradient, PixelSize canvas, diff --git a/src/Snaply.App/CapturePipeline.cs b/src/Snaply.App/CapturePipeline.cs new file mode 100644 index 0000000..7238f81 --- /dev/null +++ b/src/Snaply.App/CapturePipeline.cs @@ -0,0 +1,44 @@ +using Microsoft.UI.Xaml; + +namespace Snaply; + +internal interface ICapturePipeline : IDisposable +{ + public Task CaptureAsync(CaptureMode mode, CancellationToken cancellationToken); +} + +internal sealed class CapturePipeline : ICapturePipeline +{ + private readonly ScreenCaptureService _capture; + + internal CapturePipeline(Window appWindow, bool captureExclusionEnabled) + { + _capture = new ScreenCaptureService(appWindow, captureExclusionEnabled); + } + + public void Dispose() => _capture.Dispose(); + + public async Task CaptureAsync( + CaptureMode mode, + CancellationToken cancellationToken) + { + for (int attempt = 0; ; attempt++) + { + try + { + using CapturedFrame? frame = await _capture.CaptureAsync(mode, cancellationToken); + return frame is null + ? null + : await Task.Run( + () => BeautifyRenderer.RenderAsync(frame, cancellationToken), + cancellationToken); + } + catch (Exception exception) when ( + attempt == 0 + && _capture.IsGraphicsDeviceLost(exception)) + { + _capture.ResetGraphicsDevice(); + } + } + } +} diff --git a/src/Snaply.App/Controls/AmbientBackdrop.xaml b/src/Snaply.App/Controls/AmbientBackdrop.xaml deleted file mode 100644 index 5462846..0000000 --- a/src/Snaply.App/Controls/AmbientBackdrop.xaml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - diff --git a/src/Snaply.App/Controls/AmbientBackdrop.xaml.cs b/src/Snaply.App/Controls/AmbientBackdrop.xaml.cs deleted file mode 100644 index 9640add..0000000 --- a/src/Snaply.App/Controls/AmbientBackdrop.xaml.cs +++ /dev/null @@ -1,317 +0,0 @@ -using System.Numerics; -using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Hosting; -using Microsoft.UI.Xaml.Media; -using Microsoft.UI.Xaml.Shapes; -using Windows.Foundation; -using Windows.UI; -using Visual = Microsoft.UI.Composition.Visual; - -namespace Snaply.Controls; - -/// -/// A soft ambient backdrop for the empty canvas, generated entirely from a small aesthetic model -/// rather than hand-tuned constants — every value is derived, moment to moment, from the frame time: -/// -/// Colour lives in OKLCH (perceptually uniform): a constant, gentle chroma at a high -/// lightness means the "softness" is identical across every hue (unlike HSL, which looks harsher at -/// some hues). Perceptual uniformity is the beauty. -/// Hues are spread by the golden angle (137.5°) — the most even distribution on the -/// wheel — and the whole set rotates slowly, so all hues pass by without restriction. -/// Motion is a quasiperiodic Lissajous drift whose per-axis frequencies are scaled by -/// powers of the golden ratio: their ratios are irrational, so the field never repeats and -/// never settles into a visible loop. -/// -/// Deterministic (the maths is the design, not randomness) yet perpetually fresh. Purely decorative: -/// no pointer input, and it only runs while — the per-frame updates stop and -/// the control hides once a capture covers it. -/// -internal sealed partial class AmbientBackdrop : UserControl -{ - /// Identifies the dependency property. - public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register( - nameof(IsActive), - typeof(bool), - typeof(AmbientBackdrop), - new PropertyMetadata(false, OnIsActiveChanged)); - - /// Identifies the dependency property. - public static readonly DependencyProperty IsMutedProperty = DependencyProperty.Register( - nameof(IsMuted), - typeof(bool), - typeof(AmbientBackdrop), - new PropertyMetadata(false)); - - private const int BlobCount = 5; // a Fibonacci count; plays nicely with the golden-angle spread - - private const double Phi = 1.6180339887498949; - - // OKLCH soft pastel band: high lightness + gentle, constant chroma = uniform softness per hue. - private const double SoftLightness = 0.82; - private const double SoftChroma = 0.11; - - // Layering opacities — soft enough that the overlapping fields blend into one gentle wash. - private const byte BlobCentreAlpha = 150; - private const byte BaseWashAlpha = 150; - - // Timing: the base hue completes a full turn every HuePeriod; blobs drift on a base period, each - // axis detuned by a golden-ratio power so no two frequencies are commensurable. - private const double HuePeriodSeconds = 90.0; // slow, but clearly perceptible - private const double DriftBasePeriodSeconds = 24.0; - private const double BreatheDepth = 0.08; // ±8% scale - private const double AmplitudeFraction = 0.16; // drift amplitude vs the shorter card side - - // "Energy" scales saturation, presence and the hue-drift rate together. It eases between 1 (empty - // canvas — full, vivid) and MutedEnergy (an image is shown — calm, so it doesn't fight the image), - // over EnergyTau so the change is a gentle fade, never an instant switch. - private const double MutedEnergy = 0.4; - private const double EnergyTau = 1.8; // seconds (time constant of the ease) - - private const double GoldenAngleDeg = 360.0 / (Phi * Phi); // ≈137.5077° - private const double GoldenAngleRad = GoldenAngleDeg * Math.PI / 180.0; - private const double Omega0 = 2.0 * Math.PI / DriftBasePeriodSeconds; - private const double HueDegPerSecond = 360.0 / HuePeriodSeconds; - - private readonly Ellipse[] _blobs = new Ellipse[BlobCount]; - private readonly RadialGradientBrush[] _brushes = new RadialGradientBrush[BlobCount]; - private readonly Visual[] _visuals = new Visual[BlobCount]; - - // Per-blob motion constants (depend only on the index, so computed once). - private readonly double[] _freqX = new double[BlobCount]; - private readonly double[] _freqY = new double[BlobCount]; - private readonly double[] _freqScale = new double[BlobCount]; - private readonly double[] _phaseX = new double[BlobCount]; - private readonly double[] _phaseY = new double[BlobCount]; - private readonly double[] _phaseScale = new double[BlobCount]; - - private double _amplitude; - private double _energy = 1.0; // eases toward MutedEnergy / 1 (see OnRendering) - private double _hue; // accumulated base hue (integrated, since its rate varies) - private double _lastTime = -1; // previous frame time; <0 means "no previous frame yet" - private bool _loaded; - private bool _running; - - /// Creates the control, builds its blobs and derives their per-index motion constants. - public AmbientBackdrop() - { - InitializeComponent(); - - for (int i = 0; i < BlobCount; i++) - { - var brush = new RadialGradientBrush(); - brush.GradientStops.Add(new GradientStop { Offset = 0.0, Color = Color.FromArgb(0, 0, 0, 0) }); - brush.GradientStops.Add(new GradientStop { Offset = 1.0, Color = Color.FromArgb(0, 0, 0, 0) }); - - var blob = new Ellipse - { - HorizontalAlignment = HorizontalAlignment.Left, - VerticalAlignment = VerticalAlignment.Top, - IsHitTestVisible = false, - Fill = brush, - }; - - Root.Children.Add(blob); - _blobs[i] = blob; - _brushes[i] = brush; - - Visual visual = ElementCompositionPreview.GetElementVisual(blob); - ElementCompositionPreview.SetIsTranslationEnabled(blob, true); - _visuals[i] = visual; - - // Detune each axis by a golden-ratio power (centred on the base), so every frequency ratio - // is irrational — the Lissajous figure never closes and the motion never repeats. - double exponent = (i - ((BlobCount - 1) / 2.0)) * 0.4; - _freqX[i] = Omega0 * Math.Pow(Phi, exponent); - _freqY[i] = Omega0 * Math.Pow(Phi, exponent + 0.3); - _freqScale[i] = Omega0 * Math.Pow(Phi, exponent - 0.5); - _phaseX[i] = i * GoldenAngleRad; - _phaseY[i] = (i * GoldenAngleRad) + (Math.PI / 2.0); - _phaseScale[i] = (i * GoldenAngleRad) + (Math.PI / 4.0); - } - - Loaded += OnLoaded; - Unloaded += OnUnloaded; - Root.SizeChanged += OnRootSizeChanged; - } - - /// - /// Whether the backdrop is shown and animating. Bind this to the empty-canvas condition - /// (e.g. HasNoImage): the control hides and its per-frame updates stop when it is false. - /// - public bool IsActive - { - get => (bool)GetValue(IsActiveProperty); - set => SetValue(IsActiveProperty, value); - } - - /// - /// When true the field calms down — lower saturation, fainter, and a slower colour drift — - /// so it sits quietly behind a shown image. Bind to the "an image is present" condition - /// (e.g. HasImage). The transition eases in/out; it is never an instant switch. - /// - public bool IsMuted - { - get => (bool)GetValue(IsMutedProperty); - set => SetValue(IsMutedProperty, value); - } - - private static void OnIsActiveChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => - ((AmbientBackdrop)d).UpdateActivation(); - - private void OnLoaded(object sender, RoutedEventArgs e) - { - _loaded = true; - UpdateActivation(); - } - - private void OnUnloaded(object sender, RoutedEventArgs e) - { - _loaded = false; - StopRendering(); - } - - // Lay the blobs out to cover the card (phyllotaxis placement + generous size), clip to bounds, - // and update the drift amplitude for the new size. - private void OnRootSizeChanged(object sender, SizeChangedEventArgs e) - { - double w = Root.ActualWidth; - double h = Root.ActualHeight; - Root.Clip = new RectangleGeometry { Rect = new Rect(0, 0, w, h) }; - if (w <= 0 || h <= 0) - { - return; - } - - double diagonal = Math.Sqrt((w * w) + (h * h)); - double spread = Math.Min(w, h) * 0.32; - _amplitude = Math.Min(w, h) * AmplitudeFraction; - - for (int i = 0; i < BlobCount; i++) - { - // Big soft discs, sized off the diagonal so they overlap and fill the whole card. - double size = diagonal * (0.7 + (0.12 * i)); - - // Sunflower (golden-angle) placement so the centres are evenly, organically distributed. - double radius = spread * Math.Sqrt((i + 0.5) / BlobCount); - double angle = i * GoldenAngleRad; - double cx = (w / 2.0) + (radius * Math.Cos(angle)); - double cy = (h / 2.0) + (radius * Math.Sin(angle)); - - _blobs[i].Width = size; - _blobs[i].Height = size; - _blobs[i].Margin = new Thickness(cx - (size / 2.0), cy - (size / 2.0), 0, 0); - _visuals[i].CenterPoint = new Vector3((float)(size / 2.0), (float)(size / 2.0), 0f); - } - } - - private void UpdateActivation() - { - Visibility = IsActive ? Visibility.Visible : Visibility.Collapsed; - if (_loaded && IsActive) - { - StartRendering(); - } - else - { - StopRendering(); - } - } - - private void StartRendering() - { - if (_running) - { - return; - } - - _running = true; - CompositionTarget.Rendering += OnRendering; - } - - private void StopRendering() - { - if (!_running) - { - return; - } - - _running = false; - _lastTime = -1; // so dt doesn't jump across a pause when we resume - CompositionTarget.Rendering -= OnRendering; - } - - // The whole look, derived fresh each frame from the current time. - private void OnRendering(object? sender, object e) - { - double t = ((RenderingEventArgs)e).RenderingTime.TotalSeconds; - double dt = _lastTime < 0 ? 0.0 : Math.Clamp(t - _lastTime, 0.0, 0.1); - _lastTime = t; - - // Ease "energy" toward its target (frame-rate independent), then let it scale saturation, - // presence and the hue-drift rate — so muting is a slow, coherent calming, not a hard cut. - double target = IsMuted ? MutedEnergy : 1.0; - _energy += (target - _energy) * (1.0 - Math.Exp(-dt / EnergyTau)); - - // Integrate the base hue (its rate is energy-scaled, so it can't be a function of absolute t). - _hue = (_hue + (HueDegPerSecond * _energy * dt)) % 360.0; - - double chroma = SoftChroma * _energy; - byte blobAlpha = (byte)(BlobCentreAlpha * _energy); - byte washAlpha = (byte)(BaseWashAlpha * _energy); - - for (int i = 0; i < BlobCount; i++) - { - // Colour: this blob's hue is the rotating base plus a golden-angle offset (even spread). - (byte r, byte g, byte b) = OklchToRgb(SoftLightness, chroma, _hue + (i * GoldenAngleDeg)); - _brushes[i].GradientStops[0].Color = Color.FromArgb(blobAlpha, r, g, b); - _brushes[i].GradientStops[1].Color = Color.FromArgb(0, r, g, b); - - // Motion: quasiperiodic Lissajous drift + a gentle breathing scale about the centre. - float dx = (float)(_amplitude * Math.Sin((_freqX[i] * t) + _phaseX[i])); - float dy = (float)(_amplitude * Math.Sin((_freqY[i] * t) + _phaseY[i])); - _visuals[i].Properties.InsertVector3("Translation", new Vector3(dx, dy, 0f)); - - float scale = (float)(1.0 + (BreatheDepth * Math.Sin((_freqScale[i] * t) + _phaseScale[i]))); - _visuals[i].Scale = new Vector3(scale, scale, 1f); - } - - // Base wash: a soft two-tone that fills the whole card, its stops a golden-angle apart and - // riding the same rotating hue, so there's always colour even between the blobs. - (byte w0R, byte w0G, byte w0B) = OklchToRgb(SoftLightness, chroma * 0.85, _hue); - (byte w1R, byte w1G, byte w1B) = OklchToRgb(SoftLightness, chroma * 0.85, _hue + GoldenAngleDeg); - BaseWashStop0.Color = Color.FromArgb(washAlpha, w0R, w0G, w0B); - BaseWashStop1.Color = Color.FromArgb(washAlpha, w1R, w1G, w1B); - } - - // Perceptually-uniform OKLCH → opaque sRGB (gamut-clamped per channel). Kept self-contained here - // so the backdrop depends on nothing beyond the framework; the maths mirrors the colour science - // the app uses elsewhere (equal OKLCH steps look equally spaced, which is where the softness reads). - private static (byte R, byte G, byte B) OklchToRgb(double lightness, double chroma, double hueDegrees) - { - double h = hueDegrees * Math.PI / 180.0; - double a = chroma * Math.Cos(h); - double bComponent = chroma * Math.Sin(h); - - double lRoot = lightness + (0.3963377774 * a) + (0.2158037573 * bComponent); - double mRoot = lightness - (0.1055613458 * a) - (0.0638541728 * bComponent); - double sRoot = lightness - (0.0894841775 * a) - (1.2914855480 * bComponent); - double lCubed = lRoot * lRoot * lRoot; - double mCubed = mRoot * mRoot * mRoot; - double sCubed = sRoot * sRoot * sRoot; - - double red = (4.0767416621 * lCubed) - (3.3077115913 * mCubed) + (0.2309699292 * sCubed); - double green = (-1.2684380046 * lCubed) + (2.6097574011 * mCubed) - (0.3413193965 * sCubed); - double blue = (-0.0041960863 * lCubed) - (0.7034186147 * mCubed) + (1.7076147010 * sCubed); - - return (ToByte(LinearToSrgb(red)), ToByte(LinearToSrgb(green)), ToByte(LinearToSrgb(blue))); - } - - private static double LinearToSrgb(double channel) - { - double c = Math.Clamp(channel, 0.0, 1.0); - return c <= 0.0031308 ? (12.92 * c) : ((1.055 * Math.Pow(c, 1.0 / 2.4)) - 0.055); - } - - private static byte ToByte(double channel) => (byte)Math.Clamp(Math.Round(channel * 255.0), 0, 255); -} diff --git a/src/Snaply.App/Controls/RegionSelectionOverlay.xaml b/src/Snaply.App/Controls/RegionSelectionOverlay.xaml new file mode 100644 index 0000000..3f2aebf --- /dev/null +++ b/src/Snaply.App/Controls/RegionSelectionOverlay.xaml @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + - + - - - + + +