Compare commits

..
1 Commits
Author SHA1 Message Date
Boria138 884b0f7827 feat(tray): add Wine tools submenu
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-11-15 19:49:55 +05:00
33 changed files with 439 additions and 950 deletions

No files matched your search

@@ -1572,6 +1572,7 @@ pw_kill_autostart () {
export -f pw_kill_autostart
stop_portproton () {
pw_remove_session_env
[[ "$int_xneur" == "1" ]] && xneur &
if [[ "$PW_USE_US_LAYOUT" == "1" ]] \
@@ -3845,6 +3846,7 @@ start_portproton () {
pw_mangohud_check
pw_vkbasalt_check
pw_lsfg_vk_check
pw_save_session_env || print_warning "Could not save Wine session environment"
}
pw_run () {
@@ -3996,6 +3998,80 @@ pw_run () {
}
export -f pw_run
pw_save_session_env () {
local session_dir="${PORT_DATA_PATH}/data/tmp/wine-session-$(id -u)"
local session_tmp
( umask 077; mkdir -p "$session_dir" ) || return 1
[[ ! -L "$session_dir" && -O "$session_dir" ]] || return 1
[[ "$(stat -c %a "$session_dir")" == 700 ]] || return 1
session_tmp="$(mktemp "$session_dir/env.XXXXXX")" || return 1
if ( export PW_TERM; export -p > "$session_tmp" ) \
&& mv -fT "$session_tmp" "$session_dir/session.env" ; then
return 0
fi
rm -f "$session_tmp"
return 1
}
pw_remove_session_env () {
local session_dir="${PORT_DATA_PATH}/data/tmp/wine-session-$(id -u)"
[[ ! -L "$session_dir" && -O "$session_dir" ]] || return 0
local session_env="$session_dir/session.env"
[[ ! -L "$session_env" && -O "$session_env" ]] || return 0
if grep -qsx "declare -x PW_START_PID=\"${PW_START_PID}\"" "$session_env" ; then
rm -f "$session_env"
fi
}
pw_session_tool () {
local tool="$1" session_pid session_env
local session_dir="${PORT_DATA_PATH}/data/tmp/wine-session-$(id -u)"
local session_wait_seconds="${2:-30}" wait_left
wait_left="$session_wait_seconds"
case "$tool" in
winefile|taskmgr|winecfg|regedit|cmd|uninstaller) ;;
*) print_error "Unsupported Wine tool: $tool" ; return 1 ;;
esac
session_env="$session_dir/session.env"
while (( wait_left > 0 )) ; do
if [[ ! -L "$session_dir" && -O "$session_dir" ]] \
&& [[ "$(stat -c %a "$session_dir")" == 700 ]] \
&& [[ ! -L "$session_env" && -O "$session_env" ]] \
&& [[ "$(stat -c %a "$session_env")" == 600 ]] \
&& session_pid="$(sed -n 's/^declare -x PW_START_PID="\([0-9]*\)"$/\1/p' "$session_env")" \
&& [[ -n "$session_pid" ]] \
&& kill -0 "$session_pid" 2>/dev/null ; then
break
fi
sleep 1
(( --wait_left ))
done
if (( wait_left == 0 )) ; then
print_error "Wine session unavailable after ${session_wait_seconds} seconds"
return 2
fi
source "$session_env" || return 1
PATH_TO_GAME="${WINEPREFIX}/drive_c"
[[ -d "$PATH_TO_GAME" ]] || return 1
unset LAUNCH_PARAMETERS PW_RUN_AFTER_EXE PW_RUN_GAMESCOPE PW_USE_TERMINAL
PW_TMPFS_PATH="$(mktemp -d "$session_dir/tool.XXXXXX")" || return 1
export PW_TMPFS_PATH
export PW_LOG_FILE="$PW_TMPFS_PATH/wine.log"
[[ "$tool" == cmd ]] && PW_USE_TERMINAL=1
[[ "$tool" == winecfg || "$tool" == regedit ]] && export GST_PLUGIN_SYSTEM_PATH_1_0=""
pw_run "$tool" || return 1
}
pw_launch_wrapper () {
if [[ -z "${PW_RUN_AFTER_EXE:-}" ]] ; then
"$@"
+31 -36
View File
@@ -67,6 +67,21 @@ export PW_LOG_FILE="${PORT_DATA_PATH}/PortProton.log"
# shellcheck source=/dev/null
source "$PORT_SCRIPTS_PATH/functions_helper"
if [[ "${1:-}" == "cli" && "${2:-}" == "--wine-session-tool" ]] ; then
session_unavailable_status=2
session_wait_seconds=30
[[ -n "${4:-}" && -n "${5:-}" ]] && session_wait_seconds=1
if pw_session_tool "${3:-}" "$session_wait_seconds" ; then
exit 0
else
session_tool_status=$?
fi
if [[ "$session_tool_status" != "$session_unavailable_status" || -z "${4:-}" || -z "${5:-}" ]] ; then
python_module dbus_tools notify -i error "Wine" "Failed to start Wine tool: ${3:-}" &>/dev/null
exit 1
fi
fi
export PORT_WINE_TMP_PATH="${PORT_DATA_PATH}/data/tmp"
create_new_dir "$PORT_WINE_TMP_PATH"
rm -f "$PORT_WINE_TMP_PATH"/*.{exe,msi,tar}*
@@ -280,11 +295,7 @@ case "$1" in
--show-ppdb Show the content of .ppdb file for specified .exe file
--backup-prefix Backup specified prefix to a file
--restore-prefix Restore prefix from backup file
--winefile Open wine file explorer, requires WINE version and prefix name
--winecfg Open wine configuration, requires WINE version and prefix name
--winecmd Open wine command prompt, requires WINE version and prefix name
--winereg Open wine registry editor, requires WINE version and prefix name
--wine_uninstaller Open wine uninstaller, requires WINE version and prefix name
--wine-session-tool Open a Wine tool in the current session, or use optional WINE and prefix
--winetricks-list-all List winetricks DLLs, fonts, and settings
--winetricks-install Install winetricks items, requires WINE version and prefix name
--clear_pfx Clear specified prefix, requires WINE version and prefix name
@@ -300,7 +311,7 @@ Usage examples:
portproton cli --del-user-conf PW_MANGOHUD
portproton cli --backup-prefix DEFAULT /path/to/backup/directory
portproton cli --restore-prefix /path/to/backup/file.ppack
portproton cli --winecfg WINE_LG DEFAULT
portproton cli --wine-session-tool winecfg WINE_LG DEFAULT
portproton cli --winetricks-list-all WINE_LG DEFAULT
portproton cli --winetricks-install WINE_LG DEFAULT --no-force corefonts
portproton cli --mangohud-preview \"fps,frametime,cpu_temp,gpu_temp\"
@@ -462,37 +473,21 @@ Usage examples:
pw_unpack_prefix "$2"
exit $?
;;
--winefile)
get_wine_and_pfx "$2" "$3"
--wine-session-tool)
tool="$2"
case "$tool" in
winefile|taskmgr|winecfg|regedit|cmd|uninstaller) ;;
*) print_error "Unsupported Wine tool: $tool" ; exit 1 ;;
esac
get_wine_and_pfx "$3" "$4"
start_portproton
pw_run winefile
stop_portproton
;;
--winecfg)
get_wine_and_pfx "$2" "$3"
start_portproton
export GST_PLUGIN_SYSTEM_PATH_1_0=""
pw_run winecfg
stop_portproton
;;
--winecmd)
get_wine_and_pfx "$2" "$3"
start_portproton
cd "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c" || fatal "Prefix drive_c directory not found"
PW_USE_TERMINAL=1 pw_run cmd
stop_portproton
;;
--winereg)
get_wine_and_pfx "$2" "$3"
start_portproton
export GST_PLUGIN_SYSTEM_PATH_1_0=""
pw_run regedit
stop_portproton
;;
--wine_uninstaller)
get_wine_and_pfx "$2" "$3"
start_portproton
pw_run uninstaller
[[ "$tool" == winecfg || "$tool" == regedit ]] && export GST_PLUGIN_SYSTEM_PATH_1_0=""
if [[ "$tool" == cmd ]] ; then
cd "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c" || fatal "Prefix drive_c directory not found"
PW_USE_TERMINAL=1 pw_run "$tool"
else
pw_run "$tool"
fi
stop_portproton
;;
--winetricks-list-all)
-1
View File
@@ -1,6 +1,5 @@
#!/usr/bin/env bash
# Generate shell completion files for bash, zsh, and fish
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-101
View File
@@ -1,101 +0,0 @@
# macOS support (source installation)
The native macOS path uses macOS Wine builds, not the Linux PortProton runtime.
Linux continues to use the existing PortProton scripts. This is an unsigned source
installation, **not** a signed/notarized `.app` or a claim of macOS hardware testing.
## Build and run
Install Python 3.11 or newer, Xcode Command Line Tools, Meson, Ninja, pkg-config,
SDL3 and libarchive. With Homebrew, the native libraries/build tools are available
as `sdl3`, `libarchive`, `meson`, `ninja`, and `pkgconf`. Install the project's Python
dependencies in a virtual environment using the existing project workflow. Ensure
libarchive and SDL3 are discoverable by the dynamic loader/pkg-config; Homebrew's
Apple Silicon prefix is usually `/opt/homebrew`, Intel's is usually `/usr/local`.
Build/install with the virtual environment's Python, for example:
```sh
meson setup builddir --prefix="$VIRTUAL_ENV"
meson compile -C builddir
meson install -C builddir
portprotonqt
```
Meson builds `libportprotonqt_gamepad.dylib` against SDL3 and installs it beside the
Python modules. The Linux Vulkan GPU inspection executable is not built on macOS.
Running directly from an unbuilt checkout still requires the native gamepad
library; do not rename a Linux `.so` to `.dylib`. A distributor must separately
bundle Python/Qt/SDL3/libarchive, set appropriate install names/rpaths, handle
architecture-specific dependencies, and sign/notarize the completed application.
No `.app` packaging, signing identity, or Gatekeeper bypass is supplied here.
## Supported workflow
* Start the application without installing or running the Linux bootstrap.
* Use the existing Wine manager to browse the macOS catalog directly from
<https://git.linux-gaming.ru/Boria138/PortProton-Wine-Metadata/raw/branch/main/macos_wine_metadata.json>.
The catalog groups include Wine Crossover, macOS Wine builds, Sikarugir engines,
and Game Porting Toolkit engines. Catalog inclusion is not a compatibility
guarantee; review each upstream project's license and macOS/CPU requirements.
* Install each catalog version in its own managed directory. Archive extraction
retains the existing traversal/link checks. Plain `bin/wine[64]`, common Wine
`.app` layouts, and `wswine.bundle/bin/wine[64]` are recognized. Entries whose
archive layout does not expose one of those binaries cannot be launched.
* Select installed Wine versions and prefixes in the existing game settings.
Wine/prefix settings are the supported macOS game settings. Linux graphics,
synchronization and anticheat overrides are not silently applied.
* Launch Windows EXEs through the existing game/EXE UI and its owned process
tracking, or directly through the native adapter:
```sh
python -m portprotonqt.macos '/path/to/Game.exe' 'argument with spaces'
```
The adapter preserves arguments without a shell and replaces its own process
with Wine, allowing the normal launcher stop/shutdown path to own the process.
Wine configuration, registry editor, file manager, command prompt and uninstaller
use the selected engine and prefix through the Wine tab. Tool processes are
retained and terminated/waited during application shutdown.
* Remove installed engines through the existing installed-versions manager.
The default data directory is
`~/Library/Application Support/PortProtonQt`; an explicit `PORT_DATA_PATH` overrides
it. Engines live under `data/dist/<catalog name>`, prefixes under
`data/prefixes/<prefix name>`, and global Wine settings in `data/user.conf`.
Per-EXE settings remain `<executable>.ppdb`. Configuration values are parsed as
assignments, never sourced as shell code. If no engine is selected, the adapter
uses the first usable managed engine or `wine` on PATH; an explicitly selected
missing engine fails rather than launching another engine unexpectedly.
On Apple Silicon, x86_64 Wine builds generally require Rosetta 2 and a compatible
macOS release. Install Rosetta using Apple's documented workflow if required.
This project does not install it, choose a CPU architecture automatically, or
make incompatible Wine distributions compatible. No private, machine-specific
application bundle is used. NTLM-enabled applications may additionally need an
upstream-supported `ntlm_auth` installation (for example Samba).
## Limits and verification
Linux D-Bus/system management is disabled on macOS; system power, audio, Bluetooth,
network and storage controls are not ported. SDL gamepad navigation remains available,
but Linux `/dev/uinput` virtual-mouse emulation is disabled. Linux PortProton autoinstall scripts,
runtime downloads, Gamescope, MangoHud, vkBasalt, Linux Steam compatibility-tool
registration, Linux XDG autostart, ISO mounting and store-specific Wine wrappers
are not supported macOS workflows. Use local EXEs and macOS Wine engines. Basic
Wine tools are supported, but prefix reset/default-prefix copying and Linux
runtime-specific tools are not. Unsupported native-adapter CLI operations fail
with an error rather than executing Linux scripts.
The current macOS catalog supplies URLs and human-readable sizes, **not SHA256
checksums**. Downloads use HTTPS and existing extraction checks; this is not
cryptographic artifact verification. Failed/partial extractions may remain for
inspection and can be retried or removed; they count as installed only if a usable
Wine executable is present.
Regression tests mock the host, catalog network, executable handoff, settings and
shutdown. Linux CI cannot validate Mach-O loading, Rosetta, Wine runtime behavior,
Qt appearance, signing or actual macOS gameplay. Those require a real macOS
installation and remain release validation work.
Assisted-by: pz:gpt-6.1-sol
-3
View File
@@ -57,7 +57,6 @@ install_data(configured_portprotonqt,
rename: 'portprotonqt',
)
if host_machine.system() != 'darwin'
# Build and install vk_gpu_info executable
vk_gpu_info_sources = files('build-aux/src/vk_gpu_info.c')
vk_gpu_info_deps = [dependency('vulkan', required: true)]
@@ -70,8 +69,6 @@ executable('vk_gpu_info',
c_args: ['-std=c99'],
)
endif
# Install desktop file
install_data(
'build-aux/share/applications/ru.linux_gaming.PortProtonQt.desktop',
+8 -9
View File
@@ -816,14 +816,13 @@ def main():
except (OSError, RequestException):
logger.exception("Failed to update gogdl")
if sys.platform != "darwin":
gogdl_update_worker = GOGDLUpdateWorker(window.gog_api)
window.gogdlUpdateWorker = gogdl_update_worker
gogdl_update_worker.finished.connect(
lambda: setattr(window, "gogdlUpdateWorker", None)
)
gogdl_update_worker.finished.connect(gogdl_update_worker.deleteLater)
gogdl_update_worker.start()
gogdl_update_worker = GOGDLUpdateWorker(window.gog_api)
window.gogdlUpdateWorker = gogdl_update_worker
gogdl_update_worker.finished.connect(
lambda: setattr(window, "gogdlUpdateWorker", None)
)
gogdl_update_worker.finished.connect(gogdl_update_worker.deleteLater)
gogdl_update_worker.start()
# Execute the initial PortProton command after the UI is set up
class InitialCommandWorker(QThread):
@@ -890,7 +889,7 @@ def main():
self.finished.emit()
# Initial setup can stop Wine and must not race a silent game launch.
if start_sh and not silent_game_request and sys.platform != "darwin":
if start_sh and not silent_game_request:
worker = InitialCommandWorker(start_sh)
window.initialCommandWorker = worker
worker.finished.connect(
-6
View File
@@ -410,8 +410,6 @@ def add_steam_compat_tool(force_install: bool = False) -> bool:
Returns:
True if successful, False otherwise
"""
if sys.platform == "darwin":
return False
steam_home = get_steam_home()
if not steam_home:
print("Steam directory not found")
@@ -593,8 +591,6 @@ def reinstall_steam_compat_tool() -> bool:
def remove_steam_compat_tool() -> bool:
"""Remove PortProtonQt Steam compatibility tool from user Steam directory."""
if sys.platform == "darwin":
return False
steam_home = get_steam_home()
if not steam_home:
print("Steam directory not found")
@@ -651,8 +647,6 @@ def reset_settings() -> bool:
def is_steam_compat_tool_installed() -> bool:
"""Check if PortProtonQt is installed as Steam compatibility tool."""
if sys.platform == "darwin":
return False
steam_home = get_steam_home()
if not steam_home:
return False
-9
View File
@@ -114,11 +114,6 @@ def read_portdata_path_from_config() -> str | None:
def get_portproton_location() -> str | None:
"""Return PortProton directory path."""
if sys.platform == "darwin":
from portprotonqt.macos import data_root
root = data_root()
root.mkdir(parents=True, exist_ok=True)
return str(root)
if os.getenv("FLATPAK_ID"):
portdata_path = os.getenv("XDG_DATA_HOME", "").strip()
if portdata_path:
@@ -158,8 +153,6 @@ def save_portdata_path_to_config(portdata_path: str) -> bool:
def get_portproton_scripts_path() -> str | None:
"""Return PortProton scripts directory path."""
if sys.platform == "darwin":
return None
appdir_prefix = os.getenv("APPDIR")
sharun_prefix = os.getenv("SHARUN_DIR")
appimage_path = os.getenv("APPIMAGE", "").strip()
@@ -198,8 +191,6 @@ def get_portproton_scripts_path() -> str | None:
def get_portproton_start_command() -> list[str] | None:
"""Return command list for PortProton launch."""
if sys.platform == "darwin":
return [sys.executable, "-m", "portprotonqt.macos"]
global _portproton_start_command
if _portproton_start_command is not None:
return _portproton_start_command
+2 -7
View File
@@ -1,10 +1,11 @@
"""UI configuration settings."""
import asyncio
import os
import sys
import subprocess
from typing import Any, cast
from dbus_fast import BusType
from dbus_fast.aio import MessageBus
from portprotonqt.config.base import BaseConfig, configparser, THEMES_DIRS
from portprotonqt.config.validators import validate_string, validate_int, validate_bool
@@ -12,10 +13,6 @@ from portprotonqt.localization import get_theme_translations
from portprotonqt.logger import get_logger
if sys.platform != "darwin":
from dbus_fast import BusType
from dbus_fast.aio import MessageBus
logger = get_logger(__name__)
THEME_VARIANTS = ("dark", "light", "auto")
DOWNLOADS_SECTION = "Downloads"
@@ -207,8 +204,6 @@ def _is_qt_light_theme() -> bool:
def _is_system_light_theme() -> bool:
if sys.platform == "darwin":
return _is_qt_light_theme()
is_dark = _is_portal_dark_theme()
if is_dark is None:
is_dark = _is_gsettings_dark_theme()
-3
View File
@@ -1,7 +1,6 @@
"""Detail pages for PortProtonQt."""
import os
import sys
import weakref
from collections.abc import Callable, Sequence
@@ -617,8 +616,6 @@ class DetailPageManager:
play_button.setIcon(
self.main_window.theme_manager.get_icon("update", as_path=True)
)
if sys.platform == "darwin" and source in {"gog", "egs"}:
play_button.setEnabled(False)
buttons_layout.addWidget(play_button)
if source in {"steam", "gog", "egs"} and appid:
+3 -16
View File
@@ -1,8 +1,6 @@
"""Proton Manager dialog for PortProtonQt."""
import os
import sys
from pathlib import Path
import platform
import shutil
import tempfile
@@ -376,8 +374,6 @@ class ProtonManager(DraggableDialog):
return True
def filter_entries_by_cpu_level(self, entries, source_name):
if sys.platform == "darwin":
return entries
is_arm = platform.machine().lower().startswith(('arm', 'aarch64'))
filtered_entries = []
for entry in entries:
@@ -475,7 +471,7 @@ class ProtonManager(DraggableDialog):
url = entry.get('url', '')
filename = entry.get('name', '')
size_human = entry.get('size_human', _('Unknown'))
if url and sys.platform != "darwin":
if url:
parsed_url = urllib.parse.urlparse(url)
url_filename = os.path.basename(parsed_url.path)
if url_filename:
@@ -543,9 +539,6 @@ class ProtonManager(DraggableDialog):
def is_asset_installed(self, asset_filename, source_name):
if not self.portproton_location:
return False
if sys.platform == "darwin":
from portprotonqt.macos import find_wine, version_directory
return find_wine(version_directory(Path(self.portproton_location), asset_filename)) is not None
name_without_ext = asset_filename
for ext in ['.tar.gz', '.tar.xz']:
if name_without_ext.lower().endswith(ext):
@@ -569,9 +562,6 @@ class ProtonManager(DraggableDialog):
return source == "proton_lg" and (asset.startswith("wine"))
def get_download_extract_dir(self, asset_data: dict) -> str:
if sys.platform == "darwin":
from portprotonqt.macos import version_directory
return str(version_directory(Path(self.portproton_location), asset_data["asset_name"]))
install_to_dist = self.should_install_to_dist(
asset_data['source_name'], asset_data['asset_name']
)
@@ -639,7 +629,7 @@ class ProtonManager(DraggableDialog):
installed_versions = []
seen_paths = set()
version_dirs = [dist_path]
if sys.platform != "darwin" and not ui_config.get_disable_steam_proton_scanning():
if not ui_config.get_disable_steam_proton_scanning():
steam_dir = get_steam_compatibilitytools_dir()
if steam_dir is not None:
version_dirs.append(str(steam_dir))
@@ -663,9 +653,6 @@ class ProtonManager(DraggableDialog):
return installed_versions
def is_installed_version_dir(self, version_path: str) -> bool:
if sys.platform == "darwin":
from portprotonqt.macos import find_wine
return not Path(version_path).name.startswith(".") and find_wine(Path(version_path)) is not None
if not os.path.isdir(version_path):
return False
if os.path.isfile(os.path.join(version_path, "bin", "wine")):
@@ -1036,7 +1023,7 @@ class ProtonManager(DraggableDialog):
import subprocess
try:
start_cmd = get_portproton_start_command()
if start_cmd and not self.initial_command_executed and sys.platform != "darwin":
if start_cmd and not self.initial_command_executed:
result = subprocess.run(start_cmd + ["cli", "--initial"], timeout=10)
if result.returncode != 0:
logger.warning(f"Initial PortProton command returned non-zero exit code: {result.returncode}")
+4 -6
View File
@@ -1,7 +1,6 @@
"""Settings dialog for PortProtonQt."""
import os
import sys
import re
import subprocess
from html import escape
@@ -419,11 +418,10 @@ class ExeSettingsDialog(
self.tab_widget.addTab(self.main_tab, _("Main"))
self.tab_widget.addTab(self.advanced_tab, _("Advanced"))
if sys.platform != "darwin":
self.tab_widget.addTab(self.mangohud_tab, "MangoHud")
self.tab_widget.addTab(self.vkbasalt_tab, "vkBasalt")
if self.gamescope_available:
self.tab_widget.addTab(self.gamescope_tab, "Gamescope")
self.tab_widget.addTab(self.mangohud_tab, "MangoHud")
self.tab_widget.addTab(self.vkbasalt_tab, "vkBasalt")
if self.gamescope_available:
self.tab_widget.addTab(self.gamescope_tab, "Gamescope")
self.settings_table = QTableWidget()
self.settings_table.setAlternatingRowColors(True)
-21
View File
@@ -1,9 +1,6 @@
"""Wine archive extractor for PortProtonQt."""
import os
import sys
import shutil
import tempfile
import time
import libarchive
from PySide6.QtCore import QThread, Signal, QMutex
@@ -49,13 +46,7 @@ class ExtractionThread(QThread):
return target_path
def run(self):
destination = self.extract_dir
staging = None
try:
if sys.platform == "darwin":
os.makedirs(os.path.dirname(destination), exist_ok=True)
staging = tempfile.mkdtemp(prefix=".wine-install-", dir=os.path.dirname(destination))
self.extract_dir = staging
self.progress.emit(0)
self.speed.emit(0.0)
self.eta.emit(0)
@@ -166,14 +157,6 @@ class ExtractionThread(QThread):
except (OSError, PermissionError):
pass
if self._should_stop():
return
if staging is not None:
from pathlib import Path
from portprotonqt.macos import find_wine
if find_wine(Path(staging)) is None:
raise ValueError("Archive does not contain a macOS Wine executable")
os.rename(staging, destination)
self.progress.emit(100)
self.speed.emit(0.0)
self.eta.emit(0)
@@ -185,10 +168,6 @@ class ExtractionThread(QThread):
except Exception as e:
if not self._should_stop():
self.error.emit(str(e))
finally:
self.extract_dir = destination
if staging is not None:
shutil.rmtree(staging, ignore_errors=True)
def stop(self):
self._mutex.lock()
-8
View File
@@ -1,7 +1,6 @@
"""Wine metadata loader for PortProtonQt."""
import os
import sys
import tempfile
import orjson
@@ -105,10 +104,6 @@ class WineLoadingThread(QThread):
else github_url
)
if sys.platform == "darwin":
from portprotonqt.macos import MACOS_WINE_METADATA_URL
json_url = MACOS_WINE_METADATA_URL
with tempfile.NamedTemporaryFile(delete=False, suffix='.json') as tmp:
temp_path = tmp.name
@@ -125,9 +120,6 @@ class WineLoadingThread(QThread):
with open(temp_path, 'rb') as f:
metadata = orjson.loads(f.read())
if sys.platform == "darwin":
from portprotonqt.macos import validate_catalog
validate_catalog(metadata)
logger.info(f"Successfully loaded JSON metadata with {len(metadata)} entries")
self.loading_complete.emit(metadata)
finally:
+2 -11
View File
@@ -1,10 +1,8 @@
from __future__ import annotations
import time
import os
import sys
import math
from typing import TYPE_CHECKING, Protocol, cast, Any
from typing import Protocol, cast, Any
from evdev import UInput, ecodes
from PySide6.QtWidgets import QWidget, QStackedWidget, QApplication, QScrollArea, QMenu, QMessageBox, QTableWidget, QSlider
from PySide6.QtCore import Qt, QObject, Signal, Slot, QTimer, QThread
from portprotonqt.logger import get_logger
@@ -29,9 +27,6 @@ from portprotonqt.input_manager.runtime import GamepadRuntimeMixin
from portprotonqt.input_manager.settings import SettingsInputMixin
from portprotonqt.input_manager.settings_visual import SettingsVisualNavigationMixin
if sys.platform != "darwin" or TYPE_CHECKING:
from evdev import UInput, ecodes
logger = get_logger(__name__)
class MainWindowProtocol(Protocol):
@@ -258,10 +253,6 @@ class InputManager(
def _async_enable_mouse_emulation(self):
"""Asynchronously enable mouse emulation to avoid blocking startup."""
if sys.platform == "darwin":
self.mouse_emulation_enabled = False
logger.info("Virtual mouse emulation is Linux-only")
return
logger.info("EMUL: Attempting to create UInput virtual mouse...")
self.mouse_emulation_thread = MouseEmulationThread()
self.mouse_emulation_thread.finished.connect(self._on_mouse_emulation_finished)
-193
View File
@@ -1,193 +0,0 @@
"""Native macOS Wine launching; Linux PortProton scripts are not used."""
import os
from pathlib import Path
import re
import shlex
import shutil
import sys
import tempfile
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
MACOS_WINE_METADATA_URL = (
"https://git.linux-gaming.ru/Boria138/PortProton-Wine-Metadata/"
"raw/branch/main/macos_wine_metadata.json"
)
WINE_TOOLS = {
"--winecfg": "winecfg", "--winereg": "regedit", "--winecmd": "cmd",
"--winefile": "winefile", "--wine_uninstaller": "uninstaller",
}
def data_root() -> Path:
"""Respect explicit data paths, otherwise use macOS Application Support."""
explicit = os.environ.get("PORT_DATA_PATH")
if explicit:
return Path(explicit).expanduser()
return Path.home() / "Library" / "Application Support" / "PortProtonQt"
def version_directory(root: Path, name: str) -> Path:
"""Keep catalog version names inside the managed distribution directory."""
if not name or name in (".", "..") or Path(name).name != name:
raise ValueError(f"Invalid Wine version name: {name}")
destination = root / "data" / "dist" / name
if not destination.resolve().is_relative_to((root / "data" / "dist").resolve()):
raise ValueError(f"Wine version escapes distribution directory: {name}")
return destination
def validate_catalog(metadata: object) -> None:
"""Reject unsafe remote names before they become download paths."""
if not isinstance(metadata, dict):
raise ValueError("Invalid macOS Wine catalog")
for entries in metadata.values():
if not isinstance(entries, list):
raise ValueError("Invalid macOS Wine catalog entries")
for entry in entries:
if not isinstance(entry, dict) or not isinstance(entry.get("name"), str):
raise ValueError("Invalid macOS Wine version")
version_directory(data_root(), entry["name"])
if not isinstance(entry.get("url"), str) or not entry["url"].startswith("https://"):
raise ValueError("macOS Wine downloads require HTTPS")
def find_wine(version: Path) -> Path | None:
"""Find Wine in supported plain, application and Wine wrapper layouts."""
candidates = [version / "bin" / "wine", version / "bin" / "wine64"]
candidates.extend(version.glob("Contents/Resources/wine/bin/wine*"))
candidates.extend(version.glob("*.app/Contents/Resources/wine/bin/wine*"))
candidates.extend(version.glob("*.app/Contents/Resources/wine*/bin/wine64"))
candidates.extend(version.glob("wswine.bundle/bin/wine*"))
candidates.extend(version.glob("*/bin/wine*"))
candidates.extend(version.glob("*.app/Contents/SharedSupport/wine/bin/wine*"))
return next((path for path in candidates if path.name in ("wine", "wine64")
and path.is_file() and os.access(path, os.X_OK)), None)
def read_settings(path: Path) -> dict[str, str]:
"""Read shell-style assignments as data, never execute configuration."""
if not path.exists():
return {}
values = {}
for line in path.read_text(encoding="utf-8").splitlines():
fields = shlex.split(line, comments=True)
if fields and fields[0] == "export":
fields = fields[1:]
if len(fields) == 1 and "=" in fields[0]:
key, value = fields[0].split("=", 1)
values[key] = value
return values
def write_settings(path: Path, values: dict[str, str]) -> None:
"""Persist macOS settings without evaluating shell expressions."""
for key, value in values.items():
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key):
raise ValueError(f"Invalid setting name: {key}")
if "\n" in value or "\r" in value:
raise ValueError(f"Setting must contain a single line: {key}")
path.parent.mkdir(parents=True, exist_ok=True)
temporary = None
try:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8",
dir=path.parent, delete=False) as output:
temporary = Path(output.name)
output.write("".join(f"export {key}={shlex.quote(value)}\n"
for key, value in values.items()))
os.replace(temporary, path)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
def wine_command(root: Path, arguments: list[str], settings: dict[str, str]) -> tuple[list[str], dict[str, str]]:
"""Build the native Wine command and isolated prefix environment."""
version = settings.get("PW_WINE_USE") or settings.get("PW_DEFAULT_WINE_USE", "")
system_wine = version == "USE_SYSTEM_WINE"
wine = find_wine(version_directory(root, version)) if version and not system_wine else None
if wine is None and not version:
wine = next((found for child in sorted((root / "data" / "dist").glob("*"))
if not child.name.startswith(".") and (found := find_wine(child)) is not None), None)
executable = str(wine) if wine else (shutil.which("wine") if not version or system_wine else None)
if not executable:
raise FileNotFoundError("Install and select a macOS Wine version in the Wine manager")
prefix = settings.get("PW_PREFIX_NAME") or settings.get("PW_DEFAULT_PREFIX_NAME") or "DEFAULT"
if Path(prefix).name != prefix or prefix in (".", ".."):
raise ValueError("Invalid Wine prefix name")
prefix_path = root / "data" / "prefixes" / prefix
if not prefix_path.resolve().is_relative_to((root / "data" / "prefixes").resolve()):
raise ValueError("Wine prefix escapes prefix directory")
prefix_path.mkdir(parents=True, exist_ok=True)
environment = os.environ.copy()
environment["WINEPREFIX"] = str(prefix_path)
environment["PATH"] = str(Path(executable).parent) + os.pathsep + environment.get("PATH", "")
return [executable, *arguments], environment
def settings_command(root: Path, arguments: list[str]) -> bool:
"""Implement settings operations used by the existing settings dialog."""
action = arguments[0]
user_conf = root / "data" / "user.conf"
path = Path(arguments[1] + ".ppdb") if action in ("--show-ppdb", "--edit-db") else user_conf
values = read_settings(path)
if action in ("--get-user-conf", "--show-ppdb"):
if action == "--get-user-conf" and len(arguments) > 1:
sys.stdout.write(values.get(arguments[1], "") + "\n")
else:
sys.stdout.write("".join(f'{key}="{value}"\n' for key, value in values.items()))
elif action == "--edit-db":
for change in arguments[2:]:
key, value = change.split("=", 1)
values[key] = value
write_settings(path, values)
elif action == "--set-user-conf":
values[arguments[1]] = arguments[2]
write_settings(path, values)
elif action == "--delete-user-conf":
values.pop(arguments[1], None)
write_settings(path, values)
else:
return False
return True
def main(arguments: list[str] | None = None) -> int:
"""Run the native adapter through the existing PortProton command interface."""
arguments = list(sys.argv[1:] if arguments is None else arguments)
root = data_root()
try:
if not arguments:
raise ValueError("An executable or Wine tool is required")
settings = read_settings(root / "data" / "user.conf")
if arguments[0] == "cli":
arguments = arguments[1:]
if not arguments:
raise ValueError("A CLI operation is required")
if settings_command(root, arguments):
return 0
tool = WINE_TOOLS.get(arguments[0])
if not tool or len(arguments) != 3:
raise ValueError(f"Unsupported macOS operation: {arguments[0]}")
settings.update(PW_WINE_USE=arguments[1], PW_PREFIX_NAME=arguments[2])
arguments = [tool]
else:
settings.update(read_settings(Path(arguments[0] + ".ppdb")))
target = Path(arguments[0]).expanduser().resolve(strict=True)
arguments[0] = str(target)
dispatch = {".msi": ["msiexec", "/i"], ".bat": ["cmd", "/c"],
".cmd": ["cmd", "/c"], ".reg": ["regedit"]}
arguments = [*dispatch.get(target.suffix.lower(), []), *arguments]
os.chdir(target.parent)
command, environment = wine_command(root, arguments, settings)
os.execvpe(command[0], command, environment)
except (OSError, ValueError, IndexError) as error:
logger.error("macOS Wine operation failed: %s", error)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+4 -32
View File
@@ -343,7 +343,7 @@ class MainWindow(
self.setWindowTitle(f"{app_name} {version}")
self.setMinimumSize(890, 600)
self._pending_resolution = resolution # Store resolution for later application
self._show_system_tab = show_system_tab and sys.platform != "darwin"
self._show_system_tab = show_system_tab
self.system_tab_index = -1 # Default, set when system tab is created
self._animated_covers_suspended = False
@@ -2488,7 +2488,7 @@ class MainWindow(
return extract_exec_target_path(exec_line) or ""
def _has_running_game_process(self) -> bool:
if sys.platform == "darwin" or getattr(self, "native_game_running", False):
if getattr(self, "native_game_running", False):
if any(process.poll() is None for process in self.game_processes):
return True
groups = {process.pid for process in self.game_processes}
@@ -2695,17 +2695,6 @@ class MainWindow(
def _terminate_game_processes(self) -> None:
for proc in self.game_processes:
if sys.platform == "darwin":
try:
os.killpg(proc.pid, signal.SIGKILL)
proc.wait(timeout=0)
except ProcessLookupError:
proc.poll()
except subprocess.TimeoutExpired:
logger.debug("macOS Wine process %s is still exiting", proc.pid)
except OSError as error:
logger.warning("Failed to stop macOS Wine process group %s: %s", proc.pid, error)
continue
if proc.poll() is not None and not getattr(self, "native_game_running", False):
continue
try:
@@ -2719,8 +2708,6 @@ class MainWindow(
def _run_portproton_stop_command(self) -> bool:
"""Run PortProton CLI stop command."""
if sys.platform == "darwin":
return True
if not self.start_sh:
logger.warning("PortProton start command is unavailable for stop")
return False
@@ -2740,16 +2727,13 @@ class MainWindow(
if getattr(self, "native_game_running", False):
self._terminate_game_processes()
return True
if sys.platform != "darwin" and getattr(self, "launcher_process_only", False):
if getattr(self, "launcher_process_only", False):
if self._run_portproton_stop_command():
return True
if sys.platform != "darwin":
self._analyze_short_launch()
self._analyze_short_launch()
self._terminate_game_processes()
if sys.platform == "darwin":
return not any(proc.poll() is None for proc in self.game_processes)
self.game_processes = []
stopped = self._run_portproton_stop_command()
if hasattr(self, 'checkProcessTimer') and self.checkProcessTimer is not None:
@@ -2761,8 +2745,6 @@ class MainWindow(
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
if not prefix_name or not self.portproton_location:
return
@@ -2784,8 +2766,6 @@ class MainWindow(
def _check_missing_prefix_before_launch(self, game_exe_path: str, env_vars: dict[str, str]) -> None:
"""Check game prefix and optionally disable default recommended libs."""
if sys.platform == "darwin":
return
if not game_exe_path:
return
@@ -3271,10 +3251,6 @@ class MainWindow(
return True
def _launch_egs_game(self, app_id: str, button=None) -> None:
if sys.platform == "darwin":
self._finish_silent_launch()
QMessageBox.warning(self, _("Error"), "Epic store launch wrappers are not supported on macOS. Open the installed Windows executable directly.")
return
target = self.egs_api.get_launch_target(app_id)
if not target:
self._finish_silent_launch()
@@ -3342,10 +3318,6 @@ class MainWindow(
def _launch_gog_game(
self, app_id: str, button=None, play_sound: bool = True
) -> None:
if sys.platform == "darwin":
self._finish_silent_launch()
QMessageBox.warning(self, _("Error"), "GOG store launch wrappers are not supported on macOS. Open the installed Windows executable directly.")
return
self.gog_api.ensure_launch_parameters(app_id)
discovered_path = self.gog_api.get_installed_path(app_id)
install_path = str(discovered_path) if discovered_path else ""
-1
View File
@@ -1,7 +1,6 @@
# Install Python source files
install_data(
['__init__.py',
'macos.py',
'appimage_integration.py',
'appimage_updater.py',
'cli.py',
+1 -2
View File
@@ -1,9 +1,8 @@
import ctypes
import sys
from dataclasses import dataclass
from pathlib import Path
GAMEPAD_LIBRARY_NAME = "libportprotonqt_gamepad.dylib" if sys.platform == "darwin" else "libportprotonqt_gamepad.so"
GAMEPAD_LIBRARY_NAME = "libportprotonqt_gamepad.so"
SYSTEM_GAMEPAD_LIBRARY = Path(__file__).parent / GAMEPAD_LIBRARY_NAME
DEV_GAMEPAD_LIBRARY = (
Path(__file__).parent.parent / "build-aux" / "lib" / GAMEPAD_LIBRARY_NAME
@@ -18,11 +18,6 @@ MOUNT_ESCAPE_PATTERN = re.compile(r"\\([0-7]{3})")
def list_mounted_drive_paths(mounts_path: str = "/proc/mounts") -> list[str]:
"""Return local mounted drive paths available to the user."""
if sys.platform == "darwin":
from pathlib import Path
volumes = Path("/Volumes")
return sorted(str(path) for path in volumes.iterdir()
if path.is_dir() and os.access(path, os.R_OK)) if volumes.is_dir() else []
try:
mounts = _read_mounts(mounts_path)
mounted_drives = set()
-13
View File
@@ -1,5 +1,4 @@
import os
import sys
import shutil
import subprocess
from pathlib import Path
@@ -59,13 +58,6 @@ def get_available_wine_options(
key=version_sort_key
)
if sys.platform == "darwin":
from portprotonqt.macos import find_wine
options = [name for name in options if find_wine(Path(dist_dir, name)) is not None]
if system_wine_label and shutil.which("wine"):
options.append(system_wine_label)
return options
from portprotonqt.config import get_portproton_scripts_path
scripts_path = get_portproton_scripts_path()
if scripts_path:
@@ -151,8 +143,6 @@ def get_toggle_settings():
"""Get predefined toggle settings with descriptions."""
from portprotonqt.localization import _
if sys.platform == "darwin":
return {}
return {
# Graphics enhancements
'PW_DGVOODOO2': _("Enable dgVoodoo2. Forced use all dgVoodoo2 libs (Glide 2.11-3.1, DirectDraw 1-7, Direct3D 2-9) on all 3D API."),
@@ -404,9 +394,6 @@ def get_advanced_settings(disabled_text, logical_core_options=None, locale_optio
'default': disabled_text
})
if sys.platform == "darwin":
return [setting for setting in advanced_settings
if setting["key"] in ("PW_WINE_USE", "PW_PREFIX_NAME")]
return advanced_settings
# Keys that should be recognized as advanced settings
-1
View File
@@ -16,7 +16,6 @@ from portprotonqt.image_utils import COVER_IMAGE_EXTENSIONS
logger = get_logger(__name__)
STEAM_DATA_DIRS = (
"~/Library/Application Support/Steam",
"~/.steam/steam",
"~/snap/steam/common/.local/share/Steam",
"~/.var/app/com.valvesoftware.Steam/data/Steam",
+10 -21
View File
@@ -1,5 +1,4 @@
import os
import sys
from typing import TYPE_CHECKING, Any
from PySide6.QtCore import QObject, QRect, QSize, Qt, QTimer
@@ -230,9 +229,6 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
self.egsAccountTitle.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
gogForm.addRow(self.egsAccountTitle, egs_buttons)
self._update_egs_account_state()
if sys.platform == "darwin":
self.gogLoginButton.setEnabled(False)
self.egsLoginButton.setEnabled(False)
self.timeDetailCombo = CustomComboBox(theme=self.theme)
self.timeDetailCombo.view().window().setWindowFlags(
@@ -411,8 +407,6 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
autostart_layout.addWidget(self.autostartTitle)
autostart_layout.addStretch()
uiForm.addRow(autostart_layout)
if sys.platform == "darwin":
uiForm.setRowVisible(autostart_layout, False)
self.startMinimizedCheckBox = QCheckBox()
self.startMinimizedCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
@@ -571,7 +565,7 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
uiForm.addRow(disable_alt_dependency_check_layout)
disable_runtime_download_layout = None
if sys.platform != "darwin" and not os.getenv("FLATPAK_ID"):
if not os.getenv("FLATPAK_ID"):
self.disableRuntimeDownloadCheckBox = QCheckBox()
self.disableRuntimeDownloadCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
self.disableRuntimeDownloadCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -602,8 +596,6 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
steam_compat_layout.addWidget(self.steamCompatTitle)
steam_compat_layout.addStretch()
uiForm.addRow(steam_compat_layout)
if sys.platform == "darwin":
uiForm.setRowVisible(steam_compat_layout, False)
self.disableSteamProtonScanningCheckBox = QCheckBox()
self.disableSteamProtonScanningCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
@@ -619,10 +611,8 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
disable_steam_proton_scanning_layout.addWidget(self.disableSteamProtonScanningTitle)
disable_steam_proton_scanning_layout.addStretch()
uiForm.addRow(disable_steam_proton_scanning_layout)
if sys.platform == "darwin":
uiForm.setRowVisible(disable_steam_proton_scanning_layout, False)
if sys.platform != "darwin" and get_steam_compatibilitytools_dir() is not None:
if get_steam_compatibilitytools_dir() is not None:
self.downloadWineToSteamCheckBox = QCheckBox()
self.downloadWineToSteamCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
self.downloadWineToSteamCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -779,7 +769,7 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
hwForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(hwFrame)
filtered_gpu_list = [] if sys.platform == "darwin" else get_selectable_gpu_list()
filtered_gpu_list = get_selectable_gpu_list()
hwFrame.setVisible(len(filtered_gpu_list) > 1)
if len(filtered_gpu_list) > 1:
self.gpuCombo = CustomComboBox(theme=self.theme)
@@ -1116,7 +1106,7 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
autostart_enabled = self.autostartCheckBox.isChecked()
display_config.set_autostart_enabled(autostart_enabled)
if sys.platform != "darwin" and not apply_xdg_autostart(autostart_enabled):
if not apply_xdg_autostart(autostart_enabled):
QMessageBox.warning(self, _("Error"), _("Failed to update xdg-autostart entry."))
start_minimized = self.startMinimizedCheckBox.isChecked()
@@ -1126,13 +1116,12 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
tray_menu_mode = self.tray_menu_mode_keys[tray_menu_mode_idx]
display_config.set_tray_menu_mode(tray_menu_mode)
if sys.platform != "darwin":
steam_compat = self.steamCompatCheckBox.isChecked()
currently_installed = is_steam_compat_tool_installed()
if steam_compat and not currently_installed:
add_steam_compat_tool()
elif not steam_compat and currently_installed:
remove_steam_compat_tool()
steam_compat = self.steamCompatCheckBox.isChecked()
currently_installed = is_steam_compat_tool_installed()
if steam_compat and not currently_installed:
add_steam_compat_tool()
elif not steam_compat and currently_installed:
remove_steam_compat_tool()
ui_config.set_disable_steam_proton_scanning(self.disableSteamProtonScanningCheckBox.isChecked())
+6 -8
View File
@@ -1,5 +1,4 @@
import os
import sys
import shlex
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, cast
@@ -37,13 +36,12 @@ from portprotonqt.localization import _
from portprotonqt.logger import get_logger
from portprotonqt.sound_manager import SoundManager
from portprotonqt.preloader import Preloader
if sys.platform != "darwin":
from portprotonqt.system_manager import (
AudioManagerWorker,
BluetoothManagerWorker,
NetworkManagerWorker,
StorageManagerWorker,
)
from portprotonqt.system_manager import (
AudioManagerWorker,
BluetoothManagerWorker,
NetworkManagerWorker,
StorageManagerWorker,
)
logger = get_logger(__name__)
+8 -29
View File
@@ -1,5 +1,4 @@
import os
import sys
import re
import shutil
from typing import TYPE_CHECKING, Any
@@ -153,9 +152,6 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
self.defaultVulkanTitleLabel.setStyleSheet(self.theme.PARAMS_TITLE_STYLE)
self.defaultVulkanTitleLabel.setFocusPolicy(Qt.FocusPolicy.NoFocus)
formLayout.addRow(self.defaultVulkanTitleLabel, self.defaultVulkanCombo)
if sys.platform == "darwin":
self.defaultVulkanTitleLabel.hide()
self.defaultVulkanCombo.hide()
layout.addLayout(formLayout)
@@ -164,11 +160,12 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
tools_grid.setSpacing(6)
tools = [
("--winecfg", _("Wine Configuration")),
("--winereg", _("Registry Editor")),
("--winefile", _("File Explorer")),
("--winecmd", _("Command Prompt")),
("--wine_uninstaller", _("Uninstaller")),
("winecfg", _("Wine Configuration")),
("regedit", _("Registry Editor")),
("winefile", _("File Explorer")),
("cmd", _("Command Prompt")),
("uninstaller", _("Uninstaller")),
("taskmgr", _("Task Manager")),
]
for i, (tool_cmd, tool_name) in enumerate(tools):
@@ -199,9 +196,6 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
(_("Manage WINE versions"), self.show_proton_manager),
]
if sys.platform == "darwin":
additional_buttons = [item for item in additional_buttons
if item[1] == self.show_proton_manager]
for i, (text, callback) in enumerate(additional_buttons):
row = i // 2
col = i % 2
@@ -244,18 +238,12 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
env_vars = os.environ.copy()
self._check_missing_prefix_by_name_before_launch(prefix, env_vars)
start_sh = self.start_sh
cmd = start_sh + ["cli", cli_arg, wine, prefix]
cmd = start_sh + ["cli", "--wine-session-tool", cli_arg, wine, prefix]
# Show progress bar before launch
self.wine_progress_bar.setVisible(True)
proc = QProcess(self)
if sys.platform == "darwin":
proc.setUnixProcessParameters(QProcess.UnixProcessFlag.CreateNewSession)
if not hasattr(self, "wine_tool_processes"):
self.wine_tool_processes = []
self.wine_tool_processes.append(proc)
proc.finished.connect(lambda: self.wine_tool_processes.remove(proc))
process_env = QProcessEnvironment.systemEnvironment()
if env_vars.get("DISABLE_CP_DEFPFX") == "1":
process_env.insert("DISABLE_CP_DEFPFX", "1")
@@ -282,16 +270,7 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
def _check_wine_process(self, cli_arg):
"""Check if target .exe process started."""
exe_map = {
"--winecfg": "winecfg.exe",
"--winereg": "regedit.exe",
"--winefile": "winefile.exe",
"--winecmd": "cmd.exe",
"--wine_uninstaller": "uninstaller.exe",
}
target_exe = exe_map.get(cli_arg, "")
if not target_exe:
return
target_exe = f"{cli_arg}.exe"
# Check processes via psutil
for proc in psutil.process_iter(attrs=["name"]):
-17
View File
@@ -1,7 +1,3 @@
import os
import signal
import sys
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
@@ -20,19 +16,6 @@ class MainWindowWorkersMixin:
if not process.waitForFinished():
process.kill()
process.waitForFinished()
for process in list(getattr(self, "wine_tool_processes", [])):
if sys.platform == "darwin" and process.processId():
try:
os.killpg(process.processId(), signal.SIGKILL)
except ProcessLookupError:
logger.debug("Wine tool process group already exited")
except OSError as error:
logger.warning("Failed to stop Wine tool process group: %s", error)
process.terminate()
if not process.waitForFinished():
process.kill()
process.waitForFinished()
self.wine_tool_processes = []
worker_timeouts = {
"networkWorker": 3000,
"bluetoothWorker": 12000,
+2 -7
View File
@@ -3,13 +3,14 @@ import asyncio
import hashlib
import importlib.util
import os
import sys
import re
import shutil
import stat
import xml.etree.ElementTree as ET
from typing import Any, cast
import orjson
from dbus_fast import BusType
from dbus_fast.aio import MessageBus
from portprotonqt.logger import get_logger
from portprotonqt.theme_security import (
check_theme_directory_safety,
@@ -23,10 +24,6 @@ from portprotonqt.config import CACHE_DIR, ui_config, load_theme_metainfo
from portprotonqt.config.ui import _is_system_light_theme, _unwrap_variant
from portprotonqt.qt_utils import get_device_pixel_ratio
if sys.platform != "darwin":
from dbus_fast import BusType
from dbus_fast.aio import MessageBus
# Icon caching for performance optimization
_icon_cache = {}
# Directory structure cache for performance optimization
@@ -953,8 +950,6 @@ class SystemThemeWatcher(QThread):
self._poll_system_theme()
async def _watch_portal(self) -> None:
if sys.platform == "darwin":
raise OSError("Desktop portal is Linux-only")
bus = await MessageBus(bus_type=BusType.SESSION).connect()
try:
introspection = await bus.introspect(
+40
View File
@@ -3,6 +3,7 @@ import subprocess
import signal
import psutil
import os
from PySide6.QtCore import QProcess
from PySide6.QtWidgets import QSystemTrayIcon, QMenu, QApplication, QMessageBox
from PySide6.QtGui import QIcon, QAction
from portprotonqt.logger import get_logger
@@ -45,6 +46,39 @@ def _restart_args(args: list[str]) -> list[str]:
return restart_args
def create_wine_tools_menu(parent: QMenu, start_sh: list[str]) -> QMenu:
"""Create tools that join the running game's Wine session."""
menu = QMenu("Wine", parent)
tools = (
("winefile", _("File Explorer")),
("taskmgr", _("Task Manager")),
("winecfg", _("Wine Configuration")),
("regedit", _("Registry Editor")),
("cmd", _("Command Prompt")),
("uninstaller", _("Uninstaller")),
)
for tool, title in tools:
action = menu.addAction(title)
action.triggered.connect(
lambda checked=False, name=tool: launch_session_wine_tool(start_sh, name)
)
return menu
def launch_session_wine_tool(start_sh: list[str], tool: str) -> None:
"""Start a Wine tool without running the game's startup or cleanup."""
if not start_sh:
logger.error("Cannot launch Wine tool: PortProton command is missing")
QMessageBox.warning(None, _("Error"), _("Failed to start process."))
return
started, _pid = QProcess.startDetached(
start_sh[0], start_sh[1:] + ["cli", "--wine-session-tool", tool]
)
if not started:
logger.error("Failed to start Wine tool %s", tool)
QMessageBox.warning(None, _("Error"), _("Failed to start process."))
class TrayManager:
"""Tray management module for PortProtonQt.
@@ -83,8 +117,12 @@ class TrayManager:
self.pause_game_action.setEnabled(False)
self.pause_game_action.triggered.connect(self.toggle_game_pause)
self.wine_tools_menu = create_wine_tools_menu(self.tray_menu, self.main_window.start_sh)
self.wine_tools_menu.setEnabled(False)
self.tray_menu.addAction(self.pause_game_action)
self.tray_menu.addAction(self.stop_game_action)
self.tray_menu.addMenu(self.wine_tools_menu)
self.tray_menu.addSeparator()
self.tray_menu.addSeparator()
@@ -103,6 +141,7 @@ class TrayManager:
self.tray_menu.addAction(self.pause_game_action)
self.tray_menu.addAction(self.stop_game_action)
self.tray_menu.addMenu(self.wine_tools_menu)
self.update_game_actions()
if self.minimal_mode:
return
@@ -151,6 +190,7 @@ class TrayManager:
target_exe = getattr(self.main_window, "target_exe", None)
has_running_game = bool(game_processes or target_exe)
self.stop_game_action.setEnabled(has_running_game)
self.wine_tools_menu.setEnabled(has_running_game)
self.pause_game_action.setEnabled(bool(processes))
paused = self._are_processes_paused(processes)
self.pause_game_action.setText(_("Resume Game") if paused else _("Pause Game"))
+1 -1
View File
@@ -23,7 +23,7 @@ classifiers = [
]
dependencies = [
"babel>=2.18.0",
"evdev>=2.0.0; sys_platform == 'linux'",
"evdev>=2.0.0",
"libarchive-c>=5.3",
"orjson>=3.12.0",
"pillow>=12.3.0",
-377
View File
@@ -1,377 +0,0 @@
"""Native macOS Wine integration regressions, without a macOS host or network."""
from pathlib import Path
from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import Mock
import orjson
import pytest
from portprotonqt import macos
@pytest.mark.parametrize("layout", [
"bin/wine", "bin/wine64", "Wine.app/Contents/Resources/wine/bin/wine",
"Contents/Resources/wine/bin/wine64", "wswine.bundle/bin/wine64",
"wine-devel/bin/wine", "Wine.app/Contents/SharedSupport/wine/bin/wine64",
])
def test_find_wine_bundle_layouts(tmp_path: Path, layout: str) -> None:
binary = tmp_path / layout
binary.parent.mkdir(parents=True)
binary.write_text("wine", encoding="utf-8")
assert macos.find_wine(tmp_path) is None
binary.chmod(0o755)
assert macos.find_wine(tmp_path) == binary
@pytest.mark.parametrize("name", ["", "..", "../outside", "/tmp/wine", "nested/wine"])
def test_version_paths_reject_traversal(tmp_path: Path, name: str) -> None:
with pytest.raises(ValueError):
macos.version_directory(tmp_path, name)
def test_version_paths_reject_symlink_escape(tmp_path: Path) -> None:
dist = tmp_path / "data/dist"
dist.mkdir(parents=True)
(dist / "escape").symlink_to(tmp_path)
with pytest.raises(ValueError):
macos.version_directory(tmp_path, "escape")
def test_native_command_uses_selected_version_prefix_and_arguments(tmp_path: Path) -> None:
binary = macos.version_directory(tmp_path, "Wine 1") / "wswine.bundle/bin/wine64"
binary.parent.mkdir(parents=True)
binary.write_text("wine", encoding="utf-8")
binary.chmod(0o755)
command, environment = macos.wine_command(tmp_path, ["/games/A game.exe", "a b"], {
"PW_WINE_USE": "Wine 1", "PW_PREFIX_NAME": "GAME",
})
assert command == [str(binary), "/games/A game.exe", "a b"]
assert environment["WINEPREFIX"] == str(tmp_path / "data/prefixes/GAME")
assert environment["PATH"].split(":")[0] == str(binary.parent)
def test_native_command_does_not_fallback_from_missing_selection(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(macos.shutil, "which", lambda _name: "/usr/bin/wine")
with pytest.raises(FileNotFoundError):
macos.wine_command(tmp_path, ["game.exe"], {"PW_WINE_USE": "missing"})
@pytest.mark.parametrize("prefix", ["..", "../other", "/tmp/prefix"])
def test_native_command_rejects_prefix_traversal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, prefix: str) -> None:
monkeypatch.setattr(macos.shutil, "which", lambda _name: "/usr/bin/wine")
with pytest.raises(ValueError):
macos.wine_command(tmp_path, ["game.exe"], {"PW_PREFIX_NAME": prefix})
def test_settings_roundtrip_is_data_not_shell(tmp_path: Path) -> None:
path = tmp_path / "game.exe.ppdb"
values = {"PW_WINE_USE": "Wine Crossover", "PW_PREFIX_NAME": "GAME", "VALUE": "$(touch /tmp/not-run)"}
macos.write_settings(path, values)
assert macos.read_settings(path) == values
@pytest.mark.parametrize("values", [
{"BAD;command": "value"}, {"BAD\nNAME": "value"},
{"VALUE": "first\nsecond"}, {"VALUE": "first\rsecond"},
])
def test_invalid_settings_preserve_existing_file(tmp_path: Path, values: dict[str, str]) -> None:
path = tmp_path / "game.exe.ppdb"
original = 'export PW_PREFIX_NAME=GAME\n'
path.write_text(original)
with pytest.raises(ValueError):
macos.write_settings(path, values)
assert path.read_text() == original
assert not path.with_name(path.name + ".tmp").exists()
def test_adapter_cli_edits_existing_ppdb_and_shows_dialog_format(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path))
executable = str(tmp_path / "game.exe")
assert macos.main(["cli", "--edit-db", executable, "PW_WINE_USE=Wine 1", "PW_PREFIX_NAME=GAME"]) == 0
assert macos.main(["cli", "--show-ppdb", executable]) == 0
assert 'PW_WINE_USE="Wine 1"' in capsys.readouterr().out
assert macos.main(["cli", "--set-user-conf", "PW_DEFAULT_WINE_USE", "Wine 2"]) == 0
assert macos.main(["cli", "--get-user-conf", "PW_DEFAULT_WINE_USE"]) == 0
assert capsys.readouterr().out.strip() == "Wine 2"
def test_adapter_exec_preserves_owned_pid_and_arguments(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path))
executable = tmp_path / "A game.exe"
executable.touch()
monkeypatch.setattr(macos.os, "chdir", Mock())
macos.write_settings(Path(str(executable) + ".ppdb"), {"PW_PREFIX_NAME": "GAME"})
monkeypatch.setattr(macos.shutil, "which", lambda _name: "/opt/homebrew/bin/wine")
execute = Mock()
monkeypatch.setattr(macos.os, "execvpe", execute)
assert macos.main([str(executable), "a b"]) == 0
assert execute.call_args.args[1] == ["/opt/homebrew/bin/wine", str(executable), "a b"]
assert execute.call_args.args[2]["WINEPREFIX"] == str(tmp_path / "data/prefixes/GAME")
def test_adapter_tools_use_existing_wine_and_prefix_selection(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path))
binary = macos.version_directory(tmp_path, "Wine 1") / "bin/wine"
binary.parent.mkdir(parents=True)
binary.touch(mode=0o755)
execute = Mock()
monkeypatch.setattr(macos.os, "execvpe", execute)
assert macos.main(["cli", "--winecfg", "Wine 1", "TEST"]) == 0
assert execute.call_args.args[1] == [str(binary), "winecfg"]
assert execute.call_args.args[2]["WINEPREFIX"].endswith("/TEST")
assert macos.main(["cli", "--autoinstall", "linux.sh"]) == 1
def test_catalog_loader_uses_forgejo_and_completes_once(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt.dialogs import wine_loader
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path))
monkeypatch.setattr(wine_loader.sys, "platform", "darwin")
monkeypatch.setattr("portprotonqt.portproton_api.get_user_conf_setting", lambda _key: "GITHUB")
metadata = {"wine-crossover": [{"name": "Wine 1", "url": "https://example.org/wine.tar.xz", "size_human": "1 MiB"}]}
response = SimpleNamespace(raise_for_status=lambda: None, iter_content=lambda **_kwargs: [orjson.dumps(metadata)])
get = Mock(return_value=response)
monkeypatch.setattr(wine_loader, "get_requests_session", lambda: SimpleNamespace(get=get))
worker = wine_loader.WineLoadingThread()
success, failure = Mock(), Mock()
worker.loading_complete.connect(success)
worker.loading_error.connect(failure)
worker.run()
assert get.call_args.args[0] == macos.MACOS_WINE_METADATA_URL
success.assert_called_once_with(metadata)
failure.assert_not_called()
@pytest.mark.parametrize("entry", [{"name": "../escape", "url": "https://example.org/a"}, {"name": "Wine", "url": "http://example.org/a"}])
def test_catalog_rejects_unsafe_download_paths(entry: dict[str, str]) -> None:
with pytest.raises(ValueError):
macos.validate_catalog({"wine-crossover": [entry]})
def test_manager_installs_and_detects_separate_bundle_versions(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt.dialogs import proton_manager
monkeypatch.setattr(proton_manager.sys, "platform", "darwin")
manager = SimpleNamespace(portproton_location=str(tmp_path))
for name in ("Wine 1", "Wine 2"):
destination = proton_manager.ProtonManager.get_download_extract_dir(cast(Any, manager), {"asset_name": name})
binary = Path(destination) / "wswine.bundle/bin/wine64"
binary.parent.mkdir(parents=True)
binary.touch(mode=0o755)
assert proton_manager.ProtonManager.is_asset_installed(cast(Any, manager), name, "sikarugir-engines")
assert proton_manager.ProtonManager.is_installed_version_dir(cast(Any, manager), destination)
assert proton_manager.ProtonManager.filter_entries_by_cpu_level(cast(Any, manager), [{"name": "x86_64"}], "wine-crossover") == [{"name": "x86_64"}]
def test_darwin_config_selects_native_backend(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt.config import portproton
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path / "data root"))
monkeypatch.setattr(portproton.sys, "platform", "darwin")
assert portproton.get_portproton_location() == str(tmp_path / "data root")
command = portproton.get_portproton_start_command()
assert command is not None
assert command[1:] == ["-m", "portprotonqt.macos"]
def test_shutdown_waits_for_retained_wine_tools() -> None:
from portprotonqt.tabs.workers import MainWindowWorkersMixin
process = Mock()
process.waitForFinished.side_effect = [False, True]
window = SimpleNamespace(wine_tool_processes=[process], _stopWorkerThread=Mock(), _stopWorkerThreads=Mock())
MainWindowWorkersMixin._stopBackgroundWorkers(cast(Any, window))
process.terminate.assert_called_once()
process.kill.assert_called_once()
assert process.waitForFinished.call_count == 2
assert window.wine_tool_processes == []
def test_macos_extraction_is_per_version_and_rejects_escape(tmp_path: Path) -> None:
import io
import tarfile
from portprotonqt.dialogs.wine_extractor import ExtractionThread
archive = tmp_path / "wine.tar"
with tarfile.open(archive, "w") as stream:
entry = tarfile.TarInfo("wswine.bundle/bin/wine64")
entry.mode = 0o755
entry.size = len(b"wine")
stream.addfile(entry, io.BytesIO(b"wine"))
destination = macos.version_directory(tmp_path, "Engine 1")
worker = ExtractionThread(str(archive), str(destination))
worker.run()
assert macos.find_wine(destination) == destination / "wswine.bundle/bin/wine64"
assert not macos.version_directory(tmp_path, "Engine 2").exists()
with tarfile.open(archive, "w") as stream:
entry = tarfile.TarInfo("../escape")
entry.size = len(b"bad")
stream.addfile(entry, io.BytesIO(b"bad"))
worker = ExtractionThread(str(archive), str(destination))
failure = Mock()
worker.error.connect(failure)
worker.run()
failure.assert_called_once()
assert not (destination.parent / "escape").exists()
def test_macos_shutdown_kills_only_owned_groups_and_waits(monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt import main_window
monkeypatch.setattr(main_window.sys, "platform", "darwin")
kill_group = Mock()
monkeypatch.setattr(main_window.os, "killpg", kill_group)
process = Mock(pid=1234)
process.poll.return_value = 0
window = SimpleNamespace(game_processes=[process])
main_window.MainWindow._terminate_game_processes(cast(Any, window))
kill_group.assert_called_once_with(1234, main_window.signal.SIGKILL)
process.wait.assert_called_once_with(timeout=0)
detached = Mock()
monkeypatch.setattr(main_window.QProcess, "startDetached", detached)
assert main_window.MainWindow._run_portproton_stop_command(cast(Any, window))
detached.assert_not_called()
def test_macos_tool_shutdown_kills_session_and_waits(monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt.tabs import workers
monkeypatch.setattr(workers.sys, "platform", "darwin")
kill_group = Mock()
monkeypatch.setattr(workers.os, "killpg", kill_group)
process = Mock()
process.processId.return_value = 1234
window = SimpleNamespace(wine_tool_processes=[process], _stopWorkerThread=Mock(), _stopWorkerThreads=Mock())
workers.MainWindowWorkersMixin._stopBackgroundWorkers(cast(Any, window))
kill_group.assert_called_once_with(1234, workers.signal.SIGKILL)
process.waitForFinished.assert_called_once()
def test_macos_does_not_start_linux_virtual_mouse_worker(monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt import input_manager
monkeypatch.setattr(input_manager.sys, "platform", "darwin")
worker = Mock()
monkeypatch.setattr(input_manager, "MouseEmulationThread", worker)
manager = SimpleNamespace(mouse_emulation_enabled=True)
input_manager.InputManager._async_enable_mouse_emulation(cast(Any, manager))
assert manager.mouse_emulation_enabled is False
worker.assert_not_called()
def test_macos_settings_offer_only_implemented_engine_and_prefix(monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt import settings_manager
monkeypatch.setattr(settings_manager.sys, "platform", "darwin")
assert settings_manager.get_toggle_settings() == {}
settings = settings_manager.get_advanced_settings("disabled", ["1"], [], {}, ["Wine"], ["DEFAULT"])
assert {setting["key"] for setting in settings} == {"PW_WINE_USE", "PW_PREFIX_NAME"}
def test_explicit_system_wine_selection_uses_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(macos.shutil, "which", lambda _name: "/opt/homebrew/bin/wine")
command, _environment = macos.wine_command(tmp_path, ["game.exe"], {"PW_WINE_USE": "USE_SYSTEM_WINE"})
assert command == ["/opt/homebrew/bin/wine", "game.exe"]
def test_macos_wine_options_exclude_incomplete_engines(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt import settings_manager
monkeypatch.setattr(settings_manager.sys, "platform", "darwin")
monkeypatch.setattr(settings_manager.shutil, "which", lambda _name: None)
valid = macos.version_directory(tmp_path, "Wine") / "Wine.app/Contents/Resources/wine/bin/wine"
valid.parent.mkdir(parents=True)
valid.touch(mode=0o755)
macos.version_directory(tmp_path, "incomplete").mkdir()
assert settings_manager.get_available_wine_options(str(tmp_path)) == ["Wine"]
@pytest.mark.parametrize("method", ["_launch_egs_game", "_launch_gog_game"])
def test_macos_store_wrappers_fail_explicitly_before_linux_setup(monkeypatch: pytest.MonkeyPatch, method: str) -> None:
from portprotonqt import main_window
monkeypatch.setattr(main_window.sys, "platform", "darwin")
warning = Mock()
monkeypatch.setattr(main_window.QMessageBox, "warning", warning)
window = SimpleNamespace(_finish_silent_launch=Mock(), egs_api=Mock(), gog_api=Mock())
getattr(main_window.MainWindow, method)(cast(Any, window), "game")
window._finish_silent_launch.assert_called_once()
warning.assert_called_once()
assert "macOS" in warning.call_args.args[2]
assert "directly" in warning.call_args.args[2]
assert window.egs_api.mock_calls == []
assert window.gog_api.mock_calls == []
def test_settings_ignores_predictable_temporary_symlink(tmp_path: Path) -> None:
outside = tmp_path / "outside"
outside.write_text("preserved")
path = tmp_path / "user.conf"
path.with_suffix(".conf.tmp").symlink_to(outside)
macos.write_settings(path, {"KEY": "value"})
assert outside.read_text() == "preserved"
assert macos.read_settings(path) == {"KEY": "value"}
def test_settings_replace_failure_preserves_original(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
path = tmp_path / "user.conf"
path.write_text("original")
monkeypatch.setattr(macos.os, "replace", Mock(side_effect=OSError("disk failure")))
with pytest.raises(OSError, match="disk failure"):
macos.write_settings(path, {"KEY": "value"})
assert path.read_text() == "original"
assert list(tmp_path.iterdir()) == [path]
@pytest.mark.parametrize("extension,dispatch", [
(".msi", ["msiexec", "/i"]), (".bat", ["cmd", "/c"]),
(".cmd", ["cmd", "/c"]), (".reg", ["regedit"]),
])
def test_adapter_dispatch_and_working_directory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
extension: str, dispatch: list[str]) -> None:
target = tmp_path / ("game" + extension)
target.touch()
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path))
monkeypatch.setattr(macos.shutil, "which", lambda _: "/wine")
execute, change_directory = Mock(), Mock()
monkeypatch.setattr(macos.os, "execvpe", execute)
monkeypatch.setattr(macos.os, "chdir", change_directory)
assert macos.main([str(target), "extra argument"]) == 0
assert execute.call_args.args[1] == ["/wine", *dispatch, str(target), "extra argument"]
change_directory.assert_called_once_with(tmp_path)
def test_darwin_extraction_failure_and_cancel_preserve_version(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import io
import tarfile
from portprotonqt.dialogs import wine_extractor
monkeypatch.setattr(wine_extractor.sys, "platform", "darwin")
destination = macos.version_directory(tmp_path, "Engine")
destination.mkdir(parents=True)
(destination / "original").write_text("working")
archive = tmp_path / "wine.tar"
with tarfile.open(archive, "w") as stream:
for name in ("bin/wine", "../escape"):
entry = tarfile.TarInfo(name)
entry.mode, entry.size = 0o755, 4
stream.addfile(entry, io.BytesIO(b"wine"))
worker = wine_extractor.ExtractionThread(str(archive), str(destination))
failed = Mock()
worker.error.connect(failed)
worker.run()
failed.assert_called_once()
assert list(destination.iterdir()) == [destination / "original"]
worker.stop()
worker.run()
assert list(destination.parent.iterdir()) == [destination]
def test_darwin_extraction_promotes_complete_version(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import io
import tarfile
from portprotonqt.dialogs import wine_extractor
monkeypatch.setattr(wine_extractor.sys, "platform", "darwin")
archive = tmp_path / "wine.tar"
with tarfile.open(archive, "w") as stream:
entry = tarfile.TarInfo("bin/wine")
entry.mode, entry.size = 0o755, 4
stream.addfile(entry, io.BytesIO(b"wine"))
destination = macos.version_directory(tmp_path, "Engine")
worker = wine_extractor.ExtractionThread(str(archive), str(destination))
complete = Mock()
worker.finished.connect(complete)
worker.run()
complete.assert_called_once_with(str(archive), True)
assert macos.find_wine(destination) == destination / "bin/wine"
assert list(destination.parent.iterdir()) == [destination]
+101 -4
View File
@@ -42,7 +42,7 @@ from portprotonqt.game_library_manager import FullLibraryTile, GameLibraryManage
from portprotonqt.input_manager import InputManager
from portprotonqt.main_window import MainWindow
from portprotonqt.search_utils import SearchOptimizer, search_index
from portprotonqt.tray_manager import TrayManager
from portprotonqt.tray_manager import TrayManager, create_wine_tools_menu, launch_session_wine_tool
from portprotonqt.themes.standart.styles.constants import GAME_CARD_ANIMATION
from portprotonqt.portproton_api import remove_empty_custom_data_dirs
import portprotonqt.tabs.autoinstall_tab as autoinstall_tab_module
@@ -374,18 +374,71 @@ def test_minimal_tray_contains_game_actions() -> None:
_application = QApplication.instance() or QApplication([])
manager = TrayManager.__new__(TrayManager)
manager.tray_menu = QMenu()
manager.pause_game_action = QAction("Pause Game", manager.tray_menu)
manager.stop_game_action = QAction("Stop Game", manager.tray_menu)
owner = QWidget()
manager.pause_game_action = QAction("Pause Game", owner)
manager.stop_game_action = QAction("Stop Game", owner)
manager.wine_tools_menu = create_wine_tools_menu(manager.tray_menu, ["portproton"])
manager.minimal_mode = True
manager.update_game_actions = MagicMock()
manager.refresh_tray_menu()
manager.refresh_tray_menu()
assert manager.tray_menu.actions() == [
manager.pause_game_action,
manager.stop_game_action,
manager.wine_tools_menu.menuAction(),
]
manager.update_game_actions.assert_called_once_with()
assert manager.update_game_actions.call_count == 2
@mark.parametrize("tool_index,tool", list(enumerate(
("winefile", "taskmgr", "winecfg", "regedit", "cmd", "uninstaller")
)))
def test_wine_tools_menu_launches_session_tool(
monkeypatch: MonkeyPatch, tool_index: int, tool: str,
) -> None:
_application = QApplication.instance() or QApplication([])
parent = QMenu()
start = MagicMock(return_value=(True, 123))
monkeypatch.setattr("portprotonqt.tray_manager.QProcess.startDetached", start)
menu = create_wine_tools_menu(parent, ["bash", "/path with spaces/start.sh"])
assert len(menu.actions()) == 6
menu.actions()[tool_index].trigger()
start.assert_called_once_with(
"bash", ["/path with spaces/start.sh", "cli", "--wine-session-tool", tool]
)
def test_wine_tool_start_failure_is_reported(monkeypatch: MonkeyPatch) -> None:
_application = QApplication.instance() or QApplication([])
warning = MagicMock()
monkeypatch.setattr("portprotonqt.tray_manager.QMessageBox.warning", warning)
monkeypatch.setattr(
"portprotonqt.tray_manager.QProcess.startDetached", lambda *args: (False, 0)
)
launch_session_wine_tool(["portproton"], "winefile")
warning.assert_called_once()
@mark.parametrize("running", [False, True])
def test_wine_tools_menu_requires_running_game(running: bool) -> None:
_application = QApplication.instance() or QApplication([])
manager = TrayManager.__new__(TrayManager)
manager.main_window = SimpleNamespace(game_processes=[], target_exe="game.exe" if running else None)
manager.stop_game_action = QAction()
manager.pause_game_action = QAction()
manager.wine_tools_menu = QMenu()
manager._game_process_tree = MagicMock(return_value=[])
manager.update_game_actions()
assert manager.wine_tools_menu.isEnabled() is running
def test_tray_pauses_game_process_tree(monkeypatch: MonkeyPatch) -> None:
child = MagicMock(pid=12)
@@ -3571,3 +3624,47 @@ def test_steam_watch_keeps_stop_during_preparation_gap(monkeypatch: MonkeyPatch)
monkeypatch.setattr(main_window_module.time, "monotonic", lambda: 1004.0)
MainWindow._steam_scan_finished(cast(Any, window), "620")
assert watch["running"] is False
@mark.parametrize("tool", ["winecfg", "regedit", "winefile", "cmd", "uninstaller", "taskmgr"])
@mark.parametrize("running", [False, True])
def test_wine_settings_tools_use_unified_command(
monkeypatch: MonkeyPatch, tool: str, running: bool,
) -> None:
process = MagicMock()
monkeypatch.setattr("portprotonqt.tabs.wine_tab.QProcess", MagicMock(return_value=process))
window = MagicMock()
window.game_processes = [MagicMock()] if running else []
window.target_exe = "game.exe" if running else None
window.start_sh = ["bash", "/path with spaces/start.sh"]
window.wineCombo.currentText.return_value = "WINE_LG"
window.prefixCombo.currentText.return_value = "my prefix"
WineMixin.launch_generic_tool(window, tool)
process.start.assert_called_once_with(
"bash", ["/path with spaces/start.sh", "cli", "--wine-session-tool", tool, "WINE_LG", "MY_PREFIX"],
)
window._start_wine_process_monitor.assert_called_once_with(tool)
def test_silent_tray_includes_wine_tools_menu(monkeypatch: MonkeyPatch) -> None:
_application = QApplication.instance() or QApplication([])
manager = TrayManager.__new__(TrayManager)
manager.tray_menu = QMenu()
owner = QWidget()
manager.pause_game_action = QAction("Pause Game", owner)
manager.stop_game_action = QAction("Stop Game", owner)
manager.wine_tools_menu = create_wine_tools_menu(manager.tray_menu, ["portproton"])
manager.update_game_actions = MagicMock()
start = MagicMock(return_value=(True, 123))
monkeypatch.setattr("portprotonqt.tray_manager.QProcess.startDetached", start)
manager.set_minimal_mode()
tools = manager.tray_menu.actions()[2].menu()
assert isinstance(tools, QMenu)
assert len(tools.actions()) == 6
tools.actions()[1].trigger()
start.assert_called_once_with("portproton", ["cli", "--wine-session-tool", "taskmgr"])
+138
View File
@@ -326,3 +326,141 @@ def test_run_after_wrapper_preserves_command_with_comma(tmp_path: Path) -> None:
capture_output=True, text=True, check=True,
)
assert result.stdout.splitlines() == ["first,second", "game"]
def test_wine_session_missing_returns_distinct_status(tmp_path: Path) -> None:
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
definition = helper.split("pw_session_tool () {", 1)[1].split("pw_launch_wrapper () {", 1)[0]
script = "pw_session_tool () {" + definition + '''
print_error () { echo "$@" >&2; }
sleep () { return 0; }
pw_session_tool taskmgr 1
'''
result = subprocess.run(
["bash", "-c", script], cwd=tmp_path, capture_output=True, text=True, check=False,
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)},
)
assert result.returncode == 2
@mark.parametrize("tool", ["winecfg", "regedit", "winefile", "cmd", "uninstaller", "taskmgr"])
def test_wine_session_tool_standalone_uses_selected_wine_and_prefix(tmp_path: Path, tool: str) -> None:
start = Path("build-aux/share/portproton/scripts/start.sh").read_text()
block = start.split(" --wine-session-tool)\n", 1)[1].split(" --winetricks-list-all)", 1)[0]
script = '''
get_wine_and_pfx () { printf '%s\\n' "$@"; }
start_portproton () { mkdir -p "$PORT_DATA_PATH/data/prefixes/$PW_PREFIX_NAME/drive_c"; echo start; }
pw_run () { printf '%s\\n' "$@"; }
stop_portproton () { echo stop; }
''' + 'case "$1" in --wine-session-tool)\n' + block + '\nesac\n'
result = subprocess.run(
["bash", "-c", script, "bash", "--wine-session-tool", tool, "WINE_LG", "MY_PREFIX"],
cwd=tmp_path, capture_output=True, text=True, check=False,
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path), "PW_PREFIX_NAME": "MY_PREFIX"},
)
assert result.returncode == 0, result.stderr
assert result.stdout.splitlines() == ["WINE_LG", "MY_PREFIX", "start", tool, "stop"]
@mark.parametrize("tool", ["winefile", "taskmgr", "winecfg", "regedit", "cmd", "uninstaller"])
@mark.parametrize("tool_exit_code", [0, 2])
def test_wine_session_tools_reuse_prefix_without_game_options(
tmp_path: Path, tool: str, tool_exit_code: int,
) -> None:
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
definitions = helper.split("pw_save_session_env () {", 1)[1].split("pw_launch_wrapper () {", 1)[0]
script = "pw_save_session_env () {" + definitions + '''
print_error () { echo "$@" >&2; }
pw_run () {
printf '%s\\n' "$1" "$WINEPREFIX" "${PW_USE_TERMINAL:-0}" "${LAUNCH_PARAMETERS:-}" \\
"${PW_RUN_AFTER_EXE:-}" "${PW_RUN_GAMESCOPE:-}" "$PW_TMPFS_PATH"
return "$TOOL_EXIT_CODE"
}
PW_TERM="test-terminal"
export PW_START_PID="$$" WINEPREFIX="$PORT_DATA_PATH/prefix with spaces"
export LAUNCH_PARAMETERS="--game-only" PW_RUN_AFTER_EXE=trainer.exe PW_RUN_GAMESCOPE=gamescope
pw_save_session_env || exit 2
pw_session_tool "$1"
'''
(tmp_path / "prefix with spaces/drive_c").mkdir(parents=True)
result = subprocess.run(
["bash", "-c", script, "bash", tool], capture_output=True, text=True,
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path),
"TOOL_EXIT_CODE": str(tool_exit_code)}, check=False,
)
assert result.returncode == int(tool_exit_code != 0), result.stderr
lines = result.stdout.splitlines()
assert lines[:6] == [tool, str(tmp_path / "prefix with spaces"), "1" if tool == "cmd" else "0", "", "", ""]
assert Path(lines[6]).is_dir()
assert Path(lines[6]).stat().st_mode & 0o777 == 0o700
session = next((tmp_path / "data/tmp").glob("wine-session-*/session.env"))
assert session.stat().st_mode & 0o777 == 0o600
assert 'declare -x PW_TERM="test-terminal"' in session.read_text()
@mark.parametrize("unsafe_directory", [False, True])
def test_wine_session_save_does_not_follow_symlinks(tmp_path: Path, unsafe_directory: bool) -> None:
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
definition = helper.split("pw_save_session_env () {", 1)[1].split("pw_remove_session_env () {", 1)[0]
session_dir = tmp_path / "data/tmp" / f"wine-session-{os.getuid()}"
session_dir.parent.mkdir(parents=True)
victim = tmp_path / "victim"
victim.write_text("keep this")
if unsafe_directory:
target = tmp_path / "other-directory"
target.mkdir(mode=0o700)
session_dir.symlink_to(target, target_is_directory=True)
else:
session_dir.mkdir(mode=0o700)
(session_dir / "session.env").symlink_to(victim)
result = subprocess.run(
["bash", "-c", "pw_save_session_env () {" + definition + "\npw_save_session_env"],
capture_output=True, text=True,
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)}, check=False,
)
assert victim.read_text() == "keep this"
assert result.returncode == (1 if unsafe_directory else 0), result.stderr
if not unsafe_directory:
assert not (session_dir / "session.env").is_symlink()
def test_wine_session_tool_rejects_unknown_tool_before_reading_environment(tmp_path: Path) -> None:
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
definition = helper.split("pw_session_tool () {", 1)[1].split("pw_launch_wrapper () {", 1)[0]
script = "pw_session_tool () {" + definition + '''
print_error () { echo "$@" >&2; }
sleep () { exit 99; }
pw_session_tool '../../other-command'
'''
result = subprocess.run(
["bash", "-c", script], capture_output=True, text=True,
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)}, check=False,
)
assert result.returncode == 1
assert "Unsupported Wine tool" in result.stderr
def test_wine_session_cleanup_preserves_newer_session(tmp_path: Path) -> None:
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
definitions = helper.split("pw_save_session_env () {", 1)[1].split("pw_session_tool () {", 1)[0]
script = "pw_save_session_env () {" + definitions + '''
export PW_START_PID="$$"
pw_save_session_env || exit 2
PW_START_PID=99999999
pw_remove_session_env
[[ -f "$PORT_DATA_PATH/data/tmp/wine-session-$(id -u)/session.env" ]] || exit 3
PW_START_PID="$$"
pw_remove_session_env
[[ ! -e "$PORT_DATA_PATH/data/tmp/wine-session-$(id -u)/session.env" ]]
'''
result = subprocess.run(
["bash", "-c", script], capture_output=True, text=True,
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)}, check=False,
)
assert result.returncode == 0, result.stderr
Generated
+2 -2
View File
@@ -444,7 +444,7 @@ source = { editable = "." }
dependencies = [
{ name = "babel" },
{ name = "dbus-fast" },
{ name = "evdev", marker = "sys_platform == 'linux'" },
{ name = "evdev" },
{ name = "libarchive-c" },
{ name = "orjson" },
{ name = "pefile" },
@@ -471,7 +471,7 @@ dev = [
requires-dist = [
{ name = "babel", specifier = ">=2.18.0" },
{ name = "dbus-fast", specifier = ">=5.2.0" },
{ name = "evdev", marker = "sys_platform == 'linux'", specifier = ">=2.0.0" },
{ name = "evdev", specifier = ">=2.0.0" },
{ name = "libarchive-c", specifier = ">=5.3" },
{ name = "orjson", specifier = ">=3.12.0" },
{ name = "pefile", specifier = ">=2024.8.26" },