From 7a109da537fd720c1b779c74a4f1fc952f2f661e Mon Sep 17 00:00:00 2001
From: Osiris-DevWorks
Date: Fri, 30 Oct 2026 17:43:25 +0000
Subject: [PATCH 1/8] Bump version to 0.10.2
Branch-opening commit for the 0.10.2 integration target.
Co-Authored-By: Claude Fable 5.1
Claude-Session: https://claude.ai/code/session_011hqxFichExZVw3JZFHCByg
---
VERSION.TXT | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/VERSION.TXT b/VERSION.TXT
index 5712157..5eef0f1 100644
--- a/VERSION.TXT
+++ b/VERSION.TXT
@@ -1 +1 @@
-0.10.1
+0.10.2
From 6e69072f9dbfeeae7f4a859a117a997ac6809826 Mon Sep 17 00:00:00 2001
From: Osiris-DevWorks
Date: Fri, 30 Oct 2026 17:45:44 +0000
Subject: [PATCH 2/8] Bring /pre_release to parity with smart-citizen
Port the helper commands smart-citizen's pre-release gate is built from,
adapted to this codebase's invariants:
- /test_coverage_check: parser, models, registry, XML exporter and the
pure utils helpers require tests; GUI, input detection and scripts are
exempt but flagged for manual smoke testing.
- /docs_sync_check: README.md and ABOUT.md are rendered in-app, so string
drift, workflow currency, device-list parity with the template registry
and CHANGELOG parity are checked.
- /standards_check: resource lookups through get_resource_path, build
--add-data list, bare src/ imports, activationMode rules, AppSettings,
label-override tiers, template registry hygiene, VERSION.TXT as the
only version source, DRY calibration.
/pre_release now runs those three, the security review, a contributor and
tester acknowledgement audit against ABOUT.md, the tester installer build
and the issue close-on-verify pass, in smart-citizen's order. The language
check, Test Plan panel and portable build steps are omitted on purpose
and the command says why.
Co-Authored-By: Claude Fable 5.1
Claude-Session: https://claude.ai/code/session_011hqxFichExZVw3JZFHCByg
---
.claude/commands/docs_sync_check.md | 37 ++++++++
.claude/commands/pre_release.md | 117 ++++++++++++++++++------
.claude/commands/standards_check.md | 39 ++++++++
.claude/commands/test_coverage_check.md | 59 ++++++++++++
docs/CHANGELOG.md | 2 +-
5 files changed, 225 insertions(+), 29 deletions(-)
create mode 100644 .claude/commands/docs_sync_check.md
create mode 100644 .claude/commands/standards_check.md
create mode 100644 .claude/commands/test_coverage_check.md
diff --git a/.claude/commands/docs_sync_check.md b/.claude/commands/docs_sync_check.md
new file mode 100644
index 0000000..514a9b4
--- /dev/null
+++ b/.claude/commands/docs_sync_check.md
@@ -0,0 +1,37 @@
+---
+description: Verify user-facing strings, README, ABOUT and the CHANGELOG match the current app
+---
+
+# /docs_sync_check
+
+Cross-check the app's user-facing surface against the docs. Catches drift introduced when a button or tab is renamed in code but the doc still describes the old name, when a device template is renamed but README still lists the old name, or when a feature ships without a docs update. `README.md` and `ABOUT.md` are both rendered inside the app (About tab), so stale text ships to users.
+
+## Severities
+
+- **Critical** — `README.md` or `ABOUT.md` fails to render in-app (markdown the renderer chokes on, or a missing bundled file after a rename).
+- **Major** — a workflow step in `README.md` (Quick Start, Common Tasks, Reference) no longer matches the code, or a user-facing control is described under a name that no longer exists.
+- **Minor** — a feature or device mentioned in `ABOUT.md` or README's feature/device lists has been removed or renamed but isn't workflow-critical.
+
+## Inputs
+
+- `src/gui/*.py` — window title, tab names, button/menu labels, dialog text, status messages.
+- `visual-templates/template_registry.json` — template display names (README lists supported devices).
+- `README.md` — Quick Start, Common Tasks, Reference, Troubleshooting.
+- `ABOUT.md` — feature summary, acknowledgements.
+- `docs/CHANGELOG.md` — `[Unreleased]` must describe every user-visible change on the branch.
+
+## Checks
+
+1. **Bundled docs still load** *(Critical)*: `ABOUT.md` and `README.md` are read via `get_resource_path`; confirm both are in `scripts/build/build_exe.py`'s `--add-data` list and parse as markdown.
+2. **String drift** *(Major)*: pull every user-facing literal from `src/gui/` (tab names, button text, dialog titles) and check whether README/ABOUT refer to any of them by a name no longer in the code. Flag `doc:line → code:line` with the suspected new wording.
+3. **Workflow currency** *(Major)*: README's Common Tasks cover loading a profile, editing labels, remapping a binding, Device View, Config tab device mapping, exports. If the branch diff touched any of those flows, surface the matching README section for review.
+4. **Device list parity** *(Minor, escalate to Major if a how-to names the device)*: every non-deprecated template name in `template_registry.json` should appear where README lists supported devices, and vice versa.
+5. **CHANGELOG parity** *(Major)*: compare `git log ..HEAD --oneline` with `[Unreleased]`; every user-visible change needs an entry.
+
+## Output
+
+Group findings by severity, one per line: `doc-file:line → code-file:line — short description`.
+
+End with a one-line **verdict**: **Clean**, **Minor issues**, or **Needs attention** (any Critical or Major).
+
+After the verdict, **CHECKPOINT — pause and ask whether to draft doc updates for the Critical/Major findings, or move on.** Do not edit docs without confirmation — surface, don't auto-correct.
diff --git a/.claude/commands/pre_release.md b/.claude/commands/pre_release.md
index 854e23c..ae822b1 100644
--- a/.claude/commands/pre_release.md
+++ b/.claude/commands/pre_release.md
@@ -1,62 +1,123 @@
---
-description: Pre-release gate before merging release/X.Y.Z to main — tests, docs/CHANGELOG currency, security review, tester installer build on the release PR, then issue close-on-verify
+description: Pre-release sanity check before merging release/X.Y.Z to main — test coverage, docs sync, standards, security review, contributor + tester acknowledgement audit, tester installer build on the release PR, then issue close-on-verify
---
# /pre_release
-Run before merging the active `release/X.Y.Z` integration branch to `main`. This is the final gate: it confirms the tests pass, the CHANGELOG and user docs describe what this release changed, the code is reviewed for security, testers have an installer to verify against, and every issue fixed this cycle is closed (tester-verified) or explicitly held.
+Run before merging the active `release/X.Y.Z` integration branch to `main`. This is the final gate before the release ships — it confirms code quality, doc currency, test coverage, that every code contributor and tester is acknowledged in `ABOUT.md`, that testers have an installer to verify against, and that every issue fixed this cycle is closed (tester-verified) or explicitly held.
-Work through every step in order. After each step, stop at the **CHECKPOINT** and wait for the user.
+Mirrors smart-citizen's `/pre_release`. Three of its steps do not apply here and are omitted on purpose: the language coverage check (SCPE has no translations), the in-app Test Plan panel refresh (SCPE has no such panel), and the portable build (SCPE has no portable mode).
+
+Work through every step in order. After each step, stop at the **CHECKPOINT** and wait for the user before continuing.
## Preflight
-- Current branch must be `release/X.Y.Z`; abort otherwise.
-- Working tree clean (`git status --porcelain`); abort otherwise.
-- `VERSION.TXT` must equal `X.Y.Z`; surface a mismatch and ask.
+- Confirm the current branch is `release/X.Y.Z`. If not, abort and ask the user to switch.
+- Confirm the working tree is clean (`git status --porcelain`). If dirty, abort.
+- Confirm `VERSION.TXT` matches `X.Y.Z`. If mismatched, surface the discrepancy and ask before proceeding.
+
+**CHECKPOINT — preflight confirms release branch is ready for audit. Proceed?** Wait for the user.
+
+## 1. Test coverage check
+
+Follow `.claude/commands/test_coverage_check.md`. Present findings grouped by severity (Critical / Major / Minor) and end with the verdict line.
+
+**CHECKPOINT — ready for the next check?** Wait for the user.
+
+## 2. Docs sync check
+
+Follow `.claude/commands/docs_sync_check.md`. Present findings grouped by severity and end with the verdict line. This is also where `docs/CHANGELOG.md` `[Unreleased]` is brought up to date with the branch's user-visible changes; draft the missing entries in the file's style (`**Bold summary** — detail (issue #N)`). Doc edits land via a normal PR to the release branch.
+
+**CHECKPOINT — ready for the next check?** Wait for the user.
+
+## 3. Standards spot-check
+
+Follow `.claude/commands/standards_check.md`. Present findings grouped by severity and end with the verdict line.
+
+**CHECKPOINT — ready for the next check?** Wait for the user.
+
+## 4. Security review
+
+Run `/security-review` on `main..HEAD`. Present findings grouped by severity and end with the verdict line.
-**CHECKPOINT — preflight passes. Proceed?**
+**CHECKPOINT — ready for the contributor audit?** Wait for the user.
-## 1. Tests
+## 5. Contributor & tester acknowledgement audit
-Run `python -m pytest tests/ -q`. Everything must pass; there is no skip list. Report failures with their output.
+Verify every code contributor and frequent tester is acknowledged in `ABOUT.md` (rendered in the About tab, so this is what users see).
-**CHECKPOINT.**
+### 5a. Build the contributor list
-## 2. CHANGELOG and docs currency
+```bash
+git log --format='%aN|%aE' --no-merges | sort -u
+gh api "repos/Osiris-DevWorks/sc-profile-editor/contributors" --paginate --jq '.[] | {login: .login, contributions: .contributions}'
+```
-1. `git log main..HEAD --oneline` — the release's scope (merged PRs and the issues they close).
-2. Compare against `docs/CHANGELOG.md` `[Unreleased]`: every user-visible change (new feature, changed flow, fixed bug with a reproducible symptom) needs an entry; internal refactors do not. Draft the missing entries in the file's existing style (`**Bold summary** — detail (issue #N)`).
-3. Check `README.md` and `ABOUT.md` for anything the release renamed, added or removed (tabs, buttons, supported devices). Both are rendered in-app, so stale text ships to users.
+**Filter out**: the repo owner (`Osiris-DevWorks` / `Osiris DevWorks` / `Amr`), AI co-author trailers (`Claude`, `noreply@anthropic.com`), bot accounts (`*[bot]`), and anonymous commits with no name or GitHub login. Merge entries for one person committing under several name/email combinations; if unsure, surface the duplicates.
-**CHECKPOINT — present the proposed CHANGELOG/doc edits and ask before editing.** Land them via a normal PR to the release branch (release branches require PRs).
+### 5b. Pull the current acknowledgement set
-## 3. Security review
+Read `ABOUT.md` → `## Acknowledgements` (the tester list) and any **Contributors** section. If `README.md` carries a matching section, read it too and treat drift between the two as a finding.
-Run `/security-review` on `main..HEAD`. Present findings grouped by severity (Critical / Major / Minor) and end with a verdict line.
+### 5c. Categorize each missing contributor
-**CHECKPOINT.**
+For every contributor not acknowledged: commit count (`git log --author='' --no-merges --oneline | wc -l`) and a sample of files touched. **Substantial**: ≥3 commits or non-trivial `src/`, `scripts/`, `tests/` or `visual-templates/` changes. **Drive-by**: 1–2 commits, trivial files only.
-## 4. Tester installer on the release PR
+### 5d. Tester candidates from issue reporters
+
+```bash
+gh issue list --state all --limit 1000 --json number,author --jq '.[].author.login' | sort | uniq -c | sort -rn
+```
+
+Flag everyone with **3 or more** reported issues as a candidate tester, then drop the owner, bots, anyone already in the Acknowledgements list, and anyone who is also a code contributor (credited as a contributor, never both). Issues mirrored from Discord name the real reporter in the body; attribute by that name, and list unattributable reports rather than guessing.
+
+### 5e. Report
+
+```
+**Missing — substantial contributors** (suggest adding): …
+**Missing — drive-by fixers** (consider adding, or skip): …
+**Already acknowledged**: N covered.
+
+**Tester candidates** (≥3 reported issues, not code contributors): …
+```
+
+Verdict: **Clean** (every substantial contributor acknowledged), **Minor issues** (only drive-bys missing or README/ABOUT drift), **Needs attention** (substantial contributors missing). Tester candidates are advisory and never block a release.
+
+**CHECKPOINT — ask before drafting additions to `ABOUT.md` (and `README.md` if it carries the same list).** Do not edit without confirmation.
+
+## 6. Tester installer build on the release PR
1. Find the release PR: `gh pr list --base main --head release/X.Y.Z --state open --json number,title`.
2. If none exists, open it now with title `Release X.Y.Z` and the CHANGELOG section as the body. **Opening the PR is not merging it.**
-3. Add the `build-installer` label: `gh pr edit --add-label build-installer`. `installer-preview.yml` builds `SCProfileEditor-vX.Y.Z-Setup.exe` and comments the download link on the PR; later pushes to the PR rebuild automatically.
+3. Add the label: `gh pr edit --add-label build-installer`. `installer-preview.yml` builds `SCProfileEditor-vX.Y.Z-Setup.exe` and comments the download link on the PR; later pushes to the PR rebuild automatically. If the label was already present from an earlier round, remove and re-add it, or dispatch the workflow manually, so a build runs on the current head.
4. Report the run (`gh run list --limit 1`) and the artifact name (`scprofileeditor-installer-{SHA}`, 30-day retention).
-**CHECKPOINT — confirm before opening the PR and adding the label; both are visible on GitHub and start CI builds.**
+**CHECKPOINT — confirm before opening the PR and adding the label; both are visible on GitHub and start CI builds.** Wait for the user.
+
+## 7. Issue close-on-verify pass
+
+Runs last because verification comes from testers using the step-6 build. On the day the audit runs, most issues will legitimately sit in "awaiting verification"; that is the expected outcome. Re-run this step alone once tester sign-offs come back, before the merge to `main`.
+
+### 7a. Gather the release's issues
+
+Union of: issues labeled `next-release` (`gh issue list --state open --label next-release --json number,title,author`) and every `#NN` referenced in `git log main..HEAD --oneline`.
+
+### 7b. Classify each
-## 5. Issue close-on-verify
+Look for a confirming comment from the reporter or a tester on the preview build (`gh issue view --json title,state,comments`). Bucket as **Fixed + tester-verified** (close), **Fixed, awaiting verification** (hold; a passing local test is not a tester sign-off), or **Not addressed** (flag for re-label or defer).
-Runs last because verification comes from testers using the step-4 build.
+### 7c. Report
-1. Gather issues: `#NN` references in `git log main..HEAD` plus anything labeled `next-release`.
-2. For each, check for a tester confirmation (`gh issue view --json title,state,comments`). Bucket as **Verified — close**, **Awaiting verification — hold**, or **Not addressed — re-label or defer**. A passing local test is not a tester sign-off.
-3. Report the three buckets.
+```
+**Verified — close candidates:** …
+**Awaiting verification — hold open:** …
+**Not addressed — re-label or defer:** …
+```
-**CHECKPOINT — ask before closing anything.** On confirmation, close each verified issue with a short thanks naming the version it ships in and the tester who confirmed it. Never close one that is only awaiting verification.
+**CHECKPOINT — present the close / hold / flag list and ask before closing anything.** On confirmation, close each verified issue with a short thanks naming the version it ships in and crediting the tester who confirmed it. Never close one that is only awaiting verification.
## Final summary
-One-line overall verdict (worst case across steps), the remaining Critical/Major findings, and where testing stands. Re-run step 5 alone once tester sign-offs land.
+One-line overall verdict for release readiness (the worst case across the checks), the remaining Critical/Major findings to address before the `release/X.Y.Z` → `main` merge, and any issues still open that were expected to ship. Say plainly where testing stands: the build is out, and anything step 7 left in "awaiting verification" is waiting on testers, not on the audit.
This command does not ship the release. That is `/ship_release`.
diff --git a/.claude/commands/standards_check.md b/.claude/commands/standards_check.md
new file mode 100644
index 0000000..0ed1c42
--- /dev/null
+++ b/.claude/commands/standards_check.md
@@ -0,0 +1,39 @@
+---
+description: Lint the current diff against SC Profile Editor's documented standards
+---
+
+# /standards_check
+
+Audit the branch diff (`git diff $(git merge-base HEAD )...HEAD`, plus any working-tree changes) against the project's documented standards in `CLAUDE.md` and `docs/DEVELOPMENT.md`. Report findings with file:line references and severity. **Do not auto-fix without confirmation.**
+
+- **Critical** — breaks correctness, the packaged build, or the XML round-trip. Must fix before merge.
+- **Major** — wrong but won't immediately break. Should fix before merge.
+- **Minor** — stylistic or "consider" notes. Optional.
+
+## Checks
+
+- **Bundled resource lookup** *(Critical)*: any `open(...)`, `Path(...)` or `os.path.join(...)` that reaches a bundled file (`visual-templates/`, `example-profiles/`, `default-bindings/`, `assets/`, `UNBIND_ALL.xml`, `label_overrides.json`, `README.md`, `ABOUT.md`, `VERSION.TXT`) without going through the `_MEIPASS`-aware `get_resource_path()` helper. Works in dev, breaks in the installer.
+- **Build data list** *(Critical)*: a new bundled file or folder that is not in `scripts/build/build_exe.py`'s `--add-data` list (and the matching list in `docs/DEVELOPMENT.md`).
+- **Bare `src/` imports** *(Critical)*: new modules must import the same way their neighbours do (`from parser.xml_parser import …`, resolved by `--paths src`). A mix of `src.parser` and `parser` imports breaks the frozen build.
+- **activationMode on axes** *(Critical)*: any code path that writes `activationMode` for an input `InputValidator.is_analog_axis()` says is analog, or that writes a default mode the user did not pick (the v0.10.2 hat bug: an explicit `press` overrides the game's `hold`). `None` means "game default" and must stay omitted in the XML.
+- **Settings access** *(Major)*: direct `QSettings(...)` construction outside `src/utils/settings.py`. Use `AppSettings` so keys and the registry path stay in one place.
+- **Label resolution** *(Major)*: display labels must resolve through `src/utils/label_overrides.py` (custom → global → auto-generated). A new code path that formats an action name directly bypasses user overrides.
+- **Template registry** *(Major)*: new templates need `device_match_patterns` that match the SC product string case-sensitively, a `product_ids` list where the VID/PID is known, and `field_mapping.json` next to the PDF. Composite devices route through `device_splitter.py`; don't special-case them in the manager.
+- **Version source** *(Major)*: any literal version string in code, `installer.iss`, or docs other than `VERSION.TXT`. The window title, installer and release tag all derive from that file.
+- **Logging** *(Minor)*: `print()` in `src/` instead of the module `logger`.
+
+## Code duplication / DRY
+
+- **Copy-paste blocks** *(Major)*: 5+ line blocks in the diff that appear verbatim elsewhere. Report both locations.
+- **Magic literals** *(Minor)*: SC input prefixes (`js1_`, `kb1_`, `mouse1_`, `gp1_`), the PIDVID GUID suffix, QSettings keys, template ids repeated in 2+ places without a named constant.
+- **Near-duplicate functions** *(Minor)*: a new function structurally identical to an existing one, differing only in a literal or a call target.
+
+Calibration: 3+ occurrences → recommend extraction; 2 → "consider"; never propose a single-use helper.
+
+## Output
+
+Group findings by severity, one per line: `file:line — short description — fix hint`.
+
+End with a one-line **verdict**: **Clean**, **Minor issues**, or **Needs attention** (any Critical or Major).
+
+After the verdict, **CHECKPOINT — pause and ask whether to draft fixes for the Critical/Major findings, or move on.** Wait for the answer before doing anything else.
diff --git a/.claude/commands/test_coverage_check.md b/.claude/commands/test_coverage_check.md
new file mode 100644
index 0000000..baa0743
--- /dev/null
+++ b/.claude/commands/test_coverage_check.md
@@ -0,0 +1,59 @@
+---
+description: Audit the current branch's source changes for matching test coverage in tests/
+---
+
+# /test_coverage_check
+
+For every source file modified on the current branch, decide whether it should have a unit test and whether that test exists or was updated. Surface gaps; don't auto-write tests.
+
+## Severities
+
+- **Critical** — non-exempt code (per the table below) with no matching test. Blocks the release.
+- **Major** — an existing test covers an old branch of changed logic but does not exercise the new branch.
+- **Minor** — exempt code (GUI wiring, input detection, scripts) flagged for manual attention so the user remembers to smoke-test.
+
+## Scoping the diff
+
+```bash
+git diff --name-only $(git merge-base HEAD origin/main)...HEAD
+```
+
+On a `release/X.Y.Z` integration branch that is the right baseline. On a feature PR, use the release branch instead of `origin/main`.
+
+## Coverage rules
+
+| Area | Coverage requirement |
+|---|---|
+| `src/parser/`, `src/models/`, `src/registry/`, `src/exporters/xml_exporter.py` | **Required.** New public functions, new classes, changed branching logic need new or updated tests in `tests/`. The XML round-trip is the product; a parser/exporter change without a test is Critical. |
+| `src/utils/` pure helpers: `directinput_guid.py`, `input_validator.py`, `label_overrides.py`, `device_splitter.py`, `device_joystick_mapper.py`, `version.py` | **Required** — no Qt or hardware needed, so they are testable. |
+| `src/graphics/pdf_template_manager.py` (template matching, `find_template`) | **Required** for matching logic; PDF rendering itself is exempt. |
+| `src/utils/input_detector.py`, `src/utils/single_instance.py` | **Exempt.** Needs real hardware / Windows mutex. Manual test with a joystick plugged in. Flag for human attention. |
+| `src/gui/*.py` (widgets, signals, MainWindow wiring, dialogs) | **Exempt.** Manual GUI testing only (there is no pytest-qt). Surface for review. |
+| `src/exporters/{csv,pdf,word,graphic}_exporter.py` | **Exempt** unless a pure formatting helper was added. Manual export check. |
+| `scripts/` | **Exempt**, except `scripts/generate_pdf_template.py::parse_joy_label` which has `tests/test_parse_joy_label.py` and stays covered. |
+
+## Procedure
+
+1. Run the diff. Group the file list by area per the table above.
+2. For each non-exempt file, identify the new or changed callable. Check `tests/` for a matching test (`tests/test_.py`, `test__`).
+3. For changed branching logic in existing code, read the existing test to confirm it covers the new branch; don't trust the filename alone.
+4. Run `python -m pytest tests/ -q` and report pass/fail with the count.
+
+## Output
+
+```
+**Critical** (non-exempt code without tests):
+ src/parser/xml_parser.py::ProfileParser._parse_rebind — new activationMode branch, no test
+
+**Major** (stale tests — changed branches not exercised):
+ src/utils/directinput_guid.py::parse_sc_product_guid — test covers PIDVID form only; new XInput path uncovered
+
+**Minor** (exempt — flagged for manual attention):
+ src/gui/remap_dialog.py — activation-mode dropdown changed, manual exercise needed
+
+python -m pytest tests/: PASS (41 passed) | FAIL — see output above
+```
+
+End with a one-line **verdict**: **Clean** (no Critical/Major, pytest passes), **Minor issues** (only Minor; pytest passes), or **Needs attention** (any Critical/Major or pytest failures).
+
+After the verdict, **CHECKPOINT — pause and ask whether to draft tests for the Critical findings, or move on.** Wait for the answer before doing anything else.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 8ded832..062a353 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -17,7 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Mislabeled Virpil templates** (issue #31) — `VPC MT-50CM3 (Left/Right)` are actually Alpha Prime grip diagrams on a MongoosT-50CM3 base and are now named that way. A dedicated MT-50CM3 **throttle** template still needs to be authored.
### Added
-- **Release process ported from smart-citizen** — Long-lived `release/X.Y.Z` integration branches; PRs target the release branch and merging it to `main` is the release trigger. New workflows: `ci.yml` (tests + PyInstaller build verification on every PR to `main`/`release/**`), `release.yml` (on merge to `main`: auto-tags `v{VERSION}` from `VERSION.TXT`, builds the installer, publishes the GitHub Release with the CHANGELOG section as its body, posts to Discord), `installer-preview.yml` (add the `build-installer` label to a PR for a tester installer artifact), `installer-preview-cleanup.yml`, and `release-notify.yml` (manual Discord re-post). `.github/CODEOWNERS` requests review from the maintainer on every PR. `/start_release`, `/pre_release` and `/ship_release` commands walk the cycle with checkpoints; `docs/RELEASE_PROCESS.md` documents it.
+- **Release process ported from smart-citizen** — Long-lived `release/X.Y.Z` integration branches; PRs target the release branch and merging it to `main` is the release trigger. New workflows: `ci.yml` (tests + PyInstaller build verification on every PR to `main`/`release/**`), `release.yml` (on merge to `main`: auto-tags `v{VERSION}` from `VERSION.TXT`, builds the installer, publishes the GitHub Release with the CHANGELOG section as its body, posts to Discord), `installer-preview.yml` (add the `build-installer` label to a PR for a tester installer artifact), `installer-preview-cleanup.yml`, and `release-notify.yml` (manual Discord re-post). `.github/CODEOWNERS` requests review from the maintainer on every PR. `/start_release`, `/pre_release` and `/ship_release` commands walk the cycle with checkpoints, and `/pre_release` runs the same gate steps as smart-citizen via `/test_coverage_check`, `/docs_sync_check` and `/standards_check` plus a contributor and tester acknowledgement audit; `docs/RELEASE_PROCESS.md` documents it.
- **Scripted build** — `scripts/build/build_exe.py` (PyInstaller `--onedir`, stable `SCProfileEditor.exe` name so shortcuts survive upgrades) and `scripts/build/build_all.bat`. `installer.iss` now reads the version from `VERSION.TXT` at compile time, so `VERSION.TXT` is the single place to bump. `scripts/release_notes.py` extracts a version's CHANGELOG section for the release body. `requirements-dev.txt` holds the test/build deps.
## [0.10.1] - 2026-05-11
From 7b8cc84112e887df97286e4c8be29bb1e3b4e2d1 Mon Sep 17 00:00:00 2001
From: Osiris-DevWorks
Date: Mon, 9 Nov 2026 13:34:44 +0000
Subject: [PATCH 3/8] docs: pre-release fixes for 0.10.2
/pre_release docs-sync findings on release/0.10.2:
- README listed "VPC: MongoosT-50CM3" as a supported template. The two
Virpil templates were renamed in #32 to what they depict, an Alpha Prime
grip on a CM3 base, and a CM3 throttle template does not exist (#31),
so the device list now says that.
- CHANGELOG [Unreleased] gains a Changed section for the two user-visible
chores that landed since v0.10.1 (#28 LLC copyright, #30 PayPal link) so
the generated release notes mention them.
Co-Authored-By: Claude Fable 5.1
Claude-Session: https://claude.ai/code/session_011hqxFichExZVw3JZFHCByg
---
README.md | 2 +-
docs/CHANGELOG.md | 4 ++++
2 files changed, 5 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index d4c7de3..38b3811 100644
--- a/README.md
+++ b/README.md
@@ -254,7 +254,7 @@ The application uses a three-tier label priority system:
The application includes PDF templates for 20+ devices:
- **VKB:** Gladiator (EVO/SCG variants), Gunfighter (MCG/SCG), Space Sim Module, STECS Throttle, Throttle Quadrants, F16 MFD
-- **VPC:** MongoosT-50CM3
+- **VPC:** Alpha Prime grip (left/right, on a MongoosT-50CM3 base)
- **Thrustmaster:** T.16000M, TWCS Throttle
For devices without templates, you can still use the Controls Table, CSV, PDF, and Word exports.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 062a353..cddd652 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -20,6 +20,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Release process ported from smart-citizen** — Long-lived `release/X.Y.Z` integration branches; PRs target the release branch and merging it to `main` is the release trigger. New workflows: `ci.yml` (tests + PyInstaller build verification on every PR to `main`/`release/**`), `release.yml` (on merge to `main`: auto-tags `v{VERSION}` from `VERSION.TXT`, builds the installer, publishes the GitHub Release with the CHANGELOG section as its body, posts to Discord), `installer-preview.yml` (add the `build-installer` label to a PR for a tester installer artifact), `installer-preview-cleanup.yml`, and `release-notify.yml` (manual Discord re-post). `.github/CODEOWNERS` requests review from the maintainer on every PR. `/start_release`, `/pre_release` and `/ship_release` commands walk the cycle with checkpoints, and `/pre_release` runs the same gate steps as smart-citizen via `/test_coverage_check`, `/docs_sync_check` and `/standards_check` plus a contributor and tester acknowledgement audit; `docs/RELEASE_PROCESS.md` documents it.
- **Scripted build** — `scripts/build/build_exe.py` (PyInstaller `--onedir`, stable `SCProfileEditor.exe` name so shortcuts survive upgrades) and `scripts/build/build_all.bat`. `installer.iss` now reads the version from `VERSION.TXT` at compile time, so `VERSION.TXT` is the single place to bump. `scripts/release_notes.py` extracts a version's CHANGELOG section for the release body. `requirements-dev.txt` holds the test/build deps.
+### Changed
+- **Copyright holder and publisher** are now Osiris DevWorks, LLC (About tab, installer, LICENSE).
+- **PayPal donate link** in the footer points at the new payment page.
+
## [0.10.1] - 2026-05-11
### Fixed
From 7b68a955eebd5a41d6dae8019eba9bdfde912d5c Mon Sep 17 00:00:00 2001
From: Claude
Date: Wed, 18 Nov 2026 18:07:53 +0000
Subject: [PATCH 4/8] Add Check Profile: flag device-numbering swaps and other
silent profile problems
Today's repair of Amr's live profile turned up four problems that neither
the game nor SCPE reported (a view action forced to "press", a hat with
its view directions cleared, one button firing two mode switches, and
stick tuning saved under an old device ID). Amr also asked for a check
that the profile's js1/js2/... numbering matches the order the PC lists
the sticks, since a mismatch silently moves bindings to the wrong stick.
profile_checker.py reads the raw XML (exported layout or live
actionmaps.xml) and returns findings; system_devices.py supplies the PC's
stick order from DirectInput on Windows (the game's source), pygame
elsewhere, or the virtual sticks in --mock-joysticks mode so it is
testable without hardware. The dialog shows profile-vs-PC slots side by
side and can re-check after re-plugging. Unsaved edits are checked via a
temp export.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_011hqxFh5GLh4UnV4rY8Fzdw
---
CLAUDE.md | 4 +-
README.md | 13 +
docs/CHANGELOG.md | 1 +
docs/DEVELOPMENT.md | 10 +-
src/gui/main_window.py | 39 ++
src/gui/profile_check_dialog.py | 150 ++++++
src/utils/profile_checker.py | 481 ++++++++++++++++++
src/utils/system_devices.py | 177 +++++++
.../mock_devices/check_profile_swapped.json | 8 +
.../profiles/check_profile_problems.xml | 60 +++
tests/test_profile_checker.py | 203 ++++++++
11 files changed, 1144 insertions(+), 2 deletions(-)
create mode 100644 src/gui/profile_check_dialog.py
create mode 100644 src/utils/profile_checker.py
create mode 100644 src/utils/system_devices.py
create mode 100644 tests/fixtures/mock_devices/check_profile_swapped.json
create mode 100644 tests/fixtures/profiles/check_profile_problems.xml
create mode 100644 tests/test_profile_checker.py
diff --git a/CLAUDE.md b/CLAUDE.md
index 85b360f..2490791 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -56,6 +56,8 @@ Edits propagate **in real time** to both the Controls Table and the Device View
**DirectInput product-GUID matching (`src/utils/directinput_guid.py`)** — SC profile XML stores joysticks with a `Product` attribute like `{PIDVID-0000-0000-0000-504944564944}` (the trailing constant is "PIDVID" in ASCII; the first 8 hex chars encode `(PID << 16) | VID`). This module parses VID/PID out of that GUID so connected pygame joysticks (whose `get_guid()` returns SDL's joystick-GUID format) can be matched to profile entries without ever calling DirectInput. Pure parsing, zero runtime deps. This powers the Config tab's device-to-joystick mapping.
+**Check Profile (`src/utils/profile_checker.py`, `src/utils/system_devices.py`, `src/gui/profile_check_dialog.py`)** — Reads the raw profile XML (exported layout or live `actionmaps.xml`, which wraps everything in ``) and reports problems as findings with severities. The device-numbering check compares each `` VID/PID with the Nth connected stick; `system_devices.py` gets that order from DirectInput on Windows (what SC uses), pygame elsewhere (approximate), or the mock backend. Unsaved edits are checked via a temp XML export.
+
**Theme system (`src/gui/theme.py`)** — Ported from sibling project `smart-citizen` for visual cohesion. Themes are applied by swapping the `QPalette` on the `QApplication`; widgets relying on `WindowText`/`Text` palette roles re-color automatically. Secondary/dim labels opt in via `setProperty("role", "secondary")` and an app-level QSS rule installed by `apply_theme`. The branded `Hyperspace Race Expanded` font (`assets/fonts/HyperspaceRace-ExpandedBold.otf`) is registered at startup via `load_application_fonts()` — the family name Qt reports is the prefixed `"FONTSPRING DEMO - …"` string, which is what the title bar matches.
**Input detection (`src/utils/input_detector.py`)** — Joystick (pygame), keyboard with modifier support (pynput), mouse (pynput). Runs in a thread with a 10-second timeout; communicates with the UI via Qt signals. Used by the Remap Dialog. Joysticks are read through `src/utils/joystick_backend.py` (pygame by default); `--mock-joysticks [file.json]` / `SCPE_MOCK_JOYSTICKS` swaps in virtual sticks plus a Virtual Joysticks panel, so device and Remap work can be tested with no hardware (see `docs/DEVELOPMENT.md`).
@@ -90,7 +92,7 @@ docs/ CHANGELOG, DEVELOPMENT, RELEASE_PROCESS, CREATING_PDF_TEMP
scripts/ ad-hoc utility scripts (NOT build scripts — see Build below)
includes generate_pdf_template.py used by the Add-Device-from-Template flow
deprecated/ old SVG/PNG/OCR system removed in v0.4.0; ignore unless excavating history
-tests/ pytest unit tests: test_parser.py, test_directinput_guid.py, test_parse_joy_label.py
+tests/ pytest unit tests (parser, DI GUIDs, joy labels, joystick backend, profile checker)
ABOUT.md rendered in the About tab at runtime (bundled into the exe)
README.md end-user guide (also rendered in-app)
VERSION.TXT single source of truth for version (read by src/utils/version.py)
diff --git a/README.md b/README.md
index d4c7de3..fbc64ba 100644
--- a/README.md
+++ b/README.md
@@ -180,6 +180,19 @@ All export buttons are in the top header. Exports respect your current view (def
All exports use the **"Show Detailed"** setting - uncheck it for simplified exports, check it for complete details.
+### Checking a Profile for Problems
+
+Click **"Check Profile"** in the top header (enabled once a profile is loaded). SCPE looks for problems the game won't warn you about:
+
+- **Device numbering** — compares the profile's js1, js2, … with the order this PC numbers your sticks right now. If they differ, bindings meant for one stick land on another in game. The dialog shows both side by side; re-plug the sticks and press **Check again** until every slot matches.
+- **Sticks missing or added** — a profile stick that isn't connected, or a connected stick the profile doesn't know (which can push the others to higher numbers).
+- **View actions forced to "press"** — look behind, view yaw and similar are hold actions; a forced "press" can leave the camera stuck.
+- **One button switching several modes** — e.g. set salvage mode and toggle mining mode on the same button.
+- **Tuning saved under an old device ID** — deadzone/saturation stored for an ID no stick in the profile has, so the game ignores it.
+- **Partly bound hats**, **bindings on buttons a stick doesn't have**, and **js1 never cleared** (so the game's default joystick bindings still apply on it).
+
+Unsaved edits are included in the check. On Windows, SCPE reads the stick order from DirectInput, the same source Star Citizen uses.
+
### Filtering and Searching Bindings
The **Controls Table** has multiple ways to find and organize what you're looking for:
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 71c5671..ce94a08 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Mislabeled Virpil templates** (issue #31) — `VPC MT-50CM3 (Left/Right)` are actually Alpha Prime grip diagrams on a MongoosT-50CM3 base and are now named that way. A dedicated MT-50CM3 **throttle** template still needs to be authored.
### Added
+- **Check Profile** — A new header button checks the loaded profile (including unsaved edits) for problems Star Citizen doesn't report: the profile's js1/js2/… devices numbered differently from how this PC currently lists the sticks (so bindings would land on the wrong stick), profile sticks not connected or connected sticks missing from the profile, view/look actions forced to `activationMode="press"` (stuck camera), one input bound to several mode switches, deadzone/saturation tuning stored under a device ID no profile stick has, partly bound hats, bindings on buttons/hats a stick doesn't have, and js1 never cleared so game-default joystick bindings still apply. On Windows the stick order comes from DirectInput (the order the game uses, via `ctypes`, no new dependency); elsewhere from pygame, and in `--mock-joysticks` mode from the virtual sticks, so it is testable without hardware. **Check again** re-reads the sticks after re-plugging.
- **Develop and test without joysticks attached** — Joystick access now goes through a swappable backend (`src/utils/joystick_backend.py`). Run `python src/main.py --mock-joysticks [devices.json]` (or set `SCPE_MOCK_JOYSTICKS`) to replace real sticks with virtual ones described in a JSON file; a **Virtual Joysticks** panel opens beside the main window, and clicking its buttons, hats and axis sliders feeds the Remap dialog's *Detect Input* exactly as a real stick would. Presets in `tests/fixtures/mock_devices/` carry the VID/PID of the sticks in `example-profiles/`, so Config-tab mapping and Device View behave as on the joystick machine. The virtual setup can mirror any SC profile: by default it rebuilds from each profile you open (names, VID/PID, and enough buttons/hats for every binding), **Load setup…** picks any profile or devices file, and `--mock-joysticks` also accepts a profile `.xml`. Input-code translation is now a pure function with unit tests, and scripted fixtures replay recorded event sequences through the real detector loop in pytest. Normal launches are unchanged.
- **Release process ported from smart-citizen** — Long-lived `release/X.Y.Z` integration branches; PRs target the release branch and merging it to `main` is the release trigger. New workflows: `ci.yml` (tests + PyInstaller build verification on every PR to `main`/`release/**`), `release.yml` (on merge to `main`: auto-tags `v{VERSION}` from `VERSION.TXT`, builds the installer, publishes the GitHub Release with the CHANGELOG section as its body, posts to Discord), `installer-preview.yml` (add the `build-installer` label to a PR for a tester installer artifact), `installer-preview-cleanup.yml`, and `release-notify.yml` (manual Discord re-post). `.github/CODEOWNERS` requests review from the maintainer on every PR. `/start_release`, `/pre_release` and `/ship_release` commands walk the cycle with checkpoints; `docs/RELEASE_PROCESS.md` documents it.
- **Scripted build** — `scripts/build/build_exe.py` (PyInstaller `--onedir`, stable `SCProfileEditor.exe` name so shortcuts survive upgrades) and `scripts/build/build_all.bat`. `installer.iss` now reads the version from `VERSION.TXT` at compile time, so `VERSION.TXT` is the single place to bump. `scripts/release_notes.py` extracts a version's CHANGELOG section for the release body. `requirements-dev.txt` holds the test/build deps.
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 835119e..45c2ce0 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -39,7 +39,7 @@ Logging level is set in `src/main.py` — flip `logging.INFO` → `logging.DEBUG
## Testing
-There is no UI test harness. Unit tests cover the parser, DirectInput GUID parsing, label parsing, and joystick input translation / the mock backend; all run without hardware.
+There is no UI test harness. Unit tests cover the parser, DirectInput GUID parsing, label parsing, joystick input translation / the mock backend, and the Check Profile logic; all run without hardware.
```bash
pytest tests/
@@ -88,6 +88,14 @@ A **Virtual Joysticks** window opens next to the main window. Open a binding, pr
Copy `product` straight from an `` line in an SC profile (or give `"vid"`/`"pid"` as hex strings) to mimic your own sticks. The optional `script` replays events each time detection starts; tests use it to run the real detection loop against recorded sequences (`tests/test_joystick_backend.py`, `recorded_session.json`).
+**Check Profile without hardware.** In mock mode the virtual sticks are "this PC" for the Check Profile dialog, in panel order. To see a device-numbering mismatch, start with a devices file that lists the sticks in a different order from the profile:
+
+```bash
+python src/main.py --mock-joysticks tests/fixtures/mock_devices/check_profile_swapped.json
+```
+
+then open `tests/fixtures/profiles/check_profile_problems.xml` and click **Check Profile**: FSM.GA and T-Rudder show as swapped, along with one example of every other check. The logic lives in `src/utils/profile_checker.py` (pure, no Qt) and `src/utils/system_devices.py` (DirectInput order on Windows, pygame elsewhere, mock sticks in mock mode); `tests/test_profile_checker.py` covers it.
+
The devices file's order is the js order: the first device is `js1`. Mock mode is a developer flag only; release builds behave exactly as before unless it is passed.
**Other routes** if you need Star Citizen itself to see a fake stick (not just SCPE): install vJoy on Windows and drive it from a feeder app or `pyvjoy`. SCPE's pygame backend picks vJoy devices up like any other stick, no mock mode needed. `test_plan.md` and `TEST_PLAN_v0.8.2.md` at the repo root are historical references for what coverage typically looks like.
diff --git a/src/gui/main_window.py b/src/gui/main_window.py
index 4873fe2..65e288c 100644
--- a/src/gui/main_window.py
+++ b/src/gui/main_window.py
@@ -192,6 +192,16 @@ def setup_ui(self):
self.save_profile_btn.setEnabled(False) # Disabled until profile is modified
action_row.addWidget(self.save_profile_btn)
+ self.check_profile_btn = QPushButton("Check Profile")
+ self.check_profile_btn.setStyleSheet("QPushButton { padding: 10px 20px; font-size: 14px; }")
+ self.check_profile_btn.setToolTip(
+ "Look for problems the game won't tell you about: sticks numbered differently on this PC, "
+ "view actions stuck on \"press\", one button switching several modes, tuning saved under "
+ "an old device ID, and more")
+ self.check_profile_btn.clicked.connect(self.check_profile)
+ self.check_profile_btn.setEnabled(False)
+ action_row.addWidget(self.check_profile_btn)
+
# Neutral-chrome buttons (export + help) inherit the theme's default
# Button palette role.
_neutral_btn_qss = "QPushButton { padding: 10px 20px; font-size: 14px; }"
@@ -934,6 +944,7 @@ def display_profile(self):
self.profile_name_input.setText(profile.profile_name)
self.profile_name_input.setEnabled(True)
self.update_profile_name_btn.setEnabled(True)
+ self.check_profile_btn.setEnabled(True)
# Update profile info label
self.profile_info_label.setText(f"Profile: {profile.profile_name}")
@@ -2417,6 +2428,34 @@ def on_update_profile_name(self):
logger.info(f"Profile name updated to: {new_name}")
+ def _profile_xml_for_check(self, temp_dir: str):
+ """The XML to check: the file on disk, or a temp export when the
+ profile has unsaved edits (or was never saved)."""
+ profile = self.current_profile
+ if not profile:
+ return None
+ source = profile.source_xml_path or self.current_profile_path
+ if source and os.path.exists(source) and not profile.is_modified:
+ return source
+ from exporters.xml_exporter import export_profile, XMLExporter
+ out = os.path.join(temp_dir, "profile_to_check.xml")
+ if source and os.path.exists(source):
+ ok = export_profile(profile, source, out)
+ else:
+ ok = XMLExporter.create_new_profile(profile, out)
+ return out if ok else None
+
+ def check_profile(self):
+ """Open the Check Profile dialog for the current profile."""
+ if not self.current_profile:
+ return
+ import tempfile
+ from gui.profile_check_dialog import ProfileCheckDialog
+ with tempfile.TemporaryDirectory(prefix="scpe-check-") as temp_dir:
+ dialog = ProfileCheckDialog(lambda: self._profile_xml_for_check(temp_dir),
+ self.current_profile.profile_name, self)
+ dialog.exec()
+
def save_profile(self):
"""Save the modified profile to XML"""
if not self.current_profile or not self.current_profile.is_modified:
diff --git a/src/gui/profile_check_dialog.py b/src/gui/profile_check_dialog.py
new file mode 100644
index 0000000..1a81793
--- /dev/null
+++ b/src/gui/profile_check_dialog.py
@@ -0,0 +1,150 @@
+"""Check Profile dialog: shows what ``utils.profile_checker`` found.
+
+The device table compares the profile's js1/js2/... with the order this PC
+numbers its sticks right now; the list below it explains each problem.
+"Check again" re-reads the connected sticks, so the user can re-plug a
+stick and confirm the order is fixed without closing the dialog.
+"""
+import html
+import logging
+from typing import Callable, Optional
+
+from PyQt6.QtCore import Qt
+from PyQt6.QtGui import QColor, QBrush
+from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
+ QTableWidget, QTableWidgetItem, QTextBrowser, QHeaderView,
+ QGroupBox)
+
+from utils.profile_checker import CheckReport, check_profile, ERROR, WARNING, INFO
+from utils.system_devices import list_system_joysticks
+
+logger = logging.getLogger(__name__)
+
+_SEVERITY_LABEL = {ERROR: "Fix before playing", WARNING: "Problem", INFO: "Worth a look"}
+_SEVERITY_ICON = {ERROR: "⛔", WARNING: "⚠️", INFO: "ℹ️"}
+_STATUS_TEXT = {
+ "ok": "✓ Matches",
+ "swapped": "✗ Different stick in this slot",
+ "missing": "✗ Not connected",
+ "extra": "Not in profile",
+ "unknown": "? Can't tell",
+}
+_STATUS_COLOR = {"ok": "#2E7D32", "swapped": "#C62828", "missing": "#C62828"}
+
+
+def _fmt_id(vid_pid) -> str:
+ return f" ({vid_pid[0]:04X}:{vid_pid[1]:04X})" if vid_pid else ""
+
+
+class ProfileCheckDialog(QDialog):
+ def __init__(self, xml_path_provider: Callable[[], Optional[str]], profile_label: str, parent=None):
+ """``xml_path_provider`` returns the XML file to check (the main
+ window writes unsaved edits to a temp file first)."""
+ super().__init__(parent)
+ self._xml_path_provider = xml_path_provider
+ self.setWindowTitle(f"Check Profile — {profile_label}")
+ self.resize(900, 680)
+
+ layout = QVBoxLayout(self)
+
+ self.summary_label = QLabel()
+ self.summary_label.setStyleSheet("font-size: 15px; font-weight: bold; margin: 4px 0;")
+ self.summary_label.setWordWrap(True)
+ layout.addWidget(self.summary_label)
+
+ devices_box = QGroupBox("Device numbering: profile vs this PC")
+ devices_layout = QVBoxLayout(devices_box)
+ self.devices_table = QTableWidget(0, 4)
+ self.devices_table.setHorizontalHeaderLabels(["Slot", "In the profile", "On this PC now", "Status"])
+ self.devices_table.verticalHeader().setVisible(False)
+ self.devices_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
+ self.devices_table.setSelectionMode(QTableWidget.SelectionMode.NoSelection)
+ header = self.devices_table.horizontalHeader()
+ header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
+ header.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
+ header.setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
+ header.setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
+ devices_layout.addWidget(self.devices_table)
+ self.source_label = QLabel()
+ self.source_label.setProperty("role", "secondary")
+ self.source_label.setWordWrap(True)
+ devices_layout.addWidget(self.source_label)
+ layout.addWidget(devices_box, 2)
+
+ self.findings_view = QTextBrowser()
+ self.findings_view.setOpenExternalLinks(False)
+ layout.addWidget(self.findings_view, 3)
+
+ buttons = QHBoxLayout()
+ buttons.addStretch()
+ recheck_btn = QPushButton("Check again")
+ recheck_btn.setToolTip("Re-read the connected joysticks and the profile, e.g. after re-plugging a stick")
+ recheck_btn.clicked.connect(self.run_check)
+ buttons.addWidget(recheck_btn)
+ close_btn = QPushButton("Close")
+ close_btn.clicked.connect(self.accept)
+ buttons.addWidget(close_btn)
+ layout.addLayout(buttons)
+
+ self.report: Optional[CheckReport] = None
+ self.run_check()
+
+ def run_check(self):
+ try:
+ path = self._xml_path_provider()
+ if not path:
+ raise ValueError("There is no profile file to check.")
+ system = list_system_joysticks()
+ self.report = check_profile(path, system.devices)
+ except Exception as e:
+ logger.error(f"Profile check failed: {e}", exc_info=True)
+ self.summary_label.setText(f"Couldn't check this profile: {e}")
+ self.devices_table.setRowCount(0)
+ self.findings_view.clear()
+ return
+
+ self._show_devices(self.report)
+ note = f"This PC's order comes from {system.source_label}."
+ if not system.exact_order:
+ note += (" That can list sticks in a different order than the game does, so treat a"
+ " numbering mismatch here as a hint and confirm it in game.")
+ if not system.devices:
+ note = "No joysticks are connected right now, so the numbering couldn't be compared."
+ self.source_label.setText(note)
+ self._show_findings(self.report)
+
+ def _show_devices(self, report: CheckReport):
+ self.devices_table.setRowCount(len(report.devices))
+ for r, row in enumerate(report.devices):
+ cells = [row.slot,
+ (row.profile_name or "—") + _fmt_id(row.profile_vid_pid),
+ (row.system_name or "—") + _fmt_id(row.system_vid_pid),
+ _STATUS_TEXT.get(row.status, row.status)]
+ for c, text in enumerate(cells):
+ item = QTableWidgetItem(text)
+ if c == 3 and row.status in _STATUS_COLOR:
+ item.setForeground(QBrush(QColor(_STATUS_COLOR[row.status])))
+ self.devices_table.setItem(r, c, item)
+
+ def _show_findings(self, report: CheckReport):
+ errors, warnings, infos = report.count(ERROR), report.count(WARNING), report.count(INFO)
+ if not report.findings:
+ self.summary_label.setText("✓ No problems found.")
+ else:
+ parts = []
+ if errors:
+ parts.append(f"{errors} to fix before playing")
+ if warnings:
+ parts.append(f"{warnings} problem{'s' if warnings != 1 else ''}")
+ if infos:
+ parts.append(f"{infos} worth a look")
+ self.summary_label.setText("Found " + ", ".join(parts) + ".")
+
+ chunks = []
+ for f in report.findings:
+ chunks.append(
+ f"
")
+ self.findings_view.setHtml("".join(chunks) or "
Nothing to report.
")
diff --git a/src/utils/profile_checker.py b/src/utils/profile_checker.py
new file mode 100644
index 0000000..0be76d3
--- /dev/null
+++ b/src/utils/profile_checker.py
@@ -0,0 +1,481 @@
+"""Check a Star Citizen profile for problems the game won't tell you about.
+
+Pure logic: reads the profile XML (either an exported ``layout_*.xml`` or the
+live ``actionmaps.xml``) and, optionally, the list of joysticks this PC has
+connected, and returns a list of findings. No Qt, no hardware access, so it
+is fully unit-testable and works the same with ``--mock-joysticks``.
+
+Checks
+------
+device_order The profile's js1/js2/... devices vs the order this PC
+ numbers its sticks. A mismatch means bindings land on the
+ wrong stick in game.
+device_missing A profile stick that isn't connected, or a connected
+ stick the profile doesn't know about.
+device_unknown Bindings on a jsN the profile has no device for.
+no_such_input A binding on a button/hat the connected stick doesn't have.
+forced_press ``activationMode="press"`` on a view/look action (or a
+ ``*_hold`` action): the camera can stay stuck.
+partial_hat A hat with some directions bound and the rest free.
+mode_switch_clash One input bound to two or more mode switches.
+stale_tuning Deadzone/saturation/curve tuning stored under a device ID
+ that no stick in the profile has, so the game ignores it.
+js1_defaults js1 was never cleared, so the game's default joystick
+ bindings still apply on it alongside yours.
+"""
+from __future__ import annotations
+
+import re
+import xml.etree.ElementTree as ET
+from collections import defaultdict
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional, Sequence, Tuple
+
+from utils.directinput_guid import parse_di_product_guid
+
+ERROR = "error"
+WARNING = "warning"
+INFO = "info"
+SEVERITY_ORDER = {ERROR: 0, WARNING: 1, INFO: 2}
+
+HAT_DIRECTIONS = ("up", "down", "left", "right")
+
+_JS_INPUT_RE = re.compile(r"^js(\d+)_(.*)$", re.IGNORECASE)
+_BUTTON_RE = re.compile(r"^button(\d+)$", re.IGNORECASE)
+_HAT_RE = re.compile(r"^hat(\d+)_(up|down|left|right)$", re.IGNORECASE)
+_MODE_SWITCH_RE = re.compile(r"^v_(set|toggle)_[a-z]+_mode$|^v_master_mode_set_[a-z]+$")
+_VIEW_ACTION_RE = re.compile(r"(^v_view_|look_behind|freelook|_look_(left|right|up|down)$)")
+
+
+@dataclass
+class Finding:
+ check: str
+ severity: str
+ title: str
+ detail: str
+ inputs: List[str] = field(default_factory=list)
+
+
+@dataclass
+class DeviceRow:
+ """One line of the device-order table: profile slot vs this PC."""
+ slot: str # "js1"
+ profile_name: str # "" when the profile has none
+ profile_vid_pid: Optional[Tuple[int, int]]
+ system_name: str # "" when nothing is in that slot
+ system_vid_pid: Optional[Tuple[int, int]]
+ status: str # "ok" | "swapped" | "missing" | "extra" | "unknown"
+
+
+@dataclass
+class CheckReport:
+ findings: List[Finding]
+ devices: List[DeviceRow]
+ profile_name: str = ""
+ system_checked: bool = False
+
+ def count(self, severity: str) -> int:
+ return sum(1 for f in self.findings if f.severity == severity)
+
+ @property
+ def ok(self) -> bool:
+ return not self.findings
+
+
+@dataclass
+class _Binding:
+ actionmap: str
+ action: str
+ input: str
+ activation_mode: Optional[str]
+
+
+@dataclass
+class _ProfileDevice:
+ instance: int
+ name: str
+ vid_pid: Optional[Tuple[int, int]]
+
+
+# ---------------------------------------------------------------------------
+# Reading the XML
+# ---------------------------------------------------------------------------
+
+def _profile_root(root: ET.Element) -> ET.Element:
+ """Live actionmaps.xml wraps everything in ; exported
+ layouts don't. Prefer the profile named "default" when there are several."""
+ profiles = root.findall("ActionProfiles")
+ if not profiles:
+ return root
+ for p in profiles:
+ if p.get("profileName") == "default":
+ return p
+ return profiles[0]
+
+
+def _clean_name(product: str) -> str:
+ return " ".join(product.split("{")[0].split())
+
+
+def _read_devices(root: ET.Element) -> Dict[int, _ProfileDevice]:
+ devices: Dict[int, _ProfileDevice] = {}
+ for opt in root.findall("options"):
+ if (opt.get("type") or "").lower() != "joystick":
+ continue
+ try:
+ instance = int(opt.get("instance", "0"))
+ except ValueError:
+ continue
+ product = opt.get("Product") or ""
+ if not product.strip():
+ continue
+ devices[instance] = _ProfileDevice(instance, _clean_name(product), parse_di_product_guid(product))
+ return devices
+
+
+def _read_bindings(root: ET.Element) -> List[_Binding]:
+ out: List[_Binding] = []
+ for amap in root.iter("actionmap"):
+ map_name = amap.get("name", "")
+ for action in amap.findall("action"):
+ action_name = action.get("name", "")
+ for rebind in action.findall("rebind"):
+ value = rebind.get("input")
+ if value is None:
+ continue
+ out.append(_Binding(map_name, action_name, value.strip(), rebind.get("activationMode")))
+ return out
+
+
+def _js_parts(input_code: str) -> Optional[Tuple[int, str]]:
+ m = _JS_INPUT_RE.match(input_code)
+ if not m:
+ return None
+ return int(m.group(1)), m.group(2)
+
+
+def _is_blank(input_code: str) -> bool:
+ parts = _js_parts(input_code)
+ return parts is not None and parts[1] == ""
+
+
+# ---------------------------------------------------------------------------
+# Checks
+# ---------------------------------------------------------------------------
+
+def _fmt_vid_pid(vid_pid: Optional[Tuple[int, int]]) -> str:
+ return f"{vid_pid[0]:04X}:{vid_pid[1]:04X}" if vid_pid else "unknown ID"
+
+
+def _check_forced_press(bindings: List[_Binding]) -> List[Finding]:
+ view, hold = [], []
+ for b in bindings:
+ if (b.activation_mode or "").lower() != "press" or _is_blank(b.input):
+ continue
+ if _VIEW_ACTION_RE.search(b.action):
+ view.append(b)
+ elif b.action.endswith("_hold"):
+ hold.append(b)
+ findings = []
+ for b in view:
+ findings.append(Finding(
+ "forced_press", WARNING,
+ f"{b.action} on {b.input} is forced to \"press\"",
+ "View and look actions are hold actions in the game. Forcing \"press\" overrides that, "
+ "so the camera can stay turned after you let go. Set the activation mode back to "
+ "(Game default).",
+ [b.input]))
+ for b in hold:
+ findings.append(Finding(
+ "forced_press", INFO,
+ f"{b.action} on {b.input} is forced to \"press\"",
+ "This action is meant to be held. If it behaves oddly, set its activation mode back to "
+ "(Game default).",
+ [b.input]))
+ return findings
+
+
+def _check_partial_hats(bindings: List[_Binding], devices: Dict[int, _ProfileDevice]) -> List[Finding]:
+ bound: Dict[Tuple[int, int], set] = defaultdict(set)
+ # Actions cleared to "jsN_ " that still carry an activation mode: a
+ # binding that used to be there and was deleted.
+ cleared: Dict[int, List[str]] = defaultdict(list)
+ for b in bindings:
+ parts = _js_parts(b.input)
+ if not parts:
+ continue
+ if not parts[1]:
+ if b.activation_mode and _VIEW_ACTION_RE.search(b.action):
+ cleared[parts[0]].append(b.action)
+ continue
+ m = _HAT_RE.match(parts[1])
+ if m:
+ bound[(parts[0], int(m.group(1)))].add(m.group(2).lower())
+ findings = []
+ for (js, hat), dirs in sorted(bound.items()):
+ free = [d for d in HAT_DIRECTIONS if d not in dirs]
+ if not free:
+ continue
+ dev = devices.get(js)
+ where = f"js{js}" + (f" ({dev.name})" if dev else "")
+ detail = f"Only {', '.join(d for d in HAT_DIRECTIONS if d in dirs)} is bound on this hat."
+ lost = sorted(set(cleared.get(js, [])))
+ if lost:
+ detail += (f" These view actions were cleared on js{js} but kept their activation mode, "
+ f"which suggests they used to be on this hat: {', '.join(lost)}.")
+ else:
+ detail += " If the other directions used to do something, they were cleared."
+ findings.append(Finding(
+ "partial_hat", WARNING if lost else INFO,
+ f"Hat {hat} on {where}: {', '.join(free)} unbound",
+ detail,
+ [f"js{js}_hat{hat}_{d}" for d in free]))
+ return findings
+
+
+def _check_mode_switch_clash(bindings: List[_Binding]) -> List[Finding]:
+ by_input: Dict[str, List[_Binding]] = defaultdict(list)
+ for b in bindings:
+ if b.input and not _is_blank(b.input) and _MODE_SWITCH_RE.match(b.action):
+ by_input[b.input.lower()].append(b)
+ findings = []
+ for code, group in sorted(by_input.items()):
+ modes = {}
+ for b in group:
+ key = (b.activation_mode or "").lower()
+ modes.setdefault(key, []).append(b.action)
+ for mode, actions in modes.items():
+ actions = sorted(set(actions))
+ # set_scan_mode + toggle_scan_mode on one button is the same mode.
+ if len({_mode_word(a) for a in actions}) < 2:
+ continue
+ findings.append(Finding(
+ "mode_switch_clash", WARNING,
+ f"{group[0].input} switches {len(actions)} modes at once",
+ f"{', '.join(actions)} are all on {group[0].input}"
+ + (f" ({mode})" if mode else "")
+ + ". One press fires all of them, so you end up in whichever mode the game applies "
+ "last. Move all but one to a free button.",
+ [group[0].input]))
+ return findings
+
+
+def _mode_word(action: str) -> str:
+ m = re.match(r"^v_(?:set|toggle)_([a-z]+)_mode$", action)
+ return m.group(1) if m else action
+
+
+def _check_stale_tuning(root: ET.Element, devices: Dict[int, _ProfileDevice]) -> List[Finding]:
+ present = {d.vid_pid for d in devices.values() if d.vid_pid}
+ findings = []
+ for opts in root.findall("deviceoptions"):
+ name_attr = opts.get("name") or ""
+ vid_pid = parse_di_product_guid(name_attr)
+ if vid_pid is None or vid_pid in present:
+ continue
+ name = _clean_name(name_attr)
+ similar = [d for d in devices.values()
+ if d.vid_pid and d.vid_pid[0] == vid_pid[0] and _names_related(d.name, name)]
+ if similar:
+ target = similar[0]
+ findings.append(Finding(
+ "stale_tuning", WARNING,
+ f"Tuning for \"{name}\" ({_fmt_vid_pid(vid_pid)}) isn't applied",
+ f"The deadzone/saturation settings are stored under device ID {_fmt_vid_pid(vid_pid)}, "
+ f"but your stick now reports as \"{target.name}\" ({_fmt_vid_pid(target.vid_pid)}, "
+ f"js{target.instance}). The game ignores tuning for IDs that aren't present. "
+ "Move the settings to the new ID or set them again in game.",
+ []))
+ else:
+ findings.append(Finding(
+ "stale_tuning", INFO,
+ f"Tuning for \"{name}\" belongs to a device not in this profile",
+ "Harmless: the game ignores it. It only matters if you plug that device back in.",
+ []))
+ return findings
+
+
+def _names_related(a: str, b: str) -> bool:
+ a, b = a.lower(), b.lower()
+ return a.startswith(b) or b.startswith(a)
+
+
+def _check_js1_defaults(bindings: List[_Binding], devices: Dict[int, _ProfileDevice]) -> List[Finding]:
+ blanks: Dict[int, int] = defaultdict(int)
+ for b in bindings:
+ if _is_blank(b.input):
+ blanks[_js_parts(b.input)[0]] += 1
+ if 1 not in devices or blanks.get(1) or not blanks:
+ return []
+ cleared = ", ".join(f"js{js} ({n})" for js, n in sorted(blanks.items()))
+ return [Finding(
+ "js1_defaults", INFO,
+ f"js1 ({devices[1].name}) was never cleared",
+ f"Cleared entries exist for {cleared} but none for js1. The game's default joystick "
+ "bindings sit on js1, so they still apply alongside yours. If a button on this stick "
+ "does an extra, unexpected thing, this is why.",
+ [])]
+
+
+def _check_unknown_slots(bindings: List[_Binding], devices: Dict[int, _ProfileDevice]) -> List[Finding]:
+ used: Dict[int, int] = defaultdict(int)
+ for b in bindings:
+ parts = _js_parts(b.input)
+ if parts and parts[1]:
+ used[parts[0]] += 1
+ findings = []
+ for js, n in sorted(used.items()):
+ if js not in devices:
+ findings.append(Finding(
+ "device_unknown", WARNING,
+ f"{n} binding{'s' if n != 1 else ''} on js{js}, but the profile doesn't say which stick that is",
+ "Without a device recorded for this slot, nothing ties these bindings to a particular "
+ "stick. They will go to whatever the game numbers js" + str(js) + ".",
+ []))
+ return findings
+
+
+def _check_system(bindings: List[_Binding], devices: Dict[int, _ProfileDevice],
+ system: Sequence) -> Tuple[List[Finding], List[DeviceRow]]:
+ """Compare profile slots with the connected sticks, in system order."""
+ findings: List[Finding] = []
+ rows: List[DeviceRow] = []
+
+ sys_by_slot = {i + 1: dev for i, dev in enumerate(system)}
+ sys_slots_by_id: Dict[Tuple[int, int], List[int]] = defaultdict(list)
+ for slot, dev in sys_by_slot.items():
+ if dev.vid_pid:
+ sys_slots_by_id[dev.vid_pid].append(slot)
+
+ used_slots = {p[0] for p in (_js_parts(b.input) for b in bindings) if p and p[1]}
+ max_slot = max([0, len(system), *devices.keys(), *used_slots])
+
+ for slot in range(1, max_slot + 1):
+ pdev = devices.get(slot)
+ sdev = sys_by_slot.get(slot)
+ if pdev is None and sdev is None:
+ continue
+ if pdev is None and sdev.vid_pid is None and slot not in used_slots:
+ continue # unidentified extra (e.g. a virtual placeholder) with nothing bound
+ if pdev is None:
+ status = "extra"
+ elif sdev is None:
+ status = "missing"
+ elif pdev.vid_pid is None or sdev.vid_pid is None:
+ status = "ok" if _names_related(pdev.name, (sdev.name or "").strip()) else "unknown"
+ else:
+ status = "ok" if pdev.vid_pid == sdev.vid_pid else "swapped"
+ rows.append(DeviceRow(f"js{slot}", pdev.name if pdev else "",
+ pdev.vid_pid if pdev else None,
+ (sdev.name or "").strip() if sdev else "",
+ sdev.vid_pid if sdev else None, status))
+
+ # One finding per profile stick that won't be where the profile expects it.
+ for slot, pdev in sorted(devices.items()):
+ sdev = sys_by_slot.get(slot)
+ if pdev.vid_pid is None:
+ continue
+ if sdev is not None and sdev.vid_pid == pdev.vid_pid:
+ continue
+ now = sys_slots_by_id.get(pdev.vid_pid, [])
+ n_bind = sum(1 for b in bindings if (_js_parts(b.input) or (0, ""))[0] == slot
+ and (_js_parts(b.input) or (0, ""))[1])
+ if now:
+ other = (sdev.name or "").strip() if sdev else "nothing"
+ findings.append(Finding(
+ "device_order", ERROR,
+ f"{pdev.name} is js{slot} in the profile but js{now[0]} on this PC",
+ f"This PC currently numbers its sticks differently from the profile. In game, "
+ f"the {n_bind} js{slot} binding{'s' if n_bind != 1 else ''} meant for {pdev.name} will go to "
+ f"{other} instead. Before you play, get the PC to list the sticks in the profile's order "
+ f"(usually by re-plugging them, or using the same USB ports as when the profile was made), "
+ f"then press Check again.",
+ []))
+ else:
+ findings.append(Finding(
+ "device_missing", WARNING,
+ f"{pdev.name} (js{slot}) isn't connected",
+ f"Its {n_bind} binding{'s' if n_bind != 1 else ''} won't work, and with it missing the game "
+ "may number the sticks after it differently.",
+ []))
+
+ profile_ids = {d.vid_pid for d in devices.values() if d.vid_pid}
+ for slot, sdev in sys_by_slot.items():
+ if sdev.vid_pid and sdev.vid_pid not in profile_ids:
+ findings.append(Finding(
+ "device_missing", INFO,
+ f"{(sdev.name or '').strip() or 'A stick'} (js{slot} on this PC) isn't in the profile",
+ "The profile has no bindings recorded for this device. If it sits before your other "
+ "sticks in the order, it can push them to higher js numbers.",
+ []))
+
+ dup = [vp for vp, slots in sys_slots_by_id.items() if len(slots) > 1]
+ for vp in dup:
+ findings.append(Finding(
+ "device_order", INFO,
+ f"{len(sys_slots_by_id[vp])} identical sticks connected ({_fmt_vid_pid(vp)})",
+ "Identical models report the same ID, so this check can't tell them apart. If their "
+ "bindings feel swapped, swap the USB ports.",
+ []))
+
+ # Bindings on buttons/hats the connected stick in that slot doesn't have.
+ for slot, sdev in sys_by_slot.items():
+ pdev = devices.get(slot)
+ if pdev and pdev.vid_pid and sdev.vid_pid and pdev.vid_pid != sdev.vid_pid:
+ continue # already reported as a swap
+ too_high = []
+ for b in bindings:
+ parts = _js_parts(b.input)
+ if not parts or parts[0] != slot:
+ continue
+ mb, mh = _BUTTON_RE.match(parts[1]), _HAT_RE.match(parts[1])
+ if (mb and int(mb.group(1)) > sdev.buttons) or (mh and int(mh.group(1)) > sdev.hats):
+ too_high.append(b)
+ if too_high:
+ codes = sorted({b.input for b in too_high})
+ name = (sdev.name or "").strip()
+ findings.append(Finding(
+ "no_such_input", WARNING,
+ f"{len(too_high)} binding{'s' if len(too_high) != 1 else ''} on js{slot} ({name}) use inputs it doesn't have",
+ f"{name} has {sdev.buttons} button{'s' if sdev.buttons != 1 else ''} and "
+ f"{sdev.hats} hat{'s' if sdev.hats != 1 else ''}, so these bindings never fire: "
+ f"{', '.join(codes[:12])}{' …' if len(codes) > 12 else ''}.",
+ codes))
+ return findings, rows
+
+
+# ---------------------------------------------------------------------------
+# Entry point
+# ---------------------------------------------------------------------------
+
+def check_profile(xml_path: str, system_devices: Optional[Sequence] = None) -> CheckReport:
+ """Run every check on the profile at ``xml_path``.
+
+ ``system_devices`` is the list of connected joysticks in the order the
+ game numbers them (objects with ``name``, ``vid_pid``, ``buttons`` and
+ ``hats``, e.g. ``JoystickInfo``). Pass None to skip the checks that need
+ the PC's devices.
+ """
+ tree_root = ET.parse(xml_path).getroot()
+ root = _profile_root(tree_root)
+ devices = _read_devices(root)
+ bindings = _read_bindings(root)
+
+ findings: List[Finding] = []
+ rows: List[DeviceRow] = []
+ if system_devices is not None:
+ sys_findings, rows = _check_system(bindings, devices, system_devices)
+ findings += sys_findings
+ else:
+ rows = [DeviceRow(f"js{i}", d.name, d.vid_pid, "", None, "unknown")
+ for i, d in sorted(devices.items())]
+ findings += _check_unknown_slots(bindings, devices)
+ findings += _check_forced_press(bindings)
+ findings += _check_mode_switch_clash(bindings)
+ findings += _check_stale_tuning(root, devices)
+ findings += _check_partial_hats(bindings, devices)
+ findings += _check_js1_defaults(bindings, devices)
+
+ findings.sort(key=lambda f: SEVERITY_ORDER.get(f.severity, 9))
+ name = root.get("profileName") or tree_root.get("profileName") or ""
+ return CheckReport(findings, rows, name, system_devices is not None)
diff --git a/src/utils/system_devices.py b/src/utils/system_devices.py
new file mode 100644
index 0000000..92a4747
--- /dev/null
+++ b/src/utils/system_devices.py
@@ -0,0 +1,177 @@
+"""The joysticks this PC has connected, in the order the game numbers them.
+
+Star Citizen reads joysticks through DirectInput and numbers them js1, js2,
+... in the order DirectInput enumerates game controllers. When that order
+changes (a stick re-plugged into another USB port, a Windows update, a new
+device), every binding written for jsN lands on whichever stick is now Nth.
+
+``list_system_joysticks()`` returns the connected sticks in that order:
+
+- With ``--mock-joysticks`` the virtual sticks are the system, in panel order,
+ so the check is testable without hardware.
+- On Windows the list comes from DirectInput itself (``dinput8.dll`` via
+ ctypes, no extra dependency), which is the order the game uses.
+- Otherwise it falls back to the joystick backend (pygame/SDL). SDL can list
+ sticks in a different order than DirectInput, so the result is marked as
+ approximate.
+
+Button/hat counts come from the joystick backend, matched by VID/PID, since
+DirectInput enumeration does not report them.
+"""
+from __future__ import annotations
+
+import logging
+import sys
+from dataclasses import dataclass
+from typing import List, Optional, Tuple
+
+from utils.joystick_backend import JoystickInfo, get_backend
+
+logger = logging.getLogger(__name__)
+
+SOURCE_DIRECTINPUT = "directinput"
+SOURCE_PYGAME = "pygame"
+SOURCE_MOCK = "mock"
+
+
+@dataclass
+class SystemJoysticks:
+ devices: List[JoystickInfo]
+ source: str # one of the SOURCE_* constants
+ exact_order: bool # True when the order is the one the game uses
+
+ @property
+ def source_label(self) -> str:
+ if self.source == SOURCE_MOCK:
+ return "virtual joysticks (--mock-joysticks)"
+ if self.source == SOURCE_DIRECTINPUT:
+ return "Windows DirectInput (the order Star Citizen uses)"
+ return "pygame/SDL (order may differ from the game's)"
+
+
+def list_system_joysticks() -> SystemJoysticks:
+ backend = get_backend()
+ if getattr(backend, "is_mock", False):
+ return SystemJoysticks(list(backend.list_joysticks()), SOURCE_MOCK, True)
+
+ backend_devices: List[JoystickInfo] = []
+ try:
+ backend_devices = list(backend.list_joysticks())
+ except Exception as e: # pragma: no cover - hardware dependent
+ logger.warning(f"Joystick backend could not list devices: {e}")
+
+ if sys.platform == "win32":
+ try:
+ di = enumerate_directinput_joysticks()
+ except Exception as e: # pragma: no cover - Windows only
+ logger.warning(f"DirectInput enumeration failed, using pygame order: {e}")
+ di = None
+ if di is not None:
+ return SystemJoysticks(_merge_capabilities(di, backend_devices), SOURCE_DIRECTINPUT, True)
+
+ return SystemJoysticks(backend_devices, SOURCE_PYGAME, False)
+
+
+def _merge_capabilities(ordered: List[Tuple[str, Optional[Tuple[int, int]]]],
+ caps: List[JoystickInfo]) -> List[JoystickInfo]:
+ """Attach button/hat/axis counts from ``caps`` to DirectInput's list.
+
+ Identical models (same VID/PID) are paired up in order. A device the
+ backend could not see keeps generous defaults so it never triggers a
+ "this stick has no such button" finding by mistake.
+ """
+ remaining = list(caps)
+ out: List[JoystickInfo] = []
+ for name, vid_pid in ordered:
+ match = None
+ for i, info in enumerate(remaining):
+ if vid_pid is not None and info.vid_pid == vid_pid:
+ match = remaining.pop(i)
+ break
+ if match is not None:
+ out.append(JoystickInfo(name=name, vid_pid=vid_pid, buttons=match.buttons,
+ hats=match.hats, axes=match.axes))
+ else:
+ out.append(JoystickInfo(name=name, vid_pid=vid_pid, buttons=128, hats=4, axes=8))
+ return out
+
+
+def _looks_like_xinput_pad(name: str) -> bool:
+ n = (name or "").lower()
+ return "xbox" in n or n.startswith("controller (")
+
+
+def enumerate_directinput_joysticks() ->List[Tuple[str, Optional[Tuple[int, int]]]]: # pragma: no cover - Windows only
+ """Attached game controllers in DirectInput enumeration order.
+
+ Returns ``[(product_name, (vid, pid) or None), ...]``.
+ """
+ import ctypes
+ from ctypes import wintypes
+
+ class GUID(ctypes.Structure):
+ _fields_ = [("Data1", ctypes.c_uint32), ("Data2", ctypes.c_uint16),
+ ("Data3", ctypes.c_uint16), ("Data4", ctypes.c_ubyte * 8)]
+
+ class DIDEVICEINSTANCEW(ctypes.Structure):
+ _fields_ = [("dwSize", wintypes.DWORD),
+ ("guidInstance", GUID),
+ ("guidProduct", GUID),
+ ("dwDevType", wintypes.DWORD),
+ ("tszInstanceName", ctypes.c_wchar * 260),
+ ("tszProductName", ctypes.c_wchar * 260),
+ ("guidFFDriver", GUID),
+ ("wUsagePage", wintypes.WORD),
+ ("wUsage", wintypes.WORD)]
+
+ DIRECTINPUT_VERSION = 0x0800
+ DI8DEVCLASS_GAMECTRL = 4
+ DIEDFL_ATTACHEDONLY = 1
+ DIENUM_CONTINUE = 1
+ PIDVID = bytes(b"\x00\x00PIDVID") # Data4 of a DirectInput product GUID
+
+ iid = GUID(0xBF798031, 0x483A, 0x4DA2,
+ (ctypes.c_ubyte * 8)(0xAA, 0x99, 0x5D, 0x64, 0xED, 0x36, 0x97, 0x00))
+
+ dinput8 = ctypes.WinDLL("dinput8")
+ kernel32 = ctypes.WinDLL("kernel32")
+ kernel32.GetModuleHandleW.restype = wintypes.HMODULE
+ kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
+ dinput8.DirectInput8Create.restype = ctypes.c_long
+ dinput8.DirectInput8Create.argtypes = [wintypes.HINSTANCE, wintypes.DWORD, ctypes.POINTER(GUID),
+ ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p]
+
+ di = ctypes.c_void_p()
+ hr = dinput8.DirectInput8Create(kernel32.GetModuleHandleW(None), DIRECTINPUT_VERSION,
+ ctypes.byref(iid), ctypes.byref(di), None)
+ if hr != 0 or not di.value:
+ raise OSError(f"DirectInput8Create failed (HRESULT 0x{hr & 0xFFFFFFFF:08X})")
+
+ vtbl = ctypes.cast(di, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p))).contents
+ CALLBACK = ctypes.WINFUNCTYPE(wintypes.BOOL, ctypes.POINTER(DIDEVICEINSTANCEW), ctypes.c_void_p)
+ EnumDevices = ctypes.WINFUNCTYPE(ctypes.c_long, ctypes.c_void_p, wintypes.DWORD, CALLBACK,
+ ctypes.c_void_p, wintypes.DWORD)(vtbl[4])
+ Release = ctypes.WINFUNCTYPE(ctypes.c_ulong, ctypes.c_void_p)(vtbl[2])
+
+ found: List[Tuple[str, Optional[Tuple[int, int]]]] = []
+
+ def on_device(inst_ptr, _ref):
+ inst = inst_ptr.contents
+ prod = inst.guidProduct
+ vid_pid = None
+ if bytes(prod.Data4) == PIDVID and prod.Data2 == 0 and prod.Data3 == 0:
+ vid_pid = (prod.Data1 & 0xFFFF, (prod.Data1 >> 16) & 0xFFFF)
+ name = inst.tszProductName or inst.tszInstanceName
+ # Xbox-style pads are XInput "gamepad" devices to the game, not jsN.
+ if not _looks_like_xinput_pad(name):
+ found.append((name, vid_pid))
+ return DIENUM_CONTINUE
+
+ callback = CALLBACK(on_device)
+ try:
+ hr = EnumDevices(di, DI8DEVCLASS_GAMECTRL, callback, None, DIEDFL_ATTACHEDONLY)
+ if hr != 0:
+ raise OSError(f"EnumDevices failed (HRESULT 0x{hr & 0xFFFFFFFF:08X})")
+ finally:
+ Release(di)
+ return found
diff --git a/tests/fixtures/mock_devices/check_profile_swapped.json b/tests/fixtures/mock_devices/check_profile_swapped.json
new file mode 100644
index 0000000..5b2ba14
--- /dev/null
+++ b/tests/fixtures/mock_devices/check_profile_swapped.json
@@ -0,0 +1,8 @@
+{
+ "_comment": "Same sticks as tests/fixtures/profiles/check_profile_problems.xml, but the PC lists the T-Rudder first. Run: python src/main.py --mock-joysticks tests/fixtures/mock_devices/check_profile_swapped.json, open that profile, press Check Profile: FSM.GA and T-Rudder show as swapped.",
+ "devices": [
+ {"name": " VKBSim T-Rudder ", "product": "{011F231D-0000-0000-0000-504944564944}", "buttons": 0, "hats": 0, "axes": 3},
+ {"name": " VKBSim NXT FSM.GA ", "product": "{2220231D-0000-0000-0000-504944564944}", "buttons": 64, "hats": 2, "axes": 6},
+ {"name": " VKBsim Gladiator EVO L ", "product": "{0201231D-0000-0000-0000-504944564944}", "buttons": 34, "hats": 1, "axes": 6}
+ ]
+}
diff --git a/tests/fixtures/profiles/check_profile_problems.xml b/tests/fixtures/profiles/check_profile_problems.xml
new file mode 100644
index 0000000..2978fc7
--- /dev/null
+++ b/tests/fixtures/profiles/check_profile_problems.xml
@@ -0,0 +1,60 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/test_profile_checker.py b/tests/test_profile_checker.py
new file mode 100644
index 0000000..81f5143
--- /dev/null
+++ b/tests/test_profile_checker.py
@@ -0,0 +1,203 @@
+"""Tests for the Check Profile logic (utils.profile_checker) and the
+system-device listing it compares against, using mock joysticks."""
+import os
+import sys
+import unittest
+
+ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
+sys.path.insert(0, os.path.join(ROOT, "src"))
+sys.path.insert(0, ROOT)
+
+from utils import joystick_backend as jb
+from utils.joystick_backend import JoystickInfo, MockBackend
+from utils.profile_checker import check_profile, ERROR, WARNING, INFO
+from utils.system_devices import list_system_joysticks, SOURCE_MOCK
+
+FIXTURE = os.path.join(ROOT, "tests", "fixtures", "profiles", "check_profile_problems.xml")
+SWAPPED = os.path.join(ROOT, "tests", "fixtures", "mock_devices", "check_profile_swapped.json")
+EXAMPLES = os.path.join(ROOT, "example-profiles")
+
+FSM = (0x231D, 0x2220)
+RUDDER = (0x231D, 0x011F)
+EVO_L = (0x231D, 0x0201)
+
+
+def stick(name, vid_pid, buttons=64, hats=2):
+ return JoystickInfo(name=name, vid_pid=vid_pid, buttons=buttons, hats=hats, axes=6)
+
+
+IN_PROFILE_ORDER = [stick("VKBSim NXT FSM.GA", FSM), stick("VKBSim T-Rudder", RUDDER),
+ stick("VKBsim Gladiator EVO L", EVO_L)]
+
+
+def of(report, check, severity=None):
+ return [f for f in report.findings if f.check == check and (severity is None or f.severity == severity)]
+
+
+class TestProfileOnlyChecks(unittest.TestCase):
+ """Checks that need only the XML (the four problems from the 2026-11-18 repair)."""
+
+ @classmethod
+ def setUpClass(cls):
+ cls.report = check_profile(FIXTURE, None)
+
+ def test_forced_press_on_view_action(self):
+ found = of(self.report, "forced_press", WARNING)
+ self.assertEqual([f.inputs for f in found], [["js3_hat1_down"]])
+ self.assertIn("v_view_look_behind", found[0].title)
+
+ def test_forced_press_on_hold_action_is_info(self):
+ found = of(self.report, "forced_press", INFO)
+ self.assertEqual(len(found), 1)
+ self.assertIn("_hold", found[0].title)
+
+ def test_cleared_view_actions_are_not_flagged_as_forced_press(self):
+ titles = " ".join(f.title for f in of(self.report, "forced_press"))
+ self.assertNotIn("yaw", titles)
+
+ def test_partial_hat_with_cleared_view_actions_is_a_warning(self):
+ found = of(self.report, "partial_hat")
+ self.assertEqual(len(found), 1)
+ self.assertEqual(found[0].severity, WARNING)
+ self.assertEqual(found[0].inputs, ["js3_hat1_up", "js3_hat1_left", "js3_hat1_right"])
+ self.assertIn("v_view_yaw_left", found[0].detail)
+
+ def test_one_button_two_modes(self):
+ found = of(self.report, "mode_switch_clash")
+ self.assertEqual([f.inputs for f in found], [["js3_button27"]])
+ self.assertIn("v_set_salvage_mode", found[0].detail)
+ self.assertIn("v_toggle_mining_mode", found[0].detail)
+
+ def test_set_and_toggle_of_the_same_mode_is_fine(self):
+ self.assertNotIn(["js3_button29"], [f.inputs for f in of(self.report, "mode_switch_clash")])
+
+ def test_tuning_under_old_device_id(self):
+ warn = of(self.report, "stale_tuning", WARNING)
+ self.assertEqual(len(warn), 1)
+ self.assertIn("231D:0205", warn[0].title)
+ self.assertIn("js3", warn[0].detail)
+ info = of(self.report, "stale_tuning", INFO)
+ self.assertEqual(len(info), 1)
+ self.assertIn("T.16000M", info[0].title)
+
+ def test_js1_never_cleared(self):
+ self.assertEqual(len(of(self.report, "js1_defaults")), 1)
+
+ def test_no_device_checks_without_system(self):
+ self.assertFalse(of(self.report, "device_order"))
+ self.assertFalse(of(self.report, "device_missing"))
+ self.assertFalse(self.report.system_checked)
+
+ def test_live_actionmaps_wrapper_is_read(self):
+ """The live actionmaps.xml nests everything in ."""
+ import tempfile
+ with open(FIXTURE, encoding="utf-8") as f:
+ body = f.read()
+ body = body.replace("\n", "\n")
+ with tempfile.TemporaryDirectory() as d:
+ path = os.path.join(d, "actionmaps.xml")
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(body)
+ report = check_profile(path, IN_PROFILE_ORDER)
+ self.assertEqual(len(of(report, "mode_switch_clash")), 1)
+ self.assertEqual(len(of(report, "stale_tuning", WARNING)), 1)
+ self.assertFalse(of(report, "device_order"))
+
+
+class TestDeviceNumbering(unittest.TestCase):
+
+ def test_matching_order_is_clean(self):
+ report = check_profile(FIXTURE, IN_PROFILE_ORDER)
+ self.assertFalse(of(report, "device_order"))
+ self.assertFalse(of(report, "device_missing"))
+ self.assertEqual([r.status for r in report.devices], ["ok", "ok", "ok"])
+
+ def test_swapped_sticks_are_errors(self):
+ system = [IN_PROFILE_ORDER[1], IN_PROFILE_ORDER[0], IN_PROFILE_ORDER[2]]
+ report = check_profile(FIXTURE, system)
+ errors = of(report, "device_order", ERROR)
+ self.assertEqual(len(errors), 2)
+ self.assertIn("FSM.GA is js1 in the profile but js2 on this PC", errors[0].title)
+ self.assertIn("T-Rudder", errors[0].detail)
+ self.assertEqual([r.status for r in report.devices], ["swapped", "swapped", "ok"])
+ # Errors sort first.
+ self.assertEqual(report.findings[0].severity, ERROR)
+
+ def test_missing_stick(self):
+ report = check_profile(FIXTURE, [IN_PROFILE_ORDER[0], IN_PROFILE_ORDER[1]])
+ missing = of(report, "device_missing", WARNING)
+ self.assertEqual(len(missing), 1)
+ self.assertIn("EVO L", missing[0].title)
+ self.assertEqual(report.devices[2].status, "missing")
+
+ def test_extra_stick_shifts_the_rest(self):
+ extra = stick("VPC MongoosT-50CM3", (0x3344, 0x0194))
+ report = check_profile(FIXTURE, [extra] + IN_PROFILE_ORDER)
+ self.assertEqual(len(of(report, "device_order", ERROR)), 3)
+ self.assertEqual(len(of(report, "device_missing", INFO)), 1)
+
+ def test_identical_sticks_are_noted(self):
+ report = check_profile(FIXTURE, IN_PROFILE_ORDER + [stick("VKBsim Gladiator EVO L", EVO_L)])
+ self.assertTrue(any("identical" in f.title for f in of(report, "device_order", INFO)))
+
+ def test_bindings_on_inputs_the_stick_lacks(self):
+ rudder = stick("VKBSim T-Rudder", RUDDER, buttons=0, hats=0)
+ report = check_profile(FIXTURE, [IN_PROFILE_ORDER[0], rudder, IN_PROFILE_ORDER[2]])
+ found = of(report, "no_such_input")
+ self.assertEqual(len(found), 1)
+ self.assertEqual(found[0].inputs, ["js2_button3"])
+
+ def test_bindings_on_a_slot_with_no_device(self):
+ import tempfile
+ with open(FIXTURE, encoding="utf-8") as f:
+ body = f.read().replace('', '')
+ with tempfile.TemporaryDirectory() as d:
+ path = os.path.join(d, "p.xml")
+ with open(path, "w", encoding="utf-8") as f:
+ f.write(body)
+ report = check_profile(path, IN_PROFILE_ORDER)
+ found = of(report, "device_unknown")
+ self.assertEqual(len(found), 1)
+ self.assertIn("js4", found[0].title)
+
+
+class TestWithMockJoysticks(unittest.TestCase):
+ """The dialog's path: list_system_joysticks() + check_profile()."""
+
+ def tearDown(self):
+ jb.set_backend(None)
+
+ def test_mock_backend_is_the_system(self):
+ jb.set_backend(MockBackend.from_file(SWAPPED))
+ system = list_system_joysticks()
+ self.assertEqual(system.source, SOURCE_MOCK)
+ self.assertTrue(system.exact_order)
+ report = check_profile(FIXTURE, system.devices)
+ self.assertEqual(len(of(report, "device_order", ERROR)), 2)
+ # The rudder has no buttons, but js2 is already reported as swapped,
+ # so its button binding isn't reported a second time.
+ self.assertFalse(of(report, "no_such_input"))
+
+ def test_mock_mirroring_the_profile_matches(self):
+ jb.set_backend(MockBackend.from_path(FIXTURE))
+ report = check_profile(FIXTURE, list_system_joysticks().devices)
+ self.assertFalse(of(report, "device_order"))
+ self.assertFalse(of(report, "device_missing"))
+
+
+class TestExampleProfiles(unittest.TestCase):
+
+ def test_every_example_profile_checks_without_crashing(self):
+ for name in sorted(os.listdir(EXAMPLES)):
+ if not name.endswith(".xml"):
+ continue
+ path = os.path.join(EXAMPLES, name)
+ with self.subTest(profile=name):
+ report = check_profile(path, MockBackend.from_path(path).list_joysticks())
+ self.assertFalse(of(report, "device_order", ERROR))
+
+
+if __name__ == "__main__":
+ unittest.main()
From c2c804dee5a50ea69c1f78e5ea82cb22e43c0a18 Mon Sep 17 00:00:00 2001
From: Claude
Date: Wed, 18 Nov 2026 20:59:35 +0000
Subject: [PATCH 5/8] Bump version to 0.11.0
Branch-opening commit for the 0.11.0 integration target. Amr chose
(2026-11-18) to fold the unshipped 0.10.2 fixes and the Check Profile
feature into one minor release, so this branch starts from release/0.10.2.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_011hqxFh5GLh4UnV4rY8Fzdw
---
VERSION.TXT | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/VERSION.TXT b/VERSION.TXT
index 5eef0f1..d9df1bb 100644
--- a/VERSION.TXT
+++ b/VERSION.TXT
@@ -1 +1 @@
-0.10.2
+0.11.0
From 3ef7286005b2de414756ddc0a6ccf66e8d55ab43 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 00:43:06 +0000
Subject: [PATCH 6/8] Check Profile: offer fixes, including renumbering sticks
to match this PC
Amr expected Check Profile to repair what it finds, not just list it
(2026-11-20), and chose to add fixes before 0.11.0 ships. Each finding now
carries a fix; profile_fixer applies them to the XML and writes a temp
copy, which the app loads as an unsaved, modified profile so the user
reviews and saves as usual. The original file is never written.
Safe fixes (applied by "Fix all safe ones"): drop forced "press" on view
actions, move tuning to the stick's current device ID, clear bindings on
inputs a stick lacks, and renumber jsN so every binding follows its stick
(only offered when each profile stick is connected exactly once).
Fixes that need a choice: which action keeps a button that switches
several modes, and restoring cleared view actions onto free hat
directions. Renumbering runs last so other fixes still match old jsN.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_011hqxFh5GLh4UnV4rY8Fzdw
---
CLAUDE.md | 2 +-
README.md | 2 +
docs/CHANGELOG.md | 2 +-
docs/DEVELOPMENT.md | 2 +-
src/gui/main_window.py | 39 ++++-
src/gui/profile_check_dialog.py | 100 ++++++++++++-
src/utils/profile_checker.py | 107 ++++++++++++--
src/utils/profile_fixer.py | 248 ++++++++++++++++++++++++++++++++
tests/test_profile_fixer.py | 140 ++++++++++++++++++
9 files changed, 623 insertions(+), 19 deletions(-)
create mode 100644 src/utils/profile_fixer.py
create mode 100644 tests/test_profile_fixer.py
diff --git a/CLAUDE.md b/CLAUDE.md
index 2490791..51912a9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -56,7 +56,7 @@ Edits propagate **in real time** to both the Controls Table and the Device View
**DirectInput product-GUID matching (`src/utils/directinput_guid.py`)** — SC profile XML stores joysticks with a `Product` attribute like `{PIDVID-0000-0000-0000-504944564944}` (the trailing constant is "PIDVID" in ASCII; the first 8 hex chars encode `(PID << 16) | VID`). This module parses VID/PID out of that GUID so connected pygame joysticks (whose `get_guid()` returns SDL's joystick-GUID format) can be matched to profile entries without ever calling DirectInput. Pure parsing, zero runtime deps. This powers the Config tab's device-to-joystick mapping.
-**Check Profile (`src/utils/profile_checker.py`, `src/utils/system_devices.py`, `src/gui/profile_check_dialog.py`)** — Reads the raw profile XML (exported layout or live `actionmaps.xml`, which wraps everything in ``) and reports problems as findings with severities. The device-numbering check compares each `` VID/PID with the Nth connected stick; `system_devices.py` gets that order from DirectInput on Windows (what SC uses), pygame elsewhere (approximate), or the mock backend. Unsaved edits are checked via a temp XML export.
+**Check Profile (`src/utils/profile_checker.py`, `src/utils/system_devices.py`, `src/gui/profile_check_dialog.py`)** — Reads the raw profile XML (exported layout or live `actionmaps.xml`, which wraps everything in ``) and reports problems as findings with severities. The device-numbering check compares each `` VID/PID with the Nth connected stick; `system_devices.py` gets that order from DirectInput on Windows (what SC uses), pygame elsewhere (approximate), or the mock backend. Unsaved edits are checked via a temp XML export. Findings carry a `fix` dict; `src/utils/profile_fixer.py` applies them to the XML (renumber always last), writes a temp copy, and the main window loads it as a modified profile with Save pointed back at the original folder.
**Theme system (`src/gui/theme.py`)** — Ported from sibling project `smart-citizen` for visual cohesion. Themes are applied by swapping the `QPalette` on the `QApplication`; widgets relying on `WindowText`/`Text` palette roles re-color automatically. Secondary/dim labels opt in via `setProperty("role", "secondary")` and an app-level QSS rule installed by `apply_theme`. The branded `Hyperspace Race Expanded` font (`assets/fonts/HyperspaceRace-ExpandedBold.otf`) is registered at startup via `load_application_fonts()` — the family name Qt reports is the prefixed `"FONTSPRING DEMO - …"` string, which is what the title bar matches.
diff --git a/README.md b/README.md
index 8c9c06a..499165f 100644
--- a/README.md
+++ b/README.md
@@ -191,6 +191,8 @@ Click **"Check Profile"** in the top header (enabled once a profile is loaded).
- **Tuning saved under an old device ID** — deadzone/saturation stored for an ID no stick in the profile has, so the game ignores it.
- **Partly bound hats**, **bindings on buttons a stick doesn't have**, and **js1 never cleared** (so the game's default joystick bindings still apply on it).
+**Fixing what it finds.** Most problems have a 🔧 link under them, and **Fix all safe ones** applies every fix that doesn't need a choice from you, including **renumbering the profile's sticks to match this PC** so each binding follows its stick. For one button switching several modes, you pick which action keeps it; cleared view actions can be put back on the free hat directions. Fixes are loaded as unsaved changes: review them in the table, then **Save Profile** to keep them. Your original file is never overwritten by a fix.
+
Unsaved edits are included in the check. On Windows, SCPE reads the stick order from DirectInput, the same source Star Citizen uses.
### Filtering and Searching Bindings
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 9486863..7cbb50f 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -17,7 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Mislabeled Virpil templates** (issue #31) — `VPC MT-50CM3 (Left/Right)` are actually Alpha Prime grip diagrams on a MongoosT-50CM3 base and are now named that way. A dedicated MT-50CM3 **throttle** template still needs to be authored.
### Added
-- **Check Profile** — A new header button checks the loaded profile (including unsaved edits) for problems Star Citizen doesn't report: the profile's js1/js2/… devices numbered differently from how this PC currently lists the sticks (so bindings would land on the wrong stick), profile sticks not connected or connected sticks missing from the profile, view/look actions forced to `activationMode="press"` (stuck camera), one input bound to several mode switches, deadzone/saturation tuning stored under a device ID no profile stick has, partly bound hats, bindings on buttons/hats a stick doesn't have, and js1 never cleared so game-default joystick bindings still apply. On Windows the stick order comes from DirectInput (the order the game uses, via `ctypes`, no new dependency); elsewhere from pygame, and in `--mock-joysticks` mode from the virtual sticks, so it is testable without hardware. **Check again** re-reads the sticks after re-plugging.
+- **Check Profile** — A new header button checks the loaded profile (including unsaved edits) for problems Star Citizen doesn't report: the profile's js1/js2/… devices numbered differently from how this PC currently lists the sticks (so bindings would land on the wrong stick), profile sticks not connected or connected sticks missing from the profile, view/look actions forced to `activationMode="press"` (stuck camera), one input bound to several mode switches, deadzone/saturation tuning stored under a device ID no profile stick has, partly bound hats, bindings on buttons/hats a stick doesn't have, and js1 never cleared so game-default joystick bindings still apply. Most problems come with a **🔧 fix link**, and **Fix all safe ones** applies every fix that needs no choices: drop forced "press" modes, move tuning to the stick's current ID, remove bindings on inputs a stick lacks, and **renumber the profile's js1/js2/… to match this PC** so each binding follows its stick. One-button-several-modes asks which action keeps the button; cleared view actions can be put back on the free hat directions. Fixes load as an unsaved profile to review and save; the original file is never written. On Windows the stick order comes from DirectInput (the order the game uses, via `ctypes`, no new dependency); elsewhere from pygame, and in `--mock-joysticks` mode from the virtual sticks, so it is testable without hardware. **Check again** re-reads the sticks after re-plugging.
- **Develop and test without joysticks attached** — Joystick access now goes through a swappable backend (`src/utils/joystick_backend.py`). Run `python src/main.py --mock-joysticks [devices.json]` (or set `SCPE_MOCK_JOYSTICKS`) to replace real sticks with virtual ones described in a JSON file; a **Virtual Joysticks** panel opens beside the main window, and clicking its buttons, hats and axis sliders feeds the Remap dialog's *Detect Input* exactly as a real stick would. Presets in `tests/fixtures/mock_devices/` carry the VID/PID of the sticks in `example-profiles/`, so Config-tab mapping and Device View behave as on the joystick machine. The virtual setup can mirror any SC profile: by default it rebuilds from each profile you open (names, VID/PID, and enough buttons/hats for every binding), **Load setup…** picks any profile or devices file, and `--mock-joysticks` also accepts a profile `.xml`. Input-code translation is now a pure function with unit tests, and scripted fixtures replay recorded event sequences through the real detector loop in pytest. Normal launches are unchanged.
- **Release process ported from smart-citizen** — Long-lived `release/X.Y.Z` integration branches; PRs target the release branch and merging it to `main` is the release trigger. New workflows: `ci.yml` (tests + PyInstaller build verification on every PR to `main`/`release/**`), `release.yml` (on merge to `main`: auto-tags `v{VERSION}` from `VERSION.TXT`, builds the installer, publishes the GitHub Release with the CHANGELOG section as its body, posts to Discord), `installer-preview.yml` (add the `build-installer` label to a PR for a tester installer artifact), `installer-preview-cleanup.yml`, and `release-notify.yml` (manual Discord re-post). `.github/CODEOWNERS` requests review from the maintainer on every PR. `/start_release`, `/pre_release` and `/ship_release` commands walk the cycle with checkpoints; `docs/RELEASE_PROCESS.md` documents it.
- **Scripted build** — `scripts/build/build_exe.py` (PyInstaller `--onedir`, stable `SCProfileEditor.exe` name so shortcuts survive upgrades) and `scripts/build/build_all.bat`. `installer.iss` now reads the version from `VERSION.TXT` at compile time, so `VERSION.TXT` is the single place to bump. `scripts/release_notes.py` extracts a version's CHANGELOG section for the release body. `requirements-dev.txt` holds the test/build deps.
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 45c2ce0..ce85044 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -94,7 +94,7 @@ Copy `product` straight from an `` line i
python src/main.py --mock-joysticks tests/fixtures/mock_devices/check_profile_swapped.json
```
-then open `tests/fixtures/profiles/check_profile_problems.xml` and click **Check Profile**: FSM.GA and T-Rudder show as swapped, along with one example of every other check. The logic lives in `src/utils/profile_checker.py` (pure, no Qt) and `src/utils/system_devices.py` (DirectInput order on Windows, pygame elsewhere, mock sticks in mock mode); `tests/test_profile_checker.py` covers it.
+then open `tests/fixtures/profiles/check_profile_problems.xml` and click **Check Profile**: FSM.GA and T-Rudder show as swapped, along with one example of every other check. The logic lives in `src/utils/profile_checker.py` (pure, no Qt) and `src/utils/system_devices.py` (DirectInput order on Windows, pygame elsewhere, mock sticks in mock mode); `tests/test_profile_checker.py` covers it. Fixes live in `src/utils/profile_fixer.py` (`tests/test_profile_fixer.py`); in that mock setup **Fix all safe ones** renumbers the profile so the table goes all ✓.
The devices file's order is the js order: the first device is `js1`. Mock mode is a developer flag only; release builds behave exactly as before unless it is passed.
diff --git a/src/gui/main_window.py b/src/gui/main_window.py
index 65e288c..e8fc7fc 100644
--- a/src/gui/main_window.py
+++ b/src/gui/main_window.py
@@ -741,6 +741,7 @@ def load_profile_from_path(self, file_path: str):
parser = ProfileParser(file_path, use_bundled_defaults=True)
self.current_profile = parser.parse()
self.current_profile_path = file_path
+ self._save_dir_hint = None
# Before display_profile(): listeners such as the mock-joystick
# panel swap the "connected" devices here, so the disconnected-
# device check below sees the right set.
@@ -2453,9 +2454,42 @@ def check_profile(self):
from gui.profile_check_dialog import ProfileCheckDialog
with tempfile.TemporaryDirectory(prefix="scpe-check-") as temp_dir:
dialog = ProfileCheckDialog(lambda: self._profile_xml_for_check(temp_dir),
- self.current_profile.profile_name, self)
+ self.current_profile.profile_name, self,
+ apply_fixes=self._apply_profile_fixes)
dialog.exec()
+ def _apply_profile_fixes(self, xml_path: str, fixes, choices):
+ """Apply Check Profile fixes and load the result as an unsaved,
+ modified profile. The original file is never written; the user
+ reviews the changes and saves as usual. Returns what changed."""
+ import tempfile
+ from utils.profile_fixer import apply_fixes
+
+ profile = self.current_profile
+ original = profile.source_xml_path or self.current_profile_path
+ original_dir = os.path.dirname(original) if original else ""
+ if getattr(self, "_save_dir_hint", None):
+ original_dir = self._save_dir_hint
+ last_path = self.settings.get_last_profile_path() or original
+
+ fix_dir = tempfile.mkdtemp(prefix="scpe-fixed-")
+ out = os.path.join(fix_dir, os.path.basename(original) if original else "profile.xml")
+ changes = apply_fixes(xml_path, fixes, out, choices)
+
+ self.load_profile_from_path(out)
+ if not self.current_profile or self.current_profile_path != out:
+ raise RuntimeError("The fixed profile could not be loaded")
+ # Keep pointing "last opened" and Save at the user's real folder,
+ # not the temp copy.
+ if last_path:
+ self.settings.set_last_profile_path(last_path)
+ self._save_dir_hint = original_dir
+ self.current_profile.mark_modified()
+ self.on_profile_modified()
+ self.statusBar().showMessage(
+ f"Applied {len(changes)} fix{'es' if len(changes) != 1 else ''}. Review, then Save Profile to keep them.")
+ return changes
+
def save_profile(self):
"""Save the modified profile to XML"""
if not self.current_profile or not self.current_profile.is_modified:
@@ -2490,6 +2524,9 @@ def save_profile(self):
sc_profiles_dir = self.settings.get_sc_profiles_directory()
if sc_profiles_dir and os.path.exists(sc_profiles_dir):
suggested_dir = sc_profiles_dir
+ elif getattr(self, "_save_dir_hint", None) and os.path.isdir(self._save_dir_hint):
+ # Profile was rebuilt from a temp copy by Check Profile's fixes.
+ suggested_dir = self._save_dir_hint
elif self.current_profile.source_xml_path:
suggested_dir = os.path.dirname(self.current_profile.source_xml_path)
diff --git a/src/gui/profile_check_dialog.py b/src/gui/profile_check_dialog.py
index 1a81793..d6b67c8 100644
--- a/src/gui/profile_check_dialog.py
+++ b/src/gui/profile_check_dialog.py
@@ -13,7 +13,7 @@
from PyQt6.QtGui import QColor, QBrush
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
QTableWidget, QTableWidgetItem, QTextBrowser, QHeaderView,
- QGroupBox)
+ QGroupBox, QInputDialog, QMessageBox)
from utils.profile_checker import CheckReport, check_profile, ERROR, WARNING, INFO
from utils.system_devices import list_system_joysticks
@@ -37,11 +37,17 @@ def _fmt_id(vid_pid) -> str:
class ProfileCheckDialog(QDialog):
- def __init__(self, xml_path_provider: Callable[[], Optional[str]], profile_label: str, parent=None):
+ def __init__(self, xml_path_provider: Callable[[], Optional[str]], profile_label: str, parent=None,
+ apply_fixes: Optional[Callable] = None):
"""``xml_path_provider`` returns the XML file to check (the main
- window writes unsaved edits to a temp file first)."""
+ window writes unsaved edits to a temp file first).
+
+ ``apply_fixes(xml_path, fixes, choices) -> [str]`` applies fixes and
+ reloads the profile in the main window; without it the dialog only
+ reports."""
super().__init__(parent)
self._xml_path_provider = xml_path_provider
+ self._apply_fixes = apply_fixes
self.setWindowTitle(f"Check Profile — {profile_label}")
self.resize(900, 680)
@@ -73,9 +79,23 @@ def __init__(self, xml_path_provider: Callable[[], Optional[str]], profile_label
self.findings_view = QTextBrowser()
self.findings_view.setOpenExternalLinks(False)
+ self.findings_view.setOpenLinks(False)
+ self.findings_view.anchorClicked.connect(self._on_fix_link)
layout.addWidget(self.findings_view, 3)
+ self.fix_note = QLabel()
+ self.fix_note.setProperty("role", "secondary")
+ self.fix_note.setWordWrap(True)
+ self.fix_note.setVisible(False)
+ layout.addWidget(self.fix_note)
+
buttons = QHBoxLayout()
+ self.fix_all_btn = QPushButton("Fix all safe ones")
+ self.fix_all_btn.setToolTip("Apply every fix that needs no choices from you. Your file isn't "
+ "changed until you Save Profile.")
+ self.fix_all_btn.clicked.connect(self._fix_all_safe)
+ self.fix_all_btn.setVisible(apply_fixes is not None)
+ buttons.addWidget(self.fix_all_btn)
buttons.addStretch()
recheck_btn = QPushButton("Check again")
recheck_btn.setToolTip("Re-read the connected joysticks and the profile, e.g. after re-plugging a stick")
@@ -141,10 +161,80 @@ def _show_findings(self, report: CheckReport):
self.summary_label.setText("Found " + ", ".join(parts) + ".")
chunks = []
- for f in report.findings:
+ for i, f in enumerate(report.findings):
+ link = ""
+ if f.fix and self._apply_fixes:
+ link = f" 🔧 {html.escape(f.fix.get('label', 'Fix'))}"
chunks.append(
f"
")
self.findings_view.setHtml("".join(chunks) or "
Nothing to report.
")
+ n_safe = len(self._safe_fixes())
+ self.fix_all_btn.setEnabled(n_safe > 0)
+ self.fix_all_btn.setText(f"Fix all safe ones ({n_safe})" if n_safe else "Fix all safe ones")
+
+ # -- fixing -----------------------------------------------------------
+
+ def _safe_fixes(self):
+ if not self.report:
+ return []
+ out, seen_renumber = [], False
+ for f in self.report.findings:
+ if not f.fix or not f.fix.get("safe"):
+ continue
+ if f.fix["kind"] == "renumber":
+ if seen_renumber:
+ continue
+ seen_renumber = True
+ out.append(f.fix)
+ return out
+
+ def _on_fix_link(self, url):
+ text = url.toString()
+ if not text.startswith("fix:") or not self.report:
+ return
+ try:
+ finding = self.report.findings[int(text[4:])]
+ except (ValueError, IndexError):
+ return
+ fix = finding.fix
+ choices = {}
+ if fix["kind"] == "keep_one":
+ actions = [b["action"] for b in fix["bindings"]]
+ keep, ok = QInputDialog.getItem(
+ self, "Keep one", f"Which action should {fix['input']} keep? The others are unbound.",
+ actions, 0, False)
+ if not ok:
+ return
+ choices[0] = keep
+ elif fix.get("confirm"):
+ if QMessageBox.question(self, "Fix", fix["confirm"]) != QMessageBox.StandardButton.Yes:
+ return
+ self._run_fixes([fix], choices)
+
+ def _fix_all_safe(self):
+ fixes = self._safe_fixes()
+ if not fixes:
+ return
+ extra = [f["confirm"] for f in fixes if f.get("confirm")]
+ msg = f"Apply {len(fixes)} fix{'es' if len(fixes) != 1 else ''}?"
+ if extra:
+ msg += "\n\nThis includes:\n• " + "\n• ".join(extra)
+ msg += "\n\nNothing is written to your file until you Save Profile."
+ if QMessageBox.question(self, "Fix all safe ones", msg) != QMessageBox.StandardButton.Yes:
+ return
+ self._run_fixes(fixes, {})
+
+ def _run_fixes(self, fixes, choices):
+ try:
+ path = self._xml_path_provider()
+ changes = self._apply_fixes(path, fixes, choices)
+ except Exception as e:
+ logger.error(f"Applying fixes failed: {e}", exc_info=True)
+ QMessageBox.warning(self, "Fix", f"Couldn't apply the fix:\n{e}")
+ return
+ self.fix_note.setText("Fixed: " + "; ".join(changes) + ". Save Profile to keep the changes.")
+ self.fix_note.setVisible(True)
+ self.run_check()
diff --git a/src/utils/profile_checker.py b/src/utils/profile_checker.py
index 0be76d3..d6da932 100644
--- a/src/utils/profile_checker.py
+++ b/src/utils/profile_checker.py
@@ -54,6 +54,10 @@ class Finding:
title: str
detail: str
inputs: List[str] = field(default_factory=list)
+ # How utils.profile_fixer can repair it, or None when only the user can.
+ # {"kind": ..., "safe": bool, ...}; "safe" fixes need no choices and are
+ # applied by "Fix all safe ones".
+ fix: Optional[dict] = None
@dataclass
@@ -95,6 +99,7 @@ class _ProfileDevice:
instance: int
name: str
vid_pid: Optional[Tuple[int, int]]
+ product: str = ""
# ---------------------------------------------------------------------------
@@ -129,7 +134,7 @@ def _read_devices(root: ET.Element) -> Dict[int, _ProfileDevice]:
product = opt.get("Product") or ""
if not product.strip():
continue
- devices[instance] = _ProfileDevice(instance, _clean_name(product), parse_di_product_guid(product))
+ devices[instance] = _ProfileDevice(instance, _clean_name(product), parse_di_product_guid(product), product)
return devices
@@ -184,22 +189,44 @@ def _check_forced_press(bindings: List[_Binding]) -> List[Finding]:
"View and look actions are hold actions in the game. Forcing \"press\" overrides that, "
"so the camera can stay turned after you let go. Set the activation mode back to "
"(Game default).",
- [b.input]))
+ [b.input], _clear_mode_fix(b, safe=True)))
for b in hold:
findings.append(Finding(
"forced_press", INFO,
f"{b.action} on {b.input} is forced to \"press\"",
"This action is meant to be held. If it behaves oddly, set its activation mode back to "
"(Game default).",
- [b.input]))
+ [b.input], _clear_mode_fix(b, safe=False)))
return findings
+def _clear_mode_fix(b: _Binding, safe: bool) -> dict:
+ return {"kind": "clear_activation_mode", "safe": safe, "label": "Set to game default",
+ "actionmap": b.actionmap, "action": b.action, "input": b.input}
+
+
+# Which hat direction a cleared view action most likely sat on.
+_HAT_GUESS = [
+ (re.compile(r"(yaw|look)_left$"), "left"),
+ (re.compile(r"(yaw|look)_right$"), "right"),
+ (re.compile(r"(pitch|look)_up$"), "up"),
+ (re.compile(r"(pitch|look)_down$|look_behind$"), "down"),
+]
+
+
+def _guess_direction(action: str) -> Optional[str]:
+ for pattern, direction in _HAT_GUESS:
+ if pattern.search(action):
+ return direction
+ return None
+
+
def _check_partial_hats(bindings: List[_Binding], devices: Dict[int, _ProfileDevice]) -> List[Finding]:
bound: Dict[Tuple[int, int], set] = defaultdict(set)
# Actions cleared to "jsN_ " that still carry an activation mode: a
# binding that used to be there and was deleted.
cleared: Dict[int, List[str]] = defaultdict(list)
+ cleared_maps: Dict[Tuple[int, str], str] = {}
for b in bindings:
parts = _js_parts(b.input)
if not parts:
@@ -207,6 +234,7 @@ def _check_partial_hats(bindings: List[_Binding], devices: Dict[int, _ProfileDev
if not parts[1]:
if b.activation_mode and _VIEW_ACTION_RE.search(b.action):
cleared[parts[0]].append(b.action)
+ cleared_maps[(parts[0], b.action)] = b.actionmap
continue
m = _HAT_RE.match(parts[1])
if m:
@@ -225,11 +253,23 @@ def _check_partial_hats(bindings: List[_Binding], devices: Dict[int, _ProfileDev
f"which suggests they used to be on this hat: {', '.join(lost)}.")
else:
detail += " If the other directions used to do something, they were cleared."
+ fix = None
+ assign = []
+ for action in lost:
+ direction = _guess_direction(action)
+ if direction in free and direction not in [a["direction"] for a in assign]:
+ assign.append({"actionmap": cleared_maps[(js, action)], "action": action,
+ "direction": direction, "input": f"js{js}_hat{hat}_{direction}"})
+ if assign:
+ fix = {"kind": "restore_hat", "safe": False, "label": "Put them back on the hat",
+ "assign": assign,
+ "confirm": "Bind " + ", ".join(f"{a['action']} to {a['input']}" for a in assign)
+ + " (with the game's default activation)?"}
findings.append(Finding(
"partial_hat", WARNING if lost else INFO,
f"Hat {hat} on {where}: {', '.join(free)} unbound",
detail,
- [f"js{js}_hat{hat}_{d}" for d in free]))
+ [f"js{js}_hat{hat}_{d}" for d in free], fix))
return findings
@@ -256,7 +296,11 @@ def _check_mode_switch_clash(bindings: List[_Binding]) -> List[Finding]:
+ (f" ({mode})" if mode else "")
+ ". One press fires all of them, so you end up in whichever mode the game applies "
"last. Move all but one to a free button.",
- [group[0].input]))
+ [group[0].input],
+ {"kind": "keep_one", "safe": False, "label": "Choose which one keeps it",
+ "input": group[0].input,
+ "bindings": [{"actionmap": b.actionmap, "action": b.action}
+ for b in group if b.action in actions]}))
return findings
@@ -285,7 +329,9 @@ def _check_stale_tuning(root: ET.Element, devices: Dict[int, _ProfileDevice]) ->
f"but your stick now reports as \"{target.name}\" ({_fmt_vid_pid(target.vid_pid)}, "
f"js{target.instance}). The game ignores tuning for IDs that aren't present. "
"Move the settings to the new ID or set them again in game.",
- []))
+ [],
+ {"kind": "move_tuning", "safe": True, "label": f"Move to {target.name}",
+ "from_name": name_attr, "to_name": target.product}))
else:
findings.append(Finding(
"stale_tuning", INFO,
@@ -370,6 +416,8 @@ def _check_system(bindings: List[_Binding], devices: Dict[int, _ProfileDevice],
(sdev.name or "").strip() if sdev else "",
sdev.vid_pid if sdev else None, status))
+ renumber = _renumber_fix(devices, sys_slots_by_id, used_slots)
+
# One finding per profile stick that won't be where the profile expects it.
for slot, pdev in sorted(devices.items()):
sdev = sys_by_slot.get(slot)
@@ -389,8 +437,8 @@ def _check_system(bindings: List[_Binding], devices: Dict[int, _ProfileDevice],
f"the {n_bind} js{slot} binding{'s' if n_bind != 1 else ''} meant for {pdev.name} will go to "
f"{other} instead. Before you play, get the PC to list the sticks in the profile's order "
f"(usually by re-plugging them, or using the same USB ports as when the profile was made), "
- f"then press Check again.",
- []))
+ f"then press Check again. Or let SCPE renumber the profile to match this PC.",
+ [], renumber))
else:
findings.append(Finding(
"device_missing", WARNING,
@@ -436,14 +484,53 @@ def _check_system(bindings: List[_Binding], devices: Dict[int, _ProfileDevice],
name = (sdev.name or "").strip()
findings.append(Finding(
"no_such_input", WARNING,
- f"{len(too_high)} binding{'s' if len(too_high) != 1 else ''} on js{slot} ({name}) use inputs it doesn't have",
+ f"{len(too_high)} binding{'s' if len(too_high) != 1 else ''} on js{slot} ({name}) "
+ f"{'use' if len(too_high) != 1 else 'uses'} inputs it doesn't have",
f"{name} has {sdev.buttons} button{'s' if sdev.buttons != 1 else ''} and "
f"{sdev.hats} hat{'s' if sdev.hats != 1 else ''}, so these bindings never fire: "
f"{', '.join(codes[:12])}{' …' if len(codes) > 12 else ''}.",
- codes))
+ codes,
+ {"kind": "unbind", "safe": True, "label": "Remove them",
+ "bindings": [{"actionmap": b.actionmap, "action": b.action, "input": b.input}
+ for b in too_high]}))
return findings, rows
+def _renumber_fix(devices: Dict[int, _ProfileDevice], sys_slots_by_id: Dict[Tuple[int, int], List[int]],
+ used_slots: set) -> Optional[dict]:
+ """jsN -> jsM so every profile stick lands on the slot this PC gives it.
+
+ Only offered when every identified profile stick is connected exactly
+ once; with a stick missing or two identical ones there's no single
+ right answer.
+ """
+ ided = {slot: d for slot, d in devices.items() if d.vid_pid}
+ if not ided:
+ return None
+ mapping: Dict[int, int] = {}
+ for slot, d in ided.items():
+ now = sys_slots_by_id.get(d.vid_pid, [])
+ if len(now) != 1:
+ return None
+ mapping[slot] = now[0]
+ if all(old == new for old, new in mapping.items()):
+ return None
+ # Other slots the profile uses (no identified stick) keep their number
+ # unless a renumbered stick takes it; then they move to a free one.
+ others = sorted((set(devices) | set(used_slots)) - set(ided))
+ taken = set(mapping.values())
+ for slot in others:
+ if slot not in taken:
+ mapping[slot] = slot
+ else:
+ mapping[slot] = next(n for n in range(1, 100) if n not in taken and n not in others)
+ taken.add(mapping[slot])
+ pretty = ", ".join(f"js{o}→js{n}" for o, n in sorted(mapping.items()) if o != n)
+ return {"kind": "renumber", "safe": True, "label": "Renumber profile to match this PC",
+ "mapping": {str(o): n for o, n in mapping.items() if o != n},
+ "confirm": f"Renumber the profile's sticks ({pretty}) so each binding follows its stick?"}
+
+
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
diff --git a/src/utils/profile_fixer.py b/src/utils/profile_fixer.py
new file mode 100644
index 0000000..7f4c49b
--- /dev/null
+++ b/src/utils/profile_fixer.py
@@ -0,0 +1,248 @@
+"""Apply the fixes ``utils.profile_checker`` attaches to its findings.
+
+Works on the profile XML and writes a new file, so the original is never
+touched; the app then loads the fixed copy as an unsaved, modified profile
+for the user to review and save. Pure ElementTree, no Qt.
+
+Fix kinds (``finding.fix["kind"]``):
+
+clear_activation_mode drop a forced activationMode from one rebind
+restore_hat bind cleared view actions back onto free hat directions
+keep_one one input fires several actions: keep ``keep``, clear the rest
+move_tuning re-label a block with the stick's current ID
+unbind clear bindings on inputs the stick doesn't have
+renumber jsN -> jsM everywhere so bindings follow their stick
+"""
+from __future__ import annotations
+
+import copy
+import re
+import xml.etree.ElementTree as ET
+from typing import Dict, Iterable, List, Optional
+
+from utils.profile_checker import _profile_root
+
+_JS_PREFIX_RE = re.compile(r"\bjs(\d+)_", re.IGNORECASE)
+
+
+class FixError(Exception):
+ pass
+
+
+def _blank_for(input_code: str) -> str:
+ m = _JS_PREFIX_RE.match(input_code)
+ return f"js{m.group(1)}_ " if m else ""
+
+
+def _action(root: ET.Element, actionmap: str, action: str) -> Optional[ET.Element]:
+ for amap in root.iter("actionmap"):
+ if amap.get("name") != actionmap:
+ continue
+ for act in amap.findall("action"):
+ if act.get("name") == action:
+ return act
+ return None
+
+
+def _rebind(root: ET.Element, actionmap: str, action: str, input_code: str) -> Optional[ET.Element]:
+ act = _action(root, actionmap, action)
+ if act is None:
+ return None
+ for rb in act.findall("rebind"):
+ if (rb.get("input") or "").strip().lower() == input_code.strip().lower():
+ return rb
+ return None
+
+
+def _clear(rb: ET.Element) -> None:
+ rb.set("input", _blank_for(rb.get("input") or ""))
+ rb.attrib.pop("activationMode", None)
+
+
+# ---------------------------------------------------------------------------
+# Individual fixes. Each returns a one-line description of what changed.
+# ---------------------------------------------------------------------------
+
+def _fix_clear_activation_mode(root, fix, choice) -> str:
+ rb = _rebind(root, fix["actionmap"], fix["action"], fix["input"])
+ if rb is None:
+ raise FixError(f"{fix['action']} on {fix['input']} is no longer in the profile")
+ rb.attrib.pop("activationMode", None)
+ return f"{fix['action']} on {fix['input']}: activation mode set to game default"
+
+
+def _fix_restore_hat(root, fix, choice) -> str:
+ done = []
+ for a in fix["assign"]:
+ act = _action(root, a["actionmap"], a["action"])
+ if act is None:
+ continue
+ blank = _blank_for(a["input"]).strip()
+ target = None
+ for rb in act.findall("rebind"):
+ if (rb.get("input") or "").strip().lower() == blank.lower():
+ target = rb
+ break
+ if target is None:
+ target = ET.SubElement(act, "rebind")
+ target.set("input", a["input"])
+ target.attrib.pop("activationMode", None)
+ done.append(f"{a['action']} → {a['input']}")
+ if not done:
+ raise FixError("none of those actions are in the profile any more")
+ return "Restored " + ", ".join(done)
+
+
+def _fix_keep_one(root, fix, choice) -> str:
+ keep = choice or fix.get("keep")
+ if not keep:
+ raise FixError("no action chosen to keep the input")
+ cleared = []
+ for b in fix["bindings"]:
+ if b["action"] == keep:
+ continue
+ rb = _rebind(root, b["actionmap"], b["action"], fix["input"])
+ if rb is not None:
+ _clear(rb)
+ cleared.append(b["action"])
+ return f"{fix['input']} now only does {keep} (cleared {', '.join(cleared) or 'nothing'})"
+
+
+def _fix_move_tuning(root, fix, choice) -> str:
+ src = next((d for d in root.findall("deviceoptions") if d.get("name") == fix["from_name"]), None)
+ if src is None:
+ raise FixError("that tuning block is no longer in the profile")
+ dst = next((d for d in root.findall("deviceoptions") if d.get("name") == fix["to_name"]), None)
+ if dst is None:
+ src.set("name", fix["to_name"])
+ else:
+ # The stick already has some tuning: keep it, add the old settings
+ # it doesn't have yet.
+ have = {(o.get("input"), tuple(sorted(k for k in o.attrib if k != "input"))) for o in dst}
+ for opt in list(src):
+ key = (opt.get("input"), tuple(sorted(k for k in opt.attrib if k != "input")))
+ if key not in have:
+ dst.append(copy.deepcopy(opt))
+ root.remove(src)
+ return f"Tuning moved to {' '.join(fix['to_name'].split('{')[0].split())}"
+
+
+def _fix_unbind(root, fix, choice) -> str:
+ n = 0
+ for b in fix["bindings"]:
+ rb = _rebind(root, b["actionmap"], b["action"], b["input"])
+ if rb is not None:
+ _clear(rb)
+ n += 1
+ return f"Removed {n} binding{'s' if n != 1 else ''} on inputs the stick doesn't have"
+
+
+def _fix_renumber(root, fix, choice) -> str:
+ mapping: Dict[int, int] = {int(k): int(v) for k, v in fix["mapping"].items()}
+ if not mapping:
+ return "Nothing to renumber"
+
+ def sub(value: str) -> str:
+ return _JS_PREFIX_RE.sub(lambda m: f"js{mapping.get(int(m.group(1)), int(m.group(1)))}_", value)
+
+ for elem in root.iter():
+ for key, value in list(elem.attrib.items()):
+ if "js" in value.lower() and _JS_PREFIX_RE.search(value):
+ elem.set(key, sub(value))
+
+ # and the header list.
+ joystick_opts = [o for o in root.findall("options") if (o.get("type") or "").lower() == "joystick"]
+ for opt in joystick_opts:
+ try:
+ n = int(opt.get("instance", "0"))
+ except ValueError:
+ continue
+ if n in mapping:
+ opt.set("instance", str(mapping[n]))
+ # A bare placeholder may now share M with a moved
+ # stick; drop the placeholder.
+ seen: Dict[str, ET.Element] = {}
+ for opt in joystick_opts:
+ inst = opt.get("instance")
+ if inst in seen:
+ bare = opt if not opt.get("Product") else seen[inst]
+ root.remove(bare)
+ if bare is seen[inst]:
+ seen[inst] = opt
+ else:
+ seen[inst] = opt
+ # Keep options in instance order so the file reads naturally.
+ _sort_joystick_options(root)
+
+ for devices in root.iter("devices"):
+ for js in devices.findall("joystick"):
+ try:
+ n = int(js.get("instance", "0"))
+ except ValueError:
+ continue
+ if n in mapping:
+ js.set("instance", str(mapping[n]))
+ insts = set()
+ for js in list(devices.findall("joystick")):
+ if js.get("instance") in insts:
+ devices.remove(js)
+ insts.add(js.get("instance"))
+
+ pretty = ", ".join(f"js{o}→js{n}" for o, n in sorted(mapping.items()))
+ return f"Renumbered sticks: {pretty}"
+
+
+def _sort_joystick_options(root: ET.Element) -> None:
+ children = list(root)
+ idx = [i for i, c in enumerate(children)
+ if c.tag == "options" and (c.get("type") or "").lower() == "joystick"]
+ if not idx:
+ return
+ ordered = sorted((children[i] for i in idx), key=lambda o: int(o.get("instance", "0") or 0))
+ for i, elem in zip(idx, ordered):
+ children[i] = elem
+ for c in list(root):
+ root.remove(c)
+ root.extend(children)
+
+
+_FIXERS = {
+ "clear_activation_mode": _fix_clear_activation_mode,
+ "restore_hat": _fix_restore_hat,
+ "keep_one": _fix_keep_one,
+ "move_tuning": _fix_move_tuning,
+ "unbind": _fix_unbind,
+ "renumber": _fix_renumber,
+}
+
+
+def apply_fixes(xml_path: str, fixes: Iterable[dict], output_path: str,
+ choices: Optional[Dict[int, str]] = None) -> List[str]:
+ """Apply ``fixes`` to the profile at ``xml_path`` and write ``output_path``.
+
+ ``choices`` maps a fix's position in ``fixes`` to the user's pick for
+ fixes that need one (``keep_one``). The same renumber fix attached to
+ several findings is applied once. Returns one line per change made;
+ raises FixError if a fix can't be applied (nothing is written then).
+ """
+ tree = ET.parse(xml_path)
+ root = _profile_root(tree.getroot())
+ choices = choices or {}
+ done: List[str] = []
+ applied_renumber = False
+ fixes = list(fixes)
+ # Renumber last: the other fixes name inputs by the profile's old jsN.
+ order = sorted(range(len(fixes)), key=lambda i: fixes[i].get("kind") == "renumber")
+ for i in order:
+ fix = fixes[i]
+ kind = fix.get("kind")
+ if kind == "renumber":
+ if applied_renumber:
+ continue
+ applied_renumber = True
+ fixer = _FIXERS.get(kind)
+ if fixer is None:
+ raise FixError(f"unknown fix {kind!r}")
+ done.append(fixer(root, fix, choices.get(i)))
+ tree.write(output_path, encoding="utf-8")
+ return done
diff --git a/tests/test_profile_fixer.py b/tests/test_profile_fixer.py
new file mode 100644
index 0000000..aacb4b2
--- /dev/null
+++ b/tests/test_profile_fixer.py
@@ -0,0 +1,140 @@
+"""Tests for utils.profile_fixer: every fix Check Profile offers, applied to
+the problem fixture, leaves a profile that checks clean for that problem."""
+import os
+import sys
+import tempfile
+import unittest
+import xml.etree.ElementTree as ET
+
+ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
+sys.path.insert(0, os.path.join(ROOT, "src"))
+sys.path.insert(0, ROOT)
+
+from utils.joystick_backend import JoystickInfo
+from utils.profile_checker import check_profile
+from utils.profile_fixer import apply_fixes, FixError
+
+FIXTURE = os.path.join(ROOT, "tests", "fixtures", "profiles", "check_profile_problems.xml")
+FSM = (0x231D, 0x2220)
+RUDDER = (0x231D, 0x011F)
+EVO_L = (0x231D, 0x0201)
+
+
+def stick(name, vid_pid, buttons=64, hats=2):
+ return JoystickInfo(name=name, vid_pid=vid_pid, buttons=buttons, hats=hats, axes=6)
+
+
+IN_ORDER = [stick("FSM.GA", FSM), stick("T-Rudder", RUDDER), stick("EVO L", EVO_L)]
+SWAPPED = [IN_ORDER[1], IN_ORDER[0], IN_ORDER[2]]
+
+
+class FixerTest(unittest.TestCase):
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.out = os.path.join(self.tmp.name, "fixed.xml")
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def fix(self, check, system=IN_ORDER, choices=None, path=FIXTURE):
+ report = check_profile(path, system)
+ fixes = [f.fix for f in report.findings if f.check == check and f.fix]
+ self.assertTrue(fixes, f"no fix offered for {check}")
+ changes = apply_fixes(path, fixes, self.out, choices)
+ return changes, check_profile(self.out, system)
+
+ def checks(self, report, check):
+ return [f for f in report.findings if f.check == check]
+
+ def rebinds(self, action):
+ root = ET.parse(self.out).getroot()
+ return [rb.attrib for a in root.iter("action") if a.get("name") == action for rb in a.findall("rebind")]
+
+ def test_forced_press(self):
+ _, after = self.fix("forced_press")
+ self.assertFalse(self.checks(after, "forced_press"))
+ self.assertEqual(self.rebinds("v_view_look_behind"), [{"input": "js3_hat1_down"}])
+
+ def test_mode_switch_keep_one(self):
+ changes, after = self.fix("mode_switch_clash", choices={0: "v_toggle_mining_mode"})
+ self.assertFalse(self.checks(after, "mode_switch_clash"))
+ self.assertEqual(self.rebinds("v_toggle_mining_mode"), [{"input": "js3_button27"}])
+ self.assertEqual(self.rebinds("v_set_salvage_mode"), [{"input": "js3_ "}])
+ self.assertIn("v_toggle_mining_mode", changes[0])
+
+ def test_mode_switch_needs_a_choice(self):
+ with self.assertRaises(FixError):
+ self.fix("mode_switch_clash")
+
+ def test_move_tuning(self):
+ _, after = self.fix("stale_tuning")
+ self.assertFalse([f for f in self.checks(after, "stale_tuning") if f.severity == "warning"])
+ names = [d.get("name") for d in ET.parse(self.out).getroot().findall("deviceoptions")]
+ self.assertTrue(any("{0201231D" in n for n in names))
+ self.assertFalse(any("{0205231D" in n for n in names))
+
+ def test_restore_hat(self):
+ _, after = self.fix("partial_hat")
+ self.assertEqual(self.rebinds("v_view_yaw_left"), [{"input": "js3_hat1_left"}])
+ self.assertEqual(self.rebinds("v_view_yaw_right"), [{"input": "js3_hat1_right"}])
+ hats = self.checks(after, "partial_hat")
+ self.assertEqual([f.inputs for f in hats], [["js3_hat1_up"]])
+
+ def test_unbind_missing_inputs(self):
+ rudder = stick("T-Rudder", RUDDER, buttons=0, hats=0)
+ _, after = self.fix("no_such_input", system=[IN_ORDER[0], rudder, IN_ORDER[2]])
+ self.assertFalse(self.checks(after, "no_such_input"))
+ self.assertEqual(self.rebinds("v_strafe_up"), [{"input": "js2_ "}])
+
+ def test_renumber_to_match_this_pc(self):
+ changes, after = self.fix("device_order", system=SWAPPED)
+ self.assertFalse(self.checks(after, "device_order"))
+ self.assertEqual([r.status for r in after.devices], ["ok", "ok", "ok"])
+ # FSM.GA's binding followed it from js1 to js2, the rudder's the other way.
+ self.assertEqual(self.rebinds("v_boost"), [{"input": "js2_button1"}])
+ self.assertEqual(self.rebinds("v_strafe_up"), [{"input": "js1_button3"}])
+ self.assertEqual(len(changes), 1) # one renumber even though two findings carry it
+ root = ET.parse(self.out).getroot()
+ insts = [o.get("instance") for o in root.findall("options") if o.get("type") == "joystick"]
+ self.assertEqual(len(insts), len(set(insts)))
+
+ def test_renumber_not_offered_with_a_stick_missing(self):
+ report = check_profile(FIXTURE, [IN_ORDER[1], IN_ORDER[0]])
+ self.assertFalse([f for f in report.findings if f.fix and f.fix["kind"] == "renumber"])
+
+ def test_fix_all_safe_then_clean(self):
+ report = check_profile(FIXTURE, SWAPPED)
+ safe = []
+ for f in report.findings:
+ if f.fix and f.fix.get("safe") and f.fix not in safe:
+ safe.append(f.fix)
+ apply_fixes(FIXTURE, safe, self.out)
+ after = check_profile(self.out, SWAPPED)
+ left = {f.check for f in after.findings if f.severity in ("error", "warning")}
+ # Only the ones that need a choice from the user remain.
+ self.assertEqual(left, {"mode_switch_clash", "partial_hat"})
+
+ def test_original_file_untouched(self):
+ with open(FIXTURE, "rb") as f:
+ before = f.read()
+ self.fix("forced_press")
+ with open(FIXTURE, "rb") as f:
+ self.assertEqual(f.read(), before)
+
+ def test_live_actionmaps_wrapper(self):
+ with open(FIXTURE, encoding="utf-8") as f:
+ body = f.read()
+ body = body.replace("\n", "\n")
+ live = os.path.join(self.tmp.name, "actionmaps.xml")
+ with open(live, "w", encoding="utf-8") as f:
+ f.write(body)
+ _, after = self.fix("device_order", system=SWAPPED, path=live)
+ self.assertFalse(self.checks(after, "device_order"))
+ self.assertEqual(ET.parse(self.out).getroot().tag, "ActionMaps")
+
+
+if __name__ == "__main__":
+ unittest.main()
From ac518f753920839b710862b3aa48b479f4be89b0 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 13:30:58 +0000
Subject: [PATCH 7/8] README: make the version badge follow the latest release
The badge was hard-coded to 0.8.2 and never bumped, so the README on
GitHub showed a version three releases old. Shields' github/v/release
badge reads the latest published release, so it updates itself when
release.yml publishes. The in-app Help view skips badge lines, so nothing
changes there.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_011hqxFh5GLh4UnV4rY8Fzdw
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 499165f..543c46d 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
A desktop application for editing and exporting Star Citizen control profiles in human-readable formats. Create visual diagrams of your controller layouts and export your bindings to PDF, Word, CSV, and annotated device graphics.
-
+

## Download & Installation
From f45861a0bb78784ee4229983e72608992f45a276 Mon Sep 17 00:00:00 2001
From: Claude
Date: Fri, 20 Nov 2026 20:08:42 +0000
Subject: [PATCH 8/8] Finalize CHANGELOG for 0.11.0
release.yml builds the GitHub Release body from the ## [0.11.0] section
and fails without it. Amr asked to merge and release (2026-11-20).
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_011hqxFh5GLh4UnV4rY8Fzdw
---
docs/CHANGELOG.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 7cbb50f..04438f9 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [0.11.0] - 2026-11-20
+
### Fixed
- **Hat/button bindings stuck in "hold" actions (e.g. look left/right/behind)** — The Remap dialog forced `activationMode="press"` onto every non-axis binding it saved. Star Citizen defines the view yaw / look-behind actions as `hold` in `defaultProfile.xml`, so the explicit `press` overrode that and the camera stayed locked after the hat was released. The dialog now defaults to **(Game default)**, which writes no `activationMode` attribute at all, and only emits one when the user explicitly picks `press`, `release`, `hold`, `double_tap` or `tap`. Existing explicit modes in a profile are preserved (case-insensitively).
- **Unit tests failed on a clean checkout** — `tests/test_parser.py` pointed at a gitignored personal profile; it now uses the committed `layout_osiris-vkb-2025-10-25_exported.xml` fixture.