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"

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

") + f"{html.escape(f.detail)}{link}

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