Compare commits

..
1 Commits
Author SHA1 Message Date
Boria138 371fa0e822 feat: added MacOS support
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-11-20 00:49:41 +05:00
64 changed files with 1246 additions and 890 deletions

No files matched your search

+22 -45
View File
@@ -1,17 +1,19 @@
name: Build native binaries on Debian 11
name: Build vk_gpu_info on Debian 11
on:
workflow_dispatch:
push:
branches:
- main
- scripts
paths:
- 'build-aux/src/**'
- 'build-aux/src/vk_gpu_info.c'
- 'build-aux/src/wine_gpu_names.h'
- '.gitea/workflows/build-vk-gpu-info-debian.yml'
jobs:
build-debian11:
name: Build native binaries on Debian 11
name: Build vk_gpu_info on Debian 11
runs-on: ubuntu-latest
container:
image: debian:11
@@ -20,13 +22,8 @@ jobs:
steps:
- name: Install dependencies
run: |
set -- build-essential cmake pkg-config libvulkan-dev libwayland-dev libx11-dev git curl wget nodejs npm
if ! (apt-get update -o APT::Update::Error-Mode=any && apt-get install -y "$@"); then
echo 'APT failed; retrying with security.debian.org for bullseye-security.'
sed -i '/^[[:space:]]*deb .* bullseye-security /s|http://deb.debian.org/debian-security|http://security.debian.org/debian-security|' /etc/apt/sources.list &&
apt-get update -o APT::Update::Error-Mode=any &&
apt-get install -y "$@"
fi
apt-get update
apt-get install -y build-essential pkg-config libvulkan-dev git curl wget nodejs npm
- name: Set up Node.js
uses: https://git.linux-gaming.ru/actions/setup-node@v2
@@ -35,46 +32,26 @@ jobs:
- name: Checkout code
uses: https://git.linux-gaming.ru/actions/checkout@v3
with:
ref: ${{ gitea.ref }}
token: ${{ secrets.GITEA_TOKEN }}
- name: Build SDL3 for linking
- name: Compile vk_gpu_info
run: |
# SDL 3.2.10 is not available in Debian 11. Only the backends are shipped.
sdl_commit=877399b2b2cf21e67554ed9046410f268ce1d1b2
curl --fail --location --max-time 120 \
"https://codeload.github.com/libsdl-org/SDL/tar.gz/${sdl_commit}" -o /tmp/sdl3.tar.gz
mkdir -p /tmp/sdl3-src
tar -xzf /tmp/sdl3.tar.gz -C /tmp/sdl3-src --strip-components=1
cmake -S /tmp/sdl3-src -B /tmp/sdl3-build \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/tmp/sdl3 \
-DCMAKE_INSTALL_LIBDIR=lib -DSDL_UNIX_CONSOLE_BUILD=ON \
-DSDL_SHARED=ON -DSDL_STATIC=OFF -DSDL_TEST_LIBRARY=OFF
cmake --build /tmp/sdl3-build --parallel "$(nproc)"
cmake --install /tmp/sdl3-build
- name: Compile native binaries
run: |
export PKG_CONFIG_PATH="/tmp/sdl3/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}"
mkdir -p build-aux/bin build-aux/lib
gcc -std=c99 -o build-aux/bin/vk_gpu_info build-aux/src/vk_gpu_info.c -lvulkan
gcc -shared -fPIC -Wl,-z,defs -o build-aux/lib/libportprotonqt_gamepad.so \
build-aux/src/gamepad_backend.c $(pkg-config --cflags --libs sdl3)
gcc -shared -fPIC -Wl,-z,defs -o build-aux/lib/libportprotonqt_keyboard.so \
build-aux/src/keyboard_backend.c $(pkg-config --cflags --libs wayland-client x11)
mkdir -p build-aux/bin
gcc -o build-aux/bin/vk_gpu_info build-aux/src/vk_gpu_info.c -lvulkan
- name: Test vk_gpu_info execution
run: |
test -x build-aux/bin/vk_gpu_info
timeout 10s build-aux/bin/vk_gpu_info || echo "Vulkan smoke test failed; CI may lack a Vulkan device."
# Check if the executable was created
if [ -f "build-aux/bin/vk_gpu_info" ]; then
echo "vk_gpu_info executable created successfully"
# Try to run it (may fail if no Vulkan devices present, but that's OK for build test)
timeout 10s build-aux/bin/vk_gpu_info || echo "vk_gpu_info ran but may have failed due to lack of Vulkan hardware (expected in CI)"
else
echo "ERROR: vk_gpu_info executable was not created"
exit 1
fi
- name: Upload native binaries
- name: Upload vk_gpu_info binary
uses: https://git.linux-gaming.ru/actions/gitea-upload-artifact@v4
with:
name: native-binaries-debian11
path: |
build-aux/bin/vk_gpu_info
build-aux/lib/libportprotonqt_gamepad.so
build-aux/lib/libportprotonqt_keyboard.so
if-no-files-found: error
name: vk_gpu_info-debian11-binary
path: build-aux/bin/vk_gpu_info
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
name: Check code
runs-on: ubuntu-latest
container:
image: archlinux:base-devel@sha256:624bdc7fc6615155d67bc34cf7146c0c9fd0e3c92943977da63a630e4ca49c30
image: archlinux:base-devel@sha256:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1
steps:
- name: Configure Arch mirrors
run: |
+3 -3
View File
@@ -80,7 +80,7 @@ jobs:
needs: changes
if: needs.changes.outputs.appimage == 'true' || github.event_name == 'workflow_dispatch'
container:
image: archlinux:base-devel@sha256:624bdc7fc6615155d67bc34cf7146c0c9fd0e3c92943977da63a630e4ca49c30
image: archlinux:base-devel@sha256:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1
options: --privileged --device /dev/fuse
steps:
- name: Configure Arch mirrors
@@ -210,7 +210,7 @@ jobs:
needs: changes
if: needs.changes.outputs.arch == 'true' || github.event_name == 'workflow_dispatch'
container:
image: archlinux:base-devel@sha256:624bdc7fc6615155d67bc34cf7146c0c9fd0e3c92943977da63a630e4ca49c30
image: archlinux:base-devel@sha256:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1
steps:
- name: Configure Arch mirrors
@@ -296,7 +296,7 @@ jobs:
needs: changes
if: needs.changes.outputs.debian == 'true' || github.event_name == 'workflow_dispatch'
container:
image: debian:trixie-20261027@sha256:2dc419c6d7fe3dad0a2f9fd469c34cc90b0f9ba642d8fde837fe3d7d34a0e7f1
image: debian:trixie-20261005@sha256:913f6706df59a68922d1dd08f78c2476560a8d367897200a6005b00e5f67c2d5
options: --privileged
steps:
-6
View File
@@ -46,11 +46,6 @@
### Fixed
- Обложки заполняют отведённую область без растягивания
- Исправлена загрузка оценок времени прохождения с HowLongToBeat в карточках игр
- При нажатии вниз на D-pad с верхней панели библиотеки фокус переходит на первую карточку верхнего ряда, а не перескакивает на нижние ряды
- В карточках игр GOG отображается краткое описание без рекламы, баннеров и списков особенностей
- Недокачанные JPEG-обложки больше не попадают в кэш
- Исправлена фильтрация видеокарт DXVK и VKD3D при расхождении нативного имени GPU с именем Wine
- Запросы установки других игр GOG и EGS во время получения списка DLC добавляются в очередь вместо ошибки «Другая загрузка уже выполняется»
- Виртуальная мышь создаётся только при включении эмуляции геймпадом и удаляется при её выключении
@@ -80,7 +75,6 @@
- @rogerio-mattos
- @Rubin13
- @iodnoorov
- @gstkein
---
+1 -1
View File
@@ -9,7 +9,7 @@
<p>
<a href="https://github.com/linux-gaming-ru/PortProtonQt/releases"><img src="https://img.shields.io/github/v/release/linux-gaming-ru/PortProtonQt?style=flat-square&amp;label=Release" alt="Releases"></a>
<a href="https://github.com/linux-gaming-ru/PortProtonQt/releases"><img src="https://img.shields.io/badge/Downloads-18.9k-green?style=flat-square" alt="Total Downloads"></a>
<a href="https://github.com/linux-gaming-ru/PortProtonQt/releases"><img src="https://img.shields.io/badge/Downloads-17.9k-green?style=flat-square" alt="Total Downloads"></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/License-GPL--3.0-blue?style=flat-square" alt="License: GPL-3.0"></a>
<a href="pyproject.toml"><img src="https://img.shields.io/badge/Python-3.11%2B-blue?style=flat-square&amp;logo=python" alt="Python 3.11+"></a>
<a href="https://github.com/linux-gaming-ru/PortProtonQt"><img src="https://img.shields.io/badge/Platform-Linux-blue?style=flat-square&amp;logo=linux" alt="Platform: Linux"></a>
+1 -1
View File
@@ -9,7 +9,7 @@
<p>
<a href="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt/releases"><img src="https://img.shields.io/github/v/release/linux-gaming-ru/PortProtonQt?style=flat-square&amp;label=Релиз" alt="Релизы"></a>
<a href="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt/releases"><img src="https://img.shields.io/badge/Загрузки-18.9k-green?style=flat-square" alt="Всего загрузок"></a>
<a href="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt/releases"><img src="https://img.shields.io/badge/Загрузки-17.9k-green?style=flat-square" alt="Всего загрузок"></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/Лицензия-GPL--3.0-blue?style=flat-square" alt="Лицензия: GPL-3.0"></a>
<a href="pyproject.toml"><img src="https://img.shields.io/badge/Python-3.11+-blue?style=flat-square&amp;logo=python" alt="Python 3.11+"></a>
<a href="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt"><img src="https://img.shields.io/badge/Платформа-Linux-blue?style=flat-square&amp;logo=linux" alt="Платформа: Linux"></a>
+104
View File
@@ -0,0 +1,104 @@
# 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. For
managed engines, the adapter uses an executable `wineserver` next to the selected
Wine binary when present, without changing the parent process environment.
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
Assisted-by: pz:gpt-6.2-sol
+3
View File
@@ -59,6 +59,7 @@ 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)]
@@ -71,6 +72,8 @@ executable('vk_gpu_info',
c_args: ['-std=c99'],
)
endif
# Install desktop file
install_data(
'build-aux/share/applications/ru.linux_gaming.PortProtonQt.desktop',
+9 -8
View File
@@ -816,13 +816,14 @@ def main():
except (OSError, RequestException):
logger.exception("Failed to update gogdl")
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()
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()
# Execute the initial PortProton command after the UI is set up
class InitialCommandWorker(QThread):
@@ -889,7 +890,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:
if start_sh and not silent_game_request and sys.platform != "darwin":
worker = InitialCommandWorker(start_sh)
window.initialCommandWorker = worker
worker.finished.connect(
+6
View File
@@ -410,6 +410,8 @@ 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")
@@ -591,6 +593,8 @@ 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")
@@ -647,6 +651,8 @@ 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,6 +114,11 @@ 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:
@@ -153,6 +158,8 @@ 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()
@@ -191,6 +198,8 @@ 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
+7 -2
View File
@@ -1,11 +1,10 @@
"""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
@@ -13,6 +12,10 @@ 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"
@@ -204,6 +207,8 @@ 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,6 +1,7 @@
"""Detail pages for PortProtonQt."""
import os
import sys
import weakref
from collections.abc import Callable, Sequence
@@ -616,6 +617,8 @@ 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:
+1 -1
View File
@@ -140,7 +140,7 @@ def _add_source_corner(
) -> None:
"""Add source corner badge to cover frame."""
source = game_source.lower()
if source not in ("steam", "gog", "egs", "portproton", "native") or theme_manager is None:
if source not in ("steam", "gog", "egs", "portproton") or theme_manager is None:
return
icon_name = f"badge_{source}"
+16 -3
View File
@@ -1,6 +1,8 @@
"""Proton Manager dialog for PortProtonQt."""
import os
import sys
from pathlib import Path
import platform
import shutil
import tempfile
@@ -374,6 +376,8 @@ 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:
@@ -471,7 +475,7 @@ class ProtonManager(DraggableDialog):
url = entry.get('url', '')
filename = entry.get('name', '')
size_human = entry.get('size_human', _('Unknown'))
if url:
if url and sys.platform != "darwin":
parsed_url = urllib.parse.urlparse(url)
url_filename = os.path.basename(parsed_url.path)
if url_filename:
@@ -539,6 +543,9 @@ 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):
@@ -562,6 +569,9 @@ 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']
)
@@ -629,7 +639,7 @@ class ProtonManager(DraggableDialog):
installed_versions = []
seen_paths = set()
version_dirs = [dist_path]
if not ui_config.get_disable_steam_proton_scanning():
if sys.platform != "darwin" and 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))
@@ -653,6 +663,9 @@ 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")):
@@ -1023,7 +1036,7 @@ class ProtonManager(DraggableDialog):
import subprocess
try:
start_cmd = get_portproton_start_command()
if start_cmd and not self.initial_command_executed:
if start_cmd and not self.initial_command_executed and sys.platform != "darwin":
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}")
+6 -4
View File
@@ -1,6 +1,7 @@
"""Settings dialog for PortProtonQt."""
import os
import sys
import re
import subprocess
from html import escape
@@ -418,10 +419,11 @@ class ExeSettingsDialog(
self.tab_widget.addTab(self.main_tab, _("Main"))
self.tab_widget.addTab(self.advanced_tab, _("Advanced"))
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")
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.settings_table = QTableWidget()
self.settings_table.setAlternatingRowColors(True)
+21
View File
@@ -1,6 +1,9 @@
"""Wine archive extractor for PortProtonQt."""
import os
import sys
import shutil
import tempfile
import time
import libarchive
from PySide6.QtCore import QThread, Signal, QMutex
@@ -46,7 +49,13 @@ 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)
@@ -157,6 +166,14 @@ 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)
@@ -168,6 +185,10 @@ 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,6 +1,7 @@
"""Wine metadata loader for PortProtonQt."""
import os
import sys
import tempfile
import orjson
@@ -104,6 +105,10 @@ 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
@@ -120,6 +125,9 @@ 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:
+62 -48
View File
@@ -1,6 +1,5 @@
from PySide6.QtCore import QObject, Signal, QThread, Qt, QCoreApplication
import threading
from tempfile import NamedTemporaryFile
import os
import time
import requests
@@ -27,57 +26,36 @@ def get_requests_session():
session.verify = True
return session
def is_complete_download(path: str | Path) -> bool:
"""Check for a cached file, rejecting JPEGs without an end marker."""
jpeg_start = b"\xff\xd8"
jpeg_end = b"\xff\xd9"
try:
with open(path, "rb") as stream:
if stream.read(len(jpeg_start)) != jpeg_start:
return True
stream.seek(-len(jpeg_end), os.SEEK_END)
return stream.read() == jpeg_end
except OSError:
return False
def _save_download(response: requests.Response, local_path: str, timeout: float) -> None:
deadline = time.monotonic() + timeout
total_size = int(response.headers.get('Content-Length', 0))
destination = Path(local_path)
destination.parent.mkdir(parents=True, exist_ok=True)
with NamedTemporaryFile(dir=destination.parent, delete=False) as stream:
temporary = Path(stream.name)
try:
with tqdm(total=total_size or None, unit='B', unit_scale=True,
unit_divisor=1024, desc=f"Downloading {destination.name}", ascii=True) as pbar:
for chunk in response.iter_content(chunk_size=8192):
if time.monotonic() > deadline:
raise requests.exceptions.ReadTimeout(f"Download exceeded {timeout}s total timeout")
if chunk:
stream.write(chunk)
pbar.update(len(chunk))
stream.close()
if not is_complete_download(temporary):
raise OSError("Incomplete JPEG download")
temporary.replace(destination)
finally:
temporary.unlink(missing_ok=True)
def download_with_cache(url, local_path, timeout=5, downloader_instance=None):
if is_complete_download(local_path):
if os.path.exists(local_path):
return local_path
session = get_requests_session()
try:
with session.get(url, stream=True, timeout=timeout) as response:
response.raise_for_status()
_save_download(response, local_path, timeout)
deadline = time.monotonic() + timeout
total_size = int(response.headers.get('Content-Length', 0))
os.makedirs(os.path.dirname(local_path), exist_ok=True)
desc = Path(local_path).name
with tqdm(total=total_size if total_size > 0 else None,
unit='B', unit_scale=True, unit_divisor=1024,
desc=f"Downloading {desc}", ascii=True) as pbar:
with open(local_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if time.monotonic() > deadline:
raise requests.exceptions.ReadTimeout(
f"Download exceeded {timeout}s total timeout for {url}"
)
if chunk:
f.write(chunk)
pbar.update(len(chunk))
return local_path
except Exception as e:
logger.error(f"Download error {url}: {e}")
if downloader_instance and hasattr(downloader_instance, '_last_error'):
downloader_instance._last_error[url] = True
if os.path.exists(local_path):
os.remove(local_path)
return None
class Downloader(QObject):
@@ -123,7 +101,7 @@ class Downloader(QObject):
last_request_time = [0.0]
def _download_one(url, local_path):
if is_complete_download(local_path):
if os.path.exists(local_path):
return local_path
try:
with rate_limit_lock:
@@ -134,7 +112,22 @@ class Downloader(QObject):
with session.get(url, stream=True, timeout=timeout) as response:
response.raise_for_status()
_save_download(response, local_path, timeout)
deadline = time.monotonic() + timeout
total_size = int(response.headers.get('Content-Length', 0))
os.makedirs(os.path.dirname(local_path), exist_ok=True)
desc = Path(local_path).name
with tqdm(total=total_size if total_size > 0 else None,
unit='B', unit_scale=True, unit_divisor=1024,
desc=f"Downloading {desc}", ascii=True) as pbar:
with open(local_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if time.monotonic() > deadline:
raise requests.exceptions.ReadTimeout(
f"Download exceeded {timeout}s total timeout for {url}"
)
if chunk:
f.write(chunk)
pbar.update(len(chunk))
return local_path
except requests.exceptions.HTTPError as e:
if e.response is not None and e.response.status_code == 429:
@@ -143,22 +136,43 @@ class Downloader(QObject):
try:
with session.get(url, stream=True, timeout=timeout) as response:
response.raise_for_status()
_save_download(response, local_path, timeout)
deadline = time.monotonic() + timeout
total_size = int(response.headers.get('Content-Length', 0))
os.makedirs(os.path.dirname(local_path), exist_ok=True)
desc = Path(local_path).name
with tqdm(total=total_size if total_size > 0 else None,
unit='B', unit_scale=True, unit_divisor=1024,
desc=f"Downloading {desc}", ascii=True) as pbar:
with open(local_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if time.monotonic() > deadline:
raise requests.exceptions.ReadTimeout(
f"Download exceeded {timeout}s total timeout for {url}"
)
if chunk:
f.write(chunk)
pbar.update(len(chunk))
return local_path
except Exception as retry_e:
logger.error(f"Retry download error {url}: {retry_e}")
with self._global_lock:
self._last_error[url] = True
if os.path.exists(local_path):
os.remove(local_path)
return None
else:
logger.error(f"Download error {url}: {e}")
with self._global_lock:
self._last_error[url] = True
if os.path.exists(local_path):
os.remove(local_path)
return None
except Exception as e:
logger.error(f"Download error {url}: {e}")
with self._global_lock:
self._last_error[url] = True
if os.path.exists(local_path):
os.remove(local_path)
return None
with ThreadPoolExecutor(max_workers=max_workers) as executor:
@@ -184,7 +198,7 @@ class Downloader(QObject):
return None
if url in self._cache:
cached_path = self._cache[url]
if is_complete_download(cached_path):
if os.path.exists(cached_path):
if os.path.abspath(cached_path) == os.path.abspath(local_path):
return cached_path
else:
@@ -196,7 +210,7 @@ class Downloader(QObject):
return None
if url in self._cache:
cached_path = self._cache[url]
if is_complete_download(cached_path) and os.path.abspath(cached_path) == os.path.abspath(local_path):
if os.path.exists(cached_path) and os.path.abspath(cached_path) == os.path.abspath(local_path):
return cached_path
result = download_with_cache(url, local_path, timeout, self)
with self._global_lock:
@@ -227,7 +241,7 @@ class Downloader(QObject):
emitted_urls.add(url)
continue
cached_path = self._cache.get(url)
if (cached_path and is_complete_download(cached_path)
if (cached_path and os.path.exists(cached_path)
and os.path.abspath(cached_path) == os.path.abspath(path)):
if on_result and url not in emitted_urls:
on_result(url, cached_path)
@@ -275,7 +289,7 @@ class Downloader(QObject):
def download_async(self, url: str, local_path: str, timeout: int = 5, callback: Callable[[str | None], None] | None = None, parallel: bool = False) -> QThread | None:
with self._global_lock:
previous_error = url in self._last_error
cached = not previous_error and is_complete_download(local_path)
cached = not previous_error and os.path.exists(local_path)
if cached:
self._cache[url] = local_path
if previous_error or cached:
+5 -10
View File
@@ -517,7 +517,7 @@ class GameCard(AnimatedCard):
self.egsLabel.setVisible(self.egs_visible and not self.vertical_layout)
self.nativeLabel = SourceCorner(
icon=self.theme_manager.get_icon("badge_native", as_path=True),
icon=self.theme_manager.get_icon("badge_linux", as_path=True),
config=corner_config,
parent=self.coverWidget,
)
@@ -669,7 +669,7 @@ class GameCard(AnimatedCard):
(self.steamLabel, "badge_steam"),
(self.gogLabel, "badge_gog"),
(self.egsLabel, "badge_egs"),
(self.nativeLabel, "badge_native"),
(self.nativeLabel, "badge_linux"),
(self.portprotonLabel, "badge_portproton"),
):
icon = self.theme_manager.get_icon(
@@ -817,8 +817,9 @@ class GameCard(AnimatedCard):
radius = int(self.card_layout_cfg.get("cover_radius", 8) * self._scale)
aspect_mode = Qt.AspectRatioMode.KeepAspectRatio
else:
target_width = self.coverLabel.minimumWidth()
target_height = self.coverLabel.minimumHeight()
target_width = int(self.base_card_width * self._scale)
cover_ratio = self.card_layout_cfg.get("cover_aspect_ratio", 1.5)
target_height = int(target_width * cover_ratio)
radius = int(self.card_layout_cfg.get("cover_radius", 15) * self._scale)
aspect_mode = Qt.AspectRatioMode.KeepAspectRatioByExpanding
scaled_pixmap = self.base_pixmap.scaled(
@@ -827,12 +828,6 @@ class GameCard(AnimatedCard):
aspect_mode,
Qt.TransformationMode.SmoothTransformation,
)
if not self.list_layout:
scaled_pixmap = scaled_pixmap.copy(
(scaled_pixmap.width() - target_width) // 2,
(scaled_pixmap.height() - target_height) // 2,
target_width, target_height,
)
rounded_pixmap = round_corners(scaled_pixmap, radius)
try:
self.coverLabel.setPixmap(rounded_pixmap)
+14 -68
View File
@@ -10,7 +10,6 @@ import time
import zlib
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor, as_completed
from html import unescape
from pathlib import Path
from urllib.parse import parse_qs, urlparse
@@ -316,12 +315,7 @@ class GOGAPI:
def load_library(self) -> list[dict]:
"""Load the cached GOG library."""
data = self._load_json(self.library_path, [])
if not isinstance(data, list):
return []
for game in data:
if isinstance(game, dict) and isinstance(game.get("description"), str):
game["description"] = self._short_description(game["description"])
return data
return data if isinstance(data, list) else []
def clear_library_cache(self) -> None:
"""Remove cached GOG covers and descriptions."""
@@ -696,7 +690,7 @@ class GOGAPI:
),
{},
)
description = self._short_description(self._localized_value(data.get("summary")))
description = self._localized_value(data.get("summary"))
language = get_metadata_language().lower()
try:
product_response = requests.get(
@@ -709,11 +703,18 @@ class GOGAPI:
)
product_response.raise_for_status()
product_description = product_response.json().get("description", {})
description = (
self._short_description(str(product_description.get("lead") or ""))
or self._short_description(str(product_description.get("full") or ""))
or description
)
localized_lead = str(product_description.get("lead") or "")
if localized_lead:
paragraphs = re.split(
r"(?:<br\s*/?>\s*){2,}", localized_lead, flags=re.IGNORECASE
)
paragraph_count = (
2 if re.match(r"\s*<(?:b|strong)>", paragraphs[0], re.IGNORECASE)
else 1
)
description = "<br><br>".join(
paragraph.strip() for paragraph in paragraphs[:paragraph_count]
)
except requests.RequestException as error:
logger.warning(
"Failed to load localized GOG description for %s: %s",
@@ -731,61 +732,6 @@ class GOGAPI:
"steam_appid": str(steam_release.get("external_id", "")),
}
@staticmethod
def _short_description(description: str) -> str:
# GOG uses these modules for storefront callouts, not the synopsis.
intro = re.sub(
r"<p\b[^>]*\bclass\s*=\s*(['\"])module\1[^>]*>.*?</p\s*>", "",
description, flags=re.IGNORECASE | re.DOTALL,
)
# Store cross-sells start with a linked cover inside an overflow box.
intro = re.sub(
r"<div\s+style=(['\"])overflow:\s*hidden;?\1\s*>\s*"
r"<a\b[^>]*>\s*<img\b[^>]*>\s*</a>.*?</div\s*>",
"", intro, flags=re.IGNORECASE | re.DOTALL,
)
intro = re.sub(r"<img\b[^>]*>", "", intro, flags=re.IGNORECASE)
intro = re.split(r"<(?:ul|ol|li)\b", intro, maxsplit=1, flags=re.IGNORECASE)[0]
intro = re.sub(
r"(?:<b>\s*)?<h[1-6]\b[^>]*>.*?</h[1-6]\s*>(?:\s*</b>)?",
"<br><br>", intro,
flags=re.IGNORECASE | re.DOTALL,
)
paragraphs = re.split(
r"(?:<br\s*/?>\s*){2,}|</?(?:p|div|hr)\b[^>]*>|\r?\n[ \t]*\r?\n",
intro, flags=re.IGNORECASE,
)
content = []
for paragraph in paragraphs:
text = unescape(re.sub(r"<[^>]*>", "", paragraph)).strip()
if not text or re.fullmatch(
r"(?:Внимание!\s*)?В этой игре нет русской локализации\.?"
r"|The full version of .+? is available on GOG\.com\.\s+"
r"You can (?:buy|purchase) it here[.!]?",
text, re.IGNORECASE,
):
continue
paragraph = re.sub(
r"^(?:\s*<br\s*/?>)+|(?:(?:<br\s*/?>|&nbsp;)\s*)+$", "", paragraph,
flags=re.IGNORECASE,
).strip()
if re.search(r"</?[a-z][^>]*>", paragraph, re.IGNORECASE):
# Qt's AutoText detection stops at the first plain newline.
paragraph = re.sub(r"<(/?)strong\s*>", r"<\1b>", paragraph, flags=re.IGNORECASE)
paragraph = re.sub(r"(?:\r?\n)+", "<br>", paragraph)
content.append(paragraph)
paragraphs = content
# Prefer the synopsis over a standalone italic epigraph.
if len(paragraphs) > 1 and re.fullmatch(
r"(?:(?:<b>|<strong>))*<(i|em)>[^<]*</\1>(?:(?:</b>|</strong>))*",
paragraphs[0], re.IGNORECASE,
):
return paragraphs[1]
# Keep a standalone bold notice together with the introduction.
if paragraphs and re.fullmatch(r"<(b|strong)>[^<]*</\1>", paragraphs[0], re.IGNORECASE):
return "<br><br>".join(paragraphs[:2])
return paragraphs[0] if paragraphs else ""
@staticmethod
def _localized_value(values: dict | None) -> str:
if not isinstance(values, dict):
+20 -25
View File
@@ -23,22 +23,20 @@ class GameEntry:
class SearchConfig:
"""Search configuration."""
token: str
hp_key: str | None = None
hp_val: str | None = None
hp_key: str
hp_val: str
class HTTPClient:
"""HTTP client for HowLongToBeat API."""
BASE_URL = 'https://howlongtobeat.com/'
SEARCH_URL = BASE_URL + "api/search/site"
AUTH_URL = SEARCH_URL + "/init"
AUTH_URL = BASE_URL + "api/bleed/init"
SEARCH_URL = BASE_URL + "api/bleed"
def __init__(self, timeout: int = 60):
self.timeout = timeout
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'application/json',
'Origin': self.BASE_URL.rstrip('/'),
'referer': self.BASE_URL
})
proxy_settings = proxy_config.get_proxy()
@@ -54,18 +52,15 @@ class HTTPClient:
)
response.raise_for_status()
data = response.json()
except requests.RequestException as exc:
status = exc.response.status_code if exc.response is not None else type(exc).__name__
logger.warning("HLTB initialization failed: %s", status)
except (requests.RequestException, ValueError):
return None
token = data.get("token") if isinstance(data, dict) else None
if not isinstance(token, str) or not token:
logger.warning("HLTB initialization returned no token")
if not data.get("token") or not data.get("hpKey") or not data.get("hpVal"):
return None
hp_key, hp_val = data.get("hpKey"), data.get("hpVal")
if isinstance(hp_key, str) and hp_key and isinstance(hp_val, str) and hp_val:
return SearchConfig(token, hp_key, hp_val)
return SearchConfig(token)
return SearchConfig(
token=data["token"],
hp_key=data["hpKey"],
hp_val=data["hpVal"]
)
def search_games(self, game_name: str, page: int = 1, config: SearchConfig | None = None) -> str | None:
if not config:
@@ -76,10 +71,11 @@ class HTTPClient:
payload = self._build_search_payload(game_name, page, config)
headers = {
'content-type': 'application/json',
'x-auth-token': config.token
'accept': '*/*',
'x-auth-token': config.token,
'x-hp-key': config.hp_key,
'x-hp-val': config.hp_val
}
if config.hp_key and config.hp_val:
headers.update({'x-hp-key': config.hp_key, 'x-hp-val': config.hp_val})
try:
response = self.session.post(
self.SEARCH_URL,
@@ -110,15 +106,14 @@ class HTTPClient:
'platform': "",
'sortCategory': "popular",
'rangeCategory': "main",
'rangeTime': {'min': None, 'max': None},
'rangeTime': {'min': 0, 'max': 0},
'gameplay': {
'perspective': "",
'flow': "",
'genre': "",
"difficulty": ""
},
'year': "",
'modifier': ""
'rangeYear': {'max': "", 'min': ""}
},
'users': {'sortCategory': "postcount"},
'lists': {'sortCategory': "follows"},
@@ -126,10 +121,10 @@ class HTTPClient:
'sort': 0,
'randomizer': 0
},
'useCache': True
'useCache': True,
'fields': ["comp_main", "comp_plus", "comp_100"]
}
if config.hp_key and config.hp_val:
payload[config.hp_key] = config.hp_val
payload[config.hp_key] = config.hp_val
return payload
class ResultParser:
+5 -7
View File
@@ -10,7 +10,7 @@ from PySide6.QtWidgets import QSpacerItem, QGraphicsPixmapItem, QDialog, QApplic
from PIL import Image, ImageQt, ImageSequence
from portprotonqt.config import CACHE_DIR, ui_config
from portprotonqt.theme_manager import ThemeManager, load_theme
from portprotonqt.downloader import Downloader, is_complete_download
from portprotonqt.downloader import Downloader
from portprotonqt.icon_extractor import generate_thumbnail
from portprotonqt.logger import get_logger
from portprotonqt.qt_utils import get_device_pixel_ratio
@@ -223,12 +223,10 @@ def set_animated_cover(label: QLabel, path: str, width: int, height: int, radius
if not QFile.exists(path):
return False
if ext in (".png", ".apng") and _is_png_cover(path):
_set_cover_mask(label, width, height, radius)
animation = _PillowAnimatedCover(label, path, width, height, radius)
if not animation.start():
label.removeEventFilter(animation)
animation.deleteLater()
return False
_set_cover_mask(label, width, height, radius)
_animated_cover_movies[label] = animation
_animated_cover_radii[label] = radius
return True
@@ -471,7 +469,7 @@ def load_pixmap_async(
appid = parts[idx + 1]
if appid:
local_path = os.path.join(image_folder, f"{appid}.jpg")
if is_complete_download(local_path):
if os.path.exists(local_path):
pixmap = QPixmap(local_path)
# Check if the pixmap loaded successfully
if pixmap.isNull():
@@ -508,7 +506,7 @@ def load_pixmap_async(
local_path = os.path.join(image_folder, filename)
logger.debug("SGDB cover check: %s exists=%s", local_path, os.path.exists(local_path))
if is_complete_download(local_path):
if os.path.exists(local_path):
pixmap = QPixmap(local_path)
# Check if the pixmap loaded successfully
if pixmap.isNull():
@@ -545,7 +543,7 @@ def load_pixmap_async(
if not filename:
filename = f"{app_name}{_get_cover_url_suffix(cover)}"
local_path = os.path.join(image_folder, filename)
if is_complete_download(local_path):
if os.path.exists(local_path):
pixmap = QPixmap(local_path)
# Check if the pixmap loaded successfully
if pixmap.isNull():
+11 -13
View File
@@ -1,8 +1,10 @@
from __future__ import annotations
import time
import os
import sys
import math
from typing import Protocol, cast, Any
from evdev import UInput, ecodes
from typing import TYPE_CHECKING, Protocol, cast, Any
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
@@ -27,6 +29,9 @@ 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):
@@ -253,6 +258,10 @@ 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)
@@ -290,7 +299,6 @@ class InputManager(
except Exception as e:
logger.error("EMUL: Error closing virtual mouse: %s", e)
self.ui = None
self._keyboard_mouse_drag = False
self.mouse_emulation_thread = None
self.stick_x_raw = 0
self.stick_y_raw = 0
@@ -441,7 +449,6 @@ class InputManager(
except Exception as e:
logger.error("EMUL: Error closing virtual mouse: %s", e)
self.ui = None
self._keyboard_mouse_drag = False
self.mouse_emulation_enabled = False
self.stick_x_raw = 0
self.stick_y_raw = 0
@@ -524,15 +531,6 @@ class InputManager(
self.ui.write(ecodes.EV_REL, ecodes.REL_WHEEL, steps)
self.ui.syn()
def _set_keyboard_mouse_drag(self, held: bool) -> bool:
if held == getattr(self, '_keyboard_mouse_drag', False):
return False
if self.ui:
self.ui.write(ecodes.EV_KEY, ecodes.BTN_LEFT, int(held))
self.ui.syn()
self._keyboard_mouse_drag = held
return True
def click_left(self):
"""Left mouse button click"""
if self.ui:
+1 -1
View File
@@ -313,7 +313,7 @@ class DpadInputMixin(InputMixin):
def handle_dpad_slot(self, code: int, value: int, current_time: float) -> None:
keyboard = getattr(self._parent, 'system_keyboard', None)
if keyboard is not None and keyboard.isVisible():
if value == 0 or self._should_skip_regular_events():
if value == 0:
self._reset_dpad_repeat()
return
directions = {PAD_DPAD_X: ('left', 'right'), PAD_AXIS_LEFT_X: ('left', 'right'),
+11 -6
View File
@@ -15,6 +15,7 @@ from PySide6.QtWidgets import (
QListWidget,
QMenu,
QMessageBox,
QScrollArea,
QTableWidget,
QWidget,
)
@@ -472,12 +473,16 @@ class KeyboardInputMixin(InputMixin):
def _focus_first_game_card(self, container: QWidget | None) -> bool:
if container is None:
return False
cards = [card for card in container.findChildren(AnimatedCard) if card.isVisible() and card.isEnabled()]
if not cards:
return False
first_card = min(cards, key=lambda card: (card.y(), card.x()))
self._focus_grid_card(first_card)
return True
for card in container.findChildren(AnimatedCard):
if card.isVisible() and card.isEnabled():
card.setFocus(Qt.FocusReason.OtherFocusReason)
scroll_area = container.parentWidget()
while scroll_area and not isinstance(scroll_area, QScrollArea):
scroll_area = scroll_area.parentWidget()
if isinstance(scroll_area, QScrollArea):
scroll_area.ensureWidgetVisible(card, 50, 50)
return True
return False
def _focus_first_library_card(self) -> bool:
container = getattr(self._parent, "gamesListWidget", None)
+6 -10
View File
@@ -115,7 +115,6 @@ class GamepadRuntimeMixin(InputMixin):
def _reset_input_state(self) -> None:
"""Reset cached joystick state when the active device changes."""
self._set_keyboard_mouse_drag(False)
self._button_states.clear()
self._hat_states.clear()
self._axis_states.clear()
@@ -234,8 +233,6 @@ class GamepadRuntimeMixin(InputMixin):
if self._button_states.get(button_index) == value:
return
self._button_states[button_index] = value
if not value and button_code in BUTTONS['confirm'] and self._set_keyboard_mouse_drag(False):
return
if getattr(self._parent, "boot_animation", None) is not None:
self.button_event.emit(button_code, value)
return
@@ -269,7 +266,6 @@ class GamepadRuntimeMixin(InputMixin):
(button_code == PAD_BUTTON_START and self.select_held)
)
if emulation_combo:
self._set_keyboard_mouse_drag(False)
self.emulation_triggered = not self.emulation_triggered
self.pending_menu_fullscreen_time = 0.0
return emulation_combo
@@ -292,9 +288,6 @@ class GamepadRuntimeMixin(InputMixin):
keyboard.toggle()
return True
if keyboard.isVisible():
if button_code in BUTTONS['confirm'] and self._is_mouse_emulation_active() and self.ui:
self._set_keyboard_mouse_drag(bool(value))
return True
actions = {'confirm': 'confirm', 'back': 'back', 'menu': 'back',
'prev_tab': 'language', 'next_tab': 'shift', 'add_game': 'backspace'}
if button_code == PAD_BUTTON_START and not value:
@@ -337,9 +330,9 @@ class GamepadRuntimeMixin(InputMixin):
elif hat_value[0] > 0:
self.move_mouse(10, 0)
if previous_value[1] != hat_value[1]:
if hat_value[1] < 0:
if hat_value[1] > 0:
self.move_mouse(0, -10)
elif hat_value[1] > 0:
elif hat_value[1] < 0:
self.move_mouse(0, 10)
if self._should_skip_regular_events():
@@ -394,13 +387,16 @@ class GamepadRuntimeMixin(InputMixin):
def _is_mouse_emulation_active(self) -> bool:
"""Return True when the gamepad currently drives mouse emulation."""
keyboard = getattr(getattr(self, '_parent', None), 'system_keyboard', None)
if keyboard is not None and keyboard.isVisible():
return False
return self.mouse_emulation_enabled and self.emulation_active and self.emulation_triggered
def _should_skip_regular_events(self) -> bool:
"""Skip regular UI events while mouse emulation owns the controller."""
keyboard = getattr(getattr(self, '_parent', None), 'system_keyboard', None)
if keyboard is not None and keyboard.isVisible():
return self._is_mouse_emulation_active() and bool(self.ui)
return False
if getattr(self, '_gamepad_polling_suspended', False):
return True
return self._is_mouse_emulation_active() and QApplication.activeWindow() is not None
@@ -420,13 +420,6 @@ msgstr ""
msgid "Refresh Grid"
msgstr ""
msgid "Cannot launch game while another game is running"
msgstr ""
#, python-brace-format
msgid "Failed to launch game: {0}"
msgstr ""
msgid "Never"
msgstr ""
@@ -486,6 +479,9 @@ msgstr ""
msgid "PortProton start script not found"
msgstr ""
msgid "Cannot launch game while another game is running"
msgstr ""
msgid "Invalid command format (empty exec line)"
msgstr ""
@@ -493,7 +489,7 @@ msgid "Invalid command format (native)"
msgstr ""
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgid "Failed to launch game: {0}"
msgstr ""
msgid "Choose Folder"
@@ -696,10 +692,9 @@ msgstr ""
msgid "Run After / Wrapper"
msgstr ""
#, python-format
msgid ""
"Path to a second .exe, script, or wrapper command. Use %command% for the "
"game command"
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
"--user --scope --slice=app.slice"
msgstr ""
msgid "CPU Cores Limit"
@@ -800,6 +795,10 @@ msgstr ""
msgid "No favorites"
msgstr ""
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr ""
msgid "Debug log mode was launched"
msgstr ""
@@ -1063,6 +1062,10 @@ msgstr ""
msgid "Download Selected"
msgstr ""
#, python-brace-format
msgid "Error loading WINE/Proton: {error}"
msgstr ""
msgid "Version WINE/Proton"
msgstr ""
@@ -1082,9 +1085,6 @@ msgstr ""
msgid "Select to remove this WINE/Proton"
msgstr ""
msgid "Loading…"
msgstr ""
#, python-brace-format
msgid "Selected {} WINE/Proton:\n"
msgstr ""
@@ -1189,9 +1189,6 @@ msgstr ""
msgid "Exe Settings"
msgstr ""
msgid "Native"
msgstr ""
msgid "Edit user.conf"
msgstr ""
@@ -2006,9 +2003,6 @@ msgstr ""
msgid "Mouse Emulation"
msgstr ""
msgid "System Keyboard"
msgstr ""
msgid "Connect"
msgstr ""
@@ -2129,6 +2123,9 @@ msgstr ""
msgid "Select installation folder"
msgstr ""
msgid "Another download is running"
msgstr ""
msgid "Another GOG operation is already running"
msgstr ""
@@ -2514,6 +2511,9 @@ msgstr ""
msgid "Light"
msgstr ""
msgid "Loading…"
msgstr ""
msgid "Failed to load themes"
msgstr ""
@@ -433,13 +433,6 @@ msgstr "Entpacken"
msgid "Refresh Grid"
msgstr "Ansicht aktualisieren"
msgid "Cannot launch game while another game is running"
msgstr "Das Spiel kann nicht gestartet werden, während ein anderes Spiel läuft"
#, python-brace-format
msgid "Failed to launch game: {0}"
msgstr "Spiel konnte nicht gestartet werden: {0}"
msgid "Never"
msgstr "Niemals"
@@ -504,6 +497,9 @@ msgstr "Spiel nicht gefunden."
msgid "PortProton start script not found"
msgstr "PortProton-Startskript nicht gefunden"
msgid "Cannot launch game while another game is running"
msgstr "Das Spiel kann nicht gestartet werden, während ein anderes Spiel läuft"
msgid "Invalid command format (empty exec line)"
msgstr "Ungültiges Befehlsformat (leere exec-Zeile)"
@@ -511,8 +507,8 @@ msgid "Invalid command format (native)"
msgstr "Ungültiges Befehlsformat"
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr "Ausführen \"{name}\" mit PortProton"
msgid "Failed to launch game: {0}"
msgstr "Spiel konnte nicht gestartet werden: {0}"
msgid "Choose Folder"
msgstr "Ordner auswählen"
@@ -754,13 +750,12 @@ msgstr ""
msgid "Run After / Wrapper"
msgstr "Nach Start ausführen / Wrapper"
#, fuzzy, python-format
msgid ""
"Path to a second .exe, script, or wrapper command. Use %command% for the "
"game command"
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
"--user --scope --slice=app.slice"
msgstr ""
"Pfad zu einer zweiten .exe-Datei, einem Skript oder einem Wrapper-Befehl."
" Beispiel: systemd-run --user --scope --slice=app.slice"
"Pfad zu einer zweiten .exe-Datei, einem Skript oder einem Wrapper-Befehl. "
"Beispiel: systemd-run --user --scope --slice=app.slice"
msgid "CPU Cores Limit"
msgstr "CPU-Kerne-Limit"
@@ -877,6 +872,10 @@ msgstr "Keine aktuellen Spiele"
msgid "No favorites"
msgstr "Keine Favoriten"
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr "Ausführen \"{name}\" mit PortProton"
msgid "Debug log mode was launched"
msgstr "Der Debug-Protokollmodus wurde gestartet"
@@ -1146,6 +1145,10 @@ msgstr "Herunterladen: "
msgid "Download Selected"
msgstr "Ausgewählte herunterladen"
#, python-brace-format
msgid "Error loading WINE/Proton: {error}"
msgstr "Fehler beim Herunterladen von WINE/Proton: {error}"
msgid "Version WINE/Proton"
msgstr "WINE/Proton Version"
@@ -1165,9 +1168,6 @@ msgstr "Installiert"
msgid "Select to remove this WINE/Proton"
msgstr "Wähle, um WINE/Proton zu entfernen"
msgid "Loading…"
msgstr "Laden…"
#, python-brace-format
msgid "Selected {} WINE/Proton:\n"
msgstr "Ausgewählt {} WINE/Proton:\n"
@@ -1278,10 +1278,6 @@ msgstr "Globale Spieleinstellungen"
msgid "Exe Settings"
msgstr "Einstellungen für die exe-Datei"
#, fuzzy
msgid "Native"
msgstr "Nach Bildausgabe"
msgid "Edit user.conf"
msgstr "user.conf bearbeiten"
@@ -2114,10 +2110,6 @@ msgstr "Vollbild"
msgid "Mouse Emulation"
msgstr "Mausemulation"
#, fuzzy
msgid "System Keyboard"
msgstr "Tastatur-Eingabe abfangen"
msgid "Connect"
msgstr "Verbinden"
@@ -2238,6 +2230,9 @@ msgstr "Aktualisierung der Epic-Bibliothek fehlgeschlagen: {0}"
msgid "Select installation folder"
msgstr "Installationsordner auswählen"
msgid "Another download is running"
msgstr "Ein weiterer Download läuft"
msgid "Another GOG operation is already running"
msgstr "Eine andere GOG-Aktion läuft bereits"
@@ -2629,6 +2624,9 @@ msgstr "Dunkel"
msgid "Light"
msgstr "Hell"
msgid "Loading…"
msgstr "Laden…"
msgid "Failed to load themes"
msgstr "Laden der Themes fehlgeschlagen"
@@ -434,13 +434,6 @@ msgstr "Extrayendo"
msgid "Refresh Grid"
msgstr "Actualizar cuadrícula"
msgid "Cannot launch game while another game is running"
msgstr "No se puede iniciar el juego mientras hay otro en ejecución"
#, python-brace-format
msgid "Failed to launch game: {0}"
msgstr "Error al iniciar el juego: {0}"
msgid "Never"
msgstr "Nunca"
@@ -504,6 +497,9 @@ msgstr "Juego no encontrado."
msgid "PortProton start script not found"
msgstr "No se ha encontrado el script de inicio de PortProton"
msgid "Cannot launch game while another game is running"
msgstr "No se puede iniciar el juego mientras hay otro en ejecución"
msgid "Invalid command format (empty exec line)"
msgstr "Formato de comando no válido (línea de ejecución vacía)"
@@ -511,8 +507,8 @@ msgid "Invalid command format (native)"
msgstr "Formato de comando no válido (nativo)"
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr "Iniciar «{name}» con PortProton"
msgid "Failed to launch game: {0}"
msgstr "Error al iniciar el juego: {0}"
msgid "Choose Folder"
msgstr "Seleccionar carpeta"
@@ -769,10 +765,9 @@ msgstr ""
msgid "Run After / Wrapper"
msgstr "Ejecutar después / Envoltorio"
#, fuzzy, python-format
msgid ""
"Path to a second .exe, script, or wrapper command. Use %command% for the "
"game command"
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
"--user --scope --slice=app.slice"
msgstr ""
"Ruta a un segundo archivo .exe, script o comando de envoltura. Ejemplo: "
"systemd-run --user --scope --slice=app.slice"
@@ -892,6 +887,10 @@ msgstr "Sin juegos recientes"
msgid "No favorites"
msgstr "Sin favoritos"
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr "Iniciar «{name}» con PortProton"
msgid "Debug log mode was launched"
msgstr "Se ha iniciado el modo de registro de depuración"
@@ -1160,6 +1159,10 @@ msgstr "Descargando: "
msgid "Download Selected"
msgstr "Descargar seleccionados"
#, python-brace-format
msgid "Error loading WINE/Proton: {error}"
msgstr "Error al cargar WINE/Proton: {error}"
msgid "Version WINE/Proton"
msgstr "Versión de WINE/Proton"
@@ -1179,9 +1182,6 @@ msgstr "Instalado"
msgid "Select to remove this WINE/Proton"
msgstr "Seleccione para eliminar WINE/Proton"
msgid "Loading…"
msgstr "Cargando…"
#, python-brace-format
msgid "Selected {} WINE/Proton:\n"
msgstr "Seleccionado {} WINE/Proton:\n"
@@ -1291,9 +1291,6 @@ msgstr "Ajustes de Wine"
msgid "Exe Settings"
msgstr ""
msgid "Native"
msgstr ""
msgid "Edit user.conf"
msgstr ""
@@ -2117,9 +2114,6 @@ msgstr ""
msgid "Mouse Emulation"
msgstr ""
msgid "System Keyboard"
msgstr ""
msgid "Connect"
msgstr ""
@@ -2241,6 +2235,10 @@ msgstr "Error al iniciar el juego: {0}"
msgid "Select installation folder"
msgstr ""
#, fuzzy
msgid "Another download is running"
msgstr "Descargando"
msgid "Another GOG operation is already running"
msgstr ""
@@ -2635,6 +2633,9 @@ msgstr ""
msgid "Light"
msgstr ""
msgid "Loading…"
msgstr "Cargando…"
msgid "Failed to load themes"
msgstr "Error al cargar los temas"
+21 -21
View File
@@ -9,7 +9,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PortProtonQt 0.1.1\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2026-11-20 23:00+0500\n"
"POT-Creation-Date: 2026-10-24 18:13+0500\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@@ -416,13 +416,6 @@ msgstr ""
msgid "Refresh Grid"
msgstr ""
msgid "Cannot launch game while another game is running"
msgstr ""
#, python-brace-format
msgid "Failed to launch game: {0}"
msgstr ""
msgid "Never"
msgstr ""
@@ -482,6 +475,9 @@ msgstr ""
msgid "PortProton start script not found"
msgstr ""
msgid "Cannot launch game while another game is running"
msgstr ""
msgid "Invalid command format (empty exec line)"
msgstr ""
@@ -489,7 +485,7 @@ msgid "Invalid command format (native)"
msgstr ""
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgid "Failed to launch game: {0}"
msgstr ""
msgid "Choose Folder"
@@ -692,10 +688,9 @@ msgstr ""
msgid "Run After / Wrapper"
msgstr ""
#, python-format
msgid ""
"Path to a second .exe, script, or wrapper command. Use %command% for the "
"game command"
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
"--user --scope --slice=app.slice"
msgstr ""
msgid "CPU Cores Limit"
@@ -796,6 +791,10 @@ msgstr ""
msgid "No favorites"
msgstr ""
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr ""
msgid "Debug log mode was launched"
msgstr ""
@@ -1059,6 +1058,10 @@ msgstr ""
msgid "Download Selected"
msgstr ""
#, python-brace-format
msgid "Error loading WINE/Proton: {error}"
msgstr ""
msgid "Version WINE/Proton"
msgstr ""
@@ -1078,9 +1081,6 @@ msgstr ""
msgid "Select to remove this WINE/Proton"
msgstr ""
msgid "Loading…"
msgstr ""
#, python-brace-format
msgid "Selected {} WINE/Proton:\n"
msgstr ""
@@ -1185,9 +1185,6 @@ msgstr ""
msgid "Exe Settings"
msgstr ""
msgid "Native"
msgstr ""
msgid "Edit user.conf"
msgstr ""
@@ -2002,9 +1999,6 @@ msgstr ""
msgid "Mouse Emulation"
msgstr ""
msgid "System Keyboard"
msgstr ""
msgid "Connect"
msgstr ""
@@ -2125,6 +2119,9 @@ msgstr ""
msgid "Select installation folder"
msgstr ""
msgid "Another download is running"
msgstr ""
msgid "Another GOG operation is already running"
msgstr ""
@@ -2511,6 +2508,9 @@ msgstr ""
msgid "Light"
msgstr ""
msgid "Loading…"
msgstr ""
msgid "Failed to load themes"
msgstr ""
@@ -433,13 +433,6 @@ msgstr "Extraindo"
msgid "Refresh Grid"
msgstr "Atualizar Grade"
msgid "Cannot launch game while another game is running"
msgstr "Não é possível iniciar o jogo enquanto outro jogo estiver em execução"
#, python-brace-format
msgid "Failed to launch game: {0}"
msgstr "Falha ao iniciar o jogo: {0}"
msgid "Never"
msgstr "Nunca"
@@ -503,6 +496,9 @@ msgstr "Jogo não encontrado."
msgid "PortProton start script not found"
msgstr "Script de inicialização do PortProton não encontrado"
msgid "Cannot launch game while another game is running"
msgstr "Não é possível iniciar o jogo enquanto outro jogo estiver em execução"
msgid "Invalid command format (empty exec line)"
msgstr "Formato de comando inválido (linha exec vazia)"
@@ -510,8 +506,8 @@ msgid "Invalid command format (native)"
msgstr "Formato de comando inválido (nativo)"
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr "Iniciar \"{name}\" com o PortProton"
msgid "Failed to launch game: {0}"
msgstr "Falha ao iniciar o jogo: {0}"
msgid "Choose Folder"
msgstr "Escolher Pasta"
@@ -754,10 +750,9 @@ msgstr ""
msgid "Run After / Wrapper"
msgstr "Executar após / Wrapper"
#, fuzzy, python-format
msgid ""
"Path to a second .exe, script, or wrapper command. Use %command% for the "
"game command"
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
"--user --scope --slice=app.slice"
msgstr ""
"Caminho para um segundo arquivo .exe, script ou comando wrapper. Exemplo:"
" systemd-run --user --scope --slice=app.slice"
@@ -879,6 +874,10 @@ msgstr "Nenhum jogo recente"
msgid "No favorites"
msgstr "Nenhum favorito"
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr "Iniciar \"{name}\" com o PortProton"
msgid "Debug log mode was launched"
msgstr "O modo de log de depuração foi iniciado"
@@ -1146,6 +1145,10 @@ msgstr "Baixando: "
msgid "Download Selected"
msgstr "Baixar Selecionados"
#, python-brace-format
msgid "Error loading WINE/Proton: {error}"
msgstr "Erro ao carregar WINE/Proton: {error}"
msgid "Version WINE/Proton"
msgstr "Versão WINE/Proton"
@@ -1165,9 +1168,6 @@ msgstr "Instalado"
msgid "Select to remove this WINE/Proton"
msgstr "Selecione para remover este WINE/Proton"
msgid "Loading…"
msgstr "Carregando…"
#, python-brace-format
msgid "Selected {} WINE/Proton:\n"
msgstr "{} WINE/Proton selecionado(s):\n"
@@ -1277,10 +1277,6 @@ msgstr "Configurações globais dos jogos"
msgid "Exe Settings"
msgstr "Configurações do Exe"
#, fuzzy
msgid "Native"
msgstr "Tardio"
msgid "Edit user.conf"
msgstr "Editar o arquivo user.conf"
@@ -2111,10 +2107,6 @@ msgstr "Tela Cheia"
msgid "Mouse Emulation"
msgstr "Emulação de Mouse"
#, fuzzy
msgid "System Keyboard"
msgstr "Capturar o teclado"
msgid "Connect"
msgstr "Conectar"
@@ -2235,6 +2227,9 @@ msgstr "Falha ao atualizar a biblioteca da Epic: {0}"
msgid "Select installation folder"
msgstr "Selecionar pasta de instalação"
msgid "Another download is running"
msgstr "Outro download está em andamento"
msgid "Another GOG operation is already running"
msgstr "Outra operação da GOG já está em execução"
@@ -2624,6 +2619,9 @@ msgstr "Escuro"
msgid "Light"
msgstr "Claro"
msgid "Loading…"
msgstr "Carregando…"
msgid "Failed to load themes"
msgstr "Falha ao carregar temas"
@@ -431,13 +431,6 @@ msgstr "Распаковка"
msgid "Refresh Grid"
msgstr "Обновить сетку"
msgid "Cannot launch game while another game is running"
msgstr "Невозможно запустить игру пока запущена другая"
#, python-brace-format
msgid "Failed to launch game: {0}"
msgstr "Не удалось запустить игру: {0}"
msgid "Never"
msgstr "Никогда"
@@ -500,6 +493,9 @@ msgstr "Игра не найдена."
msgid "PortProton start script not found"
msgstr "Скрипт запуска PortProton не найден"
msgid "Cannot launch game while another game is running"
msgstr "Невозможно запустить игру пока запущена другая"
msgid "Invalid command format (empty exec line)"
msgstr "Неправильный формат команды (пустая строка exec)"
@@ -507,8 +503,8 @@ msgid "Invalid command format (native)"
msgstr "Неверный формат команды (нативный)"
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr "Запустить «{name}» с помощью PortProton"
msgid "Failed to launch game: {0}"
msgstr "Не удалось запустить игру: {0}"
msgid "Choose Folder"
msgstr "Выбрать папку"
@@ -750,10 +746,9 @@ msgstr ""
msgid "Run After / Wrapper"
msgstr "Запустить после"
#, fuzzy, python-format
msgid ""
"Path to a second .exe, script, or wrapper command. Use %command% for the "
"game command"
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
"--user --scope --slice=app.slice"
msgstr ""
"Путь к второму файлу .exe, скрипту или команде-обёртке. Пример: systemd-"
"run --user --scope --slice=app.slice"
@@ -877,6 +872,10 @@ msgstr "Нет недавних игр"
msgid "No favorites"
msgstr "Нет избранных"
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr "Запустить «{name}» с помощью PortProton"
msgid "Debug log mode was launched"
msgstr "Запущен режим логирования"
@@ -1144,6 +1143,10 @@ msgstr "Скачивание: "
msgid "Download Selected"
msgstr "Скачать выбранное"
#, python-brace-format
msgid "Error loading WINE/Proton: {error}"
msgstr "Ошибка загрузки WINE/Proton: {error}"
msgid "Version WINE/Proton"
msgstr "Версия WINE/Proton"
@@ -1163,9 +1166,6 @@ msgstr "Установленные"
msgid "Select to remove this WINE/Proton"
msgstr "Выберите, чтобы удалить WINE/Proton"
msgid "Loading…"
msgstr "Загрузка…"
#, python-brace-format
msgid "Selected {} WINE/Proton:\n"
msgstr "Выбрано {} WINE/Proton:\n"
@@ -1275,10 +1275,6 @@ msgstr "Глобальные настройки игры"
msgid "Exe Settings"
msgstr "Настройки EXE"
#, fuzzy
msgid "Native"
msgstr "После отображения кадра"
msgid "Edit user.conf"
msgstr "Изменить user.conf"
@@ -2107,10 +2103,6 @@ msgstr "Полный экран"
msgid "Mouse Emulation"
msgstr "Эмуляция мыши"
#, fuzzy
msgid "System Keyboard"
msgstr "Перехват нажатий кнопок клавиатуры"
msgid "Connect"
msgstr "Подключиться"
@@ -2229,6 +2221,9 @@ msgstr "Не удалось обновить библиотеку Epic: {0}"
msgid "Select installation folder"
msgstr "Выберите папку установки"
msgid "Another download is running"
msgstr "Другая загрузка уже выполняется"
msgid "Another GOG operation is already running"
msgstr "Другая операция GOG уже выполняется"
@@ -2614,6 +2609,9 @@ msgstr "Тёмная"
msgid "Light"
msgstr "Светлая"
msgid "Loading…"
msgstr "Загрузка…"
msgid "Failed to load themes"
msgstr "Не удалось загрузить темы"
@@ -422,13 +422,6 @@ msgstr "正在提取"
msgid "Refresh Grid"
msgstr "刷新网格"
msgid "Cannot launch game while another game is running"
msgstr "另一游戏正在运行时无法启动游戏"
#, python-brace-format
msgid "Failed to launch game: {0}"
msgstr "启动游戏失败:{0}"
msgid "Never"
msgstr "从不"
@@ -493,6 +486,9 @@ msgstr "未找到游戏。"
msgid "PortProton start script not found"
msgstr "未找到 PortProton 启动脚本"
msgid "Cannot launch game while another game is running"
msgstr "另一游戏正在运行时无法启动游戏"
msgid "Invalid command format (empty exec line)"
msgstr "命令格式无效(exec 行为空)"
@@ -500,8 +496,8 @@ msgid "Invalid command format (native)"
msgstr "命令格式无效(原生)"
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr "使用 PortProton 启动\"{name}\""
msgid "Failed to launch game: {0}"
msgstr "启动游戏失败:{0}"
msgid "Choose Folder"
msgstr "选择文件夹"
@@ -727,10 +723,9 @@ msgstr ""
msgid "Run After / Wrapper"
msgstr "运行后 / 包装器"
#, fuzzy, python-format
msgid ""
"Path to a second .exe, script, or wrapper command. Use %command% for the "
"game command"
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
"--user --scope --slice=app.slice"
msgstr "指向第二个 .exe、脚本或包装器命令的路径。示例:systemd-run --user --scope --slice=app.slice"
msgid "CPU Cores Limit"
@@ -841,6 +836,10 @@ msgstr "无最近游戏"
msgid "No favorites"
msgstr "无收藏"
#, python-brace-format
msgid "Launch \"{name}\" with PortProton"
msgstr "使用 PortProton 启动\"{name}\""
msgid "Debug log mode was launched"
msgstr "调试日志模式已启动"
@@ -1111,6 +1110,10 @@ msgstr "正在下载: "
msgid "Download Selected"
msgstr "下载选定项"
#, python-brace-format
msgid "Error loading WINE/Proton: {error}"
msgstr "加载 WINE/Proton 时出错:{error}"
msgid "Version WINE/Proton"
msgstr "WINE/Proton 版本"
@@ -1130,9 +1133,6 @@ msgstr "已安装"
msgid "Select to remove this WINE/Proton"
msgstr "选择以移除此 WINE/Proton"
msgid "Loading…"
msgstr "加载中…"
#, python-brace-format
msgid "Selected {} WINE/Proton:\n"
msgstr "已选择 {} 个 WINE/Proton:\n"
@@ -1243,10 +1243,6 @@ msgstr "保存设置"
msgid "Exe Settings"
msgstr "可执行文件设置"
#, fuzzy
msgid "Native"
msgstr "晚"
msgid "Edit user.conf"
msgstr "编辑 user.conf"
@@ -2064,10 +2060,6 @@ msgstr "全屏"
msgid "Mouse Emulation"
msgstr "鼠标模拟"
#, fuzzy
msgid "System Keyboard"
msgstr "捕获键盘"
msgid "Connect"
msgstr "连接"
@@ -2199,6 +2191,10 @@ msgstr "启动游戏失败:{0}"
msgid "Select installation folder"
msgstr "选择安装文件夹"
#, fuzzy
msgid "Another download is running"
msgstr "正在下载"
msgid "Another GOG operation is already running"
msgstr "另一个 GOG 操作正在运行中"
@@ -2598,6 +2594,9 @@ msgstr "深色"
msgid "Light"
msgstr "浅色"
msgid "Loading…"
msgstr "加载中…"
msgid "Failed to load themes"
msgstr "加载主题失败"
+197
View File
@@ -0,0 +1,197 @@
"""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", "")
if wine is not None:
wineserver = wine.with_name("wineserver")
if wineserver.is_file() and os.access(wineserver, os.X_OK):
environment["WINESERVER"] = str(wineserver)
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())
+43 -24
View File
@@ -29,7 +29,7 @@ from portprotonqt.detail_pages import DetailPageManager
from portprotonqt.portproton_api import PortProtonAPI, remove_empty_custom_data_dirs
from portprotonqt.gog_api import GOGAPI
from portprotonqt.egs_api import EGSAPI
from portprotonqt.native_games import NativeLibraryWorker, NATIVE_URI_PREFIX, get_native_launch, is_native_executable, read_native_game
from portprotonqt.native_games import NativeLibraryWorker, NATIVE_URI_PREFIX, get_native_launch, read_native_game
from portprotonqt.debug_utils import get_prefix_name
from portprotonqt.input_manager import InputManager, MainWindowProtocol
from portprotonqt.context_menu_manager import ContextMenuManager
@@ -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
self._show_system_tab = show_system_tab and sys.platform != "darwin"
self.system_tab_index = -1 # Default, set when system tab is created
self._animated_covers_suspended = False
@@ -1195,44 +1195,35 @@ class MainWindow(
dialog.deleteLater()
def _launch_native_game(self, exec_line: str, button: QPushButton | None = None) -> None:
target = Path(exec_line.removeprefix(NATIVE_URI_PREFIX))
is_shortcut = exec_line.startswith(NATIVE_URI_PREFIX)
desktop_path = Path(exec_line.removeprefix(NATIVE_URI_PREFIX))
if self.game_processes:
if getattr(self, "native_game_running", False) and self.game_start_exe == str(target):
if getattr(self, "native_game_running", False) and self.game_start_exe == str(desktop_path):
self.stop_running_game(button)
else:
QMessageBox.warning(self, _("Error"), _("Cannot launch game while another game is running"))
return
try:
if not target.is_absolute():
raise ValueError("Invalid native launch path")
if is_shortcut:
if target.suffix != ".desktop":
raise ValueError("Invalid native desktop path")
command, directory = get_native_launch(str(target))
else:
if not is_native_executable(str(target)):
raise PermissionError(str(target))
command, directory = [str(target)], str(target.parent)
if not desktop_path.is_absolute() or desktop_path.suffix != ".desktop":
raise ValueError("Invalid native desktop path")
command, directory = get_native_launch(str(desktop_path))
process = subprocess.Popen(command, cwd=directory, start_new_session=True, text=True)
except Exception as error:
logger.warning("Failed to launch native game %s: %s", target, error)
logger.warning("Failed to launch native game %s: %s", desktop_path, error)
QMessageBox.warning(self, _("Error"), _("Failed to launch game: {0}").format(error))
return
self.native_game_running = True
self.game_stopped_by_user = False
self.game_processes = [process]
self.current_running_button = button
self.target_exe = target.name
self.game_start_exe = str(target)
self.target_exe = desktop_path.name
self.game_start_exe = str(desktop_path)
self.game_start_exact_path = True
self.game_start_time = datetime.now()
self.game_launch_monotonic = time.monotonic()
self.game_launch_started = True
self.wine_download_seen = False
if is_shortcut:
save_last_launch(target.stem, self.game_start_time)
self._update_last_launch_after_start(str(target), self.game_start_time)
save_last_launch(desktop_path.stem, self.game_start_time)
self._update_last_launch_after_start(str(desktop_path), self.game_start_time)
self.launch_output_queue = Queue()
self.input_manager.suspend_gamepad_polling()
self._set_running_button_stop()
@@ -2499,7 +2490,7 @@ class MainWindow(
return extract_exec_target_path(exec_line) or ""
def _has_running_game_process(self) -> bool:
if getattr(self, "native_game_running", False):
if sys.platform == "darwin" or 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}
@@ -2706,6 +2697,17 @@ 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,6 +2721,8 @@ 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
@@ -2738,13 +2742,16 @@ class MainWindow(
if getattr(self, "native_game_running", False):
self._terminate_game_processes()
return True
if getattr(self, "launcher_process_only", False):
if sys.platform != "darwin" and getattr(self, "launcher_process_only", False):
if self._run_portproton_stop_command():
return True
self._analyze_short_launch()
if sys.platform != "darwin":
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:
@@ -2756,6 +2763,8 @@ 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
@@ -2777,6 +2786,8 @@ 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
@@ -3262,6 +3273,10 @@ 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()
@@ -3329,6 +3344,10 @@ 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,6 +1,7 @@
# Install Python source files
install_data(
['__init__.py',
'macos.py',
'appimage_integration.py',
'appimage_updater.py',
'cli.py',
+2 -1
View File
@@ -1,8 +1,9 @@
import ctypes
import sys
from dataclasses import dataclass
from pathlib import Path
GAMEPAD_LIBRARY_NAME = "libportprotonqt_gamepad.so"
GAMEPAD_LIBRARY_NAME = "libportprotonqt_gamepad.dylib" if sys.platform == "darwin" else "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
+2 -2
View File
@@ -32,9 +32,9 @@ NATIVE_ADVANCED_KEYS = frozenset({"LAUNCH_PARAMETERS", "PW_MESA_GL_VERSION_OVERR
def is_native_executable(path: str) -> bool:
"""Recognize native executables, not desktop shortcuts or Wine targets."""
"""Recognize native launch files while preserving Windows and disc formats."""
return (
not path.lower().endswith(LAUNCH_FILE_EXTENSIONS + (".desktop",))
Path(path).suffix.lower() not in LAUNCH_FILE_EXTENSIONS
and os.path.isfile(path)
and os.access(path, os.X_OK)
)
@@ -18,6 +18,11 @@ 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,4 +1,5 @@
import os
import sys
import shutil
import subprocess
from pathlib import Path
@@ -58,6 +59,13 @@ 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:
@@ -143,6 +151,8 @@ 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."),
@@ -394,6 +404,9 @@ 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,6 +16,7 @@ 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",
-6
View File
@@ -11,7 +11,6 @@ from portprotonqt.logger import get_logger
logger = get_logger(__name__)
SHUTDOWN_TIMEOUT_MS = 3000
MAX_EMOJI_LENGTH = 16
class SystemKeyboard(QObject):
@@ -78,11 +77,6 @@ class SystemKeyboard(QObject):
self.shift_pressed = False
elif isinstance(data, dict) and data.get('event') == 'shift':
self.shift_pressed = bool(data.get('value'))
elif isinstance(data, dict) and data.get('event') == 'emoji' and self.visible:
value = data.get('value')
if (isinstance(value, str) and 0 < len(value) <= MAX_EMOJI_LENGTH
and value.isprintable() and not value.isascii()):
QApplication.clipboard().setText(value)
def _process_error(self, error: QProcess.ProcessError) -> None:
if error == QProcess.ProcessError.FailedToStart:
+2 -28
View File
@@ -43,7 +43,6 @@ class SystemKeyboardPanel(VirtualKeyboard):
self.modifiers: set[int] = set()
self.layout_name = 'System'
self.drag_origin: QPoint | None = None
self.emoji_open = False
super().__init__(owner, theme)
self.set_slide_animation_enabled(False)
self.setObjectName('systemKeyboard')
@@ -106,8 +105,7 @@ class SystemKeyboardPanel(VirtualKeyboard):
for row, codes in zip(keyboard_layouts['us']['normal'], KEY_ROWS, strict=True):
self.keycodes.update(zip(row, codes, strict=True))
units = self.theme.SYSTEM_KEYBOARD['row_units']
rows = self.theme.SYSTEM_KEYBOARD['emoji_rows' if self.emoji_open else 'rows']
for row, keys in enumerate(rows):
for row, keys in enumerate(self.theme.SYSTEM_KEYBOARD['rows']):
column = 0
for key, span in keys:
if key == '▲▼':
@@ -117,8 +115,7 @@ class SystemKeyboardPanel(VirtualKeyboard):
self._add_key(key, (row * units, column, units, span))
column += span
self.apply_key_state()
default = rows[0][0][0]
self._set_selected_button(self.buttons.get(selected or default, self.buttons[default]))
self._set_selected_button(self.buttons.get(selected or 'Esc', self.buttons['Esc']))
if self.owner.warning_message:
warning = QLabel(self.owner.warning_message)
warning.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
@@ -189,25 +186,7 @@ class SystemKeyboardPanel(VirtualKeyboard):
self.owner.worker.commands.put(('release', ()))
self.apply_key_state()
def close_emoji_panel(self) -> None:
if self.emoji_open:
self.emoji_open = False
self.update_keyboard()
self._set_selected_button(self.buttons['🙂'])
def on_button_click(self, key: str) -> None:
if self.emoji_open:
if key != 'ABC':
report('emoji', key)
self.close_emoji_panel()
return
if key == '🙂':
self.stop_backspace_repeat()
self._release_modifiers()
self.emoji_open = True
self.update_keyboard()
self._set_selected_button(self.buttons['😀'])
return
code = ecodes.KEY_SPACE if key == ' ' else self.keycodes.get(key)
if code is not None:
self.owner.worker.commands.put(('tap', (code,)))
@@ -344,7 +323,6 @@ class SystemKeyboardWindow(QWidget, MainWindowControlHintsMixin):
self.worker.cancel_pending()
self.keyboard.stop_backspace_repeat()
self.keyboard._release_modifiers()
self.keyboard.close_emoji_panel()
if self.native_layer is not None:
self.native_layer.hide_layer()
self.hide()
@@ -402,10 +380,6 @@ class SystemKeyboardWindow(QWidget, MainWindowControlHintsMixin):
handlers = {'confirm': self.keyboard.activateFocusedKey, 'back': self.hide_keyboard,
'language': self.keyboard.on_lang_click, 'backspace': self.keyboard.on_backspace_pressed,
'backspace_release': self.keyboard.stop_backspace_repeat}
if self.keyboard.emoji_open and value != 'confirm':
if value == 'back':
self.keyboard.close_emoji_panel()
return
if value == 'shift':
self.keyboard.on_shift_click(not self.keyboard.shift_pressed)
elif value in handlers:
+3 -13
View File
@@ -596,12 +596,9 @@ class MainWindowLibraryTabMixin(_MainWindowTypingBase):
self.updateDeleteMissingExeButton()
def quickLaunch(self):
"""Open the launch file picker."""
def file_filter(path: str) -> bool:
return path.lower().endswith(LAUNCH_FILE_EXTENSIONS) or is_native_executable(path)
file_explorer = FileExplorer(self, self.theme, file_filter=file_filter)
file_explorer.file_signal.file_selected.connect(self._quick_launch_selected)
"""Open file manager to select executable and then open its detail page."""
file_explorer = FileExplorer(self, self.theme, file_filter=LAUNCH_FILE_EXTENSIONS)
file_explorer.file_signal.file_selected.connect(self.handle_launch_exe)
parent_geometry = self.geometry()
center_point = parent_geometry.center()
@@ -611,13 +608,6 @@ class MainWindowLibraryTabMixin(_MainWindowTypingBase):
file_explorer.show()
@Slot(str)
def _quick_launch_selected(self, path: str) -> None:
if path.lower().endswith(LAUNCH_FILE_EXTENSIONS):
self.handle_launch_exe(path)
else:
self._launch_native_game(os.path.abspath(path))
def on_search_text_changed(self, text: str):
"""Search text change handler with debounce."""
self.searchDebounceTimer.stop()
+21 -10
View File
@@ -1,4 +1,5 @@
import os
import sys
from typing import TYPE_CHECKING, Any
from PySide6.QtCore import QObject, QRect, QSize, Qt, QTimer
@@ -229,6 +230,9 @@ 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(
@@ -407,6 +411,8 @@ 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)
@@ -565,7 +571,7 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
uiForm.addRow(disable_alt_dependency_check_layout)
disable_runtime_download_layout = None
if not os.getenv("FLATPAK_ID"):
if sys.platform != "darwin" and not os.getenv("FLATPAK_ID"):
self.disableRuntimeDownloadCheckBox = QCheckBox()
self.disableRuntimeDownloadCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
self.disableRuntimeDownloadCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -596,6 +602,8 @@ 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)
@@ -611,8 +619,10 @@ 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 get_steam_compatibilitytools_dir() is not None:
if sys.platform != "darwin" and get_steam_compatibilitytools_dir() is not None:
self.downloadWineToSteamCheckBox = QCheckBox()
self.downloadWineToSteamCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
self.downloadWineToSteamCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -769,7 +779,7 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
hwForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(hwFrame)
filtered_gpu_list = get_selectable_gpu_list()
filtered_gpu_list = [] if sys.platform == "darwin" else get_selectable_gpu_list()
hwFrame.setVisible(len(filtered_gpu_list) > 1)
if len(filtered_gpu_list) > 1:
self.gpuCombo = CustomComboBox(theme=self.theme)
@@ -1106,7 +1116,7 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
autostart_enabled = self.autostartCheckBox.isChecked()
display_config.set_autostart_enabled(autostart_enabled)
if not apply_xdg_autostart(autostart_enabled):
if sys.platform != "darwin" and not apply_xdg_autostart(autostart_enabled):
QMessageBox.warning(self, _("Error"), _("Failed to update xdg-autostart entry."))
start_minimized = self.startMinimizedCheckBox.isChecked()
@@ -1116,12 +1126,13 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
tray_menu_mode = self.tray_menu_mode_keys[tray_menu_mode_idx]
display_config.set_tray_menu_mode(tray_menu_mode)
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()
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()
ui_config.set_disable_steam_proton_scanning(self.disableSteamProtonScanningCheckBox.isChecked())
+8 -6
View File
@@ -1,4 +1,5 @@
import os
import sys
import shlex
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, cast
@@ -36,12 +37,13 @@ from portprotonqt.localization import _
from portprotonqt.logger import get_logger
from portprotonqt.sound_manager import SoundManager
from portprotonqt.preloader import Preloader
from portprotonqt.system_manager import (
AudioManagerWorker,
BluetoothManagerWorker,
NetworkManagerWorker,
StorageManagerWorker,
)
if sys.platform != "darwin":
from portprotonqt.system_manager import (
AudioManagerWorker,
BluetoothManagerWorker,
NetworkManagerWorker,
StorageManagerWorker,
)
logger = get_logger(__name__)
+13
View File
@@ -1,4 +1,5 @@
import os
import sys
import re
import shutil
from typing import TYPE_CHECKING, Any
@@ -152,6 +153,9 @@ 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)
@@ -195,6 +199,9 @@ 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
@@ -243,6 +250,12 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
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")
+17
View File
@@ -1,3 +1,7 @@
import os
import signal
import sys
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
@@ -16,6 +20,19 @@ 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,
+7 -2
View File
@@ -3,14 +3,13 @@ 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,
@@ -24,6 +23,10 @@ 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
@@ -950,6 +953,8 @@ 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(
File renamed without changes.

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

@@ -334,17 +334,9 @@ SYSTEM_KEYBOARD = {
("k", 2), ("l", 2), (";", 2), ("'", 2), ("Enter", 4)),
(("⬆", 4), ("<", 2), ("z", 2), ("x", 2), ("c", 2), ("v", 2), ("b", 2), ("n", 2),
("m", 2), (",", 2), (".", 2), ("/", 2), ("RShift", 4)),
(("Ctrl", 2), ("Super", 2), ("Alt", 2), ("Space", 8), ("🙂", 2), ("🌐", 2), ("AltGr", 2),
(("Ctrl", 2), ("Super", 2), ("Alt", 2), ("Space", 10), ("🌐", 2), ("AltGr", 2),
("RCtrl", 2), ("◄", 2), ("▲▼", 2), ("►", 2), ("Hide", 2)),
),
"emoji_rows": (
(("😀", 3), ("😃", 3), ("😄", 3), ("😁", 3), ("😆", 3), ("😅", 3), ("😂", 3), ("🤣", 3), ("🙂", 3), ("🙃", 3)),
(("😉", 3), ("😊", 3), ("😍", 3), ("🥰", 3), ("😘", 3), ("😎", 3), ("🤔", 3), ("😴", 3), ("😭", 3), ("😡", 3)),
(("👍", 3), ("👎", 3), ("👏", 3), ("🙌", 3), ("🙏", 3), ("🤝", 3), ("👋", 3), ("✌️", 3), ("💪", 3), ("👌", 3)),
(("❤️", 3), ("💔", 3), ("🔥", 3), ("✨", 3), ("⭐", 3), ("🎉", 3), ("🎮", 3), ("🏆", 3), ("✅", 3), ("❌", 3)),
(("🐱", 3), ("🐶", 3), ("🌈", 3), ("☀️", 3), ("🌙", 3), ("🌻", 3), ("🍕", 3), ("🍔", 3), ("☕", 3), ("🎵", 3)),
(("ABC", 30),),
),
}
DETAIL_PAGE_LAYOUT_MODE = "full"
+1 -1
View File
@@ -23,7 +23,7 @@ classifiers = [
]
dependencies = [
"babel>=2.18.0",
"evdev>=2.0.0",
"evdev>=2.0.0; sys_platform == 'linux'",
"libarchive-c>=5.3",
"orjson>=3.12.0",
"pillow>=12.3.0",
-54
View File
@@ -737,57 +737,3 @@ def test_steam_detail_button_attaches_to_existing_game_watch() -> None:
window._toggle_steam_game.assert_called_once_with(
"steam://rungameid/3263320", button, launch=False
)
@mark.parametrize("hp_fields", [{}, {"hpKey": "field"}, {"hpKey": "field", "hpVal": "value"}])
def test_hltb_search_accepts_token_without_optional_pair(
monkeypatch: MonkeyPatch, hp_fields: dict[str, str]
) -> None:
import orjson
from portprotonqt.howlongtobeat_api import HTTPClient, ResultParser
monkeypatch.setattr("portprotonqt.howlongtobeat_api.proxy_config.get_proxy", lambda: {})
client = HTTPClient()
session = MagicMock()
monkeypatch.setattr(client, "session", session)
session.get.return_value.json.return_value = {"token": "test-token", **hp_fields}
session.post.return_value = SimpleNamespace(status_code=200, text='{"data": [{"comp_main": 12600}]}')
raw = client.search_games("MARVEL Cosmic Invasion")
assert raw is not None
assert ResultParser().parse_results(raw)[0].main_story == 3.5
assert session.get.call_args.args[0].endswith("/api/search/site/init")
assert session.post.call_args.args[0].endswith("/api/search/site")
request = session.post.call_args.kwargs
assert request["headers"]["x-auth-token"] == "test-token"
payload = orjson.loads(request["data"])
assert payload["searchTerms"] == ["MARVEL", "Cosmic", "Invasion"]
assert payload.get("field") == hp_fields.get("hpVal")
assert request["headers"].get("x-hp-key") == ("field" if "hpVal" in hp_fields else None)
assert request["headers"].get("x-hp-val") == hp_fields.get("hpVal")
def test_native_detail_cover_shows_linux_source_corner() -> None:
from PySide6.QtWidgets import QApplication, QFrame
from portprotonqt.detail_pages.widgets import _add_source_corner
from portprotonqt.game_card import SourceCorner
app = QApplication.instance() or QApplication([])
cover = QFrame()
cover.resize(300, 450)
icon_path = Path(__file__).resolve().parents[1] / (
"portprotonqt/themes/standart/images/icons/platforms/badge_native.svg"
)
theme_manager = MagicMock()
theme_manager.get_icon.return_value = str(icon_path)
theme = SimpleNamespace(get_source_corner_config=lambda: {})
_add_source_corner(cover, "native", theme, theme_manager, cover.width(), cover.height())
app.processEvents()
theme_manager.get_icon.assert_called_once_with("badge_native", as_path=True)
ribbon = cover.findChild(SourceCorner)
assert ribbon is not None and not ribbon.isHidden()
assert ribbon.geometry().bottomRight() == cover.rect().bottomRight()
-41
View File
@@ -1,13 +1,10 @@
"""Download cache completion and worker lifecycle regressions."""
from collections.abc import Iterator
from io import BytesIO
from pathlib import Path
import threading
from typing import Any, cast
from unittest.mock import MagicMock
from PIL import Image
import pytest
from PySide6.QtCore import QCoreApplication, QThread
from PySide6.QtWidgets import QApplication
@@ -24,44 +21,6 @@ def application() -> QCoreApplication:
return QApplication.instance() or QApplication([])
@pytest.mark.parametrize("parallel", [False, True])
@pytest.mark.parametrize("complete", [False, True])
def test_truncated_cached_cover_is_redownloaded(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, parallel: bool, complete: bool,
) -> None:
url = "https://example.com/cover.jpg"
target = tmp_path / "cover.jpg"
buffer = BytesIO()
Image.new("RGB", (32, 32)).save(buffer, format="JPEG")
jpeg = buffer.getvalue()
truncated = jpeg[:-30]
target.write_bytes(truncated)
response = MagicMock()
response.headers = {}
def chunks(chunk_size: int) -> Iterator[bytes]:
yield jpeg[:100]
assert target.read_bytes() == truncated
yield (jpeg if complete else truncated)[100:]
response.iter_content.side_effect = chunks
session = MagicMock()
session.get.return_value.__enter__.return_value = response
monkeypatch.setattr("portprotonqt.downloader.get_requests_session", lambda: session)
downloader = Downloader()
downloader._cache[url] = str(target)
results: list[str | None] = []
worker = downloader.download_async(url, str(target), parallel=parallel, callback=results.append)
assert worker is not None
assert worker.wait(THREAD_TIMEOUT_MS)
QApplication.processEvents()
assert results == [str(target) if complete else None]
assert target.read_bytes() == (jpeg if complete else truncated)
assert list(tmp_path.iterdir()) == [target]
@pytest.mark.parametrize("parallel", [False, True])
@pytest.mark.parametrize("failed", [False, True])
def test_resolved_download_completes_without_a_worker(
+2 -77
View File
@@ -309,84 +309,9 @@ def test_download_sizes_cache(tmp_path: Path) -> None:
assert api.get_cached_download_sizes("123") == (100, 200)
GOG_SECTIONED_DESCRIPTION = (
"<h4>Industrial revolution</h4>\n<p>\n<br>\nMagic meets technology.</p>"
"<p>&nbsp;</p><h4>Features<br></h4><ul><li>Character development</li></ul>"
)
def test_load_library_shortens_cached_description(tmp_path: Path) -> None:
api = GOGAPI()
api.library_path = tmp_path / "library.json"
games = [{"app_id": "1207658829", "description": GOG_SECTIONED_DESCRIPTION}]
api._save_json(api.library_path, games)
original = api.library_path.read_bytes()
assert api.load_library() == [{"app_id": "1207658829", "description": "Magic meets technology."}]
assert api.library_path.read_bytes() == original
@pytest.mark.parametrize(
("lead", "expected"),
[
(GOG_SECTIONED_DESCRIPTION, "Magic meets technology."),
pytest.param(
'<div><a href="/game/hellpoint"><img src="banner.jpg"></a>'
'<span>The full version of Hellpoint is available on GOG.com. You can buy it '
'<a href="/game/hellpoint"><b>here</b></a></span></div><hr>\n<br>\n'
'The Thespian Feast — бесплатная глава Hellpoint.',
"The Thespian Feast — бесплатная глава Hellpoint.",
id="hellpoint-full-version-promo",
),
pytest.param(
"<b><i>Я пишу это в состоянии значительного душевного напряжения.</i></b>"
"<br><br>Dagon — трехмерная история по рассказу <b>Лавкрафта</b>.",
"Dagon — трехмерная история по рассказу <b>Лавкрафта</b>.",
id="dagon-epigraph-before-synopsis",
),
("<i>Only available description.</i>", "<i>Only available description.</i>"),
pytest.param(
'<p class="module">Discover <a href="https://example.com">more games</a>.</p>'
'<br><hr><b><h4>Game Description</h4></b>\nShortly after landing…\n<br>\n'
'<b><h4>About Quake II RTX</h4> </b>Technical details.',
"Shortly after landing…",
id="quake-rtx-promo",
),
pytest.param(
'<p><img src="banner.jpg"></p><p class="module">В издание входит дополнение.</p>'
'<p>&nbsp;</p><p>Реалистичный психологический триллер.&nbsp;',
"Реалистичный психологический триллер.",
id="postal-edition-module",
),
pytest.param(
'<b>Внимание! В этой игре нет русской локализации.</b><br><br>Описание игры.',
"Описание игры.",
id="sang-froid-localization-notice",
),
pytest.param(
'<img src="logo.png" />\n<br>\n<b>Martial Law</b> — визуальная новелла.'
'<h4>Особенности:</h4><ul><li>Много вариантов исхода.</li></ul><i>GameJam</i>',
"<b>Martial Law</b> — визуальная новелла.",
id="martial-law-logo-and-features",
),
("<p>&nbsp;</p>", "English description"),
("Intro\n<strong>War Wind</strong> continues.", "Intro<br><b>War Wind</b> continues."),
pytest.param(
'<div style="overflow: hidden;"> <a href="/game/demo"><img src="cover.jpg"></a>'
'<span>Demo</span></div><hr>Game synopsis.',
"Game synopsis.",
id="linked-cover-cross-sell",
),
pytest.param(
{
"lead": '<div><a href="/game/shores_unknown"><img src="banner.jpg"></a><span>',
"full": '<div><span>The full version of Shores Unknown is available on GOG.com. '
'You can purchase it <a href="/game/shores_unknown">here</a></span></div><hr>'
'<i>Shores Unknown: Arrival</i> is a free demo.<br><br>Game features.',
},
"<i>Shores Unknown: Arrival</i> is a free demo.",
id="shores-unknown-truncated-lead",
),
(
"Description française.<br><br>Deuxième paragraphe.",
"Description française.",
@@ -398,7 +323,7 @@ def test_load_library_shortens_cached_description(tmp_path: Path) -> None:
],
)
def test_get_game_loads_localized_product_description(
monkeypatch: pytest.MonkeyPatch, lead: str | dict[str, str], expected: str
monkeypatch: pytest.MonkeyPatch, lead: str, expected: str
) -> None:
gamesdb_response = Mock()
gamesdb_response.json.return_value = {
@@ -412,7 +337,7 @@ def test_get_game_loads_localized_product_description(
}
product_response = Mock()
product_response.json.return_value = {
"description": {"lead": lead} if isinstance(lead, str) else lead,
"description": {"lead": lead},
}
request = Mock(side_effect=[gamesdb_response, product_response])
monkeypatch.setattr("portprotonqt.gog_api.get_metadata_language", lambda: "fr")
+1 -2
View File
@@ -650,8 +650,6 @@ def test_remote_cover_replaces_immediate_exe_fallback_only_on_success(
lambda: SimpleNamespace(current_theme_module=theme),
)
downloaded_path = fallback_path.parent / filename
downloaded_path.write_bytes(b"\xff\xd8truncated JPEG")
image_utils.load_pixmap_async(
url, 100, 150,
lambda pixmap: loaded_paths.append(cast(FakePixmap, pixmap).path),
@@ -659,6 +657,7 @@ def test_remote_cover_replaces_immediate_exe_fallback_only_on_success(
fallback_icon_path=str(fallback_path),
)
callbacks[0](None)
downloaded_path = tmp_path / "cache" / "PortProtonQt" / "images" / filename
downloaded_path.write_bytes(b"cover")
callbacks[0](str(downloaded_path))
-70
View File
@@ -13,7 +13,6 @@ from shiboken6 import delete
import portprotonqt.input_manager as input_manager
import portprotonqt.input_manager.buttons as input_buttons
import portprotonqt.input_manager.dpad as input_dpad
import portprotonqt.input_manager.keyboard as input_keyboard
import portprotonqt.input_manager.runtime as input_runtime
import portprotonqt.native_gamepad as native_gamepad
from portprotonqt.input_manager.constants import (
@@ -269,49 +268,6 @@ def test_sdl_dpad_vertical_directions() -> None:
assert emitted == [(PAD_DPAD_Y, -1, 1.0), (PAD_DPAD_Y, 1, 2.0)]
@mark.parametrize('emulation', [False, True])
@mark.parametrize(('button', 'direction'), [
(SDL_GAMEPAD_BUTTON_DPAD_UP, -1),
(SDL_GAMEPAD_BUTTON_DPAD_DOWN, 1),
])
def test_system_keyboard_gamepad_drag(emulation: bool, button: int, direction: int) -> None:
manager: Any = InputManager.__new__(InputManager)
QObject.__init__(manager)
keyboard = MagicMock()
keyboard.isVisible.return_value = True
manager._parent = SimpleNamespace(system_keyboard=keyboard)
manager._button_states = {}
manager._hat_states = {}
manager.mouse_emulation_enabled = manager.emulation_active = True
manager.emulation_triggered = emulation
manager.ui = MagicMock()
gamepad = cast(SDLGamepad, SimpleNamespace(
get_button=lambda code: int(code == button),
))
dpad = MagicMock()
manager.dpad_moved.connect(dpad)
codes = input_manager.ecodes
manager._handle_button_value(0, PAD_BUTTON_SOUTH, 1, 1.0)
manager._poll_hat_events(gamepad, 2.0)
keyboard.isVisible.return_value = False
manager._handle_button_value(0, PAD_BUTTON_SOUTH, 0, 3.0)
if emulation:
keyboard.send.assert_not_called()
dpad.assert_not_called()
assert [call.args for call in manager.ui.write.call_args_list] == [
(codes.EV_KEY, codes.BTN_LEFT, 1),
(codes.EV_REL, codes.REL_X, 0),
(codes.EV_REL, codes.REL_Y, 10 * direction),
(codes.EV_KEY, codes.BTN_LEFT, 0),
]
else:
keyboard.send.assert_called_once_with('button', 'confirm')
dpad.assert_called_once_with(PAD_DPAD_Y, direction, 2.0)
manager.ui.write.assert_not_called()
def test_disabling_mouse_emulation_keeps_gamepad_events_working() -> None:
emitted: list[tuple[int, int]] = []
manager = InputManager.__new__(InputManager)
@@ -574,32 +530,6 @@ def test_library_toolbar_navigation_includes_delete_missing_button() -> None:
assert QApplication.focusWidget() is widgets[4]
def test_dpad_down_from_toolbar_focuses_first_visual_card(monkeypatch: MonkeyPatch) -> None:
app = QApplication.instance() or QApplication([])
window = QWidget()
toolbar_button = QPushButton(window)
container = QWidget(window)
container.setGeometry(0, 40, 100, 100)
lower_card = DummyCard(container, FIRST_CARD_X)
lower_card.move(FIRST_CARD_X, 40)
right_card = DummyCard(container, NEXT_CARD_X)
first_card = DummyCard(container, FIRST_CARD_X)
window.show()
app.processEvents()
monkeypatch.setattr(input_keyboard, "AnimatedCard", DummyCard)
manager = InputManager.__new__(InputManager)
manager._parent = cast(MainWindowProtocol, SimpleNamespace(
quickLaunchButton=toolbar_button,
stackedWidget=SimpleNamespace(currentIndex=lambda: 0),
gamesListWidget=container,
))
assert right_card.isVisible()
for _ in range(2):
toolbar_button.setFocus()
assert manager._handle_library_dpad(PAD_DPAD_Y, 1)
assert QApplication.focusWidget() is first_card
def test_library_filter_navigation_includes_only_installed_checkbox() -> None:
app = QApplication.instance() or QApplication([])
controls = QWidget()
+1 -1
View File
@@ -65,7 +65,7 @@ def test_native_card_uses_linux_source_corner(
))
assert card.native_visible
assert isinstance(card.nativeLabel._icon, str)
assert Path(card.nativeLabel._icon).name == "badge_native.svg"
assert Path(card.nativeLabel._icon).name == "badge_linux.svg"
assert Path(card.nativeLabel._icon).is_file()
assert not card.portproton_visible
card.deleteLater()
-23
View File
@@ -207,14 +207,6 @@ def test_horizontal_cards_fit_viewport_height(
assert card.nameLabel.height() >= card.nameLabel.sizeHint().height()
assert card.base_card_width <= manager.card_width
assert card.base_card_width == manager.card_width
cover = QPixmap(180, 300)
cover.fill(QColor("red"))
card.on_cover_loaded(cover)
for scale in (1.0, 1.045, 1.25, 1.0):
card.setScale(scale)
app.processEvents()
assert card.coverLabel.pixmap().size() == card.coverLabel.size()
assert card.coverLabel.width() == int(card.base_card_width * scale)
card.stop_background_activity()
scroll.close()
app.processEvents()
@@ -257,18 +249,3 @@ def test_large_resize_keeps_cards_separate_between_batches(
assert all(not geometry.intersects(other) for other in geometries[index + 1:])
finally:
scroll.close()
def test_static_png_does_not_leave_cover_mask(tmp_path: Path) -> None:
from PySide6.QtWidgets import QLabel
from portprotonqt.image_utils import set_animated_cover
app = QApplication.instance() or QApplication([])
path = tmp_path / "poster.png"
pixmap = QPixmap(40, 60)
pixmap.fill(QColor("red"))
assert pixmap.save(str(path))
label = QLabel()
assert not set_animated_cover(label, str(path), 40, 60, 5)
assert label.mask().isEmpty()
app.processEvents()
+396
View File
@@ -0,0 +1,396 @@
"""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)
@pytest.mark.parametrize("server_mode", [None, 0o644, 0o755])
def test_managed_wine_prefers_executable_sibling_wineserver(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, server_mode: int | None,
) -> None:
binary = macos.version_directory(tmp_path, "Wine 1") / "wswine.bundle/bin/wine64"
binary.parent.mkdir(parents=True)
binary.touch(mode=0o755)
server = binary.with_name("wineserver")
if server_mode is not None:
server.touch(mode=server_mode)
inherited = str(tmp_path / "other wineserver")
monkeypatch.setenv("WINESERVER", inherited)
_, environment = macos.wine_command(tmp_path, ["winecfg"], {"PW_WINE_USE": "Wine 1"})
assert environment["WINESERVER"] == (str(server) if server_mode == 0o755 else inherited)
assert macos.os.environ["WINESERVER"] == inherited
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]
+1 -66
View File
@@ -12,7 +12,7 @@ import subprocess
from datetime import datetime, timedelta
import pytest
from PySide6.QtCore import QEventLoop, QMimeData, QRect, QStandardPaths, QThread, QTimer, Qt, QUrl
from PySide6.QtCore import QEventLoop, QStandardPaths, QThread, QTimer, Qt
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton
from PySide6.QtGui import QIcon
@@ -169,71 +169,6 @@ def test_native_launch_preserves_desktop_file_and_bypasses_wine(
window._set_running_button_stop.assert_called_once()
@pytest.mark.parametrize("name", ["Game.AppImage", "Game.bin", "Game with spaces", "Game.exe"])
def test_quick_launch_file_picker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, name: str) -> None:
path = tmp_path / name
path.touch(mode=0o755)
text = tmp_path / "README"
text.touch(mode=0o644)
picker = MagicMock()
monkeypatch.setattr("portprotonqt.tabs.library_tab.FileExplorer", picker)
window = cast(Any, SimpleNamespace(
theme=None, geometry=lambda: QRect(), game_processes=[], input_manager=MagicMock(),
handle_launch_exe=MagicMock(), _set_running_button_stop=MagicMock(), checkTargetExe=MagicMock(),
))
window._quick_launch_selected = MainWindow._quick_launch_selected.__get__(window)
window._launch_native_game = MainWindow._launch_native_game.__get__(window)
popen = MagicMock()
monkeypatch.setattr("portprotonqt.main_window.subprocess.Popen", popen)
monkeypatch.setattr("portprotonqt.main_window.QTimer", MagicMock())
monkeypatch.setattr("portprotonqt.main_window.SoundManager", MagicMock())
MainWindow.quickLaunch(window)
file_filter = picker.call_args.kwargs["file_filter"]
assert file_filter(str(path))
assert not file_filter(str(text))
shortcut = tmp_path / "Launcher.Desktop"
shortcut.touch(mode=0o755)
assert not file_filter(str(shortcut))
callback, = picker.return_value.file_signal.file_selected.connect.call_args.args
warning = MagicMock()
monkeypatch.setattr("portprotonqt.main_window.QMessageBox.warning", warning)
callback(str(shortcut))
warning.assert_called_once()
popen.assert_not_called()
shortcut.unlink()
callback(str(path))
if path.suffix == ".exe":
window.handle_launch_exe.assert_called_once_with(str(path))
popen.assert_not_called()
else:
window.handle_launch_exe.assert_not_called()
popen.assert_called_once_with([str(path)], cwd=str(tmp_path), start_new_session=True, text=True)
assert window.native_game_running
assert not list(tmp_path.rglob("*.desktop"))
@pytest.mark.parametrize("name", ["Game.AppImage", "Game.bin", "Game"])
def test_drop_native_executable_opens_add_dialog(tmp_path: Path, name: str) -> None:
path = tmp_path / name
path.touch(mode=0o755)
mime = QMimeData()
mime.setUrls([QUrl.fromLocalFile(str(path))])
event = cast(Any, SimpleNamespace(
mimeData=lambda: mime, acceptProposedAction=MagicMock(), ignore=MagicMock(),
))
window = cast(Any, SimpleNamespace(openAddGameDialog=MagicMock()))
MainWindow.dragEnterEvent(window, event)
MainWindow.dropEvent(window, event)
assert event.acceptProposedAction.call_count == 2
event.ignore.assert_not_called()
window.openAddGameDialog.assert_called_once_with(str(path))
def test_native_context_launch_does_not_require_portproton() -> None:
parent = SimpleNamespace(toggleGame=MagicMock())
manager = cast(Any, SimpleNamespace(parent=parent))
-33
View File
@@ -68,38 +68,6 @@ def test_layer_shell_keeps_qt_window_offscreen(
window.hide()
def test_builtin_emoji_panel(keyboard_window: SystemKeyboardWindow) -> None:
window = keyboard_window
keyboard = window.keyboard
window.ready = window.wanted_visible = True
keyboard.buttons['🙂'].click()
assert keyboard.emoji_open
assert keyboard.selected_button is keyboard.buttons['😀']
window.command('direction', 'right')
assert keyboard.selected_button is keyboard.buttons['😃']
window.command('button', 'back')
assert window.wanted_visible and not keyboard.emoji_open
keyboard.buttons['🙂'].click()
keyboard.buttons['❤️'].click()
cast(MagicMock, system_window.report).assert_called_once_with('emoji', '❤️')
assert not keyboard.emoji_open
assert keyboard.selected_button is keyboard.buttons['🙂']
def test_emoji_response_copies_to_clipboard(application: QApplication, monkeypatch: pytest.MonkeyPatch) -> None:
controller = SystemKeyboard(QWidget())
clipboard = MagicMock()
monkeypatch.setattr(QApplication, 'clipboard', lambda: clipboard)
controller.visible = True
response = '{"event":"emoji","value":"❤️"}\n'.encode()
monkeypatch.setattr(controller.process, 'readAllStandardOutput', lambda: SimpleNamespace(data=lambda: response))
controller._read_state()
clipboard.setText.assert_called_once_with('❤️')
controller.visible = False
controller._read_state()
clipboard.setText.assert_called_once()
def test_panel_matches_embedded_layout_without_extra_rows(keyboard_window: SystemKeyboardWindow) -> None:
keyboard = keyboard_window.keyboard
assert keyboard.current_layout == 'us'
@@ -493,7 +461,6 @@ def test_system_keyboard_routes_buttons_without_application_focus(application: Q
keyboard = SimpleNamespace(send=MagicMock(), isVisible=lambda: True)
manager._parent = SimpleNamespace(system_keyboard=keyboard)
manager.start_held = False
manager.mouse_emulation_enabled = False
assert manager._handle_system_keyboard_input(PAD_BUTTON_SOUTH, 1, False)
keyboard.send.assert_called_once_with('button', 'confirm')
Generated
+2 -2
View File
@@ -444,7 +444,7 @@ source = { editable = "." }
dependencies = [
{ name = "babel" },
{ name = "dbus-fast" },
{ name = "evdev" },
{ name = "evdev", marker = "sys_platform == 'linux'" },
{ 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", specifier = ">=2.0.0" },
{ name = "evdev", marker = "sys_platform == 'linux'", specifier = ">=2.0.0" },
{ name = "libarchive-c", specifier = ">=5.3" },
{ name = "orjson", specifier = ">=3.12.0" },
{ name = "pefile", specifier = ">=2024.8.26" },