From 7b68a955eebd5a41d6dae8019eba9bdfde912d5c Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 18:07:53 +0000 Subject: [PATCH] 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"

" + f"{_SEVERITY_ICON.get(f.severity, '')} {html.escape(f.title)}" + f" ({_SEVERITY_LABEL.get(f.severity, f.severity)})
" + f"{html.escape(f.detail)}

") + 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()