Compare commits

...
Author SHA1 Message Date
poli0981andClaude Opus 5.5 e39e613cf7 test: cover ShellLauncher's start info, including the elevated path
The 2.0.2 fix (Explorer by its full path when elevated) had no test, and
its two lines were the only uncovered new code that kept SonarQube
Cloud's quality gate red (coverage on new code 33.3% < 80%).
StartInfo is now a pure function: one test checks that the elevated
path starts explorer.exe from the Windows folder by its full path, the
other that TryOpen returns false for a missing file (not elevated, no
UI, nothing is launched).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:36:37 +07:00
poli0981andClaude Opus 5.5 ac378452a8 ci: send the product version to SonarQube Cloud (#67)
Without a project version every analysis reports "not provided", so the
"previous version" new-code period never moves past the first analysis:
the master quality gate measured coverage on all code changed since
2026-10-16 (33.3% < 80%). The scan now passes the version from
Directory.Build.props (eng/Get-BuildInfo.ps1), so new code starts at the
last version change.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:28:46 +00:00
dependabot[bot] 280253c3ba chore(actions): Bump zizmorcore/zizmor-action (#66)
Bumps the actions group with 1 update: [zizmorcore/zizmor-action](https://github.com/zizmorcore/zizmor-action).


Updates `zizmorcore/zizmor-action` from 0.7.0 to 0.7.1
- [Release notes](https://github.com/zizmorcore/zizmor-action/releases)
- [Commits](https://github.com/zizmorcore/zizmor-action/compare/f9597c869b2e67095f9b527070297a13a6efe928...85b2b9fb8e3325e7a23d7d0a9d7ba5ae0f999e3e)

---
updated-dependencies:
- dependency-name: zizmorcore/zizmor-action
  dependency-version: 0.7.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-22 12:16:34 +00:00
dependabot[bot] abb6b4ae20 chore(sdk): Bump dotnet-sdk from 10.0.401 to 10.0.402 (#65)
Bumps [dotnet-sdk](https://github.com/dotnet/sdk) from 10.0.401 to 10.0.402.
- [Release notes](https://github.com/dotnet/sdk/releases)
- [Commits](https://github.com/dotnet/sdk/compare/v10.0.401...v10.0.402)

---
updated-dependencies:
- dependency-name: dotnet-sdk
  dependency-version: 10.0.402
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-22 12:13:35 +00:00
poli0981 6db1b4c2a1 Merge pull request #63 from poli0981/ci/sonarcloud-scanner
ci: SonarQube Cloud analysis in CI with SonarScanner for .NET
2026-10-22 19:07:21 +07:00
poli0981andClaude Opus 5.5 1908464811 refactor: drop SonarCloud suppressions the CI analysis does not need
With a real build the analyzer binds WinEventWatcher's factory calls
(S3453), and the test projects are analyzed as tests, where the
main-code rule S2245 does not apply. The by-design suppressions (S4790,
S6640) stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:00:21 +07:00
poli0981andClaude Opus 5.5 67484ec2ce ci: analyze with SonarScanner for .NET instead of Automatic Analysis
SonarQube Cloud's Automatic Analysis does not build: it counted tests/
as product code and could not see CsWin32's generated PInvoke code,
which produced false positives (S2245 in tests, S3453 on
WinEventWatcher).

The new sonarcloud workflow builds, runs the tests with Cobertura
coverage and uploads the analysis (multi-language scan keeps the
workflows, YAML and PowerShell files). Test projects are recognized by
their TestContainer capability. Not a required check; Dependabot and
fork pull requests skip it (no SONAR_TOKEN). The scanner is pinned in
the tool manifest and updated with the other tools by Dependabot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:00:21 +07:00
poli0981 2dd57b90e5 Merge pull request #62 from poli0981/fix/sonarcloud-findings
fix: resolve the SonarQube Cloud findings (2.0.2)
2026-10-22 18:54:06 +07:00
poli0981andClaude Opus 5.5 18453dd2d3 chore(release): 2.0.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:44:40 +07:00
poli0981andClaude Opus 5.5 179e94e128 ci: least-privilege Scorecard defaults and HTTPS-only curl
- scorecard.yml: workflow default "contents: read" instead of read-all;
  the job keeps its own permissions (S8234).
- workflow-lint.yml: restrict the actionlint download to HTTPS, also
  across redirects (S6506).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:44:40 +07:00
poli0981andClaude Opus 5.5 f243521e20 fix: resolve SonarQube Cloud findings
- ShellLauncher: start Explorer by its full path when elevated. A bare
  "explorer.exe" is searched in the app folder first (user-writable), so a
  planted copy would have run with administrator rights (S4036).
- ClickSession: start the loop with an explicit CancellationToken.None.
  The session token would cancel a loop stopped before it starts without
  running it, leaving the session Running (S8949).
- StaThread: hand the test outcome back through a TaskCompletionSource
  instead of a captured local (S2583 false positive); a new test checks
  that failures are still rethrown.
- Justified suppressions for by-design findings: SHA1 only reproduces the
  v1 mutex and pipe names (S4790), reviewed token queries without a safe
  CsWin32 overload (S6640), seeded Random in tests (S2245; automatic
  analysis treats tests/ as product code) and factory-created
  WinEventWatcher (S3453; the analysis cannot see CsWin32-generated code).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:44:40 +07:00
poli0981 2a3ec3976f Merge pull request #60 from poli0981/fix/dark-theme-text
fix(ui): readable text and charts in the Dark theme (2.0.1)
2026-10-16 07:05:12 +07:00
poli0981andClaude Opus 5.5 93540054ab chore(release): 2.0.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 06:58:47 +07:00
poli0981andClaude Opus 5.5 ef8377e4fc fix(ui): page text, icons and charts follow the theme
In the Dark theme, page text and icons without a color of their own were
drawn black at startup and became readable only after switching to Light
and back. The pages had no themed Foreground: WPF-UI's implicit Page style
never reaches page subclasses, and the navigation frame passes the
window's text color on only after a theme change. Each page now sets
Foreground="{DynamicResource TextFillColorPrimaryBrush}".

LiveCharts' WPF view always uses its light theme and cleared the chart
canvas white behind text in theme colors; the charts are now transparent.
ThemeService relays WPF-UI's ApplicationThemeManager.Changed, so the
charts also follow a theme change made by Windows ("Use Windows
setting"), once per burst of changes.

The smoke test applies the theme before showing the window, as a normal
start does (applying it afterwards hid the bug), and fails when page text
or icons lack the theme color or the chart text is not updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 06:58:47 +07:00
poli0981 ddd2aae297 Merge pull request #59 from poli0981/chore/sandbox-upgrade-test
eng: Windows Sandbox upgrade test for releases
2026-10-15 22:05:06 +07:00
poli0981andClaude Opus 5.5 9908ab2acd eng: Windows Sandbox upgrade test for releases
eng/Invoke-UpgradeTest.ps1 installs an older release in Windows Sandbox, adds the
1.x fixtures from tests/Fixtures/v1, applies the new full package with the installed
Update.exe (the in-app updater's path), and checks the data migration, the smoke
test, the uninstall and a fresh install, printing PASS or FAIL per check.

RELEASING.md uses it instead of manual steps and no longer lists assets.win.json
among the uploaded files (vpk upload does not upload it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 21:59:12 +07:00
30 changed files with 621 additions and 37 deletions

No files matched your search

+7
View File
@@ -36,6 +36,13 @@
"reportgenerator"
],
"rollForward": false
},
"dotnet-sonarscanner": {
"version": "12.0.0",
"commands": [
"dotnet-sonarscanner"
],
"rollForward": false
}
}
}
+1
View File
@@ -62,6 +62,7 @@ updates:
- "nuget-license"
- "microsoft.sbom.dotnettool"
- "dotnet-reportgenerator-globaltool"
- "dotnet-sonarscanner"
- "Microsoft.Windows.CsWin32"
- package-ecosystem: "dotnet-sdk"
+2 -1
View File
@@ -11,7 +11,8 @@ on:
branches: [master]
workflow_dispatch:
permissions: read-all
permissions:
contents: read
jobs:
analysis:
+82
View File
@@ -0,0 +1,82 @@
name: SonarCloud
# SonarQube Cloud analysis with SonarScanner for .NET: issues, security hotspots and test coverage
# for the C# code (test projects are recognized as tests), plus the workflows, YAML and PowerShell
# files. Informational: not a required check. It replaces SonarQube Cloud's Automatic Analysis,
# which must stay turned off for the project (the scan fails otherwise). Dependabot and fork pull
# requests cannot read the SONAR_TOKEN secret and skip the job.
on:
push:
branches: [master]
pull_request:
branches: [master]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
DOTNET_NOLOGO: true
DOTNET_CLI_TELEMETRY_OPTOUT: true
jobs:
sonarcloud:
name: sonarcloud
if: >-
github.actor != 'dependabot[bot]' &&
(github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)
runs-on: windows-latest
timeout-minutes: 45
steps:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0 # full history: SonarQube Cloud uses blame to find new code
persist-credentials: false
- name: Setup .NET
uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0
with:
global-json-file: global.json
- name: Restore
run: |
dotnet tool restore
dotnet restore AutoClick.slnx
- name: Build info
id: info
shell: pwsh
run: ./eng/Get-BuildInfo.ps1
# The product version lets the "previous version" new-code period start at the last version
# change; without it, new code would count from the project's first analysis.
# The scanner provisions its own Java runtime. Build output and restore files are not sources.
- name: Begin analysis
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
VERSION: ${{ steps.info.outputs.version }}
run: >-
dotnet sonarscanner begin /k:poli0981_autoclick /o:poli0981 /v:"$env:VERSION"
/d:sonar.host.url=https://sonarcloud.io /d:sonar.token="$env:SONAR_TOKEN"
"/d:sonar.cs.cobertura.reportsPaths=artifacts/test-results/**/*.cobertura.xml"
"/d:sonar.exclusions=**/bin/**,**/obj/**,artifacts/**"
# A plain build: the regular CI job already builds with warnings as errors.
- name: Build
run: dotnet build AutoClick.slnx -c Release --no-restore --no-incremental --disable-build-servers
- name: Test with coverage
run: >-
dotnet test --solution AutoClick.slnx -c Release --no-build
--results-directory artifacts/test-results --coverage --coverage-output-format cobertura
- name: End analysis
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: dotnet sonarscanner end /d:sonar.token="$env:SONAR_TOKEN"
+2 -2
View File
@@ -41,7 +41,7 @@ jobs:
SHA256: 8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8
run: |
archive="actionlint_${VERSION}_linux_amd64.tar.gz"
curl -fsSLo "$archive" "https://github.com/rhysd/actionlint/releases/download/v${VERSION}/${archive}"
curl --proto '=https' --tlsv1.2 -fsSLo "$archive" "https://github.com/rhysd/actionlint/releases/download/v${VERSION}/${archive}"
echo "${SHA256} ${archive}" | sha256sum --check --strict
tar -xzf "$archive" actionlint
@@ -59,7 +59,7 @@ jobs:
persist-credentials: false
- name: Run zizmor
uses: zizmorcore/zizmor-action@f9597c869b2e67095f9b527070297a13a6efe928 # v0.7.0
uses: zizmorcore/zizmor-action@85b2b9fb8e3325e7a23d7d0a9d7ba5ae0f999e3e # v0.7.1
with:
version: 1.31.0
# Fail the job on findings instead of uploading them to code scanning.
+21 -1
View File
@@ -8,6 +8,24 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## [Unreleased]
## [2.0.2] - 2026-10-22
Security hardening from a static analysis review (SonarQube Cloud). Settings, profiles and sessions are unchanged.
### Security
- When AutoClick runs as administrator, links, files and folders are now opened with the Explorer of the Windows folder. Before, Explorer was looked up by name, so a program called `explorer.exe` placed in the AutoClick folder could have been started with administrator rights.
## [2.0.1] - 2026-10-16
Fixes for the Dark theme. Settings, profiles and sessions are unchanged.
### Fixed
- Dark theme: page titles, labels, values and icons were drawn in black on the dark background and could hardly be read. They only became readable after switching to the Light theme and back.
- Dashboard: in the Dark theme the charts had a white background that hid their axis labels and legends.
- With the theme set to *Use Windows setting*, the dashboard charts now also follow Windows when it switches between light and dark.
## [2.0.0] - 2026-10-15
AutoClick rebuilt: a new Fluent interface, no administrator rights needed for most games, and fixes for every known 1.x bug. Settings, profiles and hotkeys from 1.x carry over automatically.
@@ -348,7 +366,9 @@ Platform bridge release: no feature or data-format changes, so it is safe to upd
- `ManualResetEventSlim` for pause/resume, `CancellationToken` for stop
- `DispatcherTimer` for UI refresh and process monitoring
[Unreleased]: https://github.com/poli0981/autoclick/compare/v2.0.0...HEAD
[Unreleased]: https://github.com/poli0981/autoclick/compare/v2.0.2...HEAD
[2.0.2]: https://github.com/poli0981/autoclick/compare/v2.0.1...v2.0.2
[2.0.1]: https://github.com/poli0981/autoclick/compare/v2.0.0...v2.0.1
[2.0.0]: https://github.com/poli0981/autoclick/compare/v1.3.4...v2.0.0
[1.3.4]: https://github.com/poli0981/autoclick/compare/v1.3.3...v1.3.4
[1.3.3]: https://github.com/poli0981/autoclick/compare/v1.3.2...v1.3.3
+7 -2
View File
@@ -33,9 +33,14 @@ dotnet jb inspectcode AutoClick.slnx --no-build --properties:Configuration=Relea
- Adding a `<Resource>` item is not picked up by an incremental build: rebuild with `--no-incremental`.
- CommunityToolkit.Mvvm requires the Windows SDK projection at build time; the UI project removes the projection DLL from the output afterwards (`DropWindowsSdkProjection`). Do not set `IncludeWindowsSDKRefFrameworkReferences=false`.
- WPF-UI's `NavigationView` with a `LeftFluent` pane must not have the title bar overlaid on it (the first item would sit under the title bar); the title bar has its own grid row.
- The smoke test uses `%TEMP%\AutoClick-smoke`; a normal run creates `%LocalAppData%\AutoClick`, so clean that up after local manual tests.
- Every page sets `Foreground="{DynamicResource TextFillColorPrimaryBrush}"` on its `<Page>`. WPF-UI's implicit `Page` style never reaches page subclasses, and the navigation frame passes the window's text color on only after a theme change, so in 2.0.0 text and icons without a color of their own were black in Dark until the theme was switched. The smoke test checks it and, like `AppCoordinator`, applies the theme before showing the window (applied afterwards, it hides the bug).
- Theme colors come from `{DynamicResource …Brush}`. `ui:TextBlock Appearance` looks its brush up once and does not follow theme changes.
- LiveCharts' WPF charts always use the light LiveCharts theme and clear their canvas white unless `Background` is a solid brush: keep `Background="Transparent"` and paint the text from the WPF-UI theme (`DashboardViewModel.ApplyThemeAndTexts`).
- `ThemeService.ThemeChanged` relays WPF-UI's `ApplicationThemeManager.Changed`, so it also fires when Windows switches the theme; it is raised asynchronously, once per burst.
- The smoke test uses `%TEMP%\AutoClick-smoke`. A normal run uses `%LocalAppData%\AutoClick`, which is also the folder of an installed AutoClick (and a running installed copy takes over through the single-instance pipe): delete it after local manual tests only if it did not exist before.
- SonarQube Cloud runs in CI (`.github/workflows/sonarcloud.yml`, secret `SONAR_TOKEN`). Its Automatic Analysis must stay off, or the scan fails; it also counted `tests/` as product code and could not see CsWin32's generated code. Suppress a finding only with `[SuppressMessage]` and a `Justification`.
- Commits in this repository are GPG-signed; never bypass signing.
## Releasing
Tag `vX.Y.Z` → the release workflow uploads a **draft** (full package, SBOM, attestations) → test the update in Windows Sandbox from the previous releases → publish from the maintainer's account (`gh release edit vX.Y.Z --draft=false`). Tags are protected: fix mistakes with a new patch version. Details: [docs/RELEASING.md](docs/RELEASING.md).
Tag `vX.Y.Z` → the release workflow uploads a **draft** (full package, SBOM, attestations) → test the update from the previous releases in Windows Sandbox (`eng/Invoke-UpgradeTest.ps1`) → publish from the maintainer's account (`gh release edit vX.Y.Z --draft=false`). Tags are protected: fix mistakes with a new patch version. Details: [docs/RELEASING.md](docs/RELEASING.md).
+3
View File
@@ -29,6 +29,8 @@ The design is described in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md); the tes
| **dependency-review** | The pull request adds no vulnerable package and no disallowed license (build and test tools that are never shipped are exempt; the list is in the workflow) | GitHub only |
| **analyze (csharp)** | CodeQL security analysis | GitHub only |
SonarQube Cloud also analyzes every pull request from this repository (the **sonarcloud** check, not required): issues, security hotspots and test coverage of the changed code. Pull requests from forks and Dependabot skip it because they cannot read the `SONAR_TOKEN` secret.
Local equivalents of build-test and dead-code (PowerShell):
```powershell
@@ -58,6 +60,7 @@ Please also:
- **File formats are a contract:** profiles keep the 1.x JSON layout (property names, enums as numbers) so 1.x can still read them; settings and sessions are versioned (`schemaVersion`) and older versions must keep loading. Add tests with fixture files under `tests/Fixtures` for any change.
- **Win32:** add new APIs to `src/AutoClick.Win32/NativeMethods.txt` (CsWin32). Anything that converts game coordinates runs inside a `DpiScope` for the game window.
- **No unused code:** the dead-code check fails on it. For a deliberate exception, write `// ReSharper disable once <rule>` with a reason.
- **SonarQube Cloud findings** are fixed, or, when the code is right as it is, suppressed with `[SuppressMessage("Category", "Sxxxx:Title", Justification = "why")]`.
## Translations
+1 -1
View File
@@ -2,7 +2,7 @@
<!-- Single source of truth for the product version (release tags must match it). -->
<PropertyGroup>
<Version>2.0.0</Version>
<Version>2.0.2</Version>
<AssemblyVersion>$(Version).0</AssemblyVersion>
<FileVersion>$(Version).0</FileVersion>
<InformationalVersion>$(Version)</InformationalVersion>
+2 -2
View File
@@ -29,7 +29,7 @@ AutoClick.UI net10.0-windows10.0.19041 WPF + WPF-UI, MVVM (CommunityTo
4. Single instance: a named mutex and a named pipe, both with an ACL for the current user. A second launch asks the first one to show its window and exits.
5. Generic Host with dependency injection (`ValidateOnBuild`), then `App.Run()`.
`--smoke-test` skips 3-4, uses `%TEMP%\AutoClick-smoke` as data folder, opens every page in every theme and language plus the dialogs and a heatmap, and exits 1 on any binding error.
`--smoke-test` skips 3-4, uses `%TEMP%\AutoClick-smoke` as data folder, applies the theme before showing the window as a normal start does, opens every page in every theme and language plus the dialogs and a heatmap, checks that page text and chart text follow the theme, and exits 1 on any binding error or wrong text color.
## Click engine
@@ -56,7 +56,7 @@ Everything lives in `%LocalAppData%\AutoClick`, which is also Velopack's install
## User interface
- **Shell:** WPF-UI `FluentWindow` with a title bar row, a `NavigationView` (Queue, Dashboard, Settings, About), info bars for app-wide notices, a `ContentDialogHost` and a snackbar presenter. Pages and view models are singletons from the container.
- **Shell:** WPF-UI `FluentWindow` with a title bar row, a `NavigationView` (Queue, Dashboard, Settings, About), info bars for app-wide notices, a `ContentDialogHost` and a snackbar presenter. Pages and view models are singletons from the container. Each page sets its own themed `Foreground`, because WPF-UI's implicit `Page` style does not apply to page subclasses.
- **MVVM:** CommunityToolkit.Mvvm source generators (`[ObservableProperty]` partial properties, `[RelayCommand]`). View models use services; dialogs and file pickers go through `DialogService`.
- **One clock:** `UiTicker` raises a single once-per-second tick for statistics, the scheduler, window checks and the dashboard (1.x had five timers).
- **Localization:** `LocalizationService` reads `Strings*.resx`. XAML binds through `{l:Loc Key}` (an indexer binding), so changing the language updates the whole UI without a restart.
+1 -1
View File
@@ -32,7 +32,7 @@ The checks CI runs on every pull request, and how to run them locally, are liste
|------|---------|
| **`tools/AutoClick.ClickTarget`** | A window that logs every mouse and keyboard message it receives (client coordinates, virtual-key and scan codes). `--dpi unaware\|system\|pmv2` changes its DPI awareness to test coordinate mapping, `--log <file>` writes the log to a file. |
| **`AutoClick.UI.exe --smoke-test`** | Opens every page in every theme and language, the dialogs and a heatmap overlay, and fails on any binding error. Uses `%TEMP%\AutoClick-smoke` instead of the real data folder. |
| **Windows Sandbox** | Install and update tests from an older release (for example 1.3.3 → 2.0.0), without touching the development machine. |
| **`eng/Invoke-UpgradeTest.ps1`** | Update test in Windows Sandbox, without touching the development machine: installs an older release (for example 1.3.3), updates it to a new package with the installed updater, and checks the data migration, the uninstall and a fresh install. Used before every release ([RELEASING.md](RELEASING.md)). |
## Tested Games
+11 -3
View File
@@ -28,10 +28,10 @@ The tag starts [`release.yml`](../.github/workflows/release.yml). Its **build**
1. Checks that the tag is `vX.Y.Z`, matches the project version, and that the `vpk` CLI pinned in `.config/dotnet-tools.json` matches the Velopack library.
2. Extracts the release notes from `CHANGELOG.md`.
3. Publishes the app (self-contained `win-x64`), writes `THIRD-PARTY-NOTICES.txt` into it (failing on any license outside the policy) and runs the `--smoke-test` of the published exe.
4. Packs with `vpk pack` (full package only): `AutoClick-win-Setup.exe`, `AutoClick-win-Portable.zip`, `AutoClick-X.Y.Z-full.nupkg`, `releases.win.json`, `assets.win.json`, `RELEASES`.
4. Packs with `vpk pack` (full package only): `AutoClick-win-Setup.exe`, `AutoClick-win-Portable.zip`, `AutoClick-X.Y.Z-full.nupkg`, and the update feed `releases.win.json` plus `RELEASES` (read by older clients).
5. Generates an SPDX SBOM and creates build provenance and SBOM attestations for the installer, the portable zip and the package.
The **upload draft release** job then uploads everything (plus `AutoClick-X.Y.Z.spdx.json`) to a draft release named `AutoClick vX.Y.Z`.
The **upload draft release** job then uploads these files (plus `AutoClick-X.Y.Z.spdx.json`) to a draft release named `AutoClick vX.Y.Z`.
To rebuild an existing tag after a transient failure, use **Actions → Release → Run workflow** with the tag; it builds that tag and merges into the existing draft.
@@ -46,7 +46,15 @@ Until it is published, the release is invisible to users and to the updater.
gh attestation verify AutoClick-win-Setup.exe -R poli0981/autoclick
```
3. In **Windows Sandbox**: install the previous release, add some settings and profiles, update to the draft's package with the installed `Update.exe`, and check that the new version starts, the data is still there, and a fresh install and an uninstall work too.
3. Test the update in **Windows Sandbox** (nothing is installed on your machine), from the previous release and from older ones users may still have. In PowerShell 7:
```powershell
gh release download v1.3.4 -p AutoClick-win-Setup.exe -D artifacts/upgrade-test/old
gh release download vX.Y.Z -p 'AutoClick-*-full.nupkg' -p AutoClick-win-Setup.exe -D artifacts/upgrade-test/new
./eng/Invoke-UpgradeTest.ps1 -OldSetup artifacts/upgrade-test/old/AutoClick-win-Setup.exe -NewDir artifacts/upgrade-test/new
```
The script installs the old release, adds 1.x settings and a profile, updates with the installed `Update.exe` (as the in-app updater does), starts the new version once (data migration) and runs its smoke test, then uninstalls and checks a fresh install. It prints PASS or FAIL for each check and keeps the logs in `artifacts/upgrade-test/runs`.
## 4. Publish
+1 -1
View File
@@ -32,7 +32,7 @@ Các bước kiểm tra CI chạy cho mỗi pull request, và cách chạy chún
|---------|----------|
| **`tools/AutoClick.ClickTarget`** | Cửa sổ ghi lại mọi message chuột và bàn phím nhận được (toạ độ client, mã phím ảo và scan code). `--dpi unaware\|system\|pmv2` đổi chế độ DPI để kiểm tra quy đổi toạ độ, `--log <file>` ghi log ra file. |
| **`AutoClick.UI.exe --smoke-test`** | Mở mọi trang ở mọi theme và ngôn ngữ, các hộp thoại và lớp heatmap, báo lỗi nếu có binding hỏng. Dùng `%TEMP%\AutoClick-smoke` thay cho thư mục dữ liệu thật. |
| **Windows Sandbox** | Kiểm thử cài đặt và cập nhật từ bản cũ (ví dụ 1.3.3 → 2.0.0) mà không ảnh hưởng máy phát triển. |
| **`eng/Invoke-UpgradeTest.ps1`** | Kiểm thử cập nhật trong Windows Sandbox, không ảnh hưởng máy phát triển: cài một bản cũ (ví dụ 1.3.3), cập nhật lên gói mới bằng trình cập nhật đã cài, rồi kiểm tra việc chuyển dữ liệu, gỡ cài đặt và cài mới. Chạy trước mỗi lần phát hành ([RELEASING.md](../../RELEASING.md)). |
## Game Đã Kiểm Thử
+3 -2
View File
@@ -3,8 +3,9 @@
Runs the published app with --smoke-test and fails if it does not exit 0 in time.
.DESCRIPTION
--smoke-test builds the DI graph, opens every page in every theme and language, the
dialogs and a heatmap overlay, and exits 1 on any exception or data-binding error. It uses
%TEMP%\AutoClick-smoke as its data folder; on failure the newest log from there is printed.
dialogs and a heatmap overlay, checks that page and chart text follow the theme, and exits 1
on any exception, data-binding error or wrong text color. It uses %TEMP%\AutoClick-smoke as
its data folder; on failure the newest log from there is printed.
#>
[CmdletBinding()]
param(
+119
View File
@@ -0,0 +1,119 @@
<#
.SYNOPSIS
Tests updating an installed older release to a new release, inside Windows Sandbox.
.DESCRIPTION
Installs the old release with its Setup.exe, adds 1.x user data (tests/Fixtures/v1), applies
the new full package with the installed Update.exe (the path the in-app updater takes), starts
the new version once (settings migration), runs its smoke test, uninstalls, and installs the
new Setup.exe on a clean profile (eng/upgrade-test/run-upgrade-test.ps1). Nothing is installed
on this machine. Needs the Windows Sandbox feature; a run takes about two minutes.
Prints one line per check and exits 1 if any fails. Logs and result.json stay in the run folder.
.EXAMPLE
gh release download v1.3.4 -p AutoClick-win-Setup.exe -D artifacts/upgrade-test/old
gh release download v2.0.1 -p 'AutoClick-*-full.nupkg' -p AutoClick-win-Setup.exe -D artifacts/upgrade-test/new
./eng/Invoke-UpgradeTest.ps1 -OldSetup artifacts/upgrade-test/old/AutoClick-win-Setup.exe -NewDir artifacts/upgrade-test/new
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string] $OldSetup,
[Parameter(Mandatory)] [string] $NewDir,
[string] $OutDir = (Join-Path $PSScriptRoot '..' 'artifacts' 'upgrade-test' 'runs'),
[int] $TimeoutMinutes = 15
)
$ErrorActionPreference = 'Stop'
$sandboxExe = Join-Path $env:WINDIR 'System32\WindowsSandbox.exe'
if (-not (Test-Path -LiteralPath $sandboxExe)) {
throw 'Windows Sandbox is not installed: enable the optional feature Containers-DisposableClientVM.'
}
$sandboxProcesses = 'WindowsSandboxRemoteSession', 'WindowsSandboxClient'
if (Get-Process $sandboxProcesses -ErrorAction SilentlyContinue) {
throw 'Windows Sandbox is already running; only one instance can run at a time.'
}
$oldSetupPath = (Resolve-Path -LiteralPath $OldSetup).Path
$newDirPath = (Resolve-Path -LiteralPath $NewDir).Path
$package = Get-ChildItem -LiteralPath $newDirPath -Filter 'AutoClick-*-full.nupkg' | Select-Object -First 1
$newSetup = Join-Path $newDirPath 'AutoClick-win-Setup.exe'
if (-not $package -or -not (Test-Path -LiteralPath $newSetup)) {
throw "$newDirPath must contain AutoClick-X.Y.Z-full.nupkg and AutoClick-win-Setup.exe."
}
$version = $package.Name -replace '^AutoClick-(.+)-full\.nupkg$', '$1'
$expectedFileVersion = ($version -split '-')[0] + '.0'
# Everything the sandbox sees lives in one run folder, mapped to C:\test.
$fixtures = Join-Path $PSScriptRoot '..' 'tests' 'Fixtures' 'v1'
$work = Join-Path ([IO.Path]::GetFullPath($OutDir)) (Get-Date -Format 'yyyyMMdd-HHmmss')
foreach ($dir in 'old', 'new', 'fixtures\profiles', 'results') {
New-Item -ItemType Directory -Force (Join-Path $work $dir) | Out-Null
}
Copy-Item -LiteralPath $oldSetupPath (Join-Path $work 'old')
Copy-Item -LiteralPath $package.FullName, $newSetup (Join-Path $work 'new')
Copy-Item (Join-Path $fixtures 'settings.json') (Join-Path $work 'fixtures')
Copy-Item (Join-Path $fixtures 'profiles\*.json') (Join-Path $work 'fixtures\profiles')
Copy-Item (Join-Path $PSScriptRoot 'upgrade-test\run-upgrade-test.ps1') $work
$wsb = Join-Path $work 'upgrade-test.wsb'
@"
<Configuration>
<VGpu>Disable</VGpu>
<Networking>Disable</Networking>
<ClipboardRedirection>Disable</ClipboardRedirection>
<PrinterRedirection>Disable</PrinterRedirection>
<MappedFolders>
<MappedFolder>
<HostFolder>$work</HostFolder>
<SandboxFolder>C:\test</SandboxFolder>
<ReadOnly>false</ReadOnly>
</MappedFolder>
</MappedFolders>
<LogonCommand>
<Command>powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\test\run-upgrade-test.ps1</Command>
</LogonCommand>
</Configuration>
"@ | Set-Content -LiteralPath $wsb -Encoding utf8
Write-Host "Windows Sandbox: $(Split-Path $oldSetupPath -Leaf) (old) -> $version, run folder $work"
Start-Process -FilePath $sandboxExe -ArgumentList "`"$wsb`""
$resultFile = Join-Path $work 'results\result.json'
$deadline = (Get-Date).AddMinutes($TimeoutMinutes)
while (-not (Test-Path -LiteralPath $resultFile) -and (Get-Date) -lt $deadline) { Start-Sleep -Seconds 5 }
if (-not (Test-Path -LiteralPath $resultFile)) {
throw "No result after $TimeoutMinutes minutes; see $work\results\transcript.txt."
}
# The sandbox shuts itself down after writing the result.
$closeBy = (Get-Date).AddMinutes(2)
while ((Get-Process $sandboxProcesses -ErrorAction SilentlyContinue) -and (Get-Date) -lt $closeBy) { Start-Sleep -Seconds 3 }
$r = Get-Content -LiteralPath $resultFile -Raw | ConvertFrom-Json
$v1 = Get-Content -LiteralPath (Join-Path $fixtures 'settings.json') -Raw | ConvertFrom-Json
$warnings = @($r.firstRunWarnings | Where-Object { $_ })
$checks = [ordered]@{
'Old release installs' = $r.oldSetupExit -eq 0 -and [bool]$r.oldVersion
"Installed Update.exe applies $version" = $r.applyExit -eq 0 -and $r.newVersion -eq $expectedFileVersion
'New version starts and migrates the 1.x settings' = $r.firstRunAlive -and $r.settingsV2Exists
'Hotkeys and language carried over' = $r.migratedHotkeys -eq "$($v1.hotkeys.pauseResume) / $($v1.hotkeys.stopAll) / $($v1.hotkeys.startAll)" -and $r.migratedLanguage -eq $v1.language
'Upgraded install keeps administrator mode' = $r.migratedAlwaysRunAsAdmin -eq $true -and $r.migratedShowAdminNotice -eq $true
'1.x data untouched and backed up' = $r.v1DataUntouched -and $r.v1BackupExists
'No warning or error in the first-run log' = $warnings.Count -eq 0
'Smoke test' = $r.smokeExit -eq 0
'Uninstall' = $r.uninstallExit -eq 0
'Fresh install starts' = $r.newSetupExit -eq 0 -and $r.freshInstallVersion -eq $expectedFileVersion -and $r.freshFirstRunAlive
'Fresh install does not use administrator mode' = $r.freshAlwaysRunAsAdmin -eq $false
}
$failed = 0
foreach ($check in $checks.GetEnumerator()) {
$ok = [bool]$check.Value
if (-not $ok) { $failed++ }
Write-Host ("{0} {1}" -f ($ok ? 'PASS' : 'FAIL'), $check.Key)
}
$warnings | ForEach-Object { Write-Host " log: $_" }
Write-Host "Details: $resultFile"
if ($failed) {
Write-Host "$failed of $($checks.Count) checks failed." -ForegroundColor Red
exit 1
}
Write-Host "All $($checks.Count) checks passed."
+113
View File
@@ -0,0 +1,113 @@
<#
.SYNOPSIS
Runs inside Windows Sandbox (Windows PowerShell 5.1); started by eng/Invoke-UpgradeTest.ps1.
.DESCRIPTION
Installs the old release with its Setup.exe, adds 1.x user data, applies the new full package
with the installed Update.exe (the path the in-app updater takes), starts the new version once
to migrate the data, runs its smoke test, uninstalls, then installs the new Setup.exe and starts
it once on the clean profile. Writes C:\test\results\result.json and shuts the sandbox down.
Inputs: C:\test\old\*Setup.exe, C:\test\new\*-full.nupkg + *Setup.exe, C:\test\fixtures.
#>
$ErrorActionPreference = 'Continue'
$root = 'C:\test'
$out = Join-Path $root 'results'
New-Item -ItemType Directory -Force $out | Out-Null
Start-Transcript -Path (Join-Path $out 'transcript.txt') | Out-Null
$result = [ordered]@{ started = (Get-Date).ToString('o') }
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$result.elevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
$app = Join-Path $env:LOCALAPPDATA 'AutoClick'
function Wait-Proc($p, $seconds) {
if ($p.WaitForExit($seconds * 1000)) { return $p.ExitCode }
try { $p.Kill() } catch {}
return 'timeout'
}
function Stop-App { Get-Process AutoClick.UI -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue }
function Get-V1Hashes {
$files = @(Get-ChildItem (Join-Path $app 'settings.json'), (Join-Path $app 'profiles\*.json') -ErrorAction SilentlyContinue)
($files | Sort-Object FullName | ForEach-Object { "$($_.Name)=$((Get-FileHash $_.FullName).Hash)" }) -join ';'
}
# Callers wrap the result in @(): a function returning an empty array returns $null.
function Get-LogLines($pattern) {
Get-Content (Join-Path $app 'logs\*.log') -ErrorAction SilentlyContinue | Where-Object { $_ -match $pattern } | ForEach-Object { [string]$_ }
}
# 1. Install the old release.
$old = Get-ChildItem (Join-Path $root 'old') -Filter '*Setup.exe' | Select-Object -First 1
$p = Start-Process $old.FullName -ArgumentList '--silent', '--log', (Join-Path $out 'setup-old.log') -PassThru
$result.oldSetupExit = Wait-Proc $p 300
Start-Sleep -Seconds 8
Stop-App
$result.oldVersion = (Get-Item (Join-Path $app 'current\AutoClick.UI.exe') -ErrorAction SilentlyContinue).VersionInfo.FileVersion
# 2. Add 1.x user data (what an existing user has on disk).
Copy-Item (Join-Path $root 'fixtures\*') $app -Recurse -Force
$result.v1DataBefore = Get-V1Hashes
# 3. Apply the new full package with the installed (old) Update.exe.
$pkgDir = Join-Path $app 'packages'
New-Item -ItemType Directory -Force $pkgDir | Out-Null
$newPkg = Get-ChildItem (Join-Path $root 'new') -Filter '*-full.nupkg' | Select-Object -First 1
Copy-Item $newPkg.FullName $pkgDir -Force
$pkgPath = Join-Path $pkgDir $newPkg.Name
$p = Start-Process (Join-Path $app 'Update.exe') -ArgumentList 'apply', '--norestart', '--silent', '--package', $pkgPath, '--log', (Join-Path $out 'update-apply.log') -PassThru
$result.applyExit = Wait-Proc $p 600
Start-Sleep -Seconds 5
Stop-App
$result.newVersion = (Get-Item (Join-Path $app 'current\AutoClick.UI.exe') -ErrorAction SilentlyContinue).VersionInfo.FileVersion
# 4. First start of the new version: migrates the 1.x data. The logon script runs elevated, so the
# "keep running as administrator" setting of an upgraded install does not relaunch.
$p = Start-Process (Join-Path $app 'current\AutoClick.UI.exe') -PassThru
Start-Sleep -Seconds 15
$result.firstRunAlive = -not $p.HasExited
Stop-App
Start-Sleep -Seconds 2
$v2 = Join-Path $app 'settings.v2.json'
$result.settingsV2Exists = Test-Path $v2
if ($result.settingsV2Exists) {
$s = Get-Content $v2 -Raw | ConvertFrom-Json
$result.migratedHotkeys = "$($s.hotkeys.pauseResume) / $($s.hotkeys.stopAll) / $($s.hotkeys.startAll)"
$result.migratedLanguage = $s.language
$result.migratedAlwaysRunAsAdmin = $s.alwaysRunAsAdmin
$result.migratedShowAdminNotice = $s.showAdminModeNotice
}
$result.v1BackupExists = Test-Path (Join-Path $app 'backup\settings.v1.json')
$result.v1DataAfter = Get-V1Hashes
$result.v1DataUntouched = ($result.v1DataBefore -eq $result.v1DataAfter) -and ($result.v1DataBefore -ne '')
Copy-Item (Join-Path $app 'logs\*.log') $out -ErrorAction SilentlyContinue
$result.firstRunWarnings = @(Get-LogLines '\[(WRN|ERR|FTL)\]')
# 5. Smoke test of the updated app (uses its own temporary data folder).
$p = Start-Process (Join-Path $app 'current\AutoClick.UI.exe') -ArgumentList '--smoke-test' -PassThru
$result.smokeExit = Wait-Proc $p 180
# 6. Uninstall: removes the install root, which is also the data folder.
$p = Start-Process (Join-Path $app 'Update.exe') -ArgumentList 'uninstall', '--silent', '--log', (Join-Path $out 'uninstall.log') -PassThru
$result.uninstallExit = Wait-Proc $p 300
Start-Sleep -Seconds 5
$result.afterUninstallFiles = @(Get-ChildItem $app -Recurse -Force -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName.Substring($app.Length + 1) })
# 7. Fresh install of the new Setup.exe. A silent setup does not start the app, so start it once
# like a new user would: it must not turn on administrator mode.
$new = Get-ChildItem (Join-Path $root 'new') -Filter '*Setup.exe' | Select-Object -First 1
$p = Start-Process $new.FullName -ArgumentList '--silent', '--log', (Join-Path $out 'setup-new.log') -PassThru
$result.newSetupExit = Wait-Proc $p 300
Start-Sleep -Seconds 5
Stop-App
$result.freshInstallVersion = (Get-Item (Join-Path $app 'current\AutoClick.UI.exe') -ErrorAction SilentlyContinue).VersionInfo.FileVersion
$p = Start-Process (Join-Path $app 'current\AutoClick.UI.exe') -PassThru
Start-Sleep -Seconds 12
$result.freshFirstRunAlive = -not $p.HasExited
Stop-App
Start-Sleep -Seconds 2
$fresh = Get-Content (Join-Path $app 'settings.v2.json') -Raw -ErrorAction SilentlyContinue | ConvertFrom-Json
$result.freshAlwaysRunAsAdmin = $fresh.alwaysRunAsAdmin
$result.freshStartupLines = @(Get-LogLines 'ready \(settings')
$result.finished = (Get-Date).ToString('o')
$result | ConvertTo-Json -Depth 4 | Set-Content -Path (Join-Path $out 'result.json') -Encoding UTF8
Stop-Transcript | Out-Null
shutdown.exe /s /t 5
+1 -1
View File
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "10.0.401",
"version": "10.0.402",
"rollForward": "latestFeature"
},
"test": {
@@ -116,7 +116,9 @@ public sealed class ClickSession : IDisposable
internal void Start()
{
_logger.LogInformation("Auto-click started for {Process} ({Points} steps)", _info.ProcessName, _info.Points.Count);
Completion = Task.Run(RunAsync);
// Not the session token: a stop requested before the loop starts would cancel the task
// without running it, and the session would never report that it stopped.
Completion = Task.Run(RunAsync, CancellationToken.None);
}
public void Pause()
+136 -6
View File
@@ -1,6 +1,9 @@
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using AutoClick.Core.Abstractions;
using AutoClick.Core.Models;
@@ -10,25 +13,39 @@ using AutoClick.UI.ViewModels;
using AutoClick.UI.Views;
using AutoClick.UI.Views.Dialogs;
using AutoClick.UI.Views.Pages;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SkiaSharp;
using Wpf.Ui.Appearance;
using IconElement = Wpf.Ui.Controls.IconElement;
namespace AutoClick.UI.Services;
/// <summary>
/// <c>--smoke-test</c> (CI and release builds): opens every page in every theme and language,
/// the dialogs, the notices and a heatmap overlay, then exits with 0, or 1 on any exception or
/// data-binding error. Runs with a separate data folder, never the user's.
/// the dialogs, the notices and a heatmap overlay, and checks that the text of the pages and the
/// charts follows the theme. Exits with 0, or 1 on any exception, data-binding error or wrong
/// text color. Runs with a separate data folder, never the user's.
/// </summary>
public sealed class SmokeTest(
MainWindow window,
MainWindowViewModel mainViewModel,
ThemeService theme,
QueueViewModel queue,
DashboardViewModel dashboard,
OverlayService overlays,
IServiceProvider services,
ILogger<SmokeTest> logger)
{
private static readonly Type[] Pages = [typeof(QueuePage), typeof(DashboardPage), typeof(SettingsPage), typeof(AboutPage)];
private static readonly AppTheme[] Themes = [AppTheme.Light, AppTheme.Dark, AppTheme.HighContrast, AppTheme.System];
// Starts in Dark like a fresh start with Windows in dark mode (2.0.0 drew page text black there).
private static readonly AppTheme[] Themes = [AppTheme.Dark, AppTheme.Light, AppTheme.Dark, AppTheme.HighContrast, AppTheme.System];
// Following Windows, SystemThemeWatcher applies a theme through WPF-UI, not through ThemeService.
private static readonly ApplicationTheme[] WindowsThemes = [ApplicationTheme.Dark, ApplicationTheme.Light];
private int _colorErrors;
public async Task RunAsync()
{
@@ -41,7 +58,11 @@ public sealed class SmokeTest(
var views = 0;
try
{
// As in AppCoordinator.Start, the theme is applied before the window is shown: a theme
// change on a shown window hid the missing page Foreground of 2.0.0.
Application.Current.MainWindow = window;
new WindowInteropHelper(window).EnsureHandle();
theme.Apply(Themes[0], window);
window.Show();
var handle = new WindowInteropHelper(window).Handle;
@@ -56,7 +77,11 @@ public sealed class SmokeTest(
foreach (var appTheme in Themes)
{
theme.Apply(appTheme, window);
if (appTheme != theme.Current)
{
theme.Apply(appTheme, window);
}
foreach (var language in AppSettings.SupportedLanguages)
{
LocalizationService.Instance.SetLanguage(language);
@@ -65,8 +90,23 @@ public sealed class SmokeTest(
window.Navigate(page);
await RenderAsync();
views++;
// Colors do not depend on the language.
if (language == AppSettings.SupportedLanguages[0])
{
CheckPageColors((Page)services.GetRequiredService(page), appTheme.ToString());
}
}
}
CheckChartColors(appTheme.ToString());
}
foreach (var windowsTheme in WindowsThemes)
{
ApplicationThemeManager.Apply(windowsTheme);
await RenderAsync();
CheckChartColors($"Windows {windowsTheme}");
}
await ShowStandaloneAsync(new GamePickerView(new GamePickerViewModel(() =>
@@ -88,8 +128,9 @@ public sealed class SmokeTest(
logger.LogError("Binding error: {Error}", error);
}
exitCode = bindingErrors.Errors.Count == 0 ? 0 : 1;
logger.LogInformation("Smoke test finished: {Views} page views, {Errors} binding error(s)", views, bindingErrors.Errors.Count);
exitCode = bindingErrors.Errors.Count == 0 && _colorErrors == 0 ? 0 : 1;
logger.LogInformation("Smoke test finished: {Views} page views, {Errors} binding error(s), {ColorErrors} color error(s)",
views, bindingErrors.Errors.Count, _colorErrors);
}
catch (Exception ex)
{
@@ -125,6 +166,95 @@ public sealed class SmokeTest(
host.Close();
}
/// <summary>
/// Text and icons without a color of their own take the color of the page. WPF-UI's implicit
/// Page style never reaches page subclasses and the navigation frame does not pass the window's
/// color on, so each page sets a themed Foreground; without it this text was black (2.0.0).
/// </summary>
private void CheckPageColors(Page page, string themeName)
{
var wrong = new List<string>();
if (ForegroundSource(page) != BaseValueSource.Local)
{
wrong.Add("the page sets no Foreground");
}
var expected = (Application.Current.TryFindResource("TextFillColorPrimaryBrush") as SolidColorBrush)?.Color;
foreach (var element in Descendants(page).OfType<FrameworkElement>())
{
if (element is not (TextBlock or IconElement) || !element.IsVisible)
{
continue;
}
var source = ForegroundSource(element);
var color = (element.GetValue(TextElement.ForegroundProperty) as SolidColorBrush)?.Color;
if (source == BaseValueSource.Default
|| (source == BaseValueSource.Inherited && ForegroundProvider(element) == page && color != expected))
{
wrong.Add($"{(element as TextBlock)?.Text ?? element.GetType().Name} ({color})");
}
}
if (wrong.Count > 0)
{
_colorErrors++;
logger.LogError("Text without the theme color on {Page} ({Theme}), {Count} element(s): {Examples}",
page.GetType().Name, themeName, wrong.Count, string.Join("; ", wrong.Take(5)));
}
}
/// <summary>The dashboard paints chart text with theme colors read on <see cref="ThemeService.ThemeChanged"/>.</summary>
private void CheckChartColors(string themeName)
{
if (Application.Current.TryFindResource("TextFillColorSecondaryBrush") is not SolidColorBrush { Color: var expected })
{
return;
}
var actual = dashboard.LegendTextPaint.Color;
if (actual != new SKColor(expected.R, expected.G, expected.B, expected.A))
{
_colorErrors++;
logger.LogError("Chart text color not updated ({Theme}): {Actual}, expected {Expected}", themeName, actual, expected);
}
}
// The nearest ancestor that has its own Foreground, the one the element inherits from.
private static DependencyObject? ForegroundProvider(DependencyObject element)
{
var current = InheritanceParent(element);
while (current is not null && ForegroundSource(current) == BaseValueSource.Inherited)
{
current = InheritanceParent(current);
}
return current;
}
// WPF inherits along the logical parent when there is one, otherwise along the visual parent.
private static DependencyObject? InheritanceParent(DependencyObject element) =>
LogicalTreeHelper.GetParent(element) ?? (element is Visual ? VisualTreeHelper.GetParent(element) : null);
private static BaseValueSource ForegroundSource(DependencyObject element) =>
DependencyPropertyHelper.GetValueSource(element, TextElement.ForegroundProperty).BaseValueSource;
private static IEnumerable<DependencyObject> Descendants(DependencyObject root)
{
var pending = new Stack<DependencyObject>();
pending.Push(root);
while (pending.Count > 0)
{
var current = pending.Pop();
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(current); i++)
{
var child = VisualTreeHelper.GetChild(current, i);
pending.Push(child);
yield return child;
}
}
}
private sealed class BindingErrorListener : TraceListener
{
public List<string> Errors { get; } = [];
+27 -2
View File
@@ -1,4 +1,5 @@
using System.Windows;
using System.Windows.Threading;
using AutoClick.Core.Models;
using Wpf.Ui.Appearance;
@@ -8,8 +9,19 @@ namespace AutoClick.UI.Services;
public sealed class ThemeService
{
private Window? _watchedWindow;
private bool _changeQueued;
/// <summary>Raised after the theme resources changed (charts re-read their colors).</summary>
public ThemeService()
{
// WPF-UI raises this for every theme it applies: ours, and SystemThemeWatcher's when the
// theme follows Windows (several times for one switch in Windows).
ApplicationThemeManager.Changed += (_, _) => QueueThemeChanged();
}
/// <summary>
/// Raised after the theme resources changed, including a change made by Windows (charts re-read
/// their colors). A burst of changes raises it once, after the work already queued on the UI thread.
/// </summary>
public event EventHandler? ThemeChanged;
public AppTheme Current { get; private set; } = AppTheme.System;
@@ -44,7 +56,20 @@ public sealed class ThemeService
};
ApplicationThemeManager.Apply(wpfTheme);
}
}
ThemeChanged?.Invoke(this, EventArgs.Empty);
private void QueueThemeChanged()
{
if (_changeQueued)
{
return;
}
_changeQueued = true;
_ = Application.Current.Dispatcher.InvokeAsync(() =>
{
_changeQueued = false;
ThemeChanged?.Invoke(this, EventArgs.Empty);
}, DispatcherPriority.Background);
}
}
@@ -34,6 +34,7 @@ public sealed class SingleInstance : IDisposable
/// <summary>Same names as v1, so v1 and v2 never run side by side.</summary>
[SuppressMessage("Security", "CA5350:Do Not Use Weak Cryptographic Algorithms", Justification = "Not security related: the hash only reproduces v1's object names.")]
[SuppressMessage("Security", "S4790:Weak hashing algorithms should not be used", Justification = "Not security related: the hash only reproduces v1's object names.")]
private static string UserKey { get; } =
Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(Environment.UserName ?? "default")))[..16];
@@ -9,6 +9,7 @@
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vm="clr-namespace:AutoClick.UI.ViewModels"
d:DataContext="{d:DesignInstance vm:AboutViewModel, IsDesignTimeCreatable=False}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<Page.Resources>
<Style x:Key="LinkButton" BasedOn="{StaticResource DefaultUiButtonStyle}" TargetType="ui:Button">
@@ -9,6 +9,7 @@
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vm="clr-namespace:AutoClick.UI.ViewModels"
d:DataContext="{d:DesignInstance vm:DashboardViewModel, IsDesignTimeCreatable=False}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<StackPanel Margin="0,8,0,24">
<Grid Margin="0,0,0,12">
@@ -70,7 +71,8 @@
TextWrapping="Wrap"
Visibility="{Binding HasStats, Converter={StaticResource InverseBoolToVisibility}}" />
<!-- Clicks per minute -->
<!-- Clicks per minute. Every chart sets Background: LiveCharts' WPF view always uses its
light theme and otherwise clears the canvas white, behind text in theme colors. -->
<Border Style="{StaticResource SectionCard}">
<StackPanel>
<ui:TextBlock
@@ -80,6 +82,7 @@
<lvc:CartesianChart
Height="240"
AnimationsSpeed="00:00:00.100"
Background="Transparent"
Series="{Binding CpmSeries}"
TooltipPosition="Hidden"
XAxes="{Binding CpmXAxes}"
@@ -102,6 +105,7 @@
<lvc:PieChart
Height="220"
AnimationsSpeed="00:00:00.200"
Background="Transparent"
LegendPosition="Bottom"
LegendTextPaint="{Binding LegendTextPaint}"
Series="{Binding RatioSeries}" />
@@ -116,6 +120,7 @@
<lvc:CartesianChart
Height="220"
AnimationsSpeed="00:00:00.200"
Background="Transparent"
LegendPosition="Bottom"
LegendTextPaint="{Binding LegendTextPaint}"
Series="{Binding BreakdownSeries}"
@@ -134,6 +139,7 @@
<lvc:CartesianChart
Height="220"
AnimationsSpeed="00:00:00.100"
Background="Transparent"
LegendPosition="Right"
LegendTextPaint="{Binding LegendTextPaint}"
Series="{Binding TimelineSeries}"
@@ -11,6 +11,7 @@
xmlns:views="clr-namespace:AutoClick.UI.Views"
xmlns:vm="clr-namespace:AutoClick.UI.ViewModels"
d:DataContext="{d:DesignInstance vm:QueueViewModel, IsDesignTimeCreatable=False}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<StackPanel Margin="0,8,0,24">
<!-- Title and actions -->
@@ -9,6 +9,7 @@
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vm="clr-namespace:AutoClick.UI.ViewModels"
d:DataContext="{d:DesignInstance vm:SettingsViewModel, IsDesignTimeCreatable=False}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<Page.Resources>
<Style x:Key="Caption" TargetType="TextBlock">
+3
View File
@@ -1,5 +1,6 @@
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using AutoClick.Core.Abstractions;
using Microsoft.Win32.SafeHandles;
@@ -91,6 +92,7 @@ public sealed class ElevationService : IElevationService
}
}
[SuppressMessage("Security", "S6640:Unsafe code blocks should not be used", Justification = "Reviewed: CsWin32 has no safe overload; the struct has the size passed to the call.")]
private static bool GetOwnElevation()
{
using var token = OpenOwnToken();
@@ -120,6 +122,7 @@ public sealed class ElevationService : IElevationService
}
/// <summary>The integrity level RID (e.g. 0x2000 medium, 0x3000 high), or -1.</summary>
[SuppressMessage("Security", "S6640:Unsafe code blocks should not be used", Justification = "Reviewed: CsWin32 has no safe overloads; the buffer has the size the first call reports and stays pinned while it is read.")]
private static unsafe int GetIntegrityLevel(SafeHandle token)
{
PInvoke.GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, null, 0, out var size);
+10 -4
View File
@@ -7,6 +7,10 @@ namespace AutoClick.Win32;
/// <summary>Opens URLs, files and folders with their default handler.</summary>
public sealed class ShellLauncher(IElevationService elevation)
{
// A full path: a bare "explorer.exe" is searched in AutoClick's own folder first, which
// the user can write to, and would then run with administrator rights.
private static string ExplorerPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe");
/// <summary>
/// When AutoClick runs elevated, the target is opened through Explorer so the browser or
/// editor does not inherit administrator rights.
@@ -15,10 +19,7 @@ public sealed class ShellLauncher(IElevationService elevation)
{
try
{
var startInfo = elevation.IsCurrentProcessElevated
? new ProcessStartInfo("explorer.exe") { ArgumentList = { target }, UseShellExecute = false }
: new ProcessStartInfo(target) { UseShellExecute = true };
using var process = Process.Start(startInfo);
using var process = Process.Start(StartInfo(target, elevation.IsCurrentProcessElevated));
return true;
}
catch (Exception ex) when (ex is Win32Exception or InvalidOperationException)
@@ -26,4 +27,9 @@ public sealed class ShellLauncher(IElevationService elevation)
return false;
}
}
internal static ProcessStartInfo StartInfo(string target, bool elevated) =>
elevated
? new ProcessStartInfo(ExplorerPath) { ArgumentList = { target }, UseShellExecute = false }
: new ProcessStartInfo(target) { UseShellExecute = true };
}
@@ -0,0 +1,37 @@
using System.IO;
using AutoClick.Core.Abstractions;
namespace AutoClick.Win32.Tests;
public class ShellLauncherTests
{
[Fact]
public void StartInfo_Elevated_StartsExplorerByItsFullPath()
{
var startInfo = ShellLauncher.StartInfo("https://example.com", elevated: true);
// A bare "explorer.exe" would be searched in AutoClick's own, user-writable folder first.
Assert.True(Path.IsPathFullyQualified(startInfo.FileName));
Assert.Equal(Environment.GetFolderPath(Environment.SpecialFolder.Windows), Path.GetDirectoryName(startInfo.FileName), ignoreCase: true);
Assert.Equal("explorer.exe", Path.GetFileName(startInfo.FileName), ignoreCase: true);
Assert.True(File.Exists(startInfo.FileName));
Assert.Equal("https://example.com", Assert.Single(startInfo.ArgumentList));
Assert.False(startInfo.UseShellExecute);
}
[Fact]
public void TryOpen_MissingFile_ReturnsFalse()
{
// Not elevated: the default handler reports the missing file without showing any UI.
var launcher = new ShellLauncher(new NotElevated());
Assert.False(launcher.TryOpen(Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.autoclick-missing")));
}
private sealed class NotElevated : IElevationService
{
public bool IsCurrentProcessElevated => false;
public ElevationState GetRelativeElevation(int processId) => ElevationState.SameOrLower;
}
}
+5 -6
View File
@@ -7,16 +7,18 @@ internal static class StaThread
{
public static void Run(Action action)
{
Exception? failure = null;
// The task carries the outcome back; GetResult rethrows a failure with its original stack.
var outcome = new TaskCompletionSource();
var thread = new Thread(() =>
{
try
{
action();
outcome.SetResult();
}
catch (Exception ex)
{
failure = ex;
outcome.SetException(ex);
}
finally
{
@@ -26,10 +28,7 @@ internal static class StaThread
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Assert.True(thread.Join(TimeSpan.FromSeconds(30)), "STA test thread timed out.");
if (failure is not null)
{
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(failure).Throw();
}
outcome.Task.GetAwaiter().GetResult();
}
/// <summary>Pumps messages until <paramref name="task"/> completes (or the timeout elapses).</summary>
@@ -0,0 +1,12 @@
namespace AutoClick.Win32.Tests;
public class StaThreadTests
{
[Fact]
public void Run_TestCodeThrows_RethrowsTheSameException()
{
var failure = Assert.Throws<InvalidOperationException>(() => StaThread.Run(() => throw new InvalidOperationException("boom")));
Assert.Equal("boom", failure.Message);
}
}