Compare commits

...
Author SHA1 Message Date
Boria138 cc8e7fa515 bump to 1.0
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-23 09:24:09 +05:00
Boria138 8865def11e fix: trigger build workflow on v tags
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-23 09:20:55 +05:00
Boria138 69f3d087b3 chore(locale): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-23 09:04:29 +05:00
Boria138 39c9e0e7ee Revert "feat: add container terminal tool"
This reverts commit fb7e5b4c0c.
2026-05-23 09:04:03 +05:00
Codeberg TranslateandBoria138 bdc486f695 Translated using Weblate (Russian)
Currently translated at 100.0% (661 of 661 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
Translation: PortProtonQt/PortProtonQt
2026-05-22 18:55:36 +00:00
Boria138 385a2b3535 chore(changelog): added a simplified chinese translator from Codeberg Translate
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 23:52:48 +05:00
Codeberg TranslateandPoesty Li f740ef1a53 Translated using Weblate (Chinese (Simplified Han script))
Currently translated at 100.0% (661 of 661 strings)

Added translation using Weblate (Chinese (Simplified Han script))

Co-authored-by: Codeberg Translate <translate@codeberg.org>
Co-authored-by: Poesty Li <poesty7450@gmail.com>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/zh_Hans/
Translation: PortProtonQt/PortProtonQt
2026-05-22 18:39:46 +00:00
Boria138 b78f838ffd chore(locale): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 23:39:38 +05:00
Boria138 36ca8a6b86 fix: translate folder delete confirmation buttons
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 23:28:10 +05:00
Boria138 fb7e5b4c0c feat: add container terminal tool
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 23:09:58 +05:00
Boria138 c3235ed7d0 fix: keep settings tabs populated on first startup
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 22:44:10 +05:00
Boria138 5676daa573 fix: support dbus-fast 2.x bluetooth annotations
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 20:12:19 +05:00
Codeberg TranslateandBoria138 fba71245ef Translated using Weblate (Russian)
Currently translated at 100.0% (661 of 661 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
Translation: PortProtonQt/PortProtonQt
2026-05-22 14:31:32 +00:00
Renovate Bot 8c2b80c97e chore(deps): update https://gitea.com/actions/setup-node digest to 48b55a0 2026-05-22 14:30:09 +00:00
Renovate Bot dbab969bd7 chore(deps): update archlinux:base-devel docker digest to 6db772f 2026-05-22 14:29:39 +00:00
Boria138 a8c273c7f1 chore: relax Renovate update restrictions
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 19:27:43 +05:00
Boria138 1bfdf82770 chore(locale): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 18:01:34 +05:00
Boria138 3645b7828b chore: rename MangoHud PortProton preset
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 18:01:05 +05:00
Boria138 1b72223930 feat: adjust file explorer default bookmarks
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 17:58:02 +05:00
Boria138 8268b95b53 chore(changelog): added a Spanish translator from Codeberg Translate
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 17:38:17 +05:00
Boria138 0477e065f2 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 13:36:56 +05:00
Boria138 5d027a9c8a fix: make JSON cache writes atomic
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 13:33:32 +05:00
Boria138 fbda9ae455 remove muvm launch support
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 12:22:34 +05:00
Boria138 e34ae0642d chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 12:17:57 +05:00
Boria138 0f28fa8474 refactor: move power profile control to Python
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 07:15:26 +00:00
Boria138 41f24c9cbc feat(scripts): reuse python functions for icons and shortcuts
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 07:15:26 +00:00
Codeberg TranslateandBoria138 e11a1e1a93 Translated using Weblate (Russian)
Currently translated at 100.0% (661 of 661 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
Translation: PortProtonQt/PortProtonQt
2026-05-22 07:12:07 +00:00
Boria138 b8c1d8595f chore(locale): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 12:10:34 +05:00
Boria138 4096bd541c feat: replace Xterm to own term
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 06:53:14 +00:00
Boria138 8c934f5875 feat: add PortProton downloads mirror setting
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 08:26:26 +05:00
Boria138 3a82a5859b fix: filter unsupported Wine versions for Steam games
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-22 08:15:03 +05:00
Mikhail Tergoev 8305d6ed65 add support portproton variables for steamplay 2026-05-22 01:43:13 +03:00
Mikhail Tergoev 2b863718f4 fix steamplay without ppdb file 2026-05-22 01:37:45 +03:00
Mikhail Tergoev c5bdc0db28 update PROTON_LG to 10-30 (work with steam) 2026-05-21 21:23:46 +03:00
Mikhail Tergoev 74e4b9e747 Merge branch 'main' of git.linux-gaming.ru:Linux-Gaming/PortProtonQt 2026-05-21 21:07:25 +03:00
Mikhail Tergoev e15df2eebb add variable: PW_USE_WOW64 2026-05-21 21:07:05 +03:00
Codeberg TranslateandBoria138 c3a02ed71d Translated using Weblate (Russian)
Currently translated at 99.6% (657 of 659 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
Translation: PortProtonQt/PortProtonQt
2026-05-21 10:44:33 +00:00
Boria138 4efc5caac9 chore(locale): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-21 15:41:33 +05:00
Boria138 57a87594af feat: add ppack prefix backup MIME integration
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-21 11:31:04 +05:00
Boria138 6157d58d83 chore: use squashfs-tools from plugins
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-21 05:18:17 +00:00
Boria138 c085c31005 chore: use xterm from plugins
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-21 05:18:17 +00:00
Boria138 863bec41a0 chore(settings): move download options from appearance
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-21 05:18:17 +00:00
Boria138 dc721cc697 feat: added disable runtime download settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-21 05:18:17 +00:00
Boria138 e8521a6a98 fix: enable portable gamemode auto preload
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-21 05:14:18 +00:00
Boria138 acc4818266 changed: refresh library after prefix backup restore
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-20 23:02:58 +05:00
Boria138 70685e0f45 Revert "fix: open prefix backup dialog in prefixes directory"
This reverts commit a7f5e0dfe9.
2026-05-20 22:34:52 +05:00
Boria138 a7f5e0dfe9 fix: open prefix backup dialog in prefixes directory
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-20 22:31:47 +05:00
Boria138 a0bd1f73d6 feat: add prefix backup icons to file explorer
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-20 22:22:55 +05:00
Boria138 352420cdf8 refactor: move Qt screen helpers to qt_utils
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-20 14:47:53 +05:00
Boria138 b0da061a29 feat: add clickable tab navigation arrows
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-20 14:34:04 +05:00
Boria138 27d1ccf7a8 fix: keep compact badges sharp and aligned
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-20 09:51:26 +05:00
Boria138 3847da55ab refactor: require dbus-fast imports directly
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-19 21:03:35 +05:00
Boria138 3e1e032618 fix: keep theme SVG icons sharp when UI is scaled
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-19 21:03:35 +05:00
Boria138 a0c5b33114 chore(build): finish migrate to Linux-Gaming
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-19 21:03:35 +05:00
Boria138 46cedbc934 fix: keep empty run-after exe value unchanged
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-19 21:03:34 +05:00
Dervart c7669a3c42 fix: compress screenshots 2026-05-19 08:55:32 +07:00
Boria138 589d2e6d5f feat: support relative paths for second exe
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-18 15:18:35 +05:00
Boria138 da681007c9 fix: remove APNG FPS limit
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-18 10:16:00 +05:00
Boria138 f8fa900a22 feat: configure theme variants via metainfo
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-18 09:54:09 +05:00
Boria138 30c3882b65 feat: add configurable tray menu modes
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-17 19:58:50 +05:00
Boria138 527b0c1af0 feat: add tray tab switching
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-17 19:43:55 +05:00
Boria138 1016a864ed feat: add CLI cache and settings reset commands
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-17 19:36:40 +05:00
Boria138 951503c48b changed: hide MangoHud controls for system config
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-17 19:31:45 +05:00
Boria138 451d57a6d2 feat: add PPDB clear button to exe settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-17 14:07:04 +05:00
Boria138 392f24f244 feat: add open Steam game folder action to context menu
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-17 11:05:26 +05:00
Boria138 b44ff8bbb6 docs: add prepare_env.sh and update setup instructions in README
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-17 10:23:27 +05:00
Boria138 97a348585f fix: hide GPU settings section for single-GPU systems
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-17 09:59:31 +05:00
Boria138 ef8ee4a821 fix: skip GPU override on single-GPU systems
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-16 23:19:05 +05:00
Boria138 b831742277 fix(image_utils): verify png format for animated covers
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-16 15:33:53 +05:00
Boria138 c1a45747e9 chore(steam): block PW_USE_INHIBIT_SLEEP (steam use own inhibit)
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-16 13:54:10 +05:00
Boria138 4e40460ba2 chore(steam): block PW_USE_INHIBIT_SLEEP (steam use own inhibit)
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-16 13:37:51 +05:00
Boria138 b66841e8b7 fix: resolve Steam Play Proton runner lookup
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-16 13:21:59 +05:00
Boria138 4d34c24cdf chore(build): added python3-pillow-qt to Fedora
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-16 11:16:16 +05:00
Boria138 65bc286494 chore(appimage): fix typo
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 22:51:12 +05:00
Boria138 cb91b41b46 chore(appimage): libqwebp.so
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 22:50:06 +05:00
Boria138 c24aec0e40 fix: bundle WebP Qt image plugin in AppImage
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 22:47:29 +05:00
Boria138 54271548ec fix: keep AppImage runtime libraries in sync
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 22:13:00 +05:00
Boria138 a9552a3c1b chore(build): make pefile explicit
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 15:58:34 +05:00
Boria138 88c30025de fix: refresh detail layout after HLTB load
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 11:50:15 +05:00
Boria138 1aac62b647 Revert "adapt detail page between full and compact modes"
This reverts commit 08131ea53f.
2026-05-15 11:47:43 +05:00
Boria138 08131ea53f adapt detail page between full and compact modes
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 11:13:02 +05:00
Boria138 2666159375 reduce HEAD cache files
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 10:59:37 +05:00
Boria138 3515ad0ac5 fix: update HowLongToBeat search API
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 10:57:20 +05:00
Boria138 0875896e45 fix: remove downloader network preflight checks
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 10:30:51 +05:00
Boria138 4f406cc966 chore: show source badges regardless of display filter
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-15 10:26:27 +05:00
Boria138 f9e0081fd6 Improve MDF to ISO sector conversion
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 22:39:27 +05:00
Boria138 bc4ba2169d fix: add missing RPM packaged files
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 22:22:43 +05:00
Boria138 cfc05c2017 chore: remove redundant defaults for APP_COMMIT and APP_VERSION
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 20:47:27 +05:00
Boria138 55fba9260e build: include commit hash in nightly version
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-05-14 20:32:34 +05:00
137 changed files with 7238 additions and 1617 deletions

No files matched your search

+3 -3
View File
@@ -13,7 +13,7 @@ jobs:
name: Build AppImage
runs-on: ubuntu-22.04
container:
image: archlinux:base-devel@sha256:c528201c37821ac7883af233a18eba79fbce9bd900aeae07462888a607741abe
image: archlinux:base-devel@sha256:6db772fd1dd128b9cf7b7231ca5284af70879596fe4ec754c911cfc4ac30d5eb
options: --privileged --device /dev/fuse
steps:
- name: Prepare container
@@ -76,7 +76,7 @@ jobs:
- name: Copy fedora.spec
run: |
sed "s|git clone https://git.linux-gaming.ru/Boria138/PortProtonQt.git|git clone -b ${{ env.BUILD_BRANCH }} https://git.linux-gaming.ru/Boria138/PortProtonQt.git|" \
sed "s|git clone https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt.git|git clone -b ${{ env.BUILD_BRANCH }} https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt.git|" \
build-aux/fedora-git.spec > /home/rpmbuild/SPECS/${{ env.PACKAGE }}.spec
chown -R rpmbuild:users /home/rpmbuild
@@ -94,7 +94,7 @@ jobs:
name: Build Arch Package
runs-on: ubuntu-22.04
container:
image: archlinux:base-devel@sha256:c528201c37821ac7883af233a18eba79fbce9bd900aeae07462888a607741abe
image: archlinux:base-devel@sha256:6db772fd1dd128b9cf7b7231ca5284af70879596fe4ec754c911cfc4ac30d5eb
steps:
- name: Prepare container
+2 -2
View File
@@ -4,11 +4,11 @@ on:
workflow_dispatch:
push:
tags:
- 'v[0-9]+.[0-9]+.[0-9]+'
- 'v[0-9]*.[0-9]*'
env:
# Common version, will be used for tagging the release
VERSION: 0.1.12
VERSION: 1.0
PKGDEST: "/tmp/portprotonqt"
PACKAGE: "portprotonqt"
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
+4 -4
View File
@@ -68,7 +68,7 @@ jobs:
needs: changes
if: needs.changes.outputs.appimage == 'true' || github.event_name == 'workflow_dispatch'
container:
image: archlinux:base-devel@sha256:c528201c37821ac7883af233a18eba79fbce9bd900aeae07462888a607741abe
image: archlinux:base-devel@sha256:6db772fd1dd128b9cf7b7231ca5284af70879596fe4ec754c911cfc4ac30d5eb
options: --privileged --device /dev/fuse
steps:
- name: Prepare container
@@ -129,7 +129,7 @@ jobs:
- name: Copy fedora-git.spec
run: |
sed "s|git clone https://git.linux-gaming.ru/Boria138/PortProtonQt.git|git clone -b ${{ env.PR_BRANCH }} ${{ env.PR_REPO_URL }}|" \
sed "s|git clone https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt.git|git clone -b ${{ env.PR_BRANCH }} ${{ env.PR_REPO_URL }}|" \
build-aux/fedora-git.spec > /home/rpmbuild/SPECS/${{ env.PACKAGE }}.spec
chown -R rpmbuild:users /home/rpmbuild
@@ -149,7 +149,7 @@ jobs:
needs: changes
if: needs.changes.outputs.arch == 'true' || github.event_name == 'workflow_dispatch'
container:
image: archlinux:base-devel@sha256:c528201c37821ac7883af233a18eba79fbce9bd900aeae07462888a607741abe
image: archlinux:base-devel@sha256:6db772fd1dd128b9cf7b7231ca5284af70879596fe4ec754c911cfc4ac30d5eb
steps:
- name: Prepare container
@@ -184,7 +184,7 @@ jobs:
cd /__w/portproton-repo
git clone -b ${{ env.PR_BRANCH }} ${{ env.PR_REPO_URL }} PortProtonQt
cd /__w/portproton-repo/PortProtonQt/build-aux
sed -i "s|source=(\"git+https://git.linux-gaming.ru/Boria138/PortProtonQt.git\")|source=(\"git+${{ env.PR_REPO_URL }}#branch=${{ env.PR_BRANCH }}\")|" PKGBUILD-git
sed -i "s|source=(\"git+https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt.git\")|source=(\"git+${{ env.PR_REPO_URL }}#branch=${{ env.PR_BRANCH }}\")|" PKGBUILD-git
chown user -R ..
su user -c "yes '' | makepkg --noconfirm -s -p PKGBUILD-git"
+1 -1
View File
@@ -23,7 +23,7 @@ jobs:
- uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Set up Node.js
uses: https://gitea.com/actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
uses: https://gitea.com/actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
with:
node-version: 20
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
- uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Set up Node.js
uses: https://gitea.com/actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
uses: https://gitea.com/actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
with:
node-version: 20
+5
View File
@@ -799,6 +799,11 @@ PortProtonQt/
| Requests | HTTP | Apache-2.0 |
| Pillow | Image handling | MIT |
### Compatibility
- Keep `dbus-fast` 2.x compatibility for Fedora
- Do not use `dbus_fast.annotations` or `DBusSignature`
**License compatibility:**
- MIT, Apache-2.0, BSD: Compatible
- LGPL: Requires dynamic linking
+39 -4
View File
@@ -3,33 +3,46 @@
Все заметные изменения в этом проекте фиксируются в этом файле.
Формат основан на [Keep a Changelog](https://keepachangelog.com/) и придерживается принципов [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [1.0] - 2026-05-23
### Added
- Окно теперь можно перетаскивать левой кнопкой мыши по любой области
- В файловый менеджер добавлены действия создания, удаления и переименования папки
- В файловый менеджер добавлены иконки для резервных копий префиксов PortProton
- Достигнут 100% паритет с PortProton
- Добавлен экономный режим с минимальным количеством сетевых запросов
- Через тему теперь можно указать режим сетки библиотеки
- Виртуальная клавиатура теперь имеет анимацию появления
- Добавлено больше типов анимаций для карточки
- PortProtonQT теперь имеет встроенные скрипты, и не требуют установленного PortProton для работы
- Проведена общая чистка кода, как скриптов PortProton так и кода PortProtonQT
- В скриптах добавлен фикс для работы Melon Mod-Loader
- В скриптах улучшен код запрета ухода в сон и удалена зависимость от systemd
- В настройки PortProtonQt добавлена галочка `Использовать системный DPI для Wine`
- В настройки PortProtonQt добавлена галочка `Отключить скачивание контейнера` которая позволяет не скачивать Steam Runtime
- Аргумент командной строки `--silent` для запуска `exe` с минимальным треем
- В трей добавлена остановка запущенной игры
- В скриптах добавлена поддержка внешних Proton из каталогов Steam `steamapps` и `compatibilitytools.d`
- Добавлена классическая тема, приближенная по внешнему виду к PortProton для облегчения перехода на PortProtonQt
- Добавлены светлые темы
- Добавлен выбор цветовой схемы во вкладку `Темы`
- Для обложек добавлена поддержка APNG, animated WebP, GIF и JXL
- Добавлена поддержка запуска `.mdf`
- Добавлена MIME-ассоциация `.ppack` с PortProtonQt для восстановления резервных копий префиксов из файлового менеджера
- Добавлен аргумент командной строки `--restore-prefix` для восстановления резервной копии префикса
- Добавлен аргумент командной строки `--create-backup` для создания резервной копии префикса
- Добавлена приостановка фоновой активности при потере фокуса окна
- При запуске теперь генерируются отсутствующие изображения в `data/img` для найденных `.exe`
- Для игр из Steam добавлено создание ярлыков на рабочем столе и в меню
- В контекстное меню игр из Steam добавлено открытие папки игры
- В настройки добавлена загрузка Wine/Proton в Steam `compatibilitytools.d`
- В настройки добавлен выбор зеркала загрузок PortProton
- В настройки `.exe` добавлена кнопка очистки PPDB
- Аргументы командной строки `--clear-cache` и `--reset-settings`
- Добавлено переключение вкладок при клике по стрелкам навигации
- При запуске через инструмент совместимости Steam добавлена поддержка переменных PortProton
### Changed
- Бейджи источников (Steam и PortProton) теперь отображаются при любом фильтре библиотеки
- В стандартных закладках файлового менеджера добавлена домашняя папка пользователя и удалён корневой каталог `/`
- Обложки к играм из Steam теперь полностью локальные
- Улучшен механизм кеширования данных
- Тип геймпада `Xbox` `PS` теперь выбирается автоматически
@@ -44,10 +57,24 @@
- Формат BMP больше не поддерживается для обложек игр
- Автоматическое фоновое обновление Bluetooth-устройств удалено
- Улучшенно качестве иконок из `exe` файлов
- Переработан трей
- В трей добавлены компактный и детальный режимы меню
- Автоустановки теперь можно остановить
- Префиксы `DEFAULT`, `DOTNET` и `PROGRAMS` теперь всегда отображаются вверху списков префиксов
- Из лога удалена версия скриптов, так как скрипты теперь внутри PortProtonQt
- Из downloader удалена отдельная проверка сети через Yandex и Google
- Выбор видеокарты теперь не отображается в настройках PortProtonQt если видеокарта всего одна
- Через тему теперь можно указать режим сетки библиотеки
- Теме теперь можно указать из какой темы наследоваться, а не только из стандартной
- Виртуальная клавиатура теперь имеет анимацию появления
- В настройках MangoHud и Gamescope при выключении, а также при использовании системного конфига MangoHud теперь скрываются лишние элементы управления
- Поле запуска второго `.exe` теперь поддерживает относительные пути
- Сетка библиотеки теперь обновляется после восстановления резервной копии префикса
- Xterm заменён на самописный терминал с улучшенной интеграцией с winecmd
- `PROTON_LG` обновлён до версии `10-30`
- Удалена поддержка запуска через `muvm` и аргумент командной строки `--force-muvm`
- Начат испанский перевод `https://translate.codeberg.org/projects/portprotonqt/portprotonqt/es/`
- Добавлен перевод на Китайский (упрощённый) `https://translate.codeberg.org/projects/portprotonqt/portprotonqt/zh_Hans/`
- Пресет MangoHud `Стандартный PortProton` переименован в `PortProton`
### Fixed
- Исправлено определение `PW_USE_RUNTIME` в debug-логе
@@ -65,11 +92,19 @@
- Исправлено управление геймпадом в диалоге выбора файла для загрузки PPDB
- Исправлен повторный вывод одинаковых Vulkan GPU в `vk_gpu_info`
- Исправлена работа клавиатурного управления при раскладке, отличной от английской
- Исправлена загрузка данных HowLongToBeat
- Исправлена навигация геймпадом к кнопке выбора второго `.exe`
- Исправлено размытие SVG-иконок при масштабировании интерфейса
- В настройках игр из Steam больше не отображаются неподдерживаемые Wine/Proton
- Исправлена работа portablle версии gamemode
- Исправлен запуск через инструмент совместимости Steam без файла `.ppdb`
### Contributors
- @Dervart
- @Castro-Fidel
- @Simple16
- @gallegonovato
- @Poesty Li
---
+13 -9
View File
@@ -24,18 +24,21 @@ source .venv/bin/activate.fish # For fish
### Разработка
В проект встроен линтер (ruff), статический анализатор (pyright) и проверка lock файла, если эти проверки не пройдут PR не будет принят, поэтому перед коммитом введите такую команду
Для автоматической подготовки окружения (установка Python 3.10, зависимостей, pre-commit хуков и генерация переводов) выполните скрипт:
```sh
uv python install 3.10
uv sync --all-extras --dev
source .venv/bin/activate # For bash/zsh
# or
source .venv/bin/activate.fish # For fish
pre-commit install
./dev-scripts/prepare_env.sh
```
pre-commit сам запустится при коммите, если вы хотите запустить его вручную введите команду
Затем активируйте виртуальное окружение. Команда активации для вашей оболочки будет выведена в конце работы скрипта. Обычно это:
```sh
source .venv/bin/activate # Для bash/zsh
# или
source .venv/bin/activate.fish # Для fish
```
pre-commit сам запустится при коммите, если вы хотите запустить его вручную введите команду:
```sh
pre-commit run --all-files
@@ -57,7 +60,8 @@ PortProtonQt использует код и зависимости от след
- [Icoextract](https://github.com/jlu5/icoextract) — библиотека для извлечения иконок, лицензия [MIT](https://github.com/jlu5/icoextract/blob/master/LICENSE).
- [HowLongToBeat Python API](https://github.com/ScrappyCocco/HowLongToBeat-PythonAPI) — библиотека для взаимодействия с HowLongToBeat, лицензия [MIT](https://github.com/ScrappyCocco/HowLongToBeat-PythonAPI/blob/master/LICENSE.md).
- [mdf2iso](https://github.com/ScrappyCocco/HowLongToBeat-PythonAPI) — библиотека для конвертации mdf в iso, лицензия [GPLv2](https://salsa.debian.org/debian/mdf2iso/-/blob/master/gpl.txt).
- [iat](https://sourceforge.net/projects/iat.berlios) — библиотека для конвертации mdf в iso, лицензия GPLv3
- [pyte](https://github.com/selectel/pyte) — разбор ANSI escape-кодов, лицензия [LGPLv3](https://github.com/selectel/pyte?tab=LGPL-3.0-1-ov-file)
Полный текст лицензий см. в файле [LICENSE](LICENSE).
> [!WARNING]
+1 -1
View File
@@ -88,7 +88,7 @@ EOM
# Disable locale noextract
sed -i -E 's@[[:space:]]*usr/share/locale/\*@@g; s@[[:space:]]+@ @g; s@[[:space:]]+$@@' /etc/pacman.conf
pacman -Syy
pacman -Syyu --noconfirm --disable-download-timeout
echo "Building PortProtonQt from PKGBUILD..."
echo "---------------------------------------------------------------"
+2 -1
View File
@@ -11,6 +11,7 @@ export DESKTOP=/usr/share/applications/ru.linux_gaming.PortProtonQt.desktop
export ICON=/usr/share/icons/hicolor/scalable/apps/ru.linux_gaming.PortProtonQt.svg
export OUTNAME=PortProtonQt-"$VERSION"-anylinux-"$ARCH".AppImage
export DEPLOY_OPENGL=1
export DEPLOY_SDL=1
export DEPLOY_SYS_PYTHON=1
export OPTIMIZE_LAUNCH=1
@@ -40,7 +41,7 @@ fi
/usr/lib/libQt6Core.so* \
/usr/lib/libQt6Gui.so* \
/usr/lib/libQt6Network.so* \
/usr/lib/libudev.so*
/usr/lib/qt6/plugins/imageformats/libqwebp.so
# Turn AppDir into AppImage
./quick-sharun --make-appimage
+2 -3
View File
@@ -1,13 +1,12 @@
pkgname=('portprotonqt' 'portprotonqt-steam-compat')
pkgver=0.1.12
pkgver=1.0
pkgrel=1
pkgdesc="Modern GUI for managing and launching games from PortProton and Steam"
arch=('any')
url="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt"
license=('GPL-3.0')
depends=('python-requests' 'python-babel' 'python-evdev' 'python-pygame' 'python-orjson'
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-beautifulsoup4' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'jq' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' 'squashfs-tools' '7zip' 'python-dbus-fast')
depends_aarch64=('muvm')
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'jq' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'qt6-imageformats' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' 'squashfs-tools' '7zip' 'python-dbus-fast')
makedepends=('meson' 'ninja' 'vulkan-headers' 'gettext')
source=("git+https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt#tag=v$pkgver")
sha256sums=('SKIP')
+2 -3
View File
@@ -6,8 +6,7 @@ arch=('any')
url="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt"
license=('GPL-3.0')
depends=('python-requests' 'python-babel' 'python-evdev' 'python-pygame' 'python-orjson'
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-beautifulsoup4' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'jq' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' 'squashfs-tools' '7zip' 'python-dbus-fast')
depends_aarch64=('muvm')
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'jq' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'qt6-imageformats' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' 'squashfs-tools' '7zip' 'python-dbus-fast')
makedepends=('meson' 'ninja' 'vulkan-headers' 'gettext')
source=("git+https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt.git")
sha256sums=('SKIP')
@@ -18,7 +17,7 @@ pkgver() {
}
build() {
arch-meson PortProtonQt build
arch-meson PortProtonQt build -Dnightly=true
meson compile -C build
}
+7 -6
View File
@@ -1,5 +1,5 @@
%global pypi_name portprotonqt
%global pypi_version 0.1.12
%global pypi_version 1.0
%global oname PortProtonQt
%global build_timestamp %(date +"%Y%m%d")
%global _python_no_extras_requires 1
@@ -39,11 +39,12 @@ Requires: python3-tqdm
Requires: python3-vdf
Requires: python3-pefile
Requires: python3-pillow
Requires: python3-beautifulsoup4
Requires: python3-pillow-qt
Requires: python3-rapidfuzz
Requires: python3-libarchive-c
Requires: perl-Image-ExifTool
Requires: qt6-qtsvg
Requires: qt6-qtimageformats
Requires: cabextract
Requires: gzip
Requires: unzip
@@ -73,10 +74,6 @@ Recommends: upower
Recommends: pulseaudio-utils
Recommends: python3-qrcode
%ifarch aarch64
Requires: muvm
%endif
%description
A modern and intuitive interface for managing and launching games from PortProton and Steam. Combines libraries in one place and simplifies running Windows games on Linux.
@@ -97,6 +94,7 @@ git clone https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt.git
%build
cd %{oname}
%meson \
-Dnightly=true \
-Dpython_purelibdir=%{python3_sitelib} \
-Dudev_rulesdir=%{_udevrulesdir}
%meson_build
@@ -119,7 +117,10 @@ install -Dpm 0644 ./completions/_portprotonqt -t %{buildroot}%{zsh_completions_d
%{_udevrulesdir}/60-portprotonqt.rules
%{_datadir}/polkit-1/rules.d/ru.linux_gaming.PortProtonQt.rules
%{_datadir}/applications/ru.linux_gaming.PortProtonQt.desktop
%{_datadir}/mime/packages/ru.linux_gaming.PortProtonQt.xml
%{_datadir}/portproton/scripts/
%{_datadir}/portproton/conf/
%{_datadir}/portproton/img/
%{bash_completions_dir}/portprotonqt
%{fish_completions_dir}/portprotonqt.fish
%{zsh_completions_dir}/_portprotonqt
+6 -6
View File
@@ -1,5 +1,5 @@
%global pypi_name portprotonqt
%global pypi_version 0.1.12
%global pypi_version 1.0
%global oname PortProtonQt
%global _python_no_extras_requires 1
@@ -36,11 +36,12 @@ Requires: python3-tqdm
Requires: python3-vdf
Requires: python3-pefile
Requires: python3-pillow
Requires: python3-beautifulsoup4
Requires: python3-pillow-qt
Requires: python3-rapidfuzz
Requires: python3-libarchive-c
Requires: perl-Image-ExifTool
Requires: qt6-qtsvg
Requires: qt6-qtimageformats
Requires: cabextract
Requires: gzip
Requires: unzip
@@ -70,10 +71,6 @@ Recommends: upower
Recommends: pulseaudio-utils
Recommends: python3-qrcode
%ifarch aarch64
Requires: muvm
%endif
%description
A modern and intuitive interface for managing and launching games from PortProton and Steam. Combines libraries in one place and simplifies running Windows games on Linux.
@@ -118,7 +115,10 @@ install -Dpm 0644 ./completions/_portprotonqt -t %{buildroot}%{zsh_completions_d
%{_udevrulesdir}/60-portprotonqt.rules
%{_datadir}/polkit-1/rules.d/ru.linux_gaming.PortProtonQt.rules
%{_datadir}/applications/ru.linux_gaming.PortProtonQt.desktop
%{_datadir}/mime/packages/ru.linux_gaming.PortProtonQt.xml
%{_datadir}/portproton/scripts/
%{_datadir}/portproton/conf/
%{_datadir}/portproton/img/
%{bash_completions_dir}/portprotonqt
%{fish_completions_dir}/portprotonqt.fish
%{zsh_completions_dir}/_portprotonqt
@@ -11,4 +11,4 @@ Terminal=false
Icon=ru.linux_gaming.PortProtonQt
StartupWMClass=ru.linux_gaming.PortProtonQt
Categories=Game;Utility;
MimeType=x-scheme-handler/portproton;application/x-ms-dos-exec;application/x-executable;application/x-dosexec;application/x-iso9660-image;application/x-cd-image;application/x-raw-disk-image;application/x-mdf;application/x-mds-disk;
MimeType=x-scheme-handler/portproton;application/x-portproton-prefix-backup;application/x-ms-dos-exec;application/x-executable;application/x-dosexec;application/x-iso9660-image;application/x-cd-image;application/x-raw-disk-image;application/x-mdf;application/x-mds-disk;
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
<mime-type type="application/x-portproton-prefix-backup">
<comment>PortProton prefix backup</comment>
<comment xml:lang="ru">Резервная копия префикса PortProton</comment>
<glob pattern="*.ppack"/>
<sub-class-of type="application/vnd.squashfs"/>
</mime-type>
</mime-info>
@@ -145,7 +145,7 @@ pw_enable_idle_inhibit() {
return
fi
PW_INHIBIT_SLR="python3 -m portprotonqt.idle_inhibit"
PW_INHIBIT_SLR="python3 -m portprotonqt.scripts_utils.idle_inhibit"
print_info "Screensaver will be inhibited using D-Bus"
}
@@ -1214,7 +1214,7 @@ init_wine_ver () {
export WINEDIR="${PW_WINE_USE}"
PW_EXTERNAL_WINE_DIR=1
else
export WINEDIR="${PORT_DATA_PATH}/data/dist/${PW_WINE_USE}"
export WINEDIR="${PORT_DATA_PATH}/data/dist/${PW_WINE_USE^^}"
fi
if [[ -d "${WINEDIR}/files" && ! -d "${WINEDIR}/dist" ]] ; then
export WINEDIR="${WINEDIR}/files"
@@ -1223,6 +1223,7 @@ init_wine_ver () {
if [[ "$PW_USE_WOW64" == "1" ]] \
&& [[ -d "${WINEDIR}/bin-wow64" ]]
then
print_warning "wine wow64 mode in use!"
export WINE="${WINEDIR}/bin-wow64/wine"
export WINELOADER="${WINEDIR}/bin-wow64/wine"
export WINESERVER="${WINEDIR}/bin-wow64/wineserver"
@@ -1282,14 +1283,18 @@ init_wine_ver () {
}
pw_init_runtime () {
check_flatpak && export PW_USE_RUNTIME="0"
if [[ ! -f "${PW_WINELIB}/runtime/files/bin/vkcube" ]] \
|| [[ ! -f "${PW_WINELIB}/pressure-vessel/bin/pressure-vessel-wrap" ]]
then
export PW_USE_RUNTIME="0"
fi
if [[ "$PW_USE_RUNTIME" != "1" ]] \
|| [[ "$PW_WINE_USE" == "USE_SYSTEM_WINE" ]]
then
export PW_LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${PW_PLUGINS_PATH}/portable/lib/lib64:${PW_PLUGINS_PATH}/portable/lib/lib32"
export PW_VK_LAYER_PATH="${PW_PLUGINS_PATH}/portable/share/vulkan/implicit_layer.d"
if [[ -z "$PW_TERM" ]] ; then
export PW_TERM="env LD_LIBRARY_PATH=\"${PW_LD_LIBRARY_PATH}\" ${PW_PLUGINS_PATH}/portable/bin/xterm -bg black -fg white -e"
export PW_TERM="env LD_LIBRARY_PATH=\"${PW_LD_LIBRARY_PATH}\" python3 -m portprotonqt.easyterm -e"
fi
export pw_runtime="env"
return 0
@@ -1376,7 +1381,7 @@ ${PW_PV_OVERRIDES}/i386-linux-gnu/aliases:\
for PWRTMRW in "${PW_RT_MOUNT_RW[@]}" ; do
export PRESSURE_VESSEL_FILESYSTEMS_RW="${PRESSURE_VESSEL_FILESYSTEMS_RW:+$PRESSURE_VESSEL_FILESYSTEMS_RW:}${PWRTMRW}"
done
export PW_TERM="env LD_LIBRARY_PATH=\"${PW_LD_LIBRARY_PATH}\" ${PW_PLUGINS_PATH}/portable/bin/xterm -bg black -fg white -e"
export PW_TERM="env LD_LIBRARY_PATH=\"${PW_LD_LIBRARY_PATH}\" python3 -m portprotonqt.easyterm -e"
print_info "RUNTIME is enabled"
}
@@ -1627,8 +1632,10 @@ stop_portproton () {
find "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/" -maxdepth 1 -type f -name "*.tmp" -delete
pw_auto_create_shortcut
add_in_stop_portproton
if [[ -n "$PW_POWERPROFILECTL_PROFILE" ]] && [[ "$(pw_ppd_dbus_get_profile)" != "$PW_POWERPROFILECTL_PROFILE" ]] ; then
pw_ppd_dbus_set_profile "$PW_POWERPROFILECTL_PROFILE"
if [[ -n "$PW_POWERPROFILECTL_PROFILE" ]] \
&& [[ "$(python3 -m portprotonqt.scripts_utils.power_profiles get)" != "$PW_POWERPROFILECTL_PROFILE" ]]
then
python3 -m portprotonqt.scripts_utils.power_profiles set "$PW_POWERPROFILECTL_PROFILE" &>/dev/null
fi
if [[ $PW_LOG != 1 ]] && [[ -n $START_PW_TIME_IN_GAME ]] ; then
@@ -2251,15 +2258,12 @@ pw_create_gui_png () {
if [[ -z $name_desktop_png ]] ; then
basename_PW_EXE_FILE="$(basename "${PW_EXE_FILE}")"
if echo "$basename_PW_EXE_FILE" | grep -ie 'setup\|install\|\.msi$' &>/dev/null ; then
export PW_ICON_FOR_YAD="${PORT_DATA_PATH}/data/img/setup.png"
export name_desktop_png="setup"
return 0
elif echo "$basename_PW_EXE_FILE" | grep -ie '\.reg$' &>/dev/null ; then
export PW_ICON_FOR_YAD="${PORT_DATA_PATH}/data/img/reg.png"
export name_desktop_png="reg"
return 0
elif echo "$basename_PW_EXE_FILE"| grep -ie '\.bat$' &>/dev/null ; then
export PW_ICON_FOR_YAD="${PORT_DATA_PATH}/data/img/bat.png"
export name_desktop_png="bat"
return 0
fi
@@ -2304,7 +2308,7 @@ pw_create_gui_png () {
fi
fi
resize_png "$PW_EXE_FILE" "${PORTPROTON_NAME}" "48" "128"
resize_png "$PW_EXE_FILE" "${PORTPROTON_NAME}"
PORTPROTON_NAME_PNG="${PORTPROTON_NAME// /_}"
if [[ $PORTPROTON_NAME_PNG =~ [\!\%\$\&\<] ]] ; then
@@ -2313,15 +2317,9 @@ pw_create_gui_png () {
PORTPROTON_NAME_PNG="${PORTPROTON_NAME_PNG//$i/}"
done
fi
if [[ -z "${PW_ICON_FOR_YAD}" ]] ; then
if [[ -n "$(file "${PORT_DATA_PATH}/data/img/${PORTPROTON_NAME_PNG}.png" | grep "${PW_RESIZE_TO} x ${PW_RESIZE_TO}")" ]] ; then
export PW_ICON_FOR_YAD="${PORT_DATA_PATH}/data/img/${PORTPROTON_NAME_PNG}.png"
else
export PW_ICON_FOR_YAD="${PW_GUI_ICON_PATH}/port_proton.png"
fi
fi
}
pw_create_unique_exe () {
BASEDIR_GAME="$(dirname "$PW_EXE_FILE")"
if [[ -d "$BASEDIR_GAME" ]] ; then
@@ -2496,12 +2494,12 @@ pw_enable_gamemode_basic () {
fi
else
export GAMEMODERUN=1
if [[ -n "${PW_LD_PRELOAD}" ]]; then
export PW_LD_PRELOAD="${PW_LD_PRELOAD}:libgamemodeauto.so.0"
else
export PW_LD_PRELOAD="libgamemodeauto.so.0"
fi
if ! pw_is_process_active gamemoded ; then
if [[ -n "${PW_LD_PRELOAD}" ]]; then
export PW_LD_PRELOAD="${PW_LD_PRELOAD}:libgamemodeauto.so.0"
else
export PW_LD_PRELOAD="libgamemodeauto.so.0"
fi
env LD_LIBRARY_PATH="${PW_PLUGINS_PATH}/portable/lib/lib64:${PW_PLUGINS_PATH}/portable/lib/lib32" \
"${PW_PLUGINS_PATH}/portable/bin/gamemoded" &>/dev/null &
sleep 0.1
@@ -2515,7 +2513,7 @@ pw_enable_gamemode_basic () {
start_portproton () {
pw_check_and_download_plugins
if check_flatpak ; then
if [[ "${PW_DISABLE_RUNTIME_DOWNLOAD}" == "1" ]] ; then
try_remove_dir "${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}"
else
pw_check_and_download_runtime
@@ -2897,48 +2895,6 @@ start_portproton () {
unset __GLX_VENDOR_LIBRARY_NAME
fi
pw_ppd_dbus_get_profile() {
if ! command -v gdbus &>/dev/null; then
return 1
fi
local result
result=$(gdbus call --system \
--dest net.hadess.PowerProfiles \
--object-path /net/hadess/PowerProfiles \
--method org.freedesktop.DBus.Properties.Get \
'net.hadess.PowerProfiles' 'ActiveProfile' 2>/dev/null)
[[ -n "$result" ]] && echo "$result" | sed "s/.*'\([^']*\)'.*/\1/" || return 1
}
export -f pw_ppd_dbus_get_profile
pw_ppd_dbus_set_profile() {
local profile="$1"
if ! command -v gdbus &>/dev/null; then
return 1
fi
gdbus call --system \
--dest net.hadess.PowerProfiles \
--object-path /net/hadess/PowerProfiles \
--method org.freedesktop.DBus.Properties.Set \
'net.hadess.PowerProfiles' 'ActiveProfile' "<'$profile'>" &>/dev/null
}
export -f pw_ppd_dbus_set_profile
pw_ppd_dbus_has_profile() {
local profile="$1"
if ! command -v gdbus &>/dev/null; then
return 1
fi
local result
result=$(gdbus call --system \
--dest net.hadess.PowerProfiles \
--object-path /net/hadess/PowerProfiles \
--method org.freedesktop.DBus.Properties.GetAll \
'net.hadess.PowerProfiles' 2>/dev/null)
[[ "$result" == *"'$profile'"* ]]
}
export -f pw_ppd_dbus_has_profile
if check_gamescope_session ; then
export PW_GAMEMODERUN_SLR=""
elif [[ "$PW_USE_GAMEMODE" = "1" ]] \
@@ -2947,9 +2903,12 @@ export -f pw_ppd_dbus_has_profile
if pw_is_process_active ananicy ananicy-cpp scx scx_loader falcond ; then
export GAMEMODERUN=0
export PW_GAMEMODERUN_SLR=""
if pw_ppd_dbus_has_profile "performance" && [[ "$(pw_ppd_dbus_get_profile)" != "performance" ]] ; then
export PW_POWERPROFILECTL_PROFILE=$(pw_ppd_dbus_get_profile)
pw_ppd_dbus_set_profile performance
local current_power_profile
current_power_profile=$(python3 -m portprotonqt.scripts_utils.power_profiles get)
if [[ -n "$current_power_profile" && "$current_power_profile" != "performance" ]] \
&& python3 -m portprotonqt.scripts_utils.power_profiles set performance &>/dev/null
then
export PW_POWERPROFILECTL_PROFILE="$current_power_profile"
print_info "Gamemode replaced by power-profiles-daemon/tuned-ppd/tlp-pd via D-Bus to avoid conflicts"
else
export PW_POWERPROFILECTL_PROFILE=""
@@ -3718,6 +3677,15 @@ export -f pw_ppd_dbus_has_profile
}
pw_run () {
if [[ "$PW_USE_TERMINAL" == 1 ]] \
&& [[ "${PRESSURE_VESSEL_TERMINAL:-}" != "tty" ]]
then
local pw_terminal_command
printf -v pw_terminal_command "%q " pw_run "$@"
PRESSURE_VESSEL_TERMINAL=tty $PW_TERM "$pw_terminal_command"
return $?
fi
if [[ -n "${PATH_TO_GAME}" ]] \
&& [[ -d "${PATH_TO_GAME}" ]]
then
@@ -3770,7 +3738,6 @@ pw_run () {
"${WINELOADER}" "$@" ${proxy_launch_parameters} &>>"${PW_LOG_FILE}"
else
if [[ "$PW_USE_TERMINAL" == 1 ]] ; then
PW_ADD_TO_ARGS_IN_RUNTIME="--xterm"
pw_init_runtime
fi
echo ""
@@ -3844,11 +3811,13 @@ steamplay_launch () {
pw_check_and_download_plugins
if [[ -n "${PW_EXE_FILE:-}" ]]; then
local proton_runner
local steamplay_ld_library_path
cd "$(dirname "${PW_EXE_FILE}")"
export PATH_TO_GAME="$(pwd)"
export PORTWINE_DB_FILE="${PW_EXE_FILE}.ppdb"
[[ -f "${PORTWINE_DB_FILE}" ]] && source "${PORTWINE_DB_FILE}"
export PW_USE_SUPPLIED_DXVK_VKD3D="1"
steamplay_ld_library_path="${LD_LIBRARY_PATH}:${STEAM_RUNTIME_LIBRARY_PATH}:${PW_PLUGINS_PATH}/portable/lib/lib64:${PW_PLUGINS_PATH}/portable/lib/lib32"
[[ -d "${HOME}/.local/share/Steam/ubuntu12_32" ]] && steamplay_ld_library_path="${steamplay_ld_library_path}:${HOME}/.local/share/Steam/ubuntu12_32"
@@ -3895,6 +3864,40 @@ steamplay_launch () {
export VK_ADD_LAYER_PATH="${PW_VK_LAYER_PATH}"
export VK_INSTANCE_LAYERS="${PW_VK_INSTANCE_LAYERS}"
[[ $PW_LOG != 1 ]] && debug_timer --start -s "PW_TIME_IN_GAME"
if [[ "${PW_WINE_USE,,}" != *proton* ]] ; then
fatal "Steamplay don\`t work with ${PW_WINE_USE}!"
else
init_wine_ver
fi
check_proton_runner () {
if [[ -x "${STEAM_COMPAT_TOOL_PATHS%%:*}/proton" ]] ; then
proton_runner="${STEAM_COMPAT_TOOL_PATHS%%:*}/proton"
elif [[ "${PW_WINE_USE:-}" = /* ]] && [[ -x "${PW_WINE_USE}/proton" ]] ; then
proton_runner="${PW_WINE_USE}/proton"
elif [[ -x "${PORT_DATA_PATH}/data/dist/${PW_WINE_USE^^}/proton" ]] ; then
proton_runner="${PORT_DATA_PATH}/data/dist/${PW_WINE_USE^^}/proton"
export PW_WINE_USE="${PW_WINE_USE^^}"
elif [[ -x "${WINEDIR}/proton" ]] ; then
proton_runner="${WINEDIR}/proton"
elif [[ -x "${WINEDIR%/files}/proton" ]] ; then
proton_runner="${WINEDIR%/files}/proton"
else
return 1
fi
return 0
}
if ! check_proton_runner ; then
gui_proton_downloader "${PW_WINE_USE}"
init_wine_ver
if ! check_proton_runner ; then
fatal "$PW_WINE_USE not found!"
fi
fi
# Winetricks
if [[ -n "${PW_DLL_INSTALL:-}" ]] ; then
update_winetricks
@@ -3902,13 +3905,6 @@ steamplay_launch () {
"${PORT_WINE_TMP_PATH}/winetricks" -q ${PW_DLL_INSTALL}
fi
[[ $PW_LOG != 1 ]] && debug_timer --start -s "PW_TIME_IN_GAME"
if [[ -x "${STEAM_COMPAT_TOOL_PATHS%%:*}/proton" ]] ; then
proton_runner="${STEAM_COMPAT_TOOL_PATHS%%:*}/proton"
elif [[ -x "${WINEDIR}/proton" ]] ; then
proton_runner="${WINEDIR}/proton"
fi
# Virtual Desktop
if [[ "${PW_VIRTUAL_DESKTOP}" == "1" ]] ; then
if [[ "${PW_SCREEN_RESOLUTION:-}" != *x* ]] ; then
@@ -3926,13 +3922,13 @@ steamplay_launch () {
print_info "Steam Play virtual desktop disabled in registry"
fi
print_info "$proton_runner in use."
${PW_RUN_GAMESCOPE} \
env \
LD_LIBRARY_PATH="${steamplay_ld_library_path}" \
LD_PRELOAD="${LD_PRELOAD:+$LD_PRELOAD:}${PW_LD_PRELOAD}" \
${PW_ADD_VAR_SLR} \
${PW_GAMEMODERUN_SLR} \
${PW_INHIBIT_SLR} \
${PW_TASKSET_SLR} \
"${proton_runner}" waitforexitandrun "${PW_EXE_FILE}" "$@"
if [[ $PW_LOG != 1 ]] && [[ -n $START_PW_TIME_IN_GAME ]] ; then
@@ -4019,20 +4015,16 @@ gui_proton_downloader () {
create_new_dir "${PORT_DATA_PATH}/data/dist"
PW_WINE_USE="$1"
if [[ "$PW_WINE_USE" == PROTON_LG ]]
if [[ "${PW_WINE_USE^^}" == PROTON_LG ]]
then PW_WINE_USE="${PW_PROTON_LG_VER}"
elif [[ "$PW_WINE_USE" == WINE_*_LG ]] || [[ "$PW_WINE_USE" == WINE_LG ]]
elif [[ "${PW_WINE_USE^^}" == WINE_*_LG ]] || [[ "${PW_WINE_USE^^}" == WINE_LG ]]
then PW_WINE_USE="${PW_WINE_LG_VER}"
fi
export PW_WINE_USE
if [[ "${PW_WINE_USE}" = /* ]] && [[ -d "${PW_WINE_USE}" ]] ; then
return 0
fi
if [[ -f "${PORT_DATA_PATH}/data/dist/${PW_WINE_USE}/bin/wine" ]] \
|| [[ -f "${PORT_DATA_PATH}/data/dist/${PW_WINE_USE}/files/bin/wine" ]]
then
elif [[ -d "${PORT_DATA_PATH}/data/dist/${PW_WINE_USE^^}" ]] ; then
return 0
fi
@@ -4103,7 +4095,12 @@ gui_edit_db () {
if [[ $PW_WINE_USE =~ (PROTON_LG|WINE_LG) ]] || [[ $PW_VULKAN_USE == "0" ]] ; then
DISABLE_EDIT_DB_LIST+=" PW_USE_SUPPLIED_DXVK_VKD3D"
fi
check_flatpak && DISABLE_EDIT_DB_LIST+=" PW_USE_RUNTIME"
if [[ ! -f "${PW_WINELIB}/runtime/files/bin/vkcube" ]] \
|| [[ ! -f "${PW_WINELIB}/pressure-vessel/bin/pressure-vessel-wrap" ]]
then
DISABLE_EDIT_DB_LIST+=" PW_USE_RUNTIME"
fi
# GALLIUM NINE
[[ ! -f "${PW_TMPFS_PATH}/gallium_nine.tmp" ]] && DISABLE_EDIT_DB_LIST+=" PW_USE_GALLIUM_NINE"
@@ -4436,11 +4433,11 @@ pw_gamescope_process () {
# RESIZE PNG FILE
resize_png () {
if [[ -z "$1" ]] || [[ -z "$2" ]] || [[ -z "$3" ]] ; then
if [[ -z "$1" ]] || [[ -z "$2" ]] ; then
print_error "no argument specified for resize_png"
return 1
else
local RESIZE_FILE RESIZE_NAME_PNG resize_to resize_to_helper
local RESIZE_FILE RESIZE_NAME_PNG
RESIZE_FILE="$1"
RESIZE_NAME_PNG="${2// /_}"
fi
@@ -4449,44 +4446,26 @@ resize_png () {
then RESIZE_NAME_PNG=${RESIZE_NAME_PNG/*ru.linux_gaming.PortProton\/data\/img\//}
fi
for resize_to in "${@:3}" ; do
if [[ $resize_to == 128 ]]
then resize_to_helper=""
else resize_to_helper="_$resize_to"
fi
if [[ $RESIZE_NAME_PNG =~ [\!\%\$\&\<] ]] ; then
local ICON_NAME_REGEX=(\! % \$ \& \<)
for i in "${ICON_NAME_REGEX[@]}" ; do
RESIZE_NAME_PNG="${RESIZE_NAME_PNG//$i/}"
done
fi
if [[ $RESIZE_NAME_PNG =~ [\!\%\$\&\<] ]] ; then
local ICON_NAME_REGEX=(\! % \$ \& \<)
for i in "${ICON_NAME_REGEX[@]}" ; do
RESIZE_NAME_PNG="${RESIZE_NAME_PNG//$i/}"
done
fi
if [[ -f "${PORT_DATA_PATH}/data/img/${RESIZE_NAME_PNG}.png" ]] \
|| [[ ! -f "${RESIZE_FILE}" ]] \
|| [[ ! ${RESIZE_FILE,,} =~ .exe$ ]]
then
return 0
fi
if [[ -f "${PORT_DATA_PATH}/data/img/${RESIZE_NAME_PNG}${resize_to_helper}.png" ]] \
|| [[ ! -f "${RESIZE_FILE}" ]] \
|| [[ ! ${RESIZE_FILE,,} =~ .exe$ ]]
then
return 0
fi
try_remove_file "${PORT_DATA_PATH}/data/img/launcher.png"
try_remove_file "${PORT_DATA_PATH}/data/img/Launcher.png"
try_remove_file "${PORT_DATA_PATH}/data/img/launcher.png"
try_remove_file "${PORT_DATA_PATH}/data/img/Launcher.png"
if check_flatpak ; then
if ! timeout 3 \
exe-thumbnailer --force-resize -s "$resize_to" "$(readlink -f "${RESIZE_FILE}")" "${PORT_DATA_PATH}/data/img/${RESIZE_NAME_PNG}${resize_to_helper}.png" \
&& [[ "$ALPINE_FP" != "1" ]]
then
print_error "exe-thumbnailer - broken!"
fi
else
print_warning "use portable exe-thumbnailer"
env PYTHONPATH="${PW_PLUGINS_PATH}/portable/lib/python3.9/site-packages/" \
LD_LIBRARY_PATH="${PW_PLUGINS_PATH}/portable/lib/lib64" \
"${PW_WINELIB}/runtime/files/bin/python3.9" \
"${PW_PLUGINS_PATH}/portable/bin/exe-thumbnailer" --force-resize -s "$resize_to" "$(readlink -f "${RESIZE_FILE}")" "${PORT_DATA_PATH}/data/img/${RESIZE_NAME_PNG}${resize_to_helper}.png"
fi
done
python3 -m portprotonqt.scripts_utils.shortcut_tools thumbnail \
"$(readlink -f "${RESIZE_FILE}")" \
"${PORT_DATA_PATH}/data/img/${RESIZE_NAME_PNG}.png"
}
portwine_create_shortcut () {
@@ -4520,19 +4499,12 @@ portwine_output_yad_shortcut () {
export name_desktop="$PW_NAME_DESKTOP_PROXY"
fi
echo "[Desktop Entry]" > "${PORT_DATA_PATH}/${name_desktop}.desktop"
echo "Name=${name_desktop}" >> "${PORT_DATA_PATH}/${name_desktop}.desktop"
if check_flatpak
then echo "Exec=flatpak run ${FLATPAK_ID} --silent \"${PW_EXE_FILE}\"" >> "${PORT_DATA_PATH}/${name_desktop}.desktop"
else echo "Exec=portprotonqt --silent \"${PW_EXE_FILE}\"" >> "${PORT_DATA_PATH}/${name_desktop}.desktop"
if ! python3 -m portprotonqt.scripts_utils.shortcut_tools shortcut \
"${PW_EXE_FILE}" \
"${name_desktop}"
then
return 1
fi
{
echo "Type=Application"
echo "Categories=Game"
echo "StartupNotify=true"
echo "Icon=${PORT_DATA_PATH}/data/img/${name_desktop_png}.png"
} >> "${PORT_DATA_PATH}/${name_desktop}.desktop"
chmod +x "${PORT_DATA_PATH}/${name_desktop}.desktop"
if [[ "${PW_SHORTCUT_MENU}" == "TRUE" ]] ; then
try_remove_file "${HOME}/.local/share/applications/${name_desktop}.desktop"
@@ -4602,7 +4574,7 @@ pw_auto_create_shortcut () {
pw_init_db
export PW_NO_RESTART_PPDB="1"
edit_db_from_gui PW_PREFIX_NAME LAUNCH_URI
unset PW_ICON_FOR_YAD name_desktop_png
unset name_desktop_png
portwine_create_shortcut
fi
fi
@@ -4636,9 +4608,9 @@ pw_auto_create_shortcut () {
fi
print_info "Created link for: $link_name"
PORTPROTON_NAME="$link_name"
resize_png "$PW_EXE_FILE" "${PORTPROTON_NAME}" "48" "128"
resize_png "$PW_EXE_FILE" "${PORTPROTON_NAME}"
export PW_NO_RESTART_PPDB=1
unset PW_ICON_FOR_YAD name_desktop_png
unset name_desktop_png
portwine_create_shortcut
done
}
@@ -4692,7 +4664,7 @@ pw_create_prefix_backup_cli () {
chmod -R u+w "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}"
echo "#!/usr/bin/env bash
${TMP_ALL_PATH} mksquashfs \"${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}\" \
${TMP_ALL_PATH} \"${PW_PLUGINS_PATH}/portable/bin/mksquashfs\" \"${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}\" \
\"${PW_PREFIX_TO_BACKUP}/${PW_PREFIX_NAME}.ppack.part\" -comp zstd \
|| rm -f \"${PW_PREFIX_TO_BACKUP}/${PW_PREFIX_NAME}.ppack.part\"
" > "${PORT_WINE_TMP_PATH}/pp_pfx_backup.sh"
@@ -4733,7 +4705,7 @@ pw_unpack_prefix () {
PW_PREFIX_NAME=$(basename "${PW_BACKUP_FILE^^}" .PPACK)
echo "#!/usr/bin/env bash
${TMP_ALL_PATH} unsquashfs $NO_XATTRS_NEED -f -d \
${TMP_ALL_PATH} \"${PW_PLUGINS_PATH}/portable/bin/unsquashfs\" $NO_XATTRS_NEED -f -d \
\"${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}\" \"$PW_BACKUP_FILE\" \
|| echo \"ERROR\" > \"${PORT_WINE_TMP_PATH}/pp_pfx_unpack_error\"
" > "${PORT_WINE_TMP_PATH}/pp_pfx_unpack.sh"
@@ -6,7 +6,6 @@ export PW_VULKAN_USE="0"
export PW_WINE_USE="PROTON_LG"
export PW_PREFIX_NAME="STUDENT"
export PW_DISABLED_CREATE_DB="1"
export PW_ICON_FOR_YAD="${PORT_DATA_PATH}/data/img/setup.png"
export PW_USE_FSYNC="0"
export PW_USE_ESYNC="0"
export PW_DLL_INSTALL=""
@@ -6,7 +6,6 @@ export PW_VULKAN_USE="0"
export PW_WINE_USE="PROTON_LG"
export PW_PREFIX_NAME="TEACHER"
export PW_DISABLED_CREATE_DB="1"
export PW_ICON_FOR_YAD="${PORT_DATA_PATH}/data/img/setup.png"
export PW_USE_FSYNC="0"
export PW_USE_ESYNC="0"
export PW_DLL_INSTALL=""
+21 -16
View File
@@ -37,6 +37,11 @@ if [[ -z "$PORT_DATA_PATH" ]] ; then
fi
fi
if [[ -f "$HOME/.config/PortProtonQt.conf" ]] \
&& grep "disable_runtime_download = True" "$HOME/.config/PortProtonQt.conf" ; then
export PW_DISABLE_RUNTIME_DOWNLOAD=1
fi
export PORT_SCRIPTS_PATH PORT_IMG_PATH PORT_DATA_PATH PORT_CONF_PATH
export PW_LOG_FILE="${PORT_DATA_PATH}/PortProton.log"
@@ -62,6 +67,17 @@ export orig_IFS="$IFS"
unset PW_NO_RESTART_PPDB PW_DISABLED_CREATE_DB
# TODO:
# Setting IME to fcitx5 to fix input
# export GTK_IM_MODULE=fcitx5
# export QT_IM_MODULE=fcitx5
# export QT5_IM_MODULE=fcitx5
# export XMODIFIERS=@im=fcitx5
# Setting for emulator
# export PW_USE_WOW64="1"
# export DBUS_FATAL_WARNINGS="0"
if [[ ${1,,} == "cli" ]] ; then
shift
fi
@@ -172,7 +188,7 @@ unset WINEPREFIX
# choose mirror
if [[ -z "$MIRROR" ]] \
&& [[ "$LANGUAGE" == "ru" ]]
&& [[ "$FULL_LN" == "russian" ]]
then
echo 'export MIRROR="CLOUD"' >> "$USER_CONF"
export MIRROR="CLOUD"
@@ -188,15 +204,9 @@ if [[ $USE_ONLY_LG_RU == "1" ]] ; then
fi
print_info "The first mirror in used: $MIRROR"
# choose downloading covers from SteamGridDB or not
if [[ -z "$DOWNLOAD_STEAM_GRID" ]] ; then
echo 'export DOWNLOAD_STEAM_GRID="1"' >> "$USER_CONF"
export DOWNLOAD_STEAM_GRID="1"
fi
if check_gamescope_session
then PW_TERM="env LANG=C xterm -fullscreen -bg black -fg white -e"
else PW_TERM="env LANG=C xterm -bg black -fg white -e"
then PW_TERM="env LANG=C python3 -m portprotonqt.easyterm --fullscreen -e"
else PW_TERM="env LANG=C python3 -m portprotonqt.easyterm -e"
fi
pw_cleanup () {
@@ -428,12 +438,7 @@ Usage examples:
get_wine_and_pfx "$2" "$3"
start_portproton
cd "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c" || fatal
if check_flatpak ; then
$PW_TERM "pw_run cmd"
else
export PW_USE_TERMINAL=1
pw_run cmd
fi
PW_USE_TERMINAL=1 pw_run cmd
stop_portproton
;;
--winereg)
@@ -469,7 +474,7 @@ Usage examples:
VK_INSTANCE_LAYERS="${PW_VK_INSTANCE_LAYERS}" \
${PW_GAMEMODERUN_SLR} \
${PW_ADD_VAR_SLR} \
${PW_TERM} bash
${PW_TERM}
stop_portproton
;;
--initial)
+76 -71
View File
@@ -1,87 +1,92 @@
#!/usr/bin/env bash
########################################################################
export PROTON_USE_XALIA="0"
export PW_USE_RUNTIME="1"
export PW_RT_MOUNT_RO=("")
export PW_RT_MOUNT_RW=("/media" "/mnt" "/run/media/${USER}" "${PORT_DATA_PATH}")
#export PW_SANDBOX_HOME_PATH="${PORT_DATA_PATH}"
export PW_USE_ESYNC="0"
export PW_USE_FSYNC="0"
export PW_USE_NTSYNC="0"
export PW_USE_GAMEMODE="0"
export PW_USE_INHIBIT_SLEEP="1"
export PW_USE_TERMINAL="0"
export PW_WINDOWS_VER="10"
export WINEARCH="win64"
export PW_LIBS_VER="_v3.0.20260218"
export PW_USE_GSTREAMER="1"
export PW_USE_D3D_EXTRAS="1"
export PW_PREFIX_NAME="DEFAULT"
export WINE_WIN_START="start /wait /high /unix"
export WINE_ALLOW_XIM="0"
export PW_USE_SHADER_CACHE="1"
export PW_FORCE_SYSTEM_DPI="0"
export PW_WINE_DPI_VALUE="96"
export PW_WINE_CPU_TOPOLOGY="disabled"
export PW_MESA_GL_VERSION_OVERRIDE="disabled"
export PW_MESA_VK_WSI_PRESENT_MODE="disabled"
export PW_VKD3D_FEATURE_LEVEL="disabled"
export PW_SOUND_DRIVER_USE="disabled"
export PW_USE_EAC_AND_BE="1"
export PW_USE_US_LAYOUT="0"
export PW_LOCALE_SELECT="disabled"
export PW_DINPUT_PROTOCOL="0"
export PW_USE_VRCLIENT="0"
export STAGING_SHARED_MEMORY="1"
export PW_USE_GALLIUM_NINE="0"
export PW_USE_GALLIUM_ZINK="0"
export PW_USE_WINED3D_VULKAN="0"
export PW_USE_SUPPLIED_DXVK_VKD3D="1"
export WINEUSERNAME="steamuser"
###DEFAULT_WINE###
export PW_WINE_USE="PROTON_LG"
export PW_PLUGINS_VER="_v20"
export PW_OPTISCALER_VER="v03-0.9.0-pre8"
export PW_GALLIUM_NINE_VER="0.10"
export PW_LSFG_VK_VER="2.0.0-dev25-p11"
###WINE_AND_PROTON_LG###
export PW_PROTON_LG_VER="PROTON_LG_10-28"
###BASE VARIABLES###
export PW_PROTON_LG_VER="PROTON_LG_10-30"
export PW_WINE_LG_VER="WINE_LG_11-1"
export PW_WINE_FULLSCREEN_FSR="1"
export WINE_FULLSCREEN_FSR_MODE="0"
###DXVK_AND_VKD3D###
export PW_VULKAN_USE="6"
export PW_VULKAN_UNLOCKED="unlocked"
export VKD3D_LIMIT_TESS_FACTORS="64"
export PW_LIBS_VER="_v3.0.20260218"
export PW_PLUGINS_VER="_v20"
export DXVK_NEW_VER="2.7.1-509"
export DXVK_OLD_VER="2.6.2"
export DXVK_SAREK_VER="sarek-1.11.0"
export VKD3D_NEW_VER="1.1-5122"
export VKD3D_OLD_VER="2.14.1"
export VKD3D_SAREK_VER="sarek-2.6.0"
###VKBASALT###
export PW_VKBASALT="0"
export PW_VKBASALT_EFFECTS="Curves:cas"
export PW_VKBASALT_FFX_CAS="0.50"
export VKBASALT_CONFIG_FILE="${PORT_DATA_PATH}/data/vkBasalt.conf"
###GAMESCOPE###
export PW_GAMESCOPE="0"
export PW_GS_SDL_VIDEODRIVER_X11="0"
export PW_GS_ENABLE_GAMESCOPE_WSI="0"
export PW_GAMESCOPE_ARGS_NEW=" -f --sharpness 10 --hdr-sdr-content-nits 0"
###MANGOHUD###
export PW_MANGOHUD="0"
export DEFAULT_MANGOHUD_CONFIG="arch,cpu_mhz,cpu_temp,engine_version,gamemode,gpu_core_clock,gpu_mem_clock,gpu_name,gpu_temp,ram,resolution,vkbasalt,vram,vulkan_driver,wine,winesync"
###DGVOODOO2###
export PW_DGVOODOO2="0"
export DGV2_VER="2.79.3"
###PREFIX_VERSION###
export PW_LSFG_VK_VER="2.0.0-dev25-p11"
export PW_OPTISCALER_VER="v03-0.9.0-pre8"
export PW_GALLIUM_NINE_VER="0.10"
export DOTPFX_VER="48v9"
export DEFPFX_VER="v1"
export WINEARCH="win64"
export WINEUSERNAME="steamuser"
export WINE_WIN_START="start /wait /high /unix"
export PW_MUST_WINEDLLOVERRIDES="steam_api,steam_api64,steamclient,steamclient64=n;dotnetfx35.exe,dotnetfx35setup.exe=b;winemenubuilder.exe="
#################################################################
export DXVK_CONFIG_FILE="${PORT_DATA_PATH}/data/dxvk.conf"
#################################################################
export PW_RT_MOUNT_RO=("")
export PW_RT_MOUNT_RW=("/media" "/mnt" "/run/media/${USER}" "${PORT_DATA_PATH}")
###OTHER VARIABLES###
check_variables PW_WINE_USE "PROTON_LG"
check_variables PROTON_USE_XALIA "0"
check_variables PW_USE_RUNTIME "1"
check_variables PW_USE_ESYNC "0"
check_variables PW_USE_FSYNC "0"
check_variables PW_USE_NTSYNC "0"
check_variables PW_USE_GAMEMODE "0"
check_variables PW_USE_INHIBIT_SLEEP "1"
check_variables PW_USE_TERMINAL "0"
check_variables PW_WINDOWS_VER "10"
check_variables PW_USE_GSTREAMER "1"
check_variables PW_USE_D3D_EXTRAS "1"
check_variables PW_PREFIX_NAME "DEFAULT"
check_variables WINE_ALLOW_XIM "0"
check_variables PW_USE_SHADER_CACHE "1"
check_variables PW_FORCE_SYSTEM_DPI "0"
check_variables PW_WINE_DPI_VALUE "96"
check_variables PW_WINE_CPU_TOPOLOGY "disabled"
check_variables PW_MESA_GL_VERSION_OVERRIDE "disabled"
check_variables PW_MESA_VK_WSI_PRESENT_MODE "disabled"
check_variables PW_VKD3D_FEATURE_LEVEL "disabled"
check_variables PW_SOUND_DRIVER_USE "disabled"
check_variables PW_USE_EAC_AND_BE "1"
check_variables PW_USE_US_LAYOUT "0"
check_variables PW_LOCALE_SELECT "disabled"
check_variables PW_DINPUT_PROTOCOL "0"
check_variables PW_USE_VRCLIENT "0"
check_variables STAGING_SHARED_MEMORY "1"
check_variables PW_USE_GALLIUM_NINE "0"
check_variables PW_USE_GALLIUM_ZINK "0"
check_variables PW_USE_WINED3D_VULKAN "0"
check_variables PW_USE_SUPPLIED_DXVK_VKD3D "1"
check_variables PW_WINE_FULLSCREEN_FSR "1"
check_variables WINE_FULLSCREEN_FSR_MODE "0"
###DXVK_AND_VKD3D###
check_variables PW_VULKAN_USE "6"
check_variables PW_VULKAN_UNLOCKED "unlocked"
check_variables VKD3D_LIMIT_TESS_FACTORS "64"
###VKBASALT###
check_variables PW_VKBASALT "0"
check_variables PW_VKBASALT_EFFECTS "Curves:cas"
check_variables PW_VKBASALT_FFX_CAS "0.50"
export VKBASALT_CONFIG_FILE="${PORT_DATA_PATH}/data/vkBasalt.conf"
###GAMESCOPE###
check_variables PW_GAMESCOPE "0"
check_variables PW_GS_SDL_VIDEODRIVER_X11 "0"
check_variables PW_GS_ENABLE_GAMESCOPE_WSI "0"
export PW_GAMESCOPE_ARGS_NEW=" -f --sharpness 10 --hdr-sdr-content-nits 0"
###MANGOHUD###
check_variables PW_MANGOHUD "0"
export DEFAULT_MANGOHUD_CONFIG="arch,cpu_mhz,cpu_temp,engine_version,gamemode,gpu_core_clock,gpu_mem_clock,gpu_name,gpu_temp,ram,resolution,vkbasalt,vram,vulkan_driver,wine,winesync"
###DGVOODOO2###
check_variables PW_DGVOODOO2 "0"
check_variables DGV2_VER "2.79.3"
########################################################################
pw_list_install_dll_in_prefix ()
{
case $PW_PREFIX_NAME in
+2 -2
View File
@@ -87,12 +87,12 @@ def bump_meson(path: Path, old: str, new: str) -> bool:
def bump_app_py(path: Path, old: str, new: str) -> bool:
"""
Update __app_version__ in app.py
Update APP_VERSION fallback in app.py
"""
if not path.exists():
return False
text = path.read_text(encoding='utf-8')
pattern = re.compile(r"(?m)^(\s*__app_version__\s*=\s*)\"" + re.escape(old) + r"\"$")
pattern = re.compile(r"(?m)^(\s*APP_VERSION\s*=\s*)\"" + re.escape(old) + r"\"$")
new_text, count = pattern.subn(lambda m: m.group(1) + f'"{new}"', text)
if count:
path.write_text(new_text, encoding='utf-8')
+2 -1
View File
@@ -679,7 +679,8 @@ def get_files_from_meson_build(meson_file_path):
'install_headers', # Header files installation
'install_man', # Manual pages installation
'install_symlink', # Symlinks installation
'install_emptydir' # Empty directories installation
'install_emptydir', # Empty directories installation
'configure_file', # Files generated and potentially installed
]
# Process each install function
+17 -7
View File
@@ -18,8 +18,8 @@ _portprotonqt_completions() {
prev="${COMP_WORDS[COMP_CWORD-1]}"
# All available options
opts="--fullscreen --resolution --debug-level --force-muvm --add-steam-compat-tool --reinstall-steam-compat-tool --remove-steam-compat-tool --ppqtos --silent --help -h"
long_opts="--fullscreen --resolution --debug-level --force-muvm --add-steam-compat-tool --reinstall-steam-compat-tool --remove-steam-compat-tool --ppqtos --silent --help"
opts="--fullscreen --resolution --debug-level --add-steam-compat-tool --reinstall-steam-compat-tool --remove-steam-compat-tool --clear-cache --reset-settings --ppqtos --silent --restore-prefix --create-backup --help -h"
long_opts="--fullscreen --resolution --debug-level --add-steam-compat-tool --reinstall-steam-compat-tool --remove-steam-compat-tool --clear-cache --reset-settings --ppqtos --silent --restore-prefix --create-backup --help"
# Values for options with arguments
local debug_levels="ALL DEBUG INFO WARNING ERROR CRITICAL"
@@ -35,6 +35,10 @@ _portprotonqt_completions() {
COMPREPLY=( $(compgen -W "${resolutions}" -- "${cur}") )
return 0
;;
--restore-prefix)
COMPREPLY=( $(compgen -f -X '!*.ppack' -- "${cur}") )
return 0
;;
esac
# At command start, complete only long options to allow "--" prefix completion
@@ -66,17 +70,20 @@ _portprotonqt() {
'--fullscreen[Launch in fullscreen mode]'
'--resolution[Launch with specific resolution]:WIDTHxHEIGHT:(1920x1080 1280x720 2560x1440 3840x2160)'
'--debug-level[Set logging level]:LEVEL:(ALL DEBUG INFO WARNING ERROR CRITICAL)'
'--force-muvm[Force running under muvm]'
'--add-steam-compat-tool[Add as Steam compatibility tool]'
'--reinstall-steam-compat-tool[Reinstall Steam compatibility tool]'
'--remove-steam-compat-tool[Remove Steam compatibility tool]'
'--clear-cache[Clear PortProtonQt cache and exit]'
'--reset-settings[Reset PortProtonQt settings and exit]'
'--ppqtos[Show the system tab]'
'--silent[Launch .exe file without GUI]'
'--restore-prefix[Restore prefix from .ppack backup]:PPACK file:_files -g "*.ppack"'
'--create-backup[Create prefix backup]:PREFIX: :BACKUP_DIR:_files -/'
'(-h --help)'{-h,--help}'[Show help message]'
)
_arguments -s "${opts[@]}" && return 0
_files -g "*.exe"
_files -g "*.(exe|ppack)"
}
EOF
@@ -86,18 +93,21 @@ cat > "$OUTPUT_DIR/portprotonqt.fish" << 'EOF'
# Fish completion for portprotonqt
complete -c portprotonqt -f
complete -c portprotonqt -n "test -z (commandline -ct)" -a "--fullscreen --resolution --debug-level --force-muvm --add-steam-compat-tool --reinstall-steam-compat-tool --remove-steam-compat-tool --ppqtos --silent --help"
complete -c portprotonqt -n "test -z (commandline -ct)" -a "--fullscreen --resolution --debug-level --add-steam-compat-tool --reinstall-steam-compat-tool --remove-steam-compat-tool --clear-cache --reset-settings --ppqtos --silent --restore-prefix --create-backup --help"
complete -c portprotonqt -l fullscreen -d "Launch in fullscreen mode"
complete -c portprotonqt -l resolution -d "Launch with specific resolution" -r -f -a "1920x1080 1280x720 2560x1440 3840x2160"
complete -c portprotonqt -l debug-level -d "Set logging level" -r -f -a "ALL DEBUG INFO WARNING ERROR CRITICAL"
complete -c portprotonqt -l force-muvm -d "Force running under muvm"
complete -c portprotonqt -l add-steam-compat-tool -d "Add as Steam compatibility tool"
complete -c portprotonqt -l reinstall-steam-compat-tool -d "Reinstall Steam compatibility tool"
complete -c portprotonqt -l remove-steam-compat-tool -d "Remove Steam compatibility tool"
complete -c portprotonqt -l clear-cache -d "Clear PortProtonQt cache and exit"
complete -c portprotonqt -l reset-settings -d "Reset PortProtonQt settings and exit"
complete -c portprotonqt -l ppqtos -d "Show the system tab"
complete -c portprotonqt -l silent -d "Launch .exe file without GUI"
complete -c portprotonqt -l restore-prefix -d "Restore prefix from .ppack backup" -r -a "(__fish_complete_suffix .ppack)"
complete -c portprotonqt -l create-backup -d "Create prefix backup" -r
complete -c portprotonqt -s h -l help -d "Show help message"
complete -c portprotonqt -n "test -n (commandline -ct)" -a "(__fish_complete_suffix .exe)" -d "Executable file or URL"
complete -c portprotonqt -n "test -n (commandline -ct)" -a "(__fish_complete_suffix .exe) (__fish_complete_suffix .ppack)" -d "Executable file or URL"
EOF
echo "Generated completions in $OUTPUT_DIR"
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env bash
# PortProtonQt: Setup development environment script
# This script prepares the environment for development.
set -e
# Ensure we are in the project root directory
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$PROJECT_ROOT"
echo "🚀 Preparing PortProtonQt development environment..."
# 1. Check for uv
if ! command -v uv &> /dev/null; then
echo "❌ Error: 'uv' is not installed. Please install it first: https://docs.astral.sh/uv/"
exit 1
fi
# 2. Check if Python 3.10 is already installed via uv
# We look for cpython-3.10 and ensure it doesn't say "<download available>"
if uv python list | grep "cpython-3.10" | grep -qv "<download available>"; then
echo "✅ Python 3.10 is already available."
else
echo "🐍 Installing Python 3.10..."
uv python install 3.10
fi
# 3. Sync dependencies
echo "📦 Syncing dependencies..."
uv sync --all-extras --dev
# 4. Source the virtual environment for this script
# Since this script is bash, we source the bash-compatible activate script
if [ -f ".venv/bin/activate" ]; then
# shellcheck source=/dev/null
source .venv/bin/activate
else
echo "❌ Error: Virtual environment not found at .venv"
exit 1
fi
# 5. Install pre-commit hooks
echo "⚓ Installing pre-commit hooks..."
pre-commit install --install-hooks
# 6. Generate translations (.mo files)
echo "🌐 Generating localization files..."
python dev-scripts/l10n.py
echo ""
echo "✅ Environment is ready for development!"
# 7. Inform user how to activate the environment based on their actual shell
detect_current_shell() {
local parent_pid
local shell_name
parent_pid="$(ps -o ppid= -p "$$" | tr -d ' ')"
if [ -n "$parent_pid" ]; then
shell_name="$(ps -o comm= -p "$parent_pid" | tr -d ' ')"
fi
if [ -z "$shell_name" ]; then
shell_name="$(basename "${SHELL:-sh}")"
fi
echo "$shell_name"
}
CURRENT_SHELL="$(detect_current_shell)"
case "$CURRENT_SHELL" in
fish)
ACTIVATE_CMD="source .venv/bin/activate.fish"
;;
nu)
ACTIVATE_CMD="overlay use .venv/bin/activate.nu"
;;
tcsh|csh)
ACTIVATE_CMD="source .venv/bin/activate.csh"
;;
*)
ACTIVATE_CMD="source .venv/bin/activate"
;;
esac
echo ""
echo "----------------------------------------------------------------"
echo "Detected shell: $CURRENT_SHELL"
echo "To activate the environment:"
echo " $ACTIVATE_CMD"
echo "----------------------------------------------------------------"
+65 -3
View File
@@ -8,6 +8,7 @@
- [Theme Variants](#-theme-variants)
- [Style File](#-style-file-stylespy)
- [Style Inheritance](#-style-inheritance)
- [Terminal Color Schemes](#-terminal-color-schemes)
- [Animation configuration](#-animation-configuration)
- [Metadata](#-metadata-metainfoini)
- [Screenshots](#-screenshots)
@@ -35,10 +36,17 @@ mkdir -p ~/.local/share/PortProtonQT/themes/my_custom_theme
The theme tab groups light and dark variants under one base theme name.
- Dark variant folder: `my_custom_theme`
- Light variant folder: `my_custom_theme-light`
Define the related theme folders in each variant's `metainfo.ini`:
If both folders exist, the application shows a separate variant selector with `Dark`, `Light`, and `Auto`. If only one folder exists, the variant selector is hidden and the existing theme is used directly.
```ini
[Metainfo]
dark_variant = my_custom_theme
light_variant = my_custom_theme_light
```
The folder names can be any valid theme folder names.
If both configured folders exist, the application shows a separate variant selector with `Dark`, `Light`, and `Auto`. If only one folder exists, the variant selector is hidden and the existing theme is used directly.
`Auto` is the default variant. It follows the system color scheme using the desktop portal first, then `gsettings`, and Qt color scheme detection as a fallback.
@@ -155,6 +163,56 @@ Economy mode also forces the compact detail page layout.
---
## 🖥 Terminal Color Schemes
Terminal color schemes are separate Kitty-style `.conf` files. Built-in schemes are stored in `portprotonqt/terminal_schemes/`. User schemes can be placed in:
```text
~/.local/share/PortProtonQt/terminal_schemes/
```
The filename without `.conf` is used as the scheme name. The terminal menu lists all available `.conf` files from the user directory and the built-in directory.
Example:
```conf
foreground #d4d4d4
background #1e1e1e
cursor #bbbbbb
selection_foreground #ffffff
selection_background #264f78
background_opacity 1.0
cursor_shape block
enable_audio_bell no
color0 #000000
color1 #cd3131
color2 #0dbc79
color3 #e5e510
color4 #2472c8
color5 #bc3fbc
color6 #11a8cd
color7 #e5e5e5
font_size 14
font_family Monospace
```
Supported terminal-specific options:
- `foreground`, `background`: default text and background colors.
- `selection_foreground`, `selection_background`: selected text colors.
- `cursor` or `cursor_color`: cursor color.
- `cursor_shape`: `block`, `beam`, or `underline`.
- `enable_audio_bell`: `yes`/`no`, `true`/`false`, `on`/`off`, or `1`/`0`.
- `background_opacity`: background opacity from `0.0` to `1.0`.
- `font_size`, `font_family`: terminal font settings.
- `color0` through `color255`: ANSI palette entries.
If `cursor_shape` is omitted, the terminal uses `beam`. If `enable_audio_bell` is omitted, audio bell is disabled.
---
## 🎥 Animation configuration
The `GAME_CARD_ANIMATION` dictionary controls all animation parameters for game cards:
@@ -348,6 +406,8 @@ virtual_keyboard_slide_bounce_animation_duration = 220
```ini
[Metainfo]
dark_variant = my_custom_theme
light_variant = my_custom_theme_light
name_en = My Custom Theme
name_ru = Моя пользовательская тема
author = Your Name
@@ -364,6 +424,8 @@ You must provide translations for your theme's name and description by adding la
The application will automatically select the appropriate translation based on the user's system language, falling back to English if translations are not available for the user's language.
`dark_variant` and `light_variant` are required when the theme has both variants. Add them to both variant folders so either selected folder can resolve back to the same variant pair.
---
## 🖼 Screenshots
+65 -3
View File
@@ -8,6 +8,7 @@
- [Варианты темы](#-варианты-темы)
- [Файл стилей](#-файл-стилей-stylespy)
- [Наследование стилей](#-наследование-стилей)
- [Цветовые схемы терминала](#-цветовые-схемы-терминала)
- [Конфигурация анимации](#-конфигурация-анимации)
- [Метаинформация](#-метаинформация-metainfoini)
- [Скриншоты](#-скриншоты)
@@ -35,10 +36,17 @@ mkdir -p ~/.local/share/PortProtonQT/themes/my_custom_theme
Вкладка тем группирует светлый и тёмный варианты под одним базовым названием темы.
- Папка тёмного варианта: `my_custom_theme`
- Папка светлого варианта: `my_custom_theme-light`
Укажите связанные папки темы в `metainfo.ini` каждого варианта:
Если существуют обе папки, приложение показывает отдельный выбор варианта: `Dark`, `Light` и `Auto`. Если существует только одна папка, выбор варианта скрывается, а доступная тема используется напрямую.
```ini
[Metainfo]
dark_variant = my_custom_theme
light_variant = my_custom_theme_light
```
Имена папок могут быть любыми допустимыми именами тем.
Если существуют обе указанные папки, приложение показывает отдельный выбор варианта: `Dark`, `Light` и `Auto`. Если существует только одна папка, выбор варианта скрывается, а доступная тема используется напрямую.
`Auto` используется как вариант по умолчанию. Он следует системной цветовой схеме: сначала через desktop portal, затем через `gsettings`, с откатом к определению цветовой схемы Qt.
@@ -155,6 +163,56 @@ DETAIL_PAGE_LAYOUT_MODE = "full"
---
## 🖥 Цветовые схемы терминала
Цветовые схемы терминала задаются отдельными `.conf` файлами в Kitty-style формате. Встроенные схемы находятся в `portprotonqt/terminal_schemes/`. Пользовательские схемы можно положить в:
```text
~/.local/share/PortProtonQt/terminal_schemes/
```
Имя файла без `.conf` используется как имя схемы. Меню терминала показывает все доступные `.conf` файлы из пользовательской и встроенной директорий.
Пример:
```conf
foreground #d4d4d4
background #1e1e1e
cursor #bbbbbb
selection_foreground #ffffff
selection_background #264f78
background_opacity 1.0
cursor_shape block
enable_audio_bell no
color0 #000000
color1 #cd3131
color2 #0dbc79
color3 #e5e510
color4 #2472c8
color5 #bc3fbc
color6 #11a8cd
color7 #e5e5e5
font_size 14
font_family Monospace
```
Поддерживаемые параметры терминала:
- `foreground`, `background`: основные цвета текста и фона.
- `selection_foreground`, `selection_background`: цвета выделенного текста.
- `cursor` или `cursor_color`: цвет курсора.
- `cursor_shape`: `block`, `beam` или `underline`.
- `enable_audio_bell`: `yes`/`no`, `true`/`false`, `on`/`off` или `1`/`0`.
- `background_opacity`: прозрачность фона от `0.0` до `1.0`.
- `font_size`, `font_family`: настройки шрифта терминала.
- `color0` до `color255`: элементы ANSI-палитры.
Если `cursor_shape` не указан, терминал использует `beam`. Если `enable_audio_bell` не указан, звуковой сигнал выключен.
---
## 🎥 Конфигурация анимации
Словарь `GAME_CARD_ANIMATION` управляет всеми параметрами анимации для карточек игр:
@@ -348,6 +406,8 @@ virtual_keyboard_slide_bounce_animation_duration = 220
```ini
[Metainfo]
dark_variant = my_custom_theme
light_variant = my_custom_theme_light
name_en = My Custom Theme
name_ru = Моя пользовательская тема
author = Ваше имя
@@ -364,6 +424,8 @@ description_ru = Описание вашей темы.
Приложение автоматически выберет соответствующий перевод на основе языка системы пользователя, с откатом к английскому языку, если переводы недоступны для языка пользователя.
`dark_variant` и `light_variant` обязательны, если у темы есть оба варианта. Добавьте их в папки обоих вариантов, чтобы любая выбранная папка могла связаться с той же парой вариантов.
---
## 🖼 Скриншоты
+32 -1
View File
@@ -1,5 +1,5 @@
project('portprotonqt', 'c',
version: '0.1.12',
version: '1.0',
meson_version: '>= 0.61.2',
license: 'GPL-3.0',
)
@@ -12,6 +12,20 @@ python3 = import('python').find_installation('python3')
conf = configuration_data()
conf.set('PYTHON', python3.full_path())
version_conf = configuration_data()
version_conf.set_quoted('APP_VERSION', meson.project_version())
version_conf.set_quoted('APP_COMMIT', '')
if get_option('nightly')
git = find_program('git', required: false)
if git.found()
git_commit = run_command(git, 'rev-parse', '--short', 'HEAD', check: false)
if git_commit.returncode() == 0
version_conf.set_quoted('APP_COMMIT', git_commit.stdout().strip())
endif
endif
endif
# Directories
prefix = get_option('prefix')
datadir = prefix / get_option('datadir')
@@ -25,6 +39,17 @@ pkgdatadir = pythondir / meson.project_name()
# C compiler for vk_gpu_info
cc = meson.get_compiler('c')
configured_version = configure_file(
input: 'portprotonqt/_version.py.in',
output: '_version.py',
configuration: version_conf,
)
install_data(
configured_version,
install_dir: pythondir / meson.project_name(),
)
# Install Python package
subdir('portprotonqt')
@@ -59,6 +84,12 @@ install_data(
install_dir: datadir / 'applications',
)
# Install MIME type
install_data(
'build-aux/share/mime/packages/ru.linux_gaming.PortProtonQt.xml',
install_dir: datadir / 'mime/packages',
)
# Install icon
install_data(
'build-aux/share/icons/hicolor/scalable/apps/ru.linux_gaming.PortProtonQt.svg',
+1
View File
@@ -2,3 +2,4 @@
option('python_purelibdir', type: 'string', value: '', description: 'Python pure library installation directory (overrides purelib)')
option('udev_rulesdir', type: 'string', value: '', description: 'Udev rules installation directory (overrides default)')
option('nightly', type: 'boolean', value: false, description: 'Include git commit in application version')
+2
View File
@@ -0,0 +1,2 @@
APP_VERSION = @APP_VERSION@
APP_COMMIT = @APP_COMMIT@
+87 -34
View File
@@ -1,12 +1,22 @@
import argparse
import sys
import os
import importlib
import subprocess
import shutil
from logging import Logger
__app_id__ = "ru.linux_gaming.PortProtonQt"
__app_name__ = "PortProtonQt"
__app_version__ = "0.1.12"
try:
version_module = importlib.import_module("portprotonqt._version")
APP_COMMIT = version_module.APP_COMMIT
APP_VERSION = version_module.APP_VERSION
except ImportError:
APP_COMMIT = ""
APP_VERSION = "1.0"
__app_version__ = APP_VERSION
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication, QMenu, QSystemTrayIcon
@@ -26,16 +36,22 @@ from portprotonqt.cli import (
is_portproton_url,
parse_portproton_url,
is_launch_file,
is_prefix_backup_file,
is_exe_file,
normalize_launch_path,
add_steam_compat_tool,
reinstall_steam_compat_tool,
remove_steam_compat_tool,
clear_cache,
reset_settings,
parse_resolution,
)
from portprotonqt.localization import _, get_steam_language
def get_version():
if APP_COMMIT:
return f"{__app_version__} ({APP_COMMIT})"
try:
commit = subprocess.check_output(
["git", "rev-parse", "--short", "HEAD"],
@@ -46,24 +62,6 @@ def get_version():
return __app_version__
def is_apple_silicon():
path = "/proc/device-tree/compatible"
if not os.path.exists(path):
return False
try:
with open(path, "rb") as f:
dtcompat = f.read().decode('utf-8', errors='ignore')
if "apple,arm-platform" in dtcompat:
return True
else:
return False
except OSError:
return False
def stop_portproton_game(start_sh: list[str], logger: Logger) -> None:
try:
subprocess.run(
@@ -124,8 +122,46 @@ def run_silent_tray(app: QApplication, start_sh: list[str], exe_path: str) -> No
monitor_timer.start(1000)
def restore_prefix_backup(start_sh: list[str], backup_path: str) -> int:
"""Restore a PortProton prefix backup."""
logger = get_logger(__name__)
path = normalize_launch_path(backup_path)
cmd = start_sh + ["--restore-prefix", path]
try:
process = subprocess.Popen(
cmd,
env=os.environ.copy(),
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True,
)
return process.wait()
except (OSError, subprocess.SubprocessError) as e:
logger.error("Failed to restore prefix backup %s: %s", path, e)
return 1
def create_prefix_backup(start_sh: list[str], prefix_name: str, backup_dir: str) -> int:
"""Create a PortProton prefix backup."""
logger = get_logger(__name__)
path = os.path.abspath(os.path.expanduser(backup_dir))
cmd = start_sh + ["--backup-prefix", prefix_name, path]
try:
process = subprocess.run(cmd, env=os.environ.copy(), check=False)
except (OSError, subprocess.SubprocessError) as e:
logger.error("Failed to create prefix backup %s: %s", prefix_name, e)
return 1
return process.returncode
def is_restore_prefix_request(args: argparse.Namespace) -> bool:
if args.restore_prefix:
return bool(args.file_or_url)
return bool(args.file_or_url and is_prefix_backup_file(args.file_or_url))
def main():
# Parse args early to check for force-muvm flag
parsed_args = parse_args()
# Handle --reinstall-steam-compat-tool flag
@@ -143,19 +179,19 @@ def main():
success = remove_steam_compat_tool()
sys.exit(0 if success else 1)
# Check if running on Apple Silicon/Asahi Linux or if forced to run under muvm, and re-execute under muvm if needed
should_run_under_muvm = (is_apple_silicon() or parsed_args.force_muvm) and 'PORTPROTONQT_MUVM' not in os.environ
if should_run_under_muvm:
muvm_path = shutil.which('muvm')
if muvm_path:
env = os.environ.copy()
args_list = [muvm_path, "-i", "-e", "PORTPROTONQT_MUVM=1", sys.executable, os.path.abspath(__file__)]
os.execvpe(muvm_path, args_list + sys.argv[1:], env)
if parsed_args.clear_cache:
success = clear_cache()
sys.exit(0 if success else 1)
if parsed_args.reset_settings:
success = reset_settings()
sys.exit(0 if success else 1)
os.environ["FULL_LN"] = get_steam_language()
portproton_location = get_portproton_location()
if portproton_location:
os.environ["PORT_DATA_PATH"] = portproton_location
ui_config.get_disable_runtime_download()
# Check if running as Steam compatibility tool (STEAM_COMPAT=1).
is_steam_compat = os.environ.get("STEAM_COMPAT") == "1"
@@ -167,6 +203,20 @@ def main():
if start_sh is None:
return
if parsed_args.create_backup:
setup_logger(parsed_args.debug_level)
prefix_name, backup_dir = parsed_args.create_backup
backup_exit_code = create_prefix_backup(start_sh, prefix_name, backup_dir)
sys.exit(backup_exit_code)
if parsed_args.restore_prefix and not parsed_args.file_or_url:
setup_logger(parsed_args.debug_level)
sys.exit(1)
if is_restore_prefix_request(parsed_args):
setup_logger(parsed_args.debug_level)
restore_exit_code = restore_prefix_backup(start_sh, parsed_args.file_or_url)
sys.exit(restore_exit_code)
# Handle Steam compatibility mode - launch game directly without GUI.
if is_steam_compat:
exe_path = parsed_args.file_or_url if parsed_args.file_or_url else None
@@ -233,10 +283,9 @@ def main():
)
from portprotonqt.downloader import Downloader
from portprotonqt.debug_utils import (
get_screen_info,
get_selectable_gpu_entries,
get_system_dpi_for_wine,
)
from portprotonqt.qt_utils import get_screen_info, get_system_dpi_for_wine
# --- Single-instance logic ---
server_name = __app_id__
@@ -411,13 +460,13 @@ def main():
portproton_path = get_portproton_location()
if portproton_path:
screen_resolution, screen_primary = get_screen_info(portproton_path)
screen_resolution, screen_primary = get_screen_info()
if screen_resolution and '=' in screen_resolution:
var_name, var_value = screen_resolution.split('=', 1)
if var_value:
set_user_conf_setting(var_name, var_value)
wine_dpi_value = get_system_dpi_for_wine(var_value)
wine_dpi_value = get_system_dpi_for_wine()
if screen_primary and '=' in screen_primary:
var_name, var_value = screen_primary.split('=', 1)
@@ -428,7 +477,7 @@ def main():
current_gpu_use = get_user_conf_setting("PW_GPU_USE")
selectable_gpu_entries = get_selectable_gpu_entries()
if selectable_gpu_entries:
if len(selectable_gpu_entries) > 1:
selected_entry = None
for entry in selectable_gpu_entries:
if entry["device_name"] == current_gpu_use:
@@ -444,6 +493,10 @@ def main():
set_user_conf_setting("PW_vendorID", selected_entry["vendor_id"])
if selected_entry["device_id"]:
set_user_conf_setting("PW_deviceID", selected_entry["device_id"])
elif current_gpu_use and current_gpu_use != "disabled":
set_user_conf_setting("PW_GPU_USE", None)
set_user_conf_setting("PW_vendorID", None)
set_user_conf_setting("PW_deviceID", None)
# Run the initial PortProton command
subprocess.run(self.start_cmd + ["cli", "--initial"], timeout=10)
+46 -5
View File
@@ -7,6 +7,7 @@ from pathlib import Path
from portprotonqt.steam_api import get_steam_home
LAUNCH_FILE_EXTENSIONS = ('.exe', '.iso', '.mdf')
PREFIX_BACKUP_EXTENSION = '.ppack'
def parse_args():
@@ -31,11 +32,6 @@ def parse_args():
default='NOTSET',
help="Set logging level (ALL for all messages, default: NOTSET)"
)
parser.add_argument(
"--force-muvm",
action="store_true",
help="Force running the application under muvm even if not on Apple Silicon"
)
parser.add_argument(
"--add-steam-compat-tool",
action="store_true",
@@ -51,6 +47,16 @@ def parse_args():
action="store_true",
help="Remove PortProtonQt Steam compatibility tool from user Steam directory"
)
parser.add_argument(
"--clear-cache",
action="store_true",
help="Clear PortProtonQt cache and exit"
)
parser.add_argument(
"--reset-settings",
action="store_true",
help="Reset PortProtonQt settings and exit"
)
parser.add_argument(
"--ppqtos",
action="store_true",
@@ -61,6 +67,17 @@ def parse_args():
action="store_true",
help="Launch .exe file in tray without showing the main window"
)
parser.add_argument(
"--restore-prefix",
action="store_true",
help="Restore prefix from .ppack backup"
)
parser.add_argument(
"--create-backup",
nargs=2,
metavar=("PREFIX", "BACKUP_DIR"),
help="Create prefix backup"
)
# Add positional argument to accept launch files or portproton:// URLs
parser.add_argument(
'file_or_url',
@@ -262,6 +279,24 @@ def remove_steam_compat_tool() -> bool:
return True
def clear_cache() -> bool:
"""Clear PortProtonQt cache."""
from portprotonqt.config import cache_config
cache_config.clear_cache()
print("PortProtonQt cache cleared")
return True
def reset_settings() -> bool:
"""Reset PortProtonQt settings."""
from portprotonqt.config import reset_main_config
reset_main_config()
print("PortProtonQt settings reset")
return True
def is_steam_compat_tool_installed() -> bool:
"""Check if PortProtonQt is installed as Steam compatibility tool."""
steam_home = get_steam_home()
@@ -313,6 +348,12 @@ def is_launch_file(path: str) -> bool:
return normalized_path.lower().endswith(LAUNCH_FILE_EXTENSIONS) and os.path.isfile(normalized_path)
def is_prefix_backup_file(path: str) -> bool:
"""Check if the given path is a PortProton prefix backup."""
normalized_path = normalize_launch_path(path)
return normalized_path.lower().endswith(PREFIX_BACKUP_EXTENSION) and os.path.isfile(normalized_path)
def parse_portproton_url(url: str) -> str | None:
"""Parse a portproton:// URL to extract the full download URL.
+9 -2
View File
@@ -59,8 +59,12 @@ class BaseConfig:
config_path = str(self._config_file)
if not self._config_file.exists():
logger.debug("Configuration file %s not found", config_path)
return None
try:
self._config_file.parent.mkdir(parents=True, exist_ok=True)
self._config_file.touch()
except OSError as error:
logger.warning("Failed to create configuration file %s: %s", config_path, error)
return None
try:
current_mtime = self._config_file.stat().st_mtime
@@ -87,6 +91,7 @@ class BaseConfig:
def _save_config(self, cp: configparser.ConfigParser):
"""Save configuration to file."""
self._config_file.parent.mkdir(parents=True, exist_ok=True)
with open(self._config_file, "w", encoding="utf-8") as f:
cp.write(f)
self._invalidate_cache()
@@ -104,6 +109,8 @@ class BaseConfig:
cp = self._read_config()
if cp is None or not cp.has_section(self._section):
return self._save_value(option, default, value_type)
if not cp.has_option(self._section, option):
return self._save_value(option, default, value_type)
try:
if value_type == "int":
+25 -9
View File
@@ -11,6 +11,7 @@ from portprotonqt.config.base import BaseConfig, CACHE_DIR
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
_CACHE_FILE_LOCK = threading.RLock()
class CacheConfig(BaseConfig):
@@ -88,10 +89,17 @@ class CacheManager:
"""
cache_file = self._get_cache_file_path(name)
try:
if cache_file.exists():
with open(cache_file, "rb") as f:
return orjson.loads(f.read())
except (OSError, orjson.JSONDecodeError) as e:
with _CACHE_FILE_LOCK:
if cache_file.exists():
with open(cache_file, "rb") as f:
return orjson.loads(f.read())
except orjson.JSONDecodeError as e:
logger.warning("Failed to load cache %s: %s", cache_file, e)
try:
cache_file.unlink()
except OSError as unlink_error:
logger.debug("Failed to remove invalid cache %s: %s", cache_file, unlink_error)
except OSError as e:
logger.warning("Failed to load cache %s: %s", cache_file, e)
return None
@@ -107,15 +115,23 @@ class CacheManager:
True if saved successfully, False otherwise.
"""
cache_file = self._get_cache_file_path(name)
temp_file = cache_file.with_name(f".{cache_file.name}.{time.time_ns()}.tmp")
try:
with open(cache_file, "wb") as f:
if pretty:
f.write(json.dumps(data, indent=2).encode("utf-8"))
else:
f.write(orjson.dumps(data))
if pretty:
content = json.dumps(data, indent=2).encode("utf-8")
else:
content = orjson.dumps(data)
with _CACHE_FILE_LOCK:
with open(temp_file, "wb") as f:
f.write(content)
temp_file.replace(cache_file)
return True
except (OSError, TypeError) as e:
logger.warning("Failed to save cache %s: %s", cache_file, e)
try:
temp_file.unlink()
except OSError:
pass
return False
def load_text(self, name: str) -> str | None:
+11 -1
View File
@@ -2,7 +2,7 @@
import os
from pathlib import Path
from portprotonqt.config.base import BaseConfig
from portprotonqt.config.validators import validate_bool
from portprotonqt.config.validators import validate_bool, validate_string
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
@@ -64,6 +64,16 @@ class DisplayConfig(BaseConfig):
validate_bool(minimized, "start_minimized")
self._save_value("start_minimized", minimized, "bool")
def get_tray_menu_mode(self) -> str:
"""Get tray menu mode."""
mode = self._get_str("tray_menu_mode", "compact")
return mode if mode in ("detailed", "compact") else "compact"
def set_tray_menu_mode(self, mode: str) -> None:
"""Set tray menu mode."""
validate_string(mode, "tray_menu_mode", min_len=1, max_len=20)
self._save_value("tray_menu_mode", mode, "str")
def apply_xdg_autostart(enabled: bool) -> bool:
"""Create or remove xdg-autostart desktop entry."""
+13 -4
View File
@@ -19,6 +19,14 @@ logger = get_logger(__name__)
_portproton_start_command: list[str] | None = None
def _sanitize_icon_name(name: str) -> str:
"""Convert a game name to a safe icon file name."""
sanitized_name = name.replace(" ", "_")
for char in ("!", "%", "$", "&", "<"):
sanitized_name = sanitized_name.replace(char, "")
return sanitized_name
class PortProtonConfig(BaseConfig):
"""PortProton location configuration."""
@@ -356,8 +364,8 @@ def find_game_by_exe(exe_path: str) -> configparser.SectionProxy | None:
def create_desktop_file(
exe_path: str,
game_name: str | None = None,
) -> tuple[str, str] | None:
"""Create desktop entry content and destination path for a game."""
) -> tuple[str, str, str] | None:
"""Create desktop entry content, destination path and icon path for a game."""
portproton_path = get_portproton_location()
if not os.path.isfile(exe_path):
logger.error("Executable not found: %s", exe_path)
@@ -369,7 +377,8 @@ def create_desktop_file(
if not game_name:
game_name = os.path.splitext(os.path.basename(exe_path))[0]
base_path = os.path.join(portproton_path, "data")
icon_path = os.path.join(base_path, "img", f"{game_name}.png")
icon_name = _sanitize_icon_name(game_name)
icon_path = os.path.join(base_path, "img", f"{icon_name}.png")
desktop_path = os.path.join(portproton_path, f"{game_name}.desktop")
os.makedirs(os.path.dirname(icon_path), exist_ok=True)
@@ -391,4 +400,4 @@ def create_desktop_file(
"StartupNotify=true\n"
f"Icon={icon_path}\n"
)
return desktop_entry, desktop_path
return desktop_entry, desktop_path, icon_path
+104 -15
View File
@@ -3,6 +3,10 @@ import asyncio
import os
import subprocess
from typing import Any, cast
from dbus_fast import BusType
from dbus_fast.aio import MessageBus
from portprotonqt.config.base import BaseConfig, configparser, THEMES_DIRS
from portprotonqt.config.validators import validate_string, validate_int, validate_bool
from portprotonqt.localization import get_theme_translations
@@ -11,16 +15,39 @@ from portprotonqt.logger import get_logger
logger = get_logger(__name__)
THEME_VARIANTS = ("dark", "light", "auto")
DOWNLOADS_SECTION = "Downloads"
def _read_theme_variants(theme_name: str) -> dict[str, str]:
variants = {}
for themes_dir in THEMES_DIRS:
metainfo_file = os.path.join(themes_dir, theme_name, "metainfo.ini")
if not os.path.exists(metainfo_file):
continue
cp = configparser.ConfigParser()
cp.read(metainfo_file, encoding="utf-8")
if "Metainfo" not in cp:
return variants
dark_name = cp.get("Metainfo", "dark_variant", fallback="")
light_name = cp.get("Metainfo", "light_variant", fallback="")
if dark_name and _theme_exists(dark_name):
variants["dark"] = dark_name
if light_name and _theme_exists(light_name):
variants["light"] = light_name
return variants
return variants
def _get_theme_base_name(theme_name: str) -> str:
if theme_name.endswith("-light"):
return theme_name[:-6]
variants = _read_theme_variants(theme_name)
if variants.get("dark"):
return variants["dark"]
return theme_name
def _get_theme_variant_name(theme_name: str) -> str:
if theme_name.endswith("-light"):
variants = _read_theme_variants(theme_name)
if variants.get("light") == theme_name:
return "light"
return "auto"
@@ -33,6 +60,15 @@ def _theme_exists(theme_name: str) -> bool:
return False
def _get_theme_base_names(theme_names: list[str]) -> list[str]:
base_names = []
for theme_name in theme_names:
base_name = _get_theme_base_name(theme_name)
if base_name not in base_names:
base_names.append(base_name)
return base_names
def _unwrap_variant(value: Any) -> Any:
if isinstance(value, tuple) and len(value) == 1:
value = value[0]
@@ -42,12 +78,6 @@ def _unwrap_variant(value: Any) -> Any:
async def _read_portal_color_scheme() -> int | None:
try:
from dbus_fast import BusType
from dbus_fast.aio import MessageBus
except ModuleNotFoundError:
return None
bus = await MessageBus(bus_type=BusType.SESSION).connect()
try:
introspection = await bus.introspect(
@@ -137,12 +167,13 @@ def _is_system_light_theme() -> bool:
def _resolve_theme_name(theme_name: str, variant: str) -> str:
base_name = _get_theme_base_name(theme_name)
resolved_variant = "light" if variant == "auto" and _is_system_light_theme() else variant
resolved_name = f"{base_name}-light" if resolved_variant == "light" else base_name
variants = _read_theme_variants(base_name)
resolved_name = variants.get(resolved_variant, base_name)
if _theme_exists(resolved_name):
return resolved_name
if _theme_exists(base_name):
return base_name
light_name = f"{base_name}-light"
light_name = variants.get("light", "")
if _theme_exists(light_name):
return light_name
return base_name
@@ -167,6 +198,10 @@ class UIConfig(BaseConfig):
"""Get the selected base theme name."""
return _get_theme_base_name(self._get_str("theme", "standart"))
def get_theme_bases(self, theme_names: list[str]) -> list[str]:
"""Get unique base theme names."""
return _get_theme_base_names(theme_names)
def get_theme_variant(self) -> str:
"""Get theme variant."""
theme_name = self._get_str("theme", "standart")
@@ -184,6 +219,15 @@ class UIConfig(BaseConfig):
"""Resolve base theme and variant to an installed theme name."""
return _resolve_theme_name(theme_name, variant)
def get_terminal_scheme(self) -> str:
"""Get the current terminal scheme name."""
return self._get_str("terminal_scheme", "default")
def set_terminal_scheme(self, scheme_name: str):
"""Set the terminal scheme name."""
validate_string(scheme_name, "terminal_scheme", min_len=1, max_len=50)
self._save_value("terminal_scheme", scheme_name, "str")
def get_time_detail_level(self) -> str:
"""Get time detail level ('detailed' or 'simple')."""
cp = self._read_config()
@@ -244,21 +288,64 @@ class UIConfig(BaseConfig):
def get_economy_mode(self) -> bool:
"""Get economy mode setting."""
return self._get_bool("economy_mode", False)
return self._get_download_bool("economy_mode", False)
def set_economy_mode(self, enabled: bool):
"""Set economy mode setting."""
validate_bool(enabled, "economy_mode")
self._save_value("economy_mode", enabled, "bool")
self._save_download_value("economy_mode", enabled)
def _get_download_bool(self, option: str, default: bool) -> bool:
cp = self._read_config()
if cp is None:
return self._save_download_value(option, default)
try:
if cp.has_option(DOWNLOADS_SECTION, option):
return cp.getboolean(DOWNLOADS_SECTION, option, fallback=default)
if cp.has_option(self._section, option):
return cp.getboolean(self._section, option, fallback=default)
except ValueError as e:
logger.warning("Error reading %s: %s", option, e)
return self._save_download_value(option, default)
except configparser.Error as e:
logger.warning("Error reading %s: %s", option, e)
return self._save_download_value(option, default)
return self._save_download_value(option, default)
def _save_download_value(self, option: str, value: bool) -> bool:
validate_bool(value, option)
cp = self._read_config() or configparser.ConfigParser()
if DOWNLOADS_SECTION not in cp:
cp[DOWNLOADS_SECTION] = {}
cp[DOWNLOADS_SECTION][option] = str(value)
if cp.has_section(self._section):
cp.remove_option(self._section, option)
self._save_config(cp)
return value
def get_download_wine_to_steam(self) -> bool:
"""Get Steam compatibility tools download setting."""
return self._get_bool("download_wine_to_steam", False)
return self._get_download_bool("download_wine_to_steam", False)
def set_download_wine_to_steam(self, enabled: bool) -> None:
"""Set Steam compatibility tools download setting."""
validate_bool(enabled, "download_wine_to_steam")
self._save_value("download_wine_to_steam", enabled, "bool")
self._save_download_value("download_wine_to_steam", enabled)
def get_disable_runtime_download(self) -> bool:
"""Get PortProton runtime download setting."""
default = bool(os.getenv("FLATPAK_ID"))
return self._get_download_bool("disable_runtime_download", default)
def set_disable_runtime_download(self, enabled: bool) -> None:
"""Set PortProton runtime download setting."""
if os.getenv("FLATPAK_ID"):
enabled = True
validate_bool(enabled, "disable_runtime_download")
self._save_download_value("disable_runtime_download", enabled)
def load_theme_metainfo(theme_name: str) -> dict:
@@ -274,6 +361,8 @@ def load_theme_metainfo(theme_name: str) -> dict:
if "Metainfo" in cp:
meta["author"] = cp.get("Metainfo", "author", fallback="Unknown")
meta["author_link"] = cp.get("Metainfo", "author_link", fallback="")
meta["dark_variant"] = cp.get("Metainfo", "dark_variant", fallback="")
meta["light_variant"] = cp.get("Metainfo", "light_variant", fallback="")
meta["name"] = theme_translations.get("name", theme_name)
meta["description"] = theme_translations.get("description", "")
break
+44 -3
View File
@@ -3,7 +3,7 @@ import glob
import shutil
import tempfile
from PySide6.QtWidgets import QMessageBox, QDialog, QMenu, QLineEdit, QApplication, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QFrame
from PySide6.QtCore import QUrl, QPoint, QObject, Signal, Qt, QStandardPaths
from PySide6.QtCore import QUrl, QPoint, QObject, Signal, Qt, QStandardPaths, QTimer
from PySide6.QtGui import QDesktopServices, QIcon, QKeySequence
from portprotonqt.localization import _
from portprotonqt.config import (
@@ -15,10 +15,14 @@ from portprotonqt.config import (
from portprotonqt.steam_api import (
add_to_steam,
fetch_client_icon_async,
get_steam_home,
get_steam_libs,
is_game_in_steam,
remove_from_steam,
safe_vdf_load,
)
from portprotonqt.dialogs import AddGameDialog, generate_thumbnail
from portprotonqt.icon_extractor import generate_thumbnail
from portprotonqt.dialogs import AddGameDialog
from portprotonqt.dialogs.base import DraggableDialog
from portprotonqt.theme_manager import ThemeManager
from portprotonqt.logger import get_logger
@@ -330,6 +334,8 @@ class ContextMenuManager:
)
msg_box.setIcon(QMessageBox.Icon.Warning)
msg_box.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
msg_box.setButtonText(QMessageBox.StandardButton.Yes, _("Yes"))
msg_box.setButtonText(QMessageBox.StandardButton.No, _("No"))
if msg_box.exec() != QMessageBox.StandardButton.Yes:
return
try:
@@ -423,6 +429,13 @@ class ContextMenuManager:
if os.path.exists(menu_path)
else self.add_steam_to_menu(game_card.name, game_card.appid)
)
open_folder_action = menu.addAction(self._get_safe_icon("search"), _("Open Game Folder"))
open_folder_action.triggered.connect(
lambda: QTimer.singleShot(
0,
lambda: self.open_steam_game_folder(game_card.appid)
)
)
if game_card.game_source != "steam":
desktop_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DesktopLocation)
@@ -443,7 +456,10 @@ class ContextMenuManager:
delete_action.triggered.connect(lambda: self.delete_game(game_card.name, game_card.exec_line))
open_folder_action = menu.addAction(self._get_safe_icon("search"), _("Open Game Folder"))
open_folder_action.triggered.connect(
lambda: self.open_game_folder(game_card.name, game_card.exec_line)
lambda: QTimer.singleShot(
0,
lambda: self.open_game_folder(game_card.name, game_card.exec_line)
)
)
applications_dir = os.path.join(os.path.expanduser("~"), ".local", "share", "applications")
menu_path = self._get_shortcut_path(game_card.name, applications_dir)
@@ -1236,6 +1252,31 @@ class ContextMenuManager:
_("Failed to open folder: {error}").format(error=str(e))
)
def open_steam_game_folder(self, appid: int | str) -> None:
"""Open Steam game installation folder by appid."""
appid_str = str(appid).strip()
if not appid_str:
return
steam_home = get_steam_home()
if steam_home is None:
return
for lib in get_steam_libs(steam_home):
manifest = lib / "steamapps" / f"appmanifest_{appid_str}.acf"
if not manifest.exists():
continue
data = safe_vdf_load(manifest)
install_dir = data.get("AppState", {}).get("installdir")
if not install_dir:
return
folder_path = lib / "steamapps" / "common" / install_dir
if not folder_path.exists():
return
linux_subdir = folder_path / f"{install_dir}_linux"
if linux_subdir.exists():
folder_path = linux_subdir
QDesktopServices.openUrl(QUrl.fromLocalFile(str(folder_path)))
return
class CustomLineEdit(QLineEdit):
def __init__(self, *args, theme=None, **kwargs):
+91 -9
View File
@@ -1,8 +1,15 @@
from PySide6.QtWidgets import QLabel, QPushButton, QWidget, QLayout, QLayoutItem
from PySide6.QtCore import Qt, Signal, QRect, QSize, Property, QPropertyAnimation, QEasingCurve
from PySide6.QtGui import QFont, QFontMetrics, QPainter
from PySide6.QtWidgets import QLabel, QPushButton, QStyle, QStyleOptionButton, QWidget, QLayout, QLayoutItem
from PySide6.QtCore import Qt, Signal, QRect, QRectF, QSize, Property, QPropertyAnimation, QEasingCurve
from PySide6.QtGui import QFont, QFontMetrics, QIcon, QPainter
from PySide6.QtSvg import QSvgRenderer
from portprotonqt.theme_manager import ThemeManager
from portprotonqt.config import ui_config
from portprotonqt.qt_utils import get_device_pixel_ratio
def _is_svg_icon(icon: object) -> bool:
return isinstance(icon, str) and icon.lower().endswith(".svg")
def compute_layout(nat_sizes, rect_width, spacing, max_scale, center_rows=True):
"""
@@ -407,20 +414,33 @@ class ClickableLabel(QLabel):
spacing = self._icon_space
text = self.text()
if self._icon:
pixmap = self._icon.pixmap(icon_size, icon_size)
has_icon = bool(self._icon)
if has_icon and not _is_svg_icon(self._icon):
device_pixel_ratio = get_device_pixel_ratio()
if isinstance(self._icon, str):
pixmap = QIcon(self._icon).pixmap(
QSize(icon_size, icon_size),
device_pixel_ratio,
)
elif isinstance(self._icon, QIcon):
pixmap = self._icon.pixmap(
QSize(icon_size, icon_size),
device_pixel_ratio,
)
else:
pixmap = None
else:
pixmap = None
fm = QFontMetrics(self.font())
available_width = rect.width()
if pixmap:
if has_icon:
available_width -= (icon_size + spacing)
available_width = max(0, available_width - 4)
display_text = fm.elidedText(text, Qt.TextElideMode.ElideRight, available_width)
text_width = fm.horizontalAdvance(display_text)
text_height = fm.height()
total_width = text_width + (icon_size + spacing if pixmap else 0)
total_width = text_width + (icon_size + spacing if has_icon else 0)
if alignment & Qt.AlignmentFlag.AlignHCenter:
x = rect.left() + (rect.width() - total_width) // 2
@@ -430,7 +450,11 @@ class ClickableLabel(QLabel):
x = rect.left()
y = rect.top() + (rect.height() - text_height) // 2
if pixmap:
if isinstance(self._icon, str) and _is_svg_icon(self._icon):
icon_rect = QRect(x, y + (text_height - icon_size) // 2, icon_size, icon_size)
QSvgRenderer(self._icon).render(painter, QRectF(icon_rect))
text_x = x + icon_size + spacing
elif pixmap:
icon_rect = QRect(x, y + (text_height - icon_size) // 2, icon_size, icon_size)
painter.drawPixmap(icon_rect, pixmap)
text_x = x + icon_size + spacing
@@ -501,7 +525,6 @@ class AutoSizeButton(QPushButton):
if self._icon:
self.setIcon(self._icon)
self.setIconSize(QSize(self._icon_size, self._icon_size))
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.setFlat(True)
@@ -515,6 +538,65 @@ class AutoSizeButton(QPushButton):
def alignment(self):
return self._alignment
def rawIcon(self) -> object | None:
return self._icon
def setIcon(self, icon: object) -> None:
self._icon = icon
if _is_svg_icon(icon):
super().setIcon(QIcon())
elif isinstance(icon, str):
super().setIcon(QIcon(icon))
elif isinstance(icon, QIcon):
super().setIcon(icon)
else:
super().setIcon(QIcon())
self.setIconSize(QSize(self._icon_size, self._icon_size))
self.update()
def paintEvent(self, event):
if not _is_svg_icon(self._icon):
super().paintEvent(event)
return
icon_path = self._icon
if not isinstance(icon_path, str):
super().paintEvent(event)
return
option = QStyleOptionButton()
self.initStyleOption(option)
option.text = ""
option.icon = QIcon()
painter = QPainter(self)
self.style().drawControl(QStyle.ControlElement.CE_PushButton, option, painter, self)
rect = self.style().subElementRect(
QStyle.SubElement.SE_PushButtonContents,
option,
self,
)
fm = QFontMetrics(self.font())
text = self.text()
text_width = fm.horizontalAdvance(text)
icon_spacing = self._icon_size // 2 if text else 0
total_width = self._icon_size + icon_spacing + text_width
x = rect.left() + (rect.width() - total_width) // 2
icon_y = rect.top() + (rect.height() - self._icon_size) // 2
icon_rect = QRect(x, icon_y, self._icon_size, self._icon_size)
QSvgRenderer(icon_path).render(painter, QRectF(icon_rect))
text_rect = QRect(x + self._icon_size + icon_spacing, rect.top(), text_width, rect.height())
self.style().drawItemText(
painter,
text_rect,
self._alignment,
self.palette(),
self.isEnabled(),
text,
self.foregroundRole(),
)
def setText(self, text):
self._original_text = text
if not self._update_size:
-4
View File
@@ -19,8 +19,6 @@ from portprotonqt.debug_utils.system_info import (
get_libc_version,
get_program_bit_depth,
get_filesystem_info,
get_system_dpi_for_wine,
get_screen_info,
generate_system_info,
)
@@ -69,8 +67,6 @@ __all__ = [
"get_libc_version",
"get_program_bit_depth",
"get_filesystem_info",
"get_system_dpi_for_wine",
"get_screen_info",
"get_ppdb_content",
"get_user_overrides",
"get_prefix_name",
+2 -54
View File
@@ -7,11 +7,10 @@ import subprocess
from datetime import datetime
import psutil
from PySide6.QtWidgets import QApplication
from PySide6.QtGui import QGuiApplication
from portprotonqt.logger import get_logger
from portprotonqt.localization import _
from portprotonqt.qt_utils import get_screen_info
from portprotonqt.debug_utils.env_utils import get_file_content
from portprotonqt.debug_utils.gpu_info import get_graphics_info_detailed
@@ -300,57 +299,6 @@ def get_filesystem_info(exe_path: str | None, portproton_path: str) -> str:
return "\n".join(lines) if lines else "Unable to retrieve filesystem info"
def get_system_dpi_for_wine(screen_resolution: str | None = None) -> str:
"""Return Wine LogPixels value calculated from system scale."""
app_instance = QApplication.instance()
if isinstance(app_instance, QGuiApplication):
window = app_instance.focusWindow()
if window is None:
for widget in QApplication.topLevelWidgets():
if widget.isVisible() and widget.windowHandle() is not None:
window = widget.windowHandle()
break
if window is not None:
dpi_value = int(round(96.0 * window.devicePixelRatio()))
if dpi_value > 96:
return str(dpi_value)
return "96"
def get_screen_info(portproton_path: str, exe_path: str | None = None) -> tuple[str, str]:
"""Get screen resolution and primary info using PySide6."""
app_instance = QApplication.instance()
default_resolution = "1920x1080"
default_primary = ""
if not isinstance(app_instance, QGuiApplication):
return (
f"PW_SCREEN_RESOLUTION={default_resolution}",
f"PW_SCREEN_PRIMARY={default_primary}",
)
screen = app_instance.primaryScreen()
if screen is None:
screens = app_instance.screens()
if screens:
screen = screens[0]
if screen is None:
return (
f"PW_SCREEN_RESOLUTION={default_resolution}",
f"PW_SCREEN_PRIMARY={default_primary}",
)
geometry = screen.geometry()
if geometry.width() > 0 and geometry.height() > 0:
resolution = f"{geometry.width()}x{geometry.height()}"
else:
resolution = default_resolution
primary = screen.name() or default_primary
return f"PW_SCREEN_RESOLUTION={resolution}", f"PW_SCREEN_PRIMARY={primary}"
def generate_system_info(
exe_path: str | None = None,
start_cmd: list[str] | None = None,
@@ -448,7 +396,7 @@ def generate_system_info(
lines.append(get_graphics_info_detailed())
lines.append("-" * 61)
screen_resolution, screen_primary = get_screen_info(portproton_path, exe_path)
screen_resolution, screen_primary = get_screen_info()
if screen_resolution:
lines.append(screen_resolution)
+30 -18
View File
@@ -21,6 +21,7 @@ from portprotonqt.detail_pages.widgets import (
create_back_button,
create_content_frame,
setup_adaptive_layout,
apply_adaptive_layout,
create_cover_frame,
create_protondb_badge,
create_steam_badge,
@@ -195,19 +196,17 @@ class DetailPageManager:
return size, size
def _create_game_badges(self, parent: QWidget, game_data: dict) -> list:
from portprotonqt.config import game_config
if self._is_compact_detail_layout():
return []
display_filter = game_config.get_display_filter()
game_source = str(game_data.get("game_source", "")).lower()
appid = game_data.get("appid", "")
name = game_data.get("name", "")
exec_line = game_data.get("exec_line", "")
steam_visible = game_source == "steam" and display_filter in ("all", "favorites")
portproton_visible = game_source == "portproton" and display_filter in ("all", "favorites")
steam_visible = game_source == "steam"
portproton_visible = game_source == "portproton"
badges = []
protondb_badge = self._create_protondb_badge(parent, game_data)
@@ -323,6 +322,19 @@ class DetailPageManager:
if has_data:
game_info_layout.addLayout(hltb_layout)
QTimer.singleShot(0, self._refresh_current_detail_page_layout)
def _refresh_current_detail_page_layout(self) -> None:
"""Refresh layout after asynchronous detail content changes."""
if not self._detail_page_active or not self._current_detail_page:
return
content_frame_layout = self._get_content_frame_layout(self._current_detail_page)
if content_frame_layout:
content_frame_layout.invalidate()
apply_adaptive_layout(self._current_detail_page, content_frame_layout)
self._current_detail_page.updateGeometry()
def _add_hltb_times(
self, game: GameEntry, hltb: HowLongToBeat, hltb_layout: QHBoxLayout
@@ -378,7 +390,7 @@ class DetailPageManager:
if self._has_game_shortcut(game_name):
edit_button = self._make_action_button(
_("Edit Game"),
self.main_window.theme_manager.get_icon("edit"),
self.main_window.theme_manager.get_icon("edit", as_path=True),
)
edit_button.clicked.connect(
lambda: self.main_window.context_menu_manager.edit_game_shortcut(
@@ -389,7 +401,7 @@ class DetailPageManager:
elif str(game_source).lower() == "steam" and appid:
open_folder_button = self._make_action_button(
_("Open Game Folder"),
self.main_window.theme_manager.get_icon("search"),
self.main_window.theme_manager.get_icon("search", as_path=True),
)
open_folder_button.clicked.connect(
lambda: self._open_steam_game_folder(str(appid))
@@ -398,7 +410,7 @@ class DetailPageManager:
else:
add_button = self._make_action_button(
_("Add Game"),
self.main_window.theme_manager.get_icon("addgame"),
self.main_window.theme_manager.get_icon("addgame", as_path=True),
)
add_button.clicked.connect(
lambda: self.main_window.openAddGameDialog(
@@ -429,10 +441,10 @@ class DetailPageManager:
"""Create play/stop button."""
if self.main_window.target_exe is not None and current_exe == self.main_window.target_exe:
text = _("Stop")
icon = self.main_window.theme_manager.get_icon("stop")
icon = self.main_window.theme_manager.get_icon("stop", as_path=True)
else:
text = _("Play")
icon = self.main_window.theme_manager.get_icon("play")
icon = self.main_window.theme_manager.get_icon("play", as_path=True)
play_button = self._make_action_button(text, icon)
play_button.clicked.connect(lambda: self.main_window.toggleGame(exec_line, play_button))
@@ -442,14 +454,14 @@ class DetailPageManager:
"""Add settings and log buttons for PortProton games."""
file_to_check = self._get_file_from_exec(exec_line)
settings_icon = self.main_window.theme_manager.get_icon("settings")
settings_icon = self.main_window.theme_manager.get_icon("settings", as_path=True)
settings_button = self._make_action_button(_("Settings"), settings_icon)
settings_button.clicked.connect(
lambda: self.main_window.open_exe_settings(file_to_check, game_source="portproton")
)
buttons_layout.addWidget(settings_button)
log_icon = self.main_window.theme_manager.get_icon("edit")
log_icon = self.main_window.theme_manager.get_icon("edit", as_path=True)
log_button = self._make_action_button(_("Create Log"), log_icon)
log_button.clicked.connect(lambda: self.toggleDebugLog(file_to_check, log_button))
buttons_layout.addWidget(log_button)
@@ -468,7 +480,7 @@ class DetailPageManager:
if not os.path.exists(fake_exe_path):
open(fake_exe_path, 'a').close()
settings_icon = self.main_window.theme_manager.get_icon("settings")
settings_icon = self.main_window.theme_manager.get_icon("settings", as_path=True)
settings_button = self._make_action_button(_("Settings"), settings_icon)
settings_button.clicked.connect(
lambda: self.main_window.open_exe_settings(fake_exe_path, appid, "steam")
@@ -825,7 +837,7 @@ class DetailPageManager:
self, script_name: str, name: str, buttons_layout: FlowLayout
) -> AutoSizeButton:
"""Create install button for auto-install page."""
install_button = self._make_action_button(_("Install"), self.main_window.theme_manager.get_icon("save"))
install_button = self._make_action_button(_("Install"), self.main_window.theme_manager.get_icon("save", as_path=True))
install_button.clicked.connect(
lambda: self.main_window.launch_autoinstall(script_name, install_button)
)
@@ -844,7 +856,7 @@ class DetailPageManager:
self.main_window.installing
and self.main_window.current_install_script == script_name
):
icon = self.main_window.theme_manager.get_icon("stop")
icon = self.main_window.theme_manager.get_icon("stop", as_path=True)
if icon:
install_button.setIcon(icon)
install_button.setText(_("Stop"))
@@ -852,7 +864,7 @@ class DetailPageManager:
text = _("Reinstall") if is_installed else _("Install")
icon_name = "update" if is_installed else "save"
icon = self.main_window.theme_manager.get_icon(icon_name)
icon = self.main_window.theme_manager.get_icon(icon_name, as_path=True)
if icon:
install_button.setIcon(icon)
# Update text without changing button size drastically
@@ -950,7 +962,7 @@ class DetailPageManager:
log_file = self.debug_log_manager.stop()
button.setText(_("Create Log"))
icon = self.main_window.theme_manager.get_icon("edit")
icon = self.main_window.theme_manager.get_icon("edit", as_path=True)
if icon:
button.setIcon(icon)
@@ -971,7 +983,7 @@ class DetailPageManager:
if self.debug_log_manager.start(resolved_exe_path, start_command):
button.setText(_("Stop Log"))
icon = self.main_window.theme_manager.get_icon("stop")
icon = self.main_window.theme_manager.get_icon("stop", as_path=True)
if icon:
button.setIcon(icon)
self._startDebugTimer()
@@ -1026,7 +1038,7 @@ class DetailPageManager:
"""Update debug log button and show dialog if log saved."""
if self._debug_log_button:
self._debug_log_button.setText(_("Create Log"))
icon = self.main_window.theme_manager.get_icon("edit")
icon = self.main_window.theme_manager.get_icon("edit", as_path=True)
if icon:
self._debug_log_button.setIcon(icon)
+27 -24
View File
@@ -78,7 +78,7 @@ def create_back_button(
dummy = AutoSizeButton()
dummy.setVisible(False)
return dummy
back_button = AutoSizeButton(_("Back"), icon=theme_manager.get_icon("back"))
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.clicked.connect(on_click)
@@ -107,30 +107,33 @@ def setup_adaptive_layout(
"""Setup adaptive layout switching on resize."""
def on_detail_page_resize(event) -> None:
if detail_page.property("force_compact_detail_layout"):
content_frame_layout.setDirection(QBoxLayout.Direction.TopToBottom)
content_frame_layout.setAlignment(
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
)
QWidget.resizeEvent(detail_page, event)
return
required_width = _get_required_horizontal_width(content_frame_layout)
if detail_page.width() < required_width:
if content_frame_layout.direction() != QBoxLayout.Direction.TopToBottom:
content_frame_layout.setDirection(QBoxLayout.Direction.TopToBottom)
content_frame_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
else:
if content_frame_layout.direction() != QBoxLayout.Direction.LeftToRight:
content_frame_layout.setDirection(QBoxLayout.Direction.LeftToRight)
content_frame_layout.setAlignment(
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
)
apply_adaptive_layout(detail_page, content_frame_layout)
QWidget.resizeEvent(detail_page, event)
detail_page.resizeEvent = on_detail_page_resize
def apply_adaptive_layout(detail_page: QWidget, content_frame_layout: QBoxLayout) -> None:
"""Apply detail page adaptive layout for current size hints."""
if detail_page.property("force_compact_detail_layout"):
content_frame_layout.setDirection(QBoxLayout.Direction.TopToBottom)
content_frame_layout.setAlignment(
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
)
return
required_width = _get_required_horizontal_width(content_frame_layout)
if detail_page.width() < required_width:
if content_frame_layout.direction() != QBoxLayout.Direction.TopToBottom:
content_frame_layout.setDirection(QBoxLayout.Direction.TopToBottom)
content_frame_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
elif content_frame_layout.direction() != QBoxLayout.Direction.LeftToRight:
content_frame_layout.setDirection(QBoxLayout.Direction.LeftToRight)
content_frame_layout.setAlignment(
Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
)
def _get_required_horizontal_width(content_frame_layout: QBoxLayout) -> int:
"""Calculate minimal width for horizontal content layout."""
item_count = content_frame_layout.count()
@@ -327,7 +330,7 @@ def create_protondb_badge(
return None, False
icon_filename = GameCard.getProtonDBIconFilename(protondb_tier)
icon = main_window.theme_manager.get_icon(icon_filename, main_window.current_theme_name)
icon = main_window.theme_manager.get_icon(icon_filename, main_window.current_theme_name, as_path=True)
badge = ClickableLabel(
protondb_text,
@@ -350,7 +353,7 @@ def create_steam_badge(
main_window,
) -> ClickableLabel:
"""Create Steam badge."""
steam_icon = main_window.theme_manager.get_icon("badge_steam")
steam_icon = main_window.theme_manager.get_icon("badge_steam", as_path=True)
badge = ClickableLabel(
"Steam",
icon=steam_icon,
@@ -372,7 +375,7 @@ def create_portproton_badge(
main_window,
) -> ClickableLabel:
"""Create PortProton badge."""
portproton_icon = main_window.theme_manager.get_icon("badge_portproton")
portproton_icon = main_window.theme_manager.get_icon("badge_portproton", as_path=True)
badge = ClickableLabel(
"PortProton",
icon=portproton_icon,
@@ -399,7 +402,7 @@ def create_anticheat_badge(
return None, False
icon_filename = GameCard.getAntiCheatIconFilename(anticheat_status)
icon = main_window.theme_manager.get_icon(icon_filename, main_window.current_theme_name)
icon = main_window.theme_manager.get_icon(icon_filename, main_window.current_theme_name, as_path=True)
badge = ClickableLabel(
anticheat_text,
+1 -1
View File
@@ -5,10 +5,10 @@ New code should import directly from portprotonqt.dialogs package.
"""
# Re-export all dialog classes for backward compatibility
from portprotonqt.icon_extractor import generate_thumbnail
from portprotonqt.dialogs.base import (
GameLaunchDialog,
AddGameDialog,
generate_thumbnail,
FileSelectedSignal,
)
from portprotonqt.dialogs.file_explorer import FileExplorer
+2 -1
View File
@@ -5,7 +5,8 @@ from portprotonqt.dialogs.file_explorer import FileExplorer
from portprotonqt.dialogs.winetricks_dialog import WinetricksDialog
from portprotonqt.dialogs.settings_dialog import ExeSettingsDialog
from portprotonqt.dialogs.proton_manager import ProtonManager
from portprotonqt.dialogs.base import GameLaunchDialog, AddGameDialog, generate_thumbnail, FileSelectedSignal
from portprotonqt.icon_extractor import generate_thumbnail
from portprotonqt.dialogs.base import GameLaunchDialog, AddGameDialog, FileSelectedSignal
__all__ = [
'create_dialog_hints_widget',
+7 -77
View File
@@ -9,7 +9,6 @@ from PySide6.QtWidgets import (
QProgressBar, QSizePolicy, QWidget, QCheckBox
)
from PySide6.QtCore import Qt, QObject, Signal, QTimer, QStandardPaths, QSize
from PIL import Image
import psutil
if TYPE_CHECKING:
@@ -23,80 +22,13 @@ from portprotonqt.downloader import Downloader
from portprotonqt.virtual_keyboard import VirtualKeyboard
from portprotonqt.localization import _
from portprotonqt.image_utils import COVER_IMAGE_EXTENSIONS, set_animated_cover
from portprotonqt.icon_extractor import IconExtractor, IconExtractorError
from portprotonqt.icon_extractor import generate_thumbnail
logger = get_logger(__name__)
theme_manager = ThemeManager()
DISC_IMAGE_EXTENSIONS = (".iso", ".mdf")
def generate_thumbnail(inputfile, outfile, size=128, force_resize=True):
"""
Generates a thumbnail for an .exe file.
inputfile: the input file path (%i)
outfile: output filename (%o)
size: determines the thumbnail output size (%s)
"""
logger.debug(f"Starting thumbnail generation: {inputfile} → {outfile}, size={size}, force={force_resize}")
try:
extractor = IconExtractor(inputfile)
logger.debug("IconExtractor created successfully.")
except (RuntimeError, IconExtractorError) as e:
logger.warning(f"Failed to create IconExtractor: {e}")
return False
try:
data = extractor.get_icon()
if data is None:
return False
im = Image.open(data)
logger.debug(f"Extracted icon size {im.size}, formats: {im.format}, frames: {getattr(im, 'n_frames', 1)}")
except Exception as e:
logger.warning(f"Error extracting icon: {e}")
return False
if force_resize:
logger.debug(f"Forcing icon resize to {size}x{size}")
im = im.resize((size, size), Image.Resampling.LANCZOS)
else:
if size > 256:
logger.warning('Requested size larger than 256, set to 256')
size = 256
elif size not in (128, 256):
logger.warning(f'Unsupported size {size}, set to 128')
size = 128
if size == 256:
logger.debug("Saving icon without resize (256x256)")
im.save(outfile, "PNG")
logger.info(f"Icon saved to {outfile}")
return True
frames = getattr(im, 'n_frames', 1)
try:
for frame in range(frames):
im.seek(frame)
if im.size == (size, size):
logger.debug(f"Found frame with size {size}x{size}")
break
except EOFError:
logger.debug("Frames ended before finding required size.")
if im.size != (size, size):
logger.debug(f"Resizing from {im.size} to {size}x{size}")
im = im.resize((size, size))
try:
im.save(outfile, "PNG")
logger.info(f"Thumbnail successfully saved to {outfile}")
return True
except Exception as e:
logger.error(f"Error saving thumbnail: {e}")
return False
class FileSelectedSignal(QObject):
"""Signal class for file selection."""
file_selected = Signal(str)
@@ -144,7 +76,7 @@ class GameLaunchDialog(DraggableDialog):
self.progress_bar.setRange(0, 0)
layout.addWidget(self.progress_bar)
self.cancel_button = AutoSizeButton(_("Cancel"), icon=theme_manager.get_icon("cancel"))
self.cancel_button = AutoSizeButton(_("Cancel"), icon=theme_manager.get_icon("cancel", as_path=True))
self.cancel_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.cancel_button.clicked.connect(self.reject)
layout.addWidget(self.cancel_button, alignment=Qt.AlignmentFlag.AlignCenter)
@@ -227,7 +159,7 @@ class AddGameDialog(DraggableDialog):
if exe_path:
self.exeEdit.setText(exe_path)
exeBrowseButton = AutoSizeButton(_("Browse..."), icon=theme_manager.get_icon("search"))
exeBrowseButton = AutoSizeButton(_("Browse..."), icon=theme_manager.get_icon("search", as_path=True))
exeBrowseButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
exeBrowseButton.clicked.connect(self.browseExe)
exeBrowseButton.setObjectName("exeBrowseButton")
@@ -247,7 +179,7 @@ class AddGameDialog(DraggableDialog):
if cover_path:
self.coverEdit.setText(cover_path)
coverBrowseButton = AutoSizeButton(_("Browse..."), icon=theme_manager.get_icon("search"))
coverBrowseButton = AutoSizeButton(_("Browse..."), icon=theme_manager.get_icon("search", as_path=True))
coverBrowseButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
coverBrowseButton.clicked.connect(self.browseCover)
coverBrowseButton.setObjectName("coverBrowseButton")
@@ -303,8 +235,8 @@ class AddGameDialog(DraggableDialog):
self.button_layout = QHBoxLayout()
self.button_layout.setSpacing(10)
self.select_button = AutoSizeButton(_("Apply"), icon=theme_manager.get_icon("apply"))
self.cancel_button = AutoSizeButton(_("Cancel"), icon=theme_manager.get_icon("cancel"))
self.select_button = AutoSizeButton(_("Apply"), icon=theme_manager.get_icon("apply", as_path=True))
self.cancel_button = AutoSizeButton(_("Cancel"), icon=theme_manager.get_icon("cancel", as_path=True))
self.select_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.cancel_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.button_layout.addWidget(self.select_button)
@@ -538,9 +470,7 @@ class AddGameDialog(DraggableDialog):
result = create_desktop_file(exe_path, name)
if not result:
return None, None
desktop_entry, desktop_path = result
base_path = os.path.join(os.path.dirname(desktop_path), "data")
icon_path = os.path.join(base_path, "img", f"{name}.png")
desktop_entry, desktop_path, icon_path = result
if not self.last_cover_path and not generate_thumbnail(launch_path, icon_path, size=128):
logger.error(f"Failed to generate thumbnail from exe: {launch_path}")
+33 -14
View File
@@ -21,7 +21,8 @@ from portprotonqt.theme_manager import ThemeManager
from portprotonqt.custom_widgets import AutoSizeButton
from portprotonqt.localization import _
from portprotonqt.dialogs.dialog_utils import create_dialog_hints_widget, update_dialog_hints
from portprotonqt.dialogs.base import DraggableDialog, generate_thumbnail, FileSelectedSignal
from portprotonqt.icon_extractor import generate_thumbnail
from portprotonqt.dialogs.base import DraggableDialog, FileSelectedSignal
from portprotonqt.image_utils import COVER_IMAGE_EXTENSIONS
logger = get_logger(__name__)
@@ -283,6 +284,8 @@ class FileExplorer(DraggableDialog):
mounts.append(mount_point)
for mount_point in mounts:
if mount_point == "/":
continue
if mount_point in ("/media", "/mnt", "/run/media"):
continue
if mount_point != "/" and not mount_point.startswith(("/run/media/", "/media/", "/mnt/")):
@@ -336,8 +339,8 @@ class FileExplorer(DraggableDialog):
self.button_layout = QHBoxLayout()
self.button_layout.setSpacing(10)
self.select_button = AutoSizeButton(_("Select"), icon=theme_manager.get_icon("apply"))
self.cancel_button = AutoSizeButton(_("Cancel"), icon=theme_manager.get_icon("cancel"))
self.select_button = AutoSizeButton(_("Select"), icon=theme_manager.get_icon("apply", as_path=True))
self.cancel_button = AutoSizeButton(_("Cancel"), icon=theme_manager.get_icon("cancel", as_path=True))
self.select_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.cancel_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.button_layout.addWidget(self.select_button)
@@ -454,12 +457,21 @@ class FileExplorer(DraggableDialog):
widget.deleteLater()
self.drive_buttons = []
home_path = os.path.expanduser("~")
drives = self.get_mounted_drives()
favorite_folders = favorites_folders_config.get_folders()
if os.path.isdir(home_path) and os.access(home_path, os.R_OK):
button = AutoSizeButton(_("Home"), icon=theme_manager.get_icon("folder", as_path=True))
button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
button.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
button.clicked.connect(lambda checked, path=home_path: self.change_drive(path))
self.drives_layout.addWidget(button)
self.drive_buttons.append(button)
for drive in drives:
drive_name = os.path.basename(drive) or drive.split('/')[-1] or drive
button = AutoSizeButton(drive_name, icon=theme_manager.get_icon("mount_point"))
button = AutoSizeButton(drive_name, icon=theme_manager.get_icon("mount_point", as_path=True))
button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
button.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
button.clicked.connect(lambda checked, path=drive: self.change_drive(path))
@@ -468,7 +480,7 @@ class FileExplorer(DraggableDialog):
for folder in favorite_folders:
folder_name = os.path.basename(folder) or folder.split('/')[-1] or folder
button = AutoSizeButton(folder_name, icon=theme_manager.get_icon("folder"))
button = AutoSizeButton(folder_name, icon=theme_manager.get_icon("folder", as_path=True))
button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
button.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
button.clicked.connect(lambda checked, path=folder: self.change_drive(path))
@@ -486,15 +498,12 @@ class FileExplorer(DraggableDialog):
drive_name = focused_widget.text().strip()
logger.debug(f"Selected name: {drive_name}")
if drive_name == "/":
if os.path.isdir("/") and os.access("/", os.R_OK):
self.current_path = "/"
self.update_file_list()
logger.info("Selected root directory")
return
else:
logger.warning("Root directory is inaccessible: insufficient permissions or path error")
return
home_path = os.path.expanduser("~")
if drive_name == _("Home") and os.path.isdir(home_path) and os.access(home_path, os.R_OK):
self.current_path = os.path.normpath(home_path)
self.update_file_list()
logger.info(f"Selected home directory: {self.current_path}")
return
favorite_folders = favorites_folders_config.get_folders()
logger.debug(f"Favorite folders: {favorite_folders}")
@@ -577,6 +586,16 @@ class FileExplorer(DraggableDialog):
for f in sorted(files):
file_path = os.path.join(self.current_path, f)
item = QListWidgetItem(f)
mime_type = self.mime_db.mimeTypeForFile(file_path)
if (
mime_type.name() in ("application/vnd.squashfs", "application/x-squashfs")
or mime_type.inherits("application/vnd.squashfs")
):
ppack_icon = theme_manager.get_icon("ppack")
if isinstance(ppack_icon, str) and os.path.isfile(ppack_icon):
ppack_icon = QIcon(ppack_icon)
if isinstance(ppack_icon, QIcon):
item.setIcon(ppack_icon)
self.file_items[file_path] = item
self.file_list.addItem(item)
+76 -7
View File
@@ -4,6 +4,7 @@ import os
import re
import shutil
import subprocess
from pathlib import Path
from typing import cast, TYPE_CHECKING
from PySide6.QtCore import Qt, QObject, QEvent, QProcess, QTimer, QUrl
@@ -155,9 +156,17 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
if version not in self.dist_options:
self.dist_options.append(version)
from portprotonqt.steam_api import get_steam_proton_versions
from portprotonqt.steam_api.utils import _is_steam_proton_dir
for version in get_steam_proton_versions():
if version not in self.dist_options:
self.dist_options.append(version)
if self.game_source == "steam":
self.dist_options = [
version for version in self.dist_options
if _is_steam_proton_dir(
Path(version) if os.path.isabs(version) else Path(dist_dir, version)
)
]
self.dist_options.sort(key=version_sort_key)
prefixes_dir = os.path.join(self.portproton_path, 'prefixes')
if os.path.exists(prefixes_dir):
@@ -167,7 +176,7 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
key=prefix_sort_key
)
if shutil.which('wine'):
if self.game_source != "steam" and shutil.which('wine'):
if _('System WINE') not in self.dist_options:
self.dist_options.append(_('System WINE'))
@@ -232,6 +241,18 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
"""Get the full arguments for QProcess.start."""
return self.start_sh + subcommand_args
def _resolve_run_after_exe_path(self, exe_path: str) -> str:
"""Resolve run-after executable relative to the main executable."""
if not exe_path:
return exe_path
normalized = os.path.normpath(os.path.expanduser(exe_path))
if os.path.isabs(normalized):
return normalized
game_dir = os.path.dirname(self.exe_path or "")
if not game_dir:
return normalized
return os.path.normpath(os.path.join(game_dir, normalized))
def setup_ui(self):
"""Set up the user interface."""
self.main_layout = QVBoxLayout(self)
@@ -362,23 +383,28 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
self.gamepad_tooltip_timer.timeout.connect(lambda: self.gamepad_tooltip.setVisible(False))
button_layout = QHBoxLayout()
self.apply_button = AutoSizeButton(_("Apply"), icon=ThemeManager().get_icon("apply"))
self.cancel_button = AutoSizeButton(_("Cancel"), icon=ThemeManager().get_icon("cancel"))
self.open_ppdb_button = AutoSizeButton(_("Open PPDB"), icon=ThemeManager().get_icon("folder"))
self.apply_button = AutoSizeButton(_("Apply"), icon=ThemeManager().get_icon("apply", as_path=True))
self.cancel_button = AutoSizeButton(_("Cancel"), icon=ThemeManager().get_icon("cancel", as_path=True))
self.open_ppdb_button = AutoSizeButton(_("Open PPDB"), icon=ThemeManager().get_icon("folder", as_path=True))
self.clear_ppdb_button = AutoSizeButton(_("Clear PPDB"), icon=ThemeManager().get_icon("delete", as_path=True))
self.apply_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.cancel_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.open_ppdb_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.clear_ppdb_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.apply_button.installEventFilter(self)
self.cancel_button.installEventFilter(self)
self.open_ppdb_button.installEventFilter(self)
self.clear_ppdb_button.installEventFilter(self)
button_layout.addWidget(self.apply_button)
button_layout.addWidget(self.cancel_button)
button_layout.addWidget(self.open_ppdb_button)
button_layout.addWidget(self.clear_ppdb_button)
self.main_layout.addLayout(button_layout)
self.apply_button.clicked.connect(self.apply_changes)
self.cancel_button.clicked.connect(self.reject)
self.open_ppdb_button.clicked.connect(self.open_ppdb_file)
self.clear_ppdb_button.clicked.connect(self.clear_ppdb_file)
self._install_line_edit_event_filters()
def load_current_settings(self):
@@ -438,6 +464,7 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
"PW_USE_D3D_EXTRAS",
"PW_USE_GALLIUM_NINE",
"PW_USE_SUPPLIED_DXVK_VKD3D",
"PW_USE_INHIBIT_SLEEP",
})
if exit_code != 0 or exit_status != QProcess.ExitStatus.NormalExit:
for key in self.toggle_settings:
@@ -460,7 +487,12 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
if current_wine_version in self.lg_dist_aliases:
self.current_settings['PW_WINE_USE'] = self.lg_dist_aliases[current_wine_version]
current_wine_version = self.current_settings['PW_WINE_USE']
if current_wine_version and current_wine_version not in self.dist_options:
if (
current_wine_version
and current_wine_version not in self.dist_options
and self.game_source != "steam"
and current_wine_version != 'USE_SYSTEM_WINE'
):
self.dist_options.append(current_wine_version)
self.original_values = self.current_settings.copy()
@@ -491,6 +523,39 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
if not QDesktopServices.openUrl(QUrl.fromLocalFile(db_path)):
QMessageBox.critical(self, _("Error"), _("Failed to open PPDB file:\n") + db_path)
def clear_ppdb_file(self):
"""Remove the PPDB file and reload settings."""
if not self.exe_path:
QMessageBox.critical(self, _("Error"), _("Executable path is not available."))
return
db_path = self.exe_path + ".ppdb"
if not os.path.exists(db_path):
QMessageBox.information(self, _("Information"), _("PPDB file does not exist at: ") + db_path)
self.load_current_settings()
return
msg_box = QMessageBox(self)
msg_box.setIcon(QMessageBox.Icon.Question)
msg_box.setWindowTitle(_("Confirm PPDB Clear"))
msg_box.setText(_("Are you sure you want to clear settings? This action cannot be undone."))
msg_box.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
msg_box.setDefaultButton(QMessageBox.StandardButton.No)
msg_box.setButtonText(QMessageBox.StandardButton.Yes, _("Yes"))
msg_box.setButtonText(QMessageBox.StandardButton.No, _("No"))
if msg_box.exec() != QMessageBox.StandardButton.Yes:
return
try:
os.remove(db_path)
except OSError as exc:
logger.warning("Failed to remove PPDB file %s: %s", db_path, exc)
QMessageBox.warning(self, _("Error"), _("Failed to remove PPDB file:\n") + db_path)
return
QMessageBox.information(self, _("Success"), _("PPDB settings cleared."))
self.load_current_settings()
def populate_table(self):
"""Populate the table with settings."""
self.settings_table.setRowCount(0)
@@ -658,12 +723,13 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
if setting['key'] == 'PW_RUN_AFTER_EXE':
text_container = QWidget()
text_container.setProperty("ppqt_run_after_exe_widget", True)
text_layout = QHBoxLayout(text_container)
text_layout.setContentsMargins(0, 0, 0, 0)
text_layout.setSpacing(6)
text_layout.addWidget(line_edit)
browse_button = AutoSizeButton("...", icon=ThemeManager().get_icon("folder"))
browse_button = AutoSizeButton("...", icon=ThemeManager().get_icon("folder", as_path=True))
browse_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
browse_button.setFixedWidth(56)
browse_button.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -678,7 +744,7 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
initial_path = os.path.expanduser("~")
current_path = target_line_edit.text().strip()
if current_path:
normalized = os.path.normpath(current_path)
normalized = self._resolve_run_after_exe_path(current_path)
if os.path.isfile(normalized):
initial_path = os.path.dirname(normalized)
elif os.path.isdir(normalized):
@@ -837,6 +903,8 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
elif isinstance(widget, QLineEdit):
new_val = widget.text().strip()
if key == 'PW_RUN_AFTER_EXE':
new_val = self._resolve_run_after_exe_path(new_val)
if new_val != orig_val:
changes.append(f"{key}={new_val}")
else:
@@ -905,6 +973,7 @@ class ExeSettingsDialog(DraggableDialog, MangoHudSettingsMixin, GamescopeSetting
getattr(self, "apply_button", None),
getattr(self, "cancel_button", None),
getattr(self, "open_ppdb_button", None),
getattr(self, "clear_ppdb_button", None),
)
if obj in action_buttons:
if event.type() in (
@@ -1025,7 +1025,11 @@ class GamescopeSettingsMixin:
def _filter_gamescope_settings(self, search_text):
"""Filter Gamescope groups based on search text."""
gamescope_enabled = self.current_settings.get('PW_GAMESCOPE') == '1'
for group_box in self.gamescope_tab.findChildren(QGroupBox):
if not gamescope_enabled:
group_box.setVisible(group_box is self.gamescope_actions_group)
continue
if not search_text:
group_box.setVisible(True)
continue
+15 -8
View File
@@ -508,7 +508,7 @@ class MangoHudSettingsMixin:
actions_layout.addWidget(self.mangohud_user_conf_button, 0, 1)
preset_buttons = [
(_("PortProton default"), self.apply_portproton_default_mangohud),
("PortProton", self.apply_portproton_default_mangohud),
(_("FPS only"), lambda: self.apply_mangohud_button_preset('fps_only')),
(_("Compact"), lambda: self.apply_mangohud_button_preset('compact')),
(_("Extended"), lambda: self.apply_mangohud_button_preset('extended')),
@@ -837,6 +837,7 @@ class MangoHudSettingsMixin:
mangohud_enabled = self.current_settings.get('PW_MANGOHUD') == '1'
mangohud_user_conf_enabled = self.current_settings.get('PW_MANGOHUD_USER_CONF') == '1'
visible = mangohud_enabled
config_visible = mangohud_enabled and not mangohud_user_conf_enabled
if mangohud_enabled:
self.mangohud_enable_button.setText(_("Disable MangoHud"))
@@ -854,20 +855,20 @@ class MangoHudSettingsMixin:
self.mangohud_user_conf_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
if self.mangohud_toggle_group is not None:
self.mangohud_toggle_group.setVisible(visible)
self.mangohud_toggle_group.setVisible(config_visible)
if self.mangohud_presets_group is not None:
self.mangohud_presets_group.setVisible(visible)
self.mangohud_presets_group.setVisible(config_visible)
if self.mangohud_values_group is not None:
self.mangohud_values_group.setVisible(visible)
self.mangohud_values_group.setVisible(config_visible)
if self.mangohud_fps_group is not None:
self.mangohud_fps_group.setVisible(visible)
self.mangohud_fps_group.setVisible(config_visible)
if self.mangohud_extra_group is not None:
self.mangohud_extra_group.setVisible(visible)
self.mangohud_extra_group.setVisible(config_visible)
for button in self.mangohud_preset_buttons:
button.setVisible(visible)
button.setVisible(config_visible)
for button in self.mangohud_action_buttons:
button.setVisible(visible)
button.setVisible(config_visible)
def toggle_mangohud_enable(self):
"""Toggle PW_MANGOHUD setting."""
@@ -1225,7 +1226,13 @@ class MangoHudSettingsMixin:
def _filter_mangohud_settings(self, search_text):
"""Filter MangoHud groups based on search text."""
mangohud_enabled = self.current_settings.get('PW_MANGOHUD') == '1'
mangohud_user_conf_enabled = self.current_settings.get('PW_MANGOHUD_USER_CONF') == '1'
config_visible = mangohud_enabled and not mangohud_user_conf_enabled
for group_box in self.mangohud_tab.findChildren(QGroupBox):
if not config_visible:
group_box.setVisible(group_box is self.mangohud_actions_group)
continue
if not search_text:
group_box.setVisible(True)
continue
+8 -8
View File
@@ -94,15 +94,15 @@ class WinetricksDialog(DraggableDialog):
def update_winetricks(self):
"""Update the winetricks script."""
if not self.downloader.has_internet():
logger.warning("No internet connection, skipping winetricks update")
return
url = "https://raw.githubusercontent.com/Winetricks/winetricks/master/src/winetricks"
temp_path = os.path.join(self.tmp_path, "winetricks_temp")
try:
self.downloader.download(url, temp_path)
if not self.downloader.download(url, temp_path):
logger.warning("Failed to download external winetricks version")
if os.path.exists(temp_path):
os.remove(temp_path)
return
with open(temp_path) as f:
ext_content = f.read()
ext_ver_match = re.search(r'WINETRICKS_VERSION\s*=\s*[\'"]?([^\'"\s]+)', ext_content)
@@ -284,9 +284,9 @@ class WinetricksDialog(DraggableDialog):
button_layout = QHBoxLayout()
button_layout.setSpacing(10)
self.cancel_button = AutoSizeButton(_("Cancel"), icon=theme_manager.get_icon("cancel"))
self.force_button = AutoSizeButton(_("Force Install"), icon=theme_manager.get_icon("apply"))
self.install_button = AutoSizeButton(_("Install"), icon=theme_manager.get_icon("apply"))
self.cancel_button = AutoSizeButton(_("Cancel"), icon=theme_manager.get_icon("cancel", as_path=True))
self.force_button = AutoSizeButton(_("Force Install"), icon=theme_manager.get_icon("apply", as_path=True))
self.install_button = AutoSizeButton(_("Install"), icon=theme_manager.get_icon("apply", as_path=True))
self.cancel_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.force_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.install_button.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
+120 -43
View File
@@ -5,6 +5,7 @@ import stat
import subprocess
import tempfile
import shlex
from typing import BinaryIO
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
@@ -12,6 +13,14 @@ logger = get_logger(__name__)
SYNC_HEADER = b'\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00'
SYNC_HEADER_MDF = b'\x80\xc0\x80\x80\x80\x80\x80\xc0\x80\x80\x80\x80'
ISO_9660_SIG = b'\x01\x43\x44\x30\x30\x31\x01\x00'
DISC_BLOCK_SIZES = (2048, 2336, 2352, 2368, 2448)
SVCD_SUB_HEADERS = (
b"\x00\x00\x08\x00\x00\x00\x08\x00",
b"\x00\x00\x09\x00\x00\x00\x09\x00",
b"\x00\x00\x88\x00\x00\x00\x88\x00",
b"\x00\x00\x89\x00\x00\x00\x89\x00",
)
UDF_SIGNATURES = (b"BEA01", b"BOOT2", b"CD001", b"CDW02", b"NSR02", b"NSR03", b"TEA01")
class DiscImageManager:
@@ -52,58 +61,126 @@ class DiscImageManager:
logger.error("Failed to read ISO 9660 signature for %s: %s", file_path, e)
return False
def _write_iso_from_mdf(self, mdf_path: str, iso_path: str) -> None:
"""Convert MDF to ISO using logic from test.py or legacy fallback."""
with open(mdf_path, "rb") as source:
source.seek(0)
h0 = source.read(12)
source.seek(2352)
h2352 = source.read(12)
def _is_svcd_sub_header(self, header: bytes) -> bool:
"""Return True if header matches known SVCD subheader bytes."""
return header[:8] in SVCD_SUB_HEADERS
if h0 == SYNC_HEADER:
if h2352 == SYNC_HEADER_MDF:
sector_size = 2448
elif h2352 == SYNC_HEADER:
sector_size = 2352
def _calculate_disc_layout(self, source: BinaryIO) -> tuple[int, int]:
"""Return pregap and block size using the iat detection rules."""
source.seek(0, os.SEEK_END)
image_size = source.tell()
cd_id_start = -1
cd_id_end = 0
header_size = 0
for offset in range(32768, image_size):
source.seek(offset)
header = source.read(12)
if header == SYNC_HEADER:
header_size = self._add_header_size(header_size, 16)
continue
if self._is_svcd_sub_header(header):
header_size = self._add_header_size(header_size, 8)
continue
if header[:5] in UDF_SIGNATURES:
if cd_id_start < 0:
cd_id_start = offset
else:
raise ValueError(f"Unknown SYNC format for {mdf_path}")
cd_id_end = offset
break
source.seek(0, os.SEEK_END)
num_sectors = source.tell() // sector_size
source.seek(0)
with open(iso_path, "wb") as target:
for _ in range(num_sectors):
sector_start = source.tell()
header = source.read(16)
if len(header) < 16:
break
mode = header[15]
data_offset = 24 if mode == 2 else 16
source.seek(sector_start + data_offset)
data = source.read(2048)
if len(data) < 2048:
break
target.write(data)
source.seek(sector_start + sector_size)
return
if cd_id_start < 0 or cd_id_end <= cd_id_start:
return self._detect_sector_layout(source)
# Legacy fallback
block_size = self._calculate_block_size(cd_id_end - cd_id_start)
pregap = cd_id_start - (block_size * 16) - header_size - 1
return max(pregap, 0), block_size
def _add_header_size(self, header_size: int, value: int) -> int:
"""Add a detected header size once, matching iat's mixed header logic."""
if header_size in (value, 24):
return header_size
return header_size + value
def _calculate_block_size(self, block_delta: int) -> int:
"""Return closest iat-supported block size for descriptor spacing."""
for block_size in DISC_BLOCK_SIZES[:-1]:
if block_delta % block_size == 0:
return block_size
return DISC_BLOCK_SIZES[-1]
def _detect_sector_layout(self, source: BinaryIO) -> tuple[int, int]:
"""Fallback sector layout detection for images without two descriptors."""
source.seek(0)
h0 = source.read(12)
source.seek(2352)
h2352 = source.read(12)
if h0 == SYNC_HEADER and h2352 == SYNC_HEADER_MDF:
return 0, 2448
if h0 == SYNC_HEADER:
return 0, 2352
return 0, 2352
def _write_sync_sector_data(self, target: BinaryIO, sector: bytes) -> None:
"""Write ISO user data from a sector with a sync header."""
mode = sector[15]
if mode == 0:
target.write(sector[16:2352])
elif mode == 1:
target.write(sector[16:2064])
elif mode == 2:
self._write_mode_two_sector_data(target, sector)
else:
raise ValueError(f"Unknown MDF sector mode {mode}")
def _write_mode_two_sector_data(self, target: BinaryIO, sector: bytes) -> None:
"""Write ISO user data from a Mode 2 sector."""
sub_header = sector[16:24]
if sub_header[:4] != sub_header[4:8]:
target.write(sector[16:2352])
return
if sub_header[2] & 0x20:
target.write(sector[24:2348])
return
target.write(sector[24:2072])
def _write_headerless_sector_data(self, target: BinaryIO, sector: bytes) -> bool:
"""Write ISO user data from a 2336-byte headerless sector."""
sub_header = sector[:8]
if sub_header[:4] != sub_header[4:8]:
return False
if self._is_svcd_sub_header(sub_header):
target.write(sector[8:2332])
else:
target.write(sector[8:2056])
return True
def _write_iso_from_mdf(self, mdf_path: str, iso_path: str) -> None:
"""Convert MDF to ISO using iat-compatible sector extraction."""
with open(mdf_path, "rb") as source, open(iso_path, "wb") as target:
sector_index = 0
while True:
sector = source.read(2352)
pregap, block_size = self._calculate_disc_layout(source)
image_size = os.path.getsize(mdf_path)
source.seek(pregap)
sector_index = pregap
while sector_index < image_size:
sector = source.read(block_size)
if not sector:
return
if len(sector) != 2352:
if len(sector) != block_size:
raise ValueError(f"Truncated MDF sector at {sector_index}")
mode = sector[15]
if mode == 1:
target.write(sector[16:2064])
elif mode == 2:
target.write(sector[24:2072])
if sector.startswith(SYNC_HEADER):
self._write_sync_sector_data(target, sector)
elif block_size == 2336 and not self._write_headerless_sector_data(target, sector):
sector_index += 1
source.seek(sector_index)
continue
elif block_size == 2048:
target.write(sector)
else:
raise ValueError(f"Unknown MDF sector mode {mode} at {sector_index}")
sector_index += 1
sector_index += 1
source.seek(sector_index)
continue
sector_index += block_size
def _convert_mdf_to_iso(self, mdf_path: str) -> str | None:
"""Convert raw 2352-byte sector MDF to temporary ISO."""
-54
View File
@@ -2,7 +2,6 @@ from PySide6.QtCore import QObject, Signal, QThread
import threading
import os
import requests
import socket
from pathlib import Path
from tqdm import tqdm
from collections.abc import Callable
@@ -65,54 +64,12 @@ class Downloader(QObject):
self._locks = {}
self._active_threads: list[QThread] = []
self._global_lock = threading.Lock()
self._has_internet = None
self.callback_requested.connect(self._run_callback)
def _run_callback(self, callback, result):
if callback:
callback(result)
def has_internet(self, timeout=3):
if self._has_internet is None:
errors = []
# Primary: Yandex
try:
socket.create_connection(("77.88.8.8", 53), timeout=timeout)
except Exception as e:
errors.append(f"Yandex DNS (77.88.8.8): {e}")
try:
socket.create_connection(("77.88.8.1", 53), timeout=timeout)
except Exception as e:
errors.append(f"Yandex DNS (77.88.8.1): {e}")
try:
requests.get("https://ya.ru", timeout=timeout)
except Exception as e:
errors.append(f"ya.ru: {e}")
# Fallback: Google (if Yandex failed)
if errors:
logger.debug("Yandex check failed, trying Google fallback")
try:
socket.create_connection(("8.8.8.8", 53), timeout=timeout)
except Exception as e:
errors.append(f"Google DNS (8.8.8.8): {e}")
try:
socket.create_connection(("8.8.4.4", 53), timeout=timeout)
except Exception as e:
errors.append(f"Google DNS (8.8.4.4): {e}")
try:
requests.get("https://www.google.com", timeout=timeout)
except Exception as e:
errors.append(f"google.com: {e}")
if errors:
logger.warning("Internet unavailable:\n" + "\n".join(errors))
self._has_internet = False
else:
self._has_internet = True
return self._has_internet
def _get_url_lock(self, url):
with self._global_lock:
if url not in self._locks:
@@ -219,9 +176,6 @@ class Downloader(QObject):
return results
def download(self, url, local_path, timeout=5):
if not self.has_internet():
logger.warning(f"No internet, skipping download {url}")
return None
with self._global_lock:
if url in self._last_error:
logger.warning(f"Previous download error for {url}, skipping")
@@ -259,14 +213,6 @@ class Downloader(QObject):
max_workers=None,
on_result: Callable[[str, str | None], None] | None = None,
):
if not self.has_internet():
logger.warning("No internet, skipping parallel download")
results = dict.fromkeys(urls)
if on_result:
for url, result in results.items():
on_result(url, result)
return results
filtered_urls = []
filtered_paths = []
emitted_urls = set()
File diff suppressed because it is too large. Load diff
+8 -8
View File
@@ -89,8 +89,8 @@ class GameCard(QFrame):
self.portproton_api = PortProtonAPI(self.downloader)
self.missing_executable_path = self._get_missing_executable_path()
self.steam_visible = (str(game_source).lower() == "steam" and self.display_filter in ("all", "favorites") and not self.economy_mode)
self.portproton_visible = (str(game_source).lower() == "portproton" and self.display_filter in ("all", "favorites") and not self.economy_mode)
self.steam_visible = (str(game_source).lower() == "steam" and not self.economy_mode)
self.portproton_visible = (str(game_source).lower() == "portproton" and not self.economy_mode)
self.base_extra_margin = 8 if self.list_layout else 20
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -148,7 +148,7 @@ class GameCard(QFrame):
tier_text = "" if self.economy_mode else self.getProtonDBText(protondb_tier)
if tier_text:
icon_filename = self.getProtonDBIconFilename(protondb_tier)
icon = self.theme_manager.get_icon(icon_filename, self.current_theme_name)
icon = self.theme_manager.get_icon(icon_filename, self.current_theme_name, as_path=True)
self.protondbLabel = ClickableLabel(
tier_text,
icon=icon,
@@ -161,7 +161,7 @@ class GameCard(QFrame):
self.protondbLabel = ClickableLabel("", parent=self.coverWidget)
self.protondbLabel.setVisible(False)
steam_icon = self.theme_manager.get_icon("badge_steam")
steam_icon = self.theme_manager.get_icon("badge_steam", as_path=True)
self.steamLabel = ClickableLabel(
"Steam",
icon=steam_icon,
@@ -174,7 +174,7 @@ class GameCard(QFrame):
if self.economy_mode:
self.steamLabel.setVisible(False)
portproton_icon = self.theme_manager.get_icon("badge_portproton")
portproton_icon = self.theme_manager.get_icon("badge_portproton", as_path=True)
self.portprotonLabel = ClickableLabel(
"PortProton",
icon=portproton_icon,
@@ -191,7 +191,7 @@ class GameCard(QFrame):
anticheat_text = "" if self.economy_mode else self.getAntiCheatText(anticheat_status)
if anticheat_text:
icon_filename = self.getAntiCheatIconFilename(anticheat_status)
icon = self.theme_manager.get_icon(icon_filename, self.current_theme_name)
icon = self.theme_manager.get_icon(icon_filename, self.current_theme_name, as_path=True)
self.anticheatLabel = ClickableLabel(
anticheat_text,
icon=icon,
@@ -486,8 +486,8 @@ class GameCard(QFrame):
self.display_filter = display_filter
self.economy_mode = ui_config.get_economy_mode()
self.steam_visible = (str(self.game_source).lower() == "steam" and self.display_filter in ("all", "favorites") and not self.economy_mode)
self.portproton_visible = (str(self.game_source).lower() == "portproton" and self.display_filter in ("all", "favorites") and not self.economy_mode)
self.steam_visible = (str(self.game_source).lower() == "steam" and not self.economy_mode)
self.portproton_visible = (str(self.game_source).lower() == "portproton" and not self.economy_mode)
protondb_visible = bool(self.getProtonDBText(self.protondb_tier)) and not self.economy_mode
anticheat_visible = bool(self.getAntiCheatText(self.anticheat_status)) and not self.economy_mode
+56 -181
View File
@@ -1,11 +1,9 @@
import orjson
import re
from dataclasses import dataclass, field
import time
from dataclasses import dataclass
from typing import Any
from difflib import SequenceMatcher
from threading import Thread
import requests
from bs4 import BeautifulSoup, Tag
from portprotonqt.config import proxy_config
from portprotonqt.time_utils import format_playtime
from portprotonqt.logger import get_logger
@@ -17,66 +15,22 @@ logger = get_logger(__name__)
@dataclass
class GameEntry:
"""Game information from HowLongToBeat."""
game_id: int = -1
game_name: str | None = None
main_story: float | None = None
main_extra: float | None = None
completionist: float | None = None
similarity: float = -1.0
raw_data: dict[str, Any] = field(default_factory=dict)
@dataclass
class SearchConfig:
"""Search configuration."""
api_key: str | None = None
search_url: str | None = None
class APIKeyExtractor:
"""Extract API key and search URL from site scripts."""
@staticmethod
def extract_from_script(script_content: str) -> SearchConfig:
config = SearchConfig()
config.api_key = APIKeyExtractor._extract_api_key(script_content)
config.search_url = APIKeyExtractor._extract_search_url(script_content, config.api_key)
return config
@staticmethod
def _extract_api_key(script_content: str) -> str | None:
user_id_pattern = r'users\s*:\s*{\s*id\s*:\s*"([^"]+)"'
matches = re.findall(user_id_pattern, script_content)
if matches:
return ''.join(matches)
concat_pattern = r'\/api\/\w+\/"(?:\.concat\("[^"]*"\))+'
matches = re.findall(concat_pattern, script_content)
if matches:
parts = str(matches).split('.concat')
cleaned_parts = [re.sub(r'["\(\)\[\]\']', '', part) for part in parts[1:]]
return ''.join(cleaned_parts)
return None
@staticmethod
def _extract_search_url(script_content: str, api_key: str | None) -> str | None:
if not api_key:
return None
pattern = re.compile(
r'fetch\(\s*["\'](\/api\/[^"\']*)["\']'
r'((?:\s*\.concat\(\s*["\']([^"\']*)["\']\s*\))+)'
r'\s*,',
re.DOTALL
)
for match in pattern.finditer(script_content):
endpoint = match.group(1)
concat_calls = match.group(2)
concat_strings = re.findall(r'\.concat\(\s*["\']([^"\']*)["\']\s*\)', concat_calls)
concatenated_str = ''.join(concat_strings)
if concatenated_str == api_key:
return endpoint
return None
token: str
hp_key: str
hp_val: str
class HTTPClient:
"""HTTP client for HowLongToBeat API."""
BASE_URL = 'https://howlongtobeat.com/'
SEARCH_URL = BASE_URL + "api/s/"
AUTH_URL = BASE_URL + "api/bleed/init"
SEARCH_URL = BASE_URL + "api/bleed"
def __init__(self, timeout: int = 60):
self.timeout = timeout
@@ -89,67 +43,55 @@ class HTTPClient:
if proxy_settings:
self.session.proxies.update(proxy_settings)
def get_search_config(self, parse_all_scripts: bool = False) -> SearchConfig | None:
def get_search_config(self) -> SearchConfig | None:
try:
response = self.session.get(self.BASE_URL, timeout=self.timeout)
response = self.session.get(
self.AUTH_URL,
params={"t": int(time.time() * 1000)},
timeout=self.timeout
)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
scripts = soup.find_all('script', src=True)
script_urls = []
for script in scripts:
if isinstance(script, Tag):
src = script.get('src')
if src is not None and isinstance(src, str):
if parse_all_scripts or '_app-' in src:
script_urls.append(src)
for script_url in script_urls:
full_url = self.BASE_URL + script_url
script_response = self.session.get(full_url, timeout=self.timeout)
if script_response.status_code == 200:
config = APIKeyExtractor.extract_from_script(script_response.text)
if config.api_key:
return config
except requests.RequestException:
pass
return None
data = response.json()
except (requests.RequestException, ValueError):
return None
if not data.get("token") or not data.get("hpKey") or not data.get("hpVal"):
return None
return SearchConfig(
token=data["token"],
hp_key=data["hpKey"],
hp_val=data["hpVal"]
)
def search_games(self, game_name: str, page: int = 1, config: SearchConfig | None = None) -> str | None:
if not config:
config = self.get_search_config()
if not config:
config = self.get_search_config(parse_all_scripts=True)
if not config or not config.api_key:
if not config:
return None
search_url = self.SEARCH_URL
if config.search_url:
search_url = self.BASE_URL + config.search_url.lstrip('/')
payload = self._build_search_payload(game_name, page, config)
headers = {
'content-type': 'application/json',
'accept': '*/*'
}
try:
response = self.session.post(
search_url + config.api_key,
headers=headers,
data=orjson.dumps(payload),
timeout=self.timeout
)
for retry in range(2):
payload = self._build_search_payload(game_name, page, config)
headers = {
'content-type': 'application/json',
'accept': '*/*',
'x-auth-token': config.token,
'x-hp-key': config.hp_key,
'x-hp-val': config.hp_val
}
try:
response = self.session.post(
self.SEARCH_URL,
headers=headers,
data=orjson.dumps(payload),
timeout=self.timeout
)
except requests.RequestException:
return None
if response.status_code == 200:
return response.text
except requests.RequestException:
pass
try:
response = self.session.post(
search_url,
headers=headers,
data=orjson.dumps(payload),
timeout=self.timeout
)
if response.status_code == 200:
return response.text
except requests.RequestException:
pass
if response.status_code != 403 or retry:
return None
config = self.get_search_config()
if not config:
return None
return None
def _build_search_payload(self, game_name: str, page: int, config: SearchConfig) -> dict[str, Any]:
@@ -171,8 +113,7 @@ class HTTPClient:
'genre': "",
"difficulty": ""
},
'rangeYear': {'max': "", 'min': ""},
'modifier': "" # Hardcoded to empty string for SearchModifiers.NONE
'rangeYear': {'max': "", 'min': ""}
},
'users': {'sortCategory': "postcount"},
'lists': {'sortCategory': "follows"},
@@ -181,42 +122,26 @@ class HTTPClient:
'randomizer': 0
},
'useCache': True,
'fields': ["game_id", "game_name", "comp_main", "comp_plus", "comp_100"] # Request only needed fields
'fields': ["comp_main", "comp_plus", "comp_100"]
}
if config.api_key:
payload['searchOptions']['users']['id'] = config.api_key
payload[config.hp_key] = config.hp_val
return payload
class ResultParser:
"""Search results parser."""
def __init__(self, search_query: str, minimum_similarity: float = 0.4, case_sensitive: bool = True):
self.search_query = search_query
self.minimum_similarity = minimum_similarity
self.case_sensitive = case_sensitive
self.search_numbers = self._extract_numbers(search_query)
def parse_results(self, json_response: str, target_game_id: int | None = None) -> list[GameEntry]:
def parse_results(self, json_response: str) -> list[GameEntry]:
try:
data = orjson.loads(json_response)
games = []
# Only process the first result
if data.get("data"):
game_data = data["data"][0]
game = self._parse_game_entry(game_data)
if target_game_id is not None:
if game.game_id == target_game_id:
games.append(game)
elif self.minimum_similarity == 0.0 or game.similarity >= self.minimum_similarity:
games.append(game)
games.append(self._parse_game_entry(game_data))
return games
except (orjson.JSONDecodeError, KeyError, IndexError):
return []
def _parse_game_entry(self, game_data: dict[str, Any]) -> GameEntry:
game = GameEntry()
game.game_id = game_data.get("game_id", -1)
game.game_name = game_data.get("game_name")
game.raw_data = game_data
time_fields = [
("comp_main", "main_story"),
("comp_plus", "main_extra"),
@@ -228,35 +153,8 @@ class ResultParser:
time_seconds = game_data[json_field]
time_hours = None if all_zero else round(time_seconds / 3600, 2)
setattr(game, attr_name, time_hours)
game.similarity = self._calculate_similarity(game)
return game
def _calculate_similarity(self, game: GameEntry) -> float:
return self._compare_strings(self.search_query, game.game_name)
def _compare_strings(self, a: str | None, b: str | None) -> float:
if not a or not b:
return 0.0
if self.case_sensitive:
similarity = SequenceMatcher(None, a, b).ratio()
else:
similarity = SequenceMatcher(None, a.lower(), b.lower()).ratio()
if self.search_numbers and not self._contains_numbers(b, self.search_numbers):
similarity -= 0.1
return max(0.0, similarity)
@staticmethod
def _extract_numbers(text: str) -> list[str]:
return [word for word in text.split() if word.isdigit()]
@staticmethod
def _contains_numbers(text: str, numbers: list[str]) -> bool:
if not numbers:
return True
cleaned_text = re.sub(r'([^\s\w]|_)+', '', text)
text_numbers = [word for word in cleaned_text.split() if word.isdigit()]
return any(num in text_numbers for num in numbers)
class HowLongToBeat(QObject):
"""Main class for HowLongToBeat API."""
@@ -273,15 +171,13 @@ class HowLongToBeat(QObject):
return self.cache_manager.load_text(f"hltb_{game_name}")
def _save_to_cache(self, game_name: str, json_response: str):
"""Save data to cache, storing only first game and required fields."""
"""Save data to cache, storing only first game times."""
try:
data = orjson.loads(json_response)
if data.get("data"):
first_game = data["data"][0]
simplified_data = {
"data": [{
"game_id": first_game.get("game_id", -1),
"game_name": first_game.get("game_name"),
"comp_main": first_game.get("comp_main", 0),
"comp_plus": first_game.get("comp_plus", 0),
"comp_100": first_game.get("comp_100", 0)
@@ -298,25 +194,8 @@ class HowLongToBeat(QObject):
cached_response = self._load_from_cache(game_name)
if cached_response:
try:
cached_data = orjson.loads(cached_response)
full_json = {
"data": [
{
"game_id": game["game_id"],
"game_name": game["game_name"],
"comp_main": game["comp_main"],
"comp_plus": game["comp_plus"],
"comp_100": game["comp_100"]
}
for game in cached_data.get("data", [])
]
}
parser = ResultParser(
game_name,
self.minimum_similarity,
case_sensitive
)
return parser.parse_results(orjson.dumps(full_json).decode('utf-8'))
parser = ResultParser()
return parser.parse_results(cached_response)
except orjson.JSONDecodeError:
pass
# If not in cache, make request
@@ -325,11 +204,7 @@ class HowLongToBeat(QObject):
return None
# Save only first game to cache
self._save_to_cache(game_name, json_response)
parser = ResultParser(
game_name,
self.minimum_similarity,
case_sensitive
)
parser = ResultParser()
return parser.parse_results(json_response)
def format_game_time(self, game_entry: GameEntry, time_field: str = "main_story") -> str | None:
+30
View File
@@ -12,6 +12,36 @@ RT_ICON = 3
RT_GROUP_ICON = 14
THUMBNAIL_SIZE = 128
def generate_thumbnail(inputfile: str, outfile: str, size: int = 128, force_resize: bool = True) -> bool:
"""
Generates a thumbnail for an .exe file.
inputfile: the input file path
outfile: output filename
size: determines the thumbnail output size
"""
logger.debug("Starting thumbnail generation: %s → %s, size=%s, force=%s", inputfile, outfile, size, force_resize)
try:
extractor = IconExtractor(inputfile)
data = extractor.get_icon()
if data is None:
return False
im = Image.open(data)
if force_resize or im.size != (size, size):
logger.debug("Resizing icon to %sx%s", size, size)
im = im.resize((size, size), Image.Resampling.LANCZOS)
im.save(outfile, "PNG")
logger.info("Thumbnail successfully saved to %s", outfile)
return True
except Exception as e:
logger.error("Error generating thumbnail: %s", e)
return False
class IconExtractorError(Exception):
"""Base exception for icon extraction errors."""
-85
View File
@@ -1,85 +0,0 @@
import asyncio
import contextlib
import os
import sys
from collections.abc import Awaitable
from typing import Any
from portprotonqt.logger import get_logger
from portprotonqt.localization import _
logger = get_logger(__name__)
BUS_NAME = "org.freedesktop.ScreenSaver"
BUS_PATH = "/org/freedesktop/ScreenSaver"
APPLICATION_NAME = "ru.linux_gaming.PortProtonQt"
INHIBIT_REASON = _("Launched")
DBUS_TIMEOUT = 10
def _get_inhibit_reason() -> str:
game_name = os.getenv("PW_INHIBIT_NAME", "").strip()
if not game_name:
game_name = os.getenv("PORTPROTON_NAME", "").strip()
if not game_name:
return INHIBIT_REASON
return f"{INHIBIT_REASON} {game_name}"
async def _run_command(command: list[str]) -> int:
process = await asyncio.create_subprocess_exec(*command)
return await process.wait()
async def _dbus_call(awaitable: Awaitable[Any]) -> Any:
return await asyncio.wait_for(awaitable, timeout=DBUS_TIMEOUT)
async def _request_inhibit() -> tuple[Any, int, Any]:
import dbus_fast
import dbus_fast.aio
bus = await _dbus_call(dbus_fast.aio.MessageBus().connect())
introspection = await _dbus_call(bus.introspect(BUS_NAME, BUS_PATH))
proxy = bus.get_proxy_object(BUS_NAME, BUS_PATH, introspection)
iface = proxy.get_interface(BUS_NAME)
cookie = await _dbus_call(iface.call_inhibit(APPLICATION_NAME, _get_inhibit_reason()))
return iface, cookie, dbus_fast
async def _release_inhibit(iface: Any, cookie: int, dbus_fast: Any) -> None:
with contextlib.suppress(dbus_fast.DBusError, asyncio.TimeoutError):
await _dbus_call(iface.call_un_inhibit(cookie))
async def _inhibit_and_run(command: list[str]) -> int:
try:
iface, cookie, dbus_fast = await _request_inhibit()
except (ImportError, TimeoutError) as err:
logger.warning("Screensaver inhibit failed: %s", err)
return await _run_command(command)
except Exception as err:
logger.warning("Screensaver inhibit failed: %s", err)
return await _run_command(command)
try:
return await _run_command(command)
finally:
await _release_inhibit(iface, cookie, dbus_fast)
async def _main(command: list[str]) -> int:
if not command:
return 2
return await _inhibit_and_run(command)
def main() -> int:
return asyncio.run(_main(sys.argv[1:]))
if __name__ == "__main__":
raise SystemExit(main())
+7 -12
View File
@@ -11,6 +11,7 @@ from portprotonqt.config import ui_config
from portprotonqt.theme_manager import ThemeManager
from portprotonqt.downloader import Downloader
from portprotonqt.logger import get_logger
from portprotonqt.qt_utils import get_device_pixel_ratio
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from queue import Queue
@@ -20,22 +21,12 @@ downloader = Downloader()
logger = get_logger(__name__)
COVER_IMAGE_EXTENSIONS = (".png", ".apng", ".jpg", ".jpeg", ".gif", ".webp", ".jxl")
DEFAULT_ANIMATION_DELAY_MS = 100
ANIMATED_COVER_MIN_DELAY_MS = 100
# Global queue and thread pool for image loading
image_load_queue = Queue()
image_executor = ThreadPoolExecutor(max_workers=4)
queue_lock = threading.Lock()
def get_device_pixel_ratio() -> float:
"""
Retrieves the device pixel ratio from QApplication, with a fallback of 1.0 if not available.
"""
app = QApplication.instance()
return app.devicePixelRatio() if isinstance(app, QApplication) else 1.0
def is_animated_cover(path: str) -> bool:
"""Return True when path points to an animated cover image."""
ext = os.path.splitext(path)[1].lower()
@@ -47,6 +38,11 @@ def is_animated_cover(path: str) -> bool:
return reader.supportsAnimation() and reader.imageCount() != 1
def _is_png_cover(path: str) -> bool:
reader = QImageReader(path)
return bytes(reader.format().data()).decode("ascii", "ignore").lower() == "png"
def _set_cover_mask(label: QLabel, width: int, height: int, radius: int) -> None:
if radius <= 0:
label.clearMask()
@@ -174,7 +170,6 @@ class _PillowAnimatedCover(QObject):
def _convert_frame(self, frame: Image.Image) -> tuple[QPixmap, int]:
duration = int(frame.info.get("duration", DEFAULT_ANIMATION_DELAY_MS))
duration = max(duration, ANIMATED_COVER_MIN_DELAY_MS)
image = frame.convert("RGBA").resize(
(max(self.width, 1), max(self.height, 1)),
Image.Resampling.BILINEAR,
@@ -224,7 +219,7 @@ def set_animated_cover(label: QLabel, path: str, width: int, height: int, radius
return False
if not QFile.exists(path):
return False
if ext in (".png", ".apng"):
if ext in (".png", ".apng") and _is_png_cover(path):
_set_cover_mask(label, width, height, radius)
animation = _PillowAnimatedCover(label, path, width, height, radius)
if not animation.start():
+35
View File
@@ -1375,6 +1375,9 @@ class InputManager(QObject):
if isinstance(focused, QCheckBox) and focused.isEnabled():
focused.setChecked(not focused.isChecked())
return
if isinstance(focused, QPushButton) and focused.isEnabled():
focused.click()
return
combo_from_focus = None
if isinstance(focused, QComboBox):
combo_from_focus = focused
@@ -1602,6 +1605,8 @@ class InputManager(QObject):
self._focus_settings_advanced_value_widget(table, new_row)
elif code == PAD_DPAD_X: # Left/Right
if self._move_settings_inline_button_focus(table, value):
return
current_col = table.currentColumn()
if value < 0: # Left
if current_col > 0:
@@ -1673,8 +1678,38 @@ class InputManager(QObject):
if isinstance(cell_widget, QLineEdit):
cell_widget.setFocus(Qt.FocusReason.OtherFocusReason)
return
if (
cell_widget is not None
and cell_widget.property("ppqt_run_after_exe_widget")
):
line_edit = cell_widget.findChild(QLineEdit)
if line_edit and line_edit.isEnabled():
line_edit.setFocus(Qt.FocusReason.OtherFocusReason)
return
table.setFocus(Qt.FocusReason.OtherFocusReason)
def _move_settings_inline_button_focus(self, table: QTableWidget, value: int) -> bool:
"""Move focus between inline line edit and button in settings cell."""
if not self.settings_dialog or table != self.settings_dialog.advanced_table:
return False
if table.currentColumn() != 1:
return False
cell_widget = table.cellWidget(table.currentRow(), 1)
if cell_widget is None or not cell_widget.property("ppqt_run_after_exe_widget"):
return False
line_edit = cell_widget.findChild(QLineEdit)
button = cell_widget.findChild(QPushButton)
focused = QApplication.focusWidget()
if value > 0 and focused == line_edit and button and button.isEnabled():
button.setFocus(Qt.FocusReason.OtherFocusReason)
return True
if value < 0 and focused == button and line_edit and line_edit.isEnabled():
line_edit.setFocus(Qt.FocusReason.OtherFocusReason)
return True
return False
def _focus_first_row_in_current_settings_table(self):
table = self._get_current_settings_table()
if table and table.rowCount() > 0:
@@ -83,6 +83,12 @@ msgid ""
"cannot be undone."
msgstr ""
msgid "Yes"
msgstr ""
msgid "No"
msgstr ""
#, python-brace-format
msgid "Failed to delete folder: {error}"
msgstr ""
@@ -105,10 +111,10 @@ msgstr ""
msgid "Add to Menu"
msgstr ""
msgid "Edit Shortcut"
msgid "Open Game Folder"
msgstr ""
msgid "Open Game Folder"
msgid "Edit Shortcut"
msgstr ""
msgid "Remove from Steam"
@@ -142,12 +148,6 @@ msgid ""
".desktop file and custom data."
msgstr ""
msgid "Yes"
msgstr ""
msgid "No"
msgstr ""
#, python-brace-format
msgid "Failed to delete .desktop file: {error}"
msgstr ""
@@ -290,9 +290,6 @@ msgstr ""
msgid "Pending"
msgstr ""
msgid "Launched"
msgstr ""
msgid "Unknown Game"
msgstr ""
@@ -516,6 +513,9 @@ msgstr ""
msgid "Interface Settings"
msgstr ""
msgid "Tray Menu Type:"
msgstr ""
msgid "Launch Application in Fullscreen"
msgstr ""
@@ -531,6 +531,9 @@ msgstr ""
msgid "Hide Auto-Install Tab"
msgstr ""
msgid "Disable runtime download"
msgstr ""
msgid "Add to Steam compatibility tools"
msgstr ""
@@ -540,9 +543,15 @@ msgstr ""
msgid "Economy mode"
msgstr ""
msgid "Download mirror:"
msgstr ""
msgid "Force system DPI for Wine"
msgstr ""
msgid "Download Settings"
msgstr ""
msgid "Gamepad Settings"
msgstr ""
@@ -798,9 +807,6 @@ msgstr ""
msgid "Use container launch mode (recommended default)"
msgstr ""
msgid "System WINE"
msgstr ""
msgid "Wine Version"
msgstr ""
@@ -944,13 +950,16 @@ msgstr ""
msgid "Exit"
msgstr ""
msgid "Tabs"
msgstr ""
msgid "Recent Games"
msgstr ""
msgid "No favorites"
msgid "No recent games"
msgstr ""
msgid "No recent games"
msgid "No favorites"
msgstr ""
#, python-brace-format
@@ -1100,6 +1109,9 @@ msgstr ""
msgid "Select"
msgstr ""
msgid "Home"
msgstr ""
msgid "Path: "
msgstr ""
@@ -1237,6 +1249,9 @@ msgstr ""
msgid "Download or extraction has been cancelled."
msgstr ""
msgid "System WINE"
msgstr ""
msgid "Exe Settings"
msgstr ""
@@ -1261,6 +1276,9 @@ msgstr ""
msgid "Open PPDB"
msgstr ""
msgid "Clear PPDB"
msgstr ""
msgid "Executable path is not available."
msgstr ""
@@ -1270,6 +1288,22 @@ msgstr ""
msgid "Failed to open PPDB file:\n"
msgstr ""
msgid "Information"
msgstr ""
msgid "Confirm PPDB Clear"
msgstr ""
msgid ""
"Are you sure you want to clear settings? This action cannot be undone."
msgstr ""
msgid "Failed to remove PPDB file:\n"
msgstr ""
msgid "PPDB settings cleared."
msgstr ""
msgid "disabled"
msgstr ""
@@ -1510,9 +1544,6 @@ msgstr ""
msgid "Disable Gamescope"
msgstr ""
msgid "Information"
msgstr ""
msgid "Custom preset is empty. Save one first."
msgstr ""
@@ -1873,9 +1904,6 @@ msgstr ""
msgid "Use system config"
msgstr ""
msgid "PortProton default"
msgstr ""
msgid "FPS only"
msgstr ""
@@ -1950,6 +1978,9 @@ msgstr ""
msgid "Components installed successfully."
msgstr ""
msgid "Launched"
msgstr ""
msgid "Bluetooth PIN code"
msgstr ""
@@ -2104,4 +2135,3 @@ msgstr ""
msgid "Not selected"
msgstr ""
@@ -86,6 +86,12 @@ msgstr ""
"¿Estás seguro de que quieres eliminar la carpeta «{folder_name}»? Esta "
"acción no se puede deshacer."
msgid "Yes"
msgstr ""
msgid "No"
msgstr ""
#, python-brace-format
msgid "Failed to delete folder: {error}"
msgstr "No se ha podido eliminar la carpeta: {error}"
@@ -102,18 +108,18 @@ msgstr "Eliminar del escritorio"
msgid "Add to Desktop"
msgstr "Añadir al escritorio"
msgid "Edit Shortcut"
msgstr "Editar acceso directo"
msgid "Open Game Folder"
msgstr "Abrir la carpeta del juego"
msgid "Remove from Menu"
msgstr "Eliminar del menú"
msgid "Add to Menu"
msgstr "Añadir al menú"
msgid "Open Game Folder"
msgstr "Abrir la carpeta del juego"
msgid "Edit Shortcut"
msgstr "Editar acceso directo"
msgid "Remove from Steam"
msgstr "Eliminar de Steam"
@@ -145,12 +151,6 @@ msgid ""
"file and custom data."
msgstr ""
msgid "Yes"
msgstr ""
msgid "No"
msgstr ""
#, python-brace-format
msgid "Failed to delete .desktop file: {error}"
msgstr ""
@@ -293,9 +293,6 @@ msgstr ""
msgid "Pending"
msgstr ""
msgid "Launched"
msgstr ""
msgid "Unknown Game"
msgstr ""
@@ -519,6 +516,9 @@ msgstr ""
msgid "Interface Settings"
msgstr ""
msgid "Tray Menu Type:"
msgstr ""
msgid "Launch Application in Fullscreen"
msgstr ""
@@ -534,6 +534,9 @@ msgstr ""
msgid "Hide Auto-Install Tab"
msgstr ""
msgid "Disable runtime download"
msgstr ""
msgid "Add to Steam compatibility tools"
msgstr ""
@@ -543,9 +546,15 @@ msgstr ""
msgid "Economy mode"
msgstr ""
msgid "Download mirror:"
msgstr ""
msgid "Force system DPI for Wine"
msgstr ""
msgid "Download Settings"
msgstr ""
msgid "Gamepad Settings"
msgstr ""
@@ -801,9 +810,6 @@ msgstr ""
msgid "Use container launch mode (recommended default)"
msgstr ""
msgid "System WINE"
msgstr ""
msgid "Wine Version"
msgstr ""
@@ -944,13 +950,16 @@ msgstr ""
msgid "Exit"
msgstr ""
msgid "Tabs"
msgstr ""
msgid "Recent Games"
msgstr ""
msgid "No favorites"
msgid "No recent games"
msgstr ""
msgid "No recent games"
msgid "No favorites"
msgstr ""
#, python-brace-format
@@ -1100,6 +1109,9 @@ msgstr ""
msgid "Select"
msgstr ""
msgid "Home"
msgstr ""
msgid "Path: "
msgstr ""
@@ -1237,6 +1249,9 @@ msgstr ""
msgid "Download or extraction has been cancelled."
msgstr ""
msgid "System WINE"
msgstr ""
msgid "Exe Settings"
msgstr ""
@@ -1261,6 +1276,9 @@ msgstr ""
msgid "Open PPDB"
msgstr ""
msgid "Clear PPDB"
msgstr ""
msgid "Executable path is not available."
msgstr ""
@@ -1270,6 +1288,27 @@ msgstr ""
msgid "Failed to open PPDB file:\n"
msgstr ""
msgid "Information"
msgstr ""
#, fuzzy
msgid "Confirm PPDB Clear"
msgstr "Confirmar eliminación"
#, fuzzy, python-brace-format
msgid ""
"Are you sure you want to clear settings? This action cannot be undone."
msgstr ""
"¿Estás seguro de que quieres eliminar la carpeta «{folder_name}»? Esta "
"acción no se puede deshacer."
#, fuzzy, python-brace-format
msgid "Failed to remove PPDB file:\n"
msgstr "No se pudo cambiar el nombre de la carpeta: {error}"
msgid "PPDB settings cleared."
msgstr ""
msgid "disabled"
msgstr ""
@@ -1509,9 +1548,6 @@ msgstr ""
msgid "Disable Gamescope"
msgstr ""
msgid "Information"
msgstr ""
msgid "Custom preset is empty. Save one first."
msgstr ""
@@ -1872,9 +1908,6 @@ msgstr ""
msgid "Use system config"
msgstr ""
msgid "PortProton default"
msgstr ""
msgid "FPS only"
msgstr ""
@@ -1949,6 +1982,9 @@ msgstr ""
msgid "Components installed successfully."
msgstr ""
msgid "Launched"
msgstr ""
msgid "Bluetooth PIN code"
msgstr ""
+53 -23
View File
@@ -9,7 +9,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PortProtonQt 0.1.1\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2026-05-14 10:23+0500\n"
"POT-Creation-Date: 2026-05-23 09:04+0500\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
@@ -81,6 +81,12 @@ msgid ""
"cannot be undone."
msgstr ""
msgid "Yes"
msgstr ""
msgid "No"
msgstr ""
#, python-brace-format
msgid "Failed to delete folder: {error}"
msgstr ""
@@ -103,10 +109,10 @@ msgstr ""
msgid "Add to Menu"
msgstr ""
msgid "Edit Shortcut"
msgid "Open Game Folder"
msgstr ""
msgid "Open Game Folder"
msgid "Edit Shortcut"
msgstr ""
msgid "Remove from Steam"
@@ -140,12 +146,6 @@ msgid ""
".desktop file and custom data."
msgstr ""
msgid "Yes"
msgstr ""
msgid "No"
msgstr ""
#, python-brace-format
msgid "Failed to delete .desktop file: {error}"
msgstr ""
@@ -288,9 +288,6 @@ msgstr ""
msgid "Pending"
msgstr ""
msgid "Launched"
msgstr ""
msgid "Unknown Game"
msgstr ""
@@ -514,6 +511,9 @@ msgstr ""
msgid "Interface Settings"
msgstr ""
msgid "Tray Menu Type:"
msgstr ""
msgid "Launch Application in Fullscreen"
msgstr ""
@@ -529,6 +529,9 @@ msgstr ""
msgid "Hide Auto-Install Tab"
msgstr ""
msgid "Disable runtime download"
msgstr ""
msgid "Add to Steam compatibility tools"
msgstr ""
@@ -538,9 +541,15 @@ msgstr ""
msgid "Economy mode"
msgstr ""
msgid "Download mirror:"
msgstr ""
msgid "Force system DPI for Wine"
msgstr ""
msgid "Download Settings"
msgstr ""
msgid "Gamepad Settings"
msgstr ""
@@ -796,9 +805,6 @@ msgstr ""
msgid "Use container launch mode (recommended default)"
msgstr ""
msgid "System WINE"
msgstr ""
msgid "Wine Version"
msgstr ""
@@ -942,13 +948,16 @@ msgstr ""
msgid "Exit"
msgstr ""
msgid "Tabs"
msgstr ""
msgid "Recent Games"
msgstr ""
msgid "No favorites"
msgid "No recent games"
msgstr ""
msgid "No recent games"
msgid "No favorites"
msgstr ""
#, python-brace-format
@@ -1098,6 +1107,9 @@ msgstr ""
msgid "Select"
msgstr ""
msgid "Home"
msgstr ""
msgid "Path: "
msgstr ""
@@ -1235,6 +1247,9 @@ msgstr ""
msgid "Download or extraction has been cancelled."
msgstr ""
msgid "System WINE"
msgstr ""
msgid "Exe Settings"
msgstr ""
@@ -1259,6 +1274,9 @@ msgstr ""
msgid "Open PPDB"
msgstr ""
msgid "Clear PPDB"
msgstr ""
msgid "Executable path is not available."
msgstr ""
@@ -1268,6 +1286,21 @@ msgstr ""
msgid "Failed to open PPDB file:\n"
msgstr ""
msgid "Information"
msgstr ""
msgid "Confirm PPDB Clear"
msgstr ""
msgid "Are you sure you want to clear settings? This action cannot be undone."
msgstr ""
msgid "Failed to remove PPDB file:\n"
msgstr ""
msgid "PPDB settings cleared."
msgstr ""
msgid "disabled"
msgstr ""
@@ -1508,9 +1541,6 @@ msgstr ""
msgid "Disable Gamescope"
msgstr ""
msgid "Information"
msgstr ""
msgid "Custom preset is empty. Save one first."
msgstr ""
@@ -1871,9 +1901,6 @@ msgstr ""
msgid "Use system config"
msgstr ""
msgid "PortProton default"
msgstr ""
msgid "FPS only"
msgstr ""
@@ -1948,6 +1975,9 @@ msgstr ""
msgid "Components installed successfully."
msgstr ""
msgid "Launched"
msgstr ""
msgid "Bluetooth PIN code"
msgstr ""
@@ -82,6 +82,12 @@ msgid ""
"cannot be undone."
msgstr ""
msgid "Yes"
msgstr ""
msgid "No"
msgstr ""
#, python-brace-format
msgid "Failed to delete folder: {error}"
msgstr ""
@@ -104,10 +110,10 @@ msgstr ""
msgid "Add to Menu"
msgstr ""
msgid "Edit Shortcut"
msgid "Open Game Folder"
msgstr ""
msgid "Open Game Folder"
msgid "Edit Shortcut"
msgstr ""
msgid "Remove from Steam"
@@ -141,12 +147,6 @@ msgid ""
".desktop file and custom data."
msgstr ""
msgid "Yes"
msgstr ""
msgid "No"
msgstr ""
#, python-brace-format
msgid "Failed to delete .desktop file: {error}"
msgstr ""
@@ -289,9 +289,6 @@ msgstr ""
msgid "Pending"
msgstr ""
msgid "Launched"
msgstr ""
msgid "Unknown Game"
msgstr ""
@@ -515,6 +512,9 @@ msgstr ""
msgid "Interface Settings"
msgstr ""
msgid "Tray Menu Type:"
msgstr ""
msgid "Launch Application in Fullscreen"
msgstr ""
@@ -530,6 +530,9 @@ msgstr ""
msgid "Hide Auto-Install Tab"
msgstr ""
msgid "Disable runtime download"
msgstr ""
msgid "Add to Steam compatibility tools"
msgstr ""
@@ -539,9 +542,15 @@ msgstr ""
msgid "Economy mode"
msgstr ""
msgid "Download mirror:"
msgstr ""
msgid "Force system DPI for Wine"
msgstr ""
msgid "Download Settings"
msgstr ""
msgid "Gamepad Settings"
msgstr ""
@@ -797,9 +806,6 @@ msgstr ""
msgid "Use container launch mode (recommended default)"
msgstr ""
msgid "System WINE"
msgstr ""
msgid "Wine Version"
msgstr ""
@@ -943,13 +949,16 @@ msgstr ""
msgid "Exit"
msgstr ""
msgid "Tabs"
msgstr ""
msgid "Recent Games"
msgstr ""
msgid "No favorites"
msgid "No recent games"
msgstr ""
msgid "No recent games"
msgid "No favorites"
msgstr ""
#, python-brace-format
@@ -1099,6 +1108,9 @@ msgstr ""
msgid "Select"
msgstr ""
msgid "Home"
msgstr ""
msgid "Path: "
msgstr ""
@@ -1236,6 +1248,9 @@ msgstr ""
msgid "Download or extraction has been cancelled."
msgstr ""
msgid "System WINE"
msgstr ""
msgid "Exe Settings"
msgstr ""
@@ -1260,6 +1275,9 @@ msgstr ""
msgid "Open PPDB"
msgstr ""
msgid "Clear PPDB"
msgstr ""
msgid "Executable path is not available."
msgstr ""
@@ -1269,6 +1287,22 @@ msgstr ""
msgid "Failed to open PPDB file:\n"
msgstr ""
msgid "Information"
msgstr ""
msgid "Confirm PPDB Clear"
msgstr ""
msgid ""
"Are you sure you want to clear settings? This action cannot be undone."
msgstr ""
msgid "Failed to remove PPDB file:\n"
msgstr ""
msgid "PPDB settings cleared."
msgstr ""
msgid "disabled"
msgstr ""
@@ -1509,9 +1543,6 @@ msgstr ""
msgid "Disable Gamescope"
msgstr ""
msgid "Information"
msgstr ""
msgid "Custom preset is empty. Save one first."
msgstr ""
@@ -1872,9 +1903,6 @@ msgstr ""
msgid "Use system config"
msgstr ""
msgid "PortProton default"
msgstr ""
msgid "FPS only"
msgstr ""
@@ -1949,6 +1977,9 @@ msgstr ""
msgid "Components installed successfully."
msgstr ""
msgid "Launched"
msgstr ""
msgid "Bluetooth PIN code"
msgstr ""
@@ -2103,4 +2134,3 @@ msgstr ""
msgid "Not selected"
msgstr ""
@@ -9,7 +9,7 @@ msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2026-03-22 13:50+0500\n"
"PO-Revision-Date: 2026-05-14 05:48+0000\n"
"PO-Revision-Date: 2026-05-22 18:55+0000\n"
"Last-Translator: Boria138 <boria138@noreply.codeberg.org>\n"
"Language-Team: Russian <https://translate.codeberg.org/projects/portprotonqt/"
"portprotonqt/ru/>\n"
@@ -19,7 +19,7 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && "
"n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
"X-Generator: Weblate 5.17.1\n"
"X-Generator: Weblate 2026.5\n"
"Generated-By: Babel 2.17.0\n"
msgid "Stop Game"
@@ -87,6 +87,12 @@ msgstr ""
"Вы уверены, что хотите удалить папку '{folder_name}'? Это действие нельзя "
"отменить."
msgid "Yes"
msgstr "Да"
msgid "No"
msgstr "Нет"
#, python-brace-format
msgid "Failed to delete folder: {error}"
msgstr "Не удалось удалить папку: {error}"
@@ -109,12 +115,12 @@ msgstr "Удалить из меню"
msgid "Add to Menu"
msgstr "Добавить в меню"
msgid "Edit Shortcut"
msgstr "Редактировать ярлык"
msgid "Open Game Folder"
msgstr "Открыть папку с игрой"
msgid "Edit Shortcut"
msgstr "Редактировать ярлык"
msgid "Remove from Steam"
msgstr "Удалить из Steam"
@@ -149,12 +155,6 @@ msgstr ""
"Вы уверены, что хотите удалить '{game_name}'? Это приведёт к удалению "
"файла .desktop и пользовательских данных."
msgid "Yes"
msgstr "Да"
msgid "No"
msgstr "Нет"
#, python-brace-format
msgid "Failed to delete .desktop file: {error}"
msgstr "Не удалось удалить файл .desktop: {error}"
@@ -301,9 +301,6 @@ msgstr "Бронза"
msgid "Pending"
msgstr "В ожидании"
msgid "Launched"
msgstr "Запуск"
msgid "Unknown Game"
msgstr "Неизвестная игра"
@@ -529,6 +526,9 @@ msgstr "Тип отображения бейджей:"
msgid "Interface Settings"
msgstr "Настройки интерфейса"
msgid "Tray Menu Type:"
msgstr "Тип трея:"
msgid "Launch Application in Fullscreen"
msgstr "Запуск приложения в полноэкранном режиме"
@@ -544,6 +544,9 @@ msgstr "Запускать свёрнутым"
msgid "Hide Auto-Install Tab"
msgstr "Скрыть вкладку \"Автоустановка\""
msgid "Disable runtime download"
msgstr "Отключить скачивание контейнера"
msgid "Add to Steam compatibility tools"
msgstr "Добавить в инструменты совместимости Steam"
@@ -553,9 +556,15 @@ msgstr "Скачивать Proton в Steam"
msgid "Economy mode"
msgstr "Экономный режим"
msgid "Download mirror:"
msgstr "Зеркало для скачивания:"
msgid "Force system DPI for Wine"
msgstr "Принудительно установить системный DPI для Wine"
msgid "Download Settings"
msgstr "Настройки Скачивания"
msgid "Gamepad Settings"
msgstr "Настройки геймпада"
@@ -819,9 +828,6 @@ msgstr ""
msgid "Use container launch mode (recommended default)"
msgstr "Использовать режим запуска в контейнере (рекомендуемый по умолчанию)"
msgid "System WINE"
msgstr "Системный WINE"
msgid "Wine Version"
msgstr "Версия Wine"
@@ -1011,15 +1017,18 @@ msgstr "сек."
msgid "Exit"
msgstr "Выход"
msgid "Tabs"
msgstr "Вкладки"
msgid "Recent Games"
msgstr "Недавние"
msgid "No favorites"
msgstr "Нет избранных"
msgid "No recent games"
msgstr "Нет недавних игр"
msgid "No favorites"
msgstr "Нет избранных"
#, python-brace-format
msgid "Launch game \"{name}\" with PortProton"
msgstr "Запустить игру \"{name}\" с помощью PortProton"
@@ -1167,6 +1176,9 @@ msgstr "Очистить выбранное"
msgid "Select"
msgstr "Выбрать"
msgid "Home"
msgstr "Домашняя папка"
msgid "Path: "
msgstr "Путь: "
@@ -1311,6 +1323,9 @@ msgstr "Операция отменена"
msgid "Download or extraction has been cancelled."
msgstr "Скачивание или распаковка успешно отменена."
msgid "System WINE"
msgstr "Системный WINE"
msgid "Exe Settings"
msgstr "Настройки EXE"
@@ -1335,6 +1350,9 @@ msgstr "Описание"
msgid "Open PPDB"
msgstr "Открыть PPDB"
msgid "Clear PPDB"
msgstr "Очистить PPDB"
msgid "Executable path is not available."
msgstr "Путь к исполняемому файлу недоступен."
@@ -1344,6 +1362,23 @@ msgstr "Файл PPDB не существует по адресу: "
msgid "Failed to open PPDB file:\n"
msgstr "Не удалось открыть файл PPDB:\n"
msgid "Information"
msgstr "Информация"
msgid "Confirm PPDB Clear"
msgstr "Подтвердите очистку PPDB"
msgid ""
"Are you sure you want to clear settings? This action cannot be undone."
msgstr ""
"Вы уверены, что хотите сбросить настройки? Это действие нельзя отменить."
msgid "Failed to remove PPDB file:\n"
msgstr "Не удалось удалить файл PPDB:\n"
msgid "PPDB settings cleared."
msgstr "Настройки PPDB сброшенны"
msgid "disabled"
msgstr "отключено"
@@ -1594,9 +1629,6 @@ msgstr "Например: --cursor-scale-height=1080 --force-orientation=left"
msgid "Disable Gamescope"
msgstr "Отключить Gamescope"
msgid "Information"
msgstr "Информация"
msgid "Custom preset is empty. Save one first."
msgstr "Пользовательские настройки пусты. Сначала сохраните их."
@@ -1957,9 +1989,6 @@ msgstr "Включить MangoHud"
msgid "Use system config"
msgstr "Использовать системный конфиг"
msgid "PortProton default"
msgstr "Стандартный PortProton"
msgid "FPS only"
msgstr "Только FPS"
@@ -2036,6 +2065,9 @@ msgstr "Установка не удалась. Проверьте журнал
msgid "Components installed successfully."
msgstr "Компоненты успешно установлены."
msgid "Launched"
msgstr "Запуск"
msgid "Bluetooth PIN code"
msgstr "ПИН-код Bluetooth"
File diff suppressed because it is too large. Load diff
+143 -57
View File
@@ -6,13 +6,15 @@ import subprocess
import psutil
import re
from portprotonqt.logger import get_logger
from portprotonqt.dialogs import AddGameDialog, FileExplorer, WinetricksDialog, ExeSettingsDialog, generate_thumbnail
from portprotonqt.icon_extractor import generate_thumbnail
from portprotonqt.dialogs import AddGameDialog, FileExplorer, WinetricksDialog, ExeSettingsDialog
from portprotonqt.game_card import GameCard
from portprotonqt.animations import DetailPageAnimations
from portprotonqt.custom_widgets import ClickableLabel, AutoSizeButton, NavLabel, FlowLayout
from portprotonqt.detail_pages import DetailPageManager
from portprotonqt.portproton_api import PortProtonAPI, get_user_conf_setting, set_user_conf_setting
from portprotonqt.debug_utils import get_selectable_gpu_list, get_prefix_name, get_system_dpi_for_wine
from portprotonqt.debug_utils import get_selectable_gpu_list, get_prefix_name
from portprotonqt.qt_utils import get_system_dpi_for_wine
from portprotonqt.input_manager import InputManager, MainWindowProtocol
from portprotonqt.context_menu_manager import ContextMenuManager, CustomLineEdit
@@ -46,7 +48,7 @@ from portprotonqt.config import (
)
from portprotonqt.cli import add_steam_compat_tool, remove_steam_compat_tool, is_steam_compat_tool_installed
from portprotonqt.tray_manager import restart_application_with_muvm
from portprotonqt.tray_manager import restart_application_process
from portprotonqt.version_utils import prefix_sort_key, version_sort_key
from portprotonqt.localization import _, get_metadata_language, read_metadata_translations
from portprotonqt.downloader import Downloader
@@ -271,9 +273,10 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
navLayout.setSpacing(10)
# Left navigation button (key_left or button_lb)
self.leftNavButton = QLabel()
self.leftNavButton = NavLabel()
self.leftNavButton.setFixedSize(32, 32)
self.leftNavButton.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.leftNavButton.clicked.connect(lambda: self.switchVisibleTab(-1))
navLayout.addWidget(self.leftNavButton)
# Tabs
@@ -297,9 +300,10 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.tabButtons[0].setChecked(True)
# Right navigation button (key_right or button_rb)
self.rightNavButton = QLabel()
self.rightNavButton = NavLabel()
self.rightNavButton.setFixedSize(32, 32)
self.rightNavButton.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.rightNavButton.clicked.connect(lambda: self.switchVisibleTab(1))
navLayout.addWidget(self.rightNavButton)
# Initial update of navigation buttons based on input device
@@ -463,8 +467,8 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
return
self.current_install_button_text = button.text()
self.current_install_button_icon = button.icon()
icon = self.theme_manager.get_icon("stop")
self.current_install_button_icon = button.rawIcon()
icon = self.theme_manager.get_icon("stop", as_path=True)
if icon:
button.setIcon(icon)
button.setText(_("Stop"))
@@ -1069,6 +1073,25 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.pending_games = []
# TABS
def switchVisibleTab(self, step: int) -> None:
"""Switch to the previous or next visible tab."""
visible_indices = [
i for i, btn in self.tabButtons.items()
if btn.isVisible()
]
visible_indices.sort()
if not visible_indices:
return
current_index = self.stackedWidget.currentIndex()
try:
current_pos = visible_indices.index(current_index)
except ValueError:
current_pos = 0
new_index = visible_indices[(current_pos + step) % len(visible_indices)]
self.switchTab(new_index)
def switchTab(self, index):
"""Set active tab by index."""
# Check if the requested tab index is valid, exists, and is visible
@@ -1128,14 +1151,14 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.GameLibraryTitle.setStyleSheet(self.theme.INSTALLED_TAB_TITLE_STYLE)
layout.addWidget(self.GameLibraryTitle)
self.addGameButton = AutoSizeButton(_("Add Game"), icon=self.theme_manager.get_icon("addgame"))
self.addGameButton = AutoSizeButton(_("Add Game"), icon=self.theme_manager.get_icon("addgame", as_path=True))
self.addGameButton.setStyleSheet(self.theme.ADDGAME_BACK_BUTTON_STYLE)
self.addGameButton.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.addGameButton.clicked.connect(self.openAddGameDialog)
layout.addWidget(self.addGameButton)
# Refresh button
self.refreshButton = AutoSizeButton(_("Refresh Grid"), icon=self.theme_manager.get_icon("update"))
self.refreshButton = AutoSizeButton(_("Refresh Grid"), icon=self.theme_manager.get_icon("update", as_path=True))
self.refreshButton.setStyleSheet(self.theme.ADDGAME_BACK_BUTTON_STYLE)
self.refreshButton.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.refreshButton.clicked.connect(self.refreshGames)
@@ -1675,6 +1698,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.wineTitle.setStyleSheet(self.theme.TAB_TITLE_STYLE)
self.wineTitle.setObjectName("tabTitle")
layout.addWidget(self.wineTitle)
self.stackedWidget.addWidget(self.wineWidget)
if self.portproton_location is None:
return
@@ -1809,8 +1833,6 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
wine_progress_layout.addWidget(self.wine_progress_bar)
layout.addLayout(wine_progress_layout)
self.stackedWidget.addWidget(self.wineWidget)
def launch_generic_tool(self, cli_arg):
wine = self.wineCombo.currentText()
raw_prefix = self.prefixCombo.currentText().strip()
@@ -1999,6 +2021,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
def _on_restore_finished(self, exitCode):
if exitCode == 0:
self.refreshGames()
QMessageBox.information(self, _("Success"), _("Prefix restore completed."))
else:
QMessageBox.warning(self, _("Error"), _("Prefix restore failed."))
@@ -2284,6 +2307,31 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
uiForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(uiFrame)
self.tray_menu_mode_keys = ["compact", "detailed"]
self.tray_menu_mode_labels = [_("Compact"), _("Detailed")]
self.trayMenuModeCombo = QComboBox()
self.trayMenuModeCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.trayMenuModeCombo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.trayMenuModeCombo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.trayMenuModeCombo.addItems(self.tray_menu_mode_labels)
self.trayMenuModeCombo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
self.trayMenuModeCombo.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.trayMenuModeTitle = QLabel(_("Tray Menu Type:"))
self.trayMenuModeTitle.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.trayMenuModeTitle.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
self.trayMenuModeTitle.setFocusPolicy(Qt.FocusPolicy.NoFocus)
current = display_config.get_tray_menu_mode()
try:
idx = self.tray_menu_mode_keys.index(current)
except ValueError:
idx = 0
self.trayMenuModeCombo.setCurrentIndex(idx)
uiForm.addRow(self.trayMenuModeTitle, self.trayMenuModeCombo)
self.fullscreenCheckBox = QCheckBox() # Removed text
self.fullscreenCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
self.fullscreenCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -2364,6 +2412,23 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
hide_autoinstall_layout.addStretch()
uiForm.addRow(hide_autoinstall_layout)
disable_runtime_download_layout = None
if not os.getenv("FLATPAK_ID"):
self.disableRuntimeDownloadCheckBox = QCheckBox()
self.disableRuntimeDownloadCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
self.disableRuntimeDownloadCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.disableRuntimeDownloadTitle = QLabel(_("Disable runtime download"))
self.disableRuntimeDownloadTitle.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.disableRuntimeDownloadTitle.setStyleSheet(self.theme.SETTINGS_TITLE_CHECKBOX_STYLE)
self.disableRuntimeDownloadTitle.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.disableRuntimeDownloadCheckBox.setChecked(ui_config.get_disable_runtime_download())
disable_runtime_download_layout = QHBoxLayout()
disable_runtime_download_layout.setContentsMargins(0, 0, 0, 0)
disable_runtime_download_layout.addWidget(self.disableRuntimeDownloadCheckBox)
disable_runtime_download_layout.addWidget(self.disableRuntimeDownloadTitle)
disable_runtime_download_layout.addStretch()
download_wine_to_steam_layout = None
self.steamCompatCheckBox = QCheckBox()
self.steamCompatCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
self.steamCompatCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -2394,7 +2459,6 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
download_wine_to_steam_layout.addWidget(self.downloadWineToSteamCheckBox)
download_wine_to_steam_layout.addWidget(self.downloadWineToSteamTitle)
download_wine_to_steam_layout.addStretch()
uiForm.addRow(download_wine_to_steam_layout)
self.economyModeCheckBox = QCheckBox()
self.economyModeCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
@@ -2418,7 +2482,27 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
economy_mode_layout.addWidget(self.economyModeCheckBox)
economy_mode_layout.addWidget(self.economyModeTitle)
economy_mode_layout.addStretch()
uiForm.addRow(economy_mode_layout)
self.downloadMirrorCombo = QComboBox()
self.downloadMirrorCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
)
self.downloadMirrorCombo.view().window().setAttribute(
Qt.WidgetAttribute.WA_TranslucentBackground
)
self.downloadMirrorCombo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
self.downloadMirrorCombo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
self.downloadMirrorCombo.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.downloadMirrorCombo.addItems(["CLOUD", "GITHUB"])
current_download_mirror = get_user_conf_setting('MIRROR')
if current_download_mirror and current_download_mirror not in ("CLOUD", "GITHUB"):
self.downloadMirrorCombo.addItem(current_download_mirror)
if current_download_mirror:
self.downloadMirrorCombo.setCurrentText(current_download_mirror)
self.downloadMirrorTitle = QLabel(_("Download mirror:"))
self.downloadMirrorTitle.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
self.downloadMirrorTitle.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
self.downloadMirrorTitle.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.forceSystemDpiCheckBox = QCheckBox()
self.forceSystemDpiCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
@@ -2436,7 +2520,21 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
force_system_dpi_layout.addStretch()
uiForm.addRow(force_system_dpi_layout)
# 3. Gamepad Settings Section
# 3. Download Settings Section
downloadFrame, downloadForm = create_section(_("Download Settings"), self.theme)
downloadForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(downloadFrame)
if disable_runtime_download_layout is not None:
downloadForm.addRow(disable_runtime_download_layout)
if download_wine_to_steam_layout is not None:
downloadForm.addRow(download_wine_to_steam_layout)
downloadForm.addRow(economy_mode_layout)
downloadForm.addRow(self.downloadMirrorTitle, self.downloadMirrorCombo)
# 4. Gamepad Settings Section
padFrame, padForm = create_section(_("Gamepad Settings"), self.theme)
padForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(padFrame)
@@ -2457,13 +2555,14 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
auto_fullscreen_layout.addStretch()
padForm.addRow(auto_fullscreen_layout)
# 4. Hardware Settings Section
# 5. Hardware Settings Section
hwFrame, hwForm = create_section(_("Hardware Settings"), self.theme)
hwForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(hwFrame)
filtered_gpu_list = get_selectable_gpu_list()
if filtered_gpu_list:
hwFrame.setVisible(len(filtered_gpu_list) != 1)
if len(filtered_gpu_list) > 1:
self.gpuCombo = QComboBox()
self.gpuCombo.view().window().setWindowFlags(
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
@@ -2489,10 +2588,10 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.gpuTitle.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
self.gpuTitle.setFocusPolicy(Qt.FocusPolicy.NoFocus)
hwForm.addRow(self.gpuTitle, self.gpuCombo)
else:
elif not filtered_gpu_list:
hwForm.addRow(QLabel(_("No GPUs found")), QLabel(""))
# 5. Proxy Settings Section
# 6. Proxy Settings Section
proxyFrame, proxyForm = create_section(_("Proxy Settings"), self.theme)
proxyForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(proxyFrame)
@@ -2542,25 +2641,25 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
buttonsLayout = QHBoxLayout()
buttonsLayout.setSpacing(10)
self.saveButton = AutoSizeButton(_("Save Settings"), icon=self.theme_manager.get_icon("save"))
self.saveButton = AutoSizeButton(_("Save Settings"), icon=self.theme_manager.get_icon("save", as_path=True))
self.saveButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.saveButton.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.saveButton.clicked.connect(self.savePortProtonSettings)
buttonsLayout.addWidget(self.saveButton)
self.resetSettingsButton = AutoSizeButton(_("Reset Settings"), icon=self.theme_manager.get_icon("update"))
self.resetSettingsButton = AutoSizeButton(_("Reset Settings"), icon=self.theme_manager.get_icon("update", as_path=True))
self.resetSettingsButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.resetSettingsButton.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.resetSettingsButton.clicked.connect(self.resetSettings)
buttonsLayout.addWidget(self.resetSettingsButton)
self.migrateShortcutsButton = AutoSizeButton(_("Migrate legacy shortcuts"), icon=self.theme_manager.get_icon("update"))
self.migrateShortcutsButton = AutoSizeButton(_("Migrate legacy shortcuts"), icon=self.theme_manager.get_icon("update", as_path=True))
self.migrateShortcutsButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.migrateShortcutsButton.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.migrateShortcutsButton.clicked.connect(self.migrateLegacyShortcuts)
buttonsLayout.addWidget(self.migrateShortcutsButton)
self.clearCacheButton = AutoSizeButton(_("Clear Cache"), icon=self.theme_manager.get_icon("update"))
self.clearCacheButton = AutoSizeButton(_("Clear Cache"), icon=self.theme_manager.get_icon("update", as_path=True))
self.clearCacheButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.clearCacheButton.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
self.clearCacheButton.clicked.connect(self.clearCache)
@@ -2670,6 +2769,10 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
start_minimized = self.startMinimizedCheckBox.isChecked()
display_config.set_start_minimized(start_minimized)
tray_menu_mode_idx = self.trayMenuModeCombo.currentIndex()
tray_menu_mode = self.tray_menu_mode_keys[tray_menu_mode_idx]
display_config.set_tray_menu_mode(tray_menu_mode)
steam_compat = self.steamCompatCheckBox.isChecked()
currently_installed = is_steam_compat_tool_installed()
if steam_compat and not currently_installed:
@@ -2680,13 +2783,20 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
if hasattr(self, 'downloadWineToSteamCheckBox'):
ui_config.set_download_wine_to_steam(self.downloadWineToSteamCheckBox.isChecked())
if hasattr(self, 'disableRuntimeDownloadCheckBox'):
ui_config.set_disable_runtime_download(self.disableRuntimeDownloadCheckBox.isChecked())
else:
ui_config.get_disable_runtime_download()
set_user_conf_setting('MIRROR', self.downloadMirrorCombo.currentText())
# Save GPU selection to user.conf (only if the combo box exists)
if hasattr(self, 'gpuCombo'):
if hasattr(self, 'gpuCombo') and self.gpuCombo.count() > 1:
selected_gpu = self.gpuCombo.currentText()
set_user_conf_setting('PW_GPU_USE', selected_gpu)
if hasattr(self, 'forceSystemDpiCheckBox'):
if self.forceSystemDpiCheckBox.isChecked():
system_dpi = get_system_dpi_for_wine(get_user_conf_setting('PW_SCREEN_RESOLUTION'))
system_dpi = get_system_dpi_for_wine()
set_user_conf_setting('PW_FORCE_SYSTEM_DPI', "1")
set_user_conf_setting('PW_WINE_DPI_VALUE', system_dpi)
else:
@@ -2806,11 +2916,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.themesCombo.setObjectName("themeTabCombo")
self.themesCombo.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
theme_names = self.theme_manager.get_available_themes()
available_themes = []
for theme_name in theme_names:
base_name = theme_name[:-6] if theme_name.endswith("-light") else theme_name
if base_name not in available_themes:
available_themes.append(base_name)
available_themes = ui_config.get_theme_bases(theme_names)
current_theme_base = ui_config.get_theme_base()
if current_theme_base in available_themes:
available_themes.remove(current_theme_base)
@@ -2841,7 +2947,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
mainLayout.addLayout(self.themeTabHeaderLayout)
def hasThemeVariants(theme_name: str) -> bool:
return theme_name in theme_names and f"{theme_name}-light" in theme_names
return ui_config.resolve_theme(theme_name, "dark") != ui_config.resolve_theme(theme_name, "light")
def updateThemeVariantVisibility(*_args: object) -> None:
self.themeVariantCombo.setVisible(hasThemeVariants(self.themesCombo.currentText()))
@@ -2866,7 +2972,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
self.themeMetainfoLabel.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.themeInfoLayout.addWidget(self.themeMetainfoLabel)
self.applyButton = AutoSizeButton(_("Apply Theme"), icon=self.theme_manager.get_icon("apply"))
self.applyButton = AutoSizeButton(_("Apply Theme"), icon=self.theme_manager.get_icon("apply", as_path=True))
self.applyButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.applyButton.setObjectName("themeApplyButton")
self.applyButton.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -2940,7 +3046,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
"""Restart application."""
if not self.isFullScreen():
window_config.set_geometry(self.width(), self.height())
restart_application_with_muvm()
restart_application_process()
def restore_state(self):
"""Restore application state after restart."""
@@ -3353,11 +3459,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
if self.current_running_button is not None:
try:
self.current_running_button.setText(_("Stop"))
icon = self.theme_manager.get_icon("stop")
if isinstance(icon, str):
icon = QIcon(icon)
elif icon is None:
icon = QIcon()
icon = self.theme_manager.get_icon("stop", as_path=True)
self.current_running_button.setIcon(icon)
except RuntimeError:
self.current_running_button = None
@@ -3370,11 +3472,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
if self.wine_download_percent > 0:
status = status.replace("...", f"... {int(self.wine_download_percent)}%")
self.current_running_button.setText(status)
icon = self.theme_manager.get_icon("save")
if isinstance(icon, str):
icon = QIcon(icon)
elif icon is None:
icon = QIcon()
icon = self.theme_manager.get_icon("save", as_path=True)
self.current_running_button.setIcon(icon)
except RuntimeError:
pass
@@ -3382,11 +3480,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
if self.current_running_button is not None:
try:
self.current_running_button.setText(_("Stop"))
icon = self.theme_manager.get_icon("stop")
if isinstance(icon, str):
icon = QIcon(icon)
elif icon is None:
icon = QIcon()
icon = self.theme_manager.get_icon("stop", as_path=True)
self.current_running_button.setIcon(icon)
except RuntimeError:
self.current_running_button = None
@@ -3444,11 +3538,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
if self.current_running_button is not None:
try:
self.current_running_button.setText(_("Play"))
icon = self.theme_manager.get_icon("play")
if isinstance(icon, str):
icon = QIcon(icon) # Convert path to QIcon
elif icon is None:
icon = QIcon() # Use empty QIcon as fallback
icon = self.theme_manager.get_icon("play", as_path=True)
self.current_running_button.setIcon(icon)
except RuntimeError:
pass
@@ -3623,11 +3713,7 @@ class MainWindow(MainWindowControlHintsMixin, MainWindowSystemTabMixin, MainWind
if update_button:
try:
update_button.setText(_("Stop"))
icon = self.theme_manager.get_icon("stop")
if isinstance(icon, str):
icon = QIcon(icon)
elif icon is None:
icon = QIcon()
icon = self.theme_manager.get_icon("stop", as_path=True)
update_button.setIcon(icon)
except RuntimeError:
pass
+19 -2
View File
@@ -8,11 +8,11 @@ install_data(
'dialogs.py',
'disc_image_utils.py',
'downloader.py',
'easyterm.py',
'game_card.py',
'game_library_manager.py',
'howlongtobeat_api.py',
'idle_inhibit.py',
'image_utils.py',
'icon_extractor.py',
'input_manager.py',
@@ -23,6 +23,7 @@ install_data(
'port_data_path_selector.py',
'portproton_api.py',
'preloader.py',
'qt_utils.py',
'search_utils.py',
'settings_manager.py',
'theme_manager.py',
@@ -118,6 +119,16 @@ install_data(
install_dir: pythondir / meson.project_name() / 'debug_utils',
)
# Install scripts_utils package
install_data(
['scripts_utils/__init__.py',
'scripts_utils/idle_inhibit.py',
'scripts_utils/power_profiles.py',
'scripts_utils/shortcut_tools.py',
],
install_dir: pythondir / meson.project_name() / 'scripts_utils',
)
# Install config package
install_data(
['config/__init__.py',
@@ -144,9 +155,15 @@ install_subdir(
exclude_files: ['*.pyc'],
)
# Install terminal schemes
install_subdir(
'terminal_schemes',
install_dir: pythondir / meson.project_name(),
)
# Compile and install locales from .po files
msgfmt = find_program('msgfmt', required: true)
foreach lang : ['de', 'es', 'pt', 'ru']
foreach lang : ['de', 'es', 'pt', 'ru', 'zh_Hans']
mo_target = configure_file(
input: 'locales' / lang / 'LC_MESSAGES' / 'portprotonqt.po',
output: lang + '_portprotonqt.mo',
+41 -7
View File
@@ -31,6 +31,8 @@ logger = get_logger(__name__)
AUTOINSTALL_CACHE_DURATION = 3600 # 1 hour for autoinstall cache
HEAD_FAILURE_RETRY_DELAY = 60 # 1 minute cooldown for failed HEAD checks
HEAD_CACHE_DURATION = 24 * 60 * 60
HEAD_CACHE_NAME = "head_cache"
HEAD_CACHE_OLD_PATTERN = "head_*.json"
def _create_bootstrap_file_explorer_parent() -> tuple[QObject | None, Any]:
@@ -116,6 +118,7 @@ class PortProtonAPI:
self._head_positive_cache: set[str] = set()
self._head_negative_cache: set[str] = set()
self._head_failure_cache: dict[str, float] = {}
self._head_disk_cache_cleaned = False
self._pending_asset_notifier: QObject | None = None
self._pending_asset_batch_thread: QThread | None = None
@@ -124,6 +127,38 @@ class PortProtonAPI:
os.makedirs(game_dir, exist_ok=True)
return game_dir
def _load_head_cache_entry(self, cache_manager: CacheManager, cache_key: str) -> bool | None:
cached = cache_manager.load_json(HEAD_CACHE_NAME)
if not isinstance(cached, dict):
return None
entry = cached.get(cache_key)
if not isinstance(entry, dict):
return None
timestamp = entry.get("timestamp")
if not isinstance(timestamp, int | float):
return None
if time.time() - timestamp > HEAD_CACHE_DURATION:
return None
return entry.get("exists") is True
def _save_head_cache_entry(self, cache_manager: CacheManager, cache_key: str, exists: bool) -> None:
cached = cache_manager.load_json(HEAD_CACHE_NAME)
if not isinstance(cached, dict):
cached = {}
cached[cache_key] = {"exists": exists, "timestamp": time.time()}
cache_manager.save_json(HEAD_CACHE_NAME, cached)
self._remove_old_head_cache_files(cache_manager)
def _remove_old_head_cache_files(self, cache_manager: CacheManager) -> None:
if self._head_disk_cache_cleaned:
return
for cache_file in cache_manager.cache_dir.glob(HEAD_CACHE_OLD_PATTERN):
try:
cache_file.unlink()
except OSError as e:
logger.debug("Failed to remove old HEAD cache %s: %s", cache_file, e)
self._head_disk_cache_cleaned = True
def _check_file_exists(self, url: str, timeout: int = 5) -> bool:
if url in self._head_negative_cache:
return False
@@ -134,11 +169,10 @@ class PortProtonAPI:
return False
cache_manager = CacheManager()
cache_key = f"head_{hashlib.sha256(url.encode('utf-8')).hexdigest()}"
if cache_manager.is_fresh(cache_key, HEAD_CACHE_DURATION):
cached = cache_manager.load_json(cache_key)
if isinstance(cached, dict):
return cached.get("exists") is True
cache_key = hashlib.sha256(url.encode('utf-8')).hexdigest()
cached_exists = self._load_head_cache_entry(cache_manager, cache_key)
if cached_exists is not None:
return cached_exists
try:
session = get_requests_session()
@@ -147,13 +181,13 @@ class PortProtonAPI:
self._head_negative_cache.add(url)
self._head_positive_cache.discard(url)
self._head_failure_cache.pop(url, None)
cache_manager.save_json(cache_key, {"exists": False})
self._save_head_cache_entry(cache_manager, cache_key, False)
return False
response.raise_for_status()
if response.status_code == 200:
self._head_positive_cache.add(url)
self._head_failure_cache.pop(url, None)
cache_manager.save_json(cache_key, {"exists": True})
self._save_head_cache_entry(cache_manager, cache_key, True)
return True
return False
except requests.RequestException as e:
+59
View File
@@ -0,0 +1,59 @@
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import QApplication
def get_device_pixel_ratio() -> float:
"""Return current device pixel ratio with a safe fallback."""
app = QApplication.instance()
return app.devicePixelRatio() if isinstance(app, QApplication) else 1.0
def get_system_dpi_for_wine() -> str:
"""Return Wine LogPixels value calculated from system scale."""
app_instance = QApplication.instance()
if isinstance(app_instance, QGuiApplication):
window = app_instance.focusWindow()
if window is None:
for widget in QApplication.topLevelWidgets():
if widget.isVisible() and widget.windowHandle() is not None:
window = widget.windowHandle()
break
if window is not None:
dpi_value = int(round(96.0 * window.devicePixelRatio()))
if dpi_value > 96:
return str(dpi_value)
return "96"
def get_screen_info() -> tuple[str, str]:
"""Get screen resolution and primary info using PySide6."""
app_instance = QApplication.instance()
default_resolution = "1920x1080"
default_primary = ""
if not isinstance(app_instance, QGuiApplication):
return (
f"PW_SCREEN_RESOLUTION={default_resolution}",
f"PW_SCREEN_PRIMARY={default_primary}",
)
screen = app_instance.primaryScreen()
if screen is None:
screens = app_instance.screens()
if screens:
screen = screens[0]
if screen is None:
return (
f"PW_SCREEN_RESOLUTION={default_resolution}",
f"PW_SCREEN_PRIMARY={default_primary}",
)
geometry = screen.geometry()
if geometry.width() > 0 and geometry.height() > 0:
resolution = f"{geometry.width()}x{geometry.height()}"
else:
resolution = default_resolution
primary = screen.name() or default_primary
return f"PW_SCREEN_RESOLUTION={resolution}", f"PW_SCREEN_PRIMARY={primary}"
Whitespace-only changes.
+162
View File
@@ -0,0 +1,162 @@
import asyncio
import contextlib
import os
import sys
from collections.abc import Awaitable
from typing import Any, cast
from dbus_fast import DBusError, Message, Variant
from dbus_fast.aio import MessageBus
from portprotonqt.logger import get_logger
from portprotonqt.localization import _
logger = get_logger(__name__)
BUS_NAME = "org.freedesktop.ScreenSaver"
BUS_PATH = "/org/freedesktop/ScreenSaver"
PORTAL_BUS_NAME = "org.freedesktop.portal.Desktop"
PORTAL_BUS_PATH = "/org/freedesktop/portal/desktop"
PORTAL_INTERFACE = "org.freedesktop.portal.Inhibit"
PORTAL_REQUEST_INTERFACE = "org.freedesktop.portal.Request"
PORTAL_IDLE_FLAG = 8
APPLICATION_NAME = "ru.linux_gaming.PortProtonQt"
INHIBIT_REASON = _("Launched")
DBUS_TIMEOUT = 10
WINE_WAIT_INTERVAL = 5
WINE_PROCESS_NAMES = {"wine-preloader", "wine64-preloader", "wineserver"}
def _get_inhibit_reason() -> str:
game_name = os.getenv("PW_INHIBIT_NAME", "").strip()
if not game_name:
game_name = os.getenv("PORTPROTON_NAME", "").strip()
if not game_name:
return INHIBIT_REASON
return f"{INHIBIT_REASON} {game_name}"
async def _run_command(command: list[str]) -> int:
process = await asyncio.create_subprocess_exec(*command)
return_code = await process.wait()
await _wait_wine_processes()
return return_code
def _has_wine_process() -> bool:
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
exe_path = os.readlink(os.path.join("/proc", pid, "exe"))
except OSError:
continue
if _is_portproton_wine_process(exe_path):
return True
return False
def _is_portproton_wine_process(exe_path: str) -> bool:
lower_path = exe_path.lower()
if "portproton" not in lower_path:
return False
return os.path.basename(lower_path) in WINE_PROCESS_NAMES
async def _wait_wine_processes() -> None:
while _has_wine_process():
await asyncio.sleep(WINE_WAIT_INTERVAL)
async def _dbus_call(awaitable: Awaitable[Any]) -> Any:
return await asyncio.wait_for(awaitable, timeout=DBUS_TIMEOUT)
async def _request_screensaver_inhibit(bus: MessageBus) -> tuple[str, Any]:
introspection = await _dbus_call(bus.introspect(BUS_NAME, BUS_PATH))
proxy = bus.get_proxy_object(BUS_NAME, BUS_PATH, introspection)
iface = cast(Any, proxy.get_interface(BUS_NAME))
cookie = await _dbus_call(iface.call_inhibit(APPLICATION_NAME, _get_inhibit_reason()))
return "screensaver", (iface, cookie)
async def _request_portal_inhibit(bus: MessageBus) -> tuple[str, Any]:
options = {"reason": Variant("s", _get_inhibit_reason())}
message = Message(
destination=PORTAL_BUS_NAME,
path=PORTAL_BUS_PATH,
interface=PORTAL_INTERFACE,
member="Inhibit",
signature="sua{sv}",
body=["", PORTAL_IDLE_FLAG, options],
)
reply = await _dbus_call(bus.call(message))
return "portal", reply.body[0]
async def _request_inhibit() -> tuple[MessageBus, str, Any]:
bus = await _dbus_call(MessageBus().connect())
try:
try:
kind, payload = await _request_screensaver_inhibit(bus)
except Exception as err:
logger.warning("Screensaver inhibit failed: %s", err)
kind, payload = await _request_portal_inhibit(bus)
except Exception:
bus.disconnect()
raise
return bus, kind, payload
async def _release_portal_inhibit(bus: MessageBus, handle: str) -> None:
message = Message(
destination=PORTAL_BUS_NAME,
path=handle,
interface=PORTAL_REQUEST_INTERFACE,
member="Close",
)
await _dbus_call(bus.call(message))
async def _release_inhibit(bus: MessageBus, kind: str, payload: Any) -> None:
with contextlib.suppress(DBusError, asyncio.TimeoutError):
if kind == "screensaver":
iface, cookie = payload
await _dbus_call(iface.call_un_inhibit(cookie))
elif kind == "portal":
await _release_portal_inhibit(bus, payload)
bus.disconnect()
async def _inhibit_and_run(command: list[str]) -> int:
try:
bus, kind, payload = await _request_inhibit()
except (ImportError, TimeoutError) as err:
logger.warning("Screensaver inhibit failed: %s", err)
return await _run_command(command)
except Exception as err:
logger.warning("Screensaver inhibit failed: %s", err)
return await _run_command(command)
try:
return await _run_command(command)
finally:
await _release_inhibit(bus, kind, payload)
async def _main(command: list[str]) -> int:
if not command:
return 2
return await _inhibit_and_run(command)
def main() -> int:
return asyncio.run(_main(sys.argv[1:]))
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,162 @@
"""Power profile tools for PortProton scripts."""
import argparse
import asyncio
import sys
from typing import Any
from dbus_fast import BusType, Message, Variant
from dbus_fast.aio import MessageBus
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
Endpoint = tuple[str, str]
POWER_PROFILE_ENDPOINTS: tuple[Endpoint, ...] = (
(
"org.freedesktop.UPower.PowerProfiles",
"/org/freedesktop/UPower/PowerProfiles",
),
(
"net.hadess.PowerProfiles",
"/net/hadess/PowerProfiles",
),
)
PROPERTIES_INTERFACE = "org.freedesktop.DBus.Properties"
ACTIVE_PROFILE = "ActiveProfile"
PROFILES = "Profiles"
DBUS_TIMEOUT = 10
async def _dbus_call(bus: Any, message: Any) -> Any:
reply = await asyncio.wait_for(bus.call(message), timeout=DBUS_TIMEOUT)
if reply.message_type.name == "ERROR":
return None
return reply.body
async def _get_property(bus: Any, endpoint: Endpoint, name: str) -> Any:
bus_name, bus_path = endpoint
body = await _dbus_call(
bus,
Message(
destination=bus_name,
path=bus_path,
interface=PROPERTIES_INTERFACE,
member="Get",
signature="ss",
body=[bus_name, name],
),
)
if not body:
return None
return _variant_value(body[0])
async def _active_profile(bus: Any) -> tuple[Endpoint, str] | None:
for endpoint in POWER_PROFILE_ENDPOINTS:
try:
profile = await _get_property(bus, endpoint, ACTIVE_PROFILE)
except Exception as error:
logger.debug("Power profile endpoint unavailable: %s", error)
continue
if isinstance(profile, str):
return endpoint, profile
return None
async def get_profile() -> str | None:
"""Return active power profile."""
bus = await MessageBus(bus_type=BusType.SYSTEM).connect()
active_profile = await _active_profile(bus)
if not active_profile:
return None
return active_profile[1]
async def set_profile(profile: str) -> bool:
"""Set active power profile."""
bus = await MessageBus(bus_type=BusType.SYSTEM).connect()
active_profile = await _active_profile(bus)
if not active_profile:
return False
bus_name, bus_path = active_profile[0]
profiles = await _get_property(bus, active_profile[0], PROFILES)
if profile not in _profile_names(profiles):
return False
body = await _dbus_call(
bus,
Message(
destination=bus_name,
path=bus_path,
interface=PROPERTIES_INTERFACE,
member="Set",
signature="ssv",
body=[bus_name, ACTIVE_PROFILE, Variant("s", profile)],
),
)
return body is not None
def _variant_value(value: Any) -> Any:
if isinstance(value, Variant):
return _variant_value(value.value)
if isinstance(value, dict):
return {
_variant_value(key): _variant_value(item)
for key, item in value.items()
}
if isinstance(value, list):
return [_variant_value(item) for item in value]
return value
def _profile_names(profiles: Any) -> set[str]:
if not isinstance(profiles, list):
return set()
names = set()
for profile in profiles:
if isinstance(profile, dict) and isinstance(profile.get("Profile"), str):
names.add(profile["Profile"])
return names
def parse_args() -> argparse.Namespace:
"""Parse arguments for power profile tools."""
parser = argparse.ArgumentParser(description="PortProtonQt power profile tools")
subparsers = parser.add_subparsers(dest="command", required=True)
subparsers.add_parser("get", help="Print active power profile")
set_parser = subparsers.add_parser("set", help="Set active power profile")
set_parser.add_argument("profile", help="Power profile name")
return parser.parse_args()
async def _main() -> int:
args = parse_args()
try:
if args.command == "get":
profile = await get_profile()
if not profile:
return 1
print(profile)
return 0
if args.command == "set":
return 0 if await set_profile(args.profile) else 1
except Exception as error:
logger.debug("Power profile command failed: %s", error)
return 1
return 1
def main() -> int:
return asyncio.run(_main())
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,89 @@
"""Entry point for shortcut and thumbnail generation tools."""
import argparse
import os
import sys
from pathlib import Path
from portprotonqt.cli import normalize_launch_path
def create_shortcut(exe_path: str, game_name: str | None = None) -> bool:
"""Create a PortProtonQt desktop shortcut for an executable."""
from portprotonqt.config import create_desktop_file
from portprotonqt.icon_extractor import generate_thumbnail
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
normalized_path = normalize_launch_path(exe_path)
result = create_desktop_file(normalized_path, game_name)
if not result:
return False
desktop_entry, desktop_path, icon_path = result
if not generate_thumbnail(normalized_path, icon_path, size=128):
logger.error("Failed to generate thumbnail from exe: %s", normalized_path)
desktop_entry = desktop_entry.replace(f"Icon={icon_path}\n", "Icon=\n")
try:
Path(desktop_path).write_text(desktop_entry, encoding="utf-8")
os.chmod(desktop_path, 0o755)
except OSError as error:
logger.error("Failed to save desktop file %s: %s", desktop_path, error)
return False
return True
def create_thumbnail(exe_path: str, output_path: str) -> bool:
"""Create a PNG thumbnail for an executable."""
from portprotonqt.icon_extractor import generate_thumbnail
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
normalized_path = normalize_launch_path(exe_path)
if not normalized_path or not output_path:
return False
try:
output_dir = os.path.dirname(output_path)
if output_dir:
os.makedirs(output_dir, exist_ok=True)
except OSError as error:
logger.error("Failed to prepare thumbnail directory %s: %s", output_path, error)
return False
if not generate_thumbnail(normalized_path, output_path, size=128):
logger.error("Failed to generate thumbnail: %s", normalized_path)
return False
return True
def parse_args():
"""Parse arguments for shortcut tools."""
parser = argparse.ArgumentParser(description="PortProtonQt shortcut tools")
subparsers = parser.add_subparsers(dest="command", required=True)
shortcut_parser = subparsers.add_parser("shortcut", help="Create a desktop shortcut")
shortcut_parser.add_argument("exe_path", help="Path to the executable")
shortcut_parser.add_argument("game_name", help="Name of the game")
thumbnail_parser = subparsers.add_parser("thumbnail", help="Create a PNG thumbnail")
thumbnail_parser.add_argument("exe_path", help="Path to the executable")
thumbnail_parser.add_argument("output_path", help="Path to the output PNG file")
return parser.parse_args()
def main() -> int:
"""Main entry point for shortcut tools."""
args = parse_args()
if args.command == "shortcut":
return 0 if create_shortcut(args.exe_path, args.game_name) else 1
if args.command == "thumbnail":
return 0 if create_thumbnail(args.exe_path, args.output_path) else 1
return 1
if __name__ == "__main__":
sys.exit(main())
-4
View File
@@ -146,7 +146,6 @@ def get_advanced_settings(disabled_text, logical_core_options=None, locale_optio
numa_nodes=None, dist_options=None, prefix_options=None):
"""Get advanced settings configuration."""
from portprotonqt.localization import _
import shutil
advanced_settings = []
if dist_options is None:
@@ -161,7 +160,6 @@ def get_advanced_settings(disabled_text, logical_core_options=None, locale_optio
locale_options = get_available_locale_options()
# 1. Wine Version
# Add System WINE option if available
wine_options = []
wine_value_map = {}
for option in dist_options:
@@ -173,8 +171,6 @@ def get_advanced_settings(disabled_text, logical_core_options=None, locale_optio
wine_options.append(display_name)
else:
wine_options.append(option)
if shutil.which('wine') and _('System WINE') not in wine_options:
wine_options.append(_('System WINE'))
wine_setting = {
'key': 'PW_WINE_USE',
+1 -1
View File
@@ -15,7 +15,7 @@ import websocket
from portprotonqt.logger import get_logger
from portprotonqt.downloader import Downloader
from portprotonqt.dialogs import generate_thumbnail
from portprotonqt.icon_extractor import generate_thumbnail
from portprotonqt.config import (
extract_exec_target_path,
get_portproton_location,
+33 -73
View File
@@ -1,50 +1,16 @@
"""Bluetooth manager worker and service."""
from collections.abc import Callable
import re
import threading
import time
from collections.abc import Callable
from pathlib import Path
from typing import Annotated, Any, cast
from typing import Any
from PySide6.QtCore import QThread, Signal
try:
from dbus_fast import DBusError as _DBusError
from dbus_fast.annotations import DBusSignature as _DBusSignature
from dbus_fast.service import ServiceInterface as _ServiceInterface
from dbus_fast.service import method as _method
except ModuleNotFoundError:
class DBusError(Exception):
"""Fallback D-Bus error when dbus-fast is unavailable."""
class ServiceInterface:
"""Fallback service interface for environments without dbus-fast."""
def __init__(self, _name: str) -> None:
return None
def method(
name: str | None = None,
disabled: bool = False,
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
del name, disabled
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
return func
return decorator
class DBusSignature:
"""Fallback D-Bus signature holder when dbus-fast is unavailable."""
def __init__(self, signature: str) -> None:
self.signature = signature
else:
DBusError = cast(Any, _DBusError)
DBusSignature = cast(Any, _DBusSignature)
ServiceInterface = cast(Any, _ServiceInterface)
method = cast(Any, _method)
from dbus_fast import DBusError
from dbus_fast.service import ServiceInterface, method
from portprotonqt.localization import _
from portprotonqt.logger import get_logger
@@ -71,6 +37,14 @@ BLUEZ_AGENT_MANAGER_PATH = "/org/bluez"
BLUEZ_AGENT_PATH = "/org/portprotonqt/BluetoothAgent"
def dbus_method(annotations: dict[str, str]) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
func.__annotations__ = annotations
return method()(func)
return decorator
class BluezPairingAgent(ServiceInterface):
"""BlueZ Agent1 implementation for interactive pairing."""
@@ -78,11 +52,11 @@ class BluezPairingAgent(ServiceInterface):
super().__init__(BLUEZ_AGENT_INTERFACE)
self._service = service
@method()
@dbus_method({"device": "o", "return": "s"})
def RequestPinCode(
self,
device: Annotated[str, DBusSignature("o")],
) -> Annotated[str, DBusSignature("s")]:
device: str,
) -> str:
response = self._service._request_pairing_input(
_("Bluetooth PIN code"),
_("Enter the Bluetooth PIN code shown on the device"),
@@ -92,19 +66,19 @@ class BluezPairingAgent(ServiceInterface):
raise DBusError("org.bluez.Error.Rejected", "Bluetooth PIN entry cancelled")
return response
@method()
@dbus_method({"_device": "o", "_pincode": "s"})
def DisplayPinCode(
self,
_device: Annotated[str, DBusSignature("o")],
_pincode: Annotated[str, DBusSignature("s")],
_device: str,
_pincode: str,
) -> None:
return None
@method()
@dbus_method({"device": "o", "return": "u"})
def RequestPasskey(
self,
device: Annotated[str, DBusSignature("o")],
) -> Annotated[int, DBusSignature("u")]:
device: str,
) -> int:
response = self._service._request_pairing_input(
_("Bluetooth passkey"),
_("Enter the Bluetooth passkey shown on the device"),
@@ -114,35 +88,35 @@ class BluezPairingAgent(ServiceInterface):
raise DBusError("org.bluez.Error.Rejected", "Bluetooth passkey entry cancelled")
return int(response)
@method()
@dbus_method({"_device": "o", "_passkey": "u", "_entered": "q"})
def DisplayPasskey(
self,
_device: Annotated[str, DBusSignature("o")],
_passkey: Annotated[int, DBusSignature("u")],
_entered: Annotated[int, DBusSignature("q")],
_device: str,
_passkey: int,
_entered: int,
) -> None:
return None
@method()
@dbus_method({"device": "o", "passkey": "u"})
def RequestConfirmation(
self,
device: Annotated[str, DBusSignature("o")],
passkey: Annotated[int, DBusSignature("u")],
device: str,
passkey: int,
) -> None:
message = _("Confirm the passkey on devices: {0}").format(f"{int(passkey):06d}")
approved = self._service._request_pairing_confirm(message, str(device))
if not approved:
raise DBusError("org.bluez.Error.Rejected", "Bluetooth pairing confirmation rejected")
@method()
def RequestAuthorization(self, _device: Annotated[str, DBusSignature("o")]) -> None:
@dbus_method({"_device": "o"})
def RequestAuthorization(self, _device: str) -> None:
return None
@method()
@dbus_method({"_device": "o", "_uuid": "s"})
def AuthorizeService(
self,
_device: Annotated[str, DBusSignature("o")],
_uuid: Annotated[str, DBusSignature("s")],
_device: str,
_uuid: str,
) -> None:
return None
@@ -151,20 +125,6 @@ class BluezPairingAgent(ServiceInterface):
return None
BluezPairingAgent.RequestPinCode.__annotations__ = {"device": "o", "return": "s"}
BluezPairingAgent.DisplayPinCode.__annotations__ = {"_device": "o", "_pincode": "s"}
BluezPairingAgent.RequestPasskey.__annotations__ = {"device": "o", "return": "u"}
BluezPairingAgent.DisplayPasskey.__annotations__ = {
"_device": "o",
"_passkey": "u",
"_entered": "q",
}
BluezPairingAgent.RequestConfirmation.__annotations__ = {"device": "o", "passkey": "u"}
BluezPairingAgent.RequestAuthorization.__annotations__ = {"_device": "o"}
BluezPairingAgent.AuthorizeService.__annotations__ = {"_device": "o", "_uuid": "s"}
BluezPairingAgent.Cancel.__annotations__ = {}
class BluetoothManagerWorker(QThread):
"""Run Bluetooth actions outside the UI thread."""
+3 -28
View File
@@ -4,29 +4,8 @@ import asyncio
import re
from typing import Any
try:
from dbus_fast import BusType as _BusType
from dbus_fast import Variant as _DbusVariant
from dbus_fast.aio import MessageBus as _MessageBus
DBUS_FAST_AVAILABLE = True
except ModuleNotFoundError:
DBUS_FAST_AVAILABLE = False
_BusType = None
_DbusVariant = None
_MessageBus = None
BusType = _BusType
MessageBus = _MessageBus
class _FallbackVariant:
"""Fallback Variant for environments without dbus-fast."""
def __init__(self, _signature: str, value: Any) -> None:
self.value = value
Variant: type[Any] = _DbusVariant if _DbusVariant is not None else _FallbackVariant
from dbus_fast import BusType, Variant
from dbus_fast.aio import MessageBus
def _create_variant(signature: str, value: Any) -> Any:
@@ -57,8 +36,6 @@ class DbusFastSystemBus:
"""Minimal sync wrapper over dbus-fast system bus."""
def __init__(self) -> None:
if not DBUS_FAST_AVAILABLE:
raise NetworkManagerError("dbus-fast is not available")
self._loop = asyncio.new_event_loop()
self._proxy_cache: dict[tuple[str, str], Any] = {}
try:
@@ -67,7 +44,7 @@ class DbusFastSystemBus:
except Exception as exc:
asyncio.set_event_loop(None)
self._loop.close()
raise NetworkManagerError("dbus-fast is not available") from exc
raise NetworkManagerError("Failed to connect to system D-Bus") from exc
def close(self) -> None:
try:
@@ -124,8 +101,6 @@ class DbusFastSystemBus:
return self._loop.run_until_complete(coroutine)
async def _connect(self):
if BusType is None or MessageBus is None:
raise NetworkManagerError("dbus-fast is not available")
return await MessageBus(bus_type=BusType.SYSTEM).connect()
async def _get_interface(self, service: str, path: str, interface: str):
+184 -197
View File
@@ -2,14 +2,16 @@
from typing import Any
from PySide6.QtCore import Qt
from PySide6.QtGui import QPixmap
from PySide6.QtCore import Qt, QRectF
from PySide6.QtGui import QPainter, QPaintEvent, QPixmap
from PySide6.QtSvg import QSvgRenderer
from PySide6.QtWidgets import QHBoxLayout, QLabel, QStackedWidget, QWidget
from portprotonqt.custom_widgets import FlowLayout
from portprotonqt.input_manager import GamepadType
from portprotonqt.localization import _
from portprotonqt.logger import get_logger
from portprotonqt.qt_utils import get_device_pixel_ratio
logger = get_logger(__name__)
@@ -17,6 +19,87 @@ GAMEPAD_HINT_ACTIONS = ("confirm", "back", "add_game", "search", "decrease_size"
COMBINATION_HINT_ACTIONS = ("guide_select", "mouse_emulation")
VOLUME_HINT_ACTIONS = ("decrease_size", "increase_size")
def _load_control_hint_pixmap(paths: tuple[str | None, ...], width: int, height: int) -> QPixmap:
for path in paths:
if path is None:
continue
pixmap = _render_control_hint_path(str(path), width, height)
if not pixmap.isNull():
return pixmap
return QPixmap()
def _render_control_hint_path(path: str, width: int, height: int) -> QPixmap:
device_pixel_ratio = get_device_pixel_ratio()
target_width = max(1, int(width * device_pixel_ratio))
target_height = max(1, int(height * device_pixel_ratio))
if path.lower().endswith(".svg"):
pixmap = QPixmap(target_width, target_height)
pixmap.fill(Qt.GlobalColor.transparent)
pixmap.setDevicePixelRatio(device_pixel_ratio)
painter = QPainter(pixmap)
QSvgRenderer(path).render(painter, QRectF(0, 0, width, height))
painter.end()
return pixmap
pixmap = QPixmap(path)
if pixmap.isNull():
return pixmap
scaled = pixmap.scaled(
target_width,
target_height,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
scaled.setDevicePixelRatio(device_pixel_ratio)
return scaled
def _set_control_hint_icon(label: QLabel, paths: tuple[str | None, ...], width: int, height: int) -> None:
if isinstance(label, _ControlHintIconLabel):
label.set_icon_paths(paths)
return
pixmap = _load_control_hint_pixmap(paths, width, height)
if not pixmap.isNull():
label.setPixmap(pixmap)
class _ControlHintIconLabel(QLabel):
def __init__(self, width: int, height: int) -> None:
super().__init__()
self._icon_path = ""
self._icon_width = width
self._icon_height = height
self.setFixedSize(width, height)
self.setAlignment(Qt.AlignmentFlag.AlignCenter)
def set_icon_paths(self, paths: tuple[str | None, ...]) -> None:
self._icon_path = ""
for path in paths:
if path is None:
continue
if str(path).lower().endswith(".svg"):
renderer = QSvgRenderer(str(path))
if renderer.isValid():
self._icon_path = str(path)
break
continue
pixmap = _render_control_hint_path(str(path), self._icon_width, self._icon_height)
if not pixmap.isNull():
self.setPixmap(pixmap)
return
self.clear()
self.update()
def paintEvent(self, event: QPaintEvent) -> None:
if not self._icon_path:
super().paintEvent(event)
return
painter = QPainter(self)
QSvgRenderer(self._icon_path).render(painter, QRectF(self.rect()))
painter.end()
class MainWindowControlHintsMixin:
"""Provide control hints and navigation icon logic for main window."""
@@ -150,27 +233,16 @@ class MainWindowControlHintsMixin:
layout.setContentsMargins(0, 5, 0, 0)
layout.setSpacing(6)
icon_label = QLabel()
icon_label.setFixedSize(26, 26)
icon_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
pixmap = QPixmap()
for candidate in (
self.theme_manager.get_theme_image(icon_name, self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
):
if candidate is not None and pixmap.load(str(candidate)):
break
if not pixmap.isNull():
icon_label.setPixmap(
pixmap.scaled(
26,
26,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
)
icon_label = _ControlHintIconLabel(26, 26)
_set_control_hint_icon(
icon_label,
(
self.theme_manager.get_theme_image(icon_name, self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
),
26,
26,
)
layout.addWidget(icon_label)
@@ -198,86 +270,56 @@ class MainWindowControlHintsMixin:
layout.setContentsMargins(0, 5, 0, 0)
layout.setSpacing(6)
guide_icon = QLabel()
guide_icon.setFixedSize(26, 26)
guide_icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
pixmap = QPixmap()
for candidate in (
self.theme_manager.get_theme_image("xbox_xbox", self.current_theme_name),
self.theme_manager.get_theme_image("ps_ps", self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
):
if candidate is not None and pixmap.load(str(candidate)):
break
if not pixmap.isNull():
guide_icon.setPixmap(
pixmap.scaled(
26,
26,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
)
guide_icon = _ControlHintIconLabel(26, 26)
_set_control_hint_icon(
guide_icon,
(
self.theme_manager.get_theme_image("xbox_xbox", self.current_theme_name),
self.theme_manager.get_theme_image("ps_ps", self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
),
26,
26,
)
layout.addWidget(guide_icon)
plus_icon = QLabel()
plus_icon.setFixedSize(26, 26)
plus_icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
plus_pixmap = QPixmap()
for candidate in (
self.theme_manager.get_theme_image("key_+", self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
):
if candidate is not None and plus_pixmap.load(str(candidate)):
break
if not plus_pixmap.isNull():
plus_icon.setPixmap(
plus_pixmap.scaled(
26,
26,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
)
plus_icon = _ControlHintIconLabel(26, 26)
_set_control_hint_icon(
plus_icon,
(
self.theme_manager.get_theme_image("key_+", self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
),
26,
26,
)
layout.addWidget(plus_icon)
select_icon = QLabel()
select_icon.setFixedSize(26, 26)
select_icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
select_icon = _ControlHintIconLabel(26, 26)
if action == "mouse_emulation":
pixmap2 = QPixmap()
for candidate in (
self.theme_manager.get_theme_image("xbox_start", self.current_theme_name),
self.theme_manager.get_theme_image("ps_options", self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
):
if candidate is not None and pixmap2.load(str(candidate)):
break
_set_control_hint_icon(
select_icon,
(
self.theme_manager.get_theme_image("xbox_start", self.current_theme_name),
self.theme_manager.get_theme_image("ps_options", self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
),
26,
26,
)
else:
pixmap2 = QPixmap()
for candidate in (
self.theme_manager.get_theme_image("xbox_view", self.current_theme_name),
self.theme_manager.get_theme_image("ps_share", self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
):
if candidate is not None and pixmap2.load(str(candidate)):
break
if not pixmap2.isNull():
select_icon.setPixmap(
pixmap2.scaled(
26,
26,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
_set_control_hint_icon(
select_icon,
(
self.theme_manager.get_theme_image("xbox_view", self.current_theme_name),
self.theme_manager.get_theme_image("ps_share", self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
),
26,
26,
)
layout.addWidget(select_icon)
@@ -317,42 +359,30 @@ class MainWindowControlHintsMixin:
gtype.value,
)
left_pix = QPixmap()
if is_gamepad_connected:
left_icon_name = self.get_nav_icon('left', gtype)
else:
left_icon_name = "key_left"
left_icon = self.theme_manager.get_theme_image(left_icon_name, self.current_theme_name)
if left_icon:
left_pix.load(str(left_icon))
left_pix = _load_control_hint_pixmap(
(self.theme_manager.get_theme_image(left_icon_name, self.current_theme_name),),
32,
32,
)
if not left_pix.isNull():
self.leftNavButton.setPixmap(
left_pix.scaled(
32,
32,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
)
self.leftNavButton.setPixmap(left_pix)
self.leftNavButton.setVisible(True)
right_pix = QPixmap()
if is_gamepad_connected:
right_icon_name = self.get_nav_icon('right', gtype)
else:
right_icon_name = "key_right"
right_icon = self.theme_manager.get_theme_image(right_icon_name, self.current_theme_name)
if right_icon:
right_pix.load(str(right_icon))
right_pix = _load_control_hint_pixmap(
(self.theme_manager.get_theme_image(right_icon_name, self.current_theme_name),),
32,
32,
)
if not right_pix.isNull():
self.rightNavButton.setPixmap(
right_pix.scaled(
32,
32,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
)
self.rightNavButton.setPixmap(right_pix)
self.rightNavButton.setVisible(True)
def updateControlHints(self, *args) -> None:
@@ -405,41 +435,25 @@ class MainWindowControlHintsMixin:
else:
guide_icon_name = "xbox_xbox"
guide_pixmap = QPixmap()
for candidate in (
self.theme_manager.get_theme_image(guide_icon_name, self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
):
if candidate is not None and guide_pixmap.load(str(candidate)):
break
_set_control_hint_icon(
guide_icon,
(
self.theme_manager.get_theme_image(guide_icon_name, self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
),
26,
26,
)
if not guide_pixmap.isNull():
guide_icon.setPixmap(
guide_pixmap.scaled(
26,
26,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
)
plus_pixmap = QPixmap()
for candidate in (
self.theme_manager.get_theme_image("key_+", self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
):
if candidate is not None and plus_pixmap.load(str(candidate)):
break
if not plus_pixmap.isNull():
plus_icon.setPixmap(
plus_pixmap.scaled(
26,
26,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
)
_set_control_hint_icon(
plus_icon,
(
self.theme_manager.get_theme_image("key_+", self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
),
26,
26,
)
select_icon_name = "xbox_view"
if action == "guide_select":
@@ -455,23 +469,15 @@ class MainWindowControlHintsMixin:
else:
select_icon_name = "xbox_start"
select_pixmap = QPixmap()
for candidate in (
self.theme_manager.get_theme_image(select_icon_name, self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
):
if candidate is not None and select_pixmap.load(str(candidate)):
break
if not select_pixmap.isNull():
select_icon.setPixmap(
select_pixmap.scaled(
26,
26,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
)
_set_control_hint_icon(
select_icon,
(
self.theme_manager.get_theme_image(select_icon_name, self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
),
26,
26,
)
else:
if isinstance(icon_element, list):
logger.warning(
@@ -481,34 +487,15 @@ class MainWindowControlHintsMixin:
continue
icon_label = icon_element
icon_name = self.get_button_icon(action, gtype)
icon_path = self.theme_manager.get_theme_image(icon_name, self.current_theme_name)
pixmap = QPixmap()
if icon_path:
pixmap.load(str(icon_path))
if not pixmap.isNull():
icon_label.setPixmap(
pixmap.scaled(
26,
26,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
)
else:
placeholder = self.theme_manager.get_theme_image(
"placeholder",
self.current_theme_name,
)
if placeholder:
pixmap.load(str(placeholder))
icon_label.setPixmap(
pixmap.scaled(
26,
26,
Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation,
)
)
_set_control_hint_icon(
icon_label,
(
self.theme_manager.get_theme_image(icon_name, self.current_theme_name),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
),
26,
26,
)
else:
container.setVisible(False)
else:
+22 -22
View File
@@ -461,18 +461,18 @@ class MainWindowSystemTabMixin(_MainWindowTypingBase):
self.networkActionButtonsWidget = QWidget()
buttons_layout = QHBoxLayout(self.networkActionButtonsWidget)
buttons_layout.setContentsMargins(0, 0, 0, 0)
self.systemRefreshButton = AutoSizeButton(_("Refresh"), icon=self.theme_manager.get_icon("update"))
self.systemRefreshButton = AutoSizeButton(_("Refresh"), icon=self.theme_manager.get_icon("update", as_path=True))
self.systemRefreshButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.systemRefreshButton.clicked.connect(self.loadSystemNetworks)
buttons_layout.addWidget(self.systemRefreshButton)
self.networkConnectButton = AutoSizeButton(_("Connect"), icon=self.theme_manager.get_icon("login"))
self.networkConnectButton = AutoSizeButton(_("Connect"), icon=self.theme_manager.get_icon("login", as_path=True))
self.networkDisconnectButton = AutoSizeButton(_("Disconnect"), icon=self.theme_manager.get_icon("stop"))
self.networkDisconnectButton = AutoSizeButton(_("Disconnect"), icon=self.theme_manager.get_icon("stop", as_path=True))
self.networkForgetButton = AutoSizeButton(_("Forget"), icon=self.theme_manager.get_icon("delete"))
self.networkForgetButton = AutoSizeButton(_("Forget"), icon=self.theme_manager.get_icon("delete", as_path=True))
self.networkShareButton = AutoSizeButton(_("Share"), icon=self.theme_manager.get_icon("menu"))
self.networkShareButton = AutoSizeButton(_("Share"), icon=self.theme_manager.get_icon("menu", as_path=True))
buttons_layout.addStretch()
layout.addWidget(self.networkActionButtonsWidget)
@@ -503,16 +503,16 @@ class MainWindowSystemTabMixin(_MainWindowTypingBase):
layout.addWidget(self.vpnTable)
vpn_layout = QHBoxLayout()
self.vpnConnectButton = AutoSizeButton(_("Connect"), icon=self.theme_manager.get_icon("login"))
self.vpnConnectButton = AutoSizeButton(_("Connect"), icon=self.theme_manager.get_icon("login", as_path=True))
self.vpnDisconnectButton = AutoSizeButton(_("Disconnect"), icon=self.theme_manager.get_icon("stop"))
self.vpnDisconnectButton = AutoSizeButton(_("Disconnect"), icon=self.theme_manager.get_icon("stop", as_path=True))
self.vpnAddButton = AutoSizeButton(_("Add"), icon=self.theme_manager.get_icon("folder"))
self.vpnAddButton = AutoSizeButton(_("Add"), icon=self.theme_manager.get_icon("folder", as_path=True))
self.vpnAddButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.vpnAddButton.clicked.connect(self.addVpnProfile)
vpn_layout.addWidget(self.vpnAddButton)
self.vpnDeleteButton = AutoSizeButton(_("Delete"), icon=self.theme_manager.get_icon("delete"))
self.vpnDeleteButton = AutoSizeButton(_("Delete"), icon=self.theme_manager.get_icon("delete", as_path=True))
layout.addLayout(vpn_layout)
def _setupSystemBluetoothControls(self, layout) -> None:
@@ -577,21 +577,21 @@ class MainWindowSystemTabMixin(_MainWindowTypingBase):
def _setupSystemBluetoothActionButtons(self, layout) -> None:
buttons_layout = QHBoxLayout()
self.bluetoothRefreshButton = AutoSizeButton(_("Refresh"), icon=self.theme_manager.get_icon("update"))
self.bluetoothRefreshButton = AutoSizeButton(_("Refresh"), icon=self.theme_manager.get_icon("update", as_path=True))
self.bluetoothRefreshButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.bluetoothRefreshButton.clicked.connect(self.loadSystemBluetoothDevices)
buttons_layout.addWidget(self.bluetoothRefreshButton)
self.bluetoothScanButton = AutoSizeButton(_("Scan"), icon=self.theme_manager.get_icon("search"))
self.bluetoothScanButton = AutoSizeButton(_("Scan"), icon=self.theme_manager.get_icon("search", as_path=True))
self.bluetoothScanButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.bluetoothScanButton.clicked.connect(self.scanSystemBluetoothDevices)
buttons_layout.addWidget(self.bluetoothScanButton)
self.bluetoothConnectButton = AutoSizeButton(_("Connect"), icon=self.theme_manager.get_icon("login"))
self.bluetoothConnectButton = AutoSizeButton(_("Connect"), icon=self.theme_manager.get_icon("login", as_path=True))
self.bluetoothDisconnectButton = AutoSizeButton(_("Disconnect"), icon=self.theme_manager.get_icon("stop"))
self.bluetoothDisconnectButton = AutoSizeButton(_("Disconnect"), icon=self.theme_manager.get_icon("stop", as_path=True))
self.bluetoothForgetButton = AutoSizeButton(_("Forget"), icon=self.theme_manager.get_icon("delete"))
self.bluetoothForgetButton = AutoSizeButton(_("Forget"), icon=self.theme_manager.get_icon("delete", as_path=True))
buttons_layout.addStretch()
layout.addLayout(buttons_layout)
@@ -631,14 +631,14 @@ class MainWindowSystemTabMixin(_MainWindowTypingBase):
def _setupSystemStorageActionButtons(self, layout) -> None:
buttons_layout = QHBoxLayout()
self.storageRefreshButton = AutoSizeButton(_("Refresh"), icon=self.theme_manager.get_icon("update"))
self.storageRefreshButton = AutoSizeButton(_("Refresh"), icon=self.theme_manager.get_icon("update", as_path=True))
self.storageRefreshButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.storageRefreshButton.clicked.connect(self.loadSystemStorageDevices)
buttons_layout.addWidget(self.storageRefreshButton)
self.storageMountButton = AutoSizeButton(_("Mount"), icon=self.theme_manager.get_icon("login"))
self.storageMountButton = AutoSizeButton(_("Mount"), icon=self.theme_manager.get_icon("login", as_path=True))
self.storageUnmountButton = AutoSizeButton(_("Unmount"), icon=self.theme_manager.get_icon("stop"))
self.storageUnmountButton = AutoSizeButton(_("Unmount"), icon=self.theme_manager.get_icon("stop", as_path=True))
buttons_layout.addStretch()
layout.addLayout(buttons_layout)
@@ -703,12 +703,12 @@ class MainWindowSystemTabMixin(_MainWindowTypingBase):
def _setupSystemAudioActionButtons(self, layout) -> None:
buttons_layout = QHBoxLayout()
self.audioRefreshButton = AutoSizeButton(_("Refresh"), icon=self.theme_manager.get_icon("update"))
self.audioRefreshButton = AutoSizeButton(_("Refresh"), icon=self.theme_manager.get_icon("update", as_path=True))
self.audioRefreshButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.audioRefreshButton.clicked.connect(self.loadSystemAudioDevices)
buttons_layout.addWidget(self.audioRefreshButton)
self.audioSetOutputButton = AutoSizeButton(_("Set output"), icon=self.theme_manager.get_icon("login"))
self.audioSetOutputButton = AutoSizeButton(_("Set output"), icon=self.theme_manager.get_icon("login", as_path=True))
self.audioSetOutputButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.audioSetOutputButton.clicked.connect(self.setSelectedAudioSinkDefault)
buttons_layout.addWidget(self.audioSetOutputButton)
@@ -867,17 +867,17 @@ class MainWindowSystemTabMixin(_MainWindowTypingBase):
def _setupSystemPowerActionButtons(self, layout) -> None:
buttons_layout = QHBoxLayout()
self.systemRebootButton = AutoSizeButton(_("Reboot"), icon=self.theme_manager.get_icon("reboot"))
self.systemRebootButton = AutoSizeButton(_("Reboot"), icon=self.theme_manager.get_icon("reboot", as_path=True))
self.systemRebootButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.systemRebootButton.clicked.connect(self.rebootSystem)
buttons_layout.addWidget(self.systemRebootButton)
self.systemShutdownButton = AutoSizeButton(_("Shutdown"), icon=self.theme_manager.get_icon("shutdown"))
self.systemShutdownButton = AutoSizeButton(_("Shutdown"), icon=self.theme_manager.get_icon("shutdown", as_path=True))
self.systemShutdownButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.systemShutdownButton.clicked.connect(self.shutdownSystem)
buttons_layout.addWidget(self.systemShutdownButton)
self.systemSuspendButton = AutoSizeButton(_("Suspend"), icon=self.theme_manager.get_icon("suspend"))
self.systemSuspendButton = AutoSizeButton(_("Suspend"), icon=self.theme_manager.get_icon("suspend", as_path=True))
self.systemSuspendButton.setStyleSheet(self.theme.ACTION_BUTTON_STYLE)
self.systemSuspendButton.clicked.connect(self.suspendSystem)
buttons_layout.addWidget(self.systemSuspendButton)
@@ -0,0 +1,36 @@
# Adwaita Theme
foreground #eeeeec
background #1e1e1e
selection_foreground #ffffff
selection_background #3584e4
background_opacity 1.0
cursor_shape block
enable_audio_bell no
# Black
color0 #1e1e1e
color8 #555753
# Red
color1 #cc0000
color9 #ef2929
# Green
color2 #4e9a06
color10 #8ae234
# Yellow
color3 #c4a000
color11 #fce94f
# Blue
color4 #3465a4
color12 #729fcf
# Magenta
color5 #75507b
color13 #ad7fa8
# Cyan
color6 #06989a
color14 #34e2e2
# White
color7 #d3d7cf
color15 #eeeeec
font_size 14
font_family Monospace
+36
View File
@@ -0,0 +1,36 @@
# Breeze Theme
foreground #eff0f1
background #232629
selection_foreground #eff0f1
selection_background #3daee9
background_opacity 1.0
cursor_shape block
enable_audio_bell no
# Black
color0 #232629
color8 #7f8c8d
# Red
color1 #ed1515
color9 #c0392b
# Green
color2 #11d116
color10 #1cdc9a
# Yellow
color3 #f67400
color11 #fdbc4b
# Blue
color4 #1d99f3
color12 #3daee9
# Magenta
color5 #9b59b6
color13 #8e44ad
# Cyan
color6 #1abc9c
color14 #16a085
# White
color7 #eff0f1
color15 #ffffff
font_size 14
font_family Monospace
@@ -0,0 +1,36 @@
# Default Theme
foreground #d4d4d4
background #1e1e1e
selection_foreground #ffffff
selection_background #264f78
background_opacity 1.0
cursor_shape block
enable_audio_bell no
# Black
color0 #000000
color8 #666666
# Red
color1 #cd3131
color9 #f14c4c
# Green
color2 #0dbc79
color10 #23d18b
# Yellow
color3 #e5e510
color11 #f5f543
# Blue
color4 #2472c8
color12 #3b8eea
# Magenta
color5 #bc3fbc
color13 #d670d6
# Cyan
color6 #11a8cd
color14 #29b8db
# White
color7 #e5e5e5
color15 #e5e5e5
font_size 14
font_family Monospace
@@ -0,0 +1,36 @@
# Dracula Theme
foreground #f8f8f2
background #282a36
selection_foreground #ffffff
selection_background #44475a
background_opacity 1.0
cursor_shape block
enable_audio_bell no
# Black
color0 #21222c
color8 #6272a4
# Red
color1 #ff5555
color9 #ff6e6e
# Green
color2 #50fa7b
color10 #69ff94
# Yellow
color3 #f1fa8c
color11 #ffffa5
# Blue
color4 #bd93f9
color12 #d6acff
# Magenta
color5 #ff79c6
color13 #ff92df
# Cyan
color6 #8be9fd
color14 #a4ffff
# White
color7 #f8f8f2
color15 #ffffff
font_size 14
font_family Monospace
+36
View File
@@ -0,0 +1,36 @@
# GNOME Theme
foreground #d0cfcc
background #171421
selection_foreground #ffffff
selection_background #12488b
background_opacity 1.0
cursor_shape block
enable_audio_bell no
# Black
color0 #171421
color8 #5e5c64
# Red
color1 #c01c28
color9 #f66151
# Green
color2 #26a269
color10 #33d17a
# Yellow
color3 #a2734c
color11 #e9ad0c
# Blue
color4 #12488b
color12 #2a7bde
# Magenta
color5 #a347ba
color13 #c061cb
# Cyan
color6 #2aa1b3
color14 #33c7de
# White
color7 #d0cfcc
color15 #ffffff
font_size 14
font_family Monospace
@@ -0,0 +1,36 @@
# Gruvbox Dark Theme
foreground #ebdbb2
background #282828
selection_foreground #ebdbb2
selection_background #504945
background_opacity 1.0
cursor_shape block
enable_audio_bell no
# Black
color0 #282828
color8 #928374
# Red
color1 #cc241d
color9 #fb4934
# Green
color2 #98971a
color10 #b8bb26
# Yellow
color3 #d79921
color11 #fabd2f
# Blue
color4 #458588
color12 #83a598
# Magenta
color5 #b16286
color13 #d3869b
# Cyan
color6 #689d6a
color14 #8ec07c
# White
color7 #a89984
color15 #ebdbb2
font_size 14
font_family Monospace
+36
View File
@@ -0,0 +1,36 @@
# Nord Theme
foreground #d8dee9
background #2e3440
selection_foreground #d8dee9
selection_background #434c5e
background_opacity 1.0
cursor_shape block
enable_audio_bell no
# Black
color0 #3b4252
color8 #4c566a
# Red
color1 #bf616a
color9 #bf616a
# Green
color2 #a3be8c
color10 #a3be8c
# Yellow
color3 #ebcb8b
color11 #ebcb8b
# Blue
color4 #81a1c1
color12 #81a1c1
# Magenta
color5 #b48ead
color13 #b48ead
# Cyan
color6 #88c0d0
color14 #8fbcbb
# White
color7 #e5e9f0
color15 #eceff4
font_size 14
font_family Monospace
@@ -0,0 +1,36 @@
# Solarized Dark Theme
foreground #839496
background #002b36
selection_foreground #93a1a1
selection_background #073642
background_opacity 1.0
cursor_shape block
enable_audio_bell no
# Black
color0 #073642
color8 #002b36
# Red
color1 #dc322f
color9 #cb4b16
# Green
color2 #859900
color10 #586e75
# Yellow
color3 #b58900
color11 #657b83
# Blue
color4 #268bd2
color12 #839496
# Magenta
color5 #d33682
color13 #6c71c4
# Cyan
color6 #2aa198
color14 #93a1a1
# White
color7 #eee8d5
color15 #fdf6e3
font_size 14
font_family Monospace
@@ -0,0 +1,30 @@
# Solarized Light Theme (Kitty Original)
foreground #52676f
background #fdf6e3
cursor #52676f
selection_foreground #fcf4dc
selection_background #e9e2cb
background_opacity 1.0
cursor_shape block
enable_audio_bell no
# Palette
color0 #e4e4e4
color8 #ffffd7
color1 #d70000
color9 #d75f00
color2 #5f8700
color10 #585858
color3 #af8700
color11 #626262
color4 #0087ff
color12 #808080
color5 #af005f
color13 #5f5faf
color6 #00afaf
color14 #8a8a8a
color7 #262626
color15 #1c1c1c
font_size 14
font_family Monospace
+23
View File
@@ -0,0 +1,23 @@
background #300a24
foreground #eeeeec
cursor #bbbbbb
selection_background #b4d5ff
cursor_shape block
enable_audio_bell no
color0 #2e3436
color8 #555753
color1 #cc0000
color9 #ef2929
color2 #4e9a06
color10 #8ae234
color3 #c4a000
color11 #fce94f
color4 #3465a4
color12 #729fcf
color5 #75507b
color13 #ad7fa8
color6 #06989a
color14 #34e2e2
color7 #d3d7cf
color15 #eeeeec
selection_foreground #300a24
+42 -4
View File
@@ -7,8 +7,11 @@ from portprotonqt.theme_security import (
is_safe_font_file,
is_safe_image_file,
)
from PySide6.QtGui import QIcon, QFontDatabase, QPixmap
from PySide6.QtCore import QRectF, Qt
from PySide6.QtGui import QIcon, QFontDatabase, QPainter, QPixmap
from PySide6.QtSvg import QSvgRenderer
from portprotonqt.config import ui_config, load_theme_metainfo
from portprotonqt.qt_utils import get_device_pixel_ratio
# Icon caching for performance optimization
_icon_cache = {}
@@ -26,6 +29,40 @@ THEMES_DIRS = [
]
_loaded_theme = None
def _load_icon(icon_path: str) -> QIcon:
"""Load theme icon with device pixel ratio for crisp raster icons."""
if icon_path.lower().endswith(".svg"):
return _load_svg_icon(icon_path)
pixmap = QPixmap(icon_path)
if pixmap.isNull():
return QIcon(icon_path)
device_pixel_ratio = get_device_pixel_ratio()
if device_pixel_ratio > 1.0:
pixmap.setDevicePixelRatio(device_pixel_ratio)
return QIcon(pixmap)
def _load_svg_icon(icon_path: str) -> QIcon:
"""Render SVG icon into high-DPI pixmaps for Qt icon users."""
renderer = QSvgRenderer(icon_path)
if not renderer.isValid():
return QIcon(icon_path)
icon = QIcon()
device_pixel_ratio = get_device_pixel_ratio()
for size in (16, 20, 22, 24, 32, 48, 64):
target_size = max(1, int(size * device_pixel_ratio))
pixmap = QPixmap(target_size, target_size)
pixmap.fill(Qt.GlobalColor.transparent)
pixmap.setDevicePixelRatio(device_pixel_ratio)
painter = QPainter(pixmap)
renderer.render(painter, QRectF(0, 0, size, size))
painter.end()
icon.addPixmap(pixmap)
return icon
def _is_valid_theme_name(theme_name: str) -> bool:
"""Return True when theme name is safe to use in filesystem paths."""
@@ -520,7 +557,9 @@ class ThemeManager:
If as_path=True, return icon path instead of QIcon.
"""
# Create cache key
cache_key = f"{icon_name}_{theme_name or self.current_theme_name}_{as_path}"
theme_name = theme_name or self.current_theme_name
device_pixel_ratio = 1.0 if as_path else get_device_pixel_ratio()
cache_key = f"{icon_name}_{theme_name}_{as_path}_{device_pixel_ratio}"
# Check if we already have this icon cached
if cache_key in _icon_cache:
@@ -528,7 +567,6 @@ class ThemeManager:
return _icon_cache[cache_key]
icon_path = None
theme_name = theme_name or self.current_theme_name
# Extract base name without extension if present
supported_extensions = SUPPORTED_IMAGE_EXTENSIONS
@@ -558,7 +596,7 @@ class ThemeManager:
return icon_path
# Create QIcon and cache it
icon = QIcon(icon_path)
icon = _load_icon(icon_path)
_icon_cache[cache_key] = icon
return icon
Binary file not shown.

Before

Width:  |  Height:  |  Size: 554 KiB

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 535 KiB

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 234 KiB

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 197 KiB

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 168 KiB

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 69 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 13 KiB

Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more