Compare commits

...
1 Commits
Author SHA1 Message Date
Anton Palgunov fb9689cbad wip-1. Saturn Works! 2026-05-17 03:26:50 +01:00
21 changed files with 3552 additions and 47 deletions

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
# ppqt.sh — PortProtonQt dev helper
# Usage: ./dev-scripts/ppqt.sh [build|run|test|close]
set -e
cd "$(dirname "$0")/.."
CMD="${1:-help}"
case "$CMD" in
build)
echo "→ Running pre-commit on all files..."
uv run pre-commit run --all-files
;;
run)
echo "→ Killing old instances..."
pkill -f portprotonqt 2>/dev/null || true
sleep 1
echo "→ Starting PortProtonQt..."
uv run portprotonqt --debug-level INFO
;;
test)
echo "→ Running tests..."
uv run python -m pytest tests/ -v --tb=short "${@:2}"
;;
close)
echo "→ Killing PortProtonQt..."
# Kill by script name AND by python process running portprotonqt
pkill -f portprotonqt 2>/dev/null || true
pkill -f "python.*portprotonqt" 2>/dev/null || true
pkill -f "uv run portprotonqt" 2>/dev/null || true
echo "→ Killing Wine processes..."
pkill -9 -f "wine64-preloader|wineserver|winedevice|wine64$|/wine$" 2>/dev/null || true
echo "→ Killing Windows apps in Wine..."
pkill -9 -f "steam\.exe|Steam\.exe|Battle\.net\.exe|battle\.net\.exe|Agent\.exe|steamwebhelper" 2>/dev/null || true
sleep 1
remaining=$(pgrep -f "wine64-preloader|wineserver|winedevice|steam\.exe|battle\.net\.exe" 2>/dev/null | wc -l | tr -d ' ')
if [ "$remaining" -gt 0 ]; then
echo "⚠ Still running ($remaining processes):"
pgrep -af "wine64-preloader|wineserver|winedevice|steam\.exe|battle\.net\.exe" 2>/dev/null | awk '{print " PID",$1,$2,$3}'
else
echo "✓ All Wine processes killed"
fi
;;
*)
echo "Usage: $0 [build|run|test|close]"
echo ""
echo " build — run pre-commit on all files"
echo " run — kill old instance and start PortProtonQt"
echo " test — run pytest (extra args passed through)"
echo " close — kill PortProtonQt + all Wine processes"
;;
esac
+3 -1
View File
@@ -178,7 +178,9 @@ def main():
start_sh = get_portproton_start_command()
if start_sh is None:
return
if sys.platform == "linux":
return
start_sh = []
# Handle Steam compatibility mode - launch game directly without GUI.
if is_steam_compat:
+2
View File
@@ -18,6 +18,7 @@ from portprotonqt.config.portproton import (
create_desktop_file,
extract_exec_target_path,
find_game_by_exe,
get_macos_wine_dir,
get_portproton_location,
get_portproton_scripts_path,
get_portproton_start_command,
@@ -75,6 +76,7 @@ __all__ = [
"apply_xdg_autostart",
"read_portdata_path_from_config",
"save_portdata_path_to_config",
"get_macos_wine_dir",
"get_portproton_scripts_path",
"get_portproton_start_command",
"get_portproton_location",
+6
View File
@@ -170,6 +170,12 @@ def get_portproton_start_command() -> list[str] | None:
return None
def get_macos_wine_dir() -> str:
"""Return Wine installation directory for macOS."""
xdg_data = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
return os.path.join(xdg_data, "PortProtonQt", "wine")
def migrate_legacy_shortcut(portproton_path: str, desktop_dir: str | None = None) -> int:
"""Migrate legacy PortProton shortcuts in known desktop directories."""
flatpak_id = os.getenv("FLATPAK_ID", "").strip()
+81 -17
View File
@@ -2,6 +2,7 @@
import os
import shutil
import sys
import tempfile
import urllib.parse
from PySide6.QtWidgets import (
@@ -20,6 +21,7 @@ from portprotonqt.localization import _
from portprotonqt.version_utils import version_sort_key
from portprotonqt.dialogs.dialog_utils import create_dialog_hints_widget, update_dialog_hints
from portprotonqt.dialogs.wine_loader import WineLoadingThread, get_cpu_level
from portprotonqt.dialogs.wine_macos_loader import MacOSWineLoadingThread
from portprotonqt.dialogs.wine_downloader import DownloadThread
from portprotonqt.dialogs.wine_extractor import ExtractionThread
from portprotonqt.preloader import Preloader
@@ -28,6 +30,41 @@ from portprotonqt.steam_api import get_steam_compatibilitytools_dir, get_steam_h
logger = get_logger(__name__)
theme_manager = ThemeManager()
# Archives that extract to a generic "wswine.bundle" directory (Sikarugir/Wineskin format)
_WSWINE_GENERIC_NAME = "wswine.bundle"
def _rename_wswine_bundle(extract_dir: str, archive_name: str) -> None:
"""Rename wswine.bundle to archive stem for a readable wine list.
E.g. WS12WineSikarugir10.0-battle.net.tar.xz → WS12WineSikarugir10.0-battle.net
"""
src = os.path.join(extract_dir, _WSWINE_GENERIC_NAME)
if not os.path.isdir(src):
return
stem = archive_name
for ext in (".tar.xz", ".tar.gz", ".zip"):
if stem.endswith(ext):
stem = stem[: -len(ext)]
break
if stem == _WSWINE_GENERIC_NAME or not stem:
return
dst = os.path.join(extract_dir, stem)
if os.path.exists(dst):
logger.warning("rename wswine.bundle: target %s already exists, skipping", dst)
return
try:
os.rename(src, dst)
logger.info("renamed wswine.bundle → %s", stem)
# Fix wineserver RPATH so libinotify.0.dylib is found (wswine.bundle specific)
import sys
if sys.platform == "darwin":
from portprotonqt.macos_wine_tools import fix_wineserver_rpath
wine_bin = os.path.join(dst, "bin", "wine")
fix_wineserver_rpath(wine_bin)
except OSError as e:
logger.warning("Failed to rename wswine.bundle: %s", e)
class ProtonManager(DraggableDialog):
"""Dialog for managing Proton/Wine versions."""
@@ -185,7 +222,10 @@ class ProtonManager(DraggableDialog):
)
def start_loading_wine_data(self):
self.wine_loading_thread = WineLoadingThread()
if sys.platform == 'darwin':
self.wine_loading_thread = MacOSWineLoadingThread()
else:
self.wine_loading_thread = WineLoadingThread()
self.wine_loading_thread.loading_complete.connect(self.on_wine_data_loaded)
self.wine_loading_thread.loading_error.connect(self.on_wine_data_load_error)
self.wine_loading_thread.start()
@@ -382,17 +422,23 @@ class ProtonManager(DraggableDialog):
return basename.split('-')[0] if '-' in basename else basename
def is_asset_installed(self, asset_filename, source_name):
if not self.portproton_location:
return False
name_without_ext = asset_filename
for ext in ['.tar.gz', '.tar.xz']:
for ext in ('.tar.gz', '.tar.xz'):
if name_without_ext.lower().endswith(ext):
name_without_ext = name_without_ext[:-len(ext)]
break
if sys.platform == 'darwin':
from portprotonqt.config import get_macos_wine_dir
wine_dir = get_macos_wine_dir()
for dirname in (name_without_ext, name_without_ext.upper()):
if os.path.exists(os.path.join(wine_dir, dirname)):
return True
return False
if not self.portproton_location:
return False
dist_path = os.path.join(self.portproton_location, "data", "dist")
for dirname in (name_without_ext, name_without_ext.upper()):
expected_dir = os.path.join(dist_path, dirname)
if os.path.exists(expected_dir):
if os.path.exists(os.path.join(dist_path, dirname)):
return True
steam_dir = get_steam_compatibilitytools_dir()
if steam_dir is None:
@@ -400,6 +446,9 @@ class ProtonManager(DraggableDialog):
return steam_dir.joinpath(name_without_ext).exists()
def get_download_extract_dir(self) -> str:
if sys.platform == 'darwin':
from portprotonqt.config import get_macos_wine_dir
return get_macos_wine_dir()
if ui_config.get_download_wine_to_steam():
steam_dir = get_steam_compatibilitytools_dir()
if steam_dir is not None:
@@ -436,16 +485,21 @@ class ProtonManager(DraggableDialog):
self.tab_widget.addTab(tab, _("Installed"))
def get_installed_versions(self) -> list[tuple[str, str]]:
portproton_location = self.portproton_location
if portproton_location is None:
return []
dist_path = os.path.join(portproton_location, "data", "dist")
if not os.path.exists(dist_path):
os.makedirs(dist_path, exist_ok=True)
installed_versions = []
seen_paths = set()
version_dirs = [dist_path]
seen_paths: set[str] = set()
version_dirs: list[str] = []
if sys.platform == 'darwin':
from portprotonqt.config import get_macos_wine_dir
macos_wine_dir = get_macos_wine_dir()
os.makedirs(macos_wine_dir, exist_ok=True)
version_dirs.append(macos_wine_dir)
else:
portproton_location = self.portproton_location
if portproton_location is None:
return []
dist_path = os.path.join(portproton_location, "data", "dist")
os.makedirs(dist_path, exist_ok=True)
version_dirs.append(dist_path)
steam_dir = get_steam_compatibilitytools_dir()
if steam_dir is not None:
version_dirs.append(str(steam_dir))
@@ -471,9 +525,17 @@ class ProtonManager(DraggableDialog):
def is_installed_version_dir(self, version_path: str) -> bool:
if not os.path.isdir(version_path):
return False
if os.path.isfile(os.path.join(version_path, "bin", "wine")):
bin_dir = os.path.join(version_path, "bin")
if os.path.isfile(os.path.join(bin_dir, "wine")):
return True
if os.path.isfile(os.path.join(version_path, "files", "bin", "wine")):
if os.path.isfile(os.path.join(bin_dir, "wine64")):
return True
# macOS .app bundle layout
macos_bin = os.path.join(version_path, "Contents", "Resources", "wine", "bin")
if os.path.isfile(os.path.join(macos_bin, "wine64")):
return True
files_bin = os.path.join(version_path, "files", "bin")
if os.path.isfile(os.path.join(files_bin, "wine")):
return True
return os.path.isfile(os.path.join(version_path, "dist", "bin", "wine"))
@@ -946,6 +1008,8 @@ class ProtonManager(DraggableDialog):
def extraction_finished(archive_path, success):
if success:
logger.info(f"Successfully extracted: {archive_path}")
# Rename wswine.bundle → archive name for readable wine list
_rename_wswine_bundle(extract_dir, asset_data['asset_name'])
else:
logger.error(f"Failed to extract: {archive_path}")
QMessageBox.critical(self, _("Extraction Error"), _("Failed to extract archive: {0}").format(archive_path))
+128 -4
View File
@@ -4,6 +4,7 @@ import os
import re
import shutil
import subprocess
import sys
from typing import cast, TYPE_CHECKING
from PySide6.QtCore import Qt, QObject, QEvent, QProcess, QTimer, QUrl
@@ -148,7 +149,7 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
key=version_sort_key
)
scripts_path = get_portproton_scripts_path()
if scripts_path:
if scripts_path and sys.platform != "darwin": # LG versions are Linux-only
var_path = os.path.join(scripts_path, "var")
self.lg_dist_aliases = read_lg_dist_versions_from_var(var_path)
for version in self.lg_dist_aliases.values():
@@ -167,6 +168,20 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
key=prefix_sort_key
)
if sys.platform == 'darwin':
from portprotonqt.config import get_macos_wine_dir
from portprotonqt.macos_wine_tools import get_macos_prefixes_dir
macos_wine_dir = get_macos_wine_dir()
if os.path.isdir(macos_wine_dir):
for entry in sorted(os.listdir(macos_wine_dir)):
if os.path.isdir(os.path.join(macos_wine_dir, entry)) and entry not in self.dist_options:
self.dist_options.append(entry)
macos_pfx_dir = get_macos_prefixes_dir()
if os.path.isdir(macos_pfx_dir):
for entry in sorted(os.listdir(macos_pfx_dir)):
if os.path.isdir(os.path.join(macos_pfx_dir, entry)) and entry not in self.prefix_options:
self.prefix_options.append(entry)
if shutil.which('wine'):
if _('System WINE') not in self.dist_options:
self.dist_options.append(_('System WINE'))
@@ -261,9 +276,11 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
self.tab_widget.addTab(self.main_tab, _("Main"))
self.tab_widget.addTab(self.advanced_tab, _("Advanced"))
self.tab_widget.addTab(self.mangohud_tab, "MangoHud")
if self.gamescope_available:
self.tab_widget.addTab(self.gamescope_tab, "Gamescope")
if sys.platform != "darwin":
# MangoHud and Gamescope are Linux-only
self.tab_widget.addTab(self.mangohud_tab, "MangoHud")
if self.gamescope_available:
self.tab_widget.addTab(self.gamescope_tab, "Gamescope")
self.tab_widget.currentChanged.connect(self.on_table_selection_changed)
self.settings_table = QTableWidget()
@@ -463,6 +480,10 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
if current_wine_version and current_wine_version not in self.dist_options:
self.dist_options.append(current_wine_version)
# macOS: load saved MacOSGameSettings and merge into current_settings
if sys.platform == "darwin":
self._load_macos_settings_into_current()
self.original_values = self.current_settings.copy()
for key in set(self.toggle_settings.keys()):
self.original_values.setdefault(key, '0')
@@ -710,10 +731,45 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
desc_item.setForeground(QColor(self.theme.color_disabled_text))
self.advanced_table.setItem(row, 2, desc_item)
if sys.platform == "darwin":
self._populate_macos_settings()
if self.advanced_table.rowCount() > 0:
self.on_table_selection_changed()
self._install_line_edit_event_filters()
def _populate_macos_settings(self) -> None:
"""Add macOS-specific settings rows to the Advanced tab."""
from portprotonqt.macos_settings import MacOSGameSettings, load_game_settings
exec_line = getattr(self, "exe_path", None) or ""
mac_settings = load_game_settings(exec_line) if exec_line else MacOSGameSettings()
macos_rows = [
("WINEMSYNC", _("MSYNC"), mac_settings.msync,
_("Monolithic sync (macOS). Reduces CPU usage. Equivalent to ESYNC but for macOS.")),
("MTL_HUD_ENABLED", _("FPS HUD (Metal)"), mac_settings.show_fps,
_("Show Metal performance HUD with FPS counter (macOS equivalent of MangoHud).")),
("DXMT", _("DXMT"), mac_settings.dxmt,
_("DirectX 10/11 via Metal (Apple Silicon). Replaces DXVK for macOS.")),
("ROSETTA_ADVERTISE_AVX", _("Rosetta AVX"), mac_settings.rosetta_avx,
_("Advertise AVX support to Rosetta 2 (Apple Silicon). Needed by some games.")),
]
for key, name, current_val, desc in macos_rows:
row = self.advanced_table.rowCount()
self.advanced_table.insertRow(row)
name_item = QTableWidgetItem(f"[macOS] {name}")
name_item.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled)
name_item.setData(Qt.ItemDataRole.UserRole, key)
self.advanced_table.setItem(row, 0, name_item)
cb = QCheckBox()
cb.setChecked(bool(current_val))
self.advanced_table.setCellWidget(row, 1, cb)
self.advanced_widgets[key] = cb
self.original_display_values[key] = "1" if current_val else "0"
desc_item = QTableWidgetItem(desc)
desc_item.setFlags(Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEnabled)
self.advanced_table.setItem(row, 2, desc_item)
def init_virtual_keyboard(self):
"""Initialize virtual keyboard."""
self.keyboard = VirtualKeyboard(self, theme=self.theme, button_width=50)
@@ -781,8 +837,76 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
self._filter_mangohud_settings(search_text)
self._filter_gamescope_settings(search_text)
def _load_macos_settings_into_current(self) -> None:
"""Load MacOSGameSettings and merge into current_settings for display."""
from portprotonqt.macos_settings import load_game_settings
from portprotonqt.macos_wine_tools import get_prefix_path, get_macos_prefixes_dir
import os as _os
exec_line = getattr(self, "exe_path", None) or ""
if not exec_line:
return
settings = load_game_settings(exec_line)
# Wine Version → PW_WINE_USE
if settings.wine_version and settings.wine_version not in self.dist_options:
self.dist_options.append(settings.wine_version)
if settings.wine_version:
self.current_settings["PW_WINE_USE"] = settings.wine_version
# Prefix name → PW_PREFIX_NAME (extract name from path)
if settings.wineprefix:
prefix_name = _os.path.basename(settings.wineprefix.rstrip("/"))
if prefix_name and prefix_name not in self.prefix_options:
self.prefix_options.append(prefix_name)
self.current_settings["PW_PREFIX_NAME"] = prefix_name
def _apply_changes_macos(self) -> None:
"""macOS: save changed settings to MacOSGameSettings instead of start_sh."""
from portprotonqt.macos_settings import (
MacOSGameSettings, load_game_settings, save_game_settings,
)
from portprotonqt.macos_wine_tools import get_prefix_path
exec_line = getattr(self, "exe_path", None) or ""
settings = load_game_settings(exec_line) if exec_line else MacOSGameSettings()
for key, widget in self.advanced_widgets.items():
if isinstance(widget, QComboBox):
val = widget.currentText()
if key == "PW_WINE_USE":
settings.wine_version = val
elif key == "PW_PREFIX_NAME":
prefix_name = re.sub(r"[ \t]", "_", val.strip()).upper()
settings.wineprefix = get_prefix_path(self.portproton_path, prefix_name)
elif key == "WINEDLLOVERRIDES":
if val and val != _('disabled'):
settings.env_vars["WINEDLLOVERRIDES"] = val
else:
settings.env_vars.pop("WINEDLLOVERRIDES", None)
elif isinstance(widget, QLineEdit):
val = widget.text().strip()
if key == "PW_LAUNCH_PARAMS":
settings.launch_args = val
elif val:
settings.env_vars[key] = val
elif isinstance(widget, QCheckBox):
checked = widget.isChecked()
if key == "WINEMSYNC":
settings.msync = checked
elif key == "MTL_HUD_ENABLED":
settings.show_fps = checked
elif key == "DXMT":
settings.dxmt = checked
elif key == "ROSETTA_ADVERTISE_AVX":
settings.rosetta_avx = checked
save_game_settings(exec_line, settings)
logger.info("macOS: saved game settings for %s", exec_line)
self.apply_button.setEnabled(True)
self.accept()
def apply_changes(self):
"""Apply changes by collecting diffs from both main and advanced tabs."""
if sys.platform == "darwin":
self._apply_changes_macos()
return
changes = []
mangohud_enabled = False
+94
View File
@@ -0,0 +1,94 @@
"""macOS Wine loader — fetches Wine releases from GitHub APIs."""
import math
import sys
import orjson
from PySide6.QtCore import QThread, Signal
from portprotonqt.downloader import get_requests_session
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
MACOS_WINE_SOURCES: dict[str, str] = {
"wine-crossover": (
"https://api.github.com/repos/Heroic-Games-Launcher/wine-crossover/releases"
),
"wine-staging-macos": (
"https://api.github.com/repos/Gcenx/macOS_Wine_builds/releases"
),
# Sikarugir Engines: Wine builds with gnutls + MoltenVK bundled — best Battle.net compat
"sikarugir-engines": (
"https://api.github.com/repos/Sikarugir-App/Engines/releases"
),
"game-porting-toolkit": (
"https://api.github.com/repos/Gcenx/game-porting-toolkit/releases"
),
}
_ARCHIVE_EXTS = ('.tar.xz', '.tar.gz')
def _human_size(size_bytes: int) -> str:
if size_bytes <= 0:
return "Unknown"
units = ('B', 'KiB', 'MiB', 'GiB')
idx = min(int(math.log(max(size_bytes, 1), 1024)), len(units) - 1)
return f"{size_bytes / (1024 ** idx):.1f} {units[idx]}"
def _parse_release(release: dict) -> list[dict]:
"""Return archive entries from a single GitHub release dict."""
by_name = {a['name']: a for a in release.get('assets', [])}
entries = []
for name, asset in by_name.items():
if not any(name.endswith(ext) for ext in _ARCHIVE_EXTS):
continue
sha_url = by_name.get(name + '.sha512sum', {}).get('browser_download_url', '')
entries.append({
'name': name,
'url': asset['browser_download_url'],
'size_human': _human_size(asset.get('size', 0)),
'sha512_url': sha_url,
})
return entries
def _fetch_source(api_url: str) -> list[dict]:
"""Fetch and parse Wine entries from one GitHub Releases API URL."""
session = get_requests_session()
resp = session.get(api_url, params={'per_page': 20}, timeout=30)
resp.raise_for_status()
releases: list[dict] = orjson.loads(resp.content)
entries: list[dict] = []
for release in releases:
entries.extend(_parse_release(release))
return entries
class MacOSWineLoadingThread(QThread):
"""Fetches available macOS Wine versions from GitHub release APIs."""
loading_complete = Signal(object) # dict[str, list[dict]]
loading_error = Signal(str)
def run(self) -> None:
if sys.platform != 'darwin':
self.loading_complete.emit({})
return
result: dict[str, list[dict]] = {}
errors: list[str] = []
for source_key, api_url in MACOS_WINE_SOURCES.items():
try:
entries = _fetch_source(api_url)
if entries:
result[source_key] = entries
logger.info("macOS wine: %d entries for %s", len(entries), source_key)
except Exception as e:
logger.warning("macOS wine: failed to load %s: %s", source_key, e)
errors.append(f"{source_key}: {e}")
if not result and errors:
self.loading_error.emit('; '.join(errors))
else:
self.loading_complete.emit(result)
+12 -2
View File
@@ -8,7 +8,13 @@ os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1")
os.environ.setdefault("SDL_VIDEO_ALLOW_SCREENSAVER", "1")
import pygame
from pygame._sdl2 import controller
from evdev import UInput, ecodes
try:
from evdev import UInput, ecodes # type: ignore[import]
except ImportError:
UInput = None # type: ignore[assignment,misc]
class ecodes: # type: ignore[no-redef]
EV_KEY = EV_REL = BTN_LEFT = BTN_RIGHT = REL_X = REL_Y = REL_WHEEL = 0
from enum import Enum
from shiboken6 import isValid
from PySide6.QtWidgets import QWidget, QStackedWidget, QApplication, QScrollArea, QAbstractScrollArea, QLineEdit, QDialog, QMenu, QComboBox, QListView, QMessageBox, QListWidget, QTableWidget, QAbstractItemView, QSlider, QCheckBox, QPushButton
@@ -143,6 +149,10 @@ class MouseEmulationThread(QThread):
def run(self):
"""Run UInput device creation in background thread."""
try:
if UInput is None:
self.finished.emit(False)
return
if not os.path.exists('/dev/uinput'):
logger.error("EMUL: /dev/uinput does not exist")
self.finished.emit(False)
@@ -169,7 +179,7 @@ class MouseEmulationThread(QThread):
logger.error(f"EMUL: Error creating virtual mouse: {ex}", exc_info=True)
self.finished.emit(False)
def get_device(self) -> UInput | None:
def get_device(self) -> Any:
"""Get the created UInput device after thread finishes."""
return getattr(self, '_device', None)
+177
View File
@@ -0,0 +1,177 @@
"""Per-game macOS Wine settings — DXMT, D3DMetal, MSYNC, FPS HUD, etc.
Architecture mirrors Heroic Games Launcher's GameSettings for macOS.
Settings are persisted as JSON keyed by a hash of the game's exec_line.
"""
import hashlib
import json
import os
import sys
from dataclasses import asdict, dataclass, field
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
_SETTINGS_DIR_ENV = "XDG_DATA_HOME"
def get_game_settings_dir() -> str:
xdg = os.getenv(_SETTINGS_DIR_ENV, os.path.expanduser("~/.local/share"))
return os.path.join(xdg, "PortProtonQt", "game_settings")
def _settings_path(exec_line: str) -> str:
key = hashlib.sha256(exec_line.encode()).hexdigest()[:16]
return os.path.join(get_game_settings_dir(), f"{key}.json")
@dataclass
class MacOSGameSettings:
"""Per-game settings for macOS Wine launcher.
Mirrors Heroic's GameSettings for macOS-relevant options.
"""
# Wine selection
wine_version: str = "" # e.g. "Wine-Crossover-23.7.1-1"
wineprefix: str = "" # absolute path to WINEPREFIX
# DirectX backend (mutually exclusive)
# wined3d: default (no extra env vars needed)
dxmt: bool = False # DX10/11 via Metal — copies DXMT DLLs into prefix
d3dmetal: bool = False # DX11/12 via Metal — requires GPTK wine + Apple Silicon
dxvk: bool = False # DX10/11 via Vulkan/MoltenVK
# Sync primitives
msync: bool = True # WINEMSYNC=1 (macOS only, better than esync)
esync: bool = False # WINEESYNC=1 (fallback, auto-enabled with GPTK)
# Display
show_fps: bool = False # MTL_HUD_ENABLED=1 (Metal performance HUD)
fsr: bool = False # WINE_FULLSCREEN_FSR=1
fsr_sharpness: int = 2 # WINE_FULLSCREEN_FSR_STRENGTH
# Apple Silicon
rosetta_avx: bool = False # ROSETTA_ADVERTISE_AVX=1 for Rosetta translation
# Launch
launch_args: str = "" # extra CLI args appended to wine invocation
env_vars: dict[str, str] = field(default_factory=dict) # custom env overrides
verbose_logs: bool = False # WINEDEBUG=+fixme
def load_game_settings(exec_line: str) -> MacOSGameSettings:
"""Load saved settings for a game, returning defaults if not found."""
path = _settings_path(exec_line)
if not os.path.isfile(path):
return MacOSGameSettings()
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
return MacOSGameSettings(**{k: v for k, v in data.items() if k in MacOSGameSettings.__dataclass_fields__})
except Exception as e:
logger.warning("Failed to load game settings from %s: %s", path, e)
return MacOSGameSettings()
def save_game_settings(exec_line: str, settings: MacOSGameSettings) -> bool:
"""Persist settings for a game. Returns True on success."""
path = _settings_path(exec_line)
os.makedirs(os.path.dirname(path), exist_ok=True)
try:
with open(path, "w", encoding="utf-8") as f:
json.dump(asdict(settings), f, indent=2)
return True
except Exception as e:
logger.error("Failed to save game settings to %s: %s", path, e)
return False
def build_env_from_settings(settings: MacOSGameSettings, base_env: dict[str, str]) -> dict[str, str]:
"""Merge MacOSGameSettings into an env dict. Returns new dict (base_env unchanged)."""
env = base_env.copy()
# WINEPREFIX
if settings.wineprefix:
env["WINEPREFIX"] = settings.wineprefix
# Sync primitives
if settings.msync:
env["WINEMSYNC"] = "1"
if settings.esync or settings.d3dmetal:
env["WINEESYNC"] = "1"
# DirectX backend
if settings.dxmt:
# DXMT: DirectX 10/11 via Metal — override d3d11/dxgi DLLs
existing = env.get("WINEDLLOVERRIDES", "")
dxmt_overrides = "d3d11=n,b;d3d10core=n,b;dxgi=n,b"
env["WINEDLLOVERRIDES"] = f"{dxmt_overrides};{existing}" if existing else dxmt_overrides
env["WINEMSYNC"] = "1" # DXMT requires MSYNC
if settings.dxvk:
existing = env.get("WINEDLLOVERRIDES", "")
dxvk_overrides = "d3d11=n,b;d3d10core=n,b;dxgi=n,b"
env["WINEDLLOVERRIDES"] = f"{dxvk_overrides};{existing}" if existing else dxvk_overrides
# D3DMetal / GPTK
if settings.d3dmetal:
env["WINEESYNC"] = "1"
env["WINEMSYNC"] = "1"
# FPS HUD (macOS: MTL_HUD_ENABLED, Linux: DXVK_HUD)
if settings.show_fps:
if sys.platform == "darwin":
env["MTL_HUD_ENABLED"] = "1"
else:
env["DXVK_HUD"] = "fps"
# FSR
if settings.fsr:
env["WINE_FULLSCREEN_FSR"] = "1"
env["WINE_FULLSCREEN_FSR_STRENGTH"] = str(settings.fsr_sharpness)
# Apple Silicon Rosetta AVX
if settings.rosetta_avx:
env["ROSETTA_ADVERTISE_AVX"] = "1"
# Verbose Wine logging
if settings.verbose_logs:
env["WINEDEBUG"] = "+fixme"
# User custom env vars (highest priority)
env.update(settings.env_vars)
return env
def get_launch_args(settings: MacOSGameSettings) -> list[str]:
"""Return extra CLI arguments from settings."""
if not settings.launch_args:
return []
import shlex
try:
return shlex.split(settings.launch_args)
except ValueError:
return settings.launch_args.split()
def is_dxmt_installed(wineprefix: str) -> bool:
"""Check whether DXMT DLLs are present in a wine prefix."""
marker = os.path.join(
wineprefix, "drive_c", "windows", "system32", "winemetal.dll"
)
return os.path.isfile(marker)
def is_d3dmetal_available() -> bool:
"""Return True if D3DMetal (GPTK) conditions are met: Apple Silicon macOS."""
if sys.platform != "darwin":
return False
try:
import platform
machine = platform.machine()
return machine == "arm64"
except Exception:
return False
+380
View File
@@ -0,0 +1,380 @@
"""macOS Wine runner — download and launch Windows installers via Wine."""
import os
import re
import shlex
import subprocess
import sys
import tempfile
from PySide6.QtCore import QThread, Signal
from portprotonqt.config import get_macos_wine_dir
from portprotonqt.downloader import get_requests_session
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
def get_macos_prefixes_dir() -> str:
"""Return WINEPREFIX base directory for macOS."""
xdg = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
return os.path.join(xdg, "PortProtonQt", "prefixes")
def _wine_version_priority(name: str, wine_dir: str = "") -> int:
"""Sort key: lower = higher priority.
Priority order: Sikarugir/Kegworks > Crossover > Staging > generic > GPTK
If wine_dir given, reads version file to determine actual type for wswine.bundle.
"""
n = name.lower()
# Read version file for generic wswine.bundle to detect actual type
if "wswine" in n and wine_dir:
version_path = os.path.join(wine_dir, "version")
try:
version_content = open(version_path).read().lower()
if "gptk" in version_content or "game porting" in version_content:
return 10
if "kegworks" in version_content or "sikarugir" in version_content:
return 0
except OSError:
pass
return 0 # Default wswine is Sikarugir-based
if "sikarugir" in n or "kegworks" in n or "wswine" in n:
return 0
if "crossover" in n or "cx" in n:
return 1
if "staging" in n or "whisky" in n:
return 2
if "game-porting" in n or "gptk" in n or "game porting" in n:
return 10 # Last resort — GPTK is D3D12 focused, not general-purpose
return 5
def find_wine_binary(prefer_crossover: bool = True) -> str | None:
"""Return path to first usable wine/wine64 binary in macOS Wine dir.
Supports both .app bundle layout (Contents/Resources/wine/bin/)
and traditional layout (bin/).
When prefer_crossover=True (default), Wine-Crossover is tried before GPTK.
"""
wine_dir = get_macos_wine_dir()
if not os.path.isdir(wine_dir):
return None
candidates = (
os.path.join("Contents", "Resources", "wine", "bin", "wine64"),
os.path.join("Contents", "Resources", "wine", "bin", "wine"),
os.path.join("bin", "wine64"),
os.path.join("bin", "wine"),
)
if prefer_crossover:
entries = sorted(
os.listdir(wine_dir),
key=lambda e: _wine_version_priority(e, os.path.join(wine_dir, e))
)
else:
entries = sorted(os.listdir(wine_dir))
for entry in entries:
base = os.path.join(wine_dir, entry)
for rel in candidates:
path = os.path.join(base, rel)
if os.path.isfile(path) and os.access(path, os.X_OK):
logger.info("macOS runner: using wine binary %s", path)
return path
return None
def find_ntlm_auth() -> str | None:
"""Find ntlm_auth binary (from Samba) needed for NTLM authentication.
Wine uses ntlm_auth for Battle.net, Office, and other Windows apps
that require NTLM/Kerberos. On macOS, install via: brew install samba
"""
import shutil
# Wineskin includes /opt/local/bin (MacPorts); we also check Homebrew
search_paths = [
"/opt/homebrew/bin", # Homebrew Apple Silicon
"/usr/local/bin", # Homebrew Intel
"/opt/local/bin", # MacPorts (Wineskin default)
"/opt/local/sbin",
]
for directory in search_paths:
candidate = os.path.join(directory, "ntlm_auth")
if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
return candidate
return shutil.which("ntlm_auth")
def build_wine_env(wine_bin: str) -> dict[str, str]:
"""Build environment dict with DYLD paths and PATH for a Wine binary.
Wineskin-style: includes Homebrew + MacPorts paths so Wine can find
ntlm_auth (needed for Battle.net, NTLM auth) without extra config.
"""
bin_dir = os.path.dirname(wine_bin)
wine_root = os.path.dirname(bin_dir)
lib_dir = os.path.join(wine_root, "lib")
lib64_dir = os.path.join(wine_root, "lib64")
existing_dyld = os.getenv("DYLD_FALLBACK_LIBRARY_PATH", "")
# Include Homebrew + MacPorts lib dirs so Wine finds libgnutls (needed for NTLM/Battle.net)
# This mirrors Sikarugir's approach of bundling gnutls — we use the system-installed one.
extra_lib_dirs = [
"/opt/homebrew/lib", # Homebrew Apple Silicon
"/usr/local/lib", # Homebrew Intel
"/opt/local/lib", # MacPorts
]
dyld_parts = [p for p in [lib_dir, lib64_dir] + extra_lib_dirs + ["/usr/lib"] if os.path.isdir(p)]
if existing_dyld:
dyld_parts.append(existing_dyld)
dyld = ":".join(dyld_parts)
# Wineskin pattern: prepend Homebrew + MacPorts so ntlm_auth is found
extra_paths = ":".join(p for p in [
"/opt/homebrew/bin",
"/opt/homebrew/sbin",
"/usr/local/bin",
"/opt/local/bin",
"/opt/local/sbin",
] if os.path.isdir(p))
system_path = os.environ.get("PATH", "/usr/bin:/bin")
# MoltenVK + libinotify: check Sikarugir bundle first (ships these bundled)
# Sikarugir ships x86_64 versions compatible with wine (x86_64/Rosetta)
sikarugir_frameworks = os.path.expanduser(
"~/Applications/Sikarugir/Battlenet.app/Contents/Frameworks"
)
moltenvk_dirs = [
os.path.join(sikarugir_frameworks, "moltenvkcx"),
"/opt/homebrew/lib",
]
for mvk_dir in moltenvk_dirs:
if os.path.isfile(os.path.join(mvk_dir, "libMoltenVK.dylib")):
dyld_parts.insert(0, mvk_dir)
logger.info("macOS runner: MoltenVK found at %s", mvk_dir)
break
# libinotify: needed by wswine.bundle (Sikarugir wine) for file watching
if os.path.isfile(os.path.join(sikarugir_frameworks, "libinotify.0.dylib")):
if sikarugir_frameworks not in dyld_parts:
dyld_parts.insert(1, sikarugir_frameworks)
logger.info("macOS runner: libinotify found at %s", sikarugir_frameworks)
dyld = ":".join(dyld_parts)
env = os.environ.copy()
env["DYLD_FALLBACK_LIBRARY_PATH"] = dyld
env["PATH"] = f"{bin_dir}:{extra_paths}:{system_path}" if extra_paths else f"{bin_dir}:{system_path}"
# Sikarugir defaults: WINEESYNC=1 + WINEMSYNC=1 for best performance
env.setdefault("WINEMSYNC", "1")
env.setdefault("WINEESYNC", "1")
# Suppress verbose plugplay messages (Sikarugir default)
env.setdefault("WINEDEBUG", "-plugplay")
ntlm = find_ntlm_auth()
if ntlm:
logger.info("macOS runner: ntlm_auth found at %s", ntlm)
else:
logger.warning(
"macOS runner: ntlm_auth not found — NTLM auth (Battle.net login) will fail. "
"Fix: brew install samba"
)
return env
def _parse_script_field(script_path: str, pattern: str) -> str | None:
"""Extract first regex capture group from a script file."""
try:
with open(script_path, encoding="utf-8") as f:
content = f.read()
m = re.search(pattern, content)
return m.group(1).strip() if m else None
except OSError as e:
logger.warning("Failed to read script %s: %s", script_path, e)
return None
def parse_script_url(script_path: str) -> str | None:
"""Extract installer download URL from an autoinstall script."""
return _parse_script_field(script_path, r'try_download\s+"([^"]+)"')
def parse_script_prefix(script_path: str) -> str:
"""Extract PW_PREFIX_NAME from an autoinstall script."""
return _parse_script_field(script_path, r'PW_PREFIX_NAME\s*=\s*"?([^"\n]+)"?') or "DEFAULT"
def parse_script_launch_params(script_path: str) -> list[str]:
"""Extract LAUNCH_PARAMETERS from autoinstall script as a list of args."""
raw = _parse_script_field(script_path, r'LAUNCH_PARAMETERS\s*=\s*"([^"]*)"')
if not raw:
return []
try:
return shlex.split(raw)
except ValueError:
return raw.split()
def find_installed_exe(script_path: str, prefix_dir: str) -> str | None:
"""Resolve PW_EXE_FILE pattern against prefix_dir to find installed exe."""
raw = _parse_script_field(script_path, r'PW_EXE_FILE\s*=\s*"([^"]+)"')
if not raw:
return None
# Replace bash variables with real paths
resolved = raw.replace("$WINEPREFIX", prefix_dir).replace("\\", "/")
if os.path.isfile(resolved):
return resolved
# Case-insensitive fallback (Wine may create Steam.exe instead of steam.exe)
dir_part, base = os.path.split(resolved)
if os.path.isdir(dir_part):
for name in os.listdir(dir_part):
if name.lower() == base.lower():
return os.path.join(dir_part, name)
return None
def _download_file(url: str, dest: str) -> None:
"""Download URL to dest path, raising on HTTP errors."""
session = get_requests_session()
resp = session.get(url, stream=True, timeout=60)
resp.raise_for_status()
with open(dest, "wb") as f:
for chunk in resp.iter_content(chunk_size=65536):
if chunk:
f.write(chunk)
class MacOSAutoInstallThread(QThread):
"""Downloads a Windows installer and runs it through Wine on macOS."""
status = Signal(str) # progress message for UI
finished_ok = Signal(str) # installed exe path (or prefix dir as fallback)
finished_err = Signal(str) # error message on failure
def __init__(self, script_path: str):
super().__init__()
self.script_path = script_path
self.prefix_name = parse_script_prefix(script_path)
def run(self) -> None:
if sys.platform != "darwin":
self.finished_err.emit("MacOSAutoInstallThread used on non-macOS platform")
return
wine_bin = find_wine_binary()
if not wine_bin:
self.finished_err.emit(
"No Wine found. Download a Wine version in the Wine Manager first."
)
return
download_url = parse_script_url(self.script_path)
if not download_url:
self.finished_err.emit("Could not parse installer URL from script.")
return
launch_params = parse_script_launch_params(self.script_path)
prefix_dir = os.path.join(get_macos_prefixes_dir(), self.prefix_name)
os.makedirs(prefix_dir, exist_ok=True)
# Detect archive type from URL
url_lower = download_url.lower().split("?")[0]
is_zip = url_lower.endswith(".zip")
suffix = ".zip" if is_zip else ".exe"
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
tmp_exe = tmp.name
try:
self.status.emit("Downloading installer…")
logger.info("autoinstall: downloading %s", download_url)
_download_file(download_url, tmp_exe)
if is_zip:
# ZIP archive: extract directly into prefix (e.g. Saturn)
import zipfile
exe_pattern = _parse_script_field(self.script_path, r'PW_EXE_FILE\s*=\s*"([^"]+)"')
rel_path = ""
if exe_pattern:
# Get relative path inside drive_c
rel_path = exe_pattern.replace("$WINEPREFIX/drive_c/", "").replace("\\", "/")
extract_dir = os.path.join(prefix_dir, "drive_c", os.path.dirname(rel_path))
else:
extract_dir = os.path.join(prefix_dir, "drive_c", "Program Files (x86)")
os.makedirs(extract_dir, exist_ok=True)
self.status.emit("Extracting archive…")
logger.info("autoinstall: extracting zip to %s", extract_dir)
with zipfile.ZipFile(tmp_exe) as zf:
zf.extractall(extract_dir)
else:
self.status.emit("Running installer via Wine…")
env = build_wine_env(wine_bin)
env["WINEPREFIX"] = prefix_dir
cmd = [wine_bin, tmp_exe] + launch_params
logger.info("autoinstall: %s (prefix=%s)", cmd, prefix_dir)
result = subprocess.run(cmd, env=env, timeout=600)
if result.returncode not in (0, 1):
self.finished_err.emit(f"Installer exited with code {result.returncode}")
return
# Install base winetricks packages for better compatibility
self._install_base_packages(wine_bin, prefix_dir)
# Locate the installed exe
exe_path = find_installed_exe(self.script_path, prefix_dir)
if exe_path:
logger.info("autoinstall: found exe at %s", exe_path)
self.finished_ok.emit(exe_path)
else:
logger.info("autoinstall: no exe pattern found, emitting prefix dir")
self.finished_ok.emit(prefix_dir)
except subprocess.TimeoutExpired:
self.finished_err.emit("Installer timed out after 10 minutes.")
except Exception as e:
logger.error("macOS autoinstall failed: %s", e)
self.finished_err.emit(str(e))
finally:
if os.path.exists(tmp_exe):
os.unlink(tmp_exe)
def _install_base_packages(self, wine_bin: str, prefix_dir: str) -> None:
"""Install essential winetricks packages and apply anti-cheat workarounds."""
from portprotonqt.macos_wine_tools import (
install_winetricks_packages, detect_anticheat,
)
from portprotonqt.macos_settings import MacOSGameSettings, save_game_settings
import shutil
# Detect and handle anti-cheat (BattlEye / EAC)
ac = detect_anticheat(prefix_dir)
if ac:
logger.warning(
"autoinstall: detected anti-cheat %s in %s — "
"multiplayer will not work on macOS (kernel access required). "
"Applying beclient=n workaround so launcher can start.",
ac, prefix_dir
)
# Save WINEDLLOVERRIDES so beclient DLLs are ignored on launch
exec_line = f"autoinstall:{self.prefix_name}"
settings = MacOSGameSettings(
wineprefix=prefix_dir,
env_vars={"WINEDLLOVERRIDES": "beclient,beclient_x64=n"},
)
save_game_settings(exec_line, settings)
logger.info("autoinstall: saved beclient=n override for %s", self.prefix_name)
if not shutil.which("cabextract"):
logger.warning("autoinstall: cabextract not found, skipping winetricks packages. "
"Run: brew install cabextract")
return
self.status.emit("Installing base packages…")
results = install_winetricks_packages(wine_bin, prefix_dir, ["corefonts"])
for pkg, code in results.items():
if code == 0:
logger.info("autoinstall: %s installed successfully", pkg)
else:
logger.warning("autoinstall: %s failed (code %d)", pkg, code)
+563
View File
@@ -0,0 +1,563 @@
"""macOS Wine tools — direct invocation of wine utilities and winetricks."""
import os
import re
import shutil
import subprocess
import sys
import urllib.request
from portprotonqt.config import get_macos_wine_dir
from portprotonqt.logger import get_logger
from portprotonqt.macos_wine_runner import build_wine_env
logger = get_logger(__name__)
WINETRICKS_URL = (
"https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks"
)
# Maps start.sh CLI arg → wine sub-command args
WINE_TOOL_ARGS: dict[str, list[str]] = {
"--winecfg": ["winecfg"],
"--winereg": ["regedit"],
"--winefile": ["explorer", "/"],
"--winecmd": ["start", "cmd"],
"--wine_uninstaller": ["uninstaller"],
}
# Maps start.sh CLI arg → exe name to watch in psutil
WINE_TOOL_EXE: dict[str, str] = {
"--winecfg": "winecfg.exe",
"--winereg": "regedit.exe",
"--winefile": "explorer.exe",
"--winecmd": "cmd.exe",
"--wine_uninstaller": "uninstaller.exe",
}
def get_wine_binary_for_version(version_name: str) -> str | None:
"""Return wine binary path for a specific named version from macOS wine dir."""
wine_dir = get_macos_wine_dir()
base = os.path.join(wine_dir, version_name)
if not os.path.isdir(base):
return None
for rel in (
os.path.join("Contents", "Resources", "wine", "bin", "wine64"),
os.path.join("Contents", "Resources", "wine", "bin", "wine"),
os.path.join("bin", "wine64"),
os.path.join("bin", "wine"),
):
path = os.path.join(base, rel)
if os.path.isfile(path) and os.access(path, os.X_OK):
logger.debug("macos_wine_tools: found binary %s", path)
return path
return None
def get_wineserver_for_binary(wine_bin: str) -> str | None:
"""Return wineserver path adjacent to a given wine binary."""
candidate = os.path.join(os.path.dirname(wine_bin), "wineserver")
return candidate if os.path.isfile(candidate) and os.access(candidate, os.X_OK) else None
def get_macos_prefixes_dir() -> str:
"""Return WINEPREFIX base directory on macOS (XDG-compliant)."""
xdg = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
return os.path.join(xdg, "PortProtonQt", "prefixes")
def get_prefix_path(portproton_location: str | None, prefix_name: str) -> str:
"""Return full WINEPREFIX path, using macOS-specific dir on Darwin."""
if sys.platform == "darwin":
return os.path.join(get_macos_prefixes_dir(), prefix_name)
if portproton_location:
return os.path.join(portproton_location, "data", "prefixes", prefix_name)
return os.path.join(get_macos_prefixes_dir(), prefix_name)
def _build_tool_env(wine_bin: str, wineprefix: str) -> dict[str, str]:
env = build_wine_env(wine_bin)
env["WINEPREFIX"] = wineprefix
env["WINE"] = wine_bin
env["WINE64"] = wine_bin
wineserver = get_wineserver_for_binary(wine_bin)
if wineserver:
env["WINESERVER"] = wineserver
return env
def run_wine_tool_detached(
wine_bin: str, wineprefix: str, tool_args: list[str]
) -> subprocess.Popen:
"""Launch a wine utility non-blocking. Returns Popen for monitoring."""
os.makedirs(wineprefix, exist_ok=True)
env = _build_tool_env(wine_bin, wineprefix)
logger.info("macos tool: %s %s (prefix=%s)", wine_bin, tool_args, wineprefix)
return subprocess.Popen([wine_bin] + tool_args, env=env)
def get_winetricks_path(cache_dir: str | None = None) -> str:
"""Return local winetricks path, downloading if not present."""
if cache_dir:
dest_dir = cache_dir
else:
dest_dir = os.path.join(
os.getenv("XDG_CACHE_HOME", os.path.expanduser("~/.cache")),
"PortProtonQt",
)
os.makedirs(dest_dir, exist_ok=True)
path = os.path.join(dest_dir, "winetricks")
if not os.path.isfile(path):
logger.info("Downloading winetricks from %s", WINETRICKS_URL)
urllib.request.urlretrieve(WINETRICKS_URL, path)
os.chmod(path, 0o755)
return path
def run_winetricks_detached(
wine_bin: str, wineprefix: str, cache_dir: str | None = None
) -> subprocess.Popen:
"""Launch winetricks GUI non-blocking. Returns Popen for monitoring."""
winetricks = get_winetricks_path(cache_dir)
env = _build_tool_env(wine_bin, wineprefix)
# HeroicGamesLauncher macOS pattern: prepend homebrew/macports to PATH
bin_dir = os.path.dirname(wine_bin)
homebrew = "/opt/homebrew/bin" if os.path.isdir("/opt/homebrew/bin") else ""
env["PATH"] = ":".join(p for p in ["/opt/local/bin", homebrew, bin_dir, env.get("PATH", "")] if p)
logger.info("winetricks GUI (prefix=%s)", wineprefix)
return subprocess.Popen([winetricks, "--gui"], env=env)
def run_wineboot_init(wine_bin: str, wineprefix: str) -> int:
"""Run wineboot --init to recreate/reset a prefix. Returns exit code."""
os.makedirs(wineprefix, exist_ok=True)
env = _build_tool_env(wine_bin, wineprefix)
logger.info("wineboot --init (prefix=%s)", wineprefix)
result = subprocess.run([wine_bin, "wineboot", "--init"], env=env, timeout=120)
return result.returncode
def backup_prefix(prefix_path: str, backup_dir: str, prefix_name: str) -> str:
"""Zip a WINEPREFIX to backup_dir. Returns path to created archive."""
os.makedirs(backup_dir, exist_ok=True)
archive_base = os.path.join(backup_dir, f"{prefix_name}.ppack")
logger.info("Backing up prefix %s → %s", prefix_path, archive_base)
shutil.make_archive(
base_name=os.path.join(backup_dir, prefix_name),
format="zip",
root_dir=os.path.dirname(prefix_path),
base_dir=os.path.basename(prefix_path),
)
# Rename .zip to .ppack for compatibility
zip_path = os.path.join(backup_dir, prefix_name + ".zip")
if os.path.isfile(zip_path):
os.rename(zip_path, archive_base)
return archive_base
def restore_prefix(archive_path: str, prefixes_dir: str) -> str:
"""Extract a .ppack/.zip archive into prefixes_dir. Returns prefix path."""
os.makedirs(prefixes_dir, exist_ok=True)
logger.info("Restoring prefix from %s → %s", archive_path, prefixes_dir)
shutil.unpack_archive(archive_path, prefixes_dir, format="zip")
stem = re.sub(r"\.(ppack|zip)$", "", os.path.basename(archive_path), flags=re.IGNORECASE)
return os.path.join(prefixes_dir, stem)
def fix_wineserver_rpath(wine_bin: str) -> bool:
"""Add Sikarugir Frameworks RPATH to wineserver so libinotify.0.dylib is found.
wswine.bundle binaries depend on @rpath/libinotify.0.dylib but ship without
LC_RPATH entries. This fixes it by pointing RPATH at Sikarugir's bundle.
Returns True if fix was applied or already present.
"""
wineserver = os.path.join(os.path.dirname(wine_bin), "wineserver")
if not os.path.isfile(wineserver):
return False
# Check if RPATH already points to a libinotify location
check = subprocess.run(
["otool", "-l", wineserver], capture_output=True, text=True
)
if "libinotify" in check.stdout or "Frameworks" in check.stdout:
return True # already fixed
sika_fw = os.path.expanduser(
"~/Applications/Sikarugir/Battlenet.app/Contents/Frameworks"
)
if not os.path.isfile(os.path.join(sika_fw, "libinotify.0.dylib")):
logger.warning("fix_wineserver_rpath: libinotify not found at %s", sika_fw)
return False
result = subprocess.run(
["install_name_tool", "-add_rpath", sika_fw, wineserver],
capture_output=True, text=True,
)
if result.returncode == 0:
logger.info("fix_wineserver_rpath: added RPATH %s to %s", sika_fw, wineserver)
return True
logger.warning("fix_wineserver_rpath failed: %s", result.stderr)
return False
def detect_anticheat(prefix_path: str) -> list[str]:
"""Detect anti-cheat software installed in a Wine prefix.
Returns list of detected anti-cheat names, e.g. ['BattlEye', 'EAC'].
BattlEye and EAC require kernel-level access unavailable on macOS Wine.
"""
drive_c = os.path.join(prefix_path, "drive_c")
if not os.path.isdir(drive_c):
return []
detected = []
# BattlEye: BEService.exe anywhere in drive_c
for root, _dirs, files in os.walk(drive_c):
for fname in files:
lower = fname.lower()
if lower in ("beservice.exe", "beservice_x64.exe") and "BattlEye" not in detected:
detected.append("BattlEye")
if lower in ("easyanticheat.exe", "easyanticheat_x64.exe") and "EAC" not in detected:
detected.append("EAC")
if len(detected) >= 2:
break
return detected
def install_winetricks_packages(
wine_bin: str, wineprefix: str, packages: list[str], cache_dir: str | None = None
) -> dict[str, int]:
"""Install winetricks packages into a prefix. Returns {package: exit_code}.
Requires cabextract (brew install cabextract) for .cab archives (corefonts etc).
"""
winetricks = get_winetricks_path(cache_dir)
env = _build_tool_env(wine_bin, wineprefix)
# Ensure Homebrew tools (cabextract, curl, unzip) are in PATH
env["PATH"] = "/opt/homebrew/bin:/opt/local/bin:/usr/local/bin:" + env.get("PATH", "")
results: dict[str, int] = {}
for pkg in packages:
logger.info("winetricks: installing %s into %s", pkg, wineprefix)
r = subprocess.run([winetricks, "-q", pkg], env=env, timeout=300)
results[pkg] = r.returncode
if r.returncode != 0:
logger.warning("winetricks %s failed with code %d", pkg, r.returncode)
return results
def make_exec_line(wine_bin: str, wineprefix: str, exe_path: str) -> str:
"""Build the canonical exec_line string stored in the game library."""
return f'env WINEPREFIX="{wineprefix}" "{wine_bin}" "{exe_path}"'
def parse_exec_line(exec_line: str) -> dict[str, str]:
"""Parse a canonical exec_line back into its components.
Returns dict with keys: wineprefix, wine_bin, exe_path.
Empty strings for missing components.
"""
import shlex
try:
parts = shlex.split(exec_line)
except ValueError:
return {"wineprefix": "", "wine_bin": "", "exe_path": ""}
wineprefix = ""
wine_bin = ""
exe_path = ""
for p in parts:
if p.startswith("WINEPREFIX="):
wineprefix = p[len("WINEPREFIX="):]
elif not wine_bin and os.path.isfile(p) and p.endswith(("wine64", "wine")):
wine_bin = p
elif wine_bin and p.endswith(".exe"):
exe_path = p
break
return {"wineprefix": wineprefix, "wine_bin": wine_bin, "exe_path": exe_path}
# Known launchers: (relative path within drive_c, display name)
# Path is relative to drive_c, uses forward slashes, case-insensitive matched.
_KNOWN_LAUNCHER_PATHS: list[tuple[str, str]] = [
# Only launchers NOT covered by the autoinstall database (pw_autoinstall/)
("program files (x86)/epic games/launcher/portal/binaries/win32/epicgameslauncher.exe", "Epic Games Launcher"),
("program files (x86)/epic games/launcher/portal/binaries/win64/epicgameslauncher.exe", "Epic Games Launcher"),
("program files (x86)/gog galaxy/gogalaxy.exe", "GOG Galaxy"),
("program files (x86)/origin/origin.exe", "Origin"),
("program files (x86)/ea games/ea desktop/eadesktop.exe", "EA App"),
("program files (x86)/ubisoft/ubisoft game launcher/uplay.exe", "Ubisoft Connect"),
("program files (x86)/ubisoft game launcher/uplay.exe", "Ubisoft Connect"),
]
_PPDB_EXE_MAP: dict[str, str] | None = None # lazy: {exe_lower: display_name}
_AUTOINSTALL_PREFIX_MAP: dict[str, tuple[str, str, str]] | None = None # lazy: {prefix_name: (display, exe_pattern, cover_name)}
# System dirs to skip when scanning drive_c for exes
_SKIP_DRIVE_C_DIRS = frozenset({
"windows", "program files/common files", "program files (x86)/common files",
"program files/windows nt", "program files (x86)/windows nt",
"program files/windows media player", "program files (x86)/windows media player",
"program files/internet explorer", "program files (x86)/internet explorer",
})
def _get_autoinstall_cover(cover_name: str) -> str:
"""Return cover.png from autoinstall cache, trying multiple name variants."""
xdg = os.getenv("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
auto_root = os.path.join(xdg, "PortProtonQt", "custom_data", "autoinstall")
# Try exact name, lowercase, and without trailing qualifier (e.g. "Battle.net_Launcher" → "Battle.net")
candidates = [
cover_name,
cover_name.lower(),
cover_name.replace("_Launcher", "").replace("_launcher", ""),
cover_name.split("_")[0], # "Battle.net_Launcher" → "Battle.net"
]
for name in dict.fromkeys(candidates): # deduplicate preserving order
path = os.path.join(auto_root, name, "cover.png")
if os.path.isfile(path):
return path
return ""
def scan_wine_prefix_for_games(prefix_path: str) -> list[tuple[str, str, str]]:
"""Scan a WINEPREFIX for known launcher executables.
Returns list of (display_name, exe_path, cover_path) tuples.
cover_path is "" if no cover found.
"""
drive_c = os.path.join(prefix_path, "drive_c")
if not os.path.isdir(drive_c):
return []
found: list[tuple[str, str, str]] = []
seen: set[str] = set()
# 1. Autoinstall database — most accurate, includes cover path
prefix_name = os.path.basename(prefix_path.rstrip("/"))
auto_map = _get_autoinstall_prefix_map()
if prefix_name in auto_map:
display_name, exe_pattern, cover_name = auto_map[prefix_name]
if exe_pattern and display_name not in seen:
exe_path = _resolve_autoinstall_exe(exe_pattern, prefix_path)
if exe_path:
cover = _get_autoinstall_cover(cover_name)
found.append((display_name, exe_path, cover))
seen.add(display_name)
logger.debug("autoinstall db: found %s cover=%s", display_name, bool(cover))
# 2. Hardcoded launchers not in autoinstall db (Epic, GOG, Origin, etc.)
for rel_path, display_name in _KNOWN_LAUNCHER_PATHS:
if display_name in seen:
continue
candidate = os.path.join(drive_c, *rel_path.replace("/", os.sep).split(os.sep))
exe_path = ""
if os.path.isfile(candidate):
exe_path = candidate
else:
parts = rel_path.split("/")
resolved = _resolve_path_case_insensitive(drive_c, parts)
if resolved and os.path.isfile(resolved):
exe_path = resolved
if exe_path:
cover = _get_autoinstall_cover(display_name)
found.append((display_name, exe_path, cover))
seen.add(display_name)
logger.debug("scan_wine_prefix: found %s", display_name)
# 3. ppdb exe database — catches remaining known games
ppdb_map = _get_ppdb_exe_map()
if ppdb_map:
_scan_drive_c_with_ppdb(drive_c, ppdb_map, found, seen)
# 4. AppData/Local fallback: scan for installed launchers not in known paths
# (handles cases where installer replaces itself, e.g. VKPlayLoader→GameCenter)
if not found:
_scan_appdata_local(drive_c, found, seen)
return found
# Known AppData/Local launcher exe names and their display names
_APPDATA_LAUNCHER_EXES: dict[str, str] = {
"gamecenter.exe": "VK Play",
"vkplayloader.exe": "VK Play",
"epicgameslauncher.exe": "Epic Games Launcher",
"riotclientservices.exe": "Riot Client",
"leagueclient.exe": "League of Legends",
"valorant.exe": "Valorant",
}
def _scan_appdata_local(
drive_c: str, found: list[tuple[str, str, str]], seen: set[str]
) -> None:
"""Scan users/*/AppData/Local/ for known launcher executables."""
users_dir = os.path.join(drive_c, "users")
if not os.path.isdir(users_dir):
return
for username in os.listdir(users_dir):
appdata = _resolve_path_case_insensitive(
os.path.join(users_dir, username), ["AppData", "Local"]
) or ""
if not appdata:
continue
for entry in os.listdir(appdata):
entry_dir = os.path.join(appdata, entry)
if not os.path.isdir(entry_dir):
continue
for fname in os.listdir(entry_dir):
if not fname.lower().endswith(".exe"):
continue
display = _APPDATA_LAUNCHER_EXES.get(fname.lower())
if display and not any(s.lower() == display.lower() for s in seen):
exe_path = os.path.join(entry_dir, fname)
cover = _get_autoinstall_cover(display)
found.append((display, exe_path, cover))
seen.add(display)
logger.debug("appdata scan: found %s at %s", display, exe_path)
def _get_autoinstall_prefix_map() -> dict[str, tuple[str, str, str]]:
"""Build {PREFIX_NAME: (display_name, exe_path_pattern)} from pw_autoinstall scripts.
Uses the existing autoinstall database as ground truth — no hardcoding needed.
exe_path_pattern contains $USER and ${WINEPREFIX} that must be resolved at runtime.
"""
global _AUTOINSTALL_PREFIX_MAP
if _AUTOINSTALL_PREFIX_MAP is not None:
return _AUTOINSTALL_PREFIX_MAP
from portprotonqt.config import get_portproton_scripts_path
import re
scripts_path = get_portproton_scripts_path()
auto_dir = os.path.join(scripts_path, "pw_autoinstall") if scripts_path else ""
result: dict[str, tuple[str, str, str]] = {}
if not os.path.isdir(auto_dir):
_AUTOINSTALL_PREFIX_MAP = result
return result
for fname in os.listdir(auto_dir):
fpath = os.path.join(auto_dir, fname)
try:
content = open(fpath, encoding="utf-8", errors="ignore").read()
except OSError:
continue
prefix_m = re.search(r'PW_PREFIX_NAME\s*=\s*"?([^"\n]+)"?', content)
name_m = re.search(r'#\s*name\s*:\s*(.+)', content, re.IGNORECASE)
exe_m = re.search(r'PW_EXE_FILE\s*=\s*"([^"]+)"', content)
# pw_create_unique_exe gives cover folder name
unique_m = re.search(r'pw_create_unique_exe\s+"([^"]+)"', content)
if not prefix_m:
continue
prefix_name = prefix_m.group(1).strip()
display_name = name_m.group(1).strip() if name_m else prefix_name
exe_pattern = exe_m.group(1).strip() if exe_m else ""
# cover_name: pw_create_unique_exe arg OR exe basename without extension
if unique_m:
cover_name = unique_m.group(1).strip()
elif exe_pattern:
cover_name = os.path.splitext(os.path.basename(exe_pattern.replace("\\", "/")))[0]
cover_name = cover_name.replace("$USER", "").replace("${WINEPREFIX}", "").strip("/")
else:
cover_name = display_name
result[prefix_name] = (display_name, exe_pattern, cover_name)
logger.debug("autoinstall prefix map: %d entries", len(result))
_AUTOINSTALL_PREFIX_MAP = result
return result
def _resolve_autoinstall_exe(exe_pattern: str, prefix_path: str) -> str | None:
"""Resolve $USER/$WINEPREFIX in an exe pattern and return path if file exists.
Many scripts hardcode 'steamuser' or 'crossover' as username — we try
the real macOS username too since Wine uses the actual login name.
"""
import getpass
real_user = getpass.getuser()
# All plausible username values (real, script defaults)
usernames = [real_user, "steamuser", "crossover"]
for username in usernames:
path = (exe_pattern
.replace("${WINEPREFIX}", prefix_path)
.replace("$WINEPREFIX", prefix_path)
.replace("$USER", username)
# Also replace hardcoded 'steamuser' for scripts that don't use $USER
.replace("/steamuser/", f"/{username}/")
.replace("\\steamuser\\", f"\\{username}\\")
.replace("\\", "/"))
if os.path.isfile(path):
return path
try:
parts = os.path.relpath(path, prefix_path).split("/")
except ValueError:
continue
resolved = _resolve_path_case_insensitive(prefix_path, parts)
if resolved and os.path.isfile(resolved):
return resolved
return None
def _get_ppdb_exe_map() -> dict[str, str]:
"""Build and cache {exe_name_lower: display_name} map from portwine_db ppdb files."""
global _PPDB_EXE_MAP
if _PPDB_EXE_MAP is not None:
return _PPDB_EXE_MAP
from portprotonqt.config import get_portproton_scripts_path
import re
scripts_path = get_portproton_scripts_path()
ppdb_dir = os.path.join(scripts_path, "portwine_db") if scripts_path else ""
exe_map: dict[str, str] = {}
if not os.path.isdir(ppdb_dir):
_PPDB_EXE_MAP = exe_map
return exe_map
for fname in os.listdir(ppdb_dir):
if not fname.endswith(".ppdb"):
continue
display_name = fname[:-5]
try:
content = open(os.path.join(ppdb_dir, fname), encoding="utf-8", errors="ignore").read()
for m in re.finditer(r"^#([^#\n]+\.exe)", content, re.MULTILINE | re.IGNORECASE):
exe_map[m.group(1).strip().lower()] = display_name
except OSError:
pass
logger.debug("ppdb exe map: %d entries from %s", len(exe_map), ppdb_dir)
_PPDB_EXE_MAP = exe_map
return exe_map
def _scan_drive_c_with_ppdb(
drive_c: str, ppdb_map: dict[str, str],
found: list[tuple[str, str, str]], seen: set[str],
) -> None:
"""Walk drive_c (non-system dirs) and match exes against ppdb map."""
for top_dir in ("Program Files", "Program Files (x86)", "users"):
top_path = _resolve_path_case_insensitive(drive_c, [top_dir]) or ""
if not top_path:
continue
for root, dirs, files in os.walk(top_path):
# Skip known system subdirs
rel = os.path.relpath(root, drive_c).lower()
if any(rel.startswith(s) for s in _SKIP_DRIVE_C_DIRS):
dirs.clear()
continue
for fname in files:
if not fname.lower().endswith(".exe"):
continue
exe_lower = fname.lower()
if exe_lower in ppdb_map:
display = ppdb_map[exe_lower]
# Skip if already found (case-insensitive check)
if any(s.lower() == display.lower() for s in seen):
continue
cover = _get_autoinstall_cover(display)
found.append((display, os.path.join(root, fname), cover))
seen.add(display)
logger.debug("ppdb scan: found %s at %s", display, os.path.join(root, fname))
def _resolve_path_case_insensitive(base: str, parts: list[str]) -> str | None:
"""Walk path components case-insensitively. Returns full path or None."""
current = base
for part in parts:
if not os.path.isdir(current):
return None
entries = {e.lower(): e for e in os.listdir(current)}
match = entries.get(part.lower())
if not match:
return None
current = os.path.join(current, match)
return current if os.path.exists(current) else None
+393 -20
View File
@@ -3,6 +3,7 @@ import signal
import shlex
import shutil
import subprocess
import sys
import psutil
import re
from portprotonqt.logger import get_logger
@@ -230,6 +231,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.install_process = None
self.install_stop_process = None
self.install_monitor_timer = None
self.macos_install_thread = None
self.install_stop_requested = False
self.current_install_script = None
self.current_install_button = None
@@ -438,6 +440,9 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self._set_install_button_progress_text(_("Installing..."))
self.seen_progress = False
self.current_percent = 0.0
if sys.platform == "darwin":
self._launch_autoinstall_macos(script_name)
return
start_sh = self.start_sh
if not start_sh:
self._reset_install_state()
@@ -456,6 +461,102 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.install_monitor_timer.timeout.connect(self.monitor_install_progress)
self.install_monitor_timer.start(2000) # Start monitoring after 2s
def _launch_autoinstall_macos(self, script_name: str) -> None:
"""Launch autoinstall via Wine on macOS (replaces bash-based start.sh flow)."""
from portprotonqt.config import get_portproton_scripts_path
from portprotonqt.macos_wine_runner import MacOSAutoInstallThread
scripts_path = get_portproton_scripts_path()
if not scripts_path:
self._reset_install_state()
QMessageBox.warning(self, _("Error"), _("Could not find autoinstall scripts."))
return
script_path = os.path.join(scripts_path, "pw_autoinstall", script_name)
if not os.path.isfile(script_path):
self._reset_install_state()
QMessageBox.warning(self, _("Error"), f"Script not found: {script_name}")
return
thread = MacOSAutoInstallThread(script_path)
thread.status.connect(lambda msg: self._set_install_button_progress_text(msg))
thread.finished_ok.connect(self._on_macos_install_ok)
thread.finished_err.connect(self._on_macos_install_err)
self.macos_install_thread = thread
thread.start()
def _on_macos_install_ok(self, result_path: str) -> None:
"""Handle successful macOS autoinstall — offer to add exe to library."""
logger.info("macOS autoinstall completed: %s", result_path)
self._reset_install_state()
is_exe = result_path.lower().endswith(".exe") and os.path.isfile(result_path)
if is_exe:
msg = QMessageBox(self)
msg.setWindowTitle(_("Installation complete"))
msg.setText(_("Installation complete.\n\nAdd to library?\n{}").format(result_path))
msg.setStandardButtons(
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
)
msg.setDefaultButton(QMessageBox.StandardButton.Yes)
if msg.exec() == QMessageBox.StandardButton.Yes:
self._add_macos_wine_game(result_path)
else:
QMessageBox.information(self, _("Done"), _("Installation complete."))
def _add_macos_wine_game(self, exe_path: str) -> None:
"""Add a macOS Wine game exe to the library."""
from portprotonqt.macos_wine_tools import get_wine_binary_for_version
from portprotonqt.macos_wine_runner import find_wine_binary
game_name = os.path.splitext(os.path.basename(exe_path))[0]
wine_version = getattr(getattr(self, "wineCombo", None), "currentText", lambda: "")()
wine_bin = get_wine_binary_for_version(wine_version) if wine_version else find_wine_binary() or "wine"
prefix_dir = os.path.dirname(os.path.dirname(exe_path))
exec_line = f'env WINEPREFIX="{prefix_dir}" "{wine_bin}" "{exe_path}"'
logger.info("Adding macOS wine game: name=%s exec=%s", game_name, exec_line)
game_data = self._make_wine_game_data(game_name, exec_line)
self.game_library_manager.add_game_incremental(game_data)
def _make_wine_game_data(self, name: str, exec_line: str, cover_path: str = "") -> tuple:
"""Build a full game_data tuple for a macOS Wine game."""
# (name, description, cover_path, appid, controller_support,
# exec_line, last_launch, formatted_playtime, protondb_tier,
# anticheat_status, last_launch_ts, playtime_seconds, game_source)
return (name, "", cover_path, "", "", exec_line, "", "", "", "", 0, 0, "portproton")
def _scan_macos_wine_prefixes(self) -> list[tuple]:
"""Scan macOS Wine prefixes for installed games and return game_data tuples."""
from portprotonqt.macos_wine_tools import (
get_macos_prefixes_dir, get_wine_binary_for_version, scan_wine_prefix_for_games,
)
from portprotonqt.macos_wine_runner import find_wine_binary
# Prefer the wine version the user selected in Wine Settings
wine_bin = ""
wine_combo = getattr(self, "wineCombo", None)
if wine_combo:
selected = wine_combo.currentText()
wine_bin = get_wine_binary_for_version(selected) or ""
if wine_bin:
logger.info("scan_macos_prefixes: using selected wine %s", selected)
if not wine_bin:
wine_bin = find_wine_binary() or "wine"
logger.info("scan_macos_prefixes: fallback wine %s", wine_bin)
prefixes_dir = get_macos_prefixes_dir()
if not os.path.isdir(prefixes_dir):
return []
games: list[tuple] = []
for prefix_name in os.listdir(prefixes_dir):
prefix_path = os.path.join(prefixes_dir, prefix_name)
for display_name, exe_path, cover_path in scan_wine_prefix_for_games(prefix_path):
exec_line = f'env WINEPREFIX="{prefix_path}" "{wine_bin}" "{exe_path}"'
logger.info("Found macOS wine game: %s → %s", display_name, exe_path)
games.append(self._make_wine_game_data(display_name, exec_line, cover_path))
return games
def _on_macos_install_err(self, error: str) -> None:
logger.error("macOS autoinstall failed: %s", error)
self._reset_install_state()
QMessageBox.warning(self, _("Error"), error)
def _set_install_button_stop(self, button: AutoSizeButton | None = None) -> None:
"""Switch the active auto-install button to stop action."""
self.current_install_button = button
@@ -844,6 +945,8 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
def _load_portproton_games_async(self, callback: Callable[[list[tuple]], None]):
games = []
if sys.platform == "darwin":
games.extend(self._scan_macos_wine_prefixes())
if not self.portproton_location:
callback(games)
return
@@ -1692,9 +1795,17 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
formLayout.setLabelAlignment(Qt.AlignmentFlag.AlignLeft)
self.wine_versions = sorted([d for d in os.listdir(dist_path) if os.path.isdir(os.path.join(dist_path, d))], key=version_sort_key)
for version in self._get_lg_versions_from_var():
if version not in self.wine_versions:
self.wine_versions.append(version)
if sys.platform != "darwin": # LG versions are Linux-only (linux-gaming.ru)
for version in self._get_lg_versions_from_var():
if version not in self.wine_versions:
self.wine_versions.append(version)
if sys.platform == "darwin":
from portprotonqt.config import get_macos_wine_dir
macos_wine_dir = get_macos_wine_dir()
if os.path.isdir(macos_wine_dir):
for entry in os.listdir(macos_wine_dir):
if os.path.isdir(os.path.join(macos_wine_dir, entry)) and entry not in self.wine_versions:
self.wine_versions.append(entry)
self.wine_versions.sort(key=version_sort_key)
self.wineCombo = QComboBox()
self.wineCombo.view().window().setWindowFlags(
@@ -1714,7 +1825,21 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.wineCombo.setCurrentIndex(0)
formLayout.addRow(self.wineTitleLabel, self.wineCombo)
self.prefixes = sorted([d for d in os.listdir(prefixes_path) if os.path.isdir(os.path.join(prefixes_path, d))], key=prefix_sort_key) if os.path.exists(prefixes_path) else []
prefix_dirs = [prefixes_path]
if sys.platform == "darwin":
from portprotonqt.macos_wine_tools import get_macos_prefixes_dir
macos_pfx = get_macos_prefixes_dir()
if macos_pfx not in prefix_dirs:
prefix_dirs.append(macos_pfx)
seen_prefixes: set[str] = set()
raw_prefixes: list[str] = []
for pfx_dir in prefix_dirs:
if os.path.isdir(pfx_dir):
for d in os.listdir(pfx_dir):
if d not in seen_prefixes and os.path.isdir(os.path.join(pfx_dir, d)):
seen_prefixes.add(d)
raw_prefixes.append(d)
self.prefixes = sorted(raw_prefixes, key=prefix_sort_key)
self.prefixCombo = QComboBox()
self.prefixCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
@@ -1816,6 +1941,11 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
raw_prefix = self.prefixCombo.currentText().strip()
prefix = re.sub(r"[ \t]", "_", raw_prefix).upper() if raw_prefix else ""
if not wine or not prefix:
logger.warning("launch_generic_tool: wine=%r prefix=%r — skipping", wine, prefix)
return
logger.info("launch_generic_tool: cli_arg=%s wine=%s prefix=%s platform=%s", cli_arg, wine, prefix, sys.platform)
if sys.platform == "darwin":
self._launch_wine_tool_macos(cli_arg, wine, prefix)
return
if not self.portproton_location or not self.start_sh:
return
@@ -1845,6 +1975,31 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self._start_wine_process_monitor(cli_arg)
def _launch_wine_tool_macos(self, cli_arg: str, wine_version: str, prefix_name: str) -> None:
"""macOS: run wine tool directly without start.sh."""
from portprotonqt.macos_wine_tools import (
get_wine_binary_for_version, get_prefix_path, run_wine_tool_detached, WINE_TOOL_ARGS,
)
wine_bin = get_wine_binary_for_version(wine_version)
if not wine_bin:
logger.error("macos tool: no wine binary for %s", wine_version)
QMessageBox.warning(self, _("Error"), _("Wine binary not found for: ") + wine_version)
return
tool_args = WINE_TOOL_ARGS.get(cli_arg)
if not tool_args:
logger.warning("macos tool: unknown cli_arg %s", cli_arg)
return
prefix_path = get_prefix_path(self.portproton_location, prefix_name)
logger.info("macos tool: %s → wine %s prefix=%s", cli_arg, tool_args, prefix_path)
self.wine_progress_bar.setVisible(True)
try:
self._macos_wine_proc = run_wine_tool_detached(wine_bin, prefix_path, tool_args)
self._start_wine_process_monitor(cli_arg)
except Exception as e:
logger.error("macos tool launch failed: %s", e)
self.wine_progress_bar.setVisible(False)
QMessageBox.warning(self, _("Error"), str(e))
def _start_wine_process_monitor(self, cli_arg):
"""Start timer for Wine utility launch monitoring."""
self.wine_monitor_timer = QTimer(self)
@@ -1912,7 +2067,8 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
if not selected_prefix or not selected_wine:
return
if not self.portproton_location or not self.start_sh:
logger.info("clear_prefix: wine=%s prefix=%s", selected_wine, selected_prefix)
if sys.platform != "darwin" and not (self.portproton_location and self.start_sh):
return
msg_box = QMessageBox(self)
@@ -1927,6 +2083,10 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
if reply != QMessageBox.StandardButton.Yes:
return
if sys.platform == "darwin":
self._clear_prefix_macos(selected_wine, selected_prefix)
return
start_sh = self.start_sh
self.wine_progress_bar.setVisible(True)
@@ -1942,6 +2102,32 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
QMessageBox.warning(self, _("Error"), _("Failed to start prefix clear process."))
return
def _clear_prefix_macos(self, wine_version: str, prefix_name: str) -> None:
from portprotonqt.macos_wine_tools import (
get_wine_binary_for_version, get_prefix_path, run_wineboot_init,
)
import shutil as _shutil
wine_bin = get_wine_binary_for_version(wine_version)
if not wine_bin:
QMessageBox.warning(self, _("Error"), _("Wine binary not found for: ") + wine_version)
return
prefix_path = get_prefix_path(self.portproton_location, prefix_name)
logger.info("clear prefix macos: removing %s", prefix_path)
if os.path.isdir(prefix_path):
_shutil.rmtree(prefix_path)
self.wine_progress_bar.setVisible(True)
try:
code = run_wineboot_init(wine_bin, prefix_path)
self.wine_progress_bar.setVisible(False)
if code == 0:
QMessageBox.information(self, _("Success"), _("Prefix cleared successfully."))
else:
QMessageBox.warning(self, _("Error"), f"wineboot exited with code {code}")
except Exception as e:
self.wine_progress_bar.setVisible(False)
logger.error("clear prefix macos failed: %s", e)
QMessageBox.warning(self, _("Error"), str(e))
def _on_clear_prefix_finished(self, exitCode):
self.wine_progress_bar.setVisible(False)
if exitCode == 0:
@@ -1963,6 +2149,18 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
def _perform_backup(self, backup_dir, prefix_name):
os.makedirs(backup_dir, exist_ok=True)
logger.info("_perform_backup: prefix=%s dir=%s", prefix_name, backup_dir)
if sys.platform == "darwin":
from portprotonqt.macos_wine_tools import get_prefix_path, backup_prefix
prefix_path = get_prefix_path(self.portproton_location, prefix_name)
try:
archive = backup_prefix(prefix_path, backup_dir, prefix_name)
logger.info("backup created: %s", archive)
QMessageBox.information(self, _("Success"), _("Prefix backup completed."))
except Exception as e:
logger.error("backup failed: %s", e)
QMessageBox.warning(self, _("Error"), str(e))
return
if not self.portproton_location or not self.start_sh:
return
start_sh = self.start_sh
@@ -1981,6 +2179,17 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
def _perform_restore(self, file_path):
if not file_path or not os.path.exists(file_path):
return
logger.info("_perform_restore: %s", file_path)
if sys.platform == "darwin":
from portprotonqt.macos_wine_tools import get_macos_prefixes_dir, restore_prefix
try:
prefix_path = restore_prefix(file_path, get_macos_prefixes_dir())
logger.info("restore complete: %s", prefix_path)
QMessageBox.information(self, _("Success"), _("Prefix restore completed."))
except Exception as e:
logger.error("restore failed: %s", e)
QMessageBox.warning(self, _("Error"), str(e))
return
if not self.portproton_location or not self.start_sh:
return
start_sh = self.start_sh
@@ -2005,14 +2214,18 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
def delete_prefix(self):
selected_prefix = self.prefixCombo.currentText().strip()
if not self.portproton_location:
return
if not selected_prefix:
return
prefix_path = os.path.join(self.portproton_location, "data", "prefixes", selected_prefix)
logger.info("delete_prefix: prefix=%s", selected_prefix)
if sys.platform == "darwin":
from portprotonqt.macos_wine_tools import get_prefix_path
prefix_path = get_prefix_path(self.portproton_location, selected_prefix)
else:
if not self.portproton_location:
return
prefix_path = os.path.join(self.portproton_location, "data", "prefixes", selected_prefix)
if not os.path.exists(prefix_path):
logger.warning("delete_prefix: path does not exist: %s", prefix_path)
return
msg_box = QMessageBox(self)
@@ -2043,9 +2256,17 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
# Update the wine versions list with sorting
self.wine_versions = sorted([d for d in os.listdir(dist_path) if os.path.isdir(os.path.join(dist_path, d))], key=version_sort_key)
for version in self._get_lg_versions_from_var():
if version not in self.wine_versions:
self.wine_versions.append(version)
if sys.platform != "darwin": # LG versions are Linux-only
for version in self._get_lg_versions_from_var():
if version not in self.wine_versions:
self.wine_versions.append(version)
if sys.platform == "darwin":
from portprotonqt.config import get_macos_wine_dir
macos_wine_dir = get_macos_wine_dir()
if os.path.isdir(macos_wine_dir):
for entry in os.listdir(macos_wine_dir):
if os.path.isdir(os.path.join(macos_wine_dir, entry)) and entry not in self.wine_versions:
self.wine_versions.append(entry)
self.wine_versions.sort(key=version_sort_key)
self.wineCombo.clear()
self.wineCombo.addItems(self.wine_versions)
@@ -2102,19 +2323,39 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
selected_prefix = self.prefixCombo.currentText().strip()
if not selected_prefix:
return
selected_wine = self.wineCombo.currentText()
if not selected_wine:
return
logger.info("open_winetricks: wine=%s prefix=%s", selected_wine, selected_prefix)
if sys.platform == "darwin":
self._open_winetricks_macos(selected_wine, selected_prefix)
return
assert self.portproton_location is not None
prefix_path = os.path.join(self.portproton_location, "data", "prefixes", selected_prefix)
wine_path = os.path.join(self.portproton_location, "data", "dist", selected_wine, "bin", "wine")
# Open Winetricks dialog
dialog = WinetricksDialog(self, self.theme, prefix_path, wine_path)
dialog.exec()
def _open_winetricks_macos(self, wine_version: str, prefix_name: str) -> None:
"""Open WinetricksDialog (Qt UI) for macOS — no zenity/kdialog needed."""
from portprotonqt.macos_wine_tools import get_wine_binary_for_version, get_prefix_path
from portprotonqt.macos_wine_runner import build_wine_env
wine_bin = get_wine_binary_for_version(wine_version)
if not wine_bin:
logger.error("winetricks macos: no wine binary for %s", wine_version)
QMessageBox.warning(self, _("Error"), _("Wine binary not found for: ") + wine_version)
return
prefix_path = get_prefix_path(self.portproton_location, prefix_name)
# Inject DYLD_FALLBACK_LIBRARY_PATH so QProcess.systemEnvironment() picks it up
wine_env = build_wine_env(wine_bin)
os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = wine_env["DYLD_FALLBACK_LIBRARY_PATH"]
os.environ["WINEPREFIX"] = prefix_path
os.environ["WINE"] = wine_bin
os.environ["WINE64"] = wine_bin
logger.info("winetricks macos: wine=%s prefix=%s", wine_bin, prefix_path)
dialog = WinetricksDialog(self, self.theme, prefix_path, wine_bin)
dialog.exec()
def createPortProtonTab(self):
"""PortProton Settings tab."""
self.portProtonWidget = QWidget()
@@ -3508,6 +3749,8 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
def _check_missing_prefix_by_name_before_launch(self, prefix_name: str, env_vars: dict[str, str]) -> None:
"""Check prefix presence and optionally disable default recommended libs."""
if sys.platform == "darwin":
return # macOS uses its own prefix system, no PortProton prefix check needed
if not prefix_name or not self.portproton_location:
return
@@ -3549,6 +3792,128 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
return str(game[0])
return ""
def _build_macos_wine_launch_cmd(self, exec_line: str, exe_path: str) -> list[str] | None:
"""Build a direct wine launch command for macOS.
Handles both:
- 'env WINEPREFIX=... wine64 game.exe' (our stored format)
- Plain exe path (find wine + prefix automatically)
"""
from portprotonqt.macos_wine_tools import (
get_wine_binary_for_version, get_prefix_path,
)
from portprotonqt.macos_wine_runner import find_wine_binary, build_wine_env
parts = shlex.split(exec_line)
# Parse stored format: env WINEPREFIX=... wine_bin exe [args...]
wineprefix = ""
wine_bin = ""
extra_args: list[str] = []
if parts and parts[0] == "env":
for i, p in enumerate(parts[1:], 1):
if p.startswith("WINEPREFIX="):
wineprefix = p[len("WINEPREFIX="):]
elif not wine_bin and p.endswith(("wine64", "wine")) and os.path.isfile(p):
wine_bin = p
elif wine_bin and p == exe_path:
extra_args = parts[i + 1:]
break
else:
wine_bin = find_wine_binary() or ""
# Always prefer the best available wine over what's stored in exec_line
# (exec_line wine path can be stale if user installed a better wine later)
best_wine = find_wine_binary() or ""
if best_wine and wine_bin:
from portprotonqt.macos_wine_runner import _wine_version_priority
from portprotonqt.config import get_macos_wine_dir
wine_dir = get_macos_wine_dir()
stored_name = os.path.basename(os.path.dirname(os.path.dirname(wine_bin)))
best_name = os.path.basename(os.path.dirname(os.path.dirname(best_wine)))
stored_p = _wine_version_priority(stored_name, os.path.join(wine_dir, stored_name))
best_p = _wine_version_priority(best_name, os.path.join(wine_dir, best_name))
if best_p < stored_p:
logger.info("macOS launch: upgrading wine %s (p=%d) → %s (p=%d)",
stored_name, stored_p, best_name, best_p)
wine_bin = best_wine
if not wine_bin or not os.path.isfile(wine_bin):
wine_version = getattr(self, "wineCombo", None)
wine_version_name = wine_version.currentText() if wine_version else ""
wine_bin = get_wine_binary_for_version(wine_version_name) or best_wine or ""
if not wine_bin:
return None
if not wineprefix:
# Guess prefix from exe location: .../prefixes/NAME/drive_c/...
prefix_marker = os.sep + "drive_c" + os.sep
if prefix_marker in exe_path:
wineprefix = exe_path[:exe_path.index(prefix_marker)]
else:
wineprefix = get_prefix_path(self.portproton_location, "DEFAULT")
# Load per-game settings and apply them
from portprotonqt.macos_settings import (
load_game_settings, build_env_from_settings, get_launch_args,
)
game_settings = load_game_settings(exec_line)
# Respect per-game wine_version override (takes priority over auto-selection)
if game_settings.wine_version:
override_bin = get_wine_binary_for_version(game_settings.wine_version)
if override_bin:
logger.info("macOS launch: using per-game wine %s", game_settings.wine_version)
wine_bin = override_bin
# Steam-specific defaults: CEF sandbox + store wine in settings
if "steam.exe" in exe_path.lower():
if not game_settings.launch_args:
game_settings.launch_args = "-no-cef-sandbox -noreactlogin"
if not game_settings.wineprefix:
game_settings.wineprefix = wineprefix
# Anti-cheat check: warn if BattlEye/EAC detected in prefix
from portprotonqt.macos_wine_tools import detect_anticheat
_prefix_to_check = game_settings.wineprefix or wineprefix
if _prefix_to_check:
_ac = detect_anticheat(_prefix_to_check)
if _ac and "WINEDLLOVERRIDES" not in game_settings.env_vars:
logger.warning(
"macOS launch: %s detected in %s — "
"multiplayer unavailable on macOS. Adding beclient=n workaround.",
_ac, _prefix_to_check
)
game_settings.env_vars["WINEDLLOVERRIDES"] = "beclient,beclient_x64=n"
game_settings.wineprefix = game_settings.wineprefix or wineprefix
settings_args = get_launch_args(game_settings)
all_extra = extra_args + [a for a in settings_args if a not in extra_args]
env = build_wine_env(wine_bin)
env = build_env_from_settings(game_settings, env)
env["WINEPREFIX"] = game_settings.wineprefix or wineprefix
# Propagate critical vars so QProcess inherits them
os.environ["WINEPREFIX"] = env["WINEPREFIX"]
os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = env["DYLD_FALLBACK_LIBRARY_PATH"]
if "WINEMSYNC" in env:
os.environ["WINEMSYNC"] = env["WINEMSYNC"]
if "WINEDLLOVERRIDES" in env:
os.environ["WINEDLLOVERRIDES"] = env["WINEDLLOVERRIDES"]
if "MTL_HUD_ENABLED" in env:
os.environ["MTL_HUD_ENABLED"] = env["MTL_HUD_ENABLED"]
logger.info(
"macOS wine launch: %s %s (prefix=%s msync=%s dxmt=%s fps=%s)",
wine_bin, [exe_path] + all_extra,
env["WINEPREFIX"],
env.get("WINEMSYNC", "0"),
"1" if game_settings.dxmt else "0",
env.get("MTL_HUD_ENABLED", "0"),
)
return [wine_bin, exe_path] + all_extra
def toggleGame(self, exec_line, button=None, game_name=None):
# Handle Steam games
if exec_line.startswith("steam://"):
@@ -3582,9 +3947,17 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
QMessageBox.warning(self, _("Error"), _("PortProton start script not found"))
return
launch_cmd = self.start_sh + resolved_iso_parts
elif self.start_sh and file_to_check.lower().endswith(".exe"):
launch_file_parts = entry_exec_split if file_to_check == first_exec_part else [file_to_check]
launch_cmd = self.start_sh + launch_file_parts
elif file_to_check.lower().endswith(".exe"):
if sys.platform == "darwin":
# On macOS: exec_line may be a direct wine command (env WINEPREFIX=... wine exe)
# or just an exe path. Build the wine command directly.
launch_cmd = self._build_macos_wine_launch_cmd(exec_line, file_to_check)
if not launch_cmd:
QMessageBox.warning(self, _("Error"), _("No Wine binary found. Download Wine first."))
return
elif self.start_sh:
launch_file_parts = entry_exec_split if file_to_check == first_exec_part else [file_to_check]
launch_cmd = self.start_sh + launch_file_parts
if not os.path.exists(file_to_check):
QMessageBox.warning(self, _("Error"), _("File not found: {0}").format(file_to_check))
+4
View File
@@ -20,6 +20,9 @@ install_data(
'localization.py',
'logger.py',
'main_window.py',
'macos_settings.py',
'macos_wine_runner.py',
'macos_wine_tools.py',
'port_data_path_selector.py',
'portproton_api.py',
'preloader.py',
@@ -69,6 +72,7 @@ install_data(
'dialogs/wine_loader.py',
'dialogs/wine_downloader.py',
'dialogs/wine_extractor.py',
'dialogs/wine_macos_loader.py',
],
install_dir: pythondir / meson.project_name() / 'dialogs',
)
+2 -1
View File
@@ -24,7 +24,7 @@ classifiers = [
]
dependencies = [
"babel>=2.18.0",
"evdev>=1.9.3",
"evdev>=1.9.3; sys_platform == 'linux'",
"libarchive-c>=5.3",
"orjson>=3.11.8",
"pillow>=12.2.0",
@@ -55,6 +55,7 @@ dev = [
"pre-commit>=4.5.1",
"pyaspeller>=2.0.2",
"pyright>=1.1.408",
"pytest>=9.0.3",
]
[tool.ruff.lint]
+15
View File
@@ -0,0 +1,15 @@
"""Pytest configuration for PortProtonQt tests."""
import sys
import os
from pathlib import Path
# Ensure portprotonqt package is importable
project_root = Path(__file__).parent.parent
if str(project_root) not in sys.path:
sys.path.insert(0, str(project_root))
# Suppress pygame display output during tests
os.environ.setdefault("PYGAME_HIDE_SUPPORT_PROMPT", "1")
os.environ.setdefault("SDL_VIDEODRIVER", "dummy")
os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
View File
Whitespace-only changes.
+307
View File
@@ -0,0 +1,307 @@
"""Tests for ExeSettingsDialog macOS behaviour.
Covers:
- macOS settings rows added (MSYNC, FPS HUD, DXMT, Rosetta AVX)
- MangoHud/Gamescope tabs hidden on macOS
- apply_changes() saves to MacOSGameSettings, not start_sh
- Wine version change persists and is used at launch
- Prefix name change persists
Run:
uv run python -m pytest tests/test_exe_settings_macos.py -v --tb=short
"""
import json
import os
import sys
import pytest
pytestmark = pytest.mark.skipif(sys.platform != "darwin", reason="macOS only")
@pytest.fixture(scope="module")
def app():
from PySide6.QtWidgets import QApplication
return QApplication.instance() or QApplication([])
@pytest.fixture
def settings_dir(tmp_path, monkeypatch):
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
from importlib import reload
import portprotonqt.macos_settings as m
reload(m)
return tmp_path
# ── _apply_changes_macos logic ────────────────────────────────────────────────
class TestApplyChangesMacOS:
"""Tests for macOS apply_changes logic — no Qt widgets needed."""
def test_wine_version_saved_to_macos_settings(self, settings_dir):
"""Saving wine_version to MacOSGameSettings and loading it back."""
from portprotonqt.macos_settings import MacOSGameSettings, save_game_settings, load_game_settings
exe = "/some/prefix/drive_c/game.exe"
settings = MacOSGameSettings(wine_version="WS12WineSikarugir10.0-battle.net")
save_game_settings(exe, settings)
loaded = load_game_settings(exe)
assert loaded.wine_version == "WS12WineSikarugir10.0-battle.net"
def test_msync_saved(self, settings_dir):
from portprotonqt.macos_settings import MacOSGameSettings, save_game_settings, load_game_settings
exe = "/test/game.exe"
settings = MacOSGameSettings(msync=True, wine_version="WS12WineSikarugir10.0-battle.net")
save_game_settings(exe, settings)
loaded = load_game_settings(exe)
assert loaded.msync is True
assert loaded.wine_version == "WS12WineSikarugir10.0-battle.net"
def test_fps_hud_saved(self, settings_dir):
from portprotonqt.macos_settings import MacOSGameSettings, save_game_settings, load_game_settings
exe = "/test/game.exe"
settings = MacOSGameSettings(show_fps=True)
save_game_settings(exe, settings)
loaded = load_game_settings(exe)
assert loaded.show_fps is True
def test_dxmt_saved(self, settings_dir):
from portprotonqt.macos_settings import MacOSGameSettings, save_game_settings, load_game_settings
exe = "/test/game.exe"
settings = MacOSGameSettings(dxmt=True)
save_game_settings(exe, settings)
loaded = load_game_settings(exe)
assert loaded.dxmt is True
def test_prefix_saved_as_path(self, settings_dir):
from portprotonqt.macos_settings import MacOSGameSettings, save_game_settings, load_game_settings
from portprotonqt.macos_wine_tools import get_macos_prefixes_dir
exe = "/test/game.exe"
prefix_path = os.path.join(get_macos_prefixes_dir(), "BATTLE_NET")
settings = MacOSGameSettings(wineprefix=prefix_path)
save_game_settings(exe, settings)
loaded = load_game_settings(exe)
assert loaded.wineprefix == prefix_path
assert "BATTLE_NET" in loaded.wineprefix
def test_settings_roundtrip_wine_and_prefix(self, settings_dir):
"""Save wine+prefix, then load_macos_settings_into_current must return same values."""
from portprotonqt.macos_settings import MacOSGameSettings, save_game_settings, load_game_settings
from portprotonqt.macos_wine_tools import get_macos_prefixes_dir
exe = "/prefix/drive_c/battle.net.exe"
prefix_path = os.path.join(get_macos_prefixes_dir(), "BATTLE_NET")
settings = MacOSGameSettings(
wine_version="WS12WineSikarugir10.0-battle.net",
wineprefix=prefix_path,
msync=True,
show_fps=False,
)
save_game_settings(exe, settings)
loaded = load_game_settings(exe)
# Simulate _load_macos_settings_into_current
current_settings = {}
dist_options = []
prefix_options = []
if loaded.wine_version and loaded.wine_version not in dist_options:
dist_options.append(loaded.wine_version)
if loaded.wine_version:
current_settings["PW_WINE_USE"] = loaded.wine_version
if loaded.wineprefix:
prefix_name = os.path.basename(loaded.wineprefix.rstrip("/"))
if prefix_name not in prefix_options:
prefix_options.append(prefix_name)
current_settings["PW_PREFIX_NAME"] = prefix_name
assert current_settings.get("PW_WINE_USE") == "WS12WineSikarugir10.0-battle.net"
assert current_settings.get("PW_PREFIX_NAME") == "BATTLE_NET"
assert "WS12WineSikarugir10.0-battle.net" in dist_options
assert "BATTLE_NET" in prefix_options
def test_different_games_get_different_settings(self, settings_dir):
from portprotonqt.macos_settings import MacOSGameSettings, save_game_settings, load_game_settings
exe1 = "/prefix/battle.net.exe"
exe2 = "/prefix/steam.exe"
save_game_settings(exe1, MacOSGameSettings(wine_version="WS12WineSikarugir10.0-battle.net", dxmt=False))
save_game_settings(exe2, MacOSGameSettings(wine_version="WS12WineCX24.0.7_7", dxmt=True))
s1 = load_game_settings(exe1)
s2 = load_game_settings(exe2)
assert s1.wine_version != s2.wine_version
assert s1.dxmt is False
assert s2.dxmt is True
# ── UI structure tests ────────────────────────────────────────────────────────
class TestSettingsDialogUIMacOS:
def test_mangohud_tab_not_added_on_macos(self, app):
"""MangoHud tab must NOT appear on macOS."""
source_path = os.path.join(
os.path.dirname(__file__), "..", "portprotonqt", "dialogs", "settings_dialog.py"
)
source = open(source_path).read()
# Find the tab-adding section
start = source.find("addTab(self.main_tab")
end = source.find("self.settings_table", start)
tab_section = source[start:end]
# MangoHud tab must be inside a sys.platform != darwin check
assert "darwin" in tab_section, (
"MangoHud tab must be conditionally hidden on macOS"
)
assert "MangoHud" in tab_section
def test_macos_settings_rows_defined(self):
"""macOS-specific setting keys must be defined in _populate_macos_settings."""
source_path = os.path.join(
os.path.dirname(__file__), "..", "portprotonqt", "dialogs", "settings_dialog.py"
)
source = open(source_path).read()
start = source.find("def _populate_macos_settings")
end = source.find("\n def ", start + 1)
func = source[start:end]
required_keys = ["WINEMSYNC", "MTL_HUD_ENABLED", "DXMT", "ROSETTA_ADVERTISE_AVX"]
for key in required_keys:
assert key in func, f"macOS setting key {key} missing from _populate_macos_settings"
def test_apply_changes_macos_intercepts_on_darwin(self):
"""apply_changes must call _apply_changes_macos on darwin."""
source_path = os.path.join(
os.path.dirname(__file__), "..", "portprotonqt", "dialogs", "settings_dialog.py"
)
source = open(source_path).read()
start = source.find("def apply_changes(self):")
end = source.find("\n def ", start + 1)
func = source[start:end]
assert "_apply_changes_macos" in func, "apply_changes must call _apply_changes_macos on darwin"
assert 'sys.platform == "darwin"' in func
def test_apply_changes_macos_saves_wine_version(self):
"""_apply_changes_macos must save PW_WINE_USE to wine_version."""
source_path = os.path.join(
os.path.dirname(__file__), "..", "portprotonqt", "dialogs", "settings_dialog.py"
)
source = open(source_path).read()
start = source.find("def _apply_changes_macos")
end = source.find("\n def ", start + 1)
func = source[start:end]
assert "PW_WINE_USE" in func
assert "wine_version" in func
assert "save_game_settings" in func
def test_load_macos_settings_into_current_defined(self):
"""_load_macos_settings_into_current must exist and load wine_version."""
source_path = os.path.join(
os.path.dirname(__file__), "..", "portprotonqt", "dialogs", "settings_dialog.py"
)
source = open(source_path).read()
assert "_load_macos_settings_into_current" in source
start = source.find("def _load_macos_settings_into_current")
end = source.find("\n def ", start + 1)
func = source[start:end]
assert "load_game_settings" in func
assert "PW_WINE_USE" in func
assert "wine_version" in func
assert "PW_PREFIX_NAME" in func
def test_macos_prefixes_in_prefix_options(self):
"""macOS prefix dir must be scanned for prefix_options in settings dialog."""
source_path = os.path.join(
os.path.dirname(__file__), "..", "portprotonqt", "dialogs", "settings_dialog.py"
)
source = open(source_path).read()
# The macOS block must scan get_macos_prefixes_dir for prefix_options
assert "get_macos_prefixes_dir" in source
assert "prefix_options" in source
# Verify it actually finds prefixes
from portprotonqt.macos_wine_tools import get_macos_prefixes_dir
pfx_dir = get_macos_prefixes_dir()
if os.path.isdir(pfx_dir):
found = [f for f in os.listdir(pfx_dir) if os.path.isdir(os.path.join(pfx_dir, f))]
assert len(found) > 0, f"No prefixes found in {pfx_dir}"
def test_load_macos_called_in_on_show_ppdb_finished(self):
"""_load_macos_settings_into_current must be called during settings load."""
source_path = os.path.join(
os.path.dirname(__file__), "..", "portprotonqt", "dialogs", "settings_dialog.py"
)
source = open(source_path).read()
start = source.find("def on_show_ppdb_finished")
end = source.find("\n def ", start + 1)
func = source[start:end]
assert "_load_macos_settings_into_current" in func
assert 'sys.platform == "darwin"' in func
# ── Wine version → launch integration ─────────────────────────────────────────
class TestWineVersionPersistenceToLaunch:
def test_saved_wine_version_used_in_build_launch_cmd(self, settings_dir, tmp_path):
"""Wine version saved in settings must be used when building launch command."""
from portprotonqt.macos_settings import MacOSGameSettings, save_game_settings
from portprotonqt.macos_wine_tools import get_wine_binary_for_version
exe_path = str(tmp_path / "game.exe")
target_wine = "WS12WineSikarugir10.0-battle.net"
wine_bin = get_wine_binary_for_version(target_wine)
if not wine_bin:
pytest.skip(f"Wine version {target_wine} not installed")
exec_line = f'env WINEPREFIX="/p" "{wine_bin}" "{exe_path}"'
settings = MacOSGameSettings(wine_version=target_wine, wineprefix="/p", msync=True)
save_game_settings(exec_line, settings)
# Verify that load works and wine_version is correct
from portprotonqt.macos_settings import load_game_settings
loaded = load_game_settings(exec_line)
assert loaded.wine_version == target_wine
def test_sikarugir_wine_has_priority(self):
"""Sikarugir wine must have highest priority over Crossover/GPTK."""
from portprotonqt.macos_wine_runner import _wine_version_priority
sika_priority = _wine_version_priority("WS12WineSikarugir10.0-battle.net")
cx_priority = _wine_version_priority("Wine-Crossover-23.7.1-1")
gptk_priority = _wine_version_priority("Game Porting Toolkit.app")
assert sika_priority < cx_priority < gptk_priority
def test_all_installed_wines_in_dist_options(self):
"""All wine versions from macOS wine dir must appear in ExeSettingsDialog."""
from portprotonqt.config import get_macos_wine_dir
wine_dir = get_macos_wine_dir()
if not os.path.isdir(wine_dir):
pytest.skip("No wine dir")
installed = [
d for d in os.listdir(wine_dir)
if os.path.isdir(os.path.join(wine_dir, d)) and not d.startswith(".")
]
# Simulate what settings_dialog does for macOS dist_options
from portprotonqt.macos_wine_tools import get_wine_binary_for_version
found_with_binary = [v for v in installed if get_wine_binary_for_version(v)]
assert len(found_with_binary) > 0
def test_env_built_from_saved_settings(self):
"""env built for launch must include WINEMSYNC=1 when msync=True."""
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
from portprotonqt.macos_wine_runner import find_wine_binary, build_wine_env
wine = find_wine_binary()
if not wine:
pytest.skip("No wine")
base = build_wine_env(wine)
settings = MacOSGameSettings(msync=True, show_fps=True, dxmt=False)
env = build_env_from_settings(settings, base)
assert env.get("WINEMSYNC") == "1"
assert env.get("MTL_HUD_ENABLED") == "1"
def test_dxmt_env_when_enabled(self):
"""DXMT=True must produce correct WINEDLLOVERRIDES."""
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
from portprotonqt.macos_wine_runner import find_wine_binary, build_wine_env
wine = find_wine_binary()
if not wine:
pytest.skip("No wine")
base = build_wine_env(wine)
settings = MacOSGameSettings(dxmt=True)
env = build_env_from_settings(settings, base)
overrides = env.get("WINEDLLOVERRIDES", "")
assert "d3d11=n,b" in overrides
assert env.get("WINEMSYNC") == "1" # DXMT requires MSYNC
+304
View File
@@ -0,0 +1,304 @@
"""Tests for macOS game launch flow — direct function calls, no screenshots.
Covers:
- exec_line parsing
- wine command building
- settings applied to launch env
- library scan and game data
- prefix scanning correctness
Run:
uv run python -m pytest tests/test_macos_launch.py -v --tb=short
"""
import os
import shlex
import sys
from pathlib import Path
import pytest
# ── exec_line parsing ─────────────────────────────────────────────────────────
class TestExecLineParsing:
"""Tests for parsing the stored exec_line format back into components."""
EXEC_TEMPLATE = 'env WINEPREFIX="{prefix}" "{wine}" "{exe}"'
def _make_exec(self, prefix, wine, exe):
return self.EXEC_TEMPLATE.format(prefix=prefix, wine=wine, exe=exe)
def test_shlex_split_correct(self):
exec_line = self._make_exec("/p/prefix", "/wine/bin/wine64", "/p/prefix/drive_c/game.exe")
parts = shlex.split(exec_line)
assert parts[0] == "env"
assert "WINEPREFIX=/p/prefix" in parts
assert "/wine/bin/wine64" in parts
assert "/p/prefix/drive_c/game.exe" in parts
def test_wineprefix_extracted(self):
exec_line = self._make_exec("/my/prefix", "/wine64", "/game.exe")
parts = shlex.split(exec_line)
prefix = ""
for p in parts:
if p.startswith("WINEPREFIX="):
prefix = p[len("WINEPREFIX="):]
assert prefix == "/my/prefix"
def test_exe_path_ends_with_exe(self):
exec_line = self._make_exec("/p", "/w", "/p/drive_c/steam.exe")
parts = shlex.split(exec_line)
exe = [p for p in parts if p.endswith(".exe")]
assert len(exe) == 1
assert exe[0] == "/p/drive_c/steam.exe"
def test_wine_binary_identified(self):
exec_line = self._make_exec("/p", "/path/wine64", "/p/game.exe")
parts = shlex.split(exec_line)
wine = [p for p in parts if p.endswith(("wine64", "wine")) and "/" in p]
assert len(wine) == 1
assert wine[0] == "/path/wine64"
def test_exec_line_roundtrip_steam(self):
"""Steam exec_line stored and parsed correctly."""
from portprotonqt.macos_wine_runner import find_wine_binary
from portprotonqt.macos_wine_tools import make_exec_line, parse_exec_line
wine = find_wine_binary()
if not wine:
pytest.skip("No wine binary")
prefix = "/some/prefix"
exe = "/some/prefix/drive_c/steam.exe"
exec_line = make_exec_line(wine, prefix, exe)
parsed = parse_exec_line(exec_line)
assert parsed["wineprefix"] == prefix
assert parsed["wine_bin"] == wine
assert parsed["exe_path"] == exe
# ── wine command building ─────────────────────────────────────────────────────
class TestWineCommandBuilding:
"""Tests for building the final wine command with settings applied."""
@pytest.fixture
def wine_bin(self):
from portprotonqt.macos_wine_runner import find_wine_binary
w = find_wine_binary()
if not w:
pytest.skip("No wine binary")
return w
def test_basic_command_structure(self, wine_bin, tmp_path):
"""Command = [wine_bin, exe_path, ...args]"""
exe = str(tmp_path / "game.exe")
Path(exe).touch()
from portprotonqt.macos_settings import MacOSGameSettings, get_launch_args
settings = MacOSGameSettings()
cmd = [wine_bin, exe] + get_launch_args(settings)
assert cmd[0] == wine_bin
assert cmd[1] == exe
def test_steam_command_includes_no_cef_sandbox(self, wine_bin, tmp_path):
"""Steam must always get -no-cef-sandbox -noreactlogin."""
steam_exe = str(tmp_path / "steam.exe")
Path(steam_exe).touch()
from portprotonqt.macos_settings import MacOSGameSettings, get_launch_args
settings = MacOSGameSettings(launch_args="-no-cef-sandbox -noreactlogin")
extra = get_launch_args(settings)
assert "-no-cef-sandbox" in extra
assert "-noreactlogin" in extra
def test_env_has_wineprefix(self, wine_bin, tmp_path):
"""WINEPREFIX must be in the launch environment."""
from portprotonqt.macos_wine_runner import build_wine_env
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
prefix = str(tmp_path / "prefix")
os.makedirs(prefix)
base = build_wine_env(wine_bin)
env = build_env_from_settings(
MacOSGameSettings(wineprefix=prefix), base
)
assert env["WINEPREFIX"] == prefix
def test_env_has_dyld_fallback(self, wine_bin):
"""DYLD_FALLBACK_LIBRARY_PATH must be set for wine to find its libs."""
from portprotonqt.macos_wine_runner import build_wine_env
env = build_wine_env(wine_bin)
assert "DYLD_FALLBACK_LIBRARY_PATH" in env
dyld = env["DYLD_FALLBACK_LIBRARY_PATH"]
# Must contain wine lib dir
assert "lib" in dyld
def test_wine_sikarugir_or_crossover_preferred_over_gptk(self):
"""find_wine_binary should prefer Sikarugir/Crossover over GPTK."""
from portprotonqt.macos_wine_runner import find_wine_binary
wine = find_wine_binary()
if not wine:
pytest.skip("No wine")
from portprotonqt.config import get_macos_wine_dir
wine_dir = get_macos_wine_dir()
if not os.path.isdir(wine_dir):
pytest.skip("No wine dir")
versions = os.listdir(wine_dir)
has_gptk = any("game" in v.lower() and "porting" in v.lower() for v in versions)
has_better = any(
any(k in v.lower() for k in ("crossover", "wswine", "sikarugir", "staging", "whisky"))
for v in versions
)
if has_gptk and has_better:
assert "game porting" not in wine.lower() and "gptk" not in wine.lower(), (
f"GPTK should not be selected when better options exist, got: {wine}"
)
def test_dxmt_env_correct(self, wine_bin):
"""DXMT settings produce correct WINEDLLOVERRIDES."""
from portprotonqt.macos_wine_runner import build_wine_env
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
base = build_wine_env(wine_bin)
env = build_env_from_settings(MacOSGameSettings(dxmt=True), base)
overrides = env.get("WINEDLLOVERRIDES", "")
assert "d3d11=n,b" in overrides
assert "dxgi=n,b" in overrides
assert env.get("WINEMSYNC") == "1"
def test_no_dxmt_no_overrides(self, wine_bin):
"""Without DXMT, no d3d11 overrides should be set."""
from portprotonqt.macos_wine_runner import build_wine_env
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
base = build_wine_env(wine_bin)
env = build_env_from_settings(MacOSGameSettings(dxmt=False, dxvk=False), base)
overrides = env.get("WINEDLLOVERRIDES", "")
assert "d3d11=n,b" not in overrides
# ── Library scan correctness ──────────────────────────────────────────────────
class TestLibraryScan:
def test_scan_returns_list(self, tmp_path):
from portprotonqt.macos_wine_tools import scan_wine_prefix_for_games
results = scan_wine_prefix_for_games(str(tmp_path))
assert isinstance(results, list)
def test_scan_finds_steam(self, tmp_path):
"""Steam found via ppdb (steam.exe → 'steam' display name)."""
from portprotonqt.macos_wine_tools import scan_wine_prefix_for_games
steam_dir = tmp_path / "drive_c" / "Program Files (x86)" / "Steam"
steam_dir.mkdir(parents=True)
(steam_dir / "steam.exe").touch()
results = scan_wine_prefix_for_games(str(tmp_path))
names = [n for n, _, _ in results]
# ppdb uses lowercase 'steam' from steam.ppdb filename
assert any("steam" in n.lower() for n in names)
def test_scan_finds_battlenet_via_ppdb(self, tmp_path):
"""Battle.net.exe found via ppdb (Battle.net_Launcher.ppdb: #Battle.net.exe)."""
from portprotonqt.macos_wine_tools import scan_wine_prefix_for_games
bn_dir = tmp_path / "drive_c" / "Program Files (x86)" / "Battle.net"
bn_dir.mkdir(parents=True)
(bn_dir / "Battle.net.exe").touch()
results = scan_wine_prefix_for_games(str(tmp_path))
names = [n for n, _, _ in results]
assert any("battle" in n.lower() or "Battle" in n for n in names)
def test_scan_case_insensitive(self, tmp_path):
"""Scan works even when Wine creates different-case dirs."""
from portprotonqt.macos_wine_tools import scan_wine_prefix_for_games
# Wine-Crossover creates lowercase dirs on macOS
steam_dir = tmp_path / "drive_c" / "program files (x86)" / "steam"
steam_dir.mkdir(parents=True)
(steam_dir / "steam.exe").touch()
results = scan_wine_prefix_for_games(str(tmp_path))
names = [n for n, _, _ in results]
# ppdb resolves case-insensitively
assert any("steam" in n.lower() for n in names)
def test_scan_no_false_positives_for_system_exes(self, tmp_path):
"""Windows system exes should NOT be listed as games."""
from portprotonqt.macos_wine_tools import scan_wine_prefix_for_games
sys_dir = tmp_path / "drive_c" / "windows" / "system32"
sys_dir.mkdir(parents=True)
(sys_dir / "notepad.exe").touch()
(sys_dir / "cmd.exe").touch()
results = scan_wine_prefix_for_games(str(tmp_path))
names = [n for n, _, _ in results]
assert "notepad.exe" not in names
assert "cmd.exe" not in names
def test_game_data_tuple_correct_length(self):
"""_make_wine_game_data must produce 13-field tuple for GameCard."""
# Simulate what _make_wine_game_data returns
name = "Steam"
exec_line = 'env WINEPREFIX="/p" "wine64" "steam.exe"'
game_data = (name, "", "", "", "", exec_line, "", "", "", "", 0, 0, "portproton")
assert len(game_data) == 13, f"Expected 13 fields, got {len(game_data)}"
assert game_data[0] == name # name
assert game_data[5] == exec_line # exec_line at index 5
assert game_data[12] == "portproton" # game_source at index 12
@pytest.mark.skipif(sys.platform != "darwin", reason="macOS only")
def test_real_prefixes_scan(self):
"""Integration: scan actual installed prefixes and log findings."""
from portprotonqt.macos_wine_tools import get_macos_prefixes_dir, scan_wine_prefix_for_games
prefixes_dir = get_macos_prefixes_dir()
if not os.path.isdir(prefixes_dir):
pytest.skip("No prefixes dir")
all_found = {}
for prefix_name in os.listdir(prefixes_dir):
path = os.path.join(prefixes_dir, prefix_name)
if not os.path.isdir(path):
continue
games = scan_wine_prefix_for_games(path)
all_found[prefix_name] = [n for n, _, _ in games]
# Write report for debugging
report_path = Path("/tmp/ppqt_tests/prefix_scan_report.json")
report_path.parent.mkdir(exist_ok=True)
import json
report_path.write_text(json.dumps(all_found, indent=2))
# At least the prefixes we know about should have games
# Note: display names come from ppdb filenames (e.g. 'steam', 'Battle.net_Launcher')
known = {"DEFAULT": "steam", "BATTLE_NET": "Battle"}
for prefix, expected_substr in known.items():
if prefix in all_found:
assert any(expected_substr.lower() in n.lower() for n in all_found[prefix]), (
f"Expected '{expected_substr}' in {prefix}, found: {all_found[prefix]}"
)
# ── Wine process monitoring ───────────────────────────────────────────────────
class TestWineProcessMonitoring:
"""Tests for detecting when wine tool processes start/stop."""
def test_exe_map_complete(self):
"""Every tool CLI arg must have an exe to monitor."""
from portprotonqt.macos_wine_tools import WINE_TOOL_EXE, WINE_TOOL_ARGS
assert set(WINE_TOOL_EXE.keys()) == set(WINE_TOOL_ARGS.keys())
def test_winecfg_exe_name(self):
from portprotonqt.macos_wine_tools import WINE_TOOL_EXE
assert WINE_TOOL_EXE["--winecfg"] == "winecfg.exe"
def test_regedit_exe_name(self):
from portprotonqt.macos_wine_tools import WINE_TOOL_EXE
assert WINE_TOOL_EXE["--winereg"] == "regedit.exe"
@pytest.mark.skipif(sys.platform != "darwin", reason="macOS only")
def test_wine_version_detection(self):
"""Wine binary should report a version string."""
import subprocess
from portprotonqt.macos_wine_runner import find_wine_binary, build_wine_env
wine = find_wine_binary()
if not wine:
pytest.skip("No wine")
env = build_wine_env(wine)
result = subprocess.run(
[wine, "--version"],
capture_output=True, text=True, env=env, timeout=10
)
output = result.stdout + result.stderr
assert "wine" in output.lower(), f"Expected wine version, got: {output}"
+402
View File
@@ -0,0 +1,402 @@
"""Tests for macOS per-game settings — no screenshots, direct function calls.
Run:
uv run python -m pytest tests/test_macos_settings.py -v --tb=short
"""
import json
import os
import sys
import pytest
# ── MacOSGameSettings unit tests ─────────────────────────────────────────────
class TestMacOSGameSettings:
def test_defaults(self):
from portprotonqt.macos_settings import MacOSGameSettings
s = MacOSGameSettings()
assert s.msync is True
assert s.dxmt is False
assert s.d3dmetal is False
assert s.dxvk is False
assert s.show_fps is False
assert s.rosetta_avx is False
assert s.launch_args == ""
assert s.env_vars == {}
def test_save_and_load_roundtrip(self, tmp_path, monkeypatch):
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
from importlib import reload
import portprotonqt.macos_settings as m
reload(m)
exec_line = 'env WINEPREFIX="/tmp/p" "wine64" "game.exe"'
settings = m.MacOSGameSettings(
wine_version="Wine-Crossover-23.7.1-1",
dxmt=True,
show_fps=True,
rosetta_avx=False,
msync=True,
launch_args="-fullscreen",
)
assert m.save_game_settings(exec_line, settings)
loaded = m.load_game_settings(exec_line)
assert loaded.wine_version == "Wine-Crossover-23.7.1-1"
assert loaded.dxmt is True
assert loaded.show_fps is True
assert loaded.msync is True
assert loaded.launch_args == "-fullscreen"
def test_load_returns_defaults_when_missing(self, tmp_path, monkeypatch):
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
from importlib import reload
import portprotonqt.macos_settings as m
reload(m)
settings = m.load_game_settings("nonexistent_exec_line_12345")
assert isinstance(settings, m.MacOSGameSettings)
assert settings.dxmt is False
def test_load_handles_corrupt_file(self, tmp_path, monkeypatch):
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
from importlib import reload
import portprotonqt.macos_settings as m
reload(m)
exec_line = "test_exec"
path = m._settings_path(exec_line)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
f.write("NOT VALID JSON{{{")
settings = m.load_game_settings(exec_line)
assert isinstance(settings, m.MacOSGameSettings) # falls back to defaults
def test_different_exec_lines_get_different_files(self, tmp_path, monkeypatch):
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
from importlib import reload
import portprotonqt.macos_settings as m
reload(m)
path1 = m._settings_path("game_a.exe")
path2 = m._settings_path("game_b.exe")
assert path1 != path2
def test_settings_dir_created_on_save(self, tmp_path, monkeypatch):
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
from importlib import reload
import portprotonqt.macos_settings as m
reload(m)
m.save_game_settings("test.exe", m.MacOSGameSettings())
assert os.path.isdir(m.get_game_settings_dir())
# ── build_env_from_settings tests ────────────────────────────────────────────
class TestBuildEnvFromSettings:
def test_msync_enabled_by_default(self):
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
env = build_env_from_settings(MacOSGameSettings(), {})
assert env.get("WINEMSYNC") == "1"
def test_msync_disabled(self):
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
env = build_env_from_settings(MacOSGameSettings(msync=False), {})
assert "WINEMSYNC" not in env
def test_dxmt_sets_winedlloverrides(self):
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
env = build_env_from_settings(MacOSGameSettings(dxmt=True), {})
overrides = env.get("WINEDLLOVERRIDES", "")
assert "d3d11=n,b" in overrides
assert "dxgi=n,b" in overrides
assert env.get("WINEMSYNC") == "1" # DXMT requires MSYNC
def test_dxmt_preserves_existing_overrides(self):
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
base = {"WINEDLLOVERRIDES": "mscoree=d"}
env = build_env_from_settings(MacOSGameSettings(dxmt=True), base)
overrides = env.get("WINEDLLOVERRIDES", "")
assert "d3d11=n,b" in overrides
assert "mscoree=d" in overrides
def test_d3dmetal_sets_esync_and_msync(self):
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
env = build_env_from_settings(MacOSGameSettings(d3dmetal=True), {})
assert env.get("WINEESYNC") == "1"
assert env.get("WINEMSYNC") == "1"
def test_show_fps_sets_mtl_hud_on_macos(self, monkeypatch):
monkeypatch.setattr(sys, "platform", "darwin")
from importlib import reload
import portprotonqt.macos_settings as m
reload(m)
env = m.build_env_from_settings(m.MacOSGameSettings(show_fps=True), {})
assert env.get("MTL_HUD_ENABLED") == "1"
assert "DXVK_HUD" not in env
def test_show_fps_sets_dxvk_hud_on_linux(self, monkeypatch):
monkeypatch.setattr(sys, "platform", "linux")
from importlib import reload
import portprotonqt.macos_settings as m
reload(m)
env = m.build_env_from_settings(m.MacOSGameSettings(show_fps=True), {})
assert env.get("DXVK_HUD") == "fps"
assert "MTL_HUD_ENABLED" not in env
def test_rosetta_avx(self):
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
env = build_env_from_settings(MacOSGameSettings(rosetta_avx=True), {})
assert env.get("ROSETTA_ADVERTISE_AVX") == "1"
def test_fsr_sets_both_vars(self):
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
env = build_env_from_settings(MacOSGameSettings(fsr=True, fsr_sharpness=5), {})
assert env.get("WINE_FULLSCREEN_FSR") == "1"
assert env.get("WINE_FULLSCREEN_FSR_STRENGTH") == "5"
def test_custom_env_vars_highest_priority(self):
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
custom = MacOSGameSettings(env_vars={"MY_VAR": "hello", "WINEMSYNC": "0"})
env = build_env_from_settings(custom, {})
assert env["MY_VAR"] == "hello"
assert env["WINEMSYNC"] == "0" # Custom overrides setting
def test_verbose_logs_sets_winedebug(self):
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
env = build_env_from_settings(MacOSGameSettings(verbose_logs=True), {})
assert env.get("WINEDEBUG") == "+fixme"
def test_wineprefix_from_settings(self):
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
env = build_env_from_settings(
MacOSGameSettings(wineprefix="/my/prefix"), {}
)
assert env["WINEPREFIX"] == "/my/prefix"
def test_base_env_not_mutated(self):
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
base = {"EXISTING": "value"}
build_env_from_settings(MacOSGameSettings(msync=True), base)
assert "WINEMSYNC" not in base # base dict unchanged
# ── get_launch_args tests ─────────────────────────────────────────────────────
class TestGetLaunchArgs:
def test_empty_launch_args(self):
from portprotonqt.macos_settings import MacOSGameSettings, get_launch_args
assert get_launch_args(MacOSGameSettings()) == []
def test_single_arg(self):
from portprotonqt.macos_settings import MacOSGameSettings, get_launch_args
assert get_launch_args(MacOSGameSettings(launch_args="-fullscreen")) == ["-fullscreen"]
def test_multiple_args(self):
from portprotonqt.macos_settings import MacOSGameSettings, get_launch_args
result = get_launch_args(MacOSGameSettings(launch_args="-no-cef-sandbox -noreactlogin"))
assert result == ["-no-cef-sandbox", "-noreactlogin"]
def test_quoted_args(self):
from portprotonqt.macos_settings import MacOSGameSettings, get_launch_args
result = get_launch_args(MacOSGameSettings(launch_args='--name "My Game"'))
assert result == ["--name", "My Game"]
# ── DXMT / D3DMetal availability tests ───────────────────────────────────────
class TestDXMTD3DMetal:
def test_is_dxmt_installed_false_when_no_dll(self, tmp_path):
from portprotonqt.macos_settings import is_dxmt_installed
(tmp_path / "drive_c" / "windows" / "system32").mkdir(parents=True)
assert is_dxmt_installed(str(tmp_path)) is False
def test_is_dxmt_installed_true_when_dll_present(self, tmp_path):
from portprotonqt.macos_settings import is_dxmt_installed
dll_dir = tmp_path / "drive_c" / "windows" / "system32"
dll_dir.mkdir(parents=True)
(dll_dir / "winemetal.dll").touch()
assert is_dxmt_installed(str(tmp_path)) is True
def test_is_d3dmetal_available_only_on_apple_silicon(self, monkeypatch):
import platform
monkeypatch.setattr(platform, "machine", lambda: "arm64")
monkeypatch.setattr(sys, "platform", "darwin")
# Re-import to get fresh state
from importlib import reload
import portprotonqt.macos_settings as m
reload(m)
assert m.is_d3dmetal_available() is True
def test_is_d3dmetal_not_available_on_linux(self, monkeypatch):
monkeypatch.setattr(sys, "platform", "linux")
from importlib import reload
import portprotonqt.macos_settings as m
reload(m)
assert m.is_d3dmetal_available() is False
@pytest.mark.skipif(sys.platform != "darwin", reason="macOS only")
def test_d3dmetal_availability_on_current_machine(self):
from portprotonqt.macos_settings import is_d3dmetal_available
import platform
machine = platform.machine()
result = is_d3dmetal_available()
if machine == "arm64":
assert result is True
else:
assert result is False
# ── Integration: settings applied to wine launch env ─────────────────────────
class TestSettingsIntegrationWithWineEnv:
def test_settings_merged_into_build_wine_env(self):
"""Settings must integrate cleanly with build_wine_env output."""
from portprotonqt.macos_wine_runner import find_wine_binary, build_wine_env
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
wine = find_wine_binary()
if not wine:
pytest.skip("No wine binary")
base_env = build_wine_env(wine)
settings = MacOSGameSettings(
dxmt=False,
msync=True,
show_fps=False,
env_vars={"GAME_TEST": "1"},
)
final = build_env_from_settings(settings, base_env)
# build_wine_env keys must survive
assert "DYLD_FALLBACK_LIBRARY_PATH" in final
assert "PATH" in final
# settings keys added
assert final.get("WINEMSYNC") == "1"
assert final.get("GAME_TEST") == "1"
def test_dxmt_dlls_not_in_env_only_dll_overrides(self):
"""DXMT works via WINEDLLOVERRIDES, not by copying files at env time."""
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
env = build_env_from_settings(MacOSGameSettings(dxmt=True), {})
# Must have dll overrides
assert "WINEDLLOVERRIDES" in env
# Must NOT crash or require file operations
assert "d3d11=n,b" in env["WINEDLLOVERRIDES"]
def test_complete_steam_settings(self):
"""Steam settings: msync + no-cef-sandbox in launch_args."""
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings, get_launch_args
settings = MacOSGameSettings(
msync=True,
launch_args="-no-cef-sandbox -noreactlogin",
)
env = build_env_from_settings(settings, {})
args = get_launch_args(settings)
assert env.get("WINEMSYNC") == "1"
assert "-no-cef-sandbox" in args
assert "-noreactlogin" in args
def test_battle_net_settings(self):
"""Battle.net: msync, no special DX backend needed."""
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
settings = MacOSGameSettings(msync=True)
env = build_env_from_settings(settings, {})
assert env.get("WINEMSYNC") == "1"
assert "WINEDLLOVERRIDES" not in env # no DX override for plain wine
def test_winetricks_uses_qt_dialog_not_gui_flag(self):
"""On macOS, WinetricksDialog (Qt UI) is used — no zenity/kdialog needed."""
main_window_path = os.path.join(
os.path.dirname(__file__), "..", "portprotonqt", "main_window.py"
)
source = open(main_window_path).read()
# Find _open_winetricks_macos function body
start = source.find("def _open_winetricks_macos")
end = source.find("\n def ", start + 1)
func_source = source[start:end]
assert "WinetricksDialog" in func_source, "Must use WinetricksDialog on macOS"
assert "run_winetricks_detached" not in func_source, (
"Must not use run_winetricks_detached — requires zenity/kdialog"
)
def test_winetricks_env_propagated_via_os_environ(self):
"""DYLD_FALLBACK_LIBRARY_PATH must be in os.environ before WinetricksDialog opens."""
main_window_path = os.path.join(
os.path.dirname(__file__), "..", "portprotonqt", "main_window.py"
)
source = open(main_window_path).read()
start = source.find("def _open_winetricks_macos")
end = source.find("\n def ", start + 1)
func_source = source[start:end]
assert "os.environ" in func_source
assert "DYLD_FALLBACK_LIBRARY_PATH" in func_source
def test_detect_anticheat_battleye(self, tmp_path):
"""BEService.exe detected as BattlEye."""
from portprotonqt.macos_wine_tools import detect_anticheat
be_dir = tmp_path / "drive_c" / "Program Files (x86)" / "Common Files" / "BattlEye"
be_dir.mkdir(parents=True)
(be_dir / "BEService.exe").touch()
result = detect_anticheat(str(tmp_path))
assert "BattlEye" in result
def test_detect_anticheat_eac(self, tmp_path):
"""EasyAntiCheat.exe detected as EAC."""
from portprotonqt.macos_wine_tools import detect_anticheat
eac_dir = tmp_path / "drive_c" / "EasyAntiCheat"
eac_dir.mkdir(parents=True)
(eac_dir / "EasyAntiCheat.exe").touch()
result = detect_anticheat(str(tmp_path))
assert "EAC" in result
def test_detect_anticheat_clean_prefix(self, tmp_path):
"""Clean prefix returns empty list."""
from portprotonqt.macos_wine_tools import detect_anticheat
(tmp_path / "drive_c" / "windows").mkdir(parents=True)
result = detect_anticheat(str(tmp_path))
assert result == []
def test_detect_anticheat_real_crossout(self):
"""BattlEye detected in real CROSSOUT prefix."""
from portprotonqt.macos_wine_tools import detect_anticheat, get_macos_prefixes_dir
crossout = os.path.join(get_macos_prefixes_dir(), "CROSSOUT")
if not os.path.isdir(crossout):
pytest.skip("No CROSSOUT prefix")
result = detect_anticheat(crossout)
assert "BattlEye" in result, f"Expected BattlEye, got: {result}"
def test_battleye_override_applied_in_env(self):
"""When BattlEye detected, beclient=n must be in WINEDLLOVERRIDES."""
from portprotonqt.macos_settings import MacOSGameSettings, build_env_from_settings
from portprotonqt.macos_wine_runner import find_wine_binary, build_wine_env
wine = find_wine_binary()
if not wine:
pytest.skip("No wine binary")
settings = MacOSGameSettings(env_vars={"WINEDLLOVERRIDES": "beclient,beclient_x64=n"})
env = build_env_from_settings(settings, build_wine_env(wine))
overrides = env.get("WINEDLLOVERRIDES", "")
assert "beclient" in overrides
assert "=n" in overrides
def test_all_settings_serializable(self):
"""All settings must survive JSON round-trip."""
from portprotonqt.macos_settings import MacOSGameSettings
from dataclasses import asdict
s = MacOSGameSettings(
wine_version="Wine-Crossover",
dxmt=True,
d3dmetal=False,
msync=True,
show_fps=True,
rosetta_avx=True,
launch_args="-fullscreen",
env_vars={"TEST": "1"},
)
data = asdict(s)
serialized = json.dumps(data)
loaded = json.loads(serialized)
s2 = MacOSGameSettings(**loaded)
assert s2.dxmt is True
assert s2.wine_version == "Wine-Crossover"
assert s2.env_vars == {"TEST": "1"}
+495
View File
@@ -0,0 +1,495 @@
"""Tests for wine settings and macOS scan on macOS.
Run:
uv run python -m pytest tests/test_wine_settings_macos.py -v --tb=short
Screenshots saved to /tmp/ppqt_tests/
"""
import os
import sys
import subprocess
import tempfile
from pathlib import Path
import pytest
SCREENSHOT_DIR = Path("/tmp/ppqt_tests")
SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)
# ── Wine binary discovery ─────────────────────────────────────────────────────
class TestMacosWineTools:
def test_get_macos_prefixes_dir_respects_xdg(self, monkeypatch):
monkeypatch.setenv("XDG_DATA_HOME", "/tmp/xdg_test")
from portprotonqt.macos_wine_tools import get_macos_prefixes_dir
result = get_macos_prefixes_dir()
assert result == "/tmp/xdg_test/PortProtonQt/prefixes"
def test_get_prefix_path_darwin(self, monkeypatch):
monkeypatch.setattr(sys, "platform", "darwin")
monkeypatch.setenv("XDG_DATA_HOME", "/tmp/xdg_test")
from importlib import reload
import portprotonqt.macos_wine_tools as m
reload(m)
path = m.get_prefix_path("/some/portproton", "MYPREFIX")
assert "PortProtonQt/prefixes/MYPREFIX" in path
def test_get_prefix_path_linux(self, monkeypatch):
monkeypatch.setattr(sys, "platform", "linux")
from importlib import reload
import portprotonqt.macos_wine_tools as m
reload(m)
path = m.get_prefix_path("/some/portproton", "MYPREFIX")
assert path == "/some/portproton/data/prefixes/MYPREFIX"
def test_get_wine_binary_for_version_not_found(self):
from portprotonqt.macos_wine_tools import get_wine_binary_for_version
result = get_wine_binary_for_version("NonExistentWine-99.0")
assert result is None
def test_get_wine_binary_for_version_found(self):
from portprotonqt.macos_wine_tools import get_wine_binary_for_version
from portprotonqt.config import get_macos_wine_dir
wine_dir = get_macos_wine_dir()
if not os.path.isdir(wine_dir):
pytest.skip("No macOS wine dir")
versions = [d for d in os.listdir(wine_dir) if os.path.isdir(os.path.join(wine_dir, d))]
if not versions:
pytest.skip("No Wine versions installed")
for v in versions:
result = get_wine_binary_for_version(v)
if result:
assert os.path.isfile(result)
assert os.access(result, os.X_OK)
return
pytest.skip("No executable wine binary found in any version")
def test_find_wine_binary_returns_executable(self):
from portprotonqt.macos_wine_runner import find_wine_binary
result = find_wine_binary()
if result is None:
pytest.skip("No wine installed")
assert os.path.isfile(result)
assert os.access(result, os.X_OK)
def test_find_wine_binary_prefers_sikarugir_or_crossover_over_gptk(self):
from portprotonqt.macos_wine_runner import find_wine_binary, _wine_version_priority
from portprotonqt.config import get_macos_wine_dir
wine_dir = get_macos_wine_dir()
if not os.path.isdir(wine_dir):
pytest.skip("No wine dir")
versions = [d for d in os.listdir(wine_dir) if os.path.isdir(os.path.join(wine_dir, d))]
has_gptk = any("game" in v.lower() and "porting" in v.lower() for v in versions)
has_better = any(
any(k in v.lower() for k in ("crossover", "wswine", "sikarugir", "staging"))
for v in versions
)
if has_gptk and has_better:
gptk_priority = min(_wine_version_priority(v, os.path.join(wine_dir, v)) for v in versions if "game" in v.lower())
better_priority = min(
_wine_version_priority(v, os.path.join(wine_dir, v)) for v in versions
if any(k in v.lower() for k in ("crossover", "wswine", "sikarugir", "staging"))
)
assert better_priority < gptk_priority
def test_build_wine_env_sets_dyld(self):
from portprotonqt.macos_wine_runner import find_wine_binary, build_wine_env
wine_bin = find_wine_binary()
if not wine_bin:
pytest.skip("No wine installed")
env = build_wine_env(wine_bin)
assert "DYLD_FALLBACK_LIBRARY_PATH" in env
assert "PATH" in env
assert os.path.dirname(wine_bin) in env["PATH"]
def test_get_wineserver_for_binary(self):
from portprotonqt.macos_wine_runner import find_wine_binary
from portprotonqt.macos_wine_tools import get_wineserver_for_binary
wine_bin = find_wine_binary()
if not wine_bin:
pytest.skip("No wine installed")
wineserver = get_wineserver_for_binary(wine_bin)
if wineserver:
assert os.path.isfile(wineserver)
assert os.access(wineserver, os.X_OK)
def test_backup_and_restore_prefix(self, tmp_path):
from portprotonqt.macos_wine_tools import backup_prefix, restore_prefix
prefix_dir = tmp_path / "prefixes" / "TESTPREFIX"
prefix_dir.mkdir(parents=True)
(prefix_dir / "user.reg").write_text("fake registry")
(prefix_dir / "drive_c").mkdir()
backup_dir = tmp_path / "backups"
archive = backup_prefix(str(prefix_dir), str(backup_dir), "TESTPREFIX")
assert os.path.isfile(archive)
assert archive.endswith(".ppack")
restore_dir = tmp_path / "restored"
restored = restore_prefix(archive, str(restore_dir))
assert os.path.isdir(restored)
assert (Path(restored) / "user.reg").exists()
def test_wine_tool_args_coverage(self):
from portprotonqt.macos_wine_tools import WINE_TOOL_ARGS, WINE_TOOL_EXE
expected_args = {"--winecfg", "--winereg", "--winefile", "--winecmd", "--wine_uninstaller"}
assert expected_args == set(WINE_TOOL_ARGS.keys())
assert expected_args == set(WINE_TOOL_EXE.keys())
def test_parse_script_launch_params_steam(self):
from portprotonqt.macos_wine_runner import parse_script_launch_params
from portprotonqt.config import get_portproton_scripts_path
scripts_path = get_portproton_scripts_path()
if not scripts_path:
pytest.skip("No scripts path")
steam_script = os.path.join(scripts_path, "pw_autoinstall", "PW_STEAM")
if not os.path.isfile(steam_script):
pytest.skip("No PW_STEAM script")
params = parse_script_launch_params(steam_script)
assert "/S" in params
def test_parse_script_launch_params_empty(self, tmp_path):
from portprotonqt.macos_wine_runner import parse_script_launch_params
script = tmp_path / "test_script"
script.write_text('#!/bin/bash\ntry_download "http://example.com/setup.exe"\n')
result = parse_script_launch_params(str(script))
assert result == []
def test_find_installed_exe_resolves_pattern(self, tmp_path):
from portprotonqt.macos_wine_runner import find_installed_exe
steam_dir = tmp_path / "drive_c" / "Program Files (x86)" / "Steam"
steam_dir.mkdir(parents=True)
(steam_dir / "steam.exe").touch()
script = tmp_path / "PW_TEST"
script.write_text(
'#!/bin/bash\n'
'PW_EXE_FILE="$WINEPREFIX/drive_c/Program Files (x86)/Steam/steam.exe"\n'
)
result = find_installed_exe(str(script), str(tmp_path))
assert result is not None
assert result.endswith("steam.exe")
def test_find_installed_exe_case_insensitive(self, tmp_path):
from portprotonqt.macos_wine_runner import find_installed_exe
steam_dir = tmp_path / "drive_c" / "Program Files (x86)" / "Steam"
steam_dir.mkdir(parents=True)
(steam_dir / "Steam.exe").touch()
script = tmp_path / "PW_TEST"
script.write_text(
'#!/bin/bash\n'
'PW_EXE_FILE="$WINEPREFIX/drive_c/Program Files (x86)/Steam/steam.exe"\n'
)
result = find_installed_exe(str(script), str(tmp_path))
assert result is not None
def test_autoinstall_db_has_crossout_entry(self):
"""CROSSOUT prefix must be in autoinstall db with correct launcher path."""
from portprotonqt.macos_wine_tools import _get_autoinstall_prefix_map
import portprotonqt.macos_wine_tools as m
m._AUTOINSTALL_PREFIX_MAP = None
auto_map = _get_autoinstall_prefix_map()
assert "CROSSOUT" in auto_map, "CROSSOUT must be in autoinstall database"
display, exe_pattern, cover_name = auto_map["CROSSOUT"]
assert "crossout" in display.lower() or "Crossout" in display
assert "launcher.exe" in exe_pattern.lower() or "crossout" in exe_pattern.lower()
def test_scan_finds_crossout_in_real_prefix(self):
"""Integration: Crossout found in actual CROSSOUT prefix."""
from portprotonqt.macos_wine_tools import scan_wine_prefix_for_games, get_macos_prefixes_dir
crossout_prefix = os.path.join(get_macos_prefixes_dir(), "CROSSOUT")
if not os.path.isdir(crossout_prefix):
pytest.skip("No CROSSOUT prefix installed")
results = scan_wine_prefix_for_games(crossout_prefix)
names = [n for n, _, _ in results]
covers = [c for _, _, c in results]
assert any("crossout" in n.lower() for n in names), f"Crossout not found, got: {names}"
# Cover should be found if autoinstall cache has it
report = SCREENSHOT_DIR / "crossout_scan.txt"
report.write_text(f"Names: {names}\nCovers: {covers}")
def test_scan_wine_prefix_case_insensitive(self, tmp_path):
from portprotonqt.macos_wine_tools import scan_wine_prefix_for_games
steam_dir = tmp_path / "drive_c" / "program files (x86)" / "steam"
steam_dir.mkdir(parents=True)
(steam_dir / "steam.exe").touch()
results = scan_wine_prefix_for_games(str(tmp_path))
names = [n for n, _, _ in results]
assert any("steam" in n.lower() for n in names)
def test_scan_wine_prefix_empty_prefix(self, tmp_path):
from portprotonqt.macos_wine_tools import scan_wine_prefix_for_games
(tmp_path / "drive_c" / "windows").mkdir(parents=True)
results = scan_wine_prefix_for_games(str(tmp_path))
assert results == []
def test_scan_real_prefixes(self):
from portprotonqt.macos_wine_tools import get_macos_prefixes_dir, scan_wine_prefix_for_games
prefixes_dir = get_macos_prefixes_dir()
if not os.path.isdir(prefixes_dir):
pytest.skip("No macOS prefixes dir")
all_games = []
report_lines = []
for prefix_name in os.listdir(prefixes_dir):
prefix_path = os.path.join(prefixes_dir, prefix_name)
games = scan_wine_prefix_for_games(prefix_path)
report_lines.append(f"{prefix_name}: {[n for n, _, _ in games]}")
all_games.extend(games)
report = SCREENSHOT_DIR / "prefix_scan_report.txt"
report.write_text("\n".join(report_lines))
prefixes = [d for d in os.listdir(prefixes_dir) if os.path.isdir(os.path.join(prefixes_dir, d))]
if prefixes:
assert len(all_games) > 0, f"No games found in prefixes: {prefixes}"
def test_parse_script_url_steam(self):
from portprotonqt.macos_wine_runner import parse_script_url
from portprotonqt.config import get_portproton_scripts_path
scripts_path = get_portproton_scripts_path()
if not scripts_path:
pytest.skip("No scripts path")
steam_script = os.path.join(scripts_path, "pw_autoinstall", "PW_STEAM")
if not os.path.isfile(steam_script):
pytest.skip("No PW_STEAM script")
url = parse_script_url(steam_script)
assert url is not None
assert "steam" in url.lower() or "Steam" in url
# ── Launch flow tests ─────────────────────────────────────────────────────────
class TestLaunchFlow:
def test_build_exec_line_format(self, tmp_path):
import shlex
from portprotonqt.macos_wine_runner import find_wine_binary
wine = find_wine_binary()
if not wine:
pytest.skip("No wine binary")
prefix = str(tmp_path / "prefix")
exe = str(tmp_path / "prefix" / "drive_c" / "game.exe")
exec_line = f'env WINEPREFIX="{prefix}" "{wine}" "{exe}"'
parts = shlex.split(exec_line)
assert parts[0] == "env"
assert any("WINEPREFIX" in p for p in parts)
assert wine in parts
assert exe in parts
def test_scan_finds_steam_in_real_prefix(self):
from portprotonqt.macos_wine_tools import scan_wine_prefix_for_games, get_macos_prefixes_dir
default_prefix = os.path.join(get_macos_prefixes_dir(), "DEFAULT")
if not os.path.isdir(default_prefix):
pytest.skip("No DEFAULT prefix")
results = scan_wine_prefix_for_games(default_prefix)
found_names = [name for name, _, _ in results]
report = SCREENSHOT_DIR / "steam_scan_result.txt"
report.write_text(f"Scanned: {default_prefix}\nFound: {found_names}\n")
assert any("steam" in n.lower() for n in found_names), \
f"Steam not found. Scanned {default_prefix}, found: {found_names}"
def test_make_wine_game_data_tuple_length(self):
name = "Steam"
exec_line = 'env WINEPREFIX="/p" "wine64" "steam.exe"'
game_data = (name, "", "", "", "", exec_line, "", "", "", "", 0, 0, "portproton")
assert len(game_data) == 13
assert game_data[0] == name
assert game_data[5] == exec_line
assert game_data[12] == "portproton"
def test_sikarugir_wine_has_priority(self):
from portprotonqt.macos_wine_runner import _wine_version_priority
sika_priority = _wine_version_priority("WS12WineSikarugir10.0-battle.net")
cx_priority = _wine_version_priority("Wine-Crossover-23.7.1-1")
gptk_priority = _wine_version_priority("Game Porting Toolkit.app")
ws12gptk_priority = _wine_version_priority("WS12WineGPTK1.1_3")
assert sika_priority < cx_priority
assert cx_priority < gptk_priority
assert ws12gptk_priority == gptk_priority # GPTK wines = same low priority
def test_winetricks_download(self, tmp_path):
from portprotonqt.macos_wine_tools import get_winetricks_path
path = get_winetricks_path(str(tmp_path))
assert os.path.isfile(path)
assert os.access(path, os.X_OK)
# ── Wine tool invocation ──────────────────────────────────────────────────────
@pytest.mark.skipif(sys.platform != "darwin", reason="macOS only")
class TestWineToolInvocation:
@pytest.fixture(autouse=True)
def wine_bin_and_prefix(self, tmp_path):
from portprotonqt.macos_wine_runner import find_wine_binary
wine_bin = find_wine_binary()
if not wine_bin:
pytest.skip("No wine binary found")
self.wine_bin = wine_bin
self.prefix = str(tmp_path / "testprefix")
os.makedirs(self.prefix, exist_ok=True)
def test_wineboot_init_creates_prefix(self):
from portprotonqt.macos_wine_tools import run_wineboot_init
code = run_wineboot_init(self.wine_bin, self.prefix)
assert code in (0, 1), f"wineboot returned unexpected code {code}"
assert os.path.isdir(os.path.join(self.prefix, "drive_c")), "drive_c missing"
def test_run_wine_tool_detached_winecfg(self):
from portprotonqt.macos_wine_tools import run_wine_tool_detached
proc = run_wine_tool_detached(self.wine_bin, self.prefix, ["winecfg"])
assert proc.pid > 0
import time
time.sleep(2)
if proc.poll() is None:
proc.terminate()
proc.wait(timeout=5)
# ── GUI tests ─────────────────────────────────────────────────────────────────
@pytest.mark.skipif(
os.environ.get("DISPLAY") is None and sys.platform != "darwin",
reason="No display available"
)
class TestWineSettingsTab:
@pytest.fixture(scope="class", autouse=True)
def app(self):
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication(sys.argv)
yield app
def test_wine_settings_renders(self):
from PySide6.QtWidgets import QWidget, QComboBox, QProgressBar, QVBoxLayout
from portprotonqt.theme_manager import ThemeManager
from portprotonqt.config import ui_config
theme = ThemeManager().apply_theme(ui_config.get_theme())
widget = QWidget()
layout = QVBoxLayout(widget)
combo_wine = QComboBox()
combo_wine.setObjectName("wineCombo")
layout.addWidget(combo_wine)
widget.resize(400, 200)
widget.show()
assert widget.isVisible()
widget.close()
def test_wine_combo_has_macos_versions(self):
from portprotonqt.config import get_macos_wine_dir
from portprotonqt.macos_wine_tools import get_wine_binary_for_version
wine_dir = get_macos_wine_dir()
if not os.path.isdir(wine_dir):
pytest.skip("No macOS wine dir")
installed = [
d for d in os.listdir(wine_dir)
if os.path.isdir(os.path.join(wine_dir, d)) and get_wine_binary_for_version(d)
]
assert len(installed) > 0
def test_prefix_combo_has_macos_prefixes(self):
from portprotonqt.macos_wine_tools import get_macos_prefixes_dir
prefixes_dir = get_macos_prefixes_dir()
if not os.path.isdir(prefixes_dir):
pytest.skip("No macOS prefixes dir")
prefixes = [d for d in os.listdir(prefixes_dir) if os.path.isdir(os.path.join(prefixes_dir, d))]
assert len(prefixes) > 0
@pytest.mark.parametrize("cli_arg,expected_tool", [
("--winecfg", "winecfg"),
("--winereg", "regedit"),
("--winefile", "explorer"),
("--winecmd", "cmd"),
("--wine_uninstaller", "uninstaller"),
])
def test_wine_tool_args_map(self, cli_arg, expected_tool):
from portprotonqt.macos_wine_tools import WINE_TOOL_ARGS
args = WINE_TOOL_ARGS[cli_arg]
assert expected_tool in args[0].lower() or any(expected_tool in a.lower() for a in args)
# ── Atomic micro-tests ────────────────────────────────────────────────────────
class TestAtomicMicroTests:
def test_wine_binary_is_valid_elf_or_macho(self):
from portprotonqt.macos_wine_runner import find_wine_binary
wine = find_wine_binary()
if not wine:
pytest.skip("No wine binary")
result = subprocess.run(["file", wine], capture_output=True, text=True)
output = result.stdout.lower()
assert "executable" in output or "mach-o" in output
def test_wine_prints_version(self):
from portprotonqt.macos_wine_runner import find_wine_binary, build_wine_env
wine = find_wine_binary()
if not wine:
pytest.skip("No wine binary")
env = build_wine_env(wine)
result = subprocess.run(
[wine, "--version"],
capture_output=True, text=True, env=env, timeout=10
)
assert "wine" in result.stdout.lower() or "wine" in result.stderr.lower()
def test_prefix_structure_after_wineboot(self, tmp_path):
from portprotonqt.macos_wine_runner import find_wine_binary
from portprotonqt.macos_wine_tools import run_wineboot_init
wine = find_wine_binary()
if not wine:
pytest.skip("No wine binary")
prefix = str(tmp_path / "prefix")
code = run_wineboot_init(wine, prefix)
screenshot = SCREENSHOT_DIR / "wineboot_prefix_structure.txt"
structure = []
for root, dirs, files in os.walk(prefix):
level = root.replace(prefix, "").count(os.sep)
indent = " " * level
structure.append(f"{indent}{os.path.basename(root)}/")
for f in files[:5]:
structure.append(f"{indent} {f}")
screenshot.write_text("\n".join(structure))
assert code in (0, 1), f"wineboot --init failed with code {code}"
assert os.path.isdir(os.path.join(prefix, "drive_c"))
def test_screencapture_works(self):
path = SCREENSHOT_DIR / "screencapture_test.png"
result = subprocess.run(["screencapture", "-x", str(path)], capture_output=True)
assert result.returncode == 0 or path.exists()
def test_wine_env_has_required_keys(self):
from portprotonqt.macos_wine_runner import find_wine_binary, build_wine_env
wine = find_wine_binary()
if not wine:
pytest.skip("No wine binary")
env = build_wine_env(wine)
assert "DYLD_FALLBACK_LIBRARY_PATH" in env
assert "PATH" in env
assert env["PATH"].startswith(os.path.dirname(wine))
def test_macos_prefixes_dir_creation(self, tmp_path, monkeypatch):
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path))
from importlib import reload
import portprotonqt.macos_wine_tools as m
reload(m)
pfx_dir = m.get_macos_prefixes_dir()
os.makedirs(pfx_dir, exist_ok=True)
assert os.path.isdir(pfx_dir)
def test_get_wine_binary_for_each_installed_version(self):
from portprotonqt.config import get_macos_wine_dir
from portprotonqt.macos_wine_tools import get_wine_binary_for_version
wine_dir = get_macos_wine_dir()
if not os.path.isdir(wine_dir):
pytest.skip("No macOS wine dir")
results = {}
for entry in os.listdir(wine_dir):
if os.path.isdir(os.path.join(wine_dir, entry)):
binary = get_wine_binary_for_version(entry)
results[entry] = binary
report = SCREENSHOT_DIR / "wine_binary_discovery.txt"
report.write_text(
"\n".join(f"{k}: {v or 'NOT FOUND'}" for k, v in results.items())
)
found = [v for v in results.values() if v is not None]
assert len(found) > 0, f"No wine binaries found. Checked: {results}"
Generated
+124 -2
View File
@@ -185,6 +185,18 @@ version = "1.9.3"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/a5/f5/397b61091120a9ca5001041dd7bf76c385b3bfd67a0e5bcb74b852bd22a4/evdev-1.9.3.tar.gz", hash = "sha256:2c140e01ac8437758fa23fe5c871397412461f42d421aa20241dc8fe8cfccbc9", size = 32723, upload-time = "2026-02-05T21:54:24.987Z" }
[[package]]
name = "exceptiongroup"
version = "1.3.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "typing-extensions", marker = "python_full_version < '3.11'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" },
]
[[package]]
name = "filelock"
version = "3.20.1"
@@ -212,6 +224,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008, upload-time = "2025-10-12T14:55:18.883Z" },
]
[[package]]
name = "iniconfig"
version = "2.3.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },
]
[[package]]
name = "libarchive-c"
version = "5.3"
@@ -311,6 +332,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c0/d1/facb5b5051fabb0ef9d26c6544d87ef19a939a9a001198655d0d891062dd/orjson-3.11.8-cp314-cp314-win_arm64.whl", hash = "sha256:6ccdea2c213cf9f3d9490cbd5d427693c870753df41e6cb375bd79bcbafc8817", size = 127330, upload-time = "2026-03-31T16:16:25.496Z" },
]
[[package]]
name = "packaging"
version = "26.2"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" },
]
[[package]]
name = "pefile"
version = "2024.8.26"
@@ -427,6 +457,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cb/28/3bfe2fa5a7b9c46fe7e13c97bda14c895fb10fa2ebf1d0abb90e0cea7ee1/platformdirs-4.5.1-py3-none-any.whl", hash = "sha256:d03afa3963c806a9bed9d5125c8f4cb2fdaf74a55ab60e5d59b3fde758104d31", size = 18731, upload-time = "2025-12-05T13:52:56.823Z" },
]
[[package]]
name = "pluggy"
version = "1.6.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
]
[[package]]
name = "portprotonqt"
version = "0.1.12"
@@ -434,7 +473,7 @@ source = { editable = "." }
dependencies = [
{ name = "babel" },
{ name = "dbus-fast" },
{ name = "evdev" },
{ name = "evdev", marker = "sys_platform == 'linux'" },
{ name = "libarchive-c" },
{ name = "orjson" },
{ name = "pefile" },
@@ -455,13 +494,14 @@ dev = [
{ name = "pre-commit" },
{ name = "pyaspeller" },
{ name = "pyright" },
{ name = "pytest" },
]
[package.metadata]
requires-dist = [
{ name = "babel", specifier = ">=2.18.0" },
{ name = "dbus-fast", specifier = ">=4.0.4" },
{ name = "evdev", specifier = ">=1.9.3" },
{ name = "evdev", marker = "sys_platform == 'linux'", specifier = ">=1.9.3" },
{ name = "libarchive-c", specifier = ">=5.3" },
{ name = "orjson", specifier = ">=3.11.8" },
{ name = "pefile", specifier = ">=2024.8.26" },
@@ -482,6 +522,7 @@ dev = [
{ name = "pre-commit", specifier = ">=4.5.1" },
{ name = "pyaspeller", specifier = ">=2.0.2" },
{ name = "pyright", specifier = ">=1.1.408" },
{ name = "pytest", specifier = ">=9.0.3" },
]
[[package]]
@@ -576,6 +617,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/7e/11/17f7f319ca91824b86557e9303e3b7a71991ef17fd45286bf47d7f0a38e6/pygame-2.6.1-cp313-cp313-win_amd64.whl", hash = "sha256:813af4fba5d0b2cb8e58f5d95f7910295c34067dcc290d34f1be59c48bd1ea6a", size = 10620084, upload-time = "2024-09-29T11:48:51.587Z" },
]
[[package]]
name = "pygments"
version = "2.20.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" },
]
[[package]]
name = "pyright"
version = "1.1.408"
@@ -637,6 +687,24 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/53/27/d17f25e45820e633a70e6109b35991eda09a5e8000c2a306f0ab7538d48c/pyside6_essentials-6.11.0-cp310-abi3-win_arm64.whl", hash = "sha256:81ca603dbf21bc39f89bb42db215c25ebe0c879a1a4c387625c321d2730ec187", size = 56337457, upload-time = "2026-03-23T12:43:43.573Z" },
]
[[package]]
name = "pytest"
version = "9.0.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "colorama", marker = "sys_platform == 'win32'" },
{ name = "exceptiongroup", marker = "python_full_version < '3.11'" },
{ name = "iniconfig" },
{ name = "packaging" },
{ name = "pluggy" },
{ name = "pygments" },
{ name = "tomli", marker = "python_full_version < '3.11'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/7d/0d/549bd94f1a0a402dc8cf64563a117c0f3765662e2e668477624baeec44d5/pytest-9.0.3.tar.gz", hash = "sha256:b86ada508af81d19edeb213c681b1d48246c1a91d304c6c81a427674c17eb91c", size = 1572165, upload-time = "2026-04-07T17:16:18.027Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d4/24/a372aaf5c9b7208e7112038812994107bc65a84cd00e0354a88c2c77a617/pytest-9.0.3-py3-none-any.whl", hash = "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", size = 375249, upload-time = "2026-04-07T17:16:16.13Z" },
]
[[package]]
name = "pyyaml"
version = "6.0.3"
@@ -830,6 +898,60 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/fb/99/6e5ee21db2d6af84bbbd7d871d441dafeb069c6de5667b1aa49891a77c66/shiboken6-6.11.0-cp310-abi3-win_arm64.whl", hash = "sha256:3bd76cf56105ab2d62ecaff630366f11264f69b88d488f10f048da9a065781f4", size = 1783186, upload-time = "2026-03-23T12:47:11.832Z" },
]
[[package]]
name = "tomli"
version = "2.4.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/22/de/48c59722572767841493b26183a0d1cc411d54fd759c5607c4590b6563a6/tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f", size = 17543, upload-time = "2026-03-25T20:22:03.828Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/f4/11/db3d5885d8528263d8adc260bb2d28ebf1270b96e98f0e0268d32b8d9900/tomli-2.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f8f0fc26ec2cc2b965b7a3b87cd19c5c6b8c5e5f436b984e85f486d652285c30", size = 154704, upload-time = "2026-03-25T20:21:10.473Z" },
{ url = "https://files.pythonhosted.org/packages/6d/f7/675db52c7e46064a9aa928885a9b20f4124ecb9bc2e1ce74c9106648d202/tomli-2.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4ab97e64ccda8756376892c53a72bd1f964e519c77236368527f758fbc36a53a", size = 149454, upload-time = "2026-03-25T20:21:12.036Z" },
{ url = "https://files.pythonhosted.org/packages/61/71/81c50943cf953efa35bce7646caab3cf457a7d8c030b27cfb40d7235f9ee/tomli-2.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96481a5786729fd470164b47cdb3e0e58062a496f455ee41b4403be77cb5a076", size = 237561, upload-time = "2026-03-25T20:21:13.098Z" },
{ url = "https://files.pythonhosted.org/packages/48/c1/f41d9cb618acccca7df82aaf682f9b49013c9397212cb9f53219e3abac37/tomli-2.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a881ab208c0baf688221f8cecc5401bd291d67e38a1ac884d6736cbcd8247e9", size = 243824, upload-time = "2026-03-25T20:21:14.569Z" },
{ url = "https://files.pythonhosted.org/packages/22/e4/5a816ecdd1f8ca51fb756ef684b90f2780afc52fc67f987e3c61d800a46d/tomli-2.4.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:47149d5bd38761ac8be13a84864bf0b7b70bc051806bc3669ab1cbc56216b23c", size = 242227, upload-time = "2026-03-25T20:21:15.712Z" },
{ url = "https://files.pythonhosted.org/packages/6b/49/2b2a0ef529aa6eec245d25f0c703e020a73955ad7edf73e7f54ddc608aa5/tomli-2.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ec9bfaf3ad2df51ace80688143a6a4ebc09a248f6ff781a9945e51937008fcbc", size = 247859, upload-time = "2026-03-25T20:21:17.001Z" },
{ url = "https://files.pythonhosted.org/packages/83/bd/6c1a630eaca337e1e78c5903104f831bda934c426f9231429396ce3c3467/tomli-2.4.1-cp311-cp311-win32.whl", hash = "sha256:ff2983983d34813c1aeb0fa89091e76c3a22889ee83ab27c5eeb45100560c049", size = 97204, upload-time = "2026-03-25T20:21:18.079Z" },
{ url = "https://files.pythonhosted.org/packages/42/59/71461df1a885647e10b6bb7802d0b8e66480c61f3f43079e0dcd315b3954/tomli-2.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:5ee18d9ebdb417e384b58fe414e8d6af9f4e7a0ae761519fb50f721de398dd4e", size = 108084, upload-time = "2026-03-25T20:21:18.978Z" },
{ url = "https://files.pythonhosted.org/packages/b8/83/dceca96142499c069475b790e7913b1044c1a4337e700751f48ed723f883/tomli-2.4.1-cp311-cp311-win_arm64.whl", hash = "sha256:c2541745709bad0264b7d4705ad453b76ccd191e64aa6f0fc66b69a293a45ece", size = 95285, upload-time = "2026-03-25T20:21:20.309Z" },
{ url = "https://files.pythonhosted.org/packages/c1/ba/42f134a3fe2b370f555f44b1d72feebb94debcab01676bf918d0cb70e9aa/tomli-2.4.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c742f741d58a28940ce01d58f0ab2ea3ced8b12402f162f4d534dfe18ba1cd6a", size = 155924, upload-time = "2026-03-25T20:21:21.626Z" },
{ url = "https://files.pythonhosted.org/packages/dc/c7/62d7a17c26487ade21c5422b646110f2162f1fcc95980ef7f63e73c68f14/tomli-2.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7f86fd587c4ed9dd76f318225e7d9b29cfc5a9d43de44e5754db8d1128487085", size = 150018, upload-time = "2026-03-25T20:21:23.002Z" },
{ url = "https://files.pythonhosted.org/packages/5c/05/79d13d7c15f13bdef410bdd49a6485b1c37d28968314eabee452c22a7fda/tomli-2.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff18e6a727ee0ab0388507b89d1bc6a22b138d1e2fa56d1ad494586d61d2eae9", size = 244948, upload-time = "2026-03-25T20:21:24.04Z" },
{ url = "https://files.pythonhosted.org/packages/10/90/d62ce007a1c80d0b2c93e02cab211224756240884751b94ca72df8a875ca/tomli-2.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:136443dbd7e1dee43c68ac2694fde36b2849865fa258d39bf822c10e8068eac5", size = 253341, upload-time = "2026-03-25T20:21:25.177Z" },
{ url = "https://files.pythonhosted.org/packages/1a/7e/caf6496d60152ad4ed09282c1885cca4eea150bfd007da84aea07bcc0a3e/tomli-2.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5e262d41726bc187e69af7825504c933b6794dc3fbd5945e41a79bb14c31f585", size = 248159, upload-time = "2026-03-25T20:21:26.364Z" },
{ url = "https://files.pythonhosted.org/packages/99/e7/c6f69c3120de34bbd882c6fba7975f3d7a746e9218e56ab46a1bc4b42552/tomli-2.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5cb41aa38891e073ee49d55fbc7839cfdb2bc0e600add13874d048c94aadddd1", size = 253290, upload-time = "2026-03-25T20:21:27.46Z" },
{ url = "https://files.pythonhosted.org/packages/d6/2f/4a3c322f22c5c66c4b836ec58211641a4067364f5dcdd7b974b4c5da300c/tomli-2.4.1-cp312-cp312-win32.whl", hash = "sha256:da25dc3563bff5965356133435b757a795a17b17d01dbc0f42fb32447ddfd917", size = 98141, upload-time = "2026-03-25T20:21:28.492Z" },
{ url = "https://files.pythonhosted.org/packages/24/22/4daacd05391b92c55759d55eaee21e1dfaea86ce5c571f10083360adf534/tomli-2.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:52c8ef851d9a240f11a88c003eacb03c31fc1c9c4ec64a99a0f922b93874fda9", size = 108847, upload-time = "2026-03-25T20:21:29.386Z" },
{ url = "https://files.pythonhosted.org/packages/68/fd/70e768887666ddd9e9f5d85129e84910f2db2796f9096aa02b721a53098d/tomli-2.4.1-cp312-cp312-win_arm64.whl", hash = "sha256:f758f1b9299d059cc3f6546ae2af89670cb1c4d48ea29c3cacc4fe7de3058257", size = 95088, upload-time = "2026-03-25T20:21:30.677Z" },
{ url = "https://files.pythonhosted.org/packages/07/06/b823a7e818c756d9a7123ba2cda7d07bc2dd32835648d1a7b7b7a05d848d/tomli-2.4.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:36d2bd2ad5fb9eaddba5226aa02c8ec3fa4f192631e347b3ed28186d43be6b54", size = 155866, upload-time = "2026-03-25T20:21:31.65Z" },
{ url = "https://files.pythonhosted.org/packages/14/6f/12645cf7f08e1a20c7eb8c297c6f11d31c1b50f316a7e7e1e1de6e2e7b7e/tomli-2.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eb0dc4e38e6a1fd579e5d50369aa2e10acfc9cace504579b2faabb478e76941a", size = 149887, upload-time = "2026-03-25T20:21:33.028Z" },
{ url = "https://files.pythonhosted.org/packages/5c/e0/90637574e5e7212c09099c67ad349b04ec4d6020324539297b634a0192b0/tomli-2.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c7f2c7f2b9ca6bdeef8f0fa897f8e05085923eb091721675170254cbc5b02897", size = 243704, upload-time = "2026-03-25T20:21:34.51Z" },
{ url = "https://files.pythonhosted.org/packages/10/8f/d3ddb16c5a4befdf31a23307f72828686ab2096f068eaf56631e136c1fdd/tomli-2.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f3c6818a1a86dd6dca7ddcaaf76947d5ba31aecc28cb1b67009a5877c9a64f3f", size = 251628, upload-time = "2026-03-25T20:21:36.012Z" },
{ url = "https://files.pythonhosted.org/packages/e3/f1/dbeeb9116715abee2485bf0a12d07a8f31af94d71608c171c45f64c0469d/tomli-2.4.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d312ef37c91508b0ab2cee7da26ec0b3ed2f03ce12bd87a588d771ae15dcf82d", size = 247180, upload-time = "2026-03-25T20:21:37.136Z" },
{ url = "https://files.pythonhosted.org/packages/d3/74/16336ffd19ed4da28a70959f92f506233bd7cfc2332b20bdb01591e8b1d1/tomli-2.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:51529d40e3ca50046d7606fa99ce3956a617f9b36380da3b7f0dd3dd28e68cb5", size = 251674, upload-time = "2026-03-25T20:21:38.298Z" },
{ url = "https://files.pythonhosted.org/packages/16/f9/229fa3434c590ddf6c0aa9af64d3af4b752540686cace29e6281e3458469/tomli-2.4.1-cp313-cp313-win32.whl", hash = "sha256:2190f2e9dd7508d2a90ded5ed369255980a1bcdd58e52f7fe24b8162bf9fedbd", size = 97976, upload-time = "2026-03-25T20:21:39.316Z" },
{ url = "https://files.pythonhosted.org/packages/6a/1e/71dfd96bcc1c775420cb8befe7a9d35f2e5b1309798f009dca17b7708c1e/tomli-2.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:8d65a2fbf9d2f8352685bc1364177ee3923d6baf5e7f43ea4959d7d8bc326a36", size = 108755, upload-time = "2026-03-25T20:21:40.248Z" },
{ url = "https://files.pythonhosted.org/packages/83/7a/d34f422a021d62420b78f5c538e5b102f62bea616d1d75a13f0a88acb04a/tomli-2.4.1-cp313-cp313-win_arm64.whl", hash = "sha256:4b605484e43cdc43f0954ddae319fb75f04cc10dd80d830540060ee7cd0243cd", size = 95265, upload-time = "2026-03-25T20:21:41.219Z" },
{ url = "https://files.pythonhosted.org/packages/3c/fb/9a5c8d27dbab540869f7c1f8eb0abb3244189ce780ba9cd73f3770662072/tomli-2.4.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fd0409a3653af6c147209d267a0e4243f0ae46b011aa978b1080359fddc9b6cf", size = 155726, upload-time = "2026-03-25T20:21:42.23Z" },
{ url = "https://files.pythonhosted.org/packages/62/05/d2f816630cc771ad836af54f5001f47a6f611d2d39535364f148b6a92d6b/tomli-2.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a120733b01c45e9a0c34aeef92bf0cf1d56cfe81ed9d47d562f9ed591a9828ac", size = 149859, upload-time = "2026-03-25T20:21:43.386Z" },
{ url = "https://files.pythonhosted.org/packages/ce/48/66341bdb858ad9bd0ceab5a86f90eddab127cf8b046418009f2125630ecb/tomli-2.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:559db847dc486944896521f68d8190be1c9e719fced785720d2216fe7022b662", size = 244713, upload-time = "2026-03-25T20:21:44.474Z" },
{ url = "https://files.pythonhosted.org/packages/df/6d/c5fad00d82b3c7a3ab6189bd4b10e60466f22cfe8a08a9394185c8a8111c/tomli-2.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01f520d4f53ef97964a240a035ec2a869fe1a37dde002b57ebc4417a27ccd853", size = 252084, upload-time = "2026-03-25T20:21:45.62Z" },
{ url = "https://files.pythonhosted.org/packages/00/71/3a69e86f3eafe8c7a59d008d245888051005bd657760e96d5fbfb0b740c2/tomli-2.4.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f94b27a62cfad8496c8d2513e1a222dd446f095fca8987fceef261225538a15", size = 247973, upload-time = "2026-03-25T20:21:46.937Z" },
{ url = "https://files.pythonhosted.org/packages/67/50/361e986652847fec4bd5e4a0208752fbe64689c603c7ae5ea7cb16b1c0ca/tomli-2.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ede3e6487c5ef5d28634ba3f31f989030ad6af71edfb0055cbbd14189ff240ba", size = 256223, upload-time = "2026-03-25T20:21:48.467Z" },
{ url = "https://files.pythonhosted.org/packages/8c/9a/b4173689a9203472e5467217e0154b00e260621caa227b6fa01feab16998/tomli-2.4.1-cp314-cp314-win32.whl", hash = "sha256:3d48a93ee1c9b79c04bb38772ee1b64dcf18ff43085896ea460ca8dec96f35f6", size = 98973, upload-time = "2026-03-25T20:21:49.526Z" },
{ url = "https://files.pythonhosted.org/packages/14/58/640ac93bf230cd27d002462c9af0d837779f8773bc03dee06b5835208214/tomli-2.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:88dceee75c2c63af144e456745e10101eb67361050196b0b6af5d717254dddf7", size = 109082, upload-time = "2026-03-25T20:21:50.506Z" },
{ url = "https://files.pythonhosted.org/packages/d5/2f/702d5e05b227401c1068f0d386d79a589bb12bf64c3d2c72ce0631e3bc49/tomli-2.4.1-cp314-cp314-win_arm64.whl", hash = "sha256:b8c198f8c1805dc42708689ed6864951fd2494f924149d3e4bce7710f8eb5232", size = 96490, upload-time = "2026-03-25T20:21:51.474Z" },
{ url = "https://files.pythonhosted.org/packages/45/4b/b877b05c8ba62927d9865dd980e34a755de541eb65fffba52b4cc495d4d2/tomli-2.4.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:d4d8fe59808a54658fcc0160ecfb1b30f9089906c50b23bcb4c69eddc19ec2b4", size = 164263, upload-time = "2026-03-25T20:21:52.543Z" },
{ url = "https://files.pythonhosted.org/packages/24/79/6ab420d37a270b89f7195dec5448f79400d9e9c1826df982f3f8e97b24fd/tomli-2.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7008df2e7655c495dd12d2a4ad038ff878d4ca4b81fccaf82b714e07eae4402c", size = 160736, upload-time = "2026-03-25T20:21:53.674Z" },
{ url = "https://files.pythonhosted.org/packages/02/e0/3630057d8eb170310785723ed5adcdfb7d50cb7e6455f85ba8a3deed642b/tomli-2.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1d8591993e228b0c930c4bb0db464bdad97b3289fb981255d6c9a41aedc84b2d", size = 270717, upload-time = "2026-03-25T20:21:55.129Z" },
{ url = "https://files.pythonhosted.org/packages/7a/b4/1613716072e544d1a7891f548d8f9ec6ce2faf42ca65acae01d76ea06bb0/tomli-2.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:734e20b57ba95624ecf1841e72b53f6e186355e216e5412de414e3c51e5e3c41", size = 278461, upload-time = "2026-03-25T20:21:56.228Z" },
{ url = "https://files.pythonhosted.org/packages/05/38/30f541baf6a3f6df77b3df16b01ba319221389e2da59427e221ef417ac0c/tomli-2.4.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8a650c2dbafa08d42e51ba0b62740dae4ecb9338eefa093aa5c78ceb546fcd5c", size = 274855, upload-time = "2026-03-25T20:21:57.653Z" },
{ url = "https://files.pythonhosted.org/packages/77/a3/ec9dd4fd2c38e98de34223b995a3b34813e6bdadf86c75314c928350ed14/tomli-2.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:504aa796fe0569bb43171066009ead363de03675276d2d121ac1a4572397870f", size = 283144, upload-time = "2026-03-25T20:21:59.089Z" },
{ url = "https://files.pythonhosted.org/packages/ef/be/605a6261cac79fba2ec0c9827e986e00323a1945700969b8ee0b30d85453/tomli-2.4.1-cp314-cp314t-win32.whl", hash = "sha256:b1d22e6e9387bf4739fbe23bfa80e93f6b0373a7f1b96c6227c32bef95a4d7a8", size = 108683, upload-time = "2026-03-25T20:22:00.214Z" },
{ url = "https://files.pythonhosted.org/packages/12/64/da524626d3b9cc40c168a13da8335fe1c51be12c0a63685cc6db7308daae/tomli-2.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:2c1c351919aca02858f740c6d33adea0c5deea37f9ecca1cc1ef9e884a619d26", size = 121196, upload-time = "2026-03-25T20:22:01.169Z" },
{ url = "https://files.pythonhosted.org/packages/5a/cd/e80b62269fc78fc36c9af5a6b89c835baa8af28ff5ad28c7028d60860320/tomli-2.4.1-cp314-cp314t-win_arm64.whl", hash = "sha256:eab21f45c7f66c13f2a9e0e1535309cee140182a9cdae1e041d02e47291e8396", size = 100393, upload-time = "2026-03-25T20:22:02.137Z" },
{ url = "https://files.pythonhosted.org/packages/7b/61/cceae43728b7de99d9b847560c262873a1f6c98202171fd5ed62640b494b/tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe", size = 14583, upload-time = "2026-03-25T20:22:03.012Z" },
]
[[package]]
name = "tqdm"
version = "4.67.3"