feat: add UI sound system with theme-integrated sound effects #228
No files matched your search
@@ -388,6 +388,7 @@ tests/
|
||||
├── test_cli.py # normalize_launch_path, URL/resolution parsing
|
||||
├── test_debug_env_utils.py # Debug environment helpers, runtime variables
|
||||
├── test_input_manager.py # Gamepad input navigation and focus regressions
|
||||
├── test_sound_manager.py # UI sound playback, widget events, gamepad connection, theme sound files
|
||||
├── test_main_window.py # Main window data processing and callback regressions
|
||||
├── test_portproton_config.py # exec_line parsing, launcher tail, extensions
|
||||
├── test_portproton_api.py # PPDB API helpers, autoinstall localization fallback
|
||||
@@ -944,6 +945,6 @@ PortProtonQt/
|
||||
|
||||
---
|
||||
|
||||
**Last updated:** 2026-06-18
|
||||
**Last updated:** 2026-07-20
|
||||
**Version:** 1.2
|
||||
**Status:** Release
|
||||
@@ -434,3 +434,20 @@ proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Library General
|
||||
Public License instead of this License.
|
||||
|
||||
=====================================================================
|
||||
|
||||
===========================
|
||||
= Kenney Interface Sounds =
|
||||
===========================
|
||||
|
||||
Interface Sounds (1.0)
|
||||
|
||||
Created/distributed by Kenney (www.kenney.nl)
|
||||
|
||||
License: Creative Commons Zero, CC0
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
|
||||
This content is free to use in personal, educational and commercial projects.
|
||||
|
||||
Support us by crediting Kenney or www.kenney.nl (this is not mandatory)
|
||||
@@ -68,6 +68,8 @@ PortProtonQt uses code and dependencies from the following projects:
|
||||
- [iat](https://sourceforge.net/projects/iat.berlios) — library for converting mdf and nrg to iso, GPLv3 license.
|
||||
- [pyte](https://github.com/selectel/pyte) — ANSI escape code parser, [LGPLv3](https://github.com/selectel/pyte?tab=LGPL-3.0-1-ov-file) license.
|
||||
- [gjs-osk](https://github.com/Vishram1123/gjs-osk) — base for virtual keyboard layout data, GPLv3 license.
|
||||
- [Kenney Interface Sounds](https://kenney.nl/assets/interface-sounds) — UI feedback sound effects, [CC0](https://creativecommons.org/publicdomain/zero/1.0/) license.
|
||||
- [Modern Minimal UI Sounds](https://github.com/cadecomposer/modern-minimal-ui-sounds) — gamepad connection sound, [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) license.
|
||||
|
||||
See the [LICENSE](LICENSE) file for the full text of the licenses.
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
- [Recoloring SVG Icons](#recoloring-svg-icons)
|
||||
- [AutoSizeButton State Recoloring](#autosizebutton-state-recoloring)
|
||||
- [Non-Inherited Icon Colors](#non-inherited-icon-colors)
|
||||
- [Sound Effects](#sound-effects-optional)
|
||||
|
||||
---
|
||||
|
||||
@@ -78,6 +79,7 @@ my_custom_theme/
|
||||
├── metainfo.ini
|
||||
├── fonts/
|
||||
├── images/
|
||||
├── sounds/
|
||||
└── styles/
|
||||
├── __init__.py # This empty file makes the directory a Python package
|
||||
├── constants.py
|
||||
@@ -142,7 +144,7 @@ THEME_INHERITS = "classic"
|
||||
|
||||
If `THEME_INHERITS` is not defined, the theme inherits styles from `standart`.
|
||||
|
||||
Fonts, icons, and images also follow the inheritance chain — the first match found walking from child to `standart` wins. If your theme has a `fonts/` directory, it takes priority over the parent's. If it doesn't, the parent's fonts are loaded. Screenshots are the exception — they are loaded only from the current theme, not inherited.
|
||||
Fonts, icons, images, and sounds also follow the inheritance chain — the first match found walking from child to `standart` wins. If your theme has a `fonts/` directory, it takes priority over the parent's. Missing sound events fall back individually to the parent theme. Screenshots are the exception — they are loaded only from the current theme, not inherited.
|
||||
|
||||
### How Inheritance Works
|
||||
|
||||
@@ -742,3 +744,32 @@ When no `ICON_COLORS` entry matches an `AutoSizeButton` state, the button falls
|
||||
`ICON_COLORS` is not inherited from parent themes. If a child theme needs SVG recoloring, define its own `ICON_COLORS` dictionary in that theme.
|
||||
|
||||
---
|
||||
|
||||
## Sound Effects (optional)
|
||||
|
||||
Place UI sound effects in the theme's `sounds/` directory. File names must match an event name; do not add numeric suffixes such as `_001`:
|
||||
|
||||
| Event | Used for |
|
||||
|---|---|
|
||||
| `navigate` | Moving focus between UI items |
|
||||
| `click` | Pressing buttons and clickable labels |
|
||||
| `confirm` | Confirming an action |
|
||||
| `back` | Returning or closing with the Back action |
|
||||
| `toggle` | Changing a checkbox or toggle |
|
||||
| `open` | Opening pages, dialogs, and menus |
|
||||
| `close` | Closing UI elements |
|
||||
| `error` | Error feedback |
|
||||
| `notification` | Notifications |
|
||||
| `keyboard_key` | Virtual keyboard input |
|
||||
| `scroll` | Scrolling feedback |
|
||||
| `tab_switch` | Switching application tabs |
|
||||
| `game_launch` | Successful game process launch |
|
||||
| `gamepad_connect` | Connecting a gamepad |
|
||||
|
||||
For example, use `sounds/navigate.ogg` or `sounds/navigate.wav`. Supported extensions, in lookup order, are `.ogg`, `.oga`, `.wav`, `.mp3`, `.flac`, `.opus`, `.m4a`, `.aac`, and `.webm`. Availability of a codec at playback time depends on the Qt Multimedia backend installed on the system.
|
||||
|
||||
Sounds are inherited per event. A child theme can override only `navigate` and continue using every other sound from its parent. When more than one supported extension exists for the same event in one theme, the first extension in the list above is used.
|
||||
|
||||
Theme validation checks the extension, file size, and format signature before a sound is loaded. Sound files larger than 20 MiB, symlinks, files outside the theme directory, and files whose content does not match their extension are rejected. Include the license and attribution required by every sound asset distributed with a theme.
|
||||
|
||||
---
|
||||
@@ -26,6 +26,7 @@
|
||||
- [Перекраска SVG-иконок](#перекраска-svg-иконок)
|
||||
- [Перекраска состояний AutoSizeButton](#перекраска-состояний-autosizebutton)
|
||||
- [Ненаследуемые цвета иконок](#ненаследуемые-цвета-иконок)
|
||||
- [Звуковые эффекты](#звуковые-эффекты-опционально)
|
||||
|
||||
---
|
||||
|
||||
@@ -78,6 +79,7 @@ my_custom_theme/
|
||||
├── metainfo.ini
|
||||
├── fonts/
|
||||
├── images/
|
||||
├── sounds/
|
||||
└── styles/
|
||||
├── __init__.py # Этот пустой файл делает директорию Python-пакетом
|
||||
├── constants.py
|
||||
@@ -142,7 +144,7 @@ THEME_INHERITS = "classic"
|
||||
|
||||
Если `THEME_INHERITS` не указан, тема наследует стили от `standart`.
|
||||
|
||||
Шрифты, иконки и изображения также следуют цепочке наследования — побеждает первое совпадение при обходе от дочерней темы до `standart`. Если в вашей теме есть директория `fonts/`, она имеет приоритет над родительской. Если нет — загружаются шрифты родителя. Скриншоты — исключение: загружаются только из текущей темы, не наследуются.
|
||||
Шрифты, иконки, изображения и звуки также следуют цепочке наследования — побеждает первое совпадение при обходе от дочерней темы до `standart`. Если в вашей теме есть директория `fonts/`, она имеет приоритет над родительской. Отсутствующие звуковые события по отдельности загружаются из родительской темы. Скриншоты — исключение: загружаются только из текущей темы, не наследуются.
|
||||
|
||||
### Как работает наследование
|
||||
|
||||
@@ -742,3 +744,32 @@ ICON_COLORS = {
|
||||
`ICON_COLORS` не наследуется от родительских тем. Если дочерней теме нужна перекраска SVG, задайте собственный словарь `ICON_COLORS` в этой теме.
|
||||
|
||||
---
|
||||
|
||||
## Звуковые эффекты (опционально)
|
||||
|
||||
Поместите звуковые эффекты интерфейса в директорию `sounds/` темы. Имя файла должно совпадать с именем события; не добавляйте числовые суффиксы наподобие `_001`:
|
||||
|
||||
| Событие | Назначение |
|
||||
|---|---|
|
||||
| `navigate` | Перемещение фокуса между элементами интерфейса |
|
||||
| `click` | Нажатие кнопок и кликабельных меток |
|
||||
| `confirm` | Подтверждение действия |
|
||||
| `back` | Возврат или закрытие действием Back |
|
||||
| `toggle` | Изменение флажка или переключателя |
|
||||
| `open` | Открытие страниц, диалогов и меню |
|
||||
| `close` | Закрытие элементов интерфейса |
|
||||
| `error` | Сообщение об ошибке |
|
||||
| `notification` | Уведомления |
|
||||
| `keyboard_key` | Ввод с виртуальной клавиатуры |
|
||||
| `scroll` | Обратная связь при прокрутке |
|
||||
| `tab_switch` | Переключение вкладок приложения |
|
||||
| `game_launch` | Успешный запуск процесса игры |
|
||||
| `gamepad_connect` | Подключение геймпада |
|
||||
|
||||
Например, используйте `sounds/navigate.ogg` или `sounds/navigate.wav`. Поддерживаемые расширения в порядке поиска: `.ogg`, `.oga`, `.wav`, `.mp3`, `.flac`, `.opus`, `.m4a`, `.aac` и `.webm`. Доступность кодека при воспроизведении зависит от установленного в системе backend Qt Multimedia.
|
||||
|
||||
Звуки наследуются отдельно для каждого события. Дочерняя тема может переопределить только `navigate`, продолжая использовать остальные звуки родительской темы. Если в одной теме для события есть несколько поддерживаемых расширений, используется первое расширение из списка выше.
|
||||
|
||||
При проверке темы проверяются расширение, размер и сигнатура формата каждого звука. Файлы размером более 20 МиБ, символические ссылки, файлы за пределами директории темы и файлы, содержимое которых не соответствует расширению, отклоняются. Добавляйте лицензию и требуемую атрибуцию для каждого звукового ресурса, распространяемого вместе с темой.
|
||||
|
||||
---
|
||||
@@ -446,6 +446,15 @@ class UIConfig(BaseConfig):
|
||||
validate_bool(enabled, "enable_theme_store")
|
||||
self._save_value("enable_theme_store", enabled, "bool")
|
||||
|
||||
def get_sounds_enabled(self) -> bool:
|
||||
"""Get UI sounds enabled setting."""
|
||||
return self._get_bool("sounds_enabled", True)
|
||||
|
||||
def set_sounds_enabled(self, enabled: bool):
|
||||
"""Set UI sounds enabled setting."""
|
||||
validate_bool(enabled, "sounds_enabled")
|
||||
self._save_value("sounds_enabled", enabled, "bool")
|
||||
|
||||
|
||||
def load_theme_metainfo(theme_name: str) -> dict:
|
||||
"""Load theme metadata from metainfo.ini."""
|
||||
|
||||
@@ -72,6 +72,7 @@ def create_back_button(
|
||||
back_button = AutoSizeButton(_("Back"), icon=theme_manager.get_icon("back", as_path=True))
|
||||
back_button.setFixedWidth(100)
|
||||
back_button.setStyleSheet(theme.ADDGAME_BACK_BUTTON_STYLE)
|
||||
back_button.setProperty("sound_event", "back")
|
||||
back_button.clicked.connect(on_click)
|
||||
parent_layout.addWidget(back_button, alignment=Qt.AlignmentFlag.AlignLeft)
|
||||
return back_button
|
||||
|
||||
@@ -15,6 +15,7 @@ from PySide6.QtGui import (
|
||||
)
|
||||
from PySide6.QtCore import Signal, Property, Qt, QUrl, QTimer, QSize
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QFrame,
|
||||
QGraphicsDropShadowEffect,
|
||||
QGraphicsOpacityEffect,
|
||||
@@ -958,6 +959,15 @@ class GameCard(QFrame):
|
||||
super().leaveEvent(event)
|
||||
|
||||
def focusInEvent(self, event):
|
||||
if (
|
||||
QApplication.activeWindow() is not None
|
||||
and event.reason() not in (
|
||||
Qt.FocusReason.ActiveWindowFocusReason,
|
||||
Qt.FocusReason.MouseFocusReason,
|
||||
)
|
||||
):
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
SoundManager().play("navigate")
|
||||
self.animations.handle_focus_in_event()
|
||||
super().focusInEvent(event)
|
||||
|
||||
|
||||
@@ -540,7 +540,7 @@ class GameLibraryManager:
|
||||
for card in self.gamesListWidget.findChildren(GameCard):
|
||||
if card.isVisible() and card.isEnabled():
|
||||
self._focus_first_card_after_update = False
|
||||
card.setFocus(Qt.FocusReason.OtherFocusReason)
|
||||
card.setFocus(Qt.FocusReason.ActiveWindowFocusReason)
|
||||
if self.gamesScrollArea is not None:
|
||||
self.gamesScrollArea.ensureWidgetVisible(card, 50, 50)
|
||||
return
|
||||
|
||||
@@ -9,6 +9,7 @@ from PySide6.QtWidgets import QWidget, QStackedWidget, QApplication, QScrollArea
|
||||
from PySide6.QtCore import Qt, QObject, QEvent, QPoint, Signal, Slot, QTimer, QThread
|
||||
from PySide6.QtGui import QKeySequence
|
||||
from portprotonqt.logger import get_logger
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
from portprotonqt.image_utils import FullscreenDialog
|
||||
from portprotonqt.custom_widgets import NavLabel, AutoSizeButton
|
||||
from portprotonqt.game_card import GameCard
|
||||
@@ -912,11 +913,13 @@ class InputManager(QObject):
|
||||
if current_action not in actions:
|
||||
target_index = 0 if direction_down else len(actions) - 1
|
||||
menu.setActiveAction(actions[target_index])
|
||||
SoundManager().play("navigate")
|
||||
return
|
||||
current_index = actions.index(current_action)
|
||||
step = 1 if direction_down else -1
|
||||
next_index = (current_index + step) % len(actions)
|
||||
menu.setActiveAction(actions[next_index])
|
||||
SoundManager().play("navigate")
|
||||
|
||||
# TABLE NAVIGATION METHODS
|
||||
def handle_table_navigation(self, table: QTableWidget, code: int, value: int):
|
||||
@@ -2779,12 +2782,16 @@ class InputManager(QObject):
|
||||
system_action = getattr(self._parent, "handleSystemTableGamepadAction", None)
|
||||
if callable(system_action):
|
||||
if button_code in BUTTONS['confirm'] and system_action(focused, "confirm"):
|
||||
SoundManager().play("confirm")
|
||||
return
|
||||
if button_code in BUTTONS['back'] and system_action(focused, "back"):
|
||||
SoundManager().play("back")
|
||||
return
|
||||
if button_code in BUTTONS['prev_dir'] and system_action(focused, "prev_dir"):
|
||||
SoundManager().play("click")
|
||||
return
|
||||
if button_code in BUTTONS['add_game'] and system_action(focused, "add_game"):
|
||||
SoundManager().play("click")
|
||||
return
|
||||
|
||||
system_quick_action = getattr(self._parent, "handleSystemGamepadAction", None)
|
||||
@@ -2793,12 +2800,16 @@ class InputManager(QObject):
|
||||
and button_code in BUTTONS['add_game']
|
||||
and system_quick_action("add_game")
|
||||
):
|
||||
SoundManager().play("open")
|
||||
return
|
||||
|
||||
# Standard navigation
|
||||
if button_code in BUTTONS['confirm']:
|
||||
if not isinstance(focused, GameCard):
|
||||
SoundManager().play_widget_sound(focused)
|
||||
self._parent.activateFocusedWidget()
|
||||
elif button_code in BUTTONS['back']:
|
||||
SoundManager().play("back")
|
||||
if self._is_theme_store_visible():
|
||||
store_stack = getattr(self._parent, "themeStoreStack", None)
|
||||
detail_page = getattr(self._parent, "themeStoreDetailPage", None)
|
||||
@@ -2810,6 +2821,7 @@ class InputManager(QObject):
|
||||
self._parent.goBackDetailPage(getattr(self._parent, 'currentDetailPage', None))
|
||||
elif button_code in BUTTONS['add_game']:
|
||||
if self._parent.stackedWidget.currentIndex() == 0:
|
||||
SoundManager().play("open")
|
||||
self._parent.openAddGameDialog()
|
||||
elif button_code in BUTTONS['prev_tab']:
|
||||
idx = self._parent.stackedWidget.currentIndex()
|
||||
@@ -3148,6 +3160,7 @@ class InputManager(QObject):
|
||||
if not hasattr(self._parent, 'gamesListWidget') or self._parent.gamesListWidget is None:
|
||||
logger.error("gamesListWidget not available yet, skipping D-pad navigation")
|
||||
return
|
||||
|
||||
try:
|
||||
|
||||
app = QApplication.instance()
|
||||
@@ -3156,6 +3169,8 @@ class InputManager(QObject):
|
||||
popup = QApplication.activePopupWidget()
|
||||
if not app or not active:
|
||||
return
|
||||
if not isinstance(focused, GameCard):
|
||||
SoundManager().play("navigate")
|
||||
|
||||
# Handle QMessageBox navigation with D-pad (for multiple buttons)
|
||||
if isinstance(active, QMessageBox) and not isinstance(focused, QTableWidget):
|
||||
@@ -3508,6 +3523,17 @@ class InputManager(QObject):
|
||||
if not app:
|
||||
return super().eventFilter(obj, event)
|
||||
|
||||
if event.type() == QEvent.Type.Show:
|
||||
if isinstance(obj, QMenu):
|
||||
SoundManager().play("open")
|
||||
elif isinstance(obj, QWidget) and obj.windowType() == Qt.WindowType.Popup:
|
||||
parent = obj.parent()
|
||||
while isinstance(parent, QObject):
|
||||
if isinstance(parent, QComboBox):
|
||||
SoundManager().play("open")
|
||||
break
|
||||
parent = parent.parent()
|
||||
|
||||
if event.type() == QEvent.Type.Wheel:
|
||||
combo = obj if isinstance(obj, QComboBox) else None
|
||||
parent = obj.parent() if isinstance(obj, QObject) else None
|
||||
@@ -3547,6 +3573,12 @@ class InputManager(QObject):
|
||||
self._handle_back_mouse_button()
|
||||
return True
|
||||
|
||||
if event.type() == QEvent.Type.MouseButtonRelease:
|
||||
button_method = getattr(event, "button", None)
|
||||
button = button_method() if callable(button_method) else None
|
||||
if button == Qt.MouseButton.LeftButton:
|
||||
SoundManager().play_widget_sound(obj)
|
||||
|
||||
# Ensure obj is a QObject
|
||||
if not isinstance(obj, QObject):
|
||||
logger.debug(f"Skipping event filter for non-QObject: {type(obj).__name__}")
|
||||
@@ -3613,6 +3645,7 @@ class InputManager(QObject):
|
||||
if isinstance(focused, QLineEdit):
|
||||
return
|
||||
if isinstance(active_win, QDialog):
|
||||
SoundManager().play("back")
|
||||
active_win.reject()
|
||||
return
|
||||
self._parent.goBackDetailPage(self._parent.currentDetailPage)
|
||||
@@ -3999,7 +4032,9 @@ class InputManager(QObject):
|
||||
self.gamepad_check_timer = QTimer(self)
|
||||
self.gamepad_check_timer.setSingleShot(True)
|
||||
self.gamepad_check_timer.timeout.connect(self.check_gamepad)
|
||||
self._initial_gamepad_check = True
|
||||
self.check_gamepad()
|
||||
self._initial_gamepad_check = False
|
||||
if not self.gamepad_thread or not self.gamepad_thread.is_alive():
|
||||
self.gamepad_thread = threading.Thread(target=self.monitor_gamepad, daemon=True)
|
||||
self.gamepad_thread.start()
|
||||
@@ -4045,6 +4080,8 @@ class InputManager(QObject):
|
||||
self._last_gamepad_check_time = 0.0
|
||||
self.gamepad_type = self._get_effective_gamepad_type(new_gamepad)
|
||||
self._refresh_gamepad_ui()
|
||||
if not self._initial_gamepad_check:
|
||||
SoundManager().play("gamepad_connect")
|
||||
|
||||
if display_config.get_auto_fullscreen_gamepad() and not display_config.get_fullscreen():
|
||||
self.toggle_fullscreen.emit(True)
|
||||
@@ -4365,13 +4402,16 @@ class InputManager(QObject):
|
||||
if popup:
|
||||
if isinstance(popup, QMessageBox):
|
||||
self._handle_qmessagebox_button(popup, button_code)
|
||||
SoundManager().play("click")
|
||||
return True
|
||||
elif isinstance(popup, QMenu):
|
||||
if button_code in BUTTONS['confirm']:
|
||||
SoundManager().play("click")
|
||||
if popup.activeAction():
|
||||
popup.activeAction().trigger()
|
||||
popup.close()
|
||||
elif button_code in BUTTONS['back']:
|
||||
SoundManager().play("back")
|
||||
popup.close()
|
||||
return True
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ from portprotonqt.tray_manager import TrayManager
|
||||
from portprotonqt.game_library_manager import GameLibraryManager
|
||||
from portprotonqt.virtual_keyboard import VirtualKeyboard
|
||||
from portprotonqt.disc_image_utils import DiscImageManager
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
from portprotonqt.tabs.control_hints import MainWindowControlHintsMixin
|
||||
from portprotonqt.tabs.autoinstall_tab import MainWindowAutoInstallTabMixin
|
||||
from portprotonqt.tabs.library_tab import MainWindowLibraryTabMixin
|
||||
@@ -410,6 +411,7 @@ class MainWindow(
|
||||
self.leftNavButton = NavLabel()
|
||||
self.leftNavButton.setFixedSize(32, 32)
|
||||
self.leftNavButton.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.leftNavButton.setProperty("sound_event", False)
|
||||
self.leftNavButton.clicked.connect(lambda: self.switchVisibleTab(-1))
|
||||
navLayout.addWidget(self.leftNavButton)
|
||||
|
||||
@@ -426,6 +428,7 @@ class MainWindow(
|
||||
for i, tabName in enumerate(tabs):
|
||||
btn = NavLabel(tabName)
|
||||
btn.setCheckable(True)
|
||||
btn.setProperty("sound_event", False)
|
||||
btn.clicked.connect(lambda index=i: self.switchTab(index))
|
||||
btn.setStyleSheet(self.theme.NAV_BUTTON_STYLE)
|
||||
navLayout.addWidget(btn)
|
||||
@@ -437,6 +440,7 @@ class MainWindow(
|
||||
self.rightNavButton = NavLabel()
|
||||
self.rightNavButton.setFixedSize(32, 32)
|
||||
self.rightNavButton.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.rightNavButton.setProperty("sound_event", False)
|
||||
self.rightNavButton.clicked.connect(lambda: self.switchVisibleTab(1))
|
||||
navLayout.addWidget(self.rightNavButton)
|
||||
|
||||
@@ -1307,6 +1311,7 @@ class MainWindow(
|
||||
|
||||
def switchTab(self, index):
|
||||
"""Set active tab by index."""
|
||||
SoundManager().play("tab_switch")
|
||||
# Check if the requested tab index is valid, exists, and is visible
|
||||
if (hasattr(self, 'tabButtons') and
|
||||
index in self.tabButtons and
|
||||
@@ -1317,7 +1322,7 @@ class MainWindow(
|
||||
btn.setChecked(i == index)
|
||||
self.stackedWidget.setCurrentIndex(index)
|
||||
if index == self.auto_install_tab_index:
|
||||
self._start_autoinstall_load()
|
||||
QTimer.singleShot(0, self._start_autoinstall_load)
|
||||
else:
|
||||
# If trying to switch to a non-existent or hidden tab (like auto-install when it's hidden),
|
||||
# find the first visible tab to switch to
|
||||
@@ -1455,6 +1460,7 @@ class MainWindow(
|
||||
|
||||
def openGameDetailPage(self, game_data: dict) -> None:
|
||||
"""Open game detail page."""
|
||||
SoundManager().play("open")
|
||||
logger.debug(
|
||||
"Opening detail page for %s from stacked index %d",
|
||||
game_data.get("name", ""),
|
||||
@@ -2333,6 +2339,7 @@ class MainWindow(
|
||||
errors="replace",
|
||||
bufsize=1,
|
||||
)
|
||||
SoundManager().play("game_launch")
|
||||
self.game_processes.append(process)
|
||||
self._start_launch_output_reader(process)
|
||||
self.input_manager.suspend_gamepad_polling()
|
||||
@@ -2439,6 +2446,7 @@ class MainWindow(
|
||||
|
||||
def goBackDetailPage(self, page):
|
||||
"""Bridge method to detail page manager."""
|
||||
SoundManager().play("back")
|
||||
result = self.detail_page_manager.goBackDetailPage(page)
|
||||
# The detail page manager will handle the navigation properly
|
||||
return result
|
||||
|
||||
@@ -25,8 +25,9 @@ install_data(
|
||||
'preloader.py',
|
||||
'qt_utils.py',
|
||||
'search_utils.py',
|
||||
'settings_manager.py',
|
||||
'theme_manager.py',
|
||||
'settings_manager.py',
|
||||
'sound_manager.py',
|
||||
'theme_manager.py',
|
||||
'theme_security.py',
|
||||
'time_utils.py',
|
||||
'tray_manager.py',
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Sound manager for UI feedback sounds, integrated with the theme system."""
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QLoggingCategory, QUrl
|
||||
|
||||
from portprotonqt.config import ui_config
|
||||
from portprotonqt.logger import get_logger
|
||||
from portprotonqt.theme_security import SUPPORTED_SOUND_EXTENSIONS, is_safe_sound_file
|
||||
|
||||
logger = get_logger(__name__)
|
||||
FFMPEG_LOG_RULES = "qt.multimedia.ffmpeg=false\nqt.multimedia.ffmpeg.*=false"
|
||||
|
||||
SOUND_EVENTS = frozenset({
|
||||
"navigate", "click", "confirm", "back", "toggle", "open", "close",
|
||||
"error", "notification", "keyboard_key", "scroll", "tab_switch",
|
||||
"game_launch", "gamepad_connect",
|
||||
})
|
||||
|
||||
|
||||
class _SoundSlot:
|
||||
"""A single player slot that pre-loads a sound file."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer
|
||||
|
||||
self._audio = QAudioOutput()
|
||||
self._player = QMediaPlayer()
|
||||
self._player.setAudioOutput(self._audio)
|
||||
self._player.setLoops(QMediaPlayer.Loops.Once)
|
||||
self._player.mediaStatusChanged.connect(self._handle_media_status)
|
||||
self._loaded_event: str | None = None
|
||||
|
||||
def _handle_media_status(self, status: object) -> None:
|
||||
if status == self._player.MediaStatus.EndOfMedia:
|
||||
self._player.stop()
|
||||
|
||||
def play(self, event: str, url: QUrl) -> None:
|
||||
if (
|
||||
self._loaded_event == event
|
||||
and self._player.playbackState() == self._player.PlaybackState.PlayingState
|
||||
):
|
||||
return
|
||||
if self._loaded_event != event:
|
||||
self._player.setSource(url)
|
||||
self._loaded_event = event
|
||||
self._player.stop()
|
||||
self._player.setPosition(0)
|
||||
self._player.play()
|
||||
|
||||
def reset(self) -> None:
|
||||
self._player.setSource(QUrl())
|
||||
self._loaded_event = None
|
||||
|
||||
|
||||
class SoundManager:
|
||||
"""Manages UI feedback sounds, loading from theme directories."""
|
||||
|
||||
_instance: "SoundManager | None" = None
|
||||
|
||||
def __new__(cls) -> "SoundManager":
|
||||
if cls._instance is None:
|
||||
cls._instance = super().__new__(cls)
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self) -> None:
|
||||
if self._initialized:
|
||||
return
|
||||
self._initialized = True
|
||||
QLoggingCategory.setFilterRules(FFMPEG_LOG_RULES)
|
||||
self._enabled = ui_config.get_sounds_enabled()
|
||||
self._sounds_dirs: list[str] = []
|
||||
try:
|
||||
self._slots = [_SoundSlot() for _ in range(4)]
|
||||
except ImportError as e:
|
||||
logger.warning("UI sounds are unavailable: %s", e)
|
||||
self._slots = []
|
||||
self._slot_index = 0
|
||||
self._url_cache: dict[str, QUrl] = {}
|
||||
|
||||
def set_sounds_dirs(self, dirs: list[str]) -> None:
|
||||
if dirs != self._sounds_dirs:
|
||||
self._sounds_dirs = dirs
|
||||
self._url_cache.clear()
|
||||
for slot in self._slots:
|
||||
slot.reset()
|
||||
|
||||
def reload_config(self) -> None:
|
||||
self._enabled = ui_config.get_sounds_enabled()
|
||||
|
||||
def _find_sound_path(self, event: str) -> Path | None:
|
||||
if event not in SOUND_EVENTS:
|
||||
return None
|
||||
for sounds_dir in self._sounds_dirs:
|
||||
for extension in SUPPORTED_SOUND_EXTENSIONS:
|
||||
path = Path(sounds_dir) / f"{event}{extension}"
|
||||
if path.is_file() and is_safe_sound_file(str(path)):
|
||||
return path
|
||||
return None
|
||||
|
||||
def _get_url(self, event: str) -> QUrl | None:
|
||||
if event in self._url_cache:
|
||||
return self._url_cache[event]
|
||||
path = self._find_sound_path(event)
|
||||
if path is None:
|
||||
return None
|
||||
url = QUrl.fromLocalFile(str(path))
|
||||
self._url_cache[event] = url
|
||||
return url
|
||||
|
||||
def play(self, event: str) -> None:
|
||||
if not self._enabled:
|
||||
return
|
||||
url = self._get_url(event)
|
||||
if url is None or not self._slots:
|
||||
return
|
||||
for slot in self._slots:
|
||||
if slot._loaded_event == event:
|
||||
slot.play(event, url)
|
||||
return
|
||||
slot = self._slots[self._slot_index]
|
||||
self._slot_index = (self._slot_index + 1) % len(self._slots)
|
||||
slot.play(event, url)
|
||||
|
||||
def play_widget_sound(self, widget: object) -> None:
|
||||
from PySide6.QtWidgets import QCheckBox, QComboBox, QPushButton
|
||||
from portprotonqt.custom_widgets import AutoSizeButton, ClickableLabel, NavLabel
|
||||
property_method = getattr(widget, "property", None)
|
||||
sound_event = property_method("sound_event") if callable(property_method) else None
|
||||
if sound_event is False:
|
||||
return
|
||||
if isinstance(sound_event, str) and sound_event in SOUND_EVENTS:
|
||||
self.play(sound_event)
|
||||
return
|
||||
if isinstance(widget, (QPushButton, AutoSizeButton)):
|
||||
self.play("click")
|
||||
elif isinstance(widget, QCheckBox):
|
||||
self.play("toggle")
|
||||
elif isinstance(widget, QComboBox):
|
||||
self.play("open")
|
||||
elif isinstance(widget, (ClickableLabel, NavLabel)):
|
||||
self.play("click")
|
||||
|
||||
def set_enabled(self, enabled: bool) -> None:
|
||||
self._enabled = enabled
|
||||
ui_config.set_sounds_enabled(enabled)
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return self._enabled
|
||||
@@ -154,6 +154,7 @@ class MainWindowLibraryTabMixin(_MainWindowTypingBase):
|
||||
self.addGameButton = AutoSizeButton(_("Add a shortcut"), icon=self.theme_manager.get_icon("addgame", as_path=True))
|
||||
self.addGameButton.setStyleSheet(self.theme.ADDGAME_BACK_BUTTON_STYLE)
|
||||
self.addGameButton.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||
self.addGameButton.setProperty("sound_event", "open")
|
||||
self.addGameButton.clicked.connect(self.openAddGameDialog)
|
||||
buttons_layout.addWidget(self.addGameButton)
|
||||
buttons_layout.addStretch()
|
||||
|
||||
@@ -295,6 +295,21 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
|
||||
hide_autoinstall_layout.addStretch()
|
||||
uiForm.addRow(hide_autoinstall_layout)
|
||||
|
||||
self.soundsEnabledCheckBox = QCheckBox()
|
||||
self.soundsEnabledCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
|
||||
self.soundsEnabledCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||
self.soundsEnabledTitle = QLabel(_("Enable UI Sounds"))
|
||||
self.soundsEnabledTitle.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
|
||||
self.soundsEnabledTitle.setStyleSheet(self.theme.SETTINGS_TITLE_CHECKBOX_STYLE)
|
||||
self.soundsEnabledTitle.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
self.soundsEnabledCheckBox.setChecked(ui_config.get_sounds_enabled())
|
||||
sounds_enabled_layout = QHBoxLayout()
|
||||
sounds_enabled_layout.setContentsMargins(0, 0, 0, 0)
|
||||
sounds_enabled_layout.addWidget(self.soundsEnabledCheckBox)
|
||||
sounds_enabled_layout.addWidget(self.soundsEnabledTitle)
|
||||
sounds_enabled_layout.addStretch()
|
||||
uiForm.addRow(sounds_enabled_layout)
|
||||
|
||||
disable_runtime_download_layout = None
|
||||
if not os.getenv("FLATPAK_ID"):
|
||||
self.disableRuntimeDownloadCheckBox = QCheckBox()
|
||||
@@ -841,6 +856,12 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
|
||||
# Save the hide auto-install tab setting to config
|
||||
ui_config.set_hide_autoinstall_tab(hide_autoinstall)
|
||||
|
||||
sounds_enabled = self.soundsEnabledCheckBox.isChecked()
|
||||
ui_config.set_sounds_enabled(sounds_enabled)
|
||||
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
SoundManager().reload_config()
|
||||
|
||||
def _apply_gamepad_type_setting(self) -> None:
|
||||
"""Apply configured gamepad type to current input manager."""
|
||||
input_manager = getattr(self, "input_manager", None)
|
||||
|
||||
@@ -33,6 +33,7 @@ from portprotonqt.dialogs.base import DraggableDialog
|
||||
from portprotonqt.dialogs import FileExplorer
|
||||
from portprotonqt.localization import _
|
||||
from portprotonqt.logger import get_logger
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
from portprotonqt.preloader import Preloader
|
||||
from portprotonqt.system_manager import (
|
||||
AudioManagerWorker,
|
||||
@@ -263,6 +264,7 @@ class MainWindowSystemTabMixin(_MainWindowTypingBase):
|
||||
button.setCheckable(True)
|
||||
button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
|
||||
button.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||
button.setProperty("sound_event", False)
|
||||
button.clicked.connect(lambda _checked=False, section_index=index: self.switchSystemSection(section_index))
|
||||
self.systemSectionButtons.append(button)
|
||||
section_switcher_layout.addWidget(button)
|
||||
@@ -334,7 +336,10 @@ class MainWindowSystemTabMixin(_MainWindowTypingBase):
|
||||
return False
|
||||
if index < len(self.systemSectionButtons) and not self.systemSectionButtons[index].isVisible():
|
||||
return False
|
||||
previous_index = self.systemSectionStack.currentIndex()
|
||||
self.systemSectionStack.setCurrentIndex(index)
|
||||
if previous_index != index:
|
||||
SoundManager().play("tab_switch")
|
||||
for button_index, button in enumerate(self.systemSectionButtons):
|
||||
button.setChecked(button_index == index)
|
||||
self._focusCurrentSystemSection(index)
|
||||
|
||||
@@ -197,6 +197,7 @@ class ThemeStoreMixin:
|
||||
header = QHBoxLayout()
|
||||
self.themeStoreBackButton = AutoSizeButton(_("Back"))
|
||||
self.themeStoreBackButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
|
||||
self.themeStoreBackButton.setProperty("sound_event", "back")
|
||||
self.themeStoreBackButton.clicked.connect(self._show_theme_store_list)
|
||||
header.addWidget(self.themeStoreBackButton)
|
||||
header.addStretch(1)
|
||||
|
||||
@@ -411,6 +411,19 @@ def build_icon_cache(theme_name):
|
||||
_icon_dirs_cache[theme_name] = image_map
|
||||
return image_map
|
||||
|
||||
def _resolve_sound_dirs(theme_name: str) -> list[str]:
|
||||
"""Return ordered list of sound directories from theme inheritance chain."""
|
||||
dirs = []
|
||||
for resource_theme_name in _get_theme_resource_chain(theme_name):
|
||||
theme_folder = _find_theme_folder(resource_theme_name)
|
||||
if not theme_folder:
|
||||
continue
|
||||
sounds_dir = os.path.join(theme_folder, "sounds")
|
||||
if os.path.isdir(sounds_dir):
|
||||
dirs.append(sounds_dir)
|
||||
return dirs
|
||||
|
||||
|
||||
def load_theme_fonts(theme_name):
|
||||
"""
|
||||
Load all fonts from selected theme if not already loaded.
|
||||
@@ -804,6 +817,10 @@ class ThemeManager:
|
||||
self.current_theme_name = theme_name
|
||||
self.current_theme_module = theme_module
|
||||
ui_config.set_theme(theme_name)
|
||||
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
SoundManager().set_sounds_dirs(_resolve_sound_dirs(theme_name))
|
||||
|
||||
logger.info(f"Theme '{theme_name}' successfully applied")
|
||||
return theme_module
|
||||
|
||||
|
||||
@@ -11,6 +11,10 @@ from portprotonqt.logger import get_logger
|
||||
logger = get_logger(__name__)
|
||||
MAX_THEME_PY_FILE_SIZE = 512 * 1024
|
||||
MAX_AST_NODES = 20000
|
||||
MAX_SOUND_FILE_SIZE = 20 * 1024 * 1024
|
||||
SUPPORTED_SOUND_EXTENSIONS = (
|
||||
".ogg", ".oga", ".wav", ".mp3", ".flac", ".opus", ".m4a", ".aac", ".webm",
|
||||
)
|
||||
|
||||
|
||||
class ThemeSecurityChecker:
|
||||
@@ -568,6 +572,9 @@ def check_theme_directory_safety(theme_dir: str, allow_absolute_imports: bool =
|
||||
elif filename.endswith((".ttf", ".otf")):
|
||||
if not is_safe_font_file(file_path):
|
||||
return False
|
||||
elif filename.lower().endswith(SUPPORTED_SOUND_EXTENSIONS):
|
||||
if not is_safe_sound_file(file_path):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
@@ -607,6 +614,45 @@ def is_safe_font_file(file_path: str) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def is_safe_sound_file(file_path: str) -> bool:
|
||||
"""Check a theme sound extension, size, and file signature."""
|
||||
_, ext = os.path.splitext(file_path.lower())
|
||||
if ext not in SUPPORTED_SOUND_EXTENSIONS:
|
||||
logger.error("Unsafe sound file extension for %s: %s", file_path, ext)
|
||||
return False
|
||||
try:
|
||||
file_size = os.path.getsize(file_path)
|
||||
if file_size > MAX_SOUND_FILE_SIZE:
|
||||
logger.error("Sound file too large (%s bytes): %s", file_size, file_path)
|
||||
return False
|
||||
with open(file_path, "rb") as sound_file:
|
||||
header = sound_file.read(16)
|
||||
except OSError as e:
|
||||
logger.error("Error reading sound file %s: %s", file_path, e)
|
||||
return False
|
||||
|
||||
is_valid = False
|
||||
if ext in (".ogg", ".oga", ".opus"):
|
||||
is_valid = header.startswith(b"OggS")
|
||||
elif ext == ".wav":
|
||||
is_valid = header.startswith(b"RIFF") and header[8:12] == b"WAVE"
|
||||
elif ext == ".flac":
|
||||
is_valid = header.startswith(b"fLaC")
|
||||
elif ext == ".mp3":
|
||||
is_valid = header.startswith(b"ID3") or (
|
||||
len(header) > 1 and header[0] == 0xff and header[1] & 0xe0 == 0xe0
|
||||
)
|
||||
elif ext == ".m4a":
|
||||
is_valid = header[4:8] == b"ftyp"
|
||||
elif ext == ".aac":
|
||||
is_valid = len(header) > 1 and header[0] == 0xff and header[1] & 0xf0 == 0xf0
|
||||
elif ext == ".webm":
|
||||
is_valid = header.startswith(b"\x1a\x45\xdf\xa3")
|
||||
if not is_valid:
|
||||
logger.error("Sound file %s has invalid signature", file_path)
|
||||
return is_valid
|
||||
|
||||
|
||||
def is_safe_image_file(file_path: str) -> bool:
|
||||
"""
|
||||
Check if an image file is safe to load by verifying its extension and basic file properties.
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
|
||||
|
||||
Interface Sounds (1.0)
|
||||
|
||||
Created/distributed by Kenney (www.kenney.nl)
|
||||
Creation date: 11-02-2020
|
||||
|
||||
------------------------------
|
||||
|
||||
License: (Creative Commons Zero, CC0)
|
||||
http://creativecommons.org/publicdomain/zero/1.0/
|
||||
|
||||
This content is free to use in personal, educational and commercial projects.
|
||||
Support us by crediting Kenney or www.kenney.nl (this is not mandatory)
|
||||
|
||||
------------------------------
|
||||
|
||||
Donate: http://support.kenney.nl
|
||||
Patreon: http://patreon.com/kenney/
|
||||
|
||||
Follow on Twitter for updates:
|
||||
http://twitter.com/KenneyNL
|
||||
@@ -0,0 +1,427 @@
|
||||
Attribution-ShareAlike 4.0 International
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
||||
does not provide legal services or legal advice. Distribution of
|
||||
Creative Commons public licenses does not create a lawyer-client or
|
||||
other relationship. Creative Commons makes its licenses and related
|
||||
information available on an "as-is" basis. Creative Commons gives no
|
||||
warranties regarding its licenses, any material licensed under their
|
||||
terms and conditions, or any related information. Creative Commons
|
||||
disclaims all liability for damages resulting from their use to the
|
||||
fullest extent possible.
|
||||
|
||||
Using Creative Commons Public Licenses
|
||||
|
||||
Creative Commons public licenses provide a standard set of terms and
|
||||
conditions that creators and other rights holders may use to share
|
||||
original works of authorship and other material subject to copyright
|
||||
and certain other rights specified in the public license below. The
|
||||
following considerations are for informational purposes only, are not
|
||||
exhaustive, and do not form part of our licenses.
|
||||
|
||||
Considerations for licensors: Our public licenses are
|
||||
intended for use by those authorized to give the public
|
||||
permission to use material in ways otherwise restricted by
|
||||
copyright and certain other rights. Our licenses are
|
||||
irrevocable. Licensors should read and understand the terms
|
||||
and conditions of the license they choose before applying it.
|
||||
Licensors should also secure all rights necessary before
|
||||
applying our licenses so that the public can reuse the
|
||||
material as expected. Licensors should clearly mark any
|
||||
material not subject to the license. This includes other CC-
|
||||
licensed material, or material used under an exception or
|
||||
limitation to copyright. More considerations for licensors:
|
||||
wiki.creativecommons.org/Considerations_for_licensors
|
||||
|
||||
Considerations for the public: By using one of our public
|
||||
licenses, a licensor grants the public permission to use the
|
||||
licensed material under specified terms and conditions. If
|
||||
the licensor's permission is not necessary for any reason--for
|
||||
example, because of any applicable exception or limitation to
|
||||
copyright--then that use is not regulated by the license. Our
|
||||
licenses grant only permissions under copyright and certain
|
||||
other rights that a licensor has authority to grant. Use of
|
||||
the licensed material may still be restricted for other
|
||||
reasons, including because others have copyright or other
|
||||
rights in the material. A licensor may make special requests,
|
||||
such as asking that all changes be marked or described.
|
||||
Although not required by our licenses, you are encouraged to
|
||||
respect those requests where reasonable. More_considerations
|
||||
for the public:
|
||||
wiki.creativecommons.org/Considerations_for_licensees
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Attribution-ShareAlike 4.0 International Public
|
||||
License
|
||||
|
||||
By exercising the Licensed Rights (defined below), You accept and agree
|
||||
to be bound by the terms and conditions of this Creative Commons
|
||||
Attribution-ShareAlike 4.0 International Public License ("Public
|
||||
License"). To the extent this Public License may be interpreted as a
|
||||
contract, You are granted the Licensed Rights in consideration of Your
|
||||
acceptance of these terms and conditions, and the Licensor grants You
|
||||
such rights in consideration of benefits the Licensor receives from
|
||||
making the Licensed Material available under these terms and
|
||||
conditions.
|
||||
|
||||
|
||||
Section 1 -- Definitions.
|
||||
|
||||
a. Adapted Material means material subject to Copyright and Similar
|
||||
Rights that is derived from or based upon the Licensed Material
|
||||
and in which the Licensed Material is translated, altered,
|
||||
arranged, transformed, or otherwise modified in a manner requiring
|
||||
permission under the Copyright and Similar Rights held by the
|
||||
Licensor. For purposes of this Public License, where the Licensed
|
||||
Material is a musical work, performance, or sound recording,
|
||||
Adapted Material is always produced where the Licensed Material is
|
||||
synched in timed relation with a moving image.
|
||||
|
||||
b. Adapter's License means the license You apply to Your Copyright
|
||||
and Similar Rights in Your contributions to Adapted Material in
|
||||
accordance with the terms and conditions of this Public License.
|
||||
|
||||
c. BY-SA Compatible License means a license listed at
|
||||
creativecommons.org/compatiblelicenses, approved by Creative
|
||||
Commons as essentially the equivalent of this Public License.
|
||||
|
||||
d. Copyright and Similar Rights means copyright and/or similar rights
|
||||
closely related to copyright including, without limitation,
|
||||
performance, broadcast, sound recording, and Sui Generis Database
|
||||
Rights, without regard to how the rights are labeled or
|
||||
categorized. For purposes of this Public License, the rights
|
||||
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
||||
Rights.
|
||||
|
||||
e. Effective Technological Measures means those measures that, in the
|
||||
absence of proper authority, may not be circumvented under laws
|
||||
fulfilling obligations under Article 11 of the WIPO Copyright
|
||||
Treaty adopted on December 20, 1996, and/or similar international
|
||||
agreements.
|
||||
|
||||
f. Exceptions and Limitations means fair use, fair dealing, and/or
|
||||
any other exception or limitation to Copyright and Similar Rights
|
||||
that applies to Your use of the Licensed Material.
|
||||
|
||||
g. License Elements means the license attributes listed in the name
|
||||
of a Creative Commons Public License. The License Elements of this
|
||||
Public License are Attribution and ShareAlike.
|
||||
|
||||
h. Licensed Material means the artistic or literary work, database,
|
||||
or other material to which the Licensor applied this Public
|
||||
License.
|
||||
|
||||
i. Licensed Rights means the rights granted to You subject to the
|
||||
terms and conditions of this Public License, which are limited to
|
||||
all Copyright and Similar Rights that apply to Your use of the
|
||||
Licensed Material and that the Licensor has authority to license.
|
||||
|
||||
j. Licensor means the individual(s) or entity(ies) granting rights
|
||||
under this Public License.
|
||||
|
||||
k. Share means to provide material to the public by any means or
|
||||
process that requires permission under the Licensed Rights, such
|
||||
as reproduction, public display, public performance, distribution,
|
||||
dissemination, communication, or importation, and to make material
|
||||
available to the public including in ways that members of the
|
||||
public may access the material from a place and at a time
|
||||
individually chosen by them.
|
||||
|
||||
l. Sui Generis Database Rights means rights other than copyright
|
||||
resulting from Directive 96/9/EC of the European Parliament and of
|
||||
the Council of 11 March 1996 on the legal protection of databases,
|
||||
as amended and/or succeeded, as well as other essentially
|
||||
equivalent rights anywhere in the world.
|
||||
|
||||
m. You means the individual or entity exercising the Licensed Rights
|
||||
under this Public License. Your has a corresponding meaning.
|
||||
|
||||
|
||||
Section 2 -- Scope.
|
||||
|
||||
a. License grant.
|
||||
|
||||
1. Subject to the terms and conditions of this Public License,
|
||||
the Licensor hereby grants You a worldwide, royalty-free,
|
||||
non-sublicensable, non-exclusive, irrevocable license to
|
||||
exercise the Licensed Rights in the Licensed Material to:
|
||||
|
||||
a. reproduce and Share the Licensed Material, in whole or
|
||||
in part; and
|
||||
|
||||
b. produce, reproduce, and Share Adapted Material.
|
||||
|
||||
2. Exceptions and Limitations. For the avoidance of doubt, where
|
||||
Exceptions and Limitations apply to Your use, this Public
|
||||
License does not apply, and You do not need to comply with
|
||||
its terms and conditions.
|
||||
|
||||
3. Term. The term of this Public License is specified in Section
|
||||
6(a).
|
||||
|
||||
4. Media and formats; technical modifications allowed. The
|
||||
Licensor authorizes You to exercise the Licensed Rights in
|
||||
all media and formats whether now known or hereafter created,
|
||||
and to make technical modifications necessary to do so. The
|
||||
Licensor waives and/or agrees not to assert any right or
|
||||
authority to forbid You from making technical modifications
|
||||
necessary to exercise the Licensed Rights, including
|
||||
technical modifications necessary to circumvent Effective
|
||||
Technological Measures. For purposes of this Public License,
|
||||
simply making modifications authorized by this Section 2(a)
|
||||
(4) never produces Adapted Material.
|
||||
|
||||
5. Downstream recipients.
|
||||
|
||||
a. Offer from the Licensor -- Licensed Material. Every
|
||||
recipient of the Licensed Material automatically
|
||||
receives an offer from the Licensor to exercise the
|
||||
Licensed Rights under the terms and conditions of this
|
||||
Public License.
|
||||
|
||||
b. Additional offer from the Licensor -- Adapted Material.
|
||||
Every recipient of Adapted Material from You
|
||||
automatically receives an offer from the Licensor to
|
||||
exercise the Licensed Rights in the Adapted Material
|
||||
under the conditions of the Adapter's License You apply.
|
||||
|
||||
c. No downstream restrictions. You may not offer or impose
|
||||
any additional or different terms or conditions on, or
|
||||
apply any Effective Technological Measures to, the
|
||||
Licensed Material if doing so restricts exercise of the
|
||||
Licensed Rights by any recipient of the Licensed
|
||||
Material.
|
||||
|
||||
6. No endorsement. Nothing in this Public License constitutes or
|
||||
may be construed as permission to assert or imply that You
|
||||
are, or that Your use of the Licensed Material is, connected
|
||||
with, or sponsored, endorsed, or granted official status by,
|
||||
the Licensor or others designated to receive attribution as
|
||||
provided in Section 3(a)(1)(A)(i).
|
||||
|
||||
b. Other rights.
|
||||
|
||||
1. Moral rights, such as the right of integrity, are not
|
||||
licensed under this Public License, nor are publicity,
|
||||
privacy, and/or other similar personality rights; however, to
|
||||
the extent possible, the Licensor waives and/or agrees not to
|
||||
assert any such rights held by the Licensor to the limited
|
||||
extent necessary to allow You to exercise the Licensed
|
||||
Rights, but not otherwise.
|
||||
|
||||
2. Patent and trademark rights are not licensed under this
|
||||
Public License.
|
||||
|
||||
3. To the extent possible, the Licensor waives any right to
|
||||
collect royalties from You for the exercise of the Licensed
|
||||
Rights, whether directly or through a collecting society
|
||||
under any voluntary or waivable statutory or compulsory
|
||||
licensing scheme. In all other cases the Licensor expressly
|
||||
reserves any right to collect such royalties.
|
||||
|
||||
|
||||
Section 3 -- License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the
|
||||
following conditions.
|
||||
|
||||
a. Attribution.
|
||||
|
||||
1. If You Share the Licensed Material (including in modified
|
||||
form), You must:
|
||||
|
||||
a. retain the following if it is supplied by the Licensor
|
||||
with the Licensed Material:
|
||||
|
||||
i. identification of the creator(s) of the Licensed
|
||||
Material and any others designated to receive
|
||||
attribution, in any reasonable manner requested by
|
||||
the Licensor (including by pseudonym if
|
||||
designated);
|
||||
|
||||
ii. a copyright notice;
|
||||
|
||||
iii. a notice that refers to this Public License;
|
||||
|
||||
iv. a notice that refers to the disclaimer of
|
||||
warranties;
|
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the
|
||||
extent reasonably practicable;
|
||||
|
||||
b. indicate if You modified the Licensed Material and
|
||||
retain an indication of any previous modifications; and
|
||||
|
||||
c. indicate the Licensed Material is licensed under this
|
||||
Public License, and include the text of, or the URI or
|
||||
hyperlink to, this Public License.
|
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any
|
||||
reasonable manner based on the medium, means, and context in
|
||||
which You Share the Licensed Material. For example, it may be
|
||||
reasonable to satisfy the conditions by providing a URI or
|
||||
hyperlink to a resource that includes the required
|
||||
information.
|
||||
|
||||
3. If requested by the Licensor, You must remove any of the
|
||||
information required by Section 3(a)(1)(A) to the extent
|
||||
reasonably practicable.
|
||||
|
||||
b. ShareAlike.
|
||||
|
||||
In addition to the conditions in Section 3(a), if You Share
|
||||
Adapted Material You produce, the following conditions also apply.
|
||||
|
||||
1. The Adapter's License You apply must be a Creative Commons
|
||||
license with the same License Elements, this version or
|
||||
later, or a BY-SA Compatible License.
|
||||
|
||||
2. You must include the text of, or the URI or hyperlink to, the
|
||||
Adapter's License You apply. You may satisfy this condition
|
||||
in any reasonable manner based on the medium, means, and
|
||||
context in which You Share Adapted Material.
|
||||
|
||||
3. You may not offer or impose any additional or different terms
|
||||
or conditions on, or apply any Effective Technological
|
||||
Measures to, Adapted Material that restrict exercise of the
|
||||
rights granted under the Adapter's License You apply.
|
||||
|
||||
|
||||
Section 4 -- Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that
|
||||
apply to Your use of the Licensed Material:
|
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
||||
to extract, reuse, reproduce, and Share all or a substantial
|
||||
portion of the contents of the database;
|
||||
|
||||
b. if You include all or a substantial portion of the database
|
||||
contents in a database in which You have Sui Generis Database
|
||||
Rights, then the database in which You have Sui Generis Database
|
||||
Rights (but not its individual contents) is Adapted Material,
|
||||
|
||||
including for purposes of Section 3(b); and
|
||||
c. You must comply with the conditions in Section 3(a) if You Share
|
||||
all or a substantial portion of the contents of the database.
|
||||
|
||||
For the avoidance of doubt, this Section 4 supplements and does not
|
||||
replace Your obligations under this Public License where the Licensed
|
||||
Rights include other Copyright and Similar Rights.
|
||||
|
||||
|
||||
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
||||
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
||||
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
||||
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
||||
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
||||
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
||||
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
||||
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
||||
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
||||
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
||||
|
||||
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
||||
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
||||
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
||||
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
||||
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
||||
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
||||
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
||||
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
||||
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided
|
||||
above shall be interpreted in a manner that, to the extent
|
||||
possible, most closely approximates an absolute disclaimer and
|
||||
waiver of all liability.
|
||||
|
||||
|
||||
Section 6 -- Term and Termination.
|
||||
|
||||
a. This Public License applies for the term of the Copyright and
|
||||
Similar Rights licensed here. However, if You fail to comply with
|
||||
this Public License, then Your rights under this Public License
|
||||
terminate automatically.
|
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under
|
||||
Section 6(a), it reinstates:
|
||||
|
||||
1. automatically as of the date the violation is cured, provided
|
||||
it is cured within 30 days of Your discovery of the
|
||||
violation; or
|
||||
|
||||
2. upon express reinstatement by the Licensor.
|
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any
|
||||
right the Licensor may have to seek remedies for Your violations
|
||||
of this Public License.
|
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the
|
||||
Licensed Material under separate terms or conditions or stop
|
||||
distributing the Licensed Material at any time; however, doing so
|
||||
will not terminate this Public License.
|
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
||||
License.
|
||||
|
||||
|
||||
Section 7 -- Other Terms and Conditions.
|
||||
|
||||
a. The Licensor shall not be bound by any additional or different
|
||||
terms or conditions communicated by You unless expressly agreed.
|
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the
|
||||
Licensed Material not stated herein are separate from and
|
||||
independent of the terms and conditions of this Public License.
|
||||
|
||||
|
||||
Section 8 -- Interpretation.
|
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and
|
||||
shall not be interpreted to, reduce, limit, restrict, or impose
|
||||
conditions on any use of the Licensed Material that could lawfully
|
||||
be made without permission under this Public License.
|
||||
|
||||
b. To the extent possible, if any provision of this Public License is
|
||||
deemed unenforceable, it shall be automatically reformed to the
|
||||
minimum extent necessary to make it enforceable. If the provision
|
||||
cannot be reformed, it shall be severed from this Public License
|
||||
without affecting the enforceability of the remaining terms and
|
||||
conditions.
|
||||
|
||||
c. No term or condition of this Public License will be waived and no
|
||||
failure to comply consented to unless expressly agreed to by the
|
||||
Licensor.
|
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted
|
||||
as a limitation upon, or waiver of, any privileges and immunities
|
||||
that apply to the Licensor or You, including from the legal
|
||||
processes of any jurisdiction or authority.
|
||||
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons is not a party to its public
|
||||
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
||||
its public licenses to material it publishes and in those instances
|
||||
will be considered the “Licensor.” The text of the Creative Commons
|
||||
public licenses is dedicated to the public domain under the CC0 Public
|
||||
Domain Dedication. Except for the limited purpose of indicating that
|
||||
material is shared under a Creative Commons public license or as
|
||||
otherwise permitted by the Creative Commons policies published at
|
||||
creativecommons.org/policies, Creative Commons does not authorize the
|
||||
use of the trademark "Creative Commons" or any other trademark or logo
|
||||
of Creative Commons without its prior written consent including,
|
||||
without limitation, in connection with any unauthorized modifications
|
||||
to any of its public licenses or any other arrangements,
|
||||
understandings, or agreements concerning use of licensed material. For
|
||||
the avoidance of doubt, this paragraph does not form part of the
|
||||
public licenses.
|
||||
|
||||
Creative Commons may be contacted at creativecommons.org.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -309,6 +309,7 @@ class VirtualKeyboard(QFrame):
|
||||
|
||||
backspace = QPushButton('⌫')
|
||||
backspace.setFixedSize(fixed_w, fixed_h)
|
||||
backspace.setProperty("sound_event", False)
|
||||
backspace.pressed.connect(self.on_backspace_pressed)
|
||||
backspace.released.connect(self.stop_backspace_repeat)
|
||||
# Add gamepad icon for Backspace (X/Triangle)
|
||||
@@ -422,6 +423,8 @@ class VirtualKeyboard(QFrame):
|
||||
"""Move focus up across keyboard buttons with fixed speed"""
|
||||
current_time = self.get_current_time()
|
||||
if current_time - self.last_focus_time >= self.focus_delay:
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
SoundManager().play("navigate")
|
||||
self.focusNextKey("up")
|
||||
self.last_focus_time = current_time
|
||||
|
||||
@@ -429,6 +432,8 @@ class VirtualKeyboard(QFrame):
|
||||
"""Move focus down across keyboard buttons with fixed speed"""
|
||||
current_time = self.get_current_time()
|
||||
if current_time - self.last_focus_time >= self.focus_delay:
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
SoundManager().play("navigate")
|
||||
self.focusNextKey("down")
|
||||
self.last_focus_time = current_time
|
||||
|
||||
@@ -436,6 +441,8 @@ class VirtualKeyboard(QFrame):
|
||||
"""Move focus left across keyboard buttons with fixed speed"""
|
||||
current_time = self.get_current_time()
|
||||
if current_time - self.last_focus_time >= self.focus_delay:
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
SoundManager().play("navigate")
|
||||
self.focusNextKey("left")
|
||||
self.last_focus_time = current_time
|
||||
|
||||
@@ -443,6 +450,8 @@ class VirtualKeyboard(QFrame):
|
||||
"""Move focus right across keyboard buttons with fixed speed"""
|
||||
current_time = self.get_current_time()
|
||||
if current_time - self.last_focus_time >= self.focus_delay:
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
SoundManager().play("navigate")
|
||||
self.focusNextKey("right")
|
||||
self.last_focus_time = current_time
|
||||
|
||||
@@ -463,6 +472,8 @@ class VirtualKeyboard(QFrame):
|
||||
return position[:2] # row, col
|
||||
|
||||
def on_button_click(self, key):
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
SoundManager().play("keyboard_key")
|
||||
if key in ['TAB', 'CAPS', '⬆']:
|
||||
if key == 'TAB':
|
||||
self.on_tab_click()
|
||||
@@ -530,6 +541,8 @@ class VirtualKeyboard(QFrame):
|
||||
text = self.current_input_widget.text()
|
||||
|
||||
if cursor_pos > 0:
|
||||
from portprotonqt.sound_manager import SoundManager
|
||||
SoundManager().play("keyboard_key")
|
||||
new_text = text[:cursor_pos - 1] + text[cursor_pos:]
|
||||
self.current_input_widget.setText(new_text)
|
||||
self.current_input_widget.setCursorPosition(cursor_pos - 1)
|
||||
|
||||
@@ -7,9 +7,11 @@ from types import SimpleNamespace
|
||||
from typing import Any, cast
|
||||
|
||||
from pytest import MonkeyPatch
|
||||
from PySide6.QtCore import Qt
|
||||
|
||||
from portprotonqt.animations.library_controls import _animation_duration
|
||||
from portprotonqt.detail_pages import DetailPageManager
|
||||
from portprotonqt.game_library_manager import GameLibraryManager
|
||||
from portprotonqt.main_window import MainWindow
|
||||
from portprotonqt.portproton_api import remove_empty_custom_data_dirs
|
||||
import portprotonqt.tabs.autoinstall_tab as autoinstall_tab_module
|
||||
@@ -588,6 +590,26 @@ def test_launch_autoinstall_checks_alt_i586_dependencies() -> None:
|
||||
assert window.installing is False
|
||||
|
||||
|
||||
def test_initial_library_card_focus_does_not_use_navigation_reason() -> None:
|
||||
focus_reasons: list[Qt.FocusReason] = []
|
||||
card = SimpleNamespace(
|
||||
isVisible=lambda: True,
|
||||
isEnabled=lambda: True,
|
||||
setFocus=lambda reason: focus_reasons.append(reason),
|
||||
)
|
||||
manager: Any = GameLibraryManager.__new__(GameLibraryManager)
|
||||
manager.main_window = SimpleNamespace(
|
||||
stackedWidget=SimpleNamespace(currentIndex=lambda: 0),
|
||||
)
|
||||
manager.gamesListWidget = SimpleNamespace(findChildren=lambda _type: [card])
|
||||
manager.gamesScrollArea = None
|
||||
manager._focus_first_card_after_update = True
|
||||
|
||||
manager._focus_first_visible_card()
|
||||
|
||||
assert focus_reasons == [Qt.FocusReason.ActiveWindowFocusReason]
|
||||
|
||||
|
||||
def test_launch_dependency_percent_updates_button_before_status() -> None:
|
||||
window: Any = MainWindow.__new__(MainWindow)
|
||||
button = FakeButton()
|
||||
@@ -614,6 +636,7 @@ def test_toggle_game_replaces_invalid_launch_output_bytes(
|
||||
exe_path.write_text("", encoding="utf-8")
|
||||
process = object()
|
||||
popen_kwargs: dict[str, object] = {}
|
||||
launch_events: list[str] = []
|
||||
window: Any = MainWindow.__new__(MainWindow)
|
||||
window.start_sh = ["portproton"]
|
||||
window.game_processes = []
|
||||
@@ -623,10 +646,15 @@ def test_toggle_game_replaces_invalid_launch_output_bytes(
|
||||
window.games = []
|
||||
|
||||
def fake_popen(_command: list[str], **kwargs: object) -> object:
|
||||
launch_events.append("popen")
|
||||
popen_kwargs.update(kwargs)
|
||||
return process
|
||||
|
||||
monkeypatch.setattr("portprotonqt.main_window.subprocess.Popen", fake_popen)
|
||||
monkeypatch.setattr(
|
||||
"portprotonqt.main_window.SoundManager",
|
||||
lambda: SimpleNamespace(play=launch_events.append),
|
||||
)
|
||||
monkeypatch.setattr("portprotonqt.main_window.QTimer", FakeTimer)
|
||||
monkeypatch.setattr("portprotonqt.main_window.save_last_launch", lambda *_args: None)
|
||||
monkeypatch.setattr(window, "_check_alt_i586_dependencies_before_launch", lambda: True)
|
||||
@@ -640,6 +668,7 @@ def test_toggle_game_replaces_invalid_launch_output_bytes(
|
||||
assert popen_kwargs["text"] is True
|
||||
assert popen_kwargs["errors"] == "replace"
|
||||
assert window.input_manager.suspended
|
||||
assert launch_events == ["popen", "game_launch"]
|
||||
|
||||
|
||||
def test_process_portproton_desktop_calls_callback_without_asset_download(
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
"""Tests for UI sound playback and input integration."""
|
||||
|
||||
import types
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, cast
|
||||
from unittest.mock import Mock
|
||||
|
||||
from PySide6.QtCore import QEvent, QObject, QPointF, Qt
|
||||
from PySide6.QtGui import QMouseEvent
|
||||
from PySide6.QtWidgets import QApplication, QComboBox, QMenu, QPushButton, QWidget
|
||||
from pytest import MonkeyPatch
|
||||
|
||||
import portprotonqt.input_manager as input_manager
|
||||
import portprotonqt.main_window as main_window
|
||||
import portprotonqt.tabs.system_tab as system_tab
|
||||
from portprotonqt.input_manager import InputManager
|
||||
from portprotonqt.main_window import MainWindow
|
||||
from portprotonqt.sound_manager import SOUND_EVENTS, SoundManager, _SoundSlot
|
||||
from portprotonqt.tabs.system_tab import MainWindowSystemTabMixin
|
||||
|
||||
|
||||
def test_sound_manager_resets_slots_when_sound_dirs_change() -> None:
|
||||
slots = [Mock(), Mock()]
|
||||
manager: Any = object.__new__(SoundManager)
|
||||
manager._sounds_dirs = ["old"]
|
||||
manager._url_cache = {"click": object()}
|
||||
manager._slots = slots
|
||||
|
||||
manager.set_sounds_dirs(["new"])
|
||||
|
||||
assert manager._url_cache == {}
|
||||
assert all(slot.reset.called for slot in slots)
|
||||
|
||||
|
||||
def test_sound_manager_reuses_slot_for_same_event() -> None:
|
||||
loaded_slot = Mock(_loaded_event="navigate")
|
||||
other_slot = Mock(_loaded_event=None)
|
||||
manager: Any = object.__new__(SoundManager)
|
||||
manager._enabled = True
|
||||
manager._slots = [loaded_slot, other_slot]
|
||||
manager._slot_index = 1
|
||||
manager._get_url = lambda _event: Mock()
|
||||
|
||||
manager.play("navigate")
|
||||
|
||||
loaded_slot.play.assert_called_once()
|
||||
other_slot.play.assert_not_called()
|
||||
assert manager._slot_index == 1
|
||||
|
||||
|
||||
def test_sound_slot_stops_at_end_of_media() -> None:
|
||||
end_of_media = object()
|
||||
slot: Any = object.__new__(_SoundSlot)
|
||||
slot._player = Mock()
|
||||
slot._player.MediaStatus.EndOfMedia = end_of_media
|
||||
|
||||
slot._handle_media_status(end_of_media)
|
||||
|
||||
slot._player.stop.assert_called_once()
|
||||
|
||||
|
||||
def test_sound_manager_skips_unsafe_sound_variant(tmp_path: Path) -> None:
|
||||
sounds_dir = tmp_path / "sounds"
|
||||
sounds_dir.mkdir()
|
||||
(sounds_dir / "navigate.ogg").write_bytes(b"not audio")
|
||||
safe_sound = sounds_dir / "navigate.wav"
|
||||
safe_sound.write_bytes(b"RIFF\x00\x00\x00\x00WAVE" + b"\x00" * 32)
|
||||
manager: Any = object.__new__(SoundManager)
|
||||
manager._sounds_dirs = [str(sounds_dir)]
|
||||
|
||||
assert manager._find_sound_path("navigate") == safe_sound
|
||||
|
||||
|
||||
def test_standard_theme_provides_all_sound_events() -> None:
|
||||
sounds_dir = Path(__file__).parent.parent / "portprotonqt" / "themes" / "standart" / "sounds"
|
||||
manager: Any = object.__new__(SoundManager)
|
||||
manager._sounds_dirs = [str(sounds_dir)]
|
||||
|
||||
assert all(manager._find_sound_path(event) is not None for event in SOUND_EVENTS)
|
||||
|
||||
|
||||
def test_widget_sound_uses_semantic_event() -> None:
|
||||
manager: Any = object.__new__(SoundManager)
|
||||
manager.play = Mock()
|
||||
widget = types.SimpleNamespace(property=lambda name: "open" if name == "sound_event" else None)
|
||||
|
||||
manager.play_widget_sound(widget)
|
||||
|
||||
manager.play.assert_called_once_with("open")
|
||||
|
||||
|
||||
def test_widget_sound_can_disable_automatic_feedback() -> None:
|
||||
manager: Any = object.__new__(SoundManager)
|
||||
manager.play = Mock()
|
||||
widget = types.SimpleNamespace(property=lambda name: False if name == "sound_event" else None)
|
||||
|
||||
manager.play_widget_sound(widget)
|
||||
|
||||
manager.play.assert_not_called()
|
||||
|
||||
|
||||
def test_combo_box_uses_open_sound() -> None:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
manager: Any = object.__new__(SoundManager)
|
||||
manager.play = Mock()
|
||||
|
||||
manager.play_widget_sound(QComboBox())
|
||||
|
||||
manager.play.assert_called_once_with("open")
|
||||
assert app is not None
|
||||
|
||||
|
||||
def test_gamepad_connection_sound_skips_initial_device(monkeypatch: MonkeyPatch) -> None:
|
||||
played_events: list[str] = []
|
||||
duplicate_closed: list[bool] = []
|
||||
gamepads = [
|
||||
SimpleNamespace(path="/dev/input/js0", name="Gamepad", close=lambda: None),
|
||||
SimpleNamespace(path="/dev/input/js0", name="Gamepad", close=lambda: duplicate_closed.append(True)),
|
||||
]
|
||||
manager: Any = InputManager.__new__(InputManager)
|
||||
manager._gamepad_polling_suspended = False
|
||||
manager._initial_gamepad_check = True
|
||||
manager.gamepad = None
|
||||
manager.find_gamepad = lambda: gamepads.pop(0)
|
||||
manager.detect_gamepad_axes = lambda _gamepad: None
|
||||
manager._reset_input_state = lambda: None
|
||||
manager._get_effective_gamepad_type = lambda _gamepad: "xbox"
|
||||
manager._refresh_gamepad_ui = lambda: None
|
||||
monkeypatch.setattr(input_manager, "SoundManager", lambda: SimpleNamespace(play=played_events.append))
|
||||
monkeypatch.setattr(input_manager.display_config, "get_auto_fullscreen_gamepad", lambda: False)
|
||||
|
||||
manager.check_gamepad()
|
||||
manager._initial_gamepad_check = False
|
||||
manager.check_gamepad()
|
||||
|
||||
assert played_events == []
|
||||
assert duplicate_closed == [True]
|
||||
|
||||
|
||||
def test_gamepad_connection_sound_plays_after_startup(monkeypatch: MonkeyPatch) -> None:
|
||||
played_events: list[str] = []
|
||||
manager: Any = InputManager.__new__(InputManager)
|
||||
manager._gamepad_polling_suspended = False
|
||||
manager._initial_gamepad_check = False
|
||||
manager.gamepad = None
|
||||
manager.find_gamepad = lambda: SimpleNamespace(path="/dev/input/js0", name="Gamepad", close=lambda: None)
|
||||
manager.detect_gamepad_axes = lambda _gamepad: None
|
||||
manager._reset_input_state = lambda: None
|
||||
manager._get_effective_gamepad_type = lambda _gamepad: "xbox"
|
||||
manager._refresh_gamepad_ui = lambda: None
|
||||
monkeypatch.setattr(input_manager, "SoundManager", lambda: SimpleNamespace(play=played_events.append))
|
||||
monkeypatch.setattr(input_manager.display_config, "get_auto_fullscreen_gamepad", lambda: False)
|
||||
|
||||
manager.check_gamepad()
|
||||
|
||||
assert played_events == ["gamepad_connect"]
|
||||
|
||||
|
||||
def test_menu_navigation_plays_sound(monkeypatch: MonkeyPatch) -> None:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
menu = QMenu()
|
||||
first_action = menu.addAction("First")
|
||||
second_action = menu.addAction("Second")
|
||||
menu.setActiveAction(first_action)
|
||||
played_events: list[str] = []
|
||||
manager: Any = InputManager.__new__(InputManager)
|
||||
monkeypatch.setattr(input_manager, "SoundManager", lambda: SimpleNamespace(play=played_events.append))
|
||||
|
||||
manager._navigate_menu_actions(menu, direction_down=True)
|
||||
|
||||
assert menu.activeAction() is second_action
|
||||
assert played_events == ["navigate"]
|
||||
assert app is not None
|
||||
|
||||
|
||||
def test_menu_show_plays_open_sound(monkeypatch: MonkeyPatch) -> None:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
played_events: list[str] = []
|
||||
manager = InputManager.__new__(InputManager)
|
||||
QObject.__init__(manager)
|
||||
monkeypatch.setattr(input_manager, "SoundManager", lambda: SimpleNamespace(play=played_events.append))
|
||||
|
||||
manager.eventFilter(QMenu(), QEvent(QEvent.Type.Show))
|
||||
|
||||
assert played_events == ["open"]
|
||||
assert app is not None
|
||||
|
||||
|
||||
def test_combo_popup_show_plays_open_sound(monkeypatch: MonkeyPatch) -> None:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
played_events: list[str] = []
|
||||
manager = InputManager.__new__(InputManager)
|
||||
QObject.__init__(manager)
|
||||
combo = QComboBox()
|
||||
popup = QWidget(combo, Qt.WindowType.Popup)
|
||||
monkeypatch.setattr(input_manager, "SoundManager", lambda: SimpleNamespace(play=played_events.append))
|
||||
|
||||
manager.eventFilter(popup, QEvent(QEvent.Type.Show))
|
||||
|
||||
assert played_events == ["open"]
|
||||
assert app is not None
|
||||
|
||||
|
||||
def test_combo_show_does_not_play_open_sound(monkeypatch: MonkeyPatch) -> None:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
played_events: list[str] = []
|
||||
manager = InputManager.__new__(InputManager)
|
||||
QObject.__init__(manager)
|
||||
monkeypatch.setattr(input_manager, "SoundManager", lambda: SimpleNamespace(play=played_events.append))
|
||||
|
||||
manager.eventFilter(QComboBox(), QEvent(QEvent.Type.Show))
|
||||
|
||||
assert played_events == []
|
||||
assert app is not None
|
||||
|
||||
|
||||
def test_right_mouse_button_does_not_play_widget_sound(monkeypatch: MonkeyPatch) -> None:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
played_widgets: list[object] = []
|
||||
manager = InputManager.__new__(InputManager)
|
||||
QObject.__init__(manager)
|
||||
sound_manager = SimpleNamespace(play_widget_sound=played_widgets.append)
|
||||
monkeypatch.setattr(input_manager, "SoundManager", lambda: sound_manager)
|
||||
event = QMouseEvent(
|
||||
QEvent.Type.MouseButtonRelease,
|
||||
QPointF(),
|
||||
QPointF(),
|
||||
QPointF(),
|
||||
Qt.MouseButton.RightButton,
|
||||
Qt.MouseButton.NoButton,
|
||||
Qt.KeyboardModifier.NoModifier,
|
||||
)
|
||||
|
||||
manager.eventFilter(QPushButton(), event)
|
||||
|
||||
assert played_widgets == []
|
||||
assert app is not None
|
||||
|
||||
|
||||
def test_system_section_change_plays_tab_sound(monkeypatch: MonkeyPatch) -> None:
|
||||
played_events: list[str] = []
|
||||
section_stack = SimpleNamespace(
|
||||
count=lambda: 2,
|
||||
currentIndex=lambda: 0,
|
||||
setCurrentIndex=lambda _index: None,
|
||||
)
|
||||
buttons = [
|
||||
SimpleNamespace(isVisible=lambda: True, setChecked=lambda _checked: None),
|
||||
SimpleNamespace(isVisible=lambda: True, setChecked=lambda _checked: None),
|
||||
]
|
||||
window = SimpleNamespace(
|
||||
systemSectionStack=section_stack,
|
||||
systemSectionButtons=buttons,
|
||||
_focusCurrentSystemSection=lambda _index: None,
|
||||
)
|
||||
monkeypatch.setattr(system_tab, "SoundManager", lambda: SimpleNamespace(play=played_events.append))
|
||||
|
||||
changed = MainWindowSystemTabMixin.switchSystemSection(cast(Any, window), 1)
|
||||
|
||||
assert changed is True
|
||||
assert played_events == ["tab_switch"]
|
||||
|
||||
|
||||
def test_autoinstall_tab_defers_loading_until_after_sound(monkeypatch: MonkeyPatch) -> None:
|
||||
calls: list[str] = []
|
||||
scheduled: list[object] = []
|
||||
button = SimpleNamespace(isVisible=lambda: True, setChecked=lambda _checked: None)
|
||||
stack = SimpleNamespace(setCurrentIndex=lambda _index: None, currentIndex=lambda: 1)
|
||||
window = SimpleNamespace(
|
||||
tabButtons={1: button},
|
||||
stackedWidget=stack,
|
||||
auto_install_tab_index=1,
|
||||
system_tab_index=-1,
|
||||
_start_autoinstall_load=lambda: calls.append("load"),
|
||||
_close_library_controls=lambda: None,
|
||||
)
|
||||
monkeypatch.setattr(main_window, "SoundManager", lambda: SimpleNamespace(play=calls.append))
|
||||
monkeypatch.setattr(main_window.QTimer, "singleShot", lambda _delay, callback: scheduled.append(callback))
|
||||
|
||||
MainWindow.switchTab(cast(Any, window), 1)
|
||||
|
||||
assert calls == ["tab_switch"]
|
||||
assert scheduled == [window._start_autoinstall_load]
|
||||
@@ -9,6 +9,7 @@ from portprotonqt.theme_security import (
|
||||
check_theme_safety,
|
||||
is_safe_font_file,
|
||||
is_safe_image_file,
|
||||
is_safe_sound_file,
|
||||
)
|
||||
|
||||
THEMES_DIR = Path(__file__).resolve().parent.parent / "portprotonqt" / "themes"
|
||||
@@ -396,6 +397,34 @@ class TestFontSafety:
|
||||
assert is_safe_font_file(str(f))
|
||||
|
||||
|
||||
class TestSoundSafety:
|
||||
@pytest.mark.parametrize(
|
||||
("extension", "header"),
|
||||
[
|
||||
(".ogg", b"OggS"),
|
||||
(".oga", b"OggS"),
|
||||
(".opus", b"OggS"),
|
||||
(".wav", b"RIFF\x00\x00\x00\x00WAVE"),
|
||||
(".mp3", b"ID3"),
|
||||
(".flac", b"fLaC"),
|
||||
(".m4a", b"\x00\x00\x00\x10ftyp"),
|
||||
(".aac", b"\xff\xf1"),
|
||||
(".webm", b"\x1a\x45\xdf\xa3"),
|
||||
],
|
||||
)
|
||||
def test_supported_signatures(
|
||||
self, tmp_path: Path, extension: str, header: bytes,
|
||||
) -> None:
|
||||
sound = tmp_path / f"sound{extension}"
|
||||
sound.write_bytes(header + b"\x00" * 32)
|
||||
assert is_safe_sound_file(str(sound))
|
||||
|
||||
def test_rejects_disguised_sound(self, tmp_path: Path) -> None:
|
||||
sound = tmp_path / "sound.ogg"
|
||||
sound.write_bytes(b"not audio")
|
||||
assert not is_safe_sound_file(str(sound))
|
||||
|
||||
|
||||
# === Image safety ===
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user