Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<ActionProfiles>`) and reports problems as findings with severities. The device-numbering check compares each `<options type="joystick" instance="N" Product="…">` 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 `<ActionProfiles>`) and reports problems as findings with severities. The device-numbering check compares each `<options type="joystick" instance="N" Product="…">` 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.

Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ Copy `product` straight from an `<options type="joystick" Product="…">` 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.

Expand Down
39 changes: 38 additions & 1 deletion src/gui/main_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)

Expand Down
100 changes: 95 additions & 5 deletions src/gui/profile_check_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)

Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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"<br><a href='fix:{i}'>🔧 {html.escape(f.fix.get('label', 'Fix'))}</a>"
chunks.append(
f"<p style='margin: 0 0 10px 0;'>"
f"{_SEVERITY_ICON.get(f.severity, '')} <b>{html.escape(f.title)}</b>"
f" <span style='opacity:0.7'>({_SEVERITY_LABEL.get(f.severity, f.severity)})</span><br>"
f"{html.escape(f.detail)}</p>")
f"{html.escape(f.detail)}{link}</p>")
self.findings_view.setHtml("".join(chunks) or "<p>Nothing to report.</p>")
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()
Loading
Loading