Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1052c68a9a
|
||
|
|
b657d4ad7d
|
||
|
|
9cafdf13a4
|
||
|
|
ee7ce5c2df
|
||
|
|
cd041290d0
|
||
|
|
e58fc30a74
|
||
|
|
2b518628d5
|
||
|
|
019db054ed
|
||
|
|
882fabf52f
|
||
|
|
bd741e8639
|
||
|
|
bdf4b2855b | ||
|
|
df9c796b7f | ||
|
|
fddc02c981 | ||
|
|
682f3c8e61
|
||
|
|
f9f37762e4
|
||
|
|
54e587689c
|
No files matched your search
@@ -1,19 +1,17 @@
|
||||
name: Build vk_gpu_info on Debian 11
|
||||
name: Build native binaries on Debian 11
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- scripts
|
||||
paths:
|
||||
- 'build-aux/src/vk_gpu_info.c'
|
||||
- 'build-aux/src/wine_gpu_names.h'
|
||||
- 'build-aux/src/**'
|
||||
- '.gitea/workflows/build-vk-gpu-info-debian.yml'
|
||||
|
||||
jobs:
|
||||
build-debian11:
|
||||
name: Build vk_gpu_info on Debian 11
|
||||
name: Build native binaries on Debian 11
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: debian:11
|
||||
@@ -23,7 +21,7 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y build-essential pkg-config libvulkan-dev git curl wget nodejs npm
|
||||
apt-get install -y build-essential cmake pkg-config libvulkan-dev libwayland-dev libx11-dev git curl wget nodejs npm
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: https://git.linux-gaming.ru/actions/setup-node@v2
|
||||
@@ -32,26 +30,46 @@ jobs:
|
||||
|
||||
- name: Checkout code
|
||||
uses: https://git.linux-gaming.ru/actions/checkout@v3
|
||||
with:
|
||||
ref: ${{ gitea.ref }}
|
||||
token: ${{ secrets.GITEA_TOKEN }}
|
||||
|
||||
- name: Compile vk_gpu_info
|
||||
- name: Build SDL3 for linking
|
||||
run: |
|
||||
mkdir -p build-aux/bin
|
||||
gcc -o build-aux/bin/vk_gpu_info build-aux/src/vk_gpu_info.c -lvulkan
|
||||
# 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)
|
||||
|
||||
- name: Test vk_gpu_info execution
|
||||
run: |
|
||||
# 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
|
||||
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."
|
||||
|
||||
- name: Upload vk_gpu_info binary
|
||||
- name: Upload native binaries
|
||||
uses: https://git.linux-gaming.ru/actions/gitea-upload-artifact@v4
|
||||
with:
|
||||
name: vk_gpu_info-debian11-binary
|
||||
path: build-aux/bin/vk_gpu_info
|
||||
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
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
name: Check code
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: archlinux:base-devel@sha256:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1
|
||||
image: archlinux:base-devel@sha256:624bdc7fc6615155d67bc34cf7146c0c9fd0e3c92943977da63a630e4ca49c30
|
||||
steps:
|
||||
- name: Configure Arch mirrors
|
||||
run: |
|
||||
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.appimage == 'true' || github.event_name == 'workflow_dispatch'
|
||||
container:
|
||||
image: archlinux:base-devel@sha256:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1
|
||||
image: archlinux:base-devel@sha256:624bdc7fc6615155d67bc34cf7146c0c9fd0e3c92943977da63a630e4ca49c30
|
||||
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:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1
|
||||
image: archlinux:base-devel@sha256:624bdc7fc6615155d67bc34cf7146c0c9fd0e3c92943977da63a630e4ca49c30
|
||||
|
||||
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-20261005@sha256:913f6706df59a68922d1dd08f78c2476560a8d367897200a6005b00e5f67c2d5
|
||||
image: debian:trixie-20261027@sha256:2dc419c6d7fe3dad0a2f9fd469c34cc90b0f9ba642d8fde837fe3d7d34a0e7f1
|
||||
options: --privileged
|
||||
|
||||
steps:
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
|
||||
### Added
|
||||
|
||||
- Добавлена поддержка нативных Linux-игр: библиотека обнаруживает игры по ярлыкам `.desktop`, а через диалог добавления игры можно выбрать исполняемый файл Linux
|
||||
- Добавлена системная экранная клавиатура с управлением геймпадом: её можно открыть из меню в системном трее или сочетанием `Start` + верхняя кнопка геймпада (`Y` на Xbox, `△` на PlayStation)
|
||||
- В Run After / Wrapper добавлена поддержка `%command%` для передачи команды игры обёртке, например `mako-launch %command%`, без повторного запуска игры
|
||||
- Добавлено отслеживание запуска Steam-игр на странице игры
|
||||
- Добавлен CLI для получения локальных данных библиотеки
|
||||
@@ -44,6 +46,11 @@
|
||||
|
||||
### Fixed
|
||||
|
||||
- Обложки заполняют отведённую область без растягивания
|
||||
- Исправлена загрузка оценок времени прохождения с HowLongToBeat в карточках игр
|
||||
- При нажатии вниз на D-pad с верхней панели библиотеки фокус переходит на первую карточку верхнего ряда, а не перескакивает на нижние ряды
|
||||
- В карточках игр GOG отображается краткое описание без рекламы, баннеров и списков особенностей
|
||||
- Недокачанные JPEG-обложки больше не попадают в кэш
|
||||
- Исправлена фильтрация видеокарт DXVK и VKD3D при расхождении нативного имени GPU с именем Wine
|
||||
- Запросы установки других игр GOG и EGS во время получения списка DLC добавляются в очередь вместо ошибки «Другая загрузка уже выполняется»
|
||||
- Виртуальная мышь создаётся только при включении эмуляции геймпадом и удаляется при её выключении
|
||||
@@ -73,6 +80,7 @@
|
||||
- @rogerio-mattos
|
||||
- @Rubin13
|
||||
- @iodnoorov
|
||||
- @gstkein
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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&label=Release" alt="Releases"></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="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="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&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&logo=linux" alt="Platform: Linux"></a>
|
||||
|
||||
+1
-1
@@ -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&label=Релиз" 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="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="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&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&logo=linux" alt="Платформа: Linux"></a>
|
||||
|
||||
@@ -1572,7 +1572,6 @@ pw_kill_autostart () {
|
||||
export -f pw_kill_autostart
|
||||
|
||||
stop_portproton () {
|
||||
pw_remove_session_env
|
||||
[[ "$int_xneur" == "1" ]] && xneur &
|
||||
|
||||
if [[ "$PW_USE_US_LAYOUT" == "1" ]] \
|
||||
@@ -3872,7 +3871,6 @@ start_portproton () {
|
||||
pw_mangohud_check
|
||||
pw_vkbasalt_check
|
||||
pw_lsfg_vk_check
|
||||
pw_save_session_env || print_warning "Could not save Wine session environment"
|
||||
}
|
||||
|
||||
pw_run () {
|
||||
@@ -4024,80 +4022,6 @@ pw_run () {
|
||||
}
|
||||
export -f pw_run
|
||||
|
||||
pw_save_session_env () {
|
||||
local session_dir="${PORT_DATA_PATH}/data/tmp/wine-session-$(id -u)"
|
||||
local session_tmp
|
||||
|
||||
( umask 077; mkdir -p "$session_dir" ) || return 1
|
||||
[[ ! -L "$session_dir" && -O "$session_dir" ]] || return 1
|
||||
[[ "$(stat -c %a "$session_dir")" == 700 ]] || return 1
|
||||
|
||||
session_tmp="$(mktemp "$session_dir/env.XXXXXX")" || return 1
|
||||
if ( export PW_TERM; export -p > "$session_tmp" ) \
|
||||
&& mv -fT "$session_tmp" "$session_dir/session.env" ; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
rm -f "$session_tmp"
|
||||
return 1
|
||||
}
|
||||
|
||||
pw_remove_session_env () {
|
||||
local session_dir="${PORT_DATA_PATH}/data/tmp/wine-session-$(id -u)"
|
||||
[[ ! -L "$session_dir" && -O "$session_dir" ]] || return 0
|
||||
local session_env="$session_dir/session.env"
|
||||
[[ ! -L "$session_env" && -O "$session_env" ]] || return 0
|
||||
if grep -qsx "declare -x PW_START_PID=\"${PW_START_PID}\"" "$session_env" ; then
|
||||
rm -f "$session_env"
|
||||
fi
|
||||
}
|
||||
|
||||
pw_session_tool () {
|
||||
local tool="$1" session_pid session_env
|
||||
local session_dir="${PORT_DATA_PATH}/data/tmp/wine-session-$(id -u)"
|
||||
local session_wait_seconds="${2:-30}" wait_left
|
||||
wait_left="$session_wait_seconds"
|
||||
|
||||
case "$tool" in
|
||||
winefile|taskmgr|winecfg|regedit|cmd|uninstaller) ;;
|
||||
*) print_error "Unsupported Wine tool: $tool" ; return 1 ;;
|
||||
esac
|
||||
|
||||
session_env="$session_dir/session.env"
|
||||
while (( wait_left > 0 )) ; do
|
||||
if [[ ! -L "$session_dir" && -O "$session_dir" ]] \
|
||||
&& [[ "$(stat -c %a "$session_dir")" == 700 ]] \
|
||||
&& [[ ! -L "$session_env" && -O "$session_env" ]] \
|
||||
&& [[ "$(stat -c %a "$session_env")" == 600 ]] \
|
||||
&& session_pid="$(sed -n 's/^declare -x PW_START_PID="\([0-9]*\)"$/\1/p' "$session_env")" \
|
||||
&& [[ -n "$session_pid" ]] \
|
||||
&& kill -0 "$session_pid" 2>/dev/null ; then
|
||||
break
|
||||
fi
|
||||
|
||||
sleep 1
|
||||
(( --wait_left ))
|
||||
done
|
||||
|
||||
if (( wait_left == 0 )) ; then
|
||||
print_error "Wine session unavailable after ${session_wait_seconds} seconds"
|
||||
return 2
|
||||
fi
|
||||
|
||||
source "$session_env" || return 1
|
||||
PATH_TO_GAME="${WINEPREFIX}/drive_c"
|
||||
[[ -d "$PATH_TO_GAME" ]] || return 1
|
||||
|
||||
unset LAUNCH_PARAMETERS PW_RUN_AFTER_EXE PW_RUN_GAMESCOPE PW_USE_TERMINAL
|
||||
PW_TMPFS_PATH="$(mktemp -d "$session_dir/tool.XXXXXX")" || return 1
|
||||
export PW_TMPFS_PATH
|
||||
export PW_LOG_FILE="$PW_TMPFS_PATH/wine.log"
|
||||
|
||||
[[ "$tool" == cmd ]] && PW_USE_TERMINAL=1
|
||||
[[ "$tool" == winecfg || "$tool" == regedit ]] && export GST_PLUGIN_SYSTEM_PATH_1_0=""
|
||||
pw_run "$tool" || return 1
|
||||
}
|
||||
|
||||
pw_launch_wrapper () {
|
||||
if [[ -z "${PW_RUN_AFTER_EXE:-}" ]] ; then
|
||||
"$@"
|
||||
|
||||
@@ -67,21 +67,6 @@ export PW_LOG_FILE="${PORT_DATA_PATH}/PortProton.log"
|
||||
# shellcheck source=/dev/null
|
||||
source "$PORT_SCRIPTS_PATH/functions_helper"
|
||||
|
||||
if [[ "${1:-}" == "cli" && "${2:-}" == "--wine-session-tool" ]] ; then
|
||||
session_unavailable_status=2
|
||||
session_wait_seconds=30
|
||||
[[ -n "${4:-}" && -n "${5:-}" ]] && session_wait_seconds=1
|
||||
if pw_session_tool "${3:-}" "$session_wait_seconds" ; then
|
||||
exit 0
|
||||
else
|
||||
session_tool_status=$?
|
||||
fi
|
||||
if [[ "$session_tool_status" != "$session_unavailable_status" || -z "${4:-}" || -z "${5:-}" ]] ; then
|
||||
python_module dbus_tools notify -i error "Wine" "Failed to start Wine tool: ${3:-}" &>/dev/null
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
export PORT_WINE_TMP_PATH="${PORT_DATA_PATH}/data/tmp"
|
||||
create_new_dir "$PORT_WINE_TMP_PATH"
|
||||
rm -f "$PORT_WINE_TMP_PATH"/*.{exe,msi,tar}*
|
||||
@@ -295,7 +280,11 @@ case "$1" in
|
||||
--show-ppdb Show the content of .ppdb file for specified .exe file
|
||||
--backup-prefix Backup specified prefix to a file
|
||||
--restore-prefix Restore prefix from backup file
|
||||
--wine-session-tool Open a Wine tool in the current session, or use optional WINE and prefix
|
||||
--winefile Open wine file explorer, requires WINE version and prefix name
|
||||
--winecfg Open wine configuration, requires WINE version and prefix name
|
||||
--winecmd Open wine command prompt, requires WINE version and prefix name
|
||||
--winereg Open wine registry editor, requires WINE version and prefix name
|
||||
--wine_uninstaller Open wine uninstaller, requires WINE version and prefix name
|
||||
--winetricks-list-all List winetricks DLLs, fonts, and settings
|
||||
--winetricks-install Install winetricks items, requires WINE version and prefix name
|
||||
--clear_pfx Clear specified prefix, requires WINE version and prefix name
|
||||
@@ -311,7 +300,7 @@ Usage examples:
|
||||
portproton cli --del-user-conf PW_MANGOHUD
|
||||
portproton cli --backup-prefix DEFAULT /path/to/backup/directory
|
||||
portproton cli --restore-prefix /path/to/backup/file.ppack
|
||||
portproton cli --wine-session-tool winecfg WINE_LG DEFAULT
|
||||
portproton cli --winecfg WINE_LG DEFAULT
|
||||
portproton cli --winetricks-list-all WINE_LG DEFAULT
|
||||
portproton cli --winetricks-install WINE_LG DEFAULT --no-force corefonts
|
||||
portproton cli --mangohud-preview \"fps,frametime,cpu_temp,gpu_temp\"
|
||||
@@ -473,21 +462,37 @@ Usage examples:
|
||||
pw_unpack_prefix "$2"
|
||||
exit $?
|
||||
;;
|
||||
--wine-session-tool)
|
||||
tool="$2"
|
||||
case "$tool" in
|
||||
winefile|taskmgr|winecfg|regedit|cmd|uninstaller) ;;
|
||||
*) print_error "Unsupported Wine tool: $tool" ; exit 1 ;;
|
||||
esac
|
||||
get_wine_and_pfx "$3" "$4"
|
||||
--winefile)
|
||||
get_wine_and_pfx "$2" "$3"
|
||||
start_portproton
|
||||
[[ "$tool" == winecfg || "$tool" == regedit ]] && export GST_PLUGIN_SYSTEM_PATH_1_0=""
|
||||
if [[ "$tool" == cmd ]] ; then
|
||||
cd "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c" || fatal "Prefix drive_c directory not found"
|
||||
PW_USE_TERMINAL=1 pw_run "$tool"
|
||||
else
|
||||
pw_run "$tool"
|
||||
fi
|
||||
pw_run winefile
|
||||
stop_portproton
|
||||
;;
|
||||
--winecfg)
|
||||
get_wine_and_pfx "$2" "$3"
|
||||
start_portproton
|
||||
export GST_PLUGIN_SYSTEM_PATH_1_0=""
|
||||
pw_run winecfg
|
||||
stop_portproton
|
||||
;;
|
||||
--winecmd)
|
||||
get_wine_and_pfx "$2" "$3"
|
||||
start_portproton
|
||||
cd "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c" || fatal "Prefix drive_c directory not found"
|
||||
PW_USE_TERMINAL=1 pw_run cmd
|
||||
stop_portproton
|
||||
;;
|
||||
--winereg)
|
||||
get_wine_and_pfx "$2" "$3"
|
||||
start_portproton
|
||||
export GST_PLUGIN_SYSTEM_PATH_1_0=""
|
||||
pw_run regedit
|
||||
stop_portproton
|
||||
;;
|
||||
--wine_uninstaller)
|
||||
get_wine_and_pfx "$2" "$3"
|
||||
start_portproton
|
||||
pw_run uninstaller
|
||||
stop_portproton
|
||||
;;
|
||||
--winetricks-list-all)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# Generate shell completion files for bash, zsh, and fish
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
@@ -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") or theme_manager is None:
|
||||
if source not in ("steam", "gog", "egs", "portproton", "native") or theme_manager is None:
|
||||
return
|
||||
|
||||
icon_name = f"badge_{source}"
|
||||
|
||||
+48
-62
@@ -1,5 +1,6 @@
|
||||
from PySide6.QtCore import QObject, Signal, QThread, Qt, QCoreApplication
|
||||
import threading
|
||||
from tempfile import NamedTemporaryFile
|
||||
import os
|
||||
import time
|
||||
import requests
|
||||
@@ -26,36 +27,57 @@ 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 os.path.exists(local_path):
|
||||
if is_complete_download(local_path):
|
||||
return local_path
|
||||
session = get_requests_session()
|
||||
try:
|
||||
with session.get(url, stream=True, timeout=timeout) as response:
|
||||
response.raise_for_status()
|
||||
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))
|
||||
_save_download(response, local_path, timeout)
|
||||
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):
|
||||
@@ -101,7 +123,7 @@ class Downloader(QObject):
|
||||
last_request_time = [0.0]
|
||||
|
||||
def _download_one(url, local_path):
|
||||
if os.path.exists(local_path):
|
||||
if is_complete_download(local_path):
|
||||
return local_path
|
||||
try:
|
||||
with rate_limit_lock:
|
||||
@@ -112,22 +134,7 @@ class Downloader(QObject):
|
||||
|
||||
with session.get(url, stream=True, timeout=timeout) as response:
|
||||
response.raise_for_status()
|
||||
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))
|
||||
_save_download(response, local_path, timeout)
|
||||
return local_path
|
||||
except requests.exceptions.HTTPError as e:
|
||||
if e.response is not None and e.response.status_code == 429:
|
||||
@@ -136,43 +143,22 @@ class Downloader(QObject):
|
||||
try:
|
||||
with session.get(url, stream=True, timeout=timeout) as response:
|
||||
response.raise_for_status()
|
||||
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))
|
||||
_save_download(response, local_path, timeout)
|
||||
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:
|
||||
@@ -198,7 +184,7 @@ class Downloader(QObject):
|
||||
return None
|
||||
if url in self._cache:
|
||||
cached_path = self._cache[url]
|
||||
if os.path.exists(cached_path):
|
||||
if is_complete_download(cached_path):
|
||||
if os.path.abspath(cached_path) == os.path.abspath(local_path):
|
||||
return cached_path
|
||||
else:
|
||||
@@ -210,7 +196,7 @@ class Downloader(QObject):
|
||||
return None
|
||||
if url in self._cache:
|
||||
cached_path = self._cache[url]
|
||||
if os.path.exists(cached_path) and os.path.abspath(cached_path) == os.path.abspath(local_path):
|
||||
if is_complete_download(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:
|
||||
@@ -241,7 +227,7 @@ class Downloader(QObject):
|
||||
emitted_urls.add(url)
|
||||
continue
|
||||
cached_path = self._cache.get(url)
|
||||
if (cached_path and os.path.exists(cached_path)
|
||||
if (cached_path and is_complete_download(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)
|
||||
@@ -289,7 +275,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 os.path.exists(local_path)
|
||||
cached = not previous_error and is_complete_download(local_path)
|
||||
if cached:
|
||||
self._cache[url] = local_path
|
||||
if previous_error or cached:
|
||||
|
||||
@@ -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_linux", as_path=True),
|
||||
icon=self.theme_manager.get_icon("badge_native", 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_linux"),
|
||||
(self.nativeLabel, "badge_native"),
|
||||
(self.portprotonLabel, "badge_portproton"),
|
||||
):
|
||||
icon = self.theme_manager.get_icon(
|
||||
@@ -817,9 +817,8 @@ class GameCard(AnimatedCard):
|
||||
radius = int(self.card_layout_cfg.get("cover_radius", 8) * self._scale)
|
||||
aspect_mode = Qt.AspectRatioMode.KeepAspectRatio
|
||||
else:
|
||||
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)
|
||||
target_width = self.coverLabel.minimumWidth()
|
||||
target_height = self.coverLabel.minimumHeight()
|
||||
radius = int(self.card_layout_cfg.get("cover_radius", 15) * self._scale)
|
||||
aspect_mode = Qt.AspectRatioMode.KeepAspectRatioByExpanding
|
||||
scaled_pixmap = self.base_pixmap.scaled(
|
||||
@@ -828,6 +827,12 @@ 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)
|
||||
|
||||
+68
-14
@@ -10,6 +10,7 @@ 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
|
||||
|
||||
@@ -315,7 +316,12 @@ class GOGAPI:
|
||||
def load_library(self) -> list[dict]:
|
||||
"""Load the cached GOG library."""
|
||||
data = self._load_json(self.library_path, [])
|
||||
return data if isinstance(data, list) else []
|
||||
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
|
||||
|
||||
def clear_library_cache(self) -> None:
|
||||
"""Remove cached GOG covers and descriptions."""
|
||||
@@ -690,7 +696,7 @@ class GOGAPI:
|
||||
),
|
||||
{},
|
||||
)
|
||||
description = self._localized_value(data.get("summary"))
|
||||
description = self._short_description(self._localized_value(data.get("summary")))
|
||||
language = get_metadata_language().lower()
|
||||
try:
|
||||
product_response = requests.get(
|
||||
@@ -703,18 +709,11 @@ class GOGAPI:
|
||||
)
|
||||
product_response.raise_for_status()
|
||||
product_description = product_response.json().get("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]
|
||||
)
|
||||
description = (
|
||||
self._short_description(str(product_description.get("lead") or ""))
|
||||
or self._short_description(str(product_description.get("full") or ""))
|
||||
or description
|
||||
)
|
||||
except requests.RequestException as error:
|
||||
logger.warning(
|
||||
"Failed to load localized GOG description for %s: %s",
|
||||
@@ -732,6 +731,61 @@ 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*/?>| )\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):
|
||||
|
||||
@@ -23,20 +23,22 @@ class GameEntry:
|
||||
class SearchConfig:
|
||||
"""Search configuration."""
|
||||
token: str
|
||||
hp_key: str
|
||||
hp_val: str
|
||||
hp_key: str | None = None
|
||||
hp_val: str | None = None
|
||||
|
||||
class HTTPClient:
|
||||
"""HTTP client for HowLongToBeat API."""
|
||||
BASE_URL = 'https://howlongtobeat.com/'
|
||||
AUTH_URL = BASE_URL + "api/bleed/init"
|
||||
SEARCH_URL = BASE_URL + "api/bleed"
|
||||
SEARCH_URL = BASE_URL + "api/search/site"
|
||||
AUTH_URL = SEARCH_URL + "/init"
|
||||
|
||||
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()
|
||||
@@ -52,15 +54,18 @@ class HTTPClient:
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
except (requests.RequestException, ValueError):
|
||||
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)
|
||||
return None
|
||||
if not data.get("token") or not data.get("hpKey") or not data.get("hpVal"):
|
||||
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")
|
||||
return None
|
||||
return SearchConfig(
|
||||
token=data["token"],
|
||||
hp_key=data["hpKey"],
|
||||
hp_val=data["hpVal"]
|
||||
)
|
||||
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)
|
||||
|
||||
def search_games(self, game_name: str, page: int = 1, config: SearchConfig | None = None) -> str | None:
|
||||
if not config:
|
||||
@@ -71,11 +76,10 @@ class HTTPClient:
|
||||
payload = self._build_search_payload(game_name, page, config)
|
||||
headers = {
|
||||
'content-type': 'application/json',
|
||||
'accept': '*/*',
|
||||
'x-auth-token': config.token,
|
||||
'x-hp-key': config.hp_key,
|
||||
'x-hp-val': config.hp_val
|
||||
'x-auth-token': config.token
|
||||
}
|
||||
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,
|
||||
@@ -106,14 +110,15 @@ class HTTPClient:
|
||||
'platform': "",
|
||||
'sortCategory': "popular",
|
||||
'rangeCategory': "main",
|
||||
'rangeTime': {'min': 0, 'max': 0},
|
||||
'rangeTime': {'min': None, 'max': None},
|
||||
'gameplay': {
|
||||
'perspective': "",
|
||||
'flow': "",
|
||||
'genre': "",
|
||||
"difficulty": ""
|
||||
},
|
||||
'rangeYear': {'max': "", 'min': ""}
|
||||
'year': "",
|
||||
'modifier': ""
|
||||
},
|
||||
'users': {'sortCategory': "postcount"},
|
||||
'lists': {'sortCategory': "follows"},
|
||||
@@ -121,10 +126,10 @@ class HTTPClient:
|
||||
'sort': 0,
|
||||
'randomizer': 0
|
||||
},
|
||||
'useCache': True,
|
||||
'fields': ["comp_main", "comp_plus", "comp_100"]
|
||||
'useCache': True
|
||||
}
|
||||
payload[config.hp_key] = config.hp_val
|
||||
if config.hp_key and config.hp_val:
|
||||
payload[config.hp_key] = config.hp_val
|
||||
return payload
|
||||
|
||||
class ResultParser:
|
||||
|
||||
@@ -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
|
||||
from portprotonqt.downloader import Downloader, is_complete_download
|
||||
from portprotonqt.icon_extractor import generate_thumbnail
|
||||
from portprotonqt.logger import get_logger
|
||||
from portprotonqt.qt_utils import get_device_pixel_ratio
|
||||
@@ -223,10 +223,12 @@ 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
|
||||
@@ -469,7 +471,7 @@ def load_pixmap_async(
|
||||
appid = parts[idx + 1]
|
||||
if appid:
|
||||
local_path = os.path.join(image_folder, f"{appid}.jpg")
|
||||
if os.path.exists(local_path):
|
||||
if is_complete_download(local_path):
|
||||
pixmap = QPixmap(local_path)
|
||||
# Check if the pixmap loaded successfully
|
||||
if pixmap.isNull():
|
||||
@@ -506,7 +508,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 os.path.exists(local_path):
|
||||
if is_complete_download(local_path):
|
||||
pixmap = QPixmap(local_path)
|
||||
# Check if the pixmap loaded successfully
|
||||
if pixmap.isNull():
|
||||
@@ -543,7 +545,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 os.path.exists(local_path):
|
||||
if is_complete_download(local_path):
|
||||
pixmap = QPixmap(local_path)
|
||||
# Check if the pixmap loaded successfully
|
||||
if pixmap.isNull():
|
||||
|
||||
@@ -290,6 +290,7 @@ 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
|
||||
@@ -440,6 +441,7 @@ 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
|
||||
@@ -522,6 +524,15 @@ 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:
|
||||
|
||||
@@ -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:
|
||||
if value == 0 or self._should_skip_regular_events():
|
||||
self._reset_dpad_repeat()
|
||||
return
|
||||
directions = {PAD_DPAD_X: ('left', 'right'), PAD_AXIS_LEFT_X: ('left', 'right'),
|
||||
|
||||
@@ -15,7 +15,6 @@ from PySide6.QtWidgets import (
|
||||
QListWidget,
|
||||
QMenu,
|
||||
QMessageBox,
|
||||
QScrollArea,
|
||||
QTableWidget,
|
||||
QWidget,
|
||||
)
|
||||
@@ -473,16 +472,12 @@ class KeyboardInputMixin(InputMixin):
|
||||
def _focus_first_game_card(self, container: QWidget | None) -> bool:
|
||||
if container is None:
|
||||
return False
|
||||
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
|
||||
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
|
||||
|
||||
def _focus_first_library_card(self) -> bool:
|
||||
container = getattr(self._parent, "gamesListWidget", None)
|
||||
|
||||
@@ -115,6 +115,7 @@ 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()
|
||||
@@ -233,6 +234,8 @@ 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
|
||||
@@ -266,6 +269,7 @@ 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
|
||||
@@ -288,6 +292,9 @@ 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:
|
||||
@@ -330,9 +337,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():
|
||||
@@ -387,16 +394,13 @@ 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 False
|
||||
return self._is_mouse_emulation_active() and bool(self.ui)
|
||||
if getattr(self, '_gamepad_polling_suspended', False):
|
||||
return True
|
||||
return self._is_mouse_emulation_active() and QApplication.activeWindow() is not None
|
||||
|
||||
@@ -420,6 +420,13 @@ 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 ""
|
||||
|
||||
@@ -479,9 +486,6 @@ 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 +493,7 @@ msgid "Invalid command format (native)"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr ""
|
||||
|
||||
msgid "Choose Folder"
|
||||
@@ -692,9 +696,10 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr ""
|
||||
|
||||
#, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
msgstr ""
|
||||
|
||||
msgid "CPU Cores Limit"
|
||||
@@ -795,10 +800,6 @@ msgstr ""
|
||||
msgid "No favorites"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr ""
|
||||
|
||||
msgid "Debug log mode was launched"
|
||||
msgstr ""
|
||||
|
||||
@@ -1062,10 +1063,6 @@ msgstr ""
|
||||
msgid "Download Selected"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Error loading WINE/Proton: {error}"
|
||||
msgstr ""
|
||||
|
||||
msgid "Version WINE/Proton"
|
||||
msgstr ""
|
||||
|
||||
@@ -1085,6 +1082,9 @@ msgstr ""
|
||||
msgid "Select to remove this WINE/Proton"
|
||||
msgstr ""
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Selected {} WINE/Proton:\n"
|
||||
msgstr ""
|
||||
@@ -1189,6 +1189,9 @@ msgstr ""
|
||||
msgid "Exe Settings"
|
||||
msgstr ""
|
||||
|
||||
msgid "Native"
|
||||
msgstr ""
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr ""
|
||||
|
||||
@@ -2003,6 +2006,9 @@ msgstr ""
|
||||
msgid "Mouse Emulation"
|
||||
msgstr ""
|
||||
|
||||
msgid "System Keyboard"
|
||||
msgstr ""
|
||||
|
||||
msgid "Connect"
|
||||
msgstr ""
|
||||
|
||||
@@ -2123,9 +2129,6 @@ msgstr ""
|
||||
msgid "Select installation folder"
|
||||
msgstr ""
|
||||
|
||||
msgid "Another download is running"
|
||||
msgstr ""
|
||||
|
||||
msgid "Another GOG operation is already running"
|
||||
msgstr ""
|
||||
|
||||
@@ -2511,9 +2514,6 @@ msgstr ""
|
||||
msgid "Light"
|
||||
msgstr ""
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr ""
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr ""
|
||||
|
||||
|
||||
@@ -433,6 +433,13 @@ 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"
|
||||
|
||||
@@ -497,9 +504,6 @@ 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)"
|
||||
|
||||
@@ -507,8 +511,8 @@ msgid "Invalid command format (native)"
|
||||
msgstr "Ungültiges Befehlsformat"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Spiel konnte nicht gestartet werden: {0}"
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Ausführen \"{name}\" mit PortProton"
|
||||
|
||||
msgid "Choose Folder"
|
||||
msgstr "Ordner auswählen"
|
||||
@@ -750,12 +754,13 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr "Nach Start ausführen / Wrapper"
|
||||
|
||||
#, fuzzy, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
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"
|
||||
@@ -872,10 +877,6 @@ 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"
|
||||
|
||||
@@ -1145,10 +1146,6 @@ 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"
|
||||
|
||||
@@ -1168,6 +1165,9 @@ 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,6 +1278,10 @@ 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"
|
||||
|
||||
@@ -2110,6 +2114,10 @@ msgstr "Vollbild"
|
||||
msgid "Mouse Emulation"
|
||||
msgstr "Mausemulation"
|
||||
|
||||
#, fuzzy
|
||||
msgid "System Keyboard"
|
||||
msgstr "Tastatur-Eingabe abfangen"
|
||||
|
||||
msgid "Connect"
|
||||
msgstr "Verbinden"
|
||||
|
||||
@@ -2230,9 +2238,6 @@ 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"
|
||||
|
||||
@@ -2624,9 +2629,6 @@ msgstr "Dunkel"
|
||||
msgid "Light"
|
||||
msgstr "Hell"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Laden…"
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr "Laden der Themes fehlgeschlagen"
|
||||
|
||||
|
||||
@@ -434,6 +434,13 @@ 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"
|
||||
|
||||
@@ -497,9 +504,6 @@ 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)"
|
||||
|
||||
@@ -507,8 +511,8 @@ msgid "Invalid command format (native)"
|
||||
msgstr "Formato de comando no válido (nativo)"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Error al iniciar el juego: {0}"
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Iniciar «{name}» con PortProton"
|
||||
|
||||
msgid "Choose Folder"
|
||||
msgstr "Seleccionar carpeta"
|
||||
@@ -765,9 +769,10 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr "Ejecutar después / Envoltorio"
|
||||
|
||||
#, fuzzy, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
msgstr ""
|
||||
"Ruta a un segundo archivo .exe, script o comando de envoltura. Ejemplo: "
|
||||
"systemd-run --user --scope --slice=app.slice"
|
||||
@@ -887,10 +892,6 @@ 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"
|
||||
|
||||
@@ -1159,10 +1160,6 @@ 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"
|
||||
|
||||
@@ -1182,6 +1179,9 @@ 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,6 +1291,9 @@ msgstr "Ajustes de Wine"
|
||||
msgid "Exe Settings"
|
||||
msgstr ""
|
||||
|
||||
msgid "Native"
|
||||
msgstr ""
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr ""
|
||||
|
||||
@@ -2114,6 +2117,9 @@ msgstr ""
|
||||
msgid "Mouse Emulation"
|
||||
msgstr ""
|
||||
|
||||
msgid "System Keyboard"
|
||||
msgstr ""
|
||||
|
||||
msgid "Connect"
|
||||
msgstr ""
|
||||
|
||||
@@ -2235,10 +2241,6 @@ 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 ""
|
||||
|
||||
@@ -2633,9 +2635,6 @@ msgstr ""
|
||||
msgid "Light"
|
||||
msgstr ""
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Cargando…"
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr "Error al cargar los temas"
|
||||
|
||||
|
||||
@@ -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-10-24 18:13+0500\n"
|
||||
"POT-Creation-Date: 2026-11-20 23:00+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,6 +416,13 @@ 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 ""
|
||||
|
||||
@@ -475,9 +482,6 @@ 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 ""
|
||||
|
||||
@@ -485,7 +489,7 @@ msgid "Invalid command format (native)"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr ""
|
||||
|
||||
msgid "Choose Folder"
|
||||
@@ -688,9 +692,10 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr ""
|
||||
|
||||
#, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
msgstr ""
|
||||
|
||||
msgid "CPU Cores Limit"
|
||||
@@ -791,10 +796,6 @@ msgstr ""
|
||||
msgid "No favorites"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr ""
|
||||
|
||||
msgid "Debug log mode was launched"
|
||||
msgstr ""
|
||||
|
||||
@@ -1058,10 +1059,6 @@ msgstr ""
|
||||
msgid "Download Selected"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Error loading WINE/Proton: {error}"
|
||||
msgstr ""
|
||||
|
||||
msgid "Version WINE/Proton"
|
||||
msgstr ""
|
||||
|
||||
@@ -1081,6 +1078,9 @@ msgstr ""
|
||||
msgid "Select to remove this WINE/Proton"
|
||||
msgstr ""
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Selected {} WINE/Proton:\n"
|
||||
msgstr ""
|
||||
@@ -1185,6 +1185,9 @@ msgstr ""
|
||||
msgid "Exe Settings"
|
||||
msgstr ""
|
||||
|
||||
msgid "Native"
|
||||
msgstr ""
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr ""
|
||||
|
||||
@@ -1999,6 +2002,9 @@ msgstr ""
|
||||
msgid "Mouse Emulation"
|
||||
msgstr ""
|
||||
|
||||
msgid "System Keyboard"
|
||||
msgstr ""
|
||||
|
||||
msgid "Connect"
|
||||
msgstr ""
|
||||
|
||||
@@ -2119,9 +2125,6 @@ msgstr ""
|
||||
msgid "Select installation folder"
|
||||
msgstr ""
|
||||
|
||||
msgid "Another download is running"
|
||||
msgstr ""
|
||||
|
||||
msgid "Another GOG operation is already running"
|
||||
msgstr ""
|
||||
|
||||
@@ -2508,9 +2511,6 @@ msgstr ""
|
||||
msgid "Light"
|
||||
msgstr ""
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr ""
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr ""
|
||||
|
||||
|
||||
@@ -433,6 +433,13 @@ 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"
|
||||
|
||||
@@ -496,9 +503,6 @@ 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)"
|
||||
|
||||
@@ -506,8 +510,8 @@ msgid "Invalid command format (native)"
|
||||
msgstr "Formato de comando inválido (nativo)"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Falha ao iniciar o jogo: {0}"
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Iniciar \"{name}\" com o PortProton"
|
||||
|
||||
msgid "Choose Folder"
|
||||
msgstr "Escolher Pasta"
|
||||
@@ -750,9 +754,10 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr "Executar após / Wrapper"
|
||||
|
||||
#, fuzzy, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
msgstr ""
|
||||
"Caminho para um segundo arquivo .exe, script ou comando wrapper. Exemplo:"
|
||||
" systemd-run --user --scope --slice=app.slice"
|
||||
@@ -874,10 +879,6 @@ 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"
|
||||
|
||||
@@ -1145,10 +1146,6 @@ 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"
|
||||
|
||||
@@ -1168,6 +1165,9 @@ 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,6 +1277,10 @@ 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"
|
||||
|
||||
@@ -2107,6 +2111,10 @@ msgstr "Tela Cheia"
|
||||
msgid "Mouse Emulation"
|
||||
msgstr "Emulação de Mouse"
|
||||
|
||||
#, fuzzy
|
||||
msgid "System Keyboard"
|
||||
msgstr "Capturar o teclado"
|
||||
|
||||
msgid "Connect"
|
||||
msgstr "Conectar"
|
||||
|
||||
@@ -2227,9 +2235,6 @@ 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"
|
||||
|
||||
@@ -2619,9 +2624,6 @@ msgstr "Escuro"
|
||||
msgid "Light"
|
||||
msgstr "Claro"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Carregando…"
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr "Falha ao carregar temas"
|
||||
|
||||
|
||||
@@ -431,6 +431,13 @@ 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,9 +500,6 @@ 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)"
|
||||
|
||||
@@ -503,8 +507,8 @@ msgid "Invalid command format (native)"
|
||||
msgstr "Неверный формат команды (нативный)"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Не удалось запустить игру: {0}"
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Запустить «{name}» с помощью PortProton"
|
||||
|
||||
msgid "Choose Folder"
|
||||
msgstr "Выбрать папку"
|
||||
@@ -746,9 +750,10 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr "Запустить после"
|
||||
|
||||
#, fuzzy, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
msgstr ""
|
||||
"Путь к второму файлу .exe, скрипту или команде-обёртке. Пример: systemd-"
|
||||
"run --user --scope --slice=app.slice"
|
||||
@@ -872,10 +877,6 @@ msgstr "Нет недавних игр"
|
||||
msgid "No favorites"
|
||||
msgstr "Нет избранных"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Запустить «{name}» с помощью PortProton"
|
||||
|
||||
msgid "Debug log mode was launched"
|
||||
msgstr "Запущен режим логирования"
|
||||
|
||||
@@ -1143,10 +1144,6 @@ 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"
|
||||
|
||||
@@ -1166,6 +1163,9 @@ 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,6 +1275,10 @@ msgstr "Глобальные настройки игры"
|
||||
msgid "Exe Settings"
|
||||
msgstr "Настройки EXE"
|
||||
|
||||
#, fuzzy
|
||||
msgid "Native"
|
||||
msgstr "После отображения кадра"
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr "Изменить user.conf"
|
||||
|
||||
@@ -2103,6 +2107,10 @@ msgstr "Полный экран"
|
||||
msgid "Mouse Emulation"
|
||||
msgstr "Эмуляция мыши"
|
||||
|
||||
#, fuzzy
|
||||
msgid "System Keyboard"
|
||||
msgstr "Перехват нажатий кнопок клавиатуры"
|
||||
|
||||
msgid "Connect"
|
||||
msgstr "Подключиться"
|
||||
|
||||
@@ -2221,9 +2229,6 @@ msgstr "Не удалось обновить библиотеку Epic: {0}"
|
||||
msgid "Select installation folder"
|
||||
msgstr "Выберите папку установки"
|
||||
|
||||
msgid "Another download is running"
|
||||
msgstr "Другая загрузка уже выполняется"
|
||||
|
||||
msgid "Another GOG operation is already running"
|
||||
msgstr "Другая операция GOG уже выполняется"
|
||||
|
||||
@@ -2609,9 +2614,6 @@ msgstr "Тёмная"
|
||||
msgid "Light"
|
||||
msgstr "Светлая"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Загрузка…"
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr "Не удалось загрузить темы"
|
||||
|
||||
|
||||
@@ -422,6 +422,13 @@ 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 "从不"
|
||||
|
||||
@@ -486,9 +493,6 @@ 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 行为空)"
|
||||
|
||||
@@ -496,8 +500,8 @@ msgid "Invalid command format (native)"
|
||||
msgstr "命令格式无效(原生)"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "启动游戏失败:{0}"
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "使用 PortProton 启动\"{name}\""
|
||||
|
||||
msgid "Choose Folder"
|
||||
msgstr "选择文件夹"
|
||||
@@ -723,9 +727,10 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr "运行后 / 包装器"
|
||||
|
||||
#, fuzzy, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
msgstr "指向第二个 .exe、脚本或包装器命令的路径。示例:systemd-run --user --scope --slice=app.slice"
|
||||
|
||||
msgid "CPU Cores Limit"
|
||||
@@ -836,10 +841,6 @@ msgstr "无最近游戏"
|
||||
msgid "No favorites"
|
||||
msgstr "无收藏"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "使用 PortProton 启动\"{name}\""
|
||||
|
||||
msgid "Debug log mode was launched"
|
||||
msgstr "调试日志模式已启动"
|
||||
|
||||
@@ -1110,10 +1111,6 @@ 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 版本"
|
||||
|
||||
@@ -1133,6 +1130,9 @@ 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,6 +1243,10 @@ msgstr "保存设置"
|
||||
msgid "Exe Settings"
|
||||
msgstr "可执行文件设置"
|
||||
|
||||
#, fuzzy
|
||||
msgid "Native"
|
||||
msgstr "晚"
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr "编辑 user.conf"
|
||||
|
||||
@@ -2060,6 +2064,10 @@ msgstr "全屏"
|
||||
msgid "Mouse Emulation"
|
||||
msgstr "鼠标模拟"
|
||||
|
||||
#, fuzzy
|
||||
msgid "System Keyboard"
|
||||
msgstr "捕获键盘"
|
||||
|
||||
msgid "Connect"
|
||||
msgstr "连接"
|
||||
|
||||
@@ -2191,10 +2199,6 @@ msgstr "启动游戏失败:{0}"
|
||||
msgid "Select installation folder"
|
||||
msgstr "选择安装文件夹"
|
||||
|
||||
#, fuzzy
|
||||
msgid "Another download is running"
|
||||
msgstr "正在下载"
|
||||
|
||||
msgid "Another GOG operation is already running"
|
||||
msgstr "另一个 GOG 操作正在运行中"
|
||||
|
||||
@@ -2594,9 +2598,6 @@ msgstr "深色"
|
||||
msgid "Light"
|
||||
msgstr "浅色"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "加载中…"
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr "加载主题失败"
|
||||
|
||||
|
||||
+20
-11
@@ -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, read_native_game
|
||||
from portprotonqt.native_games import NativeLibraryWorker, NATIVE_URI_PREFIX, get_native_launch, is_native_executable, 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
|
||||
@@ -1195,35 +1195,44 @@ class MainWindow(
|
||||
dialog.deleteLater()
|
||||
|
||||
def _launch_native_game(self, exec_line: str, button: QPushButton | None = None) -> None:
|
||||
desktop_path = Path(exec_line.removeprefix(NATIVE_URI_PREFIX))
|
||||
target = Path(exec_line.removeprefix(NATIVE_URI_PREFIX))
|
||||
is_shortcut = exec_line.startswith(NATIVE_URI_PREFIX)
|
||||
if self.game_processes:
|
||||
if getattr(self, "native_game_running", False) and self.game_start_exe == str(desktop_path):
|
||||
if getattr(self, "native_game_running", False) and self.game_start_exe == str(target):
|
||||
self.stop_running_game(button)
|
||||
else:
|
||||
QMessageBox.warning(self, _("Error"), _("Cannot launch game while another game is running"))
|
||||
return
|
||||
try:
|
||||
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))
|
||||
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)
|
||||
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", desktop_path, error)
|
||||
logger.warning("Failed to launch native game %s: %s", target, 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 = desktop_path.name
|
||||
self.game_start_exe = str(desktop_path)
|
||||
self.target_exe = target.name
|
||||
self.game_start_exe = str(target)
|
||||
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
|
||||
save_last_launch(desktop_path.stem, self.game_start_time)
|
||||
self._update_last_launch_after_start(str(desktop_path), self.game_start_time)
|
||||
if is_shortcut:
|
||||
save_last_launch(target.stem, self.game_start_time)
|
||||
self._update_last_launch_after_start(str(target), self.game_start_time)
|
||||
self.launch_output_queue = Queue()
|
||||
self.input_manager.suspend_gamepad_polling()
|
||||
self._set_running_button_stop()
|
||||
|
||||
@@ -32,9 +32,9 @@ NATIVE_ADVANCED_KEYS = frozenset({"LAUNCH_PARAMETERS", "PW_MESA_GL_VERSION_OVERR
|
||||
|
||||
|
||||
def is_native_executable(path: str) -> bool:
|
||||
"""Recognize native launch files while preserving Windows and disc formats."""
|
||||
"""Recognize native executables, not desktop shortcuts or Wine targets."""
|
||||
return (
|
||||
Path(path).suffix.lower() not in LAUNCH_FILE_EXTENSIONS
|
||||
not path.lower().endswith(LAUNCH_FILE_EXTENSIONS + (".desktop",))
|
||||
and os.path.isfile(path)
|
||||
and os.access(path, os.X_OK)
|
||||
)
|
||||
|
||||
@@ -11,6 +11,7 @@ from portprotonqt.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
SHUTDOWN_TIMEOUT_MS = 3000
|
||||
MAX_EMOJI_LENGTH = 16
|
||||
|
||||
|
||||
class SystemKeyboard(QObject):
|
||||
@@ -77,6 +78,11 @@ 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:
|
||||
|
||||
@@ -43,6 +43,7 @@ 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')
|
||||
@@ -105,7 +106,8 @@ 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']
|
||||
for row, keys in enumerate(self.theme.SYSTEM_KEYBOARD['rows']):
|
||||
rows = self.theme.SYSTEM_KEYBOARD['emoji_rows' if self.emoji_open else 'rows']
|
||||
for row, keys in enumerate(rows):
|
||||
column = 0
|
||||
for key, span in keys:
|
||||
if key == '▲▼':
|
||||
@@ -115,7 +117,8 @@ class SystemKeyboardPanel(VirtualKeyboard):
|
||||
self._add_key(key, (row * units, column, units, span))
|
||||
column += span
|
||||
self.apply_key_state()
|
||||
self._set_selected_button(self.buttons.get(selected or 'Esc', self.buttons['Esc']))
|
||||
default = rows[0][0][0]
|
||||
self._set_selected_button(self.buttons.get(selected or default, self.buttons[default]))
|
||||
if self.owner.warning_message:
|
||||
warning = QLabel(self.owner.warning_message)
|
||||
warning.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
|
||||
@@ -186,7 +189,25 @@ 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,)))
|
||||
@@ -323,6 +344,7 @@ 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()
|
||||
@@ -380,6 +402,10 @@ 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:
|
||||
|
||||
@@ -596,9 +596,12 @@ class MainWindowLibraryTabMixin(_MainWindowTypingBase):
|
||||
self.updateDeleteMissingExeButton()
|
||||
|
||||
def quickLaunch(self):
|
||||
"""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)
|
||||
"""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)
|
||||
|
||||
parent_geometry = self.geometry()
|
||||
center_point = parent_geometry.center()
|
||||
@@ -608,6 +611,13 @@ 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()
|
||||
|
||||
@@ -160,12 +160,11 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
|
||||
tools_grid.setSpacing(6)
|
||||
|
||||
tools = [
|
||||
("winecfg", _("Wine Configuration")),
|
||||
("regedit", _("Registry Editor")),
|
||||
("winefile", _("File Explorer")),
|
||||
("cmd", _("Command Prompt")),
|
||||
("uninstaller", _("Uninstaller")),
|
||||
("taskmgr", _("Task Manager")),
|
||||
("--winecfg", _("Wine Configuration")),
|
||||
("--winereg", _("Registry Editor")),
|
||||
("--winefile", _("File Explorer")),
|
||||
("--winecmd", _("Command Prompt")),
|
||||
("--wine_uninstaller", _("Uninstaller")),
|
||||
]
|
||||
|
||||
for i, (tool_cmd, tool_name) in enumerate(tools):
|
||||
@@ -238,7 +237,7 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
|
||||
env_vars = os.environ.copy()
|
||||
self._check_missing_prefix_by_name_before_launch(prefix, env_vars)
|
||||
start_sh = self.start_sh
|
||||
cmd = start_sh + ["cli", "--wine-session-tool", cli_arg, wine, prefix]
|
||||
cmd = start_sh + ["cli", cli_arg, wine, prefix]
|
||||
|
||||
# Show progress bar before launch
|
||||
self.wine_progress_bar.setVisible(True)
|
||||
@@ -270,7 +269,16 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
|
||||
|
||||
def _check_wine_process(self, cli_arg):
|
||||
"""Check if target .exe process started."""
|
||||
target_exe = f"{cli_arg}.exe"
|
||||
exe_map = {
|
||||
"--winecfg": "winecfg.exe",
|
||||
"--winereg": "regedit.exe",
|
||||
"--winefile": "winefile.exe",
|
||||
"--winecmd": "cmd.exe",
|
||||
"--wine_uninstaller": "uninstaller.exe",
|
||||
}
|
||||
target_exe = exe_map.get(cli_arg, "")
|
||||
if not target_exe:
|
||||
return
|
||||
|
||||
# Check processes via psutil
|
||||
for proc in psutil.process_iter(attrs=["name"]):
|
||||
|
||||
File renamed without changes.
|
Before Width: | Height: | Size: 3.1 KiB After Width: | Height: | Size: 3.1 KiB |
@@ -334,9 +334,17 @@ 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", 10), ("🌐", 2), ("AltGr", 2),
|
||||
(("Ctrl", 2), ("Super", 2), ("Alt", 2), ("Space", 8), ("🙂", 2), ("🌐", 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"
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ import subprocess
|
||||
import signal
|
||||
import psutil
|
||||
import os
|
||||
from PySide6.QtCore import QProcess
|
||||
from PySide6.QtWidgets import QSystemTrayIcon, QMenu, QApplication, QMessageBox
|
||||
from PySide6.QtGui import QIcon, QAction
|
||||
from portprotonqt.logger import get_logger
|
||||
@@ -46,39 +45,6 @@ def _restart_args(args: list[str]) -> list[str]:
|
||||
return restart_args
|
||||
|
||||
|
||||
def create_wine_tools_menu(parent: QMenu, start_sh: list[str]) -> QMenu:
|
||||
"""Create tools that join the running game's Wine session."""
|
||||
menu = QMenu("Wine", parent)
|
||||
tools = (
|
||||
("winefile", _("File Explorer")),
|
||||
("taskmgr", _("Task Manager")),
|
||||
("winecfg", _("Wine Configuration")),
|
||||
("regedit", _("Registry Editor")),
|
||||
("cmd", _("Command Prompt")),
|
||||
("uninstaller", _("Uninstaller")),
|
||||
)
|
||||
for tool, title in tools:
|
||||
action = menu.addAction(title)
|
||||
action.triggered.connect(
|
||||
lambda checked=False, name=tool: launch_session_wine_tool(start_sh, name)
|
||||
)
|
||||
return menu
|
||||
|
||||
|
||||
def launch_session_wine_tool(start_sh: list[str], tool: str) -> None:
|
||||
"""Start a Wine tool without running the game's startup or cleanup."""
|
||||
if not start_sh:
|
||||
logger.error("Cannot launch Wine tool: PortProton command is missing")
|
||||
QMessageBox.warning(None, _("Error"), _("Failed to start process."))
|
||||
return
|
||||
started, _pid = QProcess.startDetached(
|
||||
start_sh[0], start_sh[1:] + ["cli", "--wine-session-tool", tool]
|
||||
)
|
||||
if not started:
|
||||
logger.error("Failed to start Wine tool %s", tool)
|
||||
QMessageBox.warning(None, _("Error"), _("Failed to start process."))
|
||||
|
||||
|
||||
class TrayManager:
|
||||
"""Tray management module for PortProtonQt.
|
||||
|
||||
@@ -117,12 +83,8 @@ class TrayManager:
|
||||
self.pause_game_action.setEnabled(False)
|
||||
self.pause_game_action.triggered.connect(self.toggle_game_pause)
|
||||
|
||||
self.wine_tools_menu = create_wine_tools_menu(self.tray_menu, self.main_window.start_sh)
|
||||
self.wine_tools_menu.setEnabled(False)
|
||||
|
||||
self.tray_menu.addAction(self.pause_game_action)
|
||||
self.tray_menu.addAction(self.stop_game_action)
|
||||
self.tray_menu.addMenu(self.wine_tools_menu)
|
||||
self.tray_menu.addSeparator()
|
||||
self.tray_menu.addSeparator()
|
||||
|
||||
@@ -141,7 +103,6 @@ class TrayManager:
|
||||
|
||||
self.tray_menu.addAction(self.pause_game_action)
|
||||
self.tray_menu.addAction(self.stop_game_action)
|
||||
self.tray_menu.addMenu(self.wine_tools_menu)
|
||||
self.update_game_actions()
|
||||
system_keyboard = getattr(getattr(self, 'main_window', None), 'system_keyboard', None)
|
||||
if system_keyboard is not None:
|
||||
@@ -194,7 +155,6 @@ class TrayManager:
|
||||
target_exe = getattr(self.main_window, "target_exe", None)
|
||||
has_running_game = bool(game_processes or target_exe)
|
||||
self.stop_game_action.setEnabled(has_running_game)
|
||||
self.wine_tools_menu.setEnabled(has_running_game)
|
||||
self.pause_game_action.setEnabled(bool(processes))
|
||||
paused = self._are_processes_paused(processes)
|
||||
self.pause_game_action.setText(_("Resume Game") if paused else _("Pause Game"))
|
||||
|
||||
@@ -737,3 +737,57 @@ 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()
|
||||
@@ -1,10 +1,13 @@
|
||||
"""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
|
||||
@@ -21,6 +24,44 @@ 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(
|
||||
|
||||
+77
-2
@@ -309,9 +309,84 @@ 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> </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> </p><p>Реалистичный психологический триллер. ',
|
||||
"Реалистичный психологический триллер.",
|
||||
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> </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.",
|
||||
@@ -323,7 +398,7 @@ def test_download_sizes_cache(tmp_path: Path) -> None:
|
||||
],
|
||||
)
|
||||
def test_get_game_loads_localized_product_description(
|
||||
monkeypatch: pytest.MonkeyPatch, lead: str, expected: str
|
||||
monkeypatch: pytest.MonkeyPatch, lead: str | dict[str, str], expected: str
|
||||
) -> None:
|
||||
gamesdb_response = Mock()
|
||||
gamesdb_response.json.return_value = {
|
||||
@@ -337,7 +412,7 @@ def test_get_game_loads_localized_product_description(
|
||||
}
|
||||
product_response = Mock()
|
||||
product_response.json.return_value = {
|
||||
"description": {"lead": lead},
|
||||
"description": {"lead": lead} if isinstance(lead, str) else lead,
|
||||
}
|
||||
request = Mock(side_effect=[gamesdb_response, product_response])
|
||||
monkeypatch.setattr("portprotonqt.gog_api.get_metadata_language", lambda: "fr")
|
||||
|
||||
@@ -650,6 +650,8 @@ 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),
|
||||
@@ -657,7 +659,6 @@ 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))
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ 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 (
|
||||
@@ -268,6 +269,49 @@ 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)
|
||||
@@ -530,6 +574,32 @@ 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()
|
||||
|
||||
@@ -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_linux.svg"
|
||||
assert Path(card.nativeLabel._icon).name == "badge_native.svg"
|
||||
assert Path(card.nativeLabel._icon).is_file()
|
||||
assert not card.portproton_visible
|
||||
card.deleteLater()
|
||||
|
||||
@@ -207,6 +207,14 @@ 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()
|
||||
@@ -249,3 +257,18 @@ 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()
|
||||
+4
-101
@@ -42,7 +42,7 @@ from portprotonqt.game_library_manager import FullLibraryTile, GameLibraryManage
|
||||
from portprotonqt.input_manager import InputManager
|
||||
from portprotonqt.main_window import MainWindow
|
||||
from portprotonqt.search_utils import SearchOptimizer, search_index
|
||||
from portprotonqt.tray_manager import TrayManager, create_wine_tools_menu, launch_session_wine_tool
|
||||
from portprotonqt.tray_manager import TrayManager
|
||||
from portprotonqt.themes.standart.styles.constants import GAME_CARD_ANIMATION
|
||||
from portprotonqt.portproton_api import remove_empty_custom_data_dirs
|
||||
import portprotonqt.tabs.autoinstall_tab as autoinstall_tab_module
|
||||
@@ -374,71 +374,18 @@ def test_minimal_tray_contains_game_actions() -> None:
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
manager = TrayManager.__new__(TrayManager)
|
||||
manager.tray_menu = QMenu()
|
||||
owner = QWidget()
|
||||
manager.pause_game_action = QAction("Pause Game", owner)
|
||||
manager.stop_game_action = QAction("Stop Game", owner)
|
||||
manager.wine_tools_menu = create_wine_tools_menu(manager.tray_menu, ["portproton"])
|
||||
manager.pause_game_action = QAction("Pause Game", manager.tray_menu)
|
||||
manager.stop_game_action = QAction("Stop Game", manager.tray_menu)
|
||||
manager.minimal_mode = True
|
||||
manager.update_game_actions = MagicMock()
|
||||
|
||||
manager.refresh_tray_menu()
|
||||
manager.refresh_tray_menu()
|
||||
|
||||
assert manager.tray_menu.actions() == [
|
||||
manager.pause_game_action,
|
||||
manager.stop_game_action,
|
||||
manager.wine_tools_menu.menuAction(),
|
||||
]
|
||||
assert manager.update_game_actions.call_count == 2
|
||||
|
||||
|
||||
@mark.parametrize("tool_index,tool", list(enumerate(
|
||||
("winefile", "taskmgr", "winecfg", "regedit", "cmd", "uninstaller")
|
||||
)))
|
||||
def test_wine_tools_menu_launches_session_tool(
|
||||
monkeypatch: MonkeyPatch, tool_index: int, tool: str,
|
||||
) -> None:
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
parent = QMenu()
|
||||
start = MagicMock(return_value=(True, 123))
|
||||
monkeypatch.setattr("portprotonqt.tray_manager.QProcess.startDetached", start)
|
||||
menu = create_wine_tools_menu(parent, ["bash", "/path with spaces/start.sh"])
|
||||
|
||||
assert len(menu.actions()) == 6
|
||||
menu.actions()[tool_index].trigger()
|
||||
|
||||
start.assert_called_once_with(
|
||||
"bash", ["/path with spaces/start.sh", "cli", "--wine-session-tool", tool]
|
||||
)
|
||||
|
||||
|
||||
def test_wine_tool_start_failure_is_reported(monkeypatch: MonkeyPatch) -> None:
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
warning = MagicMock()
|
||||
monkeypatch.setattr("portprotonqt.tray_manager.QMessageBox.warning", warning)
|
||||
monkeypatch.setattr(
|
||||
"portprotonqt.tray_manager.QProcess.startDetached", lambda *args: (False, 0)
|
||||
)
|
||||
|
||||
launch_session_wine_tool(["portproton"], "winefile")
|
||||
|
||||
warning.assert_called_once()
|
||||
|
||||
|
||||
@mark.parametrize("running", [False, True])
|
||||
def test_wine_tools_menu_requires_running_game(running: bool) -> None:
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
manager = TrayManager.__new__(TrayManager)
|
||||
manager.main_window = SimpleNamespace(game_processes=[], target_exe="game.exe" if running else None)
|
||||
manager.stop_game_action = QAction()
|
||||
manager.pause_game_action = QAction()
|
||||
manager.wine_tools_menu = QMenu()
|
||||
manager._game_process_tree = MagicMock(return_value=[])
|
||||
|
||||
manager.update_game_actions()
|
||||
|
||||
assert manager.wine_tools_menu.isEnabled() is running
|
||||
|
||||
manager.update_game_actions.assert_called_once_with()
|
||||
|
||||
def test_tray_pauses_game_process_tree(monkeypatch: MonkeyPatch) -> None:
|
||||
child = MagicMock(pid=12)
|
||||
@@ -3632,47 +3579,3 @@ def test_system_keyboard_control_hint_opens_keyboard() -> None:
|
||||
MainWindowControlHintsMixin._triggerControlHintAction(cast(Any, window), "system_keyboard")
|
||||
|
||||
window.system_keyboard.toggle.assert_called_once_with()
|
||||
|
||||
|
||||
@mark.parametrize("tool", ["winecfg", "regedit", "winefile", "cmd", "uninstaller", "taskmgr"])
|
||||
@mark.parametrize("running", [False, True])
|
||||
def test_wine_settings_tools_use_unified_command(
|
||||
monkeypatch: MonkeyPatch, tool: str, running: bool,
|
||||
) -> None:
|
||||
process = MagicMock()
|
||||
monkeypatch.setattr("portprotonqt.tabs.wine_tab.QProcess", MagicMock(return_value=process))
|
||||
window = MagicMock()
|
||||
window.game_processes = [MagicMock()] if running else []
|
||||
window.target_exe = "game.exe" if running else None
|
||||
window.start_sh = ["bash", "/path with spaces/start.sh"]
|
||||
window.wineCombo.currentText.return_value = "WINE_LG"
|
||||
window.prefixCombo.currentText.return_value = "my prefix"
|
||||
|
||||
WineMixin.launch_generic_tool(window, tool)
|
||||
|
||||
process.start.assert_called_once_with(
|
||||
"bash", ["/path with spaces/start.sh", "cli", "--wine-session-tool", tool, "WINE_LG", "MY_PREFIX"],
|
||||
)
|
||||
window._start_wine_process_monitor.assert_called_once_with(tool)
|
||||
|
||||
|
||||
|
||||
def test_silent_tray_includes_wine_tools_menu(monkeypatch: MonkeyPatch) -> None:
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
manager = TrayManager.__new__(TrayManager)
|
||||
manager.tray_menu = QMenu()
|
||||
owner = QWidget()
|
||||
manager.pause_game_action = QAction("Pause Game", owner)
|
||||
manager.stop_game_action = QAction("Stop Game", owner)
|
||||
manager.wine_tools_menu = create_wine_tools_menu(manager.tray_menu, ["portproton"])
|
||||
manager.update_game_actions = MagicMock()
|
||||
start = MagicMock(return_value=(True, 123))
|
||||
monkeypatch.setattr("portprotonqt.tray_manager.QProcess.startDetached", start)
|
||||
|
||||
manager.set_minimal_mode()
|
||||
|
||||
tools = manager.tray_menu.actions()[2].menu()
|
||||
assert isinstance(tools, QMenu)
|
||||
assert len(tools.actions()) == 6
|
||||
tools.actions()[1].trigger()
|
||||
start.assert_called_once_with("portproton", ["cli", "--wine-session-tool", "taskmgr"])
|
||||
@@ -12,7 +12,7 @@ import subprocess
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QEventLoop, QStandardPaths, QThread, QTimer, Qt
|
||||
from PySide6.QtCore import QEventLoop, QMimeData, QRect, QStandardPaths, QThread, QTimer, Qt, QUrl
|
||||
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton
|
||||
from PySide6.QtGui import QIcon
|
||||
|
||||
@@ -169,6 +169,71 @@ 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))
|
||||
|
||||
@@ -456,141 +456,3 @@ def test_run_after_command_placeholder_preserves_arguments_and_status(
|
||||
)
|
||||
assert result.returncode == exit_code, result.stderr
|
||||
assert result.stdout == "yes\nаргумент с пробелами\n$(false)\n\n"
|
||||
|
||||
|
||||
def test_wine_session_missing_returns_distinct_status(tmp_path: Path) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definition = helper.split("pw_session_tool () {", 1)[1].split("pw_launch_wrapper () {", 1)[0]
|
||||
script = "pw_session_tool () {" + definition + '''
|
||||
print_error () { echo "$@" >&2; }
|
||||
sleep () { return 0; }
|
||||
pw_session_tool taskmgr 1
|
||||
'''
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script], cwd=tmp_path, capture_output=True, text=True, check=False,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)},
|
||||
)
|
||||
|
||||
assert result.returncode == 2
|
||||
|
||||
|
||||
@mark.parametrize("tool", ["winecfg", "regedit", "winefile", "cmd", "uninstaller", "taskmgr"])
|
||||
def test_wine_session_tool_standalone_uses_selected_wine_and_prefix(tmp_path: Path, tool: str) -> None:
|
||||
start = Path("build-aux/share/portproton/scripts/start.sh").read_text()
|
||||
block = start.split(" --wine-session-tool)\n", 1)[1].split(" --winetricks-list-all)", 1)[0]
|
||||
script = '''
|
||||
get_wine_and_pfx () { printf '%s\\n' "$@"; }
|
||||
start_portproton () { mkdir -p "$PORT_DATA_PATH/data/prefixes/$PW_PREFIX_NAME/drive_c"; echo start; }
|
||||
pw_run () { printf '%s\\n' "$@"; }
|
||||
stop_portproton () { echo stop; }
|
||||
''' + 'case "$1" in --wine-session-tool)\n' + block + '\nesac\n'
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script, "bash", "--wine-session-tool", tool, "WINE_LG", "MY_PREFIX"],
|
||||
cwd=tmp_path, capture_output=True, text=True, check=False,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path), "PW_PREFIX_NAME": "MY_PREFIX"},
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert result.stdout.splitlines() == ["WINE_LG", "MY_PREFIX", "start", tool, "stop"]
|
||||
|
||||
|
||||
@mark.parametrize("tool", ["winefile", "taskmgr", "winecfg", "regedit", "cmd", "uninstaller"])
|
||||
@mark.parametrize("tool_exit_code", [0, 2])
|
||||
def test_wine_session_tools_reuse_prefix_without_game_options(
|
||||
tmp_path: Path, tool: str, tool_exit_code: int,
|
||||
) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definitions = helper.split("pw_save_session_env () {", 1)[1].split("pw_launch_wrapper () {", 1)[0]
|
||||
script = "pw_save_session_env () {" + definitions + '''
|
||||
print_error () { echo "$@" >&2; }
|
||||
pw_run () {
|
||||
printf '%s\\n' "$1" "$WINEPREFIX" "${PW_USE_TERMINAL:-0}" "${LAUNCH_PARAMETERS:-}" \\
|
||||
"${PW_RUN_AFTER_EXE:-}" "${PW_RUN_GAMESCOPE:-}" "$PW_TMPFS_PATH"
|
||||
return "$TOOL_EXIT_CODE"
|
||||
}
|
||||
PW_TERM="test-terminal"
|
||||
export PW_START_PID="$$" WINEPREFIX="$PORT_DATA_PATH/prefix with spaces"
|
||||
export LAUNCH_PARAMETERS="--game-only" PW_RUN_AFTER_EXE=trainer.exe PW_RUN_GAMESCOPE=gamescope
|
||||
pw_save_session_env || exit 2
|
||||
pw_session_tool "$1"
|
||||
'''
|
||||
(tmp_path / "prefix with spaces/drive_c").mkdir(parents=True)
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script, "bash", tool], capture_output=True, text=True,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path),
|
||||
"TOOL_EXIT_CODE": str(tool_exit_code)}, check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == int(tool_exit_code != 0), result.stderr
|
||||
lines = result.stdout.splitlines()
|
||||
assert lines[:6] == [tool, str(tmp_path / "prefix with spaces"), "1" if tool == "cmd" else "0", "", "", ""]
|
||||
assert Path(lines[6]).is_dir()
|
||||
assert Path(lines[6]).stat().st_mode & 0o777 == 0o700
|
||||
session = next((tmp_path / "data/tmp").glob("wine-session-*/session.env"))
|
||||
assert session.stat().st_mode & 0o777 == 0o600
|
||||
assert 'declare -x PW_TERM="test-terminal"' in session.read_text()
|
||||
|
||||
|
||||
@mark.parametrize("unsafe_directory", [False, True])
|
||||
def test_wine_session_save_does_not_follow_symlinks(tmp_path: Path, unsafe_directory: bool) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definition = helper.split("pw_save_session_env () {", 1)[1].split("pw_remove_session_env () {", 1)[0]
|
||||
session_dir = tmp_path / "data/tmp" / f"wine-session-{os.getuid()}"
|
||||
session_dir.parent.mkdir(parents=True)
|
||||
victim = tmp_path / "victim"
|
||||
victim.write_text("keep this")
|
||||
if unsafe_directory:
|
||||
target = tmp_path / "other-directory"
|
||||
target.mkdir(mode=0o700)
|
||||
session_dir.symlink_to(target, target_is_directory=True)
|
||||
else:
|
||||
session_dir.mkdir(mode=0o700)
|
||||
(session_dir / "session.env").symlink_to(victim)
|
||||
result = subprocess.run(
|
||||
["bash", "-c", "pw_save_session_env () {" + definition + "\npw_save_session_env"],
|
||||
capture_output=True, text=True,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)}, check=False,
|
||||
)
|
||||
|
||||
assert victim.read_text() == "keep this"
|
||||
assert result.returncode == (1 if unsafe_directory else 0), result.stderr
|
||||
if not unsafe_directory:
|
||||
assert not (session_dir / "session.env").is_symlink()
|
||||
|
||||
|
||||
def test_wine_session_tool_rejects_unknown_tool_before_reading_environment(tmp_path: Path) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definition = helper.split("pw_session_tool () {", 1)[1].split("pw_launch_wrapper () {", 1)[0]
|
||||
script = "pw_session_tool () {" + definition + '''
|
||||
print_error () { echo "$@" >&2; }
|
||||
sleep () { exit 99; }
|
||||
pw_session_tool '../../other-command'
|
||||
'''
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script], capture_output=True, text=True,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)}, check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 1
|
||||
assert "Unsupported Wine tool" in result.stderr
|
||||
|
||||
|
||||
def test_wine_session_cleanup_preserves_newer_session(tmp_path: Path) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definitions = helper.split("pw_save_session_env () {", 1)[1].split("pw_session_tool () {", 1)[0]
|
||||
script = "pw_save_session_env () {" + definitions + '''
|
||||
export PW_START_PID="$$"
|
||||
pw_save_session_env || exit 2
|
||||
PW_START_PID=99999999
|
||||
pw_remove_session_env
|
||||
[[ -f "$PORT_DATA_PATH/data/tmp/wine-session-$(id -u)/session.env" ]] || exit 3
|
||||
PW_START_PID="$$"
|
||||
pw_remove_session_env
|
||||
[[ ! -e "$PORT_DATA_PATH/data/tmp/wine-session-$(id -u)/session.env" ]]
|
||||
'''
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script], capture_output=True, text=True,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)}, check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
@@ -68,6 +68,38 @@ 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'
|
||||
@@ -461,6 +493,7 @@ 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')
|
||||
|
||||
|
||||
Reference in new issue
Block a user