Compare commits

...
25 Commits
Author SHA1 Message Date
Boria138 65bc286494 chore(appimage): fix typo
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 22:51:12 +05:00
Boria138 cb91b41b46 chore(appimage): libqwebp.so
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 22:50:06 +05:00
Boria138 c24aec0e40 fix: bundle WebP Qt image plugin in AppImage
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 22:47:29 +05:00
Boria138 54271548ec fix: keep AppImage runtime libraries in sync
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 22:13:00 +05:00
Boria138 a9552a3c1b chore(build): make pefile explicit
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 15:58:34 +05:00
Boria138 88c30025de fix: refresh detail layout after HLTB load
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 11:50:15 +05:00
Boria138 1aac62b647 Revert "adapt detail page between full and compact modes"
This reverts commit 08131ea53f.
2026-05-15 11:47:43 +05:00
Boria138 08131ea53f adapt detail page between full and compact modes
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 11:13:02 +05:00
Boria138 2666159375 reduce HEAD cache files
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 10:59:37 +05:00
Boria138 3515ad0ac5 fix: update HowLongToBeat search API
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 10:57:20 +05:00
Boria138 0875896e45 fix: remove downloader network preflight checks
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 10:30:51 +05:00
Boria138 4f406cc966 chore: show source badges regardless of display filter
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 10:26:27 +05:00
Boria138 f9e0081fd6 Improve MDF to ISO sector conversion
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 22:39:27 +05:00
Boria138 bc4ba2169d fix: add missing RPM packaged files
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 22:22:43 +05:00
Boria138 cfc05c2017 chore: remove redundant defaults for APP_COMMIT and APP_VERSION
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 20:47:27 +05:00
Boria138 55fba9260e build: include commit hash in nightly version
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 20:32:34 +05:00
Boria138 ebc480883a fix: read runtime status from PortProton var.log
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 18:39:33 +05:00
Boria138 3548a48b8a chore: drop scripts version from PortProtonQt log
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 18:03:40 +05:00
Boria138 cdf36315f1 chore(pre-commit): improve meson file inclusion checks
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 17:28:57 +05:00
Boria138 6b9e33e1f1 chore(build): added conf and img
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 17:24:34 +05:00
Dervart 4bcfd1ae65 fix: set frameless popup with translucent background for context menu view to eliminate color underlay 2026-05-14 11:48:24 +00:00
Dervart aeb74ea38d fix: set frameless popup with translucent background for combobox view to eliminate color underlay 2026-05-14 11:48:24 +00:00
Boria138 7b8127679c fix: stop pending PortProton launch process group
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 16:30:25 +05:00
Boria138 1364164524 chore: route keyboard shortcuts through pygame keys
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 15:38:26 +05:00
Boria138 0339906d4c dev-scripts: call extract_strings in l10n.py only with --update-all
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 10:56:14 +05:00
38 changed files with 927 additions and 698 deletions

No files matched your search

+1 -1
View File
@@ -55,5 +55,5 @@ repos:
name: Check meson.build syntax and file inclusion
entry: ./dev-scripts/check_meson_files.py
language: system
files: (^portprotonqt/.*\.py$|meson\.build$)
files: (^portprotonqt/.*\.py$|^build-aux/share/portproton/|meson\.build$)
pass_filenames: false
+6
View File
@@ -30,6 +30,7 @@
- В настройки добавлена загрузка Wine/Proton в Steam `compatibilitytools.d`
### Changed
- Бейджи источников (Steam и PortProton) теперь отображаются при любом фильтре библиотеки
- Обложки к играм из Steam теперь полностью локальные
- Улучшен механизм кеширования данных
- Тип геймпада `Xbox` `PS` теперь выбирается автоматически
@@ -47,8 +48,11 @@
- Переработан трей
- Автоустановки теперь можно остановить
- Префиксы `DEFAULT`, `DOTNET` и `PROGRAMS` теперь всегда отображаются вверху списков префиксов
- Из лога удалена версия скриптов, так как скрипты теперь внутри PortProtonQt
- Из downloader удалена отдельная проверка сети через Yandex и Google
### Fixed
- Исправлено определение `PW_USE_RUNTIME` в debug-логе
- SGDB теперь не пытается получить обложки для игр из автоустовок
- Оптимизирован предпросмотр изображений в файловом менеджере
- Исправлено зависание интерфейса при открытии раздела Bluetooth в системе без физического Bluetooth-адаптера
@@ -62,6 +66,8 @@
- `custom_data` теперь применяется сразу после добавления игры из автоустановок и редактирования ярлыка
- Исправлено управление геймпадом в диалоге выбора файла для загрузки PPDB
- Исправлен повторный вывод одинаковых Vulkan GPU в `vk_gpu_info`
- Исправлена работа клавиатурного управления при раскладке, отличной от английской
- Исправлена загрузка данных HowLongToBeat
### Contributors
- @Dervart
+1 -1
View File
@@ -57,7 +57,7 @@ PortProtonQt использует код и зависимости от след
- [Icoextract](https://github.com/jlu5/icoextract) — библиотека для извлечения иконок, лицензия [MIT](https://github.com/jlu5/icoextract/blob/master/LICENSE).
- [HowLongToBeat Python API](https://github.com/ScrappyCocco/HowLongToBeat-PythonAPI) — библиотека для взаимодействия с HowLongToBeat, лицензия [MIT](https://github.com/ScrappyCocco/HowLongToBeat-PythonAPI/blob/master/LICENSE.md).
- [mdf2iso](https://github.com/ScrappyCocco/HowLongToBeat-PythonAPI) — библиотека для конвертации mdf в iso, лицензия [GPLv2](https://salsa.debian.org/debian/mdf2iso/-/blob/master/gpl.txt).
- [iat](https://sourceforge.net/projects/iat.berlios) — библиотека для конвертации mdf в iso, лицензия GPLv3
Полный текст лицензий см. в файле [LICENSE](LICENSE).
> [!WARNING]
+1 -1
View File
@@ -88,7 +88,7 @@ EOM
# Disable locale noextract
sed -i -E 's@[[:space:]]*usr/share/locale/\*@@g; s@[[:space:]]+@ @g; s@[[:space:]]+$@@' /etc/pacman.conf
pacman -Syy
pacman -Syyu --noconfirm --disable-download-timeout
echo "Building PortProtonQt from PKGBUILD..."
echo "---------------------------------------------------------------"
+2 -1
View File
@@ -11,6 +11,7 @@ export DESKTOP=/usr/share/applications/ru.linux_gaming.PortProtonQt.desktop
export ICON=/usr/share/icons/hicolor/scalable/apps/ru.linux_gaming.PortProtonQt.svg
export OUTNAME=PortProtonQt-"$VERSION"-anylinux-"$ARCH".AppImage
export DEPLOY_OPENGL=1
export DEPLOY_SDL=1
export DEPLOY_SYS_PYTHON=1
export OPTIMIZE_LAUNCH=1
@@ -40,7 +41,7 @@ fi
/usr/lib/libQt6Core.so* \
/usr/lib/libQt6Gui.so* \
/usr/lib/libQt6Network.so* \
/usr/lib/libudev.so*
/usr/lib/qt6/plugins/imageformats/libqwebp.so
# Turn AppDir into AppImage
./quick-sharun --make-appimage
+1 -1
View File
@@ -6,7 +6,7 @@ arch=('any')
url="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt"
license=('GPL-3.0')
depends=('python-requests' 'python-babel' 'python-evdev' 'python-pygame' 'python-orjson'
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-beautifulsoup4' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'jq' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' 'squashfs-tools' '7zip' 'python-dbus-fast')
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'jq' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'qt6-imageformats' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' 'squashfs-tools' '7zip' 'python-dbus-fast')
depends_aarch64=('muvm')
makedepends=('meson' 'ninja' 'vulkan-headers' 'gettext')
source=("git+https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt#tag=v$pkgver")
+2 -2
View File
@@ -6,7 +6,7 @@ arch=('any')
url="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt"
license=('GPL-3.0')
depends=('python-requests' 'python-babel' 'python-evdev' 'python-pygame' 'python-orjson'
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-beautifulsoup4' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'jq' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' 'squashfs-tools' '7zip' 'python-dbus-fast')
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'jq' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'qt6-imageformats' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' 'squashfs-tools' '7zip' 'python-dbus-fast')
depends_aarch64=('muvm')
makedepends=('meson' 'ninja' 'vulkan-headers' 'gettext')
source=("git+https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt.git")
@@ -18,7 +18,7 @@ pkgver() {
}
build() {
arch-meson PortProtonQt build
arch-meson PortProtonQt build -Dnightly=true
meson compile -C build
}
+4 -1
View File
@@ -39,11 +39,11 @@ Requires: python3-tqdm
Requires: python3-vdf
Requires: python3-pefile
Requires: python3-pillow
Requires: python3-beautifulsoup4
Requires: python3-rapidfuzz
Requires: python3-libarchive-c
Requires: perl-Image-ExifTool
Requires: qt6-qtsvg
Requires: qt6-qtimageformats
Requires: cabextract
Requires: gzip
Requires: unzip
@@ -97,6 +97,7 @@ git clone https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt.git
%build
cd %{oname}
%meson \
-Dnightly=true \
-Dpython_purelibdir=%{python3_sitelib} \
-Dudev_rulesdir=%{_udevrulesdir}
%meson_build
@@ -120,6 +121,8 @@ install -Dpm 0644 ./completions/_portprotonqt -t %{buildroot}%{zsh_completions_d
%{_datadir}/polkit-1/rules.d/ru.linux_gaming.PortProtonQt.rules
%{_datadir}/applications/ru.linux_gaming.PortProtonQt.desktop
%{_datadir}/portproton/scripts/
%{_datadir}/portproton/conf/
%{_datadir}/portproton/img/
%{bash_completions_dir}/portprotonqt
%{fish_completions_dir}/portprotonqt.fish
%{zsh_completions_dir}/_portprotonqt
+3 -1
View File
@@ -36,11 +36,11 @@ Requires: python3-tqdm
Requires: python3-vdf
Requires: python3-pefile
Requires: python3-pillow
Requires: python3-beautifulsoup4
Requires: python3-rapidfuzz
Requires: python3-libarchive-c
Requires: perl-Image-ExifTool
Requires: qt6-qtsvg
Requires: qt6-qtimageformats
Requires: cabextract
Requires: gzip
Requires: unzip
@@ -119,6 +119,8 @@ install -Dpm 0644 ./completions/_portprotonqt -t %{buildroot}%{zsh_completions_d
%{_datadir}/polkit-1/rules.d/ru.linux_gaming.PortProtonQt.rules
%{_datadir}/applications/ru.linux_gaming.PortProtonQt.desktop
%{_datadir}/portproton/scripts/
%{_datadir}/portproton/conf/
%{_datadir}/portproton/img/
%{bash_completions_dir}/portprotonqt
%{fish_completions_dir}/portprotonqt.fish
%{zsh_completions_dir}/_portprotonqt
+2 -2
View File
@@ -87,12 +87,12 @@ def bump_meson(path: Path, old: str, new: str) -> bool:
def bump_app_py(path: Path, old: str, new: str) -> bool:
"""
Update __app_version__ in app.py
Update APP_VERSION fallback in app.py
"""
if not path.exists():
return False
text = path.read_text(encoding='utf-8')
pattern = re.compile(r"(?m)^(\s*__app_version__\s*=\s*)\"" + re.escape(old) + r"\"$")
pattern = re.compile(r"(?m)^(\s*APP_VERSION\s*=\s*)\"" + re.escape(old) + r"\"$")
new_text, count = pattern.subn(lambda m: m.group(1) + f'"{new}"', text)
if count:
path.write_text(new_text, encoding='utf-8')
+41 -1
View File
@@ -679,7 +679,8 @@ def get_files_from_meson_build(meson_file_path):
'install_headers', # Header files installation
'install_man', # Manual pages installation
'install_symlink', # Symlinks installation
'install_emptydir' # Empty directories installation
'install_emptydir', # Empty directories installation
'configure_file', # Files generated and potentially installed
]
# Process each install function
@@ -706,6 +707,15 @@ def get_files_from_meson_build(meson_file_path):
return sorted(set(files)) # Use set to remove duplicates
def get_subdirs_from_meson_build(meson_file_path):
"""Extract install_subdir paths from meson.build."""
with open(meson_file_path, 'r', encoding='utf-8') as f:
content = f.read()
matches = re.findall(r"install_subdir\(\s*'([^']+)'", content, re.DOTALL)
return sorted(set(matches))
def check_syntax(repo_root: Path) -> tuple[list[str], list[str]]:
"""Check meson.build syntax and return (errors, warnings)."""
meson_files_list = list(repo_root.glob("**/meson.build"))
@@ -741,6 +751,28 @@ def check_files(repo_root: Path) -> list[str]:
return [f for f in dir_files if f not in meson_files]
def check_portproton_subdirs(repo_root: Path) -> list[str]:
"""Check if PortProton data directories are included in root meson.build."""
portproton_dir = repo_root / 'build-aux' / 'share' / 'portproton'
root_meson = repo_root / 'meson.build'
if not portproton_dir.exists() or not root_meson.exists():
return []
dir_entries = [
str(Path('build-aux') / 'share' / 'portproton' / entry.name)
for entry in portproton_dir.iterdir()
if entry.is_dir() and not entry.name.startswith('.')
]
meson_paths = get_files_from_meson_build(root_meson)
meson_paths.extend(get_subdirs_from_meson_build(root_meson))
return [
entry for entry in sorted(dir_entries)
if not any(path == entry or path.startswith(f"{entry}/") for path in meson_paths)
]
def main():
repo_root = Path(__file__).parent.parent
exit_code = 0
@@ -764,6 +796,7 @@ def main():
# Check files inclusion (only if syntax is OK)
if exit_code == 0:
missing_files = check_files(repo_root)
missing_subdirs = check_portproton_subdirs(repo_root)
if missing_files:
print("ERROR: The following files are present in the directory but missing from meson.build:")
@@ -772,6 +805,13 @@ def main():
print("\nPlease add these files to the install_data section in portprotonqt/meson.build")
exit_code = 1
if missing_subdirs:
print("ERROR: The following PortProton directories are missing from meson.build:")
for directory in missing_subdirs:
print(f" - {directory}")
print("\nPlease add these directories to install_subdir() in the root meson.build")
exit_code = 1
# Success message
if exit_code == 0:
if all_warnings:
+1 -1
View File
@@ -459,7 +459,7 @@ def main(args) -> int:
print(f"{idx}. In '{text}': typo '{err['word']}', suggestions: {', '.join(err['s'])}")
print("-----")
return 1 if has_err else 0
extract_strings(); compile_locales()
compile_locales()
return 0
if __name__ == "__main__":
+38 -6
View File
@@ -12,6 +12,20 @@ python3 = import('python').find_installation('python3')
conf = configuration_data()
conf.set('PYTHON', python3.full_path())
version_conf = configuration_data()
version_conf.set_quoted('APP_VERSION', meson.project_version())
version_conf.set_quoted('APP_COMMIT', '')
if get_option('nightly')
git = find_program('git', required: false)
if git.found()
git_commit = run_command(git, 'rev-parse', '--short', 'HEAD', check: false)
if git_commit.returncode() == 0
version_conf.set_quoted('APP_COMMIT', git_commit.stdout().strip())
endif
endif
endif
# Directories
prefix = get_option('prefix')
datadir = prefix / get_option('datadir')
@@ -25,6 +39,17 @@ pkgdatadir = pythondir / meson.project_name()
# C compiler for vk_gpu_info
cc = meson.get_compiler('c')
configured_version = configure_file(
input: 'portprotonqt/_version.py.in',
output: '_version.py',
configuration: version_conf,
)
install_data(
configured_version,
install_dir: pythondir / meson.project_name(),
)
# Install Python package
subdir('portprotonqt')
@@ -72,15 +97,22 @@ install_data(
)
# Install PortProton scripts
install_data(
'build-aux/share/portproton/scripts/functions_helper',
'build-aux/share/portproton/scripts/start.sh',
'build-aux/share/portproton/scripts/thanks',
'build-aux/share/portproton/scripts/var',
install_dir: datadir / 'portproton' / 'scripts',
install_subdir(
'build-aux/share/portproton/scripts',
install_dir: datadir / 'portproton',
install_mode: 'rwxr-xr-x',
)
install_subdir(
'build-aux/share/portproton/conf',
install_dir: datadir / 'portproton',
)
install_subdir(
'build-aux/share/portproton/img',
install_dir: datadir / 'portproton',
)
install_subdir(
'build-aux/share/portproton/scripts/portwine_db',
install_dir: datadir / 'portproton' / 'scripts',
+1
View File
@@ -2,3 +2,4 @@
option('python_purelibdir', type: 'string', value: '', description: 'Python pure library installation directory (overrides purelib)')
option('udev_rulesdir', type: 'string', value: '', description: 'Udev rules installation directory (overrides default)')
option('nightly', type: 'boolean', value: false, description: 'Include git commit in application version')
+2
View File
@@ -0,0 +1,2 @@
APP_VERSION = @APP_VERSION@
APP_COMMIT = @APP_COMMIT@
+14 -1
View File
@@ -1,12 +1,22 @@
import sys
import os
import importlib
import subprocess
import shutil
from logging import Logger
__app_id__ = "ru.linux_gaming.PortProtonQt"
__app_name__ = "PortProtonQt"
__app_version__ = "0.1.12"
try:
version_module = importlib.import_module("portprotonqt._version")
APP_COMMIT = version_module.APP_COMMIT
APP_VERSION = version_module.APP_VERSION
except ImportError:
APP_COMMIT = ""
APP_VERSION = "0.1.12"
__app_version__ = APP_VERSION
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication, QMenu, QSystemTrayIcon
@@ -36,6 +46,9 @@ from portprotonqt.cli import (
from portprotonqt.localization import _, get_steam_language
def get_version():
if APP_COMMIT:
return f"{__app_version__} ({APP_COMMIT})"
try:
commit = subprocess.check_output(
["git", "rev-parse", "--short", "HEAD"],
+6
View File
@@ -137,6 +137,8 @@ class ContextMenuManager:
return
menu = QMenu(file_explorer)
menu.setWindowFlags(menu.windowFlags() | Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint)
menu.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
menu.setStyleSheet(self.theme.CONTEXT_MENU_STYLE)
menu.setParent(file_explorer, Qt.WindowType.Popup) # Set transientParent for Wayland
@@ -362,6 +364,8 @@ class ContextMenuManager:
pos: The position (in widget coordinates) where the menu should appear.
"""
menu = QMenu(self.parent)
menu.setWindowFlags(menu.windowFlags() | Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint)
menu.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
menu.setStyleSheet(self.theme.CONTEXT_MENU_STYLE)
# For non-Steam games, check if exe exists
@@ -1261,6 +1265,8 @@ def show_themed_line_edit_context_menu(line_edit: QLineEdit, global_pos: QPoint,
action.setEnabled(enabled)
menu = QMenu(line_edit)
menu.setWindowFlags(menu.windowFlags() | Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint)
menu.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
current_theme = theme if theme is not None else getattr(line_edit, "theme", None)
if current_theme and hasattr(current_theme, "CONTEXT_MENU_STYLE"):
menu.setStyleSheet(current_theme.CONTEXT_MENU_STYLE)
+22 -1
View File
@@ -12,6 +12,7 @@ from portprotonqt.config import get_portproton_location
from portprotonqt.debug_utils.system_info import generate_system_info
from portprotonqt.debug_utils.log_processor import process_portproton_log
from portprotonqt.debug_utils.env_utils import get_portproton_runtime_env
logger = get_logger(__name__)
@@ -24,6 +25,7 @@ class DebugLogManager:
self.exe_path: str | None = None
self.start_command: list[str] | None = None
self.wine_output: list[str] = []
self.runtime_env: dict[str, str] | None = None
self.is_running = False
self.output_queue = queue.Queue()
self.output_thread = None
@@ -37,6 +39,7 @@ class DebugLogManager:
self.exe_path = exe_path
self.start_command = start_command
self.wine_output = []
self.runtime_env = None
self._stop_event.clear()
portproton_path = get_portproton_location()
@@ -96,6 +99,7 @@ class DebugLogManager:
def stop(self) -> str | None:
"""Stop game and save debug log with captured Wine output."""
self._capture_env_vars()
self._stop_event.set()
if self.is_running and self.process:
@@ -142,15 +146,32 @@ class DebugLogManager:
self.is_running = False
return False
self._capture_env_vars()
return True
def _capture_env_vars(self) -> None:
"""Keep runtime variables before PortProton removes var.log."""
env_vars = get_portproton_runtime_env()
if env_vars.get("PW_USE_RUNTIME") is not None:
self.runtime_env = env_vars
elif self.runtime_env is None and env_vars:
self.runtime_env = env_vars
def _save_log(self) -> str | None:
"""Save complete debug log to file."""
portproton_path = get_portproton_location()
if not portproton_path:
return None
system_info = generate_system_info(self.exe_path, self.start_command)
runtime_env = self.runtime_env
if runtime_env is None:
runtime_env = get_portproton_runtime_env()
system_info = generate_system_info(
self.exe_path,
self.start_command,
runtime_env
)
lines = [system_info]
+41 -28
View File
@@ -35,6 +35,35 @@ def get_file_content(file_path: str, default: str = "") -> str:
return default
def _parse_env_content(content: str) -> dict[str, str]:
env_vars: dict[str, str] = {}
for line in content.split('\n'):
line = line.strip()
if '=' in line:
key, val = line.split('=', 1)
env_vars[key.strip()] = val.strip()
return env_vars
def get_portproton_runtime_env() -> dict[str, str]:
"""Read runtime variables from active PortProton var.log only."""
user = os.getenv('USER', 'unknown')
var_log_path = f'/tmp/PortProton_{user}/var.log'
if not os.path.exists(var_log_path):
return {}
logger.debug("Reading runtime variables from %s", var_log_path)
try:
with open(var_log_path, encoding='utf-8', errors='ignore') as f:
env_vars = _parse_env_content(f.read())
logger.debug("Found %d runtime variables from var.log", len(env_vars))
return env_vars
except OSError as e:
logger.debug("Error reading var.log: %s", e)
return {}
def get_portproton_env(exe_path: str | None) -> dict[str, str]:
"""Get environment variables as exported by PortProton.
@@ -42,28 +71,10 @@ def get_portproton_env(exe_path: str | None) -> dict[str, str]:
1. /tmp/PortProton_$USER/var.log (runtime variables from active session)
2. var file + user.conf + .ppdb (static configuration)
"""
env_vars: dict[str, str] = {}
# Priority 1: Read from /tmp/PortProton_$USER/var.log (most authoritative)
user = os.getenv('USER', 'unknown')
var_log_path = f'/tmp/PortProton_{user}/var.log'
if os.path.exists(var_log_path):
logger.debug("Reading variables from %s", var_log_path)
try:
with open(var_log_path, encoding='utf-8', errors='ignore') as f:
content = f.read()
for line in content.split('\n'):
line = line.strip()
if '=' in line:
key, val = line.split('=', 1)
env_vars[key.strip()] = val.strip()
logger.debug("Found %d variables from var.log", len(env_vars))
return env_vars
except Exception as e:
logger.debug("Error reading var.log: %s", e)
env_vars = get_portproton_runtime_env()
if env_vars:
return env_vars
# Priority 2: Read from static configuration files
portproton_path = get_portproton_location()
@@ -122,18 +133,20 @@ def get_portproton_env(exe_path: str | None) -> dict[str, str]:
def get_runtime_status(
portproton_path: str,
exe_path: str | None = None,
start_cmd: list[str] | None = None
start_cmd: list[str] | None = None,
env_vars: dict[str, str] | None = None
) -> str:
"""Check if RUNTIME is enabled and detect Flatpak usage."""
env_vars = get_portproton_env(exe_path)
runtime_val = env_vars.get("PW_USE_RUNTIME", "1")
if os.getenv("FLATPAK_ID"):
return "FLATPAK in used"
elif runtime_val == "0":
env_vars = env_vars if env_vars is not None else get_portproton_env(exe_path)
runtime_val = env_vars.get("PW_USE_RUNTIME")
if runtime_val != "1":
return "RUNTIME is disabled"
else:
return "RUNTIME is enabled"
return "RUNTIME is enabled"
def get_vulkan_use_info(portproton_path: str, exe_path: str | None = None) -> str:
+3 -8
View File
@@ -353,7 +353,8 @@ def get_screen_info(portproton_path: str, exe_path: str | None = None) -> tuple[
def generate_system_info(
exe_path: str | None = None,
start_cmd: list[str] | None = None
start_cmd: list[str] | None = None,
runtime_env: dict[str, str] | None = None
) -> str:
"""Generate system information part of debug log."""
from portprotonqt.config import get_portproton_location
@@ -383,13 +384,7 @@ def generate_system_info(
lines.append(ppqt_version)
lines.append("-" * 61)
lines.append("Scripts version:")
scripts_ver_file = os.path.join(portproton_path, "data", "tmp", "scripts_ver")
scripts_version = get_file_content(scripts_ver_file, "Unknown")
lines.append(scripts_version)
lines.append("-" * 61)
lines.append(get_runtime_status(portproton_path, exe_path, start_cmd))
lines.append(get_runtime_status(portproton_path, exe_path, start_cmd, runtime_env))
lines.append("-" * 61)
if exe_path:
+35 -4
View File
@@ -21,6 +21,7 @@ from portprotonqt.detail_pages.widgets import (
create_back_button,
create_content_frame,
setup_adaptive_layout,
apply_adaptive_layout,
create_cover_frame,
create_protondb_badge,
create_steam_badge,
@@ -195,19 +196,17 @@ class DetailPageManager:
return size, size
def _create_game_badges(self, parent: QWidget, game_data: dict) -> list:
from portprotonqt.config import game_config
if self._is_compact_detail_layout():
return []
display_filter = game_config.get_display_filter()
game_source = str(game_data.get("game_source", "")).lower()
appid = game_data.get("appid", "")
name = game_data.get("name", "")
exec_line = game_data.get("exec_line", "")
steam_visible = game_source == "steam" and display_filter in ("all", "favorites")
portproton_visible = game_source == "portproton" and display_filter in ("all", "favorites")
steam_visible = game_source == "steam"
portproton_visible = game_source == "portproton"
badges = []
protondb_badge = self._create_protondb_badge(parent, game_data)
@@ -323,6 +322,19 @@ class DetailPageManager:
if has_data:
game_info_layout.addLayout(hltb_layout)
QTimer.singleShot(0, self._refresh_current_detail_page_layout)
def _refresh_current_detail_page_layout(self) -> None:
"""Refresh layout after asynchronous detail content changes."""
if not self._detail_page_active or not self._current_detail_page:
return
content_frame_layout = self._get_content_frame_layout(self._current_detail_page)
if content_frame_layout:
content_frame_layout.invalidate()
apply_adaptive_layout(self._current_detail_page, content_frame_layout)
self._current_detail_page.updateGeometry()
def _add_hltb_times(
self, game: GameEntry, hltb: HowLongToBeat, hltb_layout: QHBoxLayout
@@ -1111,11 +1123,30 @@ class DetailPageManager:
QTimer.singleShot(10, lambda: self.main_window.loadGames(force_load=True))
else:
QTimer.singleShot(10, lambda: self.main_window.game_library_manager.update_game_grid())
QTimer.singleShot(50, self._focus_first_library_card)
elif tab_index == 1 and hasattr(self.main_window, "autoInstallContainer"):
QTimer.singleShot(10, lambda: self.main_window.autoInstallContainer.updateGeometry())
if hasattr(self.main_window, "autoInstallContainerLayout"):
QTimer.singleShot(15, lambda: self.main_window.autoInstallContainerLayout.update())
def _focus_first_library_card(self) -> None:
container = getattr(self.main_window, "gamesListWidget", None)
if container is None:
return
cards = [
widget for widget in container.findChildren(QWidget)
if widget.__class__.__name__ == "GameCard"
]
if not cards:
return
cards.sort(key=lambda card: (card.pos().y(), card.pos().x()))
cards[0].setFocus(Qt.FocusReason.OtherFocusReason)
scroll_area = container.parentWidget()
while scroll_area and not isinstance(scroll_area, QScrollArea):
scroll_area = scroll_area.parentWidget()
if scroll_area:
scroll_area.ensureWidgetVisible(cards[0], 50, 50)
def _finalize_cleanup(self) -> None:
self.main_window.currentDetailPage = None
self.main_window.current_exec_line = None
+22 -19
View File
@@ -107,30 +107,33 @@ def setup_adaptive_layout(
"""Setup adaptive layout switching on resize."""
def on_detail_page_resize(event) -> None:
if detail_page.property("force_compact_detail_layout"):
content_frame_layout.setDirection(QBoxLayout.Direction.TopToBottom)
content_frame_layout.setAlignment(
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
)
QWidget.resizeEvent(detail_page, event)
return
required_width = _get_required_horizontal_width(content_frame_layout)
if detail_page.width() < required_width:
if content_frame_layout.direction() != QBoxLayout.Direction.TopToBottom:
content_frame_layout.setDirection(QBoxLayout.Direction.TopToBottom)
content_frame_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
else:
if content_frame_layout.direction() != QBoxLayout.Direction.LeftToRight:
content_frame_layout.setDirection(QBoxLayout.Direction.LeftToRight)
content_frame_layout.setAlignment(
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
)
apply_adaptive_layout(detail_page, content_frame_layout)
QWidget.resizeEvent(detail_page, event)
detail_page.resizeEvent = on_detail_page_resize
def apply_adaptive_layout(detail_page: QWidget, content_frame_layout: QBoxLayout) -> None:
"""Apply detail page adaptive layout for current size hints."""
if detail_page.property("force_compact_detail_layout"):
content_frame_layout.setDirection(QBoxLayout.Direction.TopToBottom)
content_frame_layout.setAlignment(
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
)
return
required_width = _get_required_horizontal_width(content_frame_layout)
if detail_page.width() < required_width:
if content_frame_layout.direction() != QBoxLayout.Direction.TopToBottom:
content_frame_layout.setDirection(QBoxLayout.Direction.TopToBottom)
content_frame_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
elif content_frame_layout.direction() != QBoxLayout.Direction.LeftToRight:
content_frame_layout.setDirection(QBoxLayout.Direction.LeftToRight)
content_frame_layout.setAlignment(
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
)
def _get_required_horizontal_width(content_frame_layout: QBoxLayout) -> int:
"""Calculate minimal width for horizontal content layout."""
item_count = content_frame_layout.count()
+6 -11
View File
@@ -583,6 +583,12 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
if setting['type'] == 'combo':
combo = QComboBox()
combo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
combo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
combo.addItems(setting['options'])
if setting['key'] == 'PW_PREFIX_NAME':
combo.setEditable(True)
@@ -887,17 +893,6 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
self.load_current_settings()
self.close()
def keyPressEvent(self, event):
"""Override key press event to handle combo box interaction properly."""
focused_widget = QApplication.focusWidget()
if (event.key() == Qt.Key.Key_Escape and
isinstance(focused_widget, QComboBox) and
focused_widget.view().isVisible()):
focused_widget.hidePopup()
self.advanced_table.setFocus()
return
super().keyPressEvent(event)
def closeEvent(self, event):
if hasattr(self, 'keyboard') and self.keyboard.isVisible():
self.keyboard.hide()
@@ -412,6 +412,12 @@ class GamescopeSettingsMixin:
def _create_gamescope_resolution_widget(self, target):
"""Create a resolution combo widget and bind it to width/height fields."""
widget = QComboBox()
widget.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
widget.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
widget.addItem(_("Default value"), '')
for resolution in self._get_gamescope_resolution_options():
widget.addItem(resolution, resolution)
@@ -523,6 +529,12 @@ class GamescopeSettingsMixin:
def _create_gamescope_value_widget(self, spec):
"""Create a Gamescope value widget."""
widget = QComboBox()
widget.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
widget.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
options = spec['options']
placeholder_text = _("Default value")
for option in options:
@@ -589,6 +601,12 @@ class GamescopeSettingsMixin:
self.gamescope_toggle_group = selector_group
self.gamescope_category_combo = QComboBox()
self.gamescope_category_combo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.gamescope_category_combo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.gamescope_category_combo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
selector_layout.addWidget(self.gamescope_category_combo)
+12
View File
@@ -443,6 +443,12 @@ class MangoHudSettingsMixin:
def _create_mangohud_value_widget(self, spec):
"""Create a MangoHud value widget."""
widget = QComboBox()
widget.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
widget.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
options = spec['options']
placeholder_text = _("Default value")
if spec['key'] == 'network':
@@ -549,6 +555,12 @@ class MangoHudSettingsMixin:
self.mangohud_toggle_group = selector_group
self.mangohud_category_combo = QComboBox()
self.mangohud_category_combo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.mangohud_category_combo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.mangohud_category_combo.addItems(list(MANGOHUD_TOGGLE_CATEGORIES.keys()))
self.mangohud_category_combo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
self.mangohud_category_combo.currentTextChanged.connect(self.on_mangohud_category_changed)
+5 -5
View File
@@ -94,15 +94,15 @@ class WinetricksDialog(DraggableDialog):
def update_winetricks(self):
"""Update the winetricks script."""
if not self.downloader.has_internet():
logger.warning("No internet connection, skipping winetricks update")
return
url = "https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks"
temp_path = os.path.join(self.tmp_path, "winetricks_temp")
try:
self.downloader.download(url, temp_path)
if not self.downloader.download(url, temp_path):
logger.warning("Failed to download external winetricks version")
if os.path.exists(temp_path):
os.remove(temp_path)
return
with open(temp_path) as f:
ext_content = f.read()
ext_ver_match = re.search(r'WINETRICKS_VERSION\s*=\s*[\'"]?([^\'"\s]+)', ext_content)
+120 -43
View File
@@ -5,6 +5,7 @@ import stat
import subprocess
import tempfile
import shlex
from typing import BinaryIO
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
@@ -12,6 +13,14 @@ logger = get_logger(__name__)
SYNC_HEADER = b'\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00'
SYNC_HEADER_MDF = b'\x80\xc0\x80\x80\x80\x80\x80\xc0\x80\x80\x80\x80'
ISO_9660_SIG = b'\x01\x43\x44\x30\x30\x31\x01\x00'
DISC_BLOCK_SIZES = (2048, 2336, 2352, 2368, 2448)
SVCD_SUB_HEADERS = (
b"\x00\x00\x08\x00\x00\x00\x08\x00",
b"\x00\x00\x09\x00\x00\x00\x09\x00",
b"\x00\x00\x88\x00\x00\x00\x88\x00",
b"\x00\x00\x89\x00\x00\x00\x89\x00",
)
UDF_SIGNATURES = (b"BEA01", b"BOOT2", b"CD001", b"CDW02", b"NSR02", b"NSR03", b"TEA01")
class DiscImageManager:
@@ -52,58 +61,126 @@ class DiscImageManager:
logger.error("Failed to read ISO 9660 signature for %s: %s", file_path, e)
return False
def _write_iso_from_mdf(self, mdf_path: str, iso_path: str) -> None:
"""Convert MDF to ISO using logic from test.py or legacy fallback."""
with open(mdf_path, "rb") as source:
source.seek(0)
h0 = source.read(12)
source.seek(2352)
h2352 = source.read(12)
def _is_svcd_sub_header(self, header: bytes) -> bool:
"""Return True if header matches known SVCD subheader bytes."""
return header[:8] in SVCD_SUB_HEADERS
if h0 == SYNC_HEADER:
if h2352 == SYNC_HEADER_MDF:
sector_size = 2448
elif h2352 == SYNC_HEADER:
sector_size = 2352
def _calculate_disc_layout(self, source: BinaryIO) -> tuple[int, int]:
"""Return pregap and block size using the iat detection rules."""
source.seek(0, os.SEEK_END)
image_size = source.tell()
cd_id_start = -1
cd_id_end = 0
header_size = 0
for offset in range(32768, image_size):
source.seek(offset)
header = source.read(12)
if header == SYNC_HEADER:
header_size = self._add_header_size(header_size, 16)
continue
if self._is_svcd_sub_header(header):
header_size = self._add_header_size(header_size, 8)
continue
if header[:5] in UDF_SIGNATURES:
if cd_id_start < 0:
cd_id_start = offset
else:
raise ValueError(f"Unknown SYNC format for {mdf_path}")
cd_id_end = offset
break
source.seek(0, os.SEEK_END)
num_sectors = source.tell() // sector_size
source.seek(0)
with open(iso_path, "wb") as target:
for _ in range(num_sectors):
sector_start = source.tell()
header = source.read(16)
if len(header) < 16:
break
mode = header[15]
data_offset = 24 if mode == 2 else 16
source.seek(sector_start + data_offset)
data = source.read(2048)
if len(data) < 2048:
break
target.write(data)
source.seek(sector_start + sector_size)
return
if cd_id_start < 0 or cd_id_end <= cd_id_start:
return self._detect_sector_layout(source)
# Legacy fallback
block_size = self._calculate_block_size(cd_id_end - cd_id_start)
pregap = cd_id_start - (block_size * 16) - header_size - 1
return max(pregap, 0), block_size
def _add_header_size(self, header_size: int, value: int) -> int:
"""Add a detected header size once, matching iat's mixed header logic."""
if header_size in (value, 24):
return header_size
return header_size + value
def _calculate_block_size(self, block_delta: int) -> int:
"""Return closest iat-supported block size for descriptor spacing."""
for block_size in DISC_BLOCK_SIZES[:-1]:
if block_delta % block_size == 0:
return block_size
return DISC_BLOCK_SIZES[-1]
def _detect_sector_layout(self, source: BinaryIO) -> tuple[int, int]:
"""Fallback sector layout detection for images without two descriptors."""
source.seek(0)
h0 = source.read(12)
source.seek(2352)
h2352 = source.read(12)
if h0 == SYNC_HEADER and h2352 == SYNC_HEADER_MDF:
return 0, 2448
if h0 == SYNC_HEADER:
return 0, 2352
return 0, 2352
def _write_sync_sector_data(self, target: BinaryIO, sector: bytes) -> None:
"""Write ISO user data from a sector with a sync header."""
mode = sector[15]
if mode == 0:
target.write(sector[16:2352])
elif mode == 1:
target.write(sector[16:2064])
elif mode == 2:
self._write_mode_two_sector_data(target, sector)
else:
raise ValueError(f"Unknown MDF sector mode {mode}")
def _write_mode_two_sector_data(self, target: BinaryIO, sector: bytes) -> None:
"""Write ISO user data from a Mode 2 sector."""
sub_header = sector[16:24]
if sub_header[:4] != sub_header[4:8]:
target.write(sector[16:2352])
return
if sub_header[2] & 0x20:
target.write(sector[24:2348])
return
target.write(sector[24:2072])
def _write_headerless_sector_data(self, target: BinaryIO, sector: bytes) -> bool:
"""Write ISO user data from a 2336-byte headerless sector."""
sub_header = sector[:8]
if sub_header[:4] != sub_header[4:8]:
return False
if self._is_svcd_sub_header(sub_header):
target.write(sector[8:2332])
else:
target.write(sector[8:2056])
return True
def _write_iso_from_mdf(self, mdf_path: str, iso_path: str) -> None:
"""Convert MDF to ISO using iat-compatible sector extraction."""
with open(mdf_path, "rb") as source, open(iso_path, "wb") as target:
sector_index = 0
while True:
sector = source.read(2352)
pregap, block_size = self._calculate_disc_layout(source)
image_size = os.path.getsize(mdf_path)
source.seek(pregap)
sector_index = pregap
while sector_index < image_size:
sector = source.read(block_size)
if not sector:
return
if len(sector) != 2352:
if len(sector) != block_size:
raise ValueError(f"Truncated MDF sector at {sector_index}")
mode = sector[15]
if mode == 1:
target.write(sector[16:2064])
elif mode == 2:
target.write(sector[24:2072])
if sector.startswith(SYNC_HEADER):
self._write_sync_sector_data(target, sector)
elif block_size == 2336 and not self._write_headerless_sector_data(target, sector):
sector_index += 1
source.seek(sector_index)
continue
elif block_size == 2048:
target.write(sector)
else:
raise ValueError(f"Unknown MDF sector mode {mode} at {sector_index}")
sector_index += 1
sector_index += 1
source.seek(sector_index)
continue
sector_index += block_size
def _convert_mdf_to_iso(self, mdf_path: str) -> str | None:
"""Convert raw 2352-byte sector MDF to temporary ISO."""
-54
View File
@@ -2,7 +2,6 @@ from PySide6.QtCore import QObject, Signal, QThread
import threading
import os
import requests
import socket
from pathlib import Path
from tqdm import tqdm
from collections.abc import Callable
@@ -65,54 +64,12 @@ class Downloader(QObject):
self._locks = {}
self._active_threads: list[QThread] = []
self._global_lock = threading.Lock()
self._has_internet = None
self.callback_requested.connect(self._run_callback)
def _run_callback(self, callback, result):
if callback:
callback(result)
def has_internet(self, timeout=3):
if self._has_internet is None:
errors = []
# Primary: Yandex
try:
socket.create_connection(("77.88.8.8", 53), timeout=timeout)
except Exception as e:
errors.append(f"Yandex DNS (77.88.8.8): {e}")
try:
socket.create_connection(("77.88.8.1", 53), timeout=timeout)
except Exception as e:
errors.append(f"Yandex DNS (77.88.8.1): {e}")
try:
requests.get("https://ya.ru", timeout=timeout)
except Exception as e:
errors.append(f"ya.ru: {e}")
# Fallback: Google (if Yandex failed)
if errors:
logger.debug("Yandex check failed, trying Google fallback")
try:
socket.create_connection(("8.8.8.8", 53), timeout=timeout)
except Exception as e:
errors.append(f"Google DNS (8.8.8.8): {e}")
try:
socket.create_connection(("8.8.4.4", 53), timeout=timeout)
except Exception as e:
errors.append(f"Google DNS (8.8.4.4): {e}")
try:
requests.get("https://www.google.com", timeout=timeout)
except Exception as e:
errors.append(f"google.com: {e}")
if errors:
logger.warning("Internet unavailable:\n" + "\n".join(errors))
self._has_internet = False
else:
self._has_internet = True
return self._has_internet
def _get_url_lock(self, url):
with self._global_lock:
if url not in self._locks:
@@ -219,9 +176,6 @@ class Downloader(QObject):
return results
def download(self, url, local_path, timeout=5):
if not self.has_internet():
logger.warning(f"No internet, skipping download {url}")
return None
with self._global_lock:
if url in self._last_error:
logger.warning(f"Previous download error for {url}, skipping")
@@ -259,14 +213,6 @@ class Downloader(QObject):
max_workers=None,
on_result: Callable[[str, str | None], None] | None = None,
):
if not self.has_internet():
logger.warning("No internet, skipping parallel download")
results = dict.fromkeys(urls)
if on_result:
for url, result in results.items():
on_result(url, result)
return results
filtered_urls = []
filtered_paths = []
emitted_urls = set()
+4 -25
View File
@@ -89,8 +89,8 @@ class GameCard(QFrame):
self.portproton_api = PortProtonAPI(self.downloader)
self.missing_executable_path = self._get_missing_executable_path()
self.steam_visible = (str(game_source).lower() == "steam" and self.display_filter in ("all", "favorites") and not self.economy_mode)
self.portproton_visible = (str(game_source).lower() == "portproton" and self.display_filter in ("all", "favorites") and not self.economy_mode)
self.steam_visible = (str(game_source).lower() == "steam" and not self.economy_mode)
self.portproton_visible = (str(game_source).lower() == "portproton" and not self.economy_mode)
self.base_extra_margin = 8 if self.list_layout else 20
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -486,8 +486,8 @@ class GameCard(QFrame):
self.display_filter = display_filter
self.economy_mode = ui_config.get_economy_mode()
self.steam_visible = (str(self.game_source).lower() == "steam" and self.display_filter in ("all", "favorites") and not self.economy_mode)
self.portproton_visible = (str(self.game_source).lower() == "portproton" and self.display_filter in ("all", "favorites") and not self.economy_mode)
self.steam_visible = (str(self.game_source).lower() == "steam" and not self.economy_mode)
self.portproton_visible = (str(self.game_source).lower() == "portproton" and not self.economy_mode)
protondb_visible = bool(self.getProtonDBText(self.protondb_tier)) and not self.economy_mode
anticheat_visible = bool(self.getAntiCheatText(self.anticheat_status)) and not self.economy_mode
@@ -775,24 +775,3 @@ class GameCard(QFrame):
except RuntimeError:
# Object already deleted
pass
def keyPressEvent(self, event):
if event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
game_data = {
"name": self.name,
"description": self.description,
"cover_path": self.cover_path,
"appid": self.appid,
"controller_support": self.controller_support,
"exec_line": self.exec_line,
"last_launch": self.last_launch,
"formatted_playtime": self.formatted_playtime,
"protondb_tier": self.protondb_tier,
"game_source": self.game_source,
"anticheat_status": self.anticheat_status,
"anticheat_slug": self.anticheat_slug,
}
self.select_callback(game_data)
else:
super().keyPressEvent(event)
+56 -181
View File
@@ -1,11 +1,9 @@
import orjson
import re
from dataclasses import dataclass, field
import time
from dataclasses import dataclass
from typing import Any
from difflib import SequenceMatcher
from threading import Thread
import requests
from bs4 import BeautifulSoup, Tag
from portprotonqt.config import proxy_config
from portprotonqt.time_utils import format_playtime
from portprotonqt.logger import get_logger
@@ -17,66 +15,22 @@ logger = get_logger(__name__)
@dataclass
class GameEntry:
"""Game information from HowLongToBeat."""
game_id: int = -1
game_name: str | None = None
main_story: float | None = None
main_extra: float | None = None
completionist: float | None = None
similarity: float = -1.0
raw_data: dict[str, Any] = field(default_factory=dict)
@dataclass
class SearchConfig:
"""Search configuration."""
api_key: str | None = None
search_url: str | None = None
class APIKeyExtractor:
"""Extract API key and search URL from site scripts."""
@staticmethod
def extract_from_script(script_content: str) -> SearchConfig:
config = SearchConfig()
config.api_key = APIKeyExtractor._extract_api_key(script_content)
config.search_url = APIKeyExtractor._extract_search_url(script_content, config.api_key)
return config
@staticmethod
def _extract_api_key(script_content: str) -> str | None:
user_id_pattern = r'users\s*:\s*{\s*id\s*:\s*"([^"]+)"'
matches = re.findall(user_id_pattern, script_content)
if matches:
return ''.join(matches)
concat_pattern = r'\/api\/\w+\/"(?:\.concat\("[^"]*"\))+'
matches = re.findall(concat_pattern, script_content)
if matches:
parts = str(matches).split('.concat')
cleaned_parts = [re.sub(r'["\(\)\[\]\']', '', part) for part in parts[1:]]
return ''.join(cleaned_parts)
return None
@staticmethod
def _extract_search_url(script_content: str, api_key: str | None) -> str | None:
if not api_key:
return None
pattern = re.compile(
r'fetch\(\s*["\'](\/api\/[^"\']*)["\']'
r'((?:\s*\.concat\(\s*["\']([^"\']*)["\']\s*\))+)'
r'\s*,',
re.DOTALL
)
for match in pattern.finditer(script_content):
endpoint = match.group(1)
concat_calls = match.group(2)
concat_strings = re.findall(r'\.concat\(\s*["\']([^"\']*)["\']\s*\)', concat_calls)
concatenated_str = ''.join(concat_strings)
if concatenated_str == api_key:
return endpoint
return None
token: str
hp_key: str
hp_val: str
class HTTPClient:
"""HTTP client for HowLongToBeat API."""
BASE_URL = 'https://howlongtobeat.com/'
SEARCH_URL = BASE_URL + "api/s/"
AUTH_URL = BASE_URL + "api/bleed/init"
SEARCH_URL = BASE_URL + "api/bleed"
def __init__(self, timeout: int = 60):
self.timeout = timeout
@@ -89,67 +43,55 @@ class HTTPClient:
if proxy_settings:
self.session.proxies.update(proxy_settings)
def get_search_config(self, parse_all_scripts: bool = False) -> SearchConfig | None:
def get_search_config(self) -> SearchConfig | None:
try:
response = self.session.get(self.BASE_URL, timeout=self.timeout)
response = self.session.get(
self.AUTH_URL,
params={"t": int(time.time() * 1000)},
timeout=self.timeout
)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
scripts = soup.find_all('script', src=True)
script_urls = []
for script in scripts:
if isinstance(script, Tag):
src = script.get('src')
if src is not None and isinstance(src, str):
if parse_all_scripts or '_app-' in src:
script_urls.append(src)
for script_url in script_urls:
full_url = self.BASE_URL + script_url
script_response = self.session.get(full_url, timeout=self.timeout)
if script_response.status_code == 200:
config = APIKeyExtractor.extract_from_script(script_response.text)
if config.api_key:
return config
except requests.RequestException:
pass
return None
data = response.json()
except (requests.RequestException, ValueError):
return None
if not data.get("token") or not data.get("hpKey") or not data.get("hpVal"):
return None
return SearchConfig(
token=data["token"],
hp_key=data["hpKey"],
hp_val=data["hpVal"]
)
def search_games(self, game_name: str, page: int = 1, config: SearchConfig | None = None) -> str | None:
if not config:
config = self.get_search_config()
if not config:
config = self.get_search_config(parse_all_scripts=True)
if not config or not config.api_key:
if not config:
return None
search_url = self.SEARCH_URL
if config.search_url:
search_url = self.BASE_URL + config.search_url.lstrip('/')
payload = self._build_search_payload(game_name, page, config)
headers = {
'content-type': 'application/json',
'accept': '*/*'
}
try:
response = self.session.post(
search_url + config.api_key,
headers=headers,
data=orjson.dumps(payload),
timeout=self.timeout
)
for retry in range(2):
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
}
try:
response = self.session.post(
self.SEARCH_URL,
headers=headers,
data=orjson.dumps(payload),
timeout=self.timeout
)
except requests.RequestException:
return None
if response.status_code == 200:
return response.text
except requests.RequestException:
pass
try:
response = self.session.post(
search_url,
headers=headers,
data=orjson.dumps(payload),
timeout=self.timeout
)
if response.status_code == 200:
return response.text
except requests.RequestException:
pass
if response.status_code != 403 or retry:
return None
config = self.get_search_config()
if not config:
return None
return None
def _build_search_payload(self, game_name: str, page: int, config: SearchConfig) -> dict[str, Any]:
@@ -171,8 +113,7 @@ class HTTPClient:
'genre': "",
"difficulty": ""
},
'rangeYear': {'max': "", 'min': ""},
'modifier': "" # Hardcoded to empty string for SearchModifiers.NONE
'rangeYear': {'max': "", 'min': ""}
},
'users': {'sortCategory': "postcount"},
'lists': {'sortCategory': "follows"},
@@ -181,42 +122,26 @@ class HTTPClient:
'randomizer': 0
},
'useCache': True,
'fields': ["game_id", "game_name", "comp_main", "comp_plus", "comp_100"] # Request only needed fields
'fields': ["comp_main", "comp_plus", "comp_100"]
}
if config.api_key:
payload['searchOptions']['users']['id'] = config.api_key
payload[config.hp_key] = config.hp_val
return payload
class ResultParser:
"""Search results parser."""
def __init__(self, search_query: str, minimum_similarity: float = 0.4, case_sensitive: bool = True):
self.search_query = search_query
self.minimum_similarity = minimum_similarity
self.case_sensitive = case_sensitive
self.search_numbers = self._extract_numbers(search_query)
def parse_results(self, json_response: str, target_game_id: int | None = None) -> list[GameEntry]:
def parse_results(self, json_response: str) -> list[GameEntry]:
try:
data = orjson.loads(json_response)
games = []
# Only process the first result
if data.get("data"):
game_data = data["data"][0]
game = self._parse_game_entry(game_data)
if target_game_id is not None:
if game.game_id == target_game_id:
games.append(game)
elif self.minimum_similarity == 0.0 or game.similarity >= self.minimum_similarity:
games.append(game)
games.append(self._parse_game_entry(game_data))
return games
except (orjson.JSONDecodeError, KeyError, IndexError):
return []
def _parse_game_entry(self, game_data: dict[str, Any]) -> GameEntry:
game = GameEntry()
game.game_id = game_data.get("game_id", -1)
game.game_name = game_data.get("game_name")
game.raw_data = game_data
time_fields = [
("comp_main", "main_story"),
("comp_plus", "main_extra"),
@@ -228,35 +153,8 @@ class ResultParser:
time_seconds = game_data[json_field]
time_hours = None if all_zero else round(time_seconds / 3600, 2)
setattr(game, attr_name, time_hours)
game.similarity = self._calculate_similarity(game)
return game
def _calculate_similarity(self, game: GameEntry) -> float:
return self._compare_strings(self.search_query, game.game_name)
def _compare_strings(self, a: str | None, b: str | None) -> float:
if not a or not b:
return 0.0
if self.case_sensitive:
similarity = SequenceMatcher(None, a, b).ratio()
else:
similarity = SequenceMatcher(None, a.lower(), b.lower()).ratio()
if self.search_numbers and not self._contains_numbers(b, self.search_numbers):
similarity -= 0.1
return max(0.0, similarity)
@staticmethod
def _extract_numbers(text: str) -> list[str]:
return [word for word in text.split() if word.isdigit()]
@staticmethod
def _contains_numbers(text: str, numbers: list[str]) -> bool:
if not numbers:
return True
cleaned_text = re.sub(r'([^\s\w]|_)+', '', text)
text_numbers = [word for word in cleaned_text.split() if word.isdigit()]
return any(num in text_numbers for num in numbers)
class HowLongToBeat(QObject):
"""Main class for HowLongToBeat API."""
@@ -273,15 +171,13 @@ class HowLongToBeat(QObject):
return self.cache_manager.load_text(f"hltb_{game_name}")
def _save_to_cache(self, game_name: str, json_response: str):
"""Save data to cache, storing only first game and required fields."""
"""Save data to cache, storing only first game times."""
try:
data = orjson.loads(json_response)
if data.get("data"):
first_game = data["data"][0]
simplified_data = {
"data": [{
"game_id": first_game.get("game_id", -1),
"game_name": first_game.get("game_name"),
"comp_main": first_game.get("comp_main", 0),
"comp_plus": first_game.get("comp_plus", 0),
"comp_100": first_game.get("comp_100", 0)
@@ -298,25 +194,8 @@ class HowLongToBeat(QObject):
cached_response = self._load_from_cache(game_name)
if cached_response:
try:
cached_data = orjson.loads(cached_response)
full_json = {
"data": [
{
"game_id": game["game_id"],
"game_name": game["game_name"],
"comp_main": game["comp_main"],
"comp_plus": game["comp_plus"],
"comp_100": game["comp_100"]
}
for game in cached_data.get("data", [])
]
}
parser = ResultParser(
game_name,
self.minimum_similarity,
case_sensitive
)
return parser.parse_results(orjson.dumps(full_json).decode('utf-8'))
parser = ResultParser()
return parser.parse_results(cached_response)
except orjson.JSONDecodeError:
pass
# If not in cache, make request
@@ -325,11 +204,7 @@ class HowLongToBeat(QObject):
return None
# Save only first game to cache
self._save_to_cache(game_name, json_response)
parser = ResultParser(
game_name,
self.minimum_similarity,
case_sensitive
)
parser = ResultParser()
return parser.parse_results(json_response)
def format_game_time(self, game_entry: GameEntry, time_field: str = "main_story") -> str | None:
+340 -255
View File
@@ -10,9 +10,10 @@ import pygame
from pygame._sdl2 import controller
from evdev import UInput, ecodes
from enum import Enum
from shiboken6 import isValid
from PySide6.QtWidgets import QWidget, QStackedWidget, QApplication, QScrollArea, QAbstractScrollArea, QLineEdit, QDialog, QMenu, QComboBox, QListView, QMessageBox, QListWidget, QTableWidget, QAbstractItemView, QSlider, QCheckBox, QPushButton
from PySide6.QtCore import Qt, QObject, QEvent, QPoint, Signal, Slot, QTimer, QThread
from PySide6.QtGui import QKeyEvent, QMouseEvent
from PySide6.QtGui import QKeySequence
from portprotonqt.logger import get_logger
from portprotonqt.image_utils import FullscreenDialog
from portprotonqt.custom_widgets import NavLabel, AutoSizeButton
@@ -176,7 +177,7 @@ class MouseEmulationThread(QThread):
class InputManager(QObject):
"""
Manages input from gamepads and keyboards for navigating the application interface.
Supports gamepad hotplugging, button and axis events, and keyboard event filtering
Supports gamepad hotplugging, button and axis events, and pygame keyboard events
for seamless UI interaction.
"""
# Signals for gamepad events
@@ -307,13 +308,16 @@ class InputManager(QObject):
self.dpad_moved.connect(self.handle_dpad_slot)
self.toggle_fullscreen.connect(self.handle_fullscreen_slot)
# Install keyboard event filter
# Install wheel event filter
app = QApplication.instance()
if app is not None:
app.installEventFilter(self)
# Initialize evdev + hotplug
# Initialize pygame input backend
self.init_gamepad()
self.pygame_event_timer = QTimer(self)
self.pygame_event_timer.timeout.connect(self._process_pygame_events)
self.pygame_event_timer.start(10)
def _async_enable_mouse_emulation(self):
"""Asynchronously enable mouse emulation to avoid blocking startup."""
@@ -2926,6 +2930,8 @@ class InputManager(QObject):
if code in (PAD_DPAD_X, PAD_DPAD_Y):
current_index = self._parent.stackedWidget.currentIndex()
if current_index in (0, 1):
if code == PAD_DPAD_Y and value < 0 and self._focus_tab_from_search(current_index):
return
container = self._parent.gamesListWidget if current_index == 0 else self._parent.autoInstallContainer
if container is None:
return
@@ -3138,18 +3144,18 @@ class InputManager(QObject):
scrollable = scrollable.parent()
return True
if event.type() in (QEvent.Type.KeyPress, QEvent.Type.KeyRelease):
key = self._qt_event_to_pygame_key(event)
if key is not None and event.type() == QEvent.Type.KeyPress:
return self._handle_pygame_key_press(key, self._qt_modifiers_to_pygame(event))
if key is not None:
return self._handle_pygame_key_release(key)
if event.type() == QEvent.Type.MouseButtonPress:
mouse_event = cast(QMouseEvent, event)
if mouse_event.button() == Qt.MouseButton.ExtraButton1:
# Handle ExtraButton1 as "back" action, similar to Escape
active_win = QApplication.activeWindow()
focused = QApplication.focusWidget()
if isinstance(focused, QLineEdit):
return False # Skip if in QLineEdit
if isinstance(active_win, QDialog):
active_win.reject()
return True
self._parent.goBackDetailPage(self._parent.currentDetailPage)
button_method = getattr(event, "button", None)
button = button_method() if callable(button_method) else None
if button == Qt.MouseButton.ExtraButton1:
self._handle_back_mouse_button()
return True
# Ensure obj is a QObject
@@ -3157,243 +3163,317 @@ class InputManager(QObject):
logger.debug(f"Skipping event filter for non-QObject: {type(obj).__name__}")
return False
# Handle key press and release events
if not isinstance(event, QKeyEvent):
return super().eventFilter(obj, event)
key = event.key()
modifiers = event.modifiers()
focused = QApplication.focusWidget()
active_win = QApplication.activeWindow()
# Handle key press events
if event.type() == QEvent.Type.KeyPress:
# Handle FileExplorer specific logic
if self.file_explorer:
# Handle drive buttons in FileExplorer
if key in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
if isinstance(focused, AutoSizeButton) and hasattr(self.file_explorer, 'drive_buttons') and focused in self.file_explorer.drive_buttons:
self.file_explorer.select_drive()
return True
elif isinstance(focused, QListWidget) and focused == self.file_explorer.file_list:
current_item = focused.currentItem()
if current_item:
selected = current_item.text()
full_path = os.path.join(self.file_explorer.current_path, selected)
if os.path.isdir(full_path):
if selected == "../":
self.file_explorer.previous_dir()
else:
self.file_explorer.current_path = os.path.normpath(full_path)
self.file_explorer.update_file_list()
elif not self.file_explorer.directory_only:
self.file_explorer.file_signal.file_selected.emit(os.path.normpath(full_path))
self.file_explorer.accept()
return True
else:
self._parent.activateFocusedWidget()
return True
# Handle FileExplorer navigation with right arrow key
if key == Qt.Key.Key_Right:
try:
if hasattr(self.file_explorer, 'drive_buttons') and self.file_explorer.drive_buttons:
if not isinstance(focused, AutoSizeButton) or focused not in self.file_explorer.drive_buttons:
self.file_explorer.drive_buttons[0].setFocus()
self.file_explorer.ensure_button_visible(self.file_explorer.drive_buttons[0])
else:
current_idx = self.file_explorer.drive_buttons.index(focused)
next_idx = min(current_idx + 1, len(self.file_explorer.drive_buttons) - 1)
self.file_explorer.drive_buttons[next_idx].setFocus()
self.file_explorer.ensure_button_visible(self.file_explorer.drive_buttons[next_idx])
return True
except Exception as e:
logger.error(f"Error handling right arrow in FileExplorer: {e}")
return True
# Handle Backspace for FileExplorer navigation
if key == Qt.Key.Key_Backspace:
self.file_explorer.previous_dir()
return True
# Handle QLineEdit cursor movement with Left/Right arrows
if isinstance(focused, QLineEdit) and key in (Qt.Key.Key_Left, Qt.Key.Key_Right):
if key == Qt.Key.Key_Left:
focused.cursorBackward(False, 1) # Move cursor left by one character
elif key == Qt.Key.Key_Right:
focused.cursorForward(False, 1) # Move cursor right by one character
return True # Consume the event to prevent further processing
# Allow text editing in editable combo boxes
if key == Qt.Key.Key_Backspace:
if isinstance(focused, QComboBox) and focused.isEditable():
return False
parent = focused.parentWidget() if focused else None
if isinstance(parent, QComboBox) and parent.isEditable():
return False
# Refresh game grid with F5
if key == Qt.Key.Key_F5:
self._parent.refreshGames()
return True
# Close application with Ctrl+Q
if key == Qt.Key.Key_Q and modifiers & Qt.KeyboardModifier.ControlModifier:
app.quit()
return True
# Handle Backspace for FileExplorer navigation (move to parent directory)
if key == Qt.Key.Key_Backspace and self.file_explorer:
self.file_explorer.previous_dir()
return True
# Close Dialogs with Escape
if key == Qt.Key.Key_Escape:
if isinstance(focused, QLineEdit):
return False
if isinstance(active_win, QDialog):
active_win.reject()
return True
# FullscreenDialog navigation
if isinstance(active_win, FullscreenDialog):
if key in (Qt.Key.Key_Escape, Qt.Key.Key_Return, Qt.Key.Key_Enter, Qt.Key.Key_Backspace):
active_win.close()
return True
elif key in (Qt.Key.Key_Left, Qt.Key.Key_Right):
# Navigate screenshots in FullscreenDialog
if key == Qt.Key.Key_Left:
active_win.show_prev()
elif key == Qt.Key.Key_Right:
active_win.show_next()
return True # Consume event to prevent tab switching
# Handle common UI elements like QMessageBox before tab switching
# Check if there's an active QMessageBox that should handle the arrow keys first
active = QApplication.activeWindow()
if isinstance(active, QMessageBox):
# Prevent tab switching when there's an active QMessageBox
# Let the default Qt behavior handle the QMessageBox focus navigation
if key in (Qt.Key.Key_Left, Qt.Key.Key_Right, Qt.Key.Key_Up, Qt.Key.Key_Down):
# Just continue to let the default processing handle the QMessageBox
pass # Allow the event to continue to the default processing
# Handle tab switching with Left/Right arrow keys when not in GameCard focus or QLineEdit or QTableWidget or AutoSizeButton
# Also skip if there's an active QMessageBox or other QDialog
active = QApplication.activeWindow()
if (key in (Qt.Key.Key_Left, Qt.Key.Key_Right) and
not isinstance(focused, GameCard | QLineEdit | QTableWidget | AutoSizeButton | QCheckBox) and
not self.file_explorer and
not isinstance(active, QMessageBox)):
if not isinstance(active, QDialog):
idx = self._parent.stackedWidget.currentIndex()
# Get only visible tab indices
visible_tab_indices = []
if hasattr(self._parent, 'tabButtons'):
for i, btn in self._parent.tabButtons.items():
if btn.isVisible():
visible_tab_indices.append(i)
visible_tab_indices.sort() # Ensure they're in order
if visible_tab_indices:
# Find current position in the visible tabs list
try:
current_visible_pos = visible_tab_indices.index(idx)
except ValueError:
# Current index is not visible, default to first visible
current_visible_pos = 0
if key == Qt.Key.Key_Left:
new_visible_pos = (current_visible_pos - 1) % len(visible_tab_indices)
new_idx = visible_tab_indices[new_visible_pos]
self._parent.switchTab(new_idx)
self._parent.tabButtons[new_idx].setFocus(Qt.FocusReason.OtherFocusReason)
return True
elif key == Qt.Key.Key_Right:
new_visible_pos = (current_visible_pos + 1) % len(visible_tab_indices)
new_idx = visible_tab_indices[new_visible_pos]
self._parent.switchTab(new_idx)
self._parent.tabButtons[new_idx].setFocus(Qt.FocusReason.OtherFocusReason)
return True
# Map arrow keys to D-pad press events for other contexts
if key in (Qt.Key.Key_Up, Qt.Key.Key_Down, Qt.Key.Key_Left, Qt.Key.Key_Right):
now = time.time()
dpad_code = None
dpad_value = 0
if key == Qt.Key.Key_Up:
dpad_code = PAD_DPAD_Y
dpad_value = -1
elif key == Qt.Key.Key_Down:
dpad_code = PAD_DPAD_Y
dpad_value = 1
elif key == Qt.Key.Key_Left:
dpad_code = PAD_DPAD_X
dpad_value = -1
elif key == Qt.Key.Key_Right:
dpad_code = PAD_DPAD_X
dpad_value = 1
if dpad_code is not None:
self.dpad_moved.emit(dpad_code, dpad_value, now)
return True
# Context menu for GameCard
if isinstance(focused, GameCard):
if key == Qt.Key.Key_F10 and modifiers & Qt.KeyboardModifier.ShiftModifier:
pos = QPoint(focused.width() // 2, focused.height() // 2)
focused._show_context_menu(pos)
return True
# General actions: Activate, Back, Add
if key in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
# Special handling for table widgets
if isinstance(focused, QTableWidget):
self.handle_table_confirm(focused)
return True
self._parent.activateFocusedWidget()
return True
elif key in (Qt.Key.Key_Escape, Qt.Key.Key_Backspace):
if isinstance(focused, QLineEdit):
return False
if isinstance(focused, QComboBox) and focused.isEditable():
return False
parent = focused.parentWidget() if focused else None
if isinstance(parent, QComboBox) and parent.isEditable():
return False
self._parent.goBackDetailPage(self._parent.currentDetailPage)
return True
elif key == Qt.Key.Key_E:
if isinstance(focused, QLineEdit):
return False
# Only open AddGameDialog if in library tab (index 0)
if self._parent.stackedWidget.currentIndex() == 0:
self._parent.openAddGameDialog()
return True
# Toggle fullscreen with F11
if key == Qt.Key.Key_F11 and not self._is_gamescope_session:
self.toggle_fullscreen.emit(not self._is_fullscreen)
return True
# Handle key release events for arrow keys
elif event.type() == QEvent.Type.KeyRelease:
if key in (Qt.Key.Key_Up, Qt.Key.Key_Down, Qt.Key.Key_Left, Qt.Key.Key_Right):
now = time.time()
dpad_code = None
if key in (Qt.Key.Key_Up, Qt.Key.Key_Down):
dpad_code = PAD_DPAD_Y
elif key in (Qt.Key.Key_Left, Qt.Key.Key_Right):
dpad_code = PAD_DPAD_X
if dpad_code is not None:
# Emit release event with value 0 to stop continuous movement
self.dpad_moved.emit(dpad_code, 0, now)
return True
return super().eventFilter(obj, event)
def _qt_event_to_pygame_key(self, event: QEvent) -> int | None:
native_key = self._native_scan_to_pygame_key(event)
if native_key is not None:
return native_key
text_method = getattr(event, "text", None)
text = text_method() if callable(text_method) else ""
text = text if isinstance(text, str) else ""
if text and text.isascii() and text.isprintable():
return pygame.key.key_code(text.lower())
key_method = getattr(event, "key", None)
key_value = key_method() if callable(key_method) else 0
key = key_value if isinstance(key_value, int) else 0
name = QKeySequence(key).toString()
if len(name) == 1 and name.isprintable():
return pygame.key.key_code(name.lower())
key_names = {
"Backspace": pygame.K_BACKSPACE,
"Down": pygame.K_DOWN,
"Enter": pygame.K_KP_ENTER,
"Esc": pygame.K_ESCAPE,
"F5": pygame.K_F5,
"F10": pygame.K_F10,
"F11": pygame.K_F11,
"Left": pygame.K_LEFT,
"Return": pygame.K_RETURN,
"Right": pygame.K_RIGHT,
"Up": pygame.K_UP,
}
return key_names.get(name)
def _native_scan_to_pygame_key(self, event: QEvent) -> int | None:
scan_method = getattr(event, "nativeScanCode", None)
scan_value = scan_method() if callable(scan_method) else 0
scan_code = scan_value if isinstance(scan_value, int) else 0
scan_keys = {
16: pygame.K_q,
18: pygame.K_e,
24: pygame.K_q,
26: pygame.K_e,
}
return scan_keys.get(scan_code)
def _qt_modifiers_to_pygame(self, event: QEvent) -> int:
modifiers_method = getattr(event, "modifiers", None)
modifiers = modifiers_method() if callable(modifiers_method) else None
pygame_modifiers = 0
if isinstance(modifiers, Qt.KeyboardModifier) and modifiers & Qt.KeyboardModifier.ControlModifier:
pygame_modifiers |= pygame.KMOD_CTRL
if isinstance(modifiers, Qt.KeyboardModifier) and modifiers & Qt.KeyboardModifier.ShiftModifier:
pygame_modifiers |= pygame.KMOD_SHIFT
return pygame_modifiers
def _handle_back_mouse_button(self) -> None:
active_win = QApplication.activeWindow()
focused = self._focused_widget()
if isinstance(focused, QLineEdit):
return
if isinstance(active_win, QDialog):
active_win.reject()
return
self._parent.goBackDetailPage(self._parent.currentDetailPage)
def _focused_widget(self) -> QWidget | None:
focused = QApplication.focusWidget()
if focused is None or not isValid(focused):
return None
return focused
def _activate_focused_widget(self, focused: QWidget | None) -> None:
if focused is None or not isValid(focused):
return
try:
self._parent.activateFocusedWidget()
except RuntimeError as e:
logger.debug("Focused widget was deleted before activation: %s", e)
def _handle_pygame_mouse_button(self, event: pygame.event.Event) -> None:
"""Handle mouse input received from the pygame event queue."""
if getattr(event, "button", None) != pygame.BUTTON_X1:
return
self._handle_back_mouse_button()
def _handle_pygame_key_event(self, event: pygame.event.Event) -> None:
"""Handle keyboard input received from the pygame event queue."""
key = getattr(event, "key", None)
if key is None:
return
if event.type == pygame.KEYDOWN:
self._handle_pygame_key_press(key, pygame.key.get_mods())
elif event.type == pygame.KEYUP:
self._handle_pygame_key_release(key)
def _handle_pygame_key_press(self, key: int, modifiers: int) -> bool:
if self._handle_pygame_system_key(key, modifiers):
return True
if self._handle_pygame_file_explorer_key(key):
return True
if self._handle_pygame_text_key(key):
return True
if self._handle_pygame_dialog_key(key):
return True
if self._handle_pygame_tab_key(key):
return True
if self._handle_pygame_arrow_press(key):
return True
return self._handle_pygame_action_key(key, modifiers)
def _handle_pygame_system_key(self, key: int, modifiers: int) -> bool:
if key == pygame.K_F5:
self._parent.refreshGames()
return True
if key == pygame.K_q and modifiers & pygame.KMOD_CTRL:
app = QApplication.instance()
if app is not None:
app.quit()
return True
if key == pygame.K_F11 and not self._is_gamescope_session:
self.toggle_fullscreen.emit(not self._is_fullscreen)
return True
return False
def _handle_pygame_file_explorer_key(self, key: int) -> bool:
file_explorer = self.file_explorer
if not file_explorer:
return False
if key in (pygame.K_RETURN, pygame.K_KP_ENTER):
self._activate_file_explorer_focus()
return True
if key == pygame.K_BACKSPACE:
file_explorer.previous_dir()
return True
return False
def _activate_file_explorer_focus(self) -> None:
file_explorer = self.file_explorer
if file_explorer is None:
return
focused = self._focused_widget()
if (
isinstance(focused, AutoSizeButton) and
hasattr(file_explorer, 'drive_buttons') and
focused in file_explorer.drive_buttons
):
file_explorer.select_drive()
return
if file_explorer.file_list.count() > 0:
self._activate_file_explorer_item(file_explorer.file_list)
return
self._activate_focused_widget(focused)
def _activate_file_explorer_item(self, focused: QListWidget) -> None:
file_explorer = self.file_explorer
if file_explorer is None:
return
current_item = focused.currentItem()
if current_item is None and focused.count() > 0:
focused.setCurrentRow(0)
current_item = focused.currentItem()
if not current_item:
return
selected = current_item.text()
full_path = os.path.join(file_explorer.current_path, selected)
if os.path.isdir(full_path):
if selected == "../":
file_explorer.previous_dir()
else:
file_explorer.current_path = os.path.normpath(full_path)
file_explorer.update_file_list()
elif not file_explorer.directory_only:
file_explorer.file_signal.file_selected.emit(os.path.normpath(full_path))
file_explorer.accept()
def _handle_pygame_text_key(self, key: int) -> bool:
focused = self._focused_widget()
if isinstance(focused, QLineEdit) and key in (pygame.K_LEFT, pygame.K_RIGHT):
if key == pygame.K_LEFT:
focused.cursorBackward(False, 1)
else:
focused.cursorForward(False, 1)
return True
return False
def _focused_editable_combo(self, focused: QWidget | None) -> bool:
if isinstance(focused, QComboBox) and focused.isEditable():
return True
parent = focused.parentWidget() if focused else None
return isinstance(parent, QComboBox) and parent.isEditable()
def _handle_pygame_dialog_key(self, key: int) -> bool:
active_win = QApplication.activeWindow()
focused = self._focused_widget()
if isinstance(active_win, FullscreenDialog):
return self._handle_pygame_fullscreen_dialog_key(active_win, key)
if key != pygame.K_ESCAPE:
return False
settings_dialog = self.settings_dialog
if settings_dialog is not None:
open_combo = self._get_open_settings_combo()
if open_combo:
open_combo.hidePopup()
settings_dialog.advanced_table.setFocus()
return True
if isinstance(focused, QLineEdit):
return False
if isinstance(active_win, QDialog):
active_win.reject()
return True
return False
def _handle_pygame_fullscreen_dialog_key(self, active_win: FullscreenDialog, key: int) -> bool:
if key in (pygame.K_ESCAPE, pygame.K_RETURN, pygame.K_KP_ENTER, pygame.K_BACKSPACE):
active_win.close()
return True
if key == pygame.K_LEFT:
active_win.show_prev()
return True
if key == pygame.K_RIGHT:
active_win.show_next()
return True
return False
def _handle_pygame_tab_key(self, key: int) -> bool:
if key not in (pygame.K_LEFT, pygame.K_RIGHT):
return False
focused = self._focused_widget()
active = QApplication.activeWindow()
if self.file_explorer or isinstance(active, QMessageBox | QDialog):
return False
if isinstance(focused, GameCard | QLineEdit | QTableWidget | AutoSizeButton | QCheckBox):
return False
return self._switch_visible_tab(-1 if key == pygame.K_LEFT else 1)
def _focus_tab_from_search(self, current_index: int) -> bool:
focused = self._focused_widget()
search_edit = (
getattr(self._parent, 'searchEdit', None)
if current_index == 0
else getattr(self._parent, 'autoInstallSearchLineEdit', None)
)
if focused is not search_edit:
return False
tab_button = self._parent.tabButtons.get(current_index)
if tab_button is None or not tab_button.isVisible():
return False
tab_button.setFocus(Qt.FocusReason.OtherFocusReason)
return True
def _switch_visible_tab(self, step: int) -> bool:
idx = self._parent.stackedWidget.currentIndex()
visible = [i for i, btn in self._parent.tabButtons.items() if btn.isVisible()]
visible.sort()
if not visible:
return False
try:
current_pos = visible.index(idx)
except ValueError:
current_pos = 0
new_idx = visible[(current_pos + step) % len(visible)]
self._parent.switchTab(new_idx)
self._parent.tabButtons[new_idx].setFocus(Qt.FocusReason.OtherFocusReason)
return True
def _handle_pygame_arrow_press(self, key: int) -> bool:
dpad = {
pygame.K_UP: (PAD_DPAD_Y, -1),
pygame.K_DOWN: (PAD_DPAD_Y, 1),
pygame.K_LEFT: (PAD_DPAD_X, -1),
pygame.K_RIGHT: (PAD_DPAD_X, 1),
}.get(key)
if dpad is None:
return False
self.dpad_moved.emit(dpad[0], dpad[1], time.time())
return True
def _handle_pygame_action_key(self, key: int, modifiers: int) -> bool:
focused = self._focused_widget()
if isinstance(focused, GameCard) and key == pygame.K_F10 and modifiers & pygame.KMOD_SHIFT:
pos = QPoint(focused.width() // 2, focused.height() // 2)
focused._show_context_menu(pos)
return True
if key in (pygame.K_RETURN, pygame.K_KP_ENTER):
if isinstance(focused, QTableWidget):
self.handle_table_confirm(focused)
else:
self._activate_focused_widget(focused)
return True
elif key in (pygame.K_ESCAPE, pygame.K_BACKSPACE):
return self._handle_pygame_back_key(focused)
elif key == pygame.K_e and not isinstance(focused, QLineEdit):
if self._parent.stackedWidget.currentIndex() == 0:
self._parent.openAddGameDialog()
return True
return False
def _handle_pygame_back_key(self, focused: QWidget | None) -> bool:
if isinstance(focused, QLineEdit) or self._focused_editable_combo(focused):
return False
self._parent.goBackDetailPage(self._parent.currentDetailPage)
return True
def _handle_pygame_key_release(self, key: int) -> bool:
if key in (pygame.K_UP, pygame.K_DOWN):
self.dpad_moved.emit(PAD_DPAD_Y, 0, time.time())
return True
elif key in (pygame.K_LEFT, pygame.K_RIGHT):
self.dpad_moved.emit(PAD_DPAD_X, 0, time.time())
return True
return False
def init_gamepad(self) -> None:
self._init_pygame_backend()
self.gamepad_hotplug.connect(self._on_gamepad_hotplug)
@@ -3563,12 +3643,15 @@ class InputManager(QObject):
return int(max(-PYGAME_AXIS_SCALE, min(PYGAME_AXIS_SCALE, axis_value)))
def _process_pygame_events(self) -> None:
"""Handle controller add/remove events from the SDL event queue."""
"""Handle SDL input events from the pygame event queue."""
if not self._pygame_ready or self._gamepad_polling_suspended:
return
event_types = (
pygame.CONTROLLERDEVICEADDED,
pygame.CONTROLLERDEVICEREMOVED,
pygame.KEYDOWN,
pygame.KEYUP,
pygame.MOUSEBUTTONDOWN,
)
for event in pygame.event.get(event_types):
if event.type == pygame.CONTROLLERDEVICEADDED:
@@ -3578,6 +3661,10 @@ class InputManager(QObject):
elif event.type == pygame.CONTROLLERDEVICEREMOVED:
if self.gamepad and getattr(event, "instance_id", None) == self.gamepad.instance_id:
self.gamepad_hotplug.emit('remove')
elif event.type in (pygame.KEYDOWN, pygame.KEYUP):
self._handle_pygame_key_event(event)
elif event.type == pygame.MOUSEBUTTONDOWN:
self._handle_pygame_mouse_button(event)
def _poll_button_events(self, gamepad: PygameGamepad, current_time: float) -> None:
"""Emit button changes using evdev-compatible codes."""
@@ -3692,10 +3779,6 @@ class InputManager(QObject):
if self._gamepad_polling_suspended:
time.sleep(0.1)
continue
try:
self._process_pygame_events()
except Exception as ex:
logger.error(f"Unexpected error in gamepad event handling: {ex}")
active_gamepad = self.gamepad
if not active_gamepad:
time.sleep(0.1)
@@ -3746,6 +3829,8 @@ class InputManager(QObject):
# Stop all timers
if hasattr(self, 'gamepad_check_timer'):
self.gamepad_check_timer.stop()
if hasattr(self, 'pygame_event_timer'):
self.pygame_event_timer.stop()
self.dpad_timer.stop()
self.nav_timer.stop()
+67
View File
@@ -1,4 +1,5 @@
import os
import signal
import shlex
import shutil
import subprocess
@@ -1696,6 +1697,12 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.wine_versions.append(version)
self.wine_versions.sort(key=version_sort_key)
self.wineCombo = QComboBox()
self.wineCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.wineCombo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.wineCombo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.wineCombo.addItems(self.wine_versions)
self.wineCombo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
@@ -1709,6 +1716,12 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.prefixes = sorted([d for d in os.listdir(prefixes_path) if os.path.isdir(os.path.join(prefixes_path, d))], key=prefix_sort_key) if os.path.exists(prefixes_path) else []
self.prefixCombo = QComboBox()
self.prefixCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.prefixCombo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.prefixCombo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.prefixCombo.addItems(self.prefixes)
self.prefixCombo.setEditable(True)
@@ -2164,6 +2177,12 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
scrollLayout.addWidget(genFrame)
self.timeDetailCombo = QComboBox()
self.timeDetailCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.timeDetailCombo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.timeDetailCombo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.time_keys = ["detailed", "brief"]
self.time_labels = [_("Detailed"), _("Brief")]
@@ -2183,6 +2202,12 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
genForm.addRow(self.timeDetailTitle, self.timeDetailCombo)
self.gamesSortCombo = QComboBox()
self.gamesSortCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.gamesSortCombo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.gamesSortCombo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.sort_keys = ["last_launch", "playtime", "alphabetical"]
self.sort_labels = [_("Last launch"), _("Playtime"), _("Alphabetical")]
@@ -2204,6 +2229,12 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.filter_keys = ["all", "steam", "portproton", "favorites"]
self.filter_labels = [_("All"), "Steam", "PortProton", _("Favorites")]
self.gamesDisplayCombo = QComboBox()
self.gamesDisplayCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.gamesDisplayCombo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.gamesDisplayCombo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.gamesDisplayCombo.addItems(self.filter_labels)
self.gamesDisplayCombo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
@@ -2223,6 +2254,12 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.badge_view_keys = ["detailed", "compact", "hidden"]
self.badge_view_labels = [_("Detailed"), _("Compact"), _("Hidden")]
self.badgeViewCombo = QComboBox()
self.badgeViewCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.badgeViewCombo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.badgeViewCombo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.badgeViewCombo.addItems(self.badge_view_labels)
self.badgeViewCombo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
@@ -2428,6 +2465,12 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
filtered_gpu_list = get_selectable_gpu_list()
if filtered_gpu_list:
self.gpuCombo = QComboBox()
self.gpuCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.gpuCombo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.gpuCombo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.gpuCombo.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.gpuCombo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
@@ -2753,6 +2796,12 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.themeTabHeaderLayout.addWidget(self.themeTabTitleLabel)
self.themesCombo = QComboBox()
self.themesCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.themesCombo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.themesCombo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
self.themesCombo.setObjectName("themeTabCombo")
self.themesCombo.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -2770,6 +2819,12 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.themeTabHeaderLayout.addWidget(self.themesCombo)
self.themeVariantCombo = QComboBox()
self.themeVariantCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.themeVariantCombo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.themeVariantCombo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
self.themeVariantCombo.setObjectName("themeVariantCombo")
self.themeVariantCombo.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -3411,6 +3466,17 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
def _has_running_game_process(self) -> bool:
return any(proc.poll() is None for proc in self.game_processes)
def _terminate_game_processes(self) -> None:
for proc in self.game_processes:
if proc.poll() is not None:
continue
try:
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
except ProcessLookupError:
continue
except OSError as e:
logger.warning("Failed to terminate game process group %s: %s", proc.pid, e)
def _run_portproton_stop_command(self) -> bool:
"""Run PortProton CLI stop command."""
if not self.start_sh:
@@ -3431,6 +3497,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
if not self._run_portproton_stop_command():
return False
self._terminate_game_processes()
self.game_processes = []
if hasattr(self, 'checkProcessTimer') and self.checkProcessTimer is not None:
self.checkProcessTimer.stop()
+41 -7
View File
@@ -31,6 +31,8 @@ logger = get_logger(__name__)
AUTOINSTALL_CACHE_DURATION = 3600 # 1 hour for autoinstall cache
HEAD_FAILURE_RETRY_DELAY = 60 # 1 minute cooldown for failed HEAD checks
HEAD_CACHE_DURATION = 24 * 60 * 60
HEAD_CACHE_NAME = "head_cache"
HEAD_CACHE_OLD_PATTERN = "head_*.json"
def _create_bootstrap_file_explorer_parent() -> tuple[QObject | None, Any]:
@@ -116,6 +118,7 @@ class PortProtonAPI:
self._head_positive_cache: set[str] = set()
self._head_negative_cache: set[str] = set()
self._head_failure_cache: dict[str, float] = {}
self._head_disk_cache_cleaned = False
self._pending_asset_notifier: QObject | None = None
self._pending_asset_batch_thread: QThread | None = None
@@ -124,6 +127,38 @@ class PortProtonAPI:
os.makedirs(game_dir, exist_ok=True)
return game_dir
def _load_head_cache_entry(self, cache_manager: CacheManager, cache_key: str) -> bool | None:
cached = cache_manager.load_json(HEAD_CACHE_NAME)
if not isinstance(cached, dict):
return None
entry = cached.get(cache_key)
if not isinstance(entry, dict):
return None
timestamp = entry.get("timestamp")
if not isinstance(timestamp, int | float):
return None
if time.time() - timestamp > HEAD_CACHE_DURATION:
return None
return entry.get("exists") is True
def _save_head_cache_entry(self, cache_manager: CacheManager, cache_key: str, exists: bool) -> None:
cached = cache_manager.load_json(HEAD_CACHE_NAME)
if not isinstance(cached, dict):
cached = {}
cached[cache_key] = {"exists": exists, "timestamp": time.time()}
cache_manager.save_json(HEAD_CACHE_NAME, cached)
self._remove_old_head_cache_files(cache_manager)
def _remove_old_head_cache_files(self, cache_manager: CacheManager) -> None:
if self._head_disk_cache_cleaned:
return
for cache_file in cache_manager.cache_dir.glob(HEAD_CACHE_OLD_PATTERN):
try:
cache_file.unlink()
except OSError as e:
logger.debug("Failed to remove old HEAD cache %s: %s", cache_file, e)
self._head_disk_cache_cleaned = True
def _check_file_exists(self, url: str, timeout: int = 5) -> bool:
if url in self._head_negative_cache:
return False
@@ -134,11 +169,10 @@ class PortProtonAPI:
return False
cache_manager = CacheManager()
cache_key = f"head_{hashlib.sha256(url.encode('utf-8')).hexdigest()}"
if cache_manager.is_fresh(cache_key, HEAD_CACHE_DURATION):
cached = cache_manager.load_json(cache_key)
if isinstance(cached, dict):
return cached.get("exists") is True
cache_key = hashlib.sha256(url.encode('utf-8')).hexdigest()
cached_exists = self._load_head_cache_entry(cache_manager, cache_key)
if cached_exists is not None:
return cached_exists
try:
session = get_requests_session()
@@ -147,13 +181,13 @@ class PortProtonAPI:
self._head_negative_cache.add(url)
self._head_positive_cache.discard(url)
self._head_failure_cache.pop(url, None)
cache_manager.save_json(cache_key, {"exists": False})
self._save_head_cache_entry(cache_manager, cache_key, False)
return False
response.raise_for_status()
if response.status_code == 200:
self._head_positive_cache.add(url)
self._head_failure_cache.pop(url, None)
cache_manager.save_json(cache_key, {"exists": True})
self._save_head_cache_entry(cache_manager, cache_key, True)
return True
return False
except requests.RequestException as e:
+2
View File
@@ -718,6 +718,8 @@ class MainWindowSystemTabMixin(_MainWindowTypingBase):
def _createSystemContextMenu(self) -> QMenu:
menu = QMenu(self)
menu.setWindowFlags(menu.windowFlags() | Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint)
menu.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
menu.setStyleSheet(self.theme.CONTEXT_MENU_STYLE)
menu.setParent(self, Qt.WindowType.Popup)
return menu
@@ -1401,6 +1401,8 @@ CONTEXT_MENU_STYLE = f"""
font-size: {font_size_a};
padding: 5px;
min-width: 150px;
border: {border_b} {color_a};
border-radius: {border_radius_a};
}}
QMenu::icon {{
margin-left: 15px;
@@ -8,6 +8,8 @@ CONTEXT_MENU_STYLE = f"""
font-size: {font_size_a};
padding: 5px;
min-width: 150px;
border: {border_b} {color_a};
border-radius: {border_radius_a};
}}
QMenu::icon {{
margin-left: 15px;
+1 -2
View File
@@ -24,9 +24,7 @@ classifiers = [
]
dependencies = [
"babel>=2.18.0",
"beautifulsoup4>=4.14.3",
"evdev>=1.9.3",
"icoextract>=0.2.0",
"libarchive-c>=5.3",
"orjson>=3.11.8",
"pillow>=12.2.0",
@@ -40,6 +38,7 @@ dependencies = [
"websocket-client>=1.9.0",
"dbus-fast>=4.0.4",
"pygame>=2.6.1",
"pefile>=2024.8.26",
]
[project.scripts]
Generated
+2 -35
View File
@@ -15,19 +15,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" },
]
[[package]]
name = "beautifulsoup4"
version = "4.14.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "soupsieve" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/c3/b0/1c6a16426d389813b48d95e26898aff79abbde42ad353958ad95cc8c9b21/beautifulsoup4-4.14.3.tar.gz", hash = "sha256:6292b1c5186d356bba669ef9f7f051757099565ad9ada5dd630bd9de5fa7fb86", size = 627737, upload-time = "2025-11-30T15:08:26.084Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/1a/39/47f9197bdd44df24d67ac8893641e16f386c984a0619ef2ee4c51fbbc019/beautifulsoup4-4.14.3-py3-none-any.whl", hash = "sha256:0918bfe44902e6ad8d57732ba310582e98da931428d231a5ecb9e7c703a735bb", size = 107721, upload-time = "2025-11-30T15:08:24.087Z" },
]
[[package]]
name = "certifi"
version = "2025.11.12"
@@ -207,15 +194,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e3/7f/a1a97644e39e7316d850784c642093c99df1290a460df4ede27659056834/filelock-3.20.1-py3-none-any.whl", hash = "sha256:15d9e9a67306188a44baa72f569d2bfd803076269365fdea0934385da4dc361a", size = 16666, upload-time = "2025-12-15T23:54:26.874Z" },
]
[[package]]
name = "icoextract"
version = "0.2.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pefile" },
]
sdist = { url = "https://files.pythonhosted.org/packages/cc/a9/4653791ae2356f981ea3597a1ace0d04fef622071209a4613bf56abd0264/icoextract-0.2.0.tar.gz", hash = "sha256:e7b4770c9a927a48ecfccc4ecd35afe477c2565a71449f92a95bdc92a0d10043", size = 10949, upload-time = "2025-06-03T04:17:37.464Z" }
[[package]]
name = "identify"
version = "2.6.15"
@@ -455,12 +433,11 @@ version = "0.1.12"
source = { editable = "." }
dependencies = [
{ name = "babel" },
{ name = "beautifulsoup4" },
{ name = "dbus-fast" },
{ name = "evdev" },
{ name = "icoextract" },
{ name = "libarchive-c" },
{ name = "orjson" },
{ name = "pefile" },
{ name = "pillow" },
{ name = "psutil" },
{ name = "pygame" },
@@ -483,12 +460,11 @@ dev = [
[package.metadata]
requires-dist = [
{ name = "babel", specifier = ">=2.18.0" },
{ name = "beautifulsoup4", specifier = ">=4.14.3" },
{ name = "dbus-fast", specifier = ">=4.0.4" },
{ name = "evdev", specifier = ">=1.9.3" },
{ name = "icoextract", specifier = ">=0.2.0" },
{ name = "libarchive-c", specifier = ">=5.3" },
{ name = "orjson", specifier = ">=3.11.8" },
{ name = "pefile", specifier = ">=2024.8.26" },
{ name = "pillow", specifier = ">=12.2.0" },
{ name = "psutil", specifier = ">=7.2.2" },
{ name = "pygame", specifier = ">=2.6.1" },
@@ -854,15 +830,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/fb/99/6e5ee21db2d6af84bbbd7d871d441dafeb069c6de5667b1aa49891a77c66/shiboken6-6.11.0-cp310-abi3-win_arm64.whl", hash = "sha256:3bd76cf56105ab2d62ecaff630366f11264f69b88d488f10f048da9a065781f4", size = 1783186, upload-time = "2026-03-23T12:47:11.832Z" },
]
[[package]]
name = "soupsieve"
version = "2.8.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/89/23/adf3796d740536d63a6fbda113d07e60c734b6ed5d3058d1e47fc0495e47/soupsieve-2.8.1.tar.gz", hash = "sha256:4cf733bc50fa805f5df4b8ef4740fc0e0fa6218cf3006269afd3f9d6d80fd350", size = 117856, upload-time = "2025-12-18T13:50:34.655Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/48/f3/b67d6ea49ca9154453b6d70b34ea22f3996b9fa55da105a79d8732227adc/soupsieve-2.8.1-py3-none-any.whl", hash = "sha256:a11fe2a6f3d76ab3cf2de04eb339c1be5b506a8a47f2ceb6d139803177f85434", size = 36710, upload-time = "2025-12-18T13:50:33.267Z" },
]
[[package]]
name = "tqdm"
version = "4.67.3"