Compare commits

...
Author SHA1 Message Date
Boria138 4dce7c9683 chore(settings): move download options from appearance
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 20:40:38 +05:00
Boria138 cdeb74fd10 feat: added disable runtime download settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 18:39:53 +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
23 changed files with 701 additions and 344 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
+3
View File
@@ -47,8 +47,10 @@
- Переработан трей
- Автоустановки теперь можно остановить
- Префиксы `DEFAULT`, `DOTNET` и `PROGRAMS` теперь всегда отображаются вверху списков префиксов
- Из лога удалена версия скриптов, так как скрипты теперь внутри PortProtonQt
### Fixed
- Исправлено определение `PW_USE_RUNTIME` в debug-логе
- SGDB теперь не пытается получить обложки для игр из автоустовок
- Оптимизирован предпросмотр изображений в файловом менеджере
- Исправлено зависание интерфейса при открытии раздела Bluetooth в системе без физического Bluetooth-адаптера
@@ -62,6 +64,7 @@
- `custom_data` теперь применяется сразу после добавления игры из автоустановок и редактирования ярлыка
- Исправлено управление геймпадом в диалоге выбора файла для загрузки PPDB
- Исправлен повторный вывод одинаковых Vulkan GPU в `vk_gpu_info`
- Исправлена работа клавиатурного управления при раскладке, отличной от английской
### Contributors
- @Dervart
@@ -1282,7 +1282,11 @@ init_wine_ver () {
}
pw_init_runtime () {
check_flatpak && export PW_USE_RUNTIME="0"
if [[ ! -f "${PW_WINELIB}/runtime/files/bin/vkcube" ]] \
|| [[ ! -f "${PW_WINELIB}/pressure-vessel/bin/pressure-vessel-wrap" ]]
then
export PW_USE_RUNTIME="0"
fi
if [[ "$PW_USE_RUNTIME" != "1" ]] \
|| [[ "$PW_WINE_USE" == "USE_SYSTEM_WINE" ]]
then
@@ -2515,7 +2519,7 @@ pw_enable_gamemode_basic () {
start_portproton () {
pw_check_and_download_plugins
if check_flatpak ; then
if [[ "${PW_DISABLE_RUNTIME_DOWNLOAD}" == "1" ]] ; then
try_remove_dir "${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}"
else
pw_check_and_download_runtime
@@ -4103,7 +4107,12 @@ gui_edit_db () {
if [[ $PW_WINE_USE =~ (PROTON_LG|WINE_LG) ]] || [[ $PW_VULKAN_USE == "0" ]] ; then
DISABLE_EDIT_DB_LIST+=" PW_USE_SUPPLIED_DXVK_VKD3D"
fi
check_flatpak && DISABLE_EDIT_DB_LIST+=" PW_USE_RUNTIME"
if [[ ! -f "${PW_WINELIB}/runtime/files/bin/vkcube" ]] \
|| [[ ! -f "${PW_WINELIB}/pressure-vessel/bin/pressure-vessel-wrap" ]]
then
DISABLE_EDIT_DB_LIST+=" PW_USE_RUNTIME"
fi
# GALLIUM NINE
[[ ! -f "${PW_TMPFS_PATH}/gallium_nine.tmp" ]] && DISABLE_EDIT_DB_LIST+=" PW_USE_GALLIUM_NINE"
@@ -37,6 +37,11 @@ if [[ -z "$PORT_DATA_PATH" ]] ; then
fi
fi
if [[ -f "$HOME/.config/PortProtonQt.conf" ]] \
&& grep "disable_runtime_download = True" "$HOME/.config/PortProtonQt.conf" ; then
export PW_DISABLE_RUNTIME_DOWNLOAD=1
fi
export PORT_SCRIPTS_PATH PORT_IMG_PATH PORT_DATA_PATH PORT_CONF_PATH
export PW_LOG_FILE="${PORT_DATA_PATH}/PortProton.log"
+39
View File
@@ -706,6 +706,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 +750,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 +795,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 +804,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__":
+13 -6
View File
@@ -72,15 +72,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
@@ -156,6 +156,7 @@ def main():
portproton_location = get_portproton_location()
if portproton_location:
os.environ["PORT_DATA_PATH"] = portproton_location
ui_config.get_disable_runtime_download()
# Check if running as Steam compatibility tool (STEAM_COMPAT=1).
is_steam_compat = os.environ.get("STEAM_COMPAT") == "1"
+48 -4
View File
@@ -11,6 +11,7 @@ from portprotonqt.logger import get_logger
logger = get_logger(__name__)
THEME_VARIANTS = ("dark", "light", "auto")
DOWNLOADS_SECTION = "Downloads"
def _get_theme_base_name(theme_name: str) -> str:
@@ -244,21 +245,64 @@ class UIConfig(BaseConfig):
def get_economy_mode(self) -> bool:
"""Get economy mode setting."""
return self._get_bool("economy_mode", False)
return self._get_download_bool("economy_mode", False)
def set_economy_mode(self, enabled: bool):
"""Set economy mode setting."""
validate_bool(enabled, "economy_mode")
self._save_value("economy_mode", enabled, "bool")
self._save_download_value("economy_mode", enabled)
def _get_download_bool(self, option: str, default: bool) -> bool:
cp = self._read_config()
if cp is None:
return self._save_download_value(option, default)
try:
if cp.has_option(DOWNLOADS_SECTION, option):
return cp.getboolean(DOWNLOADS_SECTION, option, fallback=default)
if cp.has_option(self._section, option):
return cp.getboolean(self._section, option, fallback=default)
except ValueError as e:
logger.warning("Error reading %s: %s", option, e)
return self._save_download_value(option, default)
except configparser.Error as e:
logger.warning("Error reading %s: %s", option, e)
return self._save_download_value(option, default)
return self._save_download_value(option, default)
def _save_download_value(self, option: str, value: bool) -> bool:
validate_bool(value, option)
cp = self._read_config() or configparser.ConfigParser()
if DOWNLOADS_SECTION not in cp:
cp[DOWNLOADS_SECTION] = {}
cp[DOWNLOADS_SECTION][option] = str(value)
if cp.has_section(self._section):
cp.remove_option(self._section, option)
self._save_config(cp)
return value
def get_download_wine_to_steam(self) -> bool:
"""Get Steam compatibility tools download setting."""
return self._get_bool("download_wine_to_steam", False)
return self._get_download_bool("download_wine_to_steam", False)
def set_download_wine_to_steam(self, enabled: bool) -> None:
"""Set Steam compatibility tools download setting."""
validate_bool(enabled, "download_wine_to_steam")
self._save_value("download_wine_to_steam", enabled, "bool")
self._save_download_value("download_wine_to_steam", enabled)
def get_disable_runtime_download(self) -> bool:
"""Get PortProton runtime download setting."""
default = bool(os.getenv("FLATPAK_ID"))
return self._get_download_bool("disable_runtime_download", default)
def set_disable_runtime_download(self, enabled: bool) -> None:
"""Set PortProton runtime download setting."""
if os.getenv("FLATPAK_ID"):
enabled = True
validate_bool(enabled, "disable_runtime_download")
self._save_download_value("disable_runtime_download", enabled)
def load_theme_metainfo(theme_name: str) -> dict:
+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:
+19
View File
@@ -1111,11 +1111,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
+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)
-21
View File
@@ -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)
+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()
+105 -5
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)
@@ -2327,6 +2364,23 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
hide_autoinstall_layout.addStretch()
uiForm.addRow(hide_autoinstall_layout)
disable_runtime_download_layout = None
if not os.getenv("FLATPAK_ID"):
self.disableRuntimeDownloadCheckBox = QCheckBox()
self.disableRuntimeDownloadCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
self.disableRuntimeDownloadCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.disableRuntimeDownloadTitle = QLabel(_("Disable PortProton runtime download"))
self.disableRuntimeDownloadTitle.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.disableRuntimeDownloadTitle.setStyleSheet(self.theme.SETTINGS_TITLE_CHECKBOX_STYLE)
self.disableRuntimeDownloadTitle.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.disableRuntimeDownloadCheckBox.setChecked(ui_config.get_disable_runtime_download())
disable_runtime_download_layout = QHBoxLayout()
disable_runtime_download_layout.setContentsMargins(0, 0, 0, 0)
disable_runtime_download_layout.addWidget(self.disableRuntimeDownloadCheckBox)
disable_runtime_download_layout.addWidget(self.disableRuntimeDownloadTitle)
disable_runtime_download_layout.addStretch()
download_wine_to_steam_layout = None
self.steamCompatCheckBox = QCheckBox()
self.steamCompatCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
self.steamCompatCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -2357,7 +2411,6 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
download_wine_to_steam_layout.addWidget(self.downloadWineToSteamCheckBox)
download_wine_to_steam_layout.addWidget(self.downloadWineToSteamTitle)
download_wine_to_steam_layout.addStretch()
uiForm.addRow(download_wine_to_steam_layout)
self.economyModeCheckBox = QCheckBox()
self.economyModeCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
@@ -2381,7 +2434,6 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
economy_mode_layout.addWidget(self.economyModeCheckBox)
economy_mode_layout.addWidget(self.economyModeTitle)
economy_mode_layout.addStretch()
uiForm.addRow(economy_mode_layout)
self.forceSystemDpiCheckBox = QCheckBox()
self.forceSystemDpiCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
@@ -2399,7 +2451,20 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
force_system_dpi_layout.addStretch()
uiForm.addRow(force_system_dpi_layout)
# 3. Gamepad Settings Section
# 3. Download Settings Section
downloadFrame, downloadForm = create_section(_("Download Settings"), self.theme)
downloadForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(downloadFrame)
if disable_runtime_download_layout is not None:
downloadForm.addRow(disable_runtime_download_layout)
if download_wine_to_steam_layout is not None:
downloadForm.addRow(download_wine_to_steam_layout)
downloadForm.addRow(economy_mode_layout)
# 4. Gamepad Settings Section
padFrame, padForm = create_section(_("Gamepad Settings"), self.theme)
padForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(padFrame)
@@ -2420,7 +2485,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
auto_fullscreen_layout.addStretch()
padForm.addRow(auto_fullscreen_layout)
# 4. Hardware Settings Section
# 5. Hardware Settings Section
hwFrame, hwForm = create_section(_("Hardware Settings"), self.theme)
hwForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(hwFrame)
@@ -2428,6 +2493,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)
@@ -2449,7 +2520,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
else:
hwForm.addRow(QLabel(_("No GPUs found")), QLabel(""))
# 5. Proxy Settings Section
# 6. Proxy Settings Section
proxyFrame, proxyForm = create_section(_("Proxy Settings"), self.theme)
proxyForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(proxyFrame)
@@ -2637,6 +2708,11 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
if hasattr(self, 'downloadWineToSteamCheckBox'):
ui_config.set_download_wine_to_steam(self.downloadWineToSteamCheckBox.isChecked())
if hasattr(self, 'disableRuntimeDownloadCheckBox'):
ui_config.set_disable_runtime_download(self.disableRuntimeDownloadCheckBox.isChecked())
else:
ui_config.get_disable_runtime_download()
# Save GPU selection to user.conf (only if the combo box exists)
if hasattr(self, 'gpuCombo'):
selected_gpu = self.gpuCombo.currentText()
@@ -2753,6 +2829,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 +2852,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 +3499,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 +3530,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()
+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;