From a9765826a878939a17c3ffe358382f3be7013362 Mon Sep 17 00:00:00 2001 From: fruzizela Date: Sun, 25 Oct 2026 05:37:25 +0530 Subject: [PATCH 1/9] feat(ui): add Wine Prefix to game cards and tables. --- portprotonqt/config/ui.py | 8 + portprotonqt/game_card.py | 242 +++++++++++++++++- portprotonqt/game_library_manager.py | 55 +++- portprotonqt/tabs/settings_tab.py | 33 ++- portprotonqt/themes/standart-light/styles.py | 28 +- .../themes/standart/styles/constants.py | 6 +- .../themes/standart/styles/game_card.py | 29 ++- 7 files changed, 381 insertions(+), 20 deletions(-) diff --git a/portprotonqt/config/ui.py b/portprotonqt/config/ui.py index 44b374d1..3358c974 100644 --- a/portprotonqt/config/ui.py +++ b/portprotonqt/config/ui.py @@ -537,6 +537,14 @@ class UIConfig(BaseConfig): validate_bool(enabled, "disable_alt_i586_dependency_check") self._save_value("disable_alt_i586_dependency_check", enabled, "bool") + def get_show_wine_prefix_cards(self) -> bool: + """Get whether to display Wine version and Prefix name on game cards.""" + return self._get_bool("show_wine_prefix_cards", True) + + def set_show_wine_prefix_cards(self, enabled: bool) -> None: + """Set whether to display Wine version and Prefix name on game cards.""" + validate_bool(enabled, "show_wine_prefix_cards") + self._save_value("show_wine_prefix_cards", enabled, "bool") def load_theme_metainfo(theme_name: str) -> dict: """Load theme metadata from metainfo.ini.""" diff --git a/portprotonqt/game_card.py b/portprotonqt/game_card.py index 81d0bf96..05f9a7ad 100644 --- a/portprotonqt/game_card.py +++ b/portprotonqt/game_card.py @@ -19,7 +19,10 @@ from PySide6.QtGui import ( QKeyEvent, QPaintEvent, ) -from PySide6.QtCore import QEvent, Signal, Property, Qt, QUrl, QTimer, QSize +from PySide6.QtCore import QEvent, Signal, Property, Qt, QUrl, QTimer, QSize, QRunnable, QObject, Slot, QThreadPool + +from portprotonqt.logger import get_logger + from PySide6.QtWidgets import ( QApplication, QFrame, @@ -59,6 +62,81 @@ def is_valid_protondb_tier(tier: str | None) -> bool: """Check if ProtonDB tier is supported.""" return bool(tier) and tier.lower() in PROTONDB_TIERS +def show_wine_prefix_columns(theme) -> bool: + """Whether to show columns Wine/Prefix — single condition for cards and titles.""" + show = getattr(ui_config, "get_show_wine_prefix_cards", lambda: True)() + required = ( + "WINE_PREFIX_CARD_HEIGHT", + "wine_prefix_margin", + "wine_prefix_spacing", + "GAME_CARD_WINE_PREFIX_CONTAINER_STYLE", + "GAME_CARD_WINE_PREFIX_LOADING_STYLE", + ) + return show and all(hasattr(theme, attr) for attr in required) + +class TaskSignals(QObject): + """Transmitter class for signals from QRunnable.""" + result_ready = Signal(str, str) + +class WinePrefixTask(QRunnable, QObject): + """Task to extract Wine version and Prefix name from game files.""" + def __init__(self, game_source: str, exec_line: str, callback): + super().__init__() + self.game_source = game_source.lower() + self.exec_line = exec_line + self.signals = TaskSignals() + self.signals.result_ready.connect(callback) + self.setAutoDelete(True) + self._is_cancelled = False + + def cancel(self): + self._is_cancelled = True + + def run(self) -> None: + if self._is_cancelled: + return + + runtime_map = {"steam": "Steam Proton", "gog": "GOG Runtime", "egs": "Epic Proton"} + wine_version = runtime_map.get(self.game_source, _("Default")) + prefix_name = "default" + + if self.game_source in runtime_map: + self.signals.result_ready.emit(wine_version, prefix_name) + return + game_exe = GameCard._extract_executable_path(self.exec_line) + if not game_exe: + self.signals.result_ready.emit(wine_version, prefix_name) + return + + try: + with open(f"{game_exe}.ppdb", encoding="utf-8", errors="ignore") as file: + has_wine = has_prefix = False + + for line in file: + if self._is_cancelled: + return + + if not has_wine and (wine_match := re.search(r'export\s+PW_WINE_USE=["\']?(.*?)["\']?(?:\s|$)', line)): + wine_version = wine_match.group(1).strip() + has_wine = True + + if not has_prefix and (prefix_match := re.search(r'export\s+PW_PREFIX_NAME=["\']?(.*?)["\']?(?:\s|$)', line)): + prefix_name = prefix_match.group(1).strip() + has_prefix = True + + if has_wine and has_prefix: + break + except OSError: + pass + + if self._is_cancelled: + return + + if prefix_name in ("default", "") or not prefix_name.strip(): + prefix_name = os.environ.get("WINEPREFIX") or "default" + + if not self._is_cancelled: + self.signals.result_ready.emit(wine_version, prefix_name) class SourceCorner(QWidget): @@ -354,6 +432,7 @@ class GameCard(AnimatedCard): card_width=250, parent=None, context_menu_manager=None ): super().__init__(parent) + self.logger = get_logger(__name__) self.coverReady.connect(self.on_cover_loaded, Qt.ConnectionType.QueuedConnection) self.name = name self.description = description @@ -394,6 +473,7 @@ class GameCard(AnimatedCard): parent_mode or getattr(self.theme, "LIBRARY_LAYOUT_MODE", "grid") ).lower() self.list_layout = self.layout_mode in {"list", "vertical"} + self.show_wine_prefix_enabled = False self.vertical_layout = self.layout_mode == "vertical" self.horizontal_layout = self.layout_mode in {"horizontal", "horizontal_top"} self.economy_mode = ui_config.get_economy_mode() @@ -586,7 +666,7 @@ class GameCard(AnimatedCard): self.layout_.addWidget(self.nameLabel, stretches[0]) for text, stretch in zip( (self.last_launch, self.formatted_playtime, str(self.game_source)), - stretches[1:], + stretches[1:4], strict=True, ): label = QLabel(text) @@ -603,6 +683,7 @@ class GameCard(AnimatedCard): font_size = self.nameLabel.font().pointSizeF() self.base_font_size = font_size if font_size > 0 else 10.0 + self._initialize_wine_prefix_widgets() self.update_scale() @@ -615,6 +696,100 @@ class GameCard(AnimatedCard): layout.invalidate() parent.updateGeometry() + def _initialize_wine_prefix_widgets(self) -> None: + """Initialize Wine version and Prefix name widgets based on UI configuration.""" + try: + self._reset_wine_prefix_widgets() + self._check_layout_conditions() + + if not self.show_wine_prefix_enabled: + return + + self._setup_wine_prefix_layout() + + def safe_callback(wine, prefix): + try: + if hasattr(self, '_wine_task'): + self._wine_task = None + + if not self.show_wine_prefix_enabled: + return + + if hasattr(self, 'nameLabel') and self.nameLabel is not None: + self._update_wine_prefix(wine, prefix) + except Exception as e: + self.logger.error("Error processing callback information Wine Prefix", exc_info=e) + + self._wine_task = WinePrefixTask( + game_source=self.game_source, + exec_line=self.exec_line, + callback=safe_callback + ) + QThreadPool.globalInstance().start(self._wine_task) + + except Exception as e: + self.logger.error("Error initializing widgets Wine Prefix", exc_info=e) + + def _reset_wine_prefix_widgets(self): + self.wine_prefix_name_card = None + self.wine_version_label_card = None + self.wine_prefix_label_card = None + self.game_wine_label = None + self.game_prefix_label = None + + def _check_layout_conditions(self): + if self.list_layout and not self.vertical_layout: + self.show_wine_prefix_enabled = False + return + + self.show_wine_prefix_enabled = show_wine_prefix_columns(self.theme) + + def _setup_wine_prefix_layout(self): + self.update_scale() + + if self.vertical_layout: + self._setup_vertical_wine_layout() + else: + self._setup_horizontal_wine_layout() + + def _setup_vertical_wine_layout(self): + stretches = self.theme.GAME_CARD_VERTICAL["column_stretches"] + + self.game_wine_label = QLabel(f"Wine: {_('Loading...')}") + self.game_wine_label.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.game_wine_label.setProperty("theme_style_name", "GAME_CARD_COLUMN_LABEL_STYLE") + self.game_wine_label.setStyleSheet(self.theme.GAME_CARD_COLUMN_LABEL_STYLE) + self.game_wine_label.setWordWrap(True) + self.layout_.addWidget(self.game_wine_label, stretches[4] if len(stretches) > 4 else 2) + + self.game_prefix_label = QLabel(f"Prefix: {_('Loading...')}") + self.game_prefix_label.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.game_prefix_label.setProperty("theme_style_name", "GAME_CARD_COLUMN_LABEL_STYLE") + self.game_prefix_label.setStyleSheet(self.theme.GAME_CARD_COLUMN_LABEL_STYLE) + self.game_prefix_label.setWordWrap(True) + self.layout_.addWidget(self.game_prefix_label, stretches[5] if len(stretches) > 5 else 2) + + def _setup_horizontal_wine_layout(self): + self.wine_prefix_name_card = QFrame() + self.wine_prefix_name_card.setStyleSheet(self.theme.GAME_CARD_WINE_PREFIX_CONTAINER_STYLE) + self.wine_prefix_name_card.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum) + + prefix_layout = QVBoxLayout(self.wine_prefix_name_card) + prefix_layout.setContentsMargins(*self.theme.wine_prefix_margin) + prefix_layout.setSpacing(self.theme.wine_prefix_spacing) + + self.wine_version_label_card = QLabel(f"Wine: {_('Loading...')}") + self.wine_version_label_card.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) + self.wine_version_label_card.setStyleSheet(self.theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) + + self.wine_prefix_label_card = QLabel(f"Prefix: {_('Loading...')}") + self.wine_prefix_label_card.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) + self.wine_prefix_label_card.setStyleSheet(self.theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) + + prefix_layout.addWidget(self.wine_version_label_card) + prefix_layout.addWidget(self.wine_prefix_label_card) + self.layout_.addWidget(self.wine_prefix_name_card) + def refresh_theme(self, theme: Any) -> None: """Refresh cached card visuals after a live theme change.""" old_theme = self.theme @@ -675,6 +850,21 @@ class GameCard(AnimatedCard): else: self.animations.theme = theme self.update_favorite_icon() + + try: + if self.vertical_layout: + if self.game_wine_label is not None: + self.game_wine_label.setStyleSheet(theme.GAME_CARD_COLUMN_LABEL_STYLE) + if self.game_prefix_label is not None: + self.game_prefix_label.setStyleSheet(theme.GAME_CARD_COLUMN_LABEL_STYLE) + else: + if self.wine_version_label_card is not None: + self.wine_version_label_card.setStyleSheet(theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) + if self.wine_prefix_label_card is not None: + self.wine_prefix_label_card.setStyleSheet(theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) + except Exception as e: + self.logger.error("Error Update theme", exc_info=e) + layout_changed = ( old_layout_cfg != self.card_layout_cfg or old_theme.COMPACT_CARD != theme.COMPACT_CARD @@ -945,6 +1135,9 @@ class GameCard(AnimatedCard): self.theme.COMPACT_CARD["height_ratio"] if small_card_mode else self.card_geometry_cfg.get("card_height_ratio", 1.8) ) + if not self.horizontal_layout and self.show_wine_prefix_enabled: + height_ratio += self.theme.WINE_PREFIX_CARD_HEIGHT + scaled_height = int(self.base_card_width * height_ratio * self._scale) self.setFixedSize(scaled_width + scaled_extra, scaled_height + scaled_extra) cover_ratio = self.card_geometry_cfg.get("cover_aspect_ratio", 1.5) @@ -1043,6 +1236,17 @@ class GameCard(AnimatedCard): self.display_filter = display_filter self.economy_mode = ui_config.get_economy_mode() + + if self.wine_prefix_name_card is not None: + self.wine_prefix_name_card.setVisible(self.show_wine_prefix_enabled and not self.list_layout) + if self.vertical_layout: + if self.game_wine_label is not None: + self.game_wine_label.setVisible(self.show_wine_prefix_enabled) + if self.game_prefix_label is not None: + self.game_prefix_label.setVisible(self.show_wine_prefix_enabled) + + self.update_scale() + self.steam_visible = str(self.game_source).lower() == "steam" self.gog_visible = str(self.game_source).lower() == "gog" self.egs_visible = str(self.game_source).lower() == "egs" @@ -1195,6 +1399,33 @@ class GameCard(AnimatedCard): url = QUrl(f"https://www.protondb.com/app/{self.protondb_appid}") QDesktopServices.openUrl(url) + @Slot(str, str) + def _update_wine_prefix(self, wine_version: str, prefix_name: str) -> None: + """Update UI fields with formatting compatible with text wraps.""" + try: + if not hasattr(self, 'coverLabel') or self.coverLabel is None: + return + + if not self.show_wine_prefix_enabled: + return + + formatted_wine = wine_version.replace("-", "-\u200b").replace("_", "_\u200b") + formatted_prefix = prefix_name.replace("-", "-\u200b").replace("_", "_\u200b") + + if self.vertical_layout: + if self.game_wine_label is not None: + self.game_wine_label.setText(formatted_wine) + if self.game_prefix_label is not None: + self.game_prefix_label.setText(formatted_prefix) + else: + if self.wine_version_label_card is not None: + self.wine_version_label_card.setText(f"Wine: {formatted_wine}") + if self.wine_prefix_label_card is not None: + self.wine_prefix_label_card.setText(f"Prefix: {formatted_prefix}") + + except RuntimeError: + pass + def open_weanticheatyet_page(self): if self.anticheat_slug: url = QUrl(f"https://areweanticheatyet.com/game/{self.anticheat_slug}") @@ -1305,6 +1536,13 @@ class GameCard(AnimatedCard): def cleanup(self): """Clean up animations to prevent memory leaks when the card is destroyed.""" + if (task := getattr(self, '_wine_task', None)) is not None: + try: + task.cancel() + self._wine_task = None + except (RuntimeError, TypeError): + pass + if hasattr(self, 'coverLabel') and self.coverLabel is not None: cleanup_animated_cover(self.coverLabel) if hasattr(self, 'animations') and self.animations: diff --git a/portprotonqt/game_library_manager.py b/portprotonqt/game_library_manager.py index 424d0cdc..16a2e10d 100644 --- a/portprotonqt/game_library_manager.py +++ b/portprotonqt/game_library_manager.py @@ -8,7 +8,7 @@ from portprotonqt.search_utils import ( search_index, ) from PySide6.QtWidgets import QAbstractButton -from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QLabel, QFrame, QScrollArea, QSlider, QScroller, QStackedWidget +from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QGridLayout, QLabel, QFrame, QScrollArea, QSlider, QScroller, QStackedWidget, QSizePolicy from PySide6.QtCore import QElapsedTimer, QRect, QRectF, Qt, QTimer from PySide6.QtGui import QPaintEvent, QPainter, QPainterPath, QPixmap, QRegion from portprotonqt.custom_widgets import FlowLayout, AutoHideScrollArea @@ -18,7 +18,7 @@ from portprotonqt.localization import _ from portprotonqt.detail_pages.utils import remove_cover_background, setup_cover_background from portprotonqt.context_menu_manager import ContextMenuManager, CustomLineEdit from collections import deque - +from portprotonqt.game_card import show_wine_prefix_columns class FullLibraryTile(AnimatedCard): def __init__(self, theme: Any): @@ -170,6 +170,9 @@ class GameLibraryManager: self.libraryHeaderWidget = self._create_library_header() layout.addWidget(self.libraryHeaderWidget) layout.addWidget(scrollArea) + if self.layout_mode == "vertical": + self._sync_header_width() + scrollArea.viewportResized.connect(self._sync_header_width) # Slider for card size sliderLayout = QHBoxLayout() @@ -222,20 +225,50 @@ class GameLibraryManager: header_layout.setContentsMargins(*config["header_margins"]) header_layout.setSpacing(config["header_spacing"]) header_layout.addSpacing(config["header_cover_width"] + config["header_spacing"]) - labels = (_("Game Title"), _("LAST LAUNCH"), _("TIME SPENT"), _("Library")) - for text, stretch in zip(labels, config["column_stretches"], strict=True): + + base_labels = (_("Game Title"), _("LAST LAUNCH"), _("TIME SPENT"), _("Library")) + base_stretches = list(config.get("column_stretches", (4, 2, 2, 2))) + + if show_wine_prefix_columns(self.theme): + labels = base_labels + (_("WINE"), _("PREFIX")) + stretches = list(base_stretches) + while len(stretches) < len(labels): + stretches.append(2) + stretches = stretches[:len(labels)] + else: + labels = base_labels + stretches = base_stretches[:4] + + # Check WinePrefix for equality of list + if len(labels) != len(stretches): + raise ValueError("Number of marks is not equal to number of stretches") + for text, stretch in zip(labels, stretches, strict=True): label = QLabel(text.upper()) label.setAlignment( Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft - if text == labels[0] else Qt.AlignmentFlag.AlignCenter + if text == base_labels[0] else Qt.AlignmentFlag.AlignCenter ) label.setProperty("theme_style_name", "LIBRARY_HEADER_LABEL_STYLE") label.setStyleSheet(self.theme.LIBRARY_HEADER_LABEL_STYLE) + label.setMinimumWidth(0) + label.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) header_layout.addWidget(label, stretch) if self.gamesScrollArea is not None: header_layout.addSpacing(self.gamesScrollArea.verticalScrollBar().sizeHint().width()) return header + def _sync_header_width(self) -> None: + """Keeps header width equal to the card area width (scrollbar included).""" + if self.libraryHeaderWidget is None or self.gamesListWidget is None: + return + width = self.gamesListWidget.width() + if self.gamesScrollArea is not None: + scrollbar = self.gamesScrollArea.verticalScrollBar() + if scrollbar.isVisible(): + width += scrollbar.sizeHint().width() + if width > 50: + self.libraryHeaderWidget.setFixedWidth(width) + def rebuild_library_layout(self, layout_mode: str) -> None: """Replace the card layout when a theme changes its library mode.""" if self.gamesListWidget is None or self.gamesListLayout is None: @@ -284,13 +317,14 @@ class GameLibraryManager: if self.full_library_open and self.libraryBackgroundLabel is not None: remove_cover_background(self.libraryBackgroundLabel) self.layout_mode = layout_mode - if ( - layout_mode == "vertical" - and self.libraryHeaderWidget is None - and self.libraryContentLayout is not None - ): + if layout_mode == "vertical" and self.libraryContentLayout is not None: + if self.libraryHeaderWidget is not None: + self.libraryHeaderWidget.setParent(None) + self.libraryHeaderWidget.deleteLater() + self.libraryHeaderWidget = None self.libraryHeaderWidget = self._create_library_header() self.libraryContentLayout.insertWidget(1, self.libraryHeaderWidget) + self._sync_header_width() if self.libraryHeaderWidget is not None: self.libraryHeaderWidget.setVisible(layout_mode == "vertical") self.gamesListWidget.setProperty("library_layout_mode", layout_mode) @@ -565,6 +599,7 @@ class GameLibraryManager: self.gamesListLayout.invalidate() if self.gamesListWidget: self.gamesListWidget.updateGeometry() + self._sync_header_width() def _fit_horizontal_cards(self, card: GameCard | None = None) -> None: if self.layout_mode not in {"horizontal", "horizontal_top"}: diff --git a/portprotonqt/tabs/settings_tab.py b/portprotonqt/tabs/settings_tab.py index 72d03bcd..43f44052 100644 --- a/portprotonqt/tabs/settings_tab.py +++ b/portprotonqt/tabs/settings_tab.py @@ -345,6 +345,24 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase): hide_cursor_layout.addStretch() uiForm.addRow(hide_cursor_layout) + self.showWinePrefixCheckBox = QCheckBox() + self.showWinePrefixCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE) + self.showWinePrefixCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus) + self.showWinePrefixTitle = QLabel(_("Show Wine version and Prefix name on Game cards and Library vertical")) + self.showWinePrefixTitle.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) + self.showWinePrefixTitle.setStyleSheet(self.theme.SETTINGS_TITLE_CHECKBOX_STYLE) + self.showWinePrefixTitle.setFocusPolicy(Qt.FocusPolicy.NoFocus) + current_show_wine_prefix = ui_config.get_show_wine_prefix_cards() + self.showWinePrefixCheckBox.setChecked(current_show_wine_prefix) + self.showWinePrefixCheckBox.clicked.connect(self._on_show_wine_prefix_changed) + + show_wine_prefix_layout = QHBoxLayout() + show_wine_prefix_layout.setContentsMargins(0, 0, 0, 0) + show_wine_prefix_layout.addWidget(self.showWinePrefixCheckBox) + show_wine_prefix_layout.addWidget(self.showWinePrefixTitle) + show_wine_prefix_layout.addStretch() + uiForm.addRow(show_wine_prefix_layout) + self.autoFullscreenGamepadCheckBox = QCheckBox() self.autoFullscreenGamepadCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE) self.autoFullscreenGamepadCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus) @@ -907,6 +925,10 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase): layout.addLayout(actionsLayout) self.stackedWidget.addWidget(self.portProtonWidget) + def _on_show_wine_prefix_changed(self, checked: bool) -> None: + """Handle show wine/prefix checkbox toggle.""" + pass + def openGlobalGameSettings(self) -> None: from portprotonqt.dialogs.settings_dialog import ExeSettingsDialog @@ -1093,6 +1115,13 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase): display_config.set_auto_fullscreen_gamepad(auto_fullscreen_gamepad) display_config.set_boot_animation_enabled(not self.disableBootAnimationCheckBox.isChecked()) + # Save show WinePrefix setting from checkbox state + show_wine_prefix = self.showWinePrefixCheckBox.isChecked() + ui_config.set_show_wine_prefix_cards(show_wine_prefix) + + if hasattr(self, "game_library_manager") and self.game_library_manager is not None: + self.game_library_manager.rebuild_library_layout(self.game_library_manager.layout_mode) + hide_control_hints = self.hideControlHintsCheckBox.isChecked() ui_config.set_hide_control_hints(hide_control_hints) force_english = self.forceEnglishCheckBox.isChecked() @@ -1164,9 +1193,9 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase): self.keyboard.update_keyboard() if economy_mode_changed: - if self.game_library_manager.gamesListLayout is not None: + if self.game_library_manager is not None and self.game_library_manager.gamesListLayout is not None: self.game_library_manager.clear_layout(self.game_library_manager.gamesListLayout) - else: + elif self.game_library_manager is not None: display_filter = game_config.get_display_filter() for card in self.game_library_manager.game_card_cache.values(): card.update_badge_visibility(display_filter) diff --git a/portprotonqt/themes/standart-light/styles.py b/portprotonqt/themes/standart-light/styles.py index 2a865ff9..7a13077c 100644 --- a/portprotonqt/themes/standart-light/styles.py +++ b/portprotonqt/themes/standart-light/styles.py @@ -397,7 +397,25 @@ MAIN_WINDOW_STYLE = f""" background-color: {color_accent}; }} """ - +# GAME CARD STYLE WinePrefix Badge Container +GAME_CARD_WINE_PREFIX_CONTAINER_STYLE = f""" + QFrame {{ + background: {color_surface_elevated}; + border-radius: {border_radius_small}; + border: {border_none} {color_transparent}; + }} +""" +# GAME CARD STYLE WinePrefix +GAME_CARD_WINE_PREFIX_LOADING_STYLE = f""" + QLabel {{ + color: {color_text_dark}; + font-family: '{font_family}'; + font-size: 13px; + background: {color_transparent}; + qproperty-alignment: 'AlignLeft | AlignVCenter'; + qproperty-wordWrap: false; + }} +""" # Favorite Star FAVORITE_LABEL_STYLE = f"color: {color_favorite_star}; font-size: 32px; background: {color_transparent};" @@ -799,8 +817,12 @@ GAME_CARD_NAME_LABEL_STYLE = f""" }} """ -GAME_CARD_VERTICAL_NAME_STYLE = GAME_CARD_NAME_LABEL_STYLE - +GAME_CARD_VERTICAL_NAME_STYLE = f""" + {GAME_CARD_NAME_LABEL_STYLE} + QLabel {{ + background-color: {color_transparent}; + }} +""" GAME_CARD_COLUMN_LABEL_STYLE = f""" QLabel {{ color: {color_text_dark}; diff --git a/portprotonqt/themes/standart/styles/constants.py b/portprotonqt/themes/standart/styles/constants.py index 2b8ff901..4b4605e9 100644 --- a/portprotonqt/themes/standart/styles/constants.py +++ b/portprotonqt/themes/standart/styles/constants.py @@ -32,6 +32,10 @@ fullLibraryTileSize = (180, 180) fullLibraryTileColumns = 2 fullLibraryTileRows = 2 fullLibraryTileRadius = 10 +# WinePrefix constants +wine_prefix_margin = (8, 4, 6, 4) +wine_prefix_spacing = 1 +WINE_PREFIX_CARD_HEIGHT = 0.10 GAME_CARD_LIST = { "extra_margin": 8, "spacing": 12, @@ -71,7 +75,7 @@ GAME_CARD_VERTICAL = { "header_margins": (4, 0, 4, 0), "header_spacing": 12, "header_cover_width": 66, - "column_stretches": (4, 2, 2, 2), + "column_stretches": (4, 2, 2, 2, 2, 2), } downloadsSummaryHeight = 96 downloadsTableHeaderHeight = 38 diff --git a/portprotonqt/themes/standart/styles/game_card.py b/portprotonqt/themes/standart/styles/game_card.py index a547d21d..d0f99d96 100644 --- a/portprotonqt/themes/standart/styles/game_card.py +++ b/portprotonqt/themes/standart/styles/game_card.py @@ -1,5 +1,25 @@ from .constants import * - +# GAME CARD STYLE WinePrefix Badge Container +GAME_CARD_WINE_PREFIX_CONTAINER_STYLE = f""" + QFrame {{ + background: {color_detail_overlay}; + border-radius: {border_radius_small}; + border: {border_none} {color_transparent}; + margin-top: 4px; + margin-bottom: 2px; + }} +""" +# GAME CARD STYLE WinePrefix +GAME_CARD_WINE_PREFIX_LOADING_STYLE = f""" + QLabel {{ + color: {color_text_muted}; + font-family: '{font_family}'; + font-size: 12px; + background: {color_transparent}; + qproperty-alignment: 'AlignLeft | AlignVCenter'; + qproperty-wordWrap: false; + }} +""" # GAME CARD STYLE (GAMECARD) GAME_CARD_WINDOW_STYLE = f""" QFrame {{ @@ -28,7 +48,12 @@ GAME_CARD_NAME_LABEL_STYLE = f""" }} """ -GAME_CARD_VERTICAL_NAME_STYLE = GAME_CARD_NAME_LABEL_STYLE +GAME_CARD_VERTICAL_NAME_STYLE = f""" + {GAME_CARD_NAME_LABEL_STYLE} + QLabel {{ + background-color: {color_transparent}; + }} +""" GAME_CARD_COLUMN_LABEL_STYLE = f""" QLabel {{ -- 2.54.1 From 01e754bef531a35f9f3ecdc815c30209ea0c56e6 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sun, 25 Oct 2026 00:02:48 +0000 Subject: [PATCH 2/9] chore(deps): update https://git.linux-gaming.ru/actions/setup-python digest to 6d4fd22 --- .gitea/workflows/generate-appid.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitea/workflows/generate-appid.yml b/.gitea/workflows/generate-appid.yml index 7573e8e1..50911fe6 100644 --- a/.gitea/workflows/generate-appid.yml +++ b/.gitea/workflows/generate-appid.yml @@ -14,7 +14,7 @@ jobs: uses: https://git.linux-gaming.ru/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - name: Set up Python - uses: https://git.linux-gaming.ru/actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7 + uses: https://git.linux-gaming.ru/actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7 with: python-version-file: "pyproject.toml" -- 2.54.1 From 2ab0454deb8b372b0e1bf56e8458a9fe59439cda Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Sun, 25 Oct 2026 00:02:45 +0000 Subject: [PATCH 3/9] chore(deps): update archlinux:base-devel docker digest to 3cbf69d --- .gitea/workflows/code-check.yml | 2 +- .gitea/workflows/package-build.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitea/workflows/code-check.yml b/.gitea/workflows/code-check.yml index 3cb14d4c..086b3559 100644 --- a/.gitea/workflows/code-check.yml +++ b/.gitea/workflows/code-check.yml @@ -22,7 +22,7 @@ jobs: name: Check code runs-on: ubuntu-latest container: - image: archlinux:base-devel@sha256:061679925e5d5028f2df9395d441ce6c4b9accf0157ff3486c06b6962e014ef1 + image: archlinux:base-devel@sha256:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1 steps: - name: Configure Arch mirror run: | diff --git a/.gitea/workflows/package-build.yml b/.gitea/workflows/package-build.yml index d8c82e43..5d551f74 100644 --- a/.gitea/workflows/package-build.yml +++ b/.gitea/workflows/package-build.yml @@ -80,7 +80,7 @@ jobs: needs: changes if: needs.changes.outputs.appimage == 'true' || github.event_name == 'workflow_dispatch' container: - image: archlinux:base-devel@sha256:061679925e5d5028f2df9395d441ce6c4b9accf0157ff3486c06b6962e014ef1 + image: archlinux:base-devel@sha256:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1 options: --privileged --device /dev/fuse steps: - name: Configure Arch mirror @@ -195,7 +195,7 @@ jobs: needs: changes if: needs.changes.outputs.arch == 'true' || github.event_name == 'workflow_dispatch' container: - image: archlinux:base-devel@sha256:061679925e5d5028f2df9395d441ce6c4b9accf0157ff3486c06b6962e014ef1 + image: archlinux:base-devel@sha256:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1 steps: - name: Configure Arch mirror -- 2.54.1 From 318887b9b9d27fb5df110596d30d2e5fcb10a6f5 Mon Sep 17 00:00:00 2001 From: Boris Yumankulov Date: Sun, 25 Oct 2026 11:37:18 +0500 Subject: [PATCH 4/9] fix: avoid UI freezes when switching library layouts Signed-off-by: Boris Yumankulov --- CHANGELOG.md | 1 + portprotonqt/tabs/autoinstall_tab.py | 8 +++ portprotonqt/tabs/library_tab.py | 10 ++- tests/test_main_window.py | 94 +++++++++++++++++++++++++++- 4 files changed, 111 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 23516265..1cce58c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,7 @@ ### Fixed +- Исправлено зависание при смене сетки библиотеки - Исправлено открытие контекстного меню в файловом проводнике кнопкой геймпада - Исправлена блокировка установки игр GOG и EGS сообщением «Другая загрузка уже выполняется» после отмены выбора DLC - При включённом фильтре установленных игр метаданные GOG и EGS загружаются только для установленных игр diff --git a/portprotonqt/tabs/autoinstall_tab.py b/portprotonqt/tabs/autoinstall_tab.py index 592fdc54..a0b22933 100644 --- a/portprotonqt/tabs/autoinstall_tab.py +++ b/portprotonqt/tabs/autoinstall_tab.py @@ -397,6 +397,11 @@ class MainWindowAutoInstallTabMixin(_MainWindowTypingBase): """Rebuild auto-install cards after a live library layout change.""" if not hasattr(self, "autoInstallContainer"): return + if self.stackedWidget.currentIndex() != self.auto_install_tab_index: + self._autoinstall_layout_pending = True + self.autoInstallLoaded = False + return + self._autoinstall_layout_pending = False mode = ui_config.get_library_layout_mode( str(getattr(self.theme, "LIBRARY_LAYOUT_MODE", "grid")) ) @@ -487,6 +492,9 @@ class MainWindowAutoInstallTabMixin(_MainWindowTypingBase): return def _start_autoinstall_load(self, force_refresh: bool = False) -> None: + if getattr(self, "_autoinstall_layout_pending", False): + self.refresh_autoinstall_layout() + return if self.autoInstallLoaded or self.autoInstallLoading: return if not hasattr(self, "_on_autoinstall_games_loaded"): diff --git a/portprotonqt/tabs/library_tab.py b/portprotonqt/tabs/library_tab.py index 449074be..e6d6fcb0 100644 --- a/portprotonqt/tabs/library_tab.py +++ b/portprotonqt/tabs/library_tab.py @@ -152,9 +152,17 @@ class MainWindowLibraryTabMixin(_MainWindowTypingBase): card_orientation = "vertical" elif layout_mode in {"horizontal", "horizontal_top"}: card_orientation = "horizontal" + theme_mode = str(getattr(self.theme, "LIBRARY_LAYOUT_MODE", "grid")) + previous_mode = ui_config.get_library_layout_mode(theme_mode) + previous_orientation = ui_config.get_horizontal_card_orientation("theme") ui_config.set_library_layout_mode(layout_mode) ui_config.set_horizontal_card_orientation(card_orientation) - theme_mode = str(getattr(self.theme, "LIBRARY_LAYOUT_MODE", "grid")) + if ( + previous_mode == ui_config.get_library_layout_mode(theme_mode) + and (previous_mode not in {"horizontal", "horizontal_top"} + or previous_orientation == card_orientation) + ): + return self.game_library_manager.rebuild_library_layout( ui_config.get_library_layout_mode(theme_mode) ) diff --git a/tests/test_main_window.py b/tests/test_main_window.py index 2086aed8..d0583b9c 100644 --- a/tests/test_main_window.py +++ b/tests/test_main_window.py @@ -787,6 +787,9 @@ def test_vertical_theme_rebuilds_autoinstall_layout() -> None: window.auto_size_slider.maximum.return_value = 250 window.autoInstallLoading = False window._start_autoinstall_load = MagicMock() + window.auto_install_tab_index = 1 + window.stackedWidget = MagicMock() + window.stackedWidget.currentIndex.return_value = 1 window.refresh_autoinstall_layout() @@ -2650,7 +2653,7 @@ def test_library_layout_control_rebuilds_both_libraries( monkeypatch.setattr( library_tab_module.ui_config, "get_library_layout_mode", - lambda theme_mode: "grid", + MagicMock(side_effect=["list", "grid", "grid"]), ) LibraryMixin._on_library_layout_changed(window, 1) @@ -3136,3 +3139,92 @@ def test_shutdown_stops_batch_before_store_processes() -> None: process.kill.assert_called_once_with() assert process.waitForFinished.call_count == 2 assert window.store_download_queue == [] + + +@mark.parametrize("mode", ["grid", "list", "horizontal", "horizontal_top"]) +def test_hidden_autoinstall_defers_layout_rebuild(mode: str, monkeypatch: MonkeyPatch) -> None: + window = cast(Any, AutoInstallMixin()) + window.theme = SimpleNamespace(LIBRARY_LAYOUT_MODE=mode) + window.autoInstallContainer = MagicMock() + window.stackedWidget = MagicMock() + window.stackedWidget.currentIndex.return_value = 0 + window.auto_install_tab_index = 1 + window.autoInstallLoaded = True + window._set_autoinstall_container_layout = MagicMock() + window._start_autoinstall_load = MagicMock() + monkeypatch.setattr(autoinstall_tab_module.ui_config, "get_library_layout_mode", lambda _: mode) + + window.refresh_autoinstall_layout() + window.refresh_autoinstall_layout() + + assert window._autoinstall_layout_pending is True + assert window.autoInstallLoaded is False + window._set_autoinstall_container_layout.assert_not_called() + window._start_autoinstall_load.assert_not_called() + + +def test_autoinstall_load_applies_pending_layout_before_loading() -> None: + window = cast(Any, AutoInstallMixin()) + window._autoinstall_layout_pending = True + window.autoInstallLoaded = True + window.refresh_autoinstall_layout = MagicMock() + window.portproton_api = MagicMock() + + window._start_autoinstall_load() + + window.refresh_autoinstall_layout.assert_called_once_with() + window.portproton_api.start_autoinstall_games_load.assert_not_called() + + +def test_library_theme_grid_switch_preserves_cards( + monkeypatch: MonkeyPatch, tmp_config_dir: Path, +) -> None: + window = cast(Any, SimpleNamespace( + library_layout_keys=["theme", "grid"], + theme=SimpleNamespace(LIBRARY_LAYOUT_MODE="grid"), + game_library_manager=SimpleNamespace(rebuild_library_layout=MagicMock()), + refresh_autoinstall_layout=MagicMock(), + )) + monkeypatch.setattr(library_tab_module.ui_config, "get_library_layout_mode", lambda _: "grid") + monkeypatch.setattr(library_tab_module.ui_config, "set_library_layout_mode", MagicMock()) + monkeypatch.setattr(library_tab_module.ui_config, "set_horizontal_card_orientation", MagicMock()) + + LibraryMixin._on_library_layout_changed(window, 1) + LibraryMixin._on_library_layout_changed(window, 0) + + window.game_library_manager.rebuild_library_layout.assert_not_called() + window.refresh_autoinstall_layout.assert_not_called() + + +def test_deferred_autoinstall_layout_loads_latest_mode_once( + monkeypatch: MonkeyPatch, +) -> None: + window = cast(Any, AutoInstallMixin()) + window.theme = SimpleNamespace(LIBRARY_LAYOUT_MODE="grid") + window.autoInstallContainer = MagicMock() + window.autoInstallStatusHeader = MagicMock() + window.auto_size_slider = MagicMock() + window.auto_size_slider.maximum.return_value = 250 + window.stackedWidget = MagicMock() + window.stackedWidget.currentIndex.return_value = 0 + window.auto_install_tab_index = 1 + window.autoInstallLoaded = True + window.autoInstallLoading = False + window._set_autoinstall_container_layout = MagicMock() + window._on_autoinstall_games_loaded = MagicMock() + window.portproton_api = MagicMock() + mode = ["list"] + monkeypatch.setattr(autoinstall_tab_module.ui_config, "get_library_layout_mode", lambda _: mode[0]) + + window.refresh_autoinstall_layout() + mode[0] = "vertical" + window.refresh_autoinstall_layout() + window.stackedWidget.currentIndex.return_value = 1 + window._start_autoinstall_load() + + window._set_autoinstall_container_layout.assert_called_once_with("vertical") + window.portproton_api.start_autoinstall_games_load.assert_called_once_with( + window._on_autoinstall_games_loaded, force_refresh=False, + ) + assert window._autoinstall_layout_pending is False + assert window.autoInstallLoading is True -- 2.54.1 From 37c25aed0c9434bb2ada70e513d9f424e69a6e1c Mon Sep 17 00:00:00 2001 From: Gitea Actions Date: Sun, 25 Oct 2026 14:59:05 +0000 Subject: [PATCH 5/9] chore: download stats 2026-10-25T14:59:05Z --- README.md | 2 +- README.ru.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c8f30aba..4dcd80af 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@

Releases - Total Downloads + Total Downloads License: GPL-3.0 Python 3.11+ Platform: Linux diff --git a/README.ru.md b/README.ru.md index 09da1cf1..cdd6e7cf 100644 --- a/README.ru.md +++ b/README.ru.md @@ -9,7 +9,7 @@

Релизы - Всего загрузок + Всего загрузок Лицензия: GPL-3.0 Python 3.11+ Платформа: Linux -- 2.54.1 From 5a568e3adbd4fc0b44b3ffea0167d67ca716623d Mon Sep 17 00:00:00 2001 From: Boris Yumankulov Date: Mon, 26 Oct 2026 15:33:13 +0500 Subject: [PATCH 6/9] feat: add Space hint for multiple selection Signed-off-by: Boris Yumankulov --- CHANGELOG.md | 1 + portprotonqt/tabs/control_hints.py | 1 + .../themes/standart-light/images/icons/keyboards/key_space.svg | 1 + .../themes/standart/images/icons/keyboards/key_space.svg | 1 + 4 files changed, 4 insertions(+) create mode 100644 portprotonqt/themes/standart-light/images/icons/keyboards/key_space.svg create mode 100644 portprotonqt/themes/standart/images/icons/keyboards/key_space.svg diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cce58c4..39c35db4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,7 @@ - Исправлена гонка при запуске игры с `--silent` ### Contributors +- @Dervart - @adem4ik - @rogerio-mattos - @Rubin13 diff --git a/portprotonqt/tabs/control_hints.py b/portprotonqt/tabs/control_hints.py index 18ffc243..180c7918 100644 --- a/portprotonqt/tabs/control_hints.py +++ b/portprotonqt/tabs/control_hints.py @@ -226,6 +226,7 @@ class MainWindowControlHintsMixin: keyboard_hints = [ ("key_enter", _("Select"), "confirm"), + ("key_space", _("Select multiple"), None), ("key_backspace", _("Back"), "back"), ("key_e", _("Add a shortcut"), "add_game"), ("key_context", _("Menu"), "context_menu"), diff --git a/portprotonqt/themes/standart-light/images/icons/keyboards/key_space.svg b/portprotonqt/themes/standart-light/images/icons/keyboards/key_space.svg new file mode 100644 index 00000000..be3d3a12 --- /dev/null +++ b/portprotonqt/themes/standart-light/images/icons/keyboards/key_space.svg @@ -0,0 +1 @@ + diff --git a/portprotonqt/themes/standart/images/icons/keyboards/key_space.svg b/portprotonqt/themes/standart/images/icons/keyboards/key_space.svg new file mode 100644 index 00000000..2b0daff1 --- /dev/null +++ b/portprotonqt/themes/standart/images/icons/keyboards/key_space.svg @@ -0,0 +1 @@ + -- 2.54.1 From d30fb3b8b60bb48002b146a9bcd0252d057a6821 Mon Sep 17 00:00:00 2001 From: Boris Yumankulov Date: Mon, 26 Oct 2026 15:48:29 +0500 Subject: [PATCH 7/9] fix(settings): prevent favorite value clipping Signed-off-by: Boris Yumankulov --- CHANGELOG.md | 1 + portprotonqt/dialogs/settings_dialog.py | 2 ++ 2 files changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 39c35db4..58870084 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,7 @@ - Исправлена высокая нагрузка на CPU из-за непрерывной перерисовки таблиц в настройках exe - В меню системного трея при запуске игры с `--silent` добавлены отсутствовавшие действия приостановки и возобновления игры - Исправлена гонка при запуске игры с `--silent` +- Исправлено обрезание значений в избранных настройках ### Contributors - @Dervart diff --git a/portprotonqt/dialogs/settings_dialog.py b/portprotonqt/dialogs/settings_dialog.py index 420f09ee..fe7971ce 100644 --- a/portprotonqt/dialogs/settings_dialog.py +++ b/portprotonqt/dialogs/settings_dialog.py @@ -1108,6 +1108,8 @@ class ExeSettingsDialog( break source_header = source_table.horizontalHeader() + if source_header.sectionResizeMode(1) == QHeaderView.ResizeMode.ResizeToContents: + source_table.resizeColumnToContents(1) target_header = self.favorites_table.horizontalHeader() target_header.setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch) target_header.setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed) -- 2.54.1 From 56213341289662baca679756103b7bc96753f076 Mon Sep 17 00:00:00 2001 From: Boris Yumankulov Date: Mon, 26 Oct 2026 23:47:04 +0500 Subject: [PATCH 8/9] feat: add SGDB fallback for Steam shortcut artwork Signed-off-by: Boris Yumankulov --- CHANGELOG.md | 1 + portprotonqt/steam_api/api.py | 10 +++--- portprotonqt/steam_api/shortcuts.py | 54 +++++++++++++++++++++++------ tests/test_shortcuts.py | 54 +++++++++++++++++++++++++++++ 4 files changed, 105 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58870084..fc21bf17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ ### Added +- При добавлении игр в Steam добавлена загрузка обложек из SteamGridDB, если Steam AppID не найден - В диалоги добавления и редактирования EXE добавлен выбор пользовательской иконки - Добавлена возможность добавлять установленные игры GOG и EGS в Steam - Добавлен массовый импорт игр из выбранной папки diff --git a/portprotonqt/steam_api/api.py b/portprotonqt/steam_api/api.py index 55ddba9c..3b1b58df 100644 --- a/portprotonqt/steam_api/api.py +++ b/portprotonqt/steam_api/api.py @@ -47,10 +47,12 @@ SGDB_CACHE_DURATION = 24 * 60 * 60 STEAM_CLIENT_ICON_SIZES = (16, 32, 64, 128, 256) -def fetch_sgdb_cover_async(game_name: str, callback: Callable[[str], None]) -> None: +def fetch_sgdb_cover_async( + game_name: str, callback: Callable[[str], None], image_type: str = "grids" +) -> None: """Asynchronously fetch cover image URL from steamgrid.usebottles.com.""" - encoded = urllib.parse.quote(game_name) - url = f"https://steamgrid.usebottles.com/api/search/{encoded}" + encoded = urllib.parse.quote(game_name, safe="") + url = f"https://steamgrid.usebottles.com/api/search/{encoded}/{image_type}" def process_response(result: str | None) -> None: if not result or not os.path.exists(result): @@ -75,7 +77,7 @@ def fetch_sgdb_cover_async(game_name: str, callback: Callable[[str], None]) -> N cache_manager = CacheManager() safe_name = "".join(c for c in game_name if c.isalnum() or c in " -_")[:50] - cache_file = cache_manager.cache_dir / f"sgdb_{safe_name}.json" + cache_file = cache_manager.cache_dir / f"sgdb_{safe_name}_{image_type}.json" if cache_file.exists() and time.time() - cache_file.stat().st_mtime < SGDB_CACHE_DURATION: process_response(str(cache_file)) return diff --git a/portprotonqt/steam_api/shortcuts.py b/portprotonqt/steam_api/shortcuts.py index 857fc64f..22858b06 100644 --- a/portprotonqt/steam_api/shortcuts.py +++ b/portprotonqt/steam_api/shortcuts.py @@ -7,7 +7,9 @@ import re import shlex import shutil import zlib +from functools import partial from pathlib import Path +from urllib.parse import urlsplit import orjson import requests @@ -33,6 +35,7 @@ from portprotonqt.steam_api.utils import ( ) from portprotonqt.steam_api.api import ( get_steam_game_info_async, + fetch_sgdb_cover_async, ) logger = get_logger(__name__) @@ -328,11 +331,12 @@ def _add_shortcut_via_vdf( def _download_covers( appid: int, - steam_appid: int, + steam_appid: tuple[int | None, str], grid_dir: str, was_api_used: bool ) -> None: """Download cover images for the game.""" + source_appid, game_name = steam_appid cover_types = [ ("p.jpg", "library_600x900_2x.jpg"), ("_hero.jpg", "library_hero.jpg"), @@ -349,7 +353,7 @@ def _download_covers( with open(result_path, 'rb') as f: img_b64 = base64.b64encode(f.read()).decode('utf-8') logger.info(f"Applying cover type '{steam_name}' via API for AppID {appid}") - ext = Path(steam_name).suffix.lstrip('.') + ext = Path(result_path).suffix.lstrip('.') call_steam_api("setGrid", appid, index, ext, img_b64) except Exception as e: logger.error(f"Failed to apply cover '{steam_name}' via API: {e}") @@ -358,14 +362,45 @@ def _download_covers( except Exception as e: logger.error(f"Failed to process cover {steam_name} for appid {steam_appid}: {e}") + def download_sgdb(index: int, cover_file: str, steam_name: str) -> None: + image_type = ("grids", "heroes", "logos", "hgrids")[index] + + def on_url(url: str) -> None: + if not url.startswith("https://cdn2.steamgriddb.com/"): + on_cover_download(None, steam_name, index) + return + extension = Path(urlsplit(url).path).suffix.lower() + if extension not in (".png", ".jpg", ".jpeg"): + logger.warning("Unsupported SGDB artwork format: %s", extension) + on_cover_download(None, steam_name, index) + return + destination = str(Path(cover_file).with_suffix(extension)) + downloader.download_async( + url, destination, timeout=5, + callback=partial(on_cover_download, steam_name=steam_name, index=index), + ) + + fetch_sgdb_cover_async(game_name, on_url, image_type) + + def on_steam_download( + index: int, steam_name: str, cover_file: str, result: str | None + ) -> None: + if result: + on_cover_download(result, steam_name, index) + else: + download_sgdb(index, cover_file, steam_name) + for i, (suffix, steam_name) in enumerate(cover_types): cover_file = os.path.join(grid_dir, f"{appid}{suffix}") - cover_url = f"https://cdn.cloudflare.steamstatic.com/steam/apps/{steam_appid}/{steam_name}" + if not source_appid: + download_sgdb(i, cover_file, steam_name) + continue + cover_url = f"https://cdn.cloudflare.steamstatic.com/steam/apps/{source_appid}/{steam_name}" downloader.download_async( cover_url, cover_file, timeout=5, - callback=lambda result, index=i, name=steam_name: on_cover_download(result, name, index) + callback=partial(on_steam_download, i, steam_name, cover_file) ) @@ -475,10 +510,10 @@ def add_to_steam( nonlocal steam_appid steam_appid = game_info.get("appid") if not steam_appid or not isinstance(steam_appid, int): - logger.info("No valid Steam appid found, skipping cover download") + _download_covers(appid, (None, game_name), str(grid_dir), was_api_used) return logger.info(f"Found Steam AppID {steam_appid} for cover download") - _download_covers(appid, steam_appid, str(grid_dir), was_api_used) + _download_covers(appid, (steam_appid, game_name), str(grid_dir), was_api_used) get_steam_game_info_async(game_name, exec_line, on_game_info) @@ -491,10 +526,9 @@ def add_to_steam( def _delete_cover_files(grid_dir: str, appid: int) -> None: """Delete cover files for a game.""" cover_files = [ - os.path.join(grid_dir, f"{appid}.jpg"), - os.path.join(grid_dir, f"{appid}p.jpg"), - os.path.join(grid_dir, f"{appid}_hero.jpg"), - os.path.join(grid_dir, f"{appid}_logo.png") + os.path.join(grid_dir, f"{appid}{suffix}{extension}") + for suffix in ("", "p", "_hero", "_logo") + for extension in (".jpg", ".png", ".jpeg") ] for cover_file in cover_files: if os.path.exists(cover_file): diff --git a/tests/test_shortcuts.py b/tests/test_shortcuts.py index 0c8b0f2e..21efee09 100644 --- a/tests/test_shortcuts.py +++ b/tests/test_shortcuts.py @@ -2576,3 +2576,57 @@ def test_exe_dialog_saves_custom_icon(tmp_path: Path, monkeypatch: Any) -> None: assert source.is_file() assert dialog.result() == QDialog.DialogCode.Accepted dialog.close() + + +@pytest.mark.parametrize("source_appid", [None, 620]) +@pytest.mark.parametrize("extension", ["png", "jpg"]) +def test_steam_artwork_sgdb_fallback( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, source_appid: int | None, extension: str +) -> None: + requested = [] + applied = [] + original = b"original artwork bytes" + + def fetch(name: str, callback: Any, image_type: str) -> None: + requested.append((name, image_type)) + callback(f"https://cdn2.steamgriddb.com/grid/{image_type}.{extension}") + + def download(url: str, destination: str, timeout: int, callback: Any) -> None: + if "steamstatic.com" in url: + callback(None) + return + Path(destination).write_bytes(original) + callback(destination) + + monkeypatch.setattr(steam_shortcuts, "fetch_sgdb_cover_async", fetch) + monkeypatch.setattr(steam_shortcuts.downloader, "download_async", download) + monkeypatch.setattr(steam_shortcuts, "call_steam_api", lambda *args: applied.append(args)) + steam_shortcuts._download_covers(123, (source_appid, "Portal 2"), str(tmp_path), True) + assert requested == [("Portal 2", kind) for kind in ("grids", "heroes", "logos", "hgrids")] + assert len(applied) == 4 + assert all(call[3] == extension for call in applied) + for suffix in ("p", "_hero", "_logo", ""): + assert (tmp_path / f"123{suffix}.{extension}").read_bytes() == original + + +def test_sgdb_artwork_cache_separates_types( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + import portprotonqt.steam_api.api as api + + monkeypatch.setattr(api, "CacheManager", lambda: SimpleNamespace(cache_dir=tmp_path)) + downloads = [] + + def download(url: str, path: str, timeout: int, callback: Any) -> None: + downloads.append(url) + Path(path).write_text(f'"{url}"', encoding="utf-8") + callback(path) + + monkeypatch.setattr(api.downloader, "download_async", download) + completed = [] + for image_type in ("grids", "heroes", "grids", "heroes"): + api.fetch_sgdb_cover_async("Portal/2", completed.append, image_type) + assert len(downloads) == 2 + assert downloads[0].endswith("Portal%2F2/grids") + assert downloads[1].endswith("Portal%2F2/heroes") + assert completed == downloads + downloads -- 2.54.1 From 9ac8bef22f5c8af2db15c3767159cfa50b7b0531 Mon Sep 17 00:00:00 2001 From: fruzizela Date: Tue, 27 Oct 2026 05:28:58 +0530 Subject: [PATCH 9/9] chore(ui): WinePrefix auto-hide enhancements. --- portprotonqt/game_card.py | 341 +++++++++++++++++---------- portprotonqt/game_library_manager.py | 26 +- portprotonqt/tabs/settings_tab.py | 2 +- 3 files changed, 246 insertions(+), 123 deletions(-) diff --git a/portprotonqt/game_card.py b/portprotonqt/game_card.py index 05f9a7ad..95a3b738 100644 --- a/portprotonqt/game_card.py +++ b/portprotonqt/game_card.py @@ -62,9 +62,49 @@ def is_valid_protondb_tier(tier: str | None) -> bool: """Check if ProtonDB tier is supported.""" return bool(tier) and tier.lower() in PROTONDB_TIERS -def show_wine_prefix_columns(theme) -> bool: - """Whether to show columns Wine/Prefix — single condition for cards and titles.""" - show = getattr(ui_config, "get_show_wine_prefix_cards", lambda: True)() +def show_wine_prefix_check_card( + wp_exec_line: str, + wp_game_source: str, + wp_is_missing_exe: bool, + wp_games: list[tuple] | None = None, +) -> bool: + """Collects data and checks rules for showing WinePrefix.""" + if not getattr(ui_config, "get_show_wine_prefix_cards", lambda: True)(): + return False + if wp_games is not None: + # Header mode: game[5] = exec_line, game[12] = game_source. + for game in wp_games: + wp_exec = str(game[5] or "") + wp_source = str(game[12] or "") + wp_missing = False + # to not change this code extract_executable_path + if wp_source.lower() == "portproton": + wp_path = GameCard._extract_executable_path(wp_exec) + if wp_path and wp_path.lower().endswith(WINDOWS_LAUNCH_EXTENSIONS): + wp_missing = not os.path.exists(wp_path) + if show_wine_prefix_check_card(wp_exec, wp_source, wp_missing): + return True + return False + # Hidden for: + if wp_exec_line.startswith("autoinstall:"): + return False + wp_source_lower = str(wp_game_source).lower() + if wp_source_lower in ("steam", "gog", "egs"): + return False + if wp_is_missing_exe: + return False + if wp_source_lower == "portproton" and not GameCard._extract_executable_path(wp_exec_line): + return False + return True + +def show_wine_prefix_columns( + theme, + wp_games: list[tuple] | None = None, + wp_exec_line: str | None = None, + wp_game_source: str | None = None, + wp_is_missing_exe: bool | None = None, +) -> bool: + """Theme: passes only when the theme has all required attributes.""" required = ( "WINE_PREFIX_CARD_HEIGHT", "wine_prefix_margin", @@ -72,7 +112,14 @@ def show_wine_prefix_columns(theme) -> bool: "GAME_CARD_WINE_PREFIX_CONTAINER_STYLE", "GAME_CARD_WINE_PREFIX_LOADING_STYLE", ) - return show and all(hasattr(theme, attr) for attr in required) + if not all(hasattr(theme, attr) for attr in required): + return False + return show_wine_prefix_check_card( + wp_exec_line=wp_exec_line or "", + wp_game_source=wp_game_source or "", + wp_is_missing_exe=bool(wp_is_missing_exe), + wp_games=wp_games, + ) class TaskSignals(QObject): """Transmitter class for signals from QRunnable.""" @@ -80,10 +127,10 @@ class TaskSignals(QObject): class WinePrefixTask(QRunnable, QObject): """Task to extract Wine version and Prefix name from game files.""" - def __init__(self, game_source: str, exec_line: str, callback): + def __init__(self, wp_exec_line: str, callback): super().__init__() - self.game_source = game_source.lower() - self.exec_line = exec_line + self.logger = get_logger(__name__) + self.wp_exec_line = wp_exec_line self.signals = TaskSignals() self.signals.result_ready.connect(callback) self.setAutoDelete(True) @@ -96,47 +143,56 @@ class WinePrefixTask(QRunnable, QObject): if self._is_cancelled: return - runtime_map = {"steam": "Steam Proton", "gog": "GOG Runtime", "egs": "Epic Proton"} - wine_version = runtime_map.get(self.game_source, _("Default")) - prefix_name = "default" + wp_wine = _("Not found") + wp_prefix = _("Not found") - if self.game_source in runtime_map: - self.signals.result_ready.emit(wine_version, prefix_name) - return - game_exe = GameCard._extract_executable_path(self.exec_line) - if not game_exe: - self.signals.result_ready.emit(wine_version, prefix_name) + wp_exe = GameCard._extract_executable_path(self.wp_exec_line) + if not wp_exe: + self.signals.result_ready.emit(wp_wine, wp_prefix) return try: - with open(f"{game_exe}.ppdb", encoding="utf-8", errors="ignore") as file: - has_wine = has_prefix = False + with open(f"{wp_exe}.ppdb", encoding="utf-8", errors="ignore") as file: + has_wp_wine = has_wp_prefix = False for line in file: if self._is_cancelled: return - if not has_wine and (wine_match := re.search(r'export\s+PW_WINE_USE=["\']?(.*?)["\']?(?:\s|$)', line)): - wine_version = wine_match.group(1).strip() - has_wine = True + if not has_wp_wine and (wp_wine_match := re.search( + r'export\s+PW_WINE_USE=["\']?(.*?)["\']?(?:\s|$)', line + )): + wp_wine = wp_wine_match.group(1).strip() + has_wp_wine = True - if not has_prefix and (prefix_match := re.search(r'export\s+PW_PREFIX_NAME=["\']?(.*?)["\']?(?:\s|$)', line)): - prefix_name = prefix_match.group(1).strip() - has_prefix = True + if not has_wp_prefix and (wp_prefix_match := re.search( + r'export\s+PW_PREFIX_NAME=["\']?(.*?)["\']?(?:\s|$)', line + )): + wp_prefix = wp_prefix_match.group(1).strip() + has_wp_prefix = True - if has_wine and has_prefix: + if has_wp_wine and has_wp_prefix: break - except OSError: - pass - + except FileNotFoundError: + pass # no .ppdb file → "Not found" is the expected result + except OSError as e: + self.logger.error(f"Error reading wine-prefix .ppdb file: {wp_exe}", exc_info=e) if self._is_cancelled: return - if prefix_name in ("default", "") or not prefix_name.strip(): - prefix_name = os.environ.get("WINEPREFIX") or "default" + # Reference to the user's PortProton defaults + if re.fullmatch(r"\$?\{?PW_DEFAULT_WINE_USE\}?", wp_wine): + wp_wine = _("Default (settings)") + if not wp_wine.strip(): + wp_wine = _("Not found") + if re.fullmatch(r"\$?\{?PW_DEFAULT_PREFIX_NAME\}?", wp_prefix): + wp_prefix = _("Default (settings)") + elif wp_prefix in ("default", "") or not wp_prefix.strip(): + # WINEPREFIX is the prefix the game will actually run in + wp_prefix = os.environ.get("WINEPREFIX") or _("Not found") if not self._is_cancelled: - self.signals.result_ready.emit(wine_version, prefix_name) + self.signals.result_ready.emit(wp_wine, wp_prefix) class SourceCorner(QWidget): @@ -473,7 +529,7 @@ class GameCard(AnimatedCard): parent_mode or getattr(self.theme, "LIBRARY_LAYOUT_MODE", "grid") ).lower() self.list_layout = self.layout_mode in {"list", "vertical"} - self.show_wine_prefix_enabled = False + self.wp_enabled = False self.vertical_layout = self.layout_mode == "vertical" self.horizontal_layout = self.layout_mode in {"horizontal", "horizontal_top"} self.economy_mode = ui_config.get_economy_mode() @@ -683,8 +739,7 @@ class GameCard(AnimatedCard): font_size = self.nameLabel.font().pointSizeF() self.base_font_size = font_size if font_size > 0 else 10.0 - self._initialize_wine_prefix_widgets() - + self._initialize_wp_widgets() self.update_scale() # Force initial layout update to ensure correct geometry @@ -696,99 +751,143 @@ class GameCard(AnimatedCard): layout.invalidate() parent.updateGeometry() - def _initialize_wine_prefix_widgets(self) -> None: + def _initialize_wp_widgets(self) -> None: """Initialize Wine version and Prefix name widgets based on UI configuration.""" try: - self._reset_wine_prefix_widgets() - self._check_layout_conditions() + self._reset_wp_widgets() + self._check_wp_conditions() - if not self.show_wine_prefix_enabled: + if not self.wp_enabled: + if self.vertical_layout: + # Empty Wine/Prefix columns keep + self._setup_wp_vertical_layout() + # Excessive, but protected + self._sync_wp_columns_alignment() return - self._setup_wine_prefix_layout() + self._setup_wp_layout() - def safe_callback(wine, prefix): + def safe_callback(wp_wine, wp_prefix): try: - if hasattr(self, '_wine_task'): - self._wine_task = None + if hasattr(self, "_wp_task"): + self._wp_task = None - if not self.show_wine_prefix_enabled: + if not self.wp_enabled: return - if hasattr(self, 'nameLabel') and self.nameLabel is not None: - self._update_wine_prefix(wine, prefix) + if hasattr(self, "nameLabel") and self.nameLabel is not None: + self._update_wp(wp_wine, wp_prefix) except Exception as e: self.logger.error("Error processing callback information Wine Prefix", exc_info=e) - self._wine_task = WinePrefixTask( - game_source=self.game_source, - exec_line=self.exec_line, - callback=safe_callback + self._wp_task = WinePrefixTask( + wp_exec_line=self.exec_line, + callback=safe_callback, ) - QThreadPool.globalInstance().start(self._wine_task) + QThreadPool.globalInstance().start(self._wp_task) except Exception as e: self.logger.error("Error initializing widgets Wine Prefix", exc_info=e) - def _reset_wine_prefix_widgets(self): - self.wine_prefix_name_card = None - self.wine_version_label_card = None - self.wine_prefix_label_card = None - self.game_wine_label = None - self.game_prefix_label = None + def _reset_wp_widgets(self): + self.wp_container_card = None + self.wp_wine_label_card = None + self.wp_prefix_label_card = None + self.wp_wine_column_label = None + self.wp_prefix_column_label = None + self._wp_columns_visible = False - def _check_layout_conditions(self): + def _check_wp_conditions(self): if self.list_layout and not self.vertical_layout: - self.show_wine_prefix_enabled = False + self.wp_enabled = False return - self.show_wine_prefix_enabled = show_wine_prefix_columns(self.theme) + self.wp_enabled = show_wine_prefix_columns( + self.theme, + wp_exec_line=self.exec_line, + wp_game_source=self.game_source, + wp_is_missing_exe=bool(self.missing_executable_path), + ) - def _setup_wine_prefix_layout(self): + def _setup_wp_layout(self): self.update_scale() if self.vertical_layout: - self._setup_vertical_wine_layout() + self._setup_wp_vertical_layout() else: - self._setup_horizontal_wine_layout() + self._setup_wp_horizontal_layout() - def _setup_vertical_wine_layout(self): + def _setup_wp_vertical_layout(self): stretches = self.theme.GAME_CARD_VERTICAL["column_stretches"] - self.game_wine_label = QLabel(f"Wine: {_('Loading...')}") - self.game_wine_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - self.game_wine_label.setProperty("theme_style_name", "GAME_CARD_COLUMN_LABEL_STYLE") - self.game_wine_label.setStyleSheet(self.theme.GAME_CARD_COLUMN_LABEL_STYLE) - self.game_wine_label.setWordWrap(True) - self.layout_.addWidget(self.game_wine_label, stretches[4] if len(stretches) > 4 else 2) + wp_wine_text = _("Loading...") if self.wp_enabled else "" + self.wp_wine_column_label = QLabel(wp_wine_text) + self.wp_wine_column_label.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.wp_wine_column_label.setProperty("theme_style_name", "GAME_CARD_COLUMN_LABEL_STYLE") + self.wp_wine_column_label.setStyleSheet(self.theme.GAME_CARD_COLUMN_LABEL_STYLE) + self.wp_wine_column_label.setWordWrap(True) + self.layout_.addWidget(self.wp_wine_column_label, stretches[4] if len(stretches) > 4 else 2) - self.game_prefix_label = QLabel(f"Prefix: {_('Loading...')}") - self.game_prefix_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - self.game_prefix_label.setProperty("theme_style_name", "GAME_CARD_COLUMN_LABEL_STYLE") - self.game_prefix_label.setStyleSheet(self.theme.GAME_CARD_COLUMN_LABEL_STYLE) - self.game_prefix_label.setWordWrap(True) - self.layout_.addWidget(self.game_prefix_label, stretches[5] if len(stretches) > 5 else 2) + wp_prefix_text = _("Loading...") if self.wp_enabled else "" + self.wp_prefix_column_label = QLabel(wp_prefix_text) + self.wp_prefix_column_label.setAlignment(Qt.AlignmentFlag.AlignCenter) + self.wp_prefix_column_label.setProperty("theme_style_name", "GAME_CARD_COLUMN_LABEL_STYLE") + self.wp_prefix_column_label.setStyleSheet(self.theme.GAME_CARD_COLUMN_LABEL_STYLE) + self.wp_prefix_column_label.setWordWrap(True) + self.layout_.addWidget(self.wp_prefix_column_label, stretches[5] if len(stretches) > 5 else 2) - def _setup_horizontal_wine_layout(self): - self.wine_prefix_name_card = QFrame() - self.wine_prefix_name_card.setStyleSheet(self.theme.GAME_CARD_WINE_PREFIX_CONTAINER_STYLE) - self.wine_prefix_name_card.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum) + def _setup_wp_horizontal_layout(self): + self.wp_container_card = QFrame() + self.wp_container_card.setStyleSheet(self.theme.GAME_CARD_WINE_PREFIX_CONTAINER_STYLE) + self.wp_container_card.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Maximum) - prefix_layout = QVBoxLayout(self.wine_prefix_name_card) - prefix_layout.setContentsMargins(*self.theme.wine_prefix_margin) - prefix_layout.setSpacing(self.theme.wine_prefix_spacing) + wp_layout = QVBoxLayout(self.wp_container_card) + wp_layout.setContentsMargins(*self.theme.wine_prefix_margin) + wp_layout.setSpacing(self.theme.wine_prefix_spacing) - self.wine_version_label_card = QLabel(f"Wine: {_('Loading...')}") - self.wine_version_label_card.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) - self.wine_version_label_card.setStyleSheet(self.theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) + self.wp_wine_label_card = QLabel(f"Wine: {_('Loading...')}") + self.wp_wine_label_card.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) + self.wp_wine_label_card.setStyleSheet(self.theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) - self.wine_prefix_label_card = QLabel(f"Prefix: {_('Loading...')}") - self.wine_prefix_label_card.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) - self.wine_prefix_label_card.setStyleSheet(self.theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) + self.wp_prefix_label_card = QLabel(f"Prefix: {_('Loading...')}") + self.wp_prefix_label_card.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) + self.wp_prefix_label_card.setStyleSheet(self.theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) - prefix_layout.addWidget(self.wine_version_label_card) - prefix_layout.addWidget(self.wine_prefix_label_card) - self.layout_.addWidget(self.wine_prefix_name_card) + wp_layout.addWidget(self.wp_wine_label_card) + wp_layout.addWidget(self.wp_prefix_label_card) + self.layout_.addWidget(self.wp_container_card) + + def update_wp_columns_alignment(self, wp_columns_visible: bool) -> None: + """Show or hide empty WinePrefix. Excluded cards only.""" + wp_visible = bool(wp_columns_visible) + height_changed = wp_visible != self._wp_columns_visible + self._wp_columns_visible = wp_visible + if self.wp_enabled or not self.vertical_layout: + if height_changed and not self.wp_enabled and not self.horizontal_layout: + self.update_scale() + return + try: + if self.wp_wine_column_label is not None: + self.wp_wine_column_label.setVisible(wp_visible) + if self.wp_prefix_column_label is not None: + self.wp_prefix_column_label.setVisible(wp_visible) + except RuntimeError: + pass + + def _sync_wp_columns_alignment(self) -> None: + """Immediately following its creation.""" + try: + parent = self.parent() + while parent is not None: + manager = getattr(parent, "game_library_manager", None) + if manager is not None: + self.update_wp_columns_alignment( + bool(getattr(manager, "_wp_header_columns_visible", False)) + ) + return + parent = parent.parent() + except RuntimeError: + pass def refresh_theme(self, theme: Any) -> None: """Refresh cached card visuals after a live theme change.""" @@ -853,15 +952,15 @@ class GameCard(AnimatedCard): try: if self.vertical_layout: - if self.game_wine_label is not None: - self.game_wine_label.setStyleSheet(theme.GAME_CARD_COLUMN_LABEL_STYLE) - if self.game_prefix_label is not None: - self.game_prefix_label.setStyleSheet(theme.GAME_CARD_COLUMN_LABEL_STYLE) + if self.wp_wine_column_label is not None: + self.wp_wine_column_label.setStyleSheet(theme.GAME_CARD_COLUMN_LABEL_STYLE) + if self.wp_prefix_column_label is not None: + self.wp_prefix_column_label.setStyleSheet(theme.GAME_CARD_COLUMN_LABEL_STYLE) else: - if self.wine_version_label_card is not None: - self.wine_version_label_card.setStyleSheet(theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) - if self.wine_prefix_label_card is not None: - self.wine_prefix_label_card.setStyleSheet(theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) + if self.wp_wine_label_card is not None: + self.wp_wine_label_card.setStyleSheet(theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) + if self.wp_prefix_label_card is not None: + self.wp_prefix_label_card.setStyleSheet(theme.GAME_CARD_WINE_PREFIX_LOADING_STYLE) except Exception as e: self.logger.error("Error Update theme", exc_info=e) @@ -1135,7 +1234,7 @@ class GameCard(AnimatedCard): self.theme.COMPACT_CARD["height_ratio"] if small_card_mode else self.card_geometry_cfg.get("card_height_ratio", 1.8) ) - if not self.horizontal_layout and self.show_wine_prefix_enabled: + if not self.horizontal_layout and (self.wp_enabled or self._wp_columns_visible): height_ratio += self.theme.WINE_PREFIX_CARD_HEIGHT scaled_height = int(self.base_card_width * height_ratio * self._scale) @@ -1237,13 +1336,13 @@ class GameCard(AnimatedCard): self.display_filter = display_filter self.economy_mode = ui_config.get_economy_mode() - if self.wine_prefix_name_card is not None: - self.wine_prefix_name_card.setVisible(self.show_wine_prefix_enabled and not self.list_layout) + if self.wp_container_card is not None: + self.wp_container_card.setVisible(self.wp_enabled and not self.list_layout) if self.vertical_layout: - if self.game_wine_label is not None: - self.game_wine_label.setVisible(self.show_wine_prefix_enabled) - if self.game_prefix_label is not None: - self.game_prefix_label.setVisible(self.show_wine_prefix_enabled) + if self.wp_wine_column_label is not None: + self.wp_wine_column_label.setVisible(self.wp_enabled or self._wp_columns_visible) + if self.wp_prefix_column_label is not None: + self.wp_prefix_column_label.setVisible(self.wp_enabled or self._wp_columns_visible) self.update_scale() @@ -1400,28 +1499,28 @@ class GameCard(AnimatedCard): QDesktopServices.openUrl(url) @Slot(str, str) - def _update_wine_prefix(self, wine_version: str, prefix_name: str) -> None: + def _update_wp(self, wp_wine: str, wp_prefix: str) -> None: """Update UI fields with formatting compatible with text wraps.""" try: - if not hasattr(self, 'coverLabel') or self.coverLabel is None: + if not hasattr(self, "coverLabel") or self.coverLabel is None: return - if not self.show_wine_prefix_enabled: + if not self.wp_enabled: return - formatted_wine = wine_version.replace("-", "-\u200b").replace("_", "_\u200b") - formatted_prefix = prefix_name.replace("-", "-\u200b").replace("_", "_\u200b") + formatted_wine = wp_wine.replace("-", "-\u200b").replace("_", "_\u200b") + formatted_prefix = wp_prefix.replace("-", "-\u200b").replace("_", "_\u200b") if self.vertical_layout: - if self.game_wine_label is not None: - self.game_wine_label.setText(formatted_wine) - if self.game_prefix_label is not None: - self.game_prefix_label.setText(formatted_prefix) + if self.wp_wine_column_label is not None: + self.wp_wine_column_label.setText(formatted_wine) + if self.wp_prefix_column_label is not None: + self.wp_prefix_column_label.setText(formatted_prefix) else: - if self.wine_version_label_card is not None: - self.wine_version_label_card.setText(f"Wine: {formatted_wine}") - if self.wine_prefix_label_card is not None: - self.wine_prefix_label_card.setText(f"Prefix: {formatted_prefix}") + if self.wp_wine_label_card is not None: + self.wp_wine_label_card.setText(f"Wine: {formatted_wine}") + if self.wp_prefix_label_card is not None: + self.wp_prefix_label_card.setText(f"Prefix: {formatted_prefix}") except RuntimeError: pass @@ -1536,10 +1635,10 @@ class GameCard(AnimatedCard): def cleanup(self): """Clean up animations to prevent memory leaks when the card is destroyed.""" - if (task := getattr(self, '_wine_task', None)) is not None: + if (task := getattr(self, "_wp_task", None)) is not None: try: task.cancel() - self._wine_task = None + self._wp_task = None except (RuntimeError, TypeError): pass diff --git a/portprotonqt/game_library_manager.py b/portprotonqt/game_library_manager.py index 16a2e10d..b723ee17 100644 --- a/portprotonqt/game_library_manager.py +++ b/portprotonqt/game_library_manager.py @@ -101,6 +101,7 @@ class GameLibraryManager: self._incremental_scroll_delay_ms: int = 250 self._focus_first_card_after_update = False self._pending_update = False + self._wp_header_columns_visible: bool | None = None self.pending_deletions = deque() self.is_filtering = False self.dirty = False @@ -229,7 +230,11 @@ class GameLibraryManager: base_labels = (_("Game Title"), _("LAST LAUNCH"), _("TIME SPENT"), _("Library")) base_stretches = list(config.get("column_stretches", (4, 2, 2, 2))) - if show_wine_prefix_columns(self.theme): + wp_visible = show_wine_prefix_columns(self.theme, self.filtered_games) + self._wp_header_columns_visible = wp_visible + for card in self.game_card_cache.values(): + card.update_wp_columns_alignment(wp_visible) + if wp_visible: labels = base_labels + (_("WINE"), _("PREFIX")) stretches = list(base_stretches) while len(stretches) < len(labels): @@ -540,7 +545,25 @@ class GameLibraryManager: if not self._pending_update: return self._pending_update = False + old_wp_visible = self._wp_header_columns_visible + wp_visible = show_wine_prefix_columns(self.theme, self.filtered_games) + self._wp_header_columns_visible = wp_visible self._update_game_grid_immediate() + # Sync newly created cards with the current header state + for card in self.game_card_cache.values(): + card.update_wp_columns_alignment(wp_visible) + # The vertical header only when WinePrefix visibility changes + if self.layout_mode != "vertical" or self.libraryContentLayout is None: + return + if self.libraryHeaderWidget is not None and wp_visible == old_wp_visible: + return + if self.libraryHeaderWidget is not None: + self.libraryHeaderWidget.setParent(None) + self.libraryHeaderWidget.deleteLater() + self.libraryHeaderWidget = None + self.libraryHeaderWidget = self._create_library_header() + self.libraryContentLayout.insertWidget(1, self.libraryHeaderWidget) + self._sync_header_width() def update_game_grid( self, @@ -964,6 +987,7 @@ class GameLibraryManager: parent=self.gamesListWidget, context_menu_manager=self.context_menu_manager ) + card.update_wp_columns_alignment(bool(self._wp_header_columns_visible)) card.hoverChanged.connect(self._on_card_hovered) card.focusChanged.connect(self._on_card_focused) diff --git a/portprotonqt/tabs/settings_tab.py b/portprotonqt/tabs/settings_tab.py index 43f44052..ba7d5904 100644 --- a/portprotonqt/tabs/settings_tab.py +++ b/portprotonqt/tabs/settings_tab.py @@ -348,7 +348,7 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase): self.showWinePrefixCheckBox = QCheckBox() self.showWinePrefixCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE) self.showWinePrefixCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus) - self.showWinePrefixTitle = QLabel(_("Show Wine version and Prefix name on Game cards and Library vertical")) + self.showWinePrefixTitle = QLabel(_("On game card wine and prefix")) self.showWinePrefixTitle.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) self.showWinePrefixTitle.setStyleSheet(self.theme.SETTINGS_TITLE_CHECKBOX_STYLE) self.showWinePrefixTitle.setFocusPolicy(Qt.FocusPolicy.NoFocus) -- 2.54.1