Compare commits

...
668 Commits
Author SHA1 Message Date
Boria138 300c08626b bump to 0.1.12
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-17 12:52:08 +05:00
Boria138 c573f45337 chore localization update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-16 18:30:37 +05:00
Boria138 4321d215ea chore(settings): drop PW_USE_SAREK_ASYNC
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-16 18:29:55 +05:00
Boria138 662f0bf494 fix(polkit): allow ppqtos child nmcli for VPN import
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-16 14:01:02 +05:00
Boria138 75f216ca6c chore(agents): added sign and license rule
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-16 12:21:48 +05:00
Boria138 c462925477 chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-16 12:09:57 +05:00
Boria138 2a34b08a0a chore(system): drop scan from Wi-Fi
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-16 11:47:10 +05:00
Boria138 33fd22af23 chore(system): replace Wi-Fi show hide text to icon
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-16 11:42:57 +05:00
Boria138 a7d43068ed fix(system): migrate to dbus and drop bluetoothctl
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-16 11:34:43 +05:00
Boria138 d522ece132 fix(system): fix bluetooth with passkey
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-16 09:38:10 +05:00
Codeberg TranslateandBoria138 dab39e2821 Translated using Weblate (Russian)
Currently translated at 100.0% (662 of 662 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
Translation: PortProtonQt/PortProtonQt
2026-04-15 13:31:23 +00:00
Codeberg TranslateandBoria138 d7121db730 Translated using Weblate (Russian)
Currently translated at 100.0% (662 of 662 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
Translation: PortProtonQt/PortProtonQt
2026-04-15 13:27:49 +00:00
Boria138 4a44d95055 I forget update po oops
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-15 18:25:53 +05:00
Boria138 ae084974dd refactor: trim system i18n keys and simplify UI labels
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-15 18:24:17 +05:00
Codeberg TranslateandBoria138 1cb7d08479 Translated using Weblate (Russian)
Currently translated at 99.3% (660 of 664 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
Translation: PortProtonQt/PortProtonQt
2026-04-15 13:17:26 +00:00
Boria138 980fb964b7 refactor: reduce i18n scope for system tab and managers
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-15 18:00:22 +05:00
Boria138 7aa3b04ff4 chore(locale): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-15 13:58:50 +05:00
Boria138 68829bc00b chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-15 13:34:36 +05:00
Boria138 71a8ebd89a feat: added system tab with wifi and bluetooth
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-15 08:31:20 +00:00
Boria138 b17575dece fix: open launch file via IPC in existing app instance
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-13 10:29:48 +05:00
Boria138 60135211e5 feat: fix stop icon after wine download during launch
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-12 17:37:31 +05:00
Boria138 082be63f7d fix: parse MangoHud and Gamescope toggles from PPDB 2026-04-12 13:57:40 +05:00
Boria138 fc5572a262 fix: prevent badge overlay on app startup
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-09 22:51:11 +05:00
Boria138 ab67e9bf4e fix: allow hidden badge_view_mode from ui config
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-09 22:41:28 +05:00
Codeberg TranslateandBoria138 a7ae3b834f Translated using Weblate (Russian)
Currently translated at 100.0% (619 of 619 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
Translation: PortProtonQt/PortProtonQt
2026-04-09 16:27:09 +00:00
Boria138 00b0c0fdfc feat: Add hidden badge mode
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-09 21:24:24 +05:00
Boria138 cf46e3b67f feat: Add Steam compat tool toggle to settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-09 21:13:46 +05:00
Boria138 044abe9543 fix: reorder MangoHud Actions section above Presets
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-09 18:27:20 +05:00
Boria138 07da5368b2 chore(build): added dummy dependency linker for ALT Linux
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-09 13:01:14 +05:00
Codeberg TranslateandBoria138 f40b93b6ed Translated using Weblate (Russian)
Currently translated at 100.0% (617 of 617 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
Translation: PortProtonQt/PortProtonQt
2026-04-08 15:47:09 +00:00
Boria138 4db56869d1 fix: avoid /dev/stdout in autoinstall log
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-08 20:43:33 +05:00
Boria138 0e782b3463 feat: refine MangoHud preset sections
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-08 20:36:55 +05:00
Boria138 9bc1760107 fix: enlarge and center compact badge icons at 1.5x
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-08 20:10:49 +05:00
Boria138 ce6a28c2d9 fix: use anticheat slug for AWACY links and cache refresh
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-08 17:49:35 +05:00
Boria138 a8dfc19b04 chore: drop default WINE button in wine settings tab
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-07 09:29:52 +05:00
Boria138 8e87c2183c Revert "fix: correct gamepad face button mapping"
This reverts commit 5beec85ee8.
2026-04-07 09:20:28 +05:00
Boria138 5070f1fdc7 fix: refresh library grid after game card deletion
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-07 09:17:27 +05:00
Boria138 5beec85ee8 fix: correct gamepad face button mapping
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-06 18:52:22 +05:00
Boria138 a964b2882e fix: restore library loading after fast cli launch
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-05 18:07:25 +05:00
Boria138 14c5b0406a fix: detect bluetooth gamepad scroll axis
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-04 20:34:40 +05:00
Boria138 0adc218908 fix: update GameCard Property declarations for PySide6
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-04 09:47:37 +05:00
Boria138 ccdf79f89f fix(settings): block PW_USE_SAREK_ASYNC for Steam games
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-03 14:38:54 +05:00
Boria138 650653399b fix(settings): block D3D Extras and return EAC for Steam games
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-03 10:16:31 +05:00
Boria138 ad565ea3e5 fix(settings): block Galium Nine for Steam games
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-02 20:03:47 +05:00
Boria138 771fc8990a fix(settings): block EAC and BE runtime for Steam games
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-02 19:54:40 +05:00
Boria138 e8cc1f919e fix: remove runtime ExeSettingsDialog cast in Gamescope settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-02 19:06:02 +05:00
Boria138 9a6a83db23 fix: remove runtime ExeSettingsDialog cast in MangoHud settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-02 19:03:56 +05:00
Boria138 4f823d4ebc refactor: move MangoHud layout section below switches
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-02 18:54:37 +05:00
Boria138 28d3333269 fix: preserve toggle settings order in dialog
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-02 18:46:48 +05:00
Boria138 4bce23b83c chore(locale): add localized comments to desktop file
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-02 12:26:07 +05:00
Codeberg TranslateandBoria138 471a9c1099 Translated using Weblate (Russian)
Currently translated at 100.0% (621 of 621 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
Translation: PortProtonQt/PortProtonQt
2026-04-02 05:41:04 +00:00
Boria138 a291c54e14 feat: add toggle buttons for MangoHud and Gamescope in settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-02 10:37:50 +05:00
Boria138 53bc799e4f refactor: reorder toggle settings in logical groups
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-02 09:17:25 +05:00
Boria138 b48fbd3383 fix: normalize Gamescope args before change detection
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-02 00:07:55 +05:00
Boria138 91b434a5d9 chore(data): drop unneded now linux-gaming_topics
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-04-01 11:26:53 +05:00
Gitea Actions ac1ed68b86 chore: update steam apps list 2026-04-01T00:01:47Z 2026-04-01 00:01:48 +00:00
Boria138 50f1fbd1d6 fix: remove deprecated AST node usage in theme checks
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-31 20:38:50 +05:00
Boria138 fa93eacd3a rework blocked check style
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-31 20:34:10 +05:00
Boria138 1f72d6edb6 Revert "fix(theme-security): harden custom theme loading and validation"
This reverts commit 605b80850f.
2026-03-31 19:05:52 +05:00
Boria138 605b80850f fix(theme-security): harden custom theme loading and validation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-30 21:52:01 +05:00
Boria138 78d04a7a5f Reapply "fix: improve theme fallbacks for preloader and custom themes"
This reverts commit 02ab53c996.
2026-03-30 21:10:55 +05:00
Boria138 007713f1be chore: drop renovate i'm too lazy for fix rate limit
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-30 10:23:41 +05:00
Boria138 a28465fd7f fix: simplify file URI handling in CLI path normalization
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-30 10:13:41 +05:00
Boria138 21696eea9b feat(settings): add custom preset buttons for Gamescope
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-29 19:06:02 +05:00
Boria138 4d732c8f22 fix(cli): support file:// URIs from pcmanfm for launch files
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-29 19:02:23 +05:00
Boria138 8cee173ed2 feat: add remove Steam compat tool CLI flag 2026-03-29 16:15:33 +05:00
Boria138 02ab53c996 Revert "fix: improve theme fallbacks for preloader and custom themes"
This reverts commit 04ca284807.
2026-03-29 15:27:06 +05:00
Boria138 04ca284807 fix: improve theme fallbacks for preloader and custom themes
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-29 15:20:55 +05:00
Boria138 c12e1996cb feat(cli): add reinstall option to shell completions
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-28 23:51:38 +05:00
Boria138 76e922a431 feat(cli): added --reinstall-steam-compat-tool
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-28 23:45:40 +05:00
Codeberg TranslateandBoria138 51e903e961 Translated using Weblate (Russian)
Currently translated at 100.0% (615 of 615 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
Translation: PortProtonQt/PortProtonQt
2026-03-28 17:34:27 +00:00
Codeberg TranslateandBoria138 052a804c14 Translated using Weblate (Spanish)
Currently translated at 1.3% (8 of 615 strings)

Co-authored-by: Boria138 <boria138@noreply.codeberg.org>
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/es/
Translation: PortProtonQt/PortProtonQt
2026-03-28 17:34:27 +00:00
Boria138 f2a2013ba7 chore: clean MangoHud preview warnings ignore
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-28 20:16:55 +05:00
Boria138 0f394b8974 Translated using Weblate (Russian)
Currently translated at 100.0% (617 of 617 strings)

Translation: PortProtonQt/PortProtonQt
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
2026-03-28 14:42:47 +00:00
Boria138 a1817abe65 chore(localization): unify
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-28 19:42:25 +05:00
Boria138 1a48635582 chore(localization): simplify Mangohud preview error text
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-28 19:32:22 +05:00
Boria138 183dbb8253 Translated using Weblate (Russian)
Currently translated at 100.0% (614 of 614 strings)

Translation: PortProtonQt/PortProtonQt
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
2026-03-28 14:27:45 +00:00
Boria138 d2f21aa585 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-28 19:27:13 +05:00
Boria138 eb6e4dcb40 feat: add default WINE button in wine settings tab
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-28 19:25:56 +05:00
Boria138 a1f2913e88 feat(mangohud): added preview
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-28 17:45:51 +05:00
Boria138 841da7eed0 feat(settings): block gstreamer/runtime/dgvoodoo2 for Steam games
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-28 12:33:51 +05:00
Boria138 bb1f3ba1ee chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-28 10:53:58 +05:00
Boria138 a3b9e8b5e1 fix: make virtual keyboard width responsive
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-28 10:49:58 +05:00
Boria138 c7f3ee79bb fix(input_manager): resolve combobox tab-switch regression from 169ff00 2026-03-27 21:41:32 +05:00
Boria138 2aab2b0286 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-27 20:56:39 +05:00
Boria138 ca3fd2947a refactor: remove screenshot captions
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-27 20:54:56 +05:00
Boria138 627d708e81 fix: keep PPQt settings tab active after save
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-27 20:04:12 +05:00
Boria138 513c9872da Revert "fix: drop from Steam LD_LIBRARY_PATH only curl"
This reverts commit 26aa44c0d4.
2026-03-27 12:44:27 +05:00
Boria138 26aa44c0d4 fix: drop from Steam LD_LIBRARY_PATH only curl
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-26 21:18:15 +05:00
Boria138 53664b2ab7 fix: lock 3D Api field in Steam game settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-25 16:15:45 +05:00
Boria138 6e07e56741 Translated using Weblate (Russian)
Currently translated at 100.0% (612 of 612 strings)

Translation: PortProtonQt/PortProtonQt
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
2026-03-25 06:57:34 +00:00
Boria138 dd22838e25 chore: drop PPQT_GUI
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-24 20:49:20 +05:00
Boria138 fa721ad84c fix(locales): update only entries
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-24 10:53:27 +05:00
Boria138 8a1a1582a2 fix: lock prefix field in Steam game settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-24 10:45:12 +05:00
Boria138 4a2649a33d chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-24 10:41:36 +05:00
Boria138 cd39183e47 fix: replace Steam Add Game button with Open Game Folder
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-24 10:39:16 +05:00
Boria138 de004667d4 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-23 23:53:36 +05:00
Boria138 8c0f8bb657 feat: add MangoHud system config export button
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-23 23:53:04 +05:00
Boria138 ae8c264da7 fix: dont unset ld preload
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-23 20:51:28 +05:00
Boria138 b1f5b001b2 chore: Prefer 7zz over 7z when extracting ISO files.
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-23 19:33:16 +05:00
Boria138 cf80c92a5d fix: replace udisks ISO flow with pure 7z extraction
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-23 19:25:46 +05:00
Boria138 2c1cd96e43 chore(build): added udisks2 dep for ISO mount
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-23 18:33:55 +05:00
Boria138 ca0293474b chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-23 18:23:07 +05:00
Boria138 3408d71003 feat: add ISO launch support
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-23 18:21:26 +05:00
Boria138 4a0378686d fix: start from steam
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-23 12:53:39 +05:00
Boria138 30ddac4cab chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-23 10:56:49 +05:00
Boria138 cb2c3baf10 fix: resolve .desktop lookup via custom_data metadata 2026-03-23 10:35:53 +05:00
Boria138 bf65f451d1 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 22:27:54 +05:00
Boria138 7a02b6b666 fix: resolve stats by exact exe path and clean on delete
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 22:27:48 +05:00
Boria138 0b5013df2b chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 21:08:00 +05:00
Boria138 2e7a977fec fix: refresh tray submenus on tray menu open
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 21:06:49 +05:00
Boria138 dc0a402113 fix: sync autostart checkbox with desktop file presence
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 17:13:03 +05:00
Boria138 d53a5f7ce9 fix: prioritize custom/steam/sgdb/exe cover on CLI launch
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 16:56:19 +05:00
Boria138 b0b1bf2fcb chore(localization): compile locales after extract
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 16:32:44 +05:00
Boria138 7de71798b9 chore(build): fix locales generate
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 16:18:02 +05:00
Simple16 39e92cf437 Translated using Weblate (Russian)
Currently translated at 100.0% (609 of 609 strings)

Translation: PortProtonQt/PortProtonQt
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
2026-03-22 09:54:54 +00:00
Boria138 d7071c84e7 Translated using Weblate (Spanish)
Currently translated at 0.6% (4 of 609 strings)

Translation: PortProtonQt/PortProtonQt
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/es/
2026-03-22 09:54:54 +00:00
Boria138 4dcd845978 fix: use direct venv binary in xdg autostart Exec
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 14:54:29 +05:00
Boria138 4dcf257a38 i18n: reduce Weblate conflicts in l10n updates
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 14:24:51 +05:00
Boria138 9782de831b Translated using Weblate (Russian)
Currently translated at 100.0% (609 of 609 strings)

Translation: PortProtonQt/PortProtonQt
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/ru/
2026-03-22 09:08:17 +00:00
Boria138 4d367abcc5 chore(localization): drop mo for avoid weblate conflict
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 14:02:44 +05:00
Boria138 ced8e6a2b9 chore(localization): fix dev script
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 13:51:12 +05:00
Boria138 72821f1ac6 chore(localization): update pot
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-22 09:56:33 +05:00
Boria138 a46959f7db Revert "chore(localization): add initial es AI translate for test Codeberg sync"
This reverts commit 813275a049.
2026-03-22 09:55:19 +05:00
Boria138 31f28eba1e fix: route autoinstall process output to stdout
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-21 20:47:25 +05:00
Boria138 33f26f9559 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-21 19:23:35 +05:00
Boria138 28884e56c1 feat: add xdg autostart and start-in-tray settings 2026-03-21 19:18:17 +05:00
Boria138 9bdbbb6b30 fix: handle clicked bool in run-after exe selector 2026-03-21 12:58:20 +05:00
Boria138 24eb968371 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-21 12:19:14 +05:00
Boria138 89090409a4 feat: add PW_RUN_AFTER_EXE picker in exe settings 2026-03-21 12:17:04 +05:00
Boria138 813275a049 chore(localization): add initial es AI translate for test Codeberg sync
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-20 22:16:42 +05:00
Boria138 674bcec476 build: add Codeberg Translate url to metainfo
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-20 14:08:39 +05:00
Boria138 4210f43130 docs: add Codeberg Translate widget and update localization guide
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-20 14:04:53 +05:00
Boria138 7518e948e7 chore(localization): fix weblate checks
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-20 13:49:45 +05:00
Boria138 1543b3b42b chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-20 13:39:34 +05:00
Boria138 5a9bd455e1 chore(tranlations): drop unneded tranlate
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-20 13:38:44 +05:00
Boria138 239ace42c9 Translated using Weblate (Russian)
Currently translated at 100.0% (605 of 605 strings)

Translation: PotrtProtonQt/PortProtonQt
Translate-URL: https://translate.codeberg.org/projects/potrtprotonqt/portprotonqt/ru/
2026-03-20 08:30:57 +00:00
Boria138 6c43289c85 Translated using Weblate (Spanish)
Currently translated at 0.3% (2 of 605 strings)

Translation: PortProtonQt/PortProtonQt
Translate-URL: https://translate.codeberg.org/projects/portprotonqt/portprotonqt/es/
2026-03-20 07:27:08 +00:00
Simple16 ca32ce4e25 Boria138 small fib about translations. Updating the translation 2026-03-19 17:42:48 +00:00
Boria138 3fbabc0267 docs: add fish shell instruction to README
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-19 22:37:41 +05:00
Boria138 ef5a302ff5 fix: use custom_data cover for CLI launched games
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-19 20:12:34 +05:00
Boria138 d05665be15 fix: improve dialog and detail page controller navigation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-19 20:10:06 +05:00
Boria138 b51174c172 fix: use saved Exec line for edited shortcut actions
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-19 19:56:43 +05:00
Boria138 169ff005ce feat(detail_page): added add game and edit shortcut
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-19 19:53:42 +05:00
Boria138 6792abdac6 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-19 18:51:36 +05:00
Boria138 f2f11b608e feat: add compact badge mode with hover accordion text 2026-03-19 18:47:31 +05:00
Boria138 2fd91b9556 fix: skip cover copy when source and destination match
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-19 18:23:52 +05:00
Boria138 40b50de937 chore: use horizontal layout for checkbox in add game dialog
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-19 15:58:35 +05:00
Boria138 f39267e979 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-19 15:38:55 +05:00
Boria138 710c876374 feat: add shortcut toggles to add game dialog with state sync 2026-03-19 15:36:34 +05:00
Boria138 d00d789246 perf: reduce git requests and stream autoinstall asset updates
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-19 14:49:14 +05:00
Boria138 edcdb7cef4 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-18 23:45:08 +05:00
Boria138 03cf25492f fix: disable accidental wheel scrolling on comboboxes
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-18 23:43:32 +05:00
Boria138 9f84d2e9c3 fix: unify desktop entry generation and enforce 0755 perms
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-18 23:34:24 +05:00
Boria138 38c162f38a fix: run downloader callbacks in Qt thread to avoid cross-thread UI
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-18 23:25:06 +05:00
Boria138 41046f3439 chore(downloader): added user-agent
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-18 22:27:20 +05:00
Boria138 5428cd311b chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-18 22:01:31 +05:00
Boria138 21580d76ba feat: use Yandex as primary server for internet connectivity check
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-18 21:59:50 +05:00
Boria138 174e439509 fix: skip SGDB and SteamCDN covers when custom_data exists
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-18 16:58:26 +05:00
Boria138 b7f8e1edf2 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-18 16:50:22 +05:00
Boria138 b52785791a fix: constrain theme tab gamepad focus and add visible focus styles 2026-03-18 16:49:09 +05:00
Boria138 b280dc1f54 fix: reduce SGDB timeout to avoid startup delays 2026-03-17 14:42:24 +05:00
Boria138 1775911416 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-16 14:19:04 +05:00
Boria138 9f47dafb24 feat: normalize wine tool prefix to uppercase before cli launch 2026-03-15 21:36:53 +05:00
Boria138 0996b90ba3 fix: normalize PW_PREFIX_NAME and prefix directory names
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-15 18:13:40 +05:00
Renovate Bot 07e3850bce chore(deps): update archlinux:base-devel docker digest to b3c1ff7 2026-03-15 11:43:14 +00:00
Simple16 4536ce09bd Updating the translation of the Gamescope settings 2026-03-15 07:58:12 +05:00
Simple16 4d61cb3316 merge upstream 2026-03-14 19:02:01 +00:00
Boria138 c40caeae5c feat(gamescope): rework layout
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-14 17:48:27 +05:00
Boria138 74085a2d0b feat: clean user.conf CLI
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-14 17:32:26 +05:00
Simple16 3d55994962 Updating the translation of the MangoHud and Gamescope settings 2026-03-14 10:09:48 +00:00
Simple16 769c84edbd Updating the translation of the main Gamescope settings 2026-03-14 10:09:48 +00:00
Simple16 4ec1174bcd Updating the translation of the MangoHud setting №2 2026-03-14 10:09:48 +00:00
Simple16 6fe2fe08ba Updating the translation of the MangoHud settings №1 2026-03-14 10:09:48 +00:00
Simple16 cda1340293 Updating the translation of the MangoHud and Gamescope settings 2026-03-14 14:55:41 +05:00
Simple16 773569773e Updating the translation of the main Gamescope settings 2026-03-14 13:13:33 +05:00
Simple16 f9cd038aa1 Updating the translation of the MangoHud setting №2 2026-03-14 12:11:49 +05:00
Boria138 c0bae645e4 feat: hide unsupported gamescope options and handle aliases
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-14 11:02:35 +05:00
Boria138 6c63815ec3 feat: force PW_GAMESCOPE and PW_MANGOHUD on tab save
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-14 10:46:03 +05:00
Simple16 5c006a5b7e Updating the translation of the MangoHud settings №1 2026-03-14 09:21:26 +05:00
Boria138 c6a9031ee2 Reapply "fix: use short gamescope args for PortProton compatibility"
This reverts commit 3f6a4f538d.
2026-03-13 15:43:15 +05:00
Boria138 91a3cb4c26 refactor: switch user.conf helpers to PortProton CLI
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-13 14:14:52 +05:00
Boria138 c93f10c2a2 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-13 14:02:20 +05:00
Boria138 ab055f3708 fix: wrap control hints in small window sizes
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-13 14:00:48 +05:00
Boria138 823fff912e chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-13 13:57:16 +05:00
Boria138 100556e1d0 fix: use two-column layout for prefix backup action buttons
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-13 13:53:50 +05:00
Dervart d639283db5 fix scroll for exe settings 2026-03-12 09:59:24 +00:00
Dervart 7f4d06f825 fix end of file 2026-03-12 09:59:24 +00:00
Dervart b4baf8e230 Unified styles for comboboxes, checkboxes, input fields, scrollbars, and titlebars. 2026-03-12 09:59:24 +00:00
Boria138 3f6a4f538d Revert "fix: use short gamescope args for PortProton compatibility"
This reverts commit 0ac7959031.
2026-03-12 10:40:45 +05:00
Boria138 0ac7959031 fix: use short gamescope args for PortProton compatibility
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-12 10:06:08 +05:00
Boria138 3397e633c6 chore(completion): drop .bash ext
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-12 09:53:04 +05:00
Boria138 9abeddfb51 chore(compltion): added fish and zsh
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-12 00:22:20 +05:00
Boria138 754fc039f9 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 23:36:13 +05:00
Boria138 0b9b2f6e48 feat(gamescope): added gamepad navigation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 23:35:11 +05:00
Boria138 b8fd7aff1b refactor: unify toggle grid layout for mangohud and gamescope
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 23:22:14 +05:00
Boria138 92f84d9c9c chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 23:19:33 +05:00
Boria138 228db2bbf1 refactor: centralize settings context menu and tooltip handling
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 23:17:36 +05:00
Boria138 5277f88b80 revert: remove gamescope screen-size validation on parse
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 23:04:52 +05:00
Boria138 f0de078dcd ui: move gamescope presets and toggles above resolution
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 23:02:55 +05:00
Boria138 ff20458ffb fix: drop invalid gamescope short resolution args
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 22:58:43 +05:00
Dervart 22956d7140 add styles for editable QComboBox 2026-03-11 15:33:39 +00:00
Dervart f31c8409cc remove background in checkbox container 2026-03-11 15:33:39 +00:00
Boria138 dc2eaa71ba feat(gamescope): added initial
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 20:33:17 +05:00
Boria138 e66dffeef0 feat: added create pfx
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 17:42:20 +05:00
Boria138 eac9583252 refactor: extract MangoHud settings into separate dialog module
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 10:10:18 +05:00
Boria138 39df4d7946 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 09:54:16 +05:00
Boria138 9ffb563280 fix: keep focused input visible when virtual keyboard opens 2026-03-11 09:46:08 +05:00
Boria138 c0c4eea813 fix(mangohud): fix gamepad navigation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 09:40:58 +05:00
Boria138 27ea663f7d chore(mangohud): added Default value placeholder
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-11 09:17:21 +05:00
Boria138 ca851735e6 docs: clarify and align AGENTS.md policy rules
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-10 23:59:01 +05:00
Boria138 ac1270a7fd refactor: move hardcoded styles to theme files
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-10 23:33:22 +05:00
Boria138 8e76ee8789 chore(mangohud): drop translate from MANGOHUD_TOGGLE_SPECS
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-10 23:05:02 +05:00
Boria138 f11f7d594b chore: rework custom tooltip
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-10 23:02:33 +05:00
Boria138 2014a89c27 feat(mangohud): added gpu_list
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-10 22:38:46 +05:00
Boria138 4ae38a1f55 chore(mangohud): use gamepad tooltip insted system tooltip
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-10 20:58:57 +05:00
Boria138 a3853ef1a6 feat(mangohud): added short description to button
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-10 20:21:29 +05:00
Boria138 f3ac329e54 fix(mangohud): fix gamepad navigation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-10 20:06:27 +05:00
Boria138 94f2c6df2e chore(mangohud): fix preset Layout
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-10 11:42:52 +05:00
Dervart 7fccaa4b0d Styles for mangohud settings 2026-03-09 20:56:28 +07:00
Boria138 9c1a80add5 feat(mangohud): added background_alpha and round_corners
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-09 13:47:39 +05:00
Boria138 6b859f6bdf fix MANGOHUD_VALUE_SPECS
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-09 13:19:03 +05:00
Boria138 aacabd81d9 chore(mangohud): rework layout
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-09 13:15:30 +05:00
Simple16 b1dc9d87dd Updating the translation of the main MangoHud settings. FIX 2026-03-09 09:38:49 +05:00
Simple16 63b8d26b1c Updating the translation of the main MangoHud settings 2026-03-09 09:21:53 +05:00
Boria138 858314a21c feat(mangohud): added network
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-08 23:45:16 +05:00
Boria138 622baaa31c feat(mangohud): added device_battery
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-08 23:09:33 +05:00
Boria138 2e93af677c feat(mangohud): added gamepad navigation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-08 22:47:18 +05:00
Boria138 f55701b963 chore(mangohud): replace QPlainTextEdit to QLineEdit
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-08 22:21:47 +05:00
Boria138 188f2925ba chor(mangohud): hide font size
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-08 22:18:30 +05:00
Boria138 ce334fb232 chore(mangohud): added custom preset system
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-08 22:04:01 +05:00
Boria138 f4eca46112 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-08 21:45:54 +05:00
Boria138 811083748c chore: update screenshots
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-08 21:44:06 +05:00
Dervart 6bd8593300 Increased the width of setting titles 2026-03-08 23:13:38 +07:00
Dervart aa629e79a2 Separated checkbox and combobox classes for settings titles 2026-03-08 23:12:37 +07:00
Dervart 3508248e53 Added font styles for tab titles in get_wine & winetricks 2026-03-08 15:49:14 +00:00
Dervart abe8ee0575 Removed underline in block title. 2026-03-08 15:49:14 +00:00
Dervart d0e9d721d1 Increased the width of the combobox in the game settings as requested by @Simple16 2026-03-08 15:49:14 +00:00
Dervart 343ed115a1 styles for PortProton settings tab 2026-03-08 15:49:14 +00:00
Boria138 9f78196c8d feat: added initial mangohud settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-08 19:49:38 +05:00
Renovate Bot bc4748ca56 chore(deps): update archlinux:base-devel docker digest to a4e49d3 2026-03-08 10:12:10 +00:00
Renovate Bot 5718584809 chore(deps): update https://gitea.com/actions/setup-node digest to 53b8394 2026-03-08 00:01:20 +00:00
Simple16 1fb4ced62f Update of Russian localization 2026-03-07 20:49:14 +05:00
Boria138 98cfa3e50e chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-07 20:21:02 +05:00
Boria138 006b6a6dd1 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-07 20:16:30 +05:00
Boria138 8ab3b796f3 fix: translate QMessageBox Yes/No buttons
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-07 20:16:29 +05:00
Boria138 3730fa1183 refactor: Unify cache management with CacheManager
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-07 16:43:42 +05:00
Boria138 d6d415d184 feat: Add --resolution CLI argument for custom window size
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-07 16:07:05 +05:00
Boria138 af90c5fdff chore(todo): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-07 16:06:21 +05:00
Boria138 e8e3fefbf0 fix: Correct locale links in localization guide
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-07 15:39:35 +05:00
Simple16 9c29a66314 Update of English and Russian strings. Update of Russian localization 2026-03-06 22:27:18 +05:00
Simple16 c26dd358e5 Update of English and Russian strings. Update of Russian localization 2026-03-06 21:34:21 +05:00
Simple16 ad469c6755 Update locale 2026-03-06 21:06:17 +05:00
Boria138 fad86df55f fix: add setuptools package discovery config for uv build
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-06 20:22:56 +05:00
Boria138 20ebb51f9a fix: restore project.scripts entry point for uv installation 2026-03-06 19:45:40 +05:00
Boria138 85b7f6a70c chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-06 12:29:06 +05:00
Boria138 7542be7bfd chore: simplify pyproject.toml for uv-only usage
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-06 12:25:39 +05:00
Boria138 9dce0bc2ef revert broken hook
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-05 13:44:34 +05:00
Boria138 d813be7e29 fix: added exclude for pre-commit hooks
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-05 13:32:25 +05:00
Boria138 b460fd507e chore(localization): sync russian and english strings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-05 13:20:22 +05:00
Boria138 b377759db4 chore localization update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-05 12:44:06 +05:00
Boria138 ba3233dabf chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-05 11:49:39 +05:00
Boria138 aeaef9b6d7 feat: add cancel button to ProtonManager dialog
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-05 11:47:41 +05:00
Boria138 08808cf975 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-04 23:42:30 +05:00
Boria138 b23a83c96d feat: lazy load autoinstall
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-04 23:31:57 +05:00
Boria138 69e38452bf feat: batch download for autoinstall assets with rate limiting 2026-03-04 22:34:37 +05:00
Boria138 dd66585c52 fix: reduce CPU load and memory leak on card resize
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-04 20:38:38 +05:00
Boria138 b8e0359367 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-04 13:31:40 +05:00
Boria138 8d264ac743 fix: avoid library hang and reduce asset requests 2026-03-04 13:07:11 +05:00
Boria138 732f5e5f60 style: update PortProton Settings tab layout 2026-03-03 18:18:32 +05:00
Boria138 2b735aadbd perf: incremental library render 2026-03-03 13:41:02 +05:00
Boria138 0cef434c2e chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-03 12:44:12 +05:00
Boria138 757bd34885 fix: Steam CEF API detection and restart-free add/remove 2026-03-03 12:07:51 +05:00
Boria138 da79f07780 fix: fix get anticheat status for Steam Games
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-02 14:32:42 +05:00
Boria138 55d5b097d9 debug: add SGDB cache logging and reduce URL log verbosity 2026-03-02 13:39:38 +05:00
Boria138 650844c704 fix: check local cache before SteamCDN request to prevent redundant network calls
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-02 13:12:18 +05:00
Boria138 c4e3e30bf7 fix: remove blocking SGDB and URL check calls to prevent UI freeze 2026-03-02 00:56:48 +05:00
Boria138 97d6d54c93 fix: detect VDF format by first byte to avoid load errors 2026-03-02 00:56:42 +05:00
Boria138 be09e152e4 refactor: split steam_api.py into package with separate modules
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-03-02 00:56:36 +05:00
Renovate Bot 54df09f94a chore(deps): update archlinux:base-devel docker digest to f7227ef 2026-03-01 05:40:01 +00:00
Gitea Actions eb39264578 chore: update steam apps list 2026-03-01T00:01:59Z 2026-03-01 00:01:59 +00:00
Simple16 f9ea5e992b Update the Russian translation in the settings menu 2026-02-28 15:30:53 +00:00
Boria138 81637c3729 feat: auto-add MANGOHUD_CONFIG from var when enabling PW_MANGOHUD
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-28 20:29:15 +05:00
Boria138 80a79ed45b feat: add settings button for Steam games using PortProtonQt 2026-02-28 13:25:40 +05:00
Boria138 c6b997366f feat: launch games directly in Steam compatibility mode 2026-02-28 09:53:24 +05:00
Boria138 2bdcf107f2 feat: skip desktop file creation for steamapps/common games 2026-02-27 21:35:14 +05:00
Boria138 25f3e526ae feat: prioritize var.log for environment variables 2026-02-27 16:23:09 +05:00
Boria138 d081ae68db refactor: extract common process.log parsing function
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-27 16:13:56 +05:00
Boria138 d1b8f0fa93 feat: add PW_USE_INHIBIT_SLEEP_INFO setting 2026-02-27 16:10:39 +05:00
Boria138 23e19a14d0 feat: add Wine download progress monitoring
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-27 16:05:15 +05:00
Boria138 f9ef6751dd fix: tray use correct exec line 2026-02-27 15:23:18 +05:00
Boria138 6363c08781 refactor: extract dialogs to separate package and fix UI updates
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-26 23:26:11 +05:00
Boria138 7eb2934b44 fix: Run initial PortProton command in QThread to avoid UI blocking 2026-02-26 22:14:37 +05:00
Boria138 2519ccd6d0 fix: create UInput mouse in QThread to avoid blocking UI 2026-02-26 22:08:11 +05:00
Boria138 da204786c1 refactor: remove redundant branch input from nightly build workflow 2026-02-26 21:41:43 +05:00
Boria138 f6e871feaf fix: PKGBUILD steam-compat directory delete 2026-02-26 20:29:38 +05:00
Boria138 a9e0304437 fix: resolve file conflict between main and steam-compat packages 2026-02-26 19:50:56 +05:00
Boria138 994769d3cf feat: Add Steam compatibility tool as separate package 2026-02-26 17:58:54 +05:00
Boria138 6fd2e9b34a feat: Add CLI option to install PortProtonQt as Steam compatibility tool 2026-02-26 17:42:53 +05:00
Boria138 387133b87f feat: add direct exe launch via CLI 2026-02-26 17:22:49 +05:00
Boria138 8bd6e30e0b refactor: split config_utils into config package with validation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-24 20:30:40 +05:00
Boria138 b168e32fc8 refactor: split detail_pages into package 2026-02-24 13:02:22 +05:00
Boria138 1812b8de5f refactor: split debug_utils into submodules
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-22 16:40:43 +05:00
Boria138 cfc4532edd fix: CSS comment syntax validation and winetricks.py typos 2026-02-22 16:03:52 +05:00
Boria138 50d6d952dd fix: invalid CSS comments in combobox styles
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-22 15:53:15 +05:00
Boria138 18f277e707 fix: adaptive width for PortProton settings tab
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-22 13:20:30 +05:00
Boria138 a769263aa1 refactor: split get_graphics_info_detailed into small functions
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-22 12:57:44 +05:00
Boria138 159cd49a16 chore(agents): update again
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-22 12:57:38 +05:00
Renovate Bot 68c8ca07b9 chore(deps): update archlinux:base-devel docker digest to 839e930 2026-02-22 00:01:07 +00:00
Boria138 ee22a5d8fb docs(agents): add dev-scripts exemption policy 2026-02-20 13:55:43 +05:00
Boria138 48f156e433 refactor: replace print() with logger and add exception logging 2026-02-20 13:50:00 +05:00
Boria138 85b199d5ea chore: translate comments to English and clean up TODOs
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-20 11:26:24 +05:00
Boria138 8d0bab134e feat(agents): finalize AI Governance Policy and consolidate LLM restrictions
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-20 11:08:57 +05:00
Boria138 5525a6988a docs(agents): remove redundant manual lint commands 2026-02-20 10:28:40 +05:00
Boria138 d6dc7db5e4 chore(agents): rework agents rules
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-19 23:49:07 +05:00
Boria138andQwen-Coder 09313e30cf fix(pre-commit): fix pyright exclude pattern for theme files
Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-02-19 17:41:46 +05:00
Boria138 8d539469a3 fix(agents): rewrite pre-commit manual start
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-19 17:39:40 +05:00
Boria138 45f9b2950f fix(build): Fix vk_gpu_info Fedora BR
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-19 15:17:22 +05:00
Boria138 0d6df9ed6c chore: added AI Instruction (CLAUDE, GEMINI, QWEN, CURSOR, CODEX, OPENCODE)
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-19 15:09:32 +05:00
Boria138 b92eb1fe9d chore(portproton_settings): drop favorites adaptive
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-19 11:14:29 +05:00
Boria138 b200d73879 feat(portproton_settings): make it adaptive
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-19 11:12:44 +05:00
Boria138 335f3223db feat(detail_page): make it adaptive
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-19 10:32:14 +05:00
Boria138 bcc6f1c2ce fix typo on arch PKGBUILD
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-18 13:15:00 +05:00
Boria138 b88ed89136 bump to 0.1.11
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-18 13:03:41 +05:00
Boria138 78d4c820e4 docs(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-18 13:01:43 +05:00
Boria138 47c84ceb67 fix: hide settings and log buttons for Steam/EGS games in detail page
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-18 12:56:37 +05:00
Boria138 e882a94395 chore: fix typos in CHANGELOG
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-17 23:22:33 +05:00
Boria138 4c372ad083 chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-17 20:10:38 +05:00
Boria138 0a1f0dfdf1 chore: use Qt on open_ppdb_file
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-17 20:06:02 +05:00
Boria138 228e3262c8 fix: fix advanced settings translate
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-17 20:00:58 +05:00
Boria138 017c56227a chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-15 14:10:20 +05:00
Boria138 0f28c0dbeb chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-15 14:08:36 +05:00
Boria138 80c51198b9 feat: added system_wine to dist options
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-15 13:56:33 +05:00
Boria138 c5a46780df feat: Remove PW prefix from settings display and add Open PPDB button 2026-02-15 13:37:00 +05:00
Boria138 f729e10e20 chore(screenshots): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-14 21:27:18 +05:00
Boria138 1affd68159 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-14 21:16:34 +05:00
Boria138 c597c37610 chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-14 20:53:38 +05:00
Boria138 ffc040c8af fix(get_wine_module): clear selected assets after download completion
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-14 20:35:21 +05:00
Boria138 f676ab6abe chore: drop amd vulkan driver from settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-14 20:13:16 +05:00
Boria138 8ac7cf235a feat: added hint for mouse emulation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-13 16:44:03 +05:00
Boria138 0a231e6664 feat(input_manager): make mouse emulation work regardless of window focus state
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-13 16:35:04 +05:00
Boria138 461df5006d feat(debug_utils): added device type to log
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-13 14:18:04 +05:00
Boria138 3cb04d0d42 fix(build): fix ternary operator usage in udev rules installation 2026-02-11 23:03:24 +05:00
Boria138 e6b94ef907 chore(build): added udev_rulesdir for rpm based
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-11 22:48:47 +05:00
Boria138 d6a58ecd60 chore: drop xdg-utils from deps
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-11 22:37:15 +05:00
Boria138 bdfc18203b chore(build): added sitelib for rpm based
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-11 18:24:04 +05:00
Boria138 0814326624 chore(build): fixes
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-11 18:03:53 +05:00
Boria138 bcfb69bd08 chore(renovate): fix rate-limit
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-11 16:23:20 +05:00
Renovate Bot 5ad70b1d5a chore(deps): update archlinux:base-devel docker digest to 7c81df5 2026-02-11 10:44:18 +00:00
Renovate Bot f10de90210 chore(deps): update https://gitea.com/actions/checkout digest to de0fac2 2026-02-11 10:38:37 +00:00
Boria138 4b33637846 chore: drop xrandr dependency
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-11 15:13:57 +05:00
Boria138 e309bb4f10 feat(debug_utils): use own vk_gpu_info
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-11 12:02:53 +05:00
Boria138 52572b85c7 chore: added simply vulkan-info file
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-11 11:47:18 +05:00
Boria138 1c952c009a chore: clean code and deps
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-10 22:13:09 +05:00
Boria138 0a0fbf47b1 Revert "feat(debug_utils): drop vulkaninfo from deps"
This reverts commit 7b703f5bf1.
2026-02-10 22:09:03 +05:00
Boria138 d29e144d4e feat(debug_utils): drop xdpyinfo from deps
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-10 22:02:31 +05:00
Boria138 7b703f5bf1 feat(debug_utils): drop vulkaninfo from deps
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-10 21:53:35 +05:00
Boria138 1a44bc00af feat: added PW_GPU_USE to PortProton Settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-09 17:53:08 +05:00
Boria138 1cdde3ada8 feat(detail_pages): added log auto-save conditions 2026-02-09 13:13:01 +05:00
Boria138 e7cbff82fd chore(build): added muvm to Fedora
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-09 12:51:33 +05:00
Boria138 dcf1748976 chore(build): added log dependency
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-09 12:49:07 +05:00
Boria138 cc9a585c74 fix(debug_utils): replace FLATPAK is used to FLATPAK in used
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-09 00:38:04 +05:00
Boria138 11835e0337 feat(debug_utils): remove caching and improve PW_VULKAN_USE detection
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-09 00:08:26 +05:00
Boria138 97e41be7b7 feat(debug_utils): filter PW_USE_RUNTIME when Flatpak is used and read from default if PPDB missing 2026-02-08 19:57:12 +05:00
Boria138 73d99a6aec chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-08 15:22:54 +05:00
Boria138 2ebecc96bc chore(portproton_api): clean
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-08 15:19:49 +05:00
Boria138 63f8201098 feat(completions): add --force-muvm and URL arg to bash completion 2026-02-08 14:55:13 +05:00
Boria138 48a066eee8 feat(cli): add --force-muvm flag to run under muvm regardless of platform 2026-02-08 14:51:59 +05:00
Boria138 da52f7e821 fix: preserve muvm when restarting after theme change 2026-02-08 14:45:53 +05:00
Boria138 8fe1f35433 fix(ui): prevent hidden auto-install tab from breaking navigation and indexes 2026-02-08 14:37:39 +05:00
Boria138 9daabff516 chore(docs): update localization guide to mention only Poedit and GTranslator 2026-02-08 14:14:32 +05:00
Boria138 d3c21fef3f chore(localization): change locale directory lookup order to prioritize local directory first 2026-02-08 14:09:15 +05:00
Boria138 c123514ce5 chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-08 14:02:46 +05:00
Simple16 3c1c9dffe8 Updating the Russian localization 2026-02-08 12:23:15 +05:00
Boria138 aed6492c25 fix: theme loading for custom themes with relative imports 2026-02-08 01:19:32 +05:00
Boria138 66583f52f4 feat: restructure icon themes with organized subdirectories 2026-02-08 00:30:22 +05:00
Boria138 b64670d8b3 feat: added ppdb.linux-gaming.ru handler
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-07 19:25:17 +05:00
Boria138 9d16105c8a fix(docs): correct grammar mistakes in CHANGELOG.md 2026-02-07 17:45:28 +05:00
Boria138 ee23957f43 fix(appimage): fix locale
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-06 11:16:12 +05:00
Boria138 b414147bbd chore(meson): clean
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-05 16:03:36 +05:00
Boria138 a2b42ac0ed chore(workflow): make release job continue on error 2026-02-05 13:00:01 +05:00
Boria138 92caf0dbb1 feat(ui): add setting to hide auto-install tab 2026-02-04 23:10:56 +05:00
Boria138 fc36dd7983 feat(debug_utils): add Flatpak detection to get_runtime_status 2026-02-04 11:24:24 +05:00
Boria138 643f914f6d fix(config_utils): prioritize Flatpak version in get_portproton_start_command 2026-02-04 11:05:24 +05:00
Boria138 8c3fc1307c fix(get_graphics_info_detailed): I forget about AMD and Intel
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-03 20:37:17 +05:00
Boria138 e0195856a8 feat(build): add muvm as aarch64 depend for Asahi Linux support 2026-02-03 16:15:55 +05:00
Boria138 04583c2586 feat: add Asahi Linux support via muvm re-execution 2026-02-03 16:09:11 +05:00
Boria138 bd8d280561 chore(log): make log async
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-03 16:00:36 +05:00
Boria138 48bfb308dd chore(log): rename PPQT to PortProtonQt
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-01 20:50:49 +05:00
Boria138 dcfa307fcd chore(log): enhance vulkaninfo output with API and driver versions
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-01 20:49:22 +05:00
Boria138 3509701b1a chore(log): remove vkcube subprocess call 2026-02-01 20:49:17 +05:00
Boria138 04c723e4cc chore(log): add anonymization for /run/media/barry and /media/barry paths
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-02-01 20:48:54 +05:00
Gitea Actions 63de266289 chore: update steam apps list 2026-02-01T00:02:12Z 2026-02-01 00:02:13 +00:00
Boria138 4d20626f80 chore(log): delete PortProton.log before PW_LOG and PPQT.log save
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-31 22:44:08 +05:00
Boria138 3a59f1af76 fix: prevert log coruption
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-31 22:33:25 +05:00
Boria138 abc3b0b716 chore(log): fixed musl libc detect
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-31 19:05:23 +05:00
Boria138 9159b63000 chore(log): added musl libc detect support
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-31 15:37:52 +05:00
Boria138 296476afa3 chore(log): copy portproton format
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-31 13:31:22 +05:00
Boria138 17f938ded4 chore: update log
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-30 18:12:34 +05:00
Boria138 5ccd47d461 feat: add meson.build linter with comprehensive syntax checks
Add pre-commit hook to validate meson.build files:
   - Check for unbalanced brackets: (), [], {}
   - Detect unclosed quotes: ', "
   - Find missing/double commas between list items
   - Validate control structures (if/endif, foreach/endforeach)
   - Check for invalid operators (===, !==, :=, ;)
   - Detect common typos in meson functions
   - Verify all Python files are included in install_data

Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-29 22:56:21 +05:00
Boria138 35e449f730 feat: initial add log
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-29 22:27:48 +05:00
Boria138 b6062f1ee0 fix(gamecard): correct argument order when creating GameCard
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-26 23:28:06 +05:00
Boria138 651040de70 feat: replace linux-gaming topics to ppdb.linux-gaming.ru api calls
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-26 23:09:02 +05:00
Renovate Bot 3f0b3d65ad chore(deps): update archlinux:base-devel docker digest to d2bd09b 2026-01-26 12:17:08 +00:00
Renovate Bot ec449f12d1 chore(deps): update https://gitea.com/actions/setup-python digest to a309ff8 2026-01-26 12:16:50 +00:00
Boria138 2d5932f144 fix: prevent QMessageBox from closing immediately on gamepad 2026-01-26 17:16:05 +05:00
Boria138 0a9381b1d2 fix: open virtual keyboard on all QLineEdit
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-26 17:12:02 +05:00
Boria138 20fb7174c1 fix: update virtual keyboard icons on change gamepad type
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-26 17:07:22 +05:00
Boria138 8f9e6ea958 chore(build): switch from pyproject to meson build system
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-19 06:19:04 +00:00
Renovate Bot 19aecd75c4 chore(deps): update archlinux:base-devel docker digest to 84c36fa 2026-01-18 05:56:49 +00:00
Renovate Bot 905ebe1d61 chore(deps): update https://gitea.com/actions/setup-node digest to 6044e13 2026-01-18 00:01:59 +00:00
Boria138 ae0b3a0f1a chore(build): added qt6-svg
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-14 18:08:32 +05:00
Boria138 678f28ed30 bump ver to 0.1.10
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-14 17:37:42 +05:00
Boria138 e7d2860c0e chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-14 17:36:58 +05:00
Boria138 55a7f77a33 fix(detail_pages): handle RuntimeError on detail page exit animation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-13 14:29:37 +05:00
Boria138 8e6c0aafd1 fix(image_utils): remove corrupted cached images on load failure
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-13 14:21:11 +05:00
Boria138 dd65021976 fix(time_utils): make playtime parsing robust to malformed data
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-13 14:13:59 +05:00
Boria138 5f3a451c50 chore(locale): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-12 21:03:51 +05:00
Boria138 c33813dae5 feat(get_wine): added total size to update_selection_display
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-12 20:56:41 +05:00
Boria138 88a436c29f fix(locales): clean fuzzy in poedit
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-12 20:40:08 +05:00
Simple16 9ca4b38a14 Обновление русской локализации в окне "Управление версиями WINE" 2026-01-12 19:58:42 +05:00
Dervart 7fdd260868 window width for get_wine module 2026-01-12 20:07:49 +07:00
Boria138 091780bf9f feat(get_wine): make it async
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-12 11:19:21 +05:00
Boria138 1729f553bc feat(get_wine): unify tabble code
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-12 11:07:51 +05:00
Dervart b79d6e0331 styles fix for get_wine module 2026-01-11 22:58:29 +07:00
Boria138 96766643b7 feat(get_wine): added Installed tab for wine remove
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-11 20:02:50 +05:00
Boria138 f08becdbde fix(input_manager): handle common UI elements like QMessageBox, QMenu, etc. first
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-11 12:04:55 +05:00
Renovate Bot c2ab0c5d6c chore(deps): update archlinux:base-devel docker digest to ebcaeca 2026-01-11 00:01:02 +00:00
Boria138 df62b76bf1 chore: remove DPAD left/right navigation for tabs
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-09 16:03:43 +05:00
Boria138 eaaf726f15 chore(input_manager): drop unneded code
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-08 22:16:58 +05:00
Boria138 4b50cd4da1 fix(input_manager): fixed card increase_size on BT and added BTN_TRIGGER_HAPPY to switch tab
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-08 22:13:35 +05:00
Boria138 f07fbeee9e chore: drop delete_wine_module
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-08 19:47:41 +05:00
Boria138 59aecbc6e8 chore(input_manager): clean code
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-08 17:26:11 +05:00
Dervart bbfc51f908 styles for get_wine module 2026-01-07 15:31:35 +07:00
Boria138 7e44ec67d8 fix: fix dist sorting on Wine Settings tab
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-06 12:02:44 +05:00
Boria138 224f88aebd feat: rework proton sort
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-06 11:51:53 +05:00
Boria138 9bb7e45b27 feat: use alphabeth and number sort on prefixes and dist
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-05 21:54:31 +05:00
Boria138 59093f743c chore(appimage): use debloated packages later
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-05 21:14:09 +05:00
Boria138 a7c8977dab feat: use QFileSystemWatcher to dist and prefixes update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-05 11:42:15 +05:00
Boria138 ff744fc581 chore(flow_layout): drop very heavy numpy
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-05 00:02:17 +05:00
Simple16 05de549d07 Updating the Russian translation 2026-01-04 21:24:18 +05:00
Boria138 3e74cbdcf5 chore(locales): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-03 20:34:42 +05:00
Boria138 a9b97e3a4b feat(get_wine): make unpack progress real
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-03 16:13:19 +05:00
Boria138 b9fe0250ed chore: unify get and delete wine
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-03 16:13:14 +05:00
Simple16 4dcfca919f Updating the Russian translation 2026-01-03 01:31:28 +05:00
Boria138 66c23db29c fix(animations): resolve memory leaks in GameCardAnimations and DetailPageAnimations
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-02 21:11:41 +05:00
Boria138 e7a7300665 chore(get_wine): simplify archive extraction using libarchive native API
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-02 14:21:22 +05:00
Boria138 2521f7d2f4 fix(get_wine): handle symlinks too
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-02 12:14:08 +05:00
Simple16 5df0b8783f Updating the translation for the WINE download window 2026-01-02 00:10:09 +05:00
Boria138 044ea7d151 feat(get_wine): added CPU filtering
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-01 19:03:46 +05:00
Boria138 cd93f9ebfe chore(tabbles): disable edititng
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-01 16:19:38 +05:00
Boria138 1b9595ca95 chore(build): added python-libarchive-c to dependency
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-01-01 15:50:58 +05:00
Gitea Actions 4dff545c0f chore: update steam apps list 2026-01-01T00:00:54Z 2026-01-01 00:00:54 +00:00
Boria138 69d8e53c7b feat: reworked wine download
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-31 13:50:52 +05:00
Renovate Bot 40769bfdf6 fix(deps): lock file maintenance python dependencies 2025-12-30 15:58:37 +00:00
Renovate Bot b3adef68d3 chore(deps): update archlinux:base-devel docker digest to f6b259c 2025-12-30 15:56:27 +00:00
Renovate Bot df707a84bc chore(deps): update ghcr.io/renovatebot/renovate:latest docker digest to eec497d 2025-12-30 15:52:48 +00:00
Renovate Bot 4c340c13ab chore(deps): pin archlinux docker tag to f6b259c 2025-12-30 15:48:13 +00:00
Boria138 a81cef4457 feat(appimage): use AnyLinux Appimage to support musl-libc systems
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-30 15:44:59 +00:00
Boria138 4c537248f1 Revert "fix(animations): prevent memory leaks by properly clearing animation references"
This reverts commit 55dcda738b.
2025-12-30 11:06:15 +05:00
Boria138 55dcda738b fix(animations): prevent memory leaks by properly clearing animation references
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-29 11:17:09 +05:00
Boria138 aa0c0a5675 fix: fix slider size on autoinstall
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-27 00:13:13 +05:00
Boria138 613b28a751 chore(localization): added translate support to theme name, description and screenshots
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-26 13:02:45 +05:00
Boria138 a9e9f4e4e3 get_other_wine: added initial
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-26 00:23:07 +05:00
Boria138 61c59814a5 feat(security): strengthen theme security against multiple attack vectors
- Detect dangerous modules, functions, attributes, and system/network operations
- Prevent code execution via dynamic imports, reflection, and importlib
- Block f-string injection and dangerous expressions
- Detect obfuscated code patterns, including string concatenation (im+port, ev+al),
  Base64-encoded payloads, and character code arrays
- Validate image files using extension checks, magic bytes, and size limits
- Implement AST-based analysis for deep code inspection

Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-25 16:02:34 +05:00
Boria138 80d3b69311 chore(themes): reorgonize it to submodules
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-25 12:30:27 +05:00
Boria138 ac09ac1e36 fix: handle None steam data in egs_api callbacks
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-23 00:27:18 +05:00
Boria138 7cdc7264cd chore(steam_api): returned partially search oops
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-23 00:22:27 +05:00
Boria138 94f61b1124 perf: optimize Steam and anti-cheat metadata caching
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-23 00:15:45 +05:00
Boria138 58bbff8e69 chore: clean all vulture 80% confidence dead code
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-21 19:34:32 +05:00
Renovate Bot 6457084d56 chore(deps): update ghcr.io/renovatebot/renovate:latest docker digest to e09f710 2025-12-21 10:19:52 +00:00
Renovate Bot 3c83a90721 fix(deps): lock file maintenance python dependencies 2025-12-21 04:54:36 +00:00
Renovate Bot c76b80586a chore(deps): update archlinux:base-devel docker digest to 9414f5b 2025-12-21 00:00:43 +00:00
Boria138 b30ade6e1e fix(tests): fix ruff and pyright
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-20 15:42:18 +05:00
Boria138 7a5b467490 feat(autoinstalls): added detail page
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-19 16:28:50 +05:00
Boria138 6f82068864 chore: bump to 0.1.9
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-08 11:47:25 +05:00
Boria138 d4672ecb0e chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-08 11:47:19 +05:00
Renovate Bot 087ac8eda2 chore(deps): update https://gitea.com/actions/setup-node digest to 395ad32 2025-12-07 10:48:27 +00:00
Renovate Bot 0a9acaf5da chore(deps): update https://gitea.com/actions/checkout digest to 8e8c483 2025-12-07 10:48:16 +00:00
Boria138 d0fad6a3c9 fix: added correct parent to GameCard
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-07 15:46:27 +05:00
Boria138 468887110c fix(qt): prevent RuntimeError from accessing deleted Qt C++ objects
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-07 12:45:37 +05:00
Boria138 32e4950a00 Revert "chore: bump ver to 0.1.9"
This reverts commit 29d25cec01.
2025-12-06 14:26:04 +05:00
Boria138 b16074fa5c fix: Add protection against accessing deleted Qt objects in async callbacks
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-06 14:22:41 +05:00
Boria138 1bd7c23419 fix(settings): Remove surrounding quotes from the value if present
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-04 11:53:54 +05:00
Boria138 f4275dd465 fix(get_portproton_start_command): Check if flatpak command exists before trying to run it
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-02 18:44:47 +05:00
Boria138 c8b91c4687 fix(settings): update keyboard navigation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-02 18:40:27 +05:00
Boria138 4aaeb2e809 fix: dont start game by Enter
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-02 18:23:49 +05:00
Boria138 b6ea9350fa fix: fix gamecard refrefresh regression after 0889aa8
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-02 17:52:19 +05:00
Boria138 29d25cec01 chore: bump ver to 0.1.9
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-01 20:29:45 +05:00
Boria138 a634de5462 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-01 20:27:12 +05:00
Boria138 1ba1781994 feat(settings): added preloader because flatpak is too slow
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-01 17:06:20 +05:00
Boria138 0aae292f61 fix(settings): fix work on Flatpak
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-01 16:59:43 +05:00
Boria138 3ef433af0c fix: Only handle menu button if our main window is currently active
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-12-01 12:08:55 +05:00
Gitea Actions 9fe33e02d8 chore: update steam apps list 2025-12-01T00:01:44Z 2025-12-01 00:01:44 +00:00
Boria138 2ac91a759d chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-30 13:20:33 +05:00
Boria138 2c82bff204 fix(main_window): remove redundant loading status and improve loading flow
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-30 13:14:38 +05:00
Boria138 0889aa883e fix: refresh button refresh custom data too now
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-30 12:59:32 +05:00
Boria138 7780dcfc4d chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-29 23:12:31 +05:00
Boria138 9ef39ae2b6 fix: save cover images from URL to custom_data folder
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-29 23:08:54 +05:00
Boria138 86fb2b2d7c chore: added refresh hint
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-29 11:33:07 +05:00
Dervart 9d469f0a12 add horizontal scroll styles for exe settings 2025-11-28 13:54:25 +00:00
Boria138 665a4df322 perf(search): implement full async + indexed search system with major performance gains
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-28 13:48:17 +05:00
Boria138 3abaccb1e0 fix(startup): prevent main thread hangs and optimize resource loading
- run start_sh initialization via QTimer.singleShot with timeout
- add timeout protection to load_theme_fonts()
- load Steam/EGS/PortProton games in parallel instead of sequential
- delay game loading until UI is fully initialized
- fix callback chaining to avoid blocking operations
- add proper timeout + error handling for all Steam/EGS network requests
- add timeouts for flatpak subprocess calls
- improve file I/O error handling to avoid UI freeze
- optimize theme font loading:
  - delay font loading via QTimer.singleShot
  - load fonts in batches of 10
  - reduce font load timeout to 3s
  - remove fonts only when switching themes

Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-28 12:00:00 +05:00
Boria138 77b025f580 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-27 16:03:43 +05:00
Renovate Bot 42e2025e54 fix(deps): lock file maintenance python dependencies 2025-11-27 10:58:16 +00:00
Renovate Bot 8f84bbce31 chore(deps): update https://gitea.com/actions/setup-python digest to 83679a8 2025-11-27 10:55:42 +00:00
Boria138 3026e7da4e fix: fix code work with pyside 6.10
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-27 15:54:08 +05:00
Boria138 3522764c3e fix(detail-page): prevent crash on exit by adding robust widget/animation safety checks
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-26 21:43:18 +05:00
Boria138 fd456e5330 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-26 18:02:48 +05:00
Boria138 99a963d60c chore: drop all pyright ignore
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-26 17:34:24 +05:00
Boria138 0b36e73bce chore(build): fix build on arch
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-26 16:59:04 +05:00
Boria138 4baa2e8684 chore(themes): delete unused fonts
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-26 16:57:56 +05:00
Boria138 4344bbca70 feat: added combination for Update Grid
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-26 14:54:15 +05:00
Boria138 0a8a290d2d chore: ignore pyright
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-25 20:49:58 +05:00
Boria138 92652e8faa fix(mouse_emulations): ignore triggers
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-25 20:32:44 +05:00
Boria138 4f2afaed24 fix: use kernel for detect_gamepad_axes
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-25 14:39:52 +05:00
Boria138 1751e01e47 feat: added setfocus to gamedetail page
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-25 10:22:27 +05:00
Boria138 0f74a47aed chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-24 23:49:29 +05:00
Boria138 666ec654a0 fix(ui): prevent text truncation in show_gamepad_tooltip
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-24 23:34:57 +05:00
Boria138 0c25cc9fd2 chore(settings): rework tabble
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-24 23:23:56 +05:00
Boria138 5de83dbf49 fix(settings): drop .ppdb from show-ppdb
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-24 23:03:31 +05:00
Dervart 1821faadf6 styles for virtual keyboard 2025-11-24 16:47:41 +00:00
Boria138 17f0a6b0ea fix(ui): prevent segfault by validating widget existence in async callbacks
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-24 16:27:02 +05:00
Boria138 e9c75b998f chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-23 15:43:59 +05:00
Boria138 bbfbc00c11 fix(settings): fix virtual keyboard
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-23 15:28:30 +05:00
Boria138 b7804fdd01 fix(ui): unify handling of QMessageBox and QMenu in controller
- Added _handle_common_ui_elements() for QMessageBox, QMenu, etc.
- Fixed A/B behavior for single- and multi-button QMessageBox dialogs
- Improved D-pad navigation and focused-button selection
- Removed duplicated logic in specialized handlers

Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-23 15:13:21 +05:00
Renovate Bot 043da2cf5d chore(deps): update https://gitea.com/actions/checkout action to v6 2025-11-23 00:01:25 +00:00
Boria138 2fa10e7db3 feat(settings): added tooltip to desc
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-22 23:34:11 +05:00
Boria138 b1b9706272 chore(input_manager): clean dialogs code
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-22 22:36:37 +05:00
Boria138 9c11d33c0a chore(setting): add human readeble value to PW_VULKAN_USE
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-22 19:52:36 +05:00
Boria138 173e1cb88e fix(settings): fix PW_WINE_USE_LIST
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-22 11:53:24 +05:00
Boria138 30606c7ec1 Revert "fix: eliminate blocking calls causing startup freezes and UI hangs"
This reverts commit b2a1046f9d.
2025-11-22 11:21:25 +05:00
Boria138 873e8b050e chore(settings): added disable style to comboboxes
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-22 00:28:15 +05:00
Boria138 59dad21945 chore(settings): adjust virtual keyboard button width (40 → 50)
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-22 00:16:14 +05:00
Boria138 b0c4e943ae feat(settings): added blocked style to advanced tab
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-22 00:05:46 +05:00
Boria138 19e01bba17 Fix: normalize disabled value for PW_AMD_VULKAN_USE
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-21 23:43:36 +05:00
Boria138 836e6cdd36 feat(settings): added initial gamepad navigation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-21 00:08:02 +05:00
Boria138 b2a1046f9d fix: eliminate blocking calls causing startup freezes and UI hangs
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-20 10:55:35 +05:00
Boria138 80a2c06b5a feat: added refresh button
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-16 17:07:58 +05:00
Boria138 f0a4ace735 perf: add config and icon caching to reduce I/O and improve UI responsiveness
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-16 16:57:40 +05:00
Boria138 7dfaee6831 feat(settings): added proton, 3d_api and prefixes settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-16 13:35:35 +05:00
Boria138 5481cd80d7 chore: added null pixmaps check
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-16 12:25:01 +05:00
Boria138 a016cfa810 chore: convert list to set for optimize
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-16 12:13:42 +05:00
Boria138 8fc097ccaf chore: remove broken styles
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-16 12:03:18 +05:00
Boria138 ad3eeb6e06 chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-15 21:39:05 +05:00
Boria138 92631cd2c6 chore: separate settings list to new module
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-15 21:39:03 +05:00
Boria138 4477679f2d chore: replace emulataion buttons to xbox + start
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-15 21:38:07 +05:00
Renovate Bot b6644eeee5 fix(deps): update dependency pillow to v12 2025-11-15 21:38:07 +05:00
Renovate Bot 2e921226c4 chore(deps): update https://gitea.com/actions/setup-python action to v6 2025-11-15 21:38:06 +05:00
Renovate Bot 4fc1ea73d3 chore(deps): update https://gitea.com/actions/setup-node action to v6 2025-11-15 21:38:06 +05:00
Renovate Bot 3c15cbe495 chore(deps): update archlinux:base-devel docker digest to 943bdad 2025-11-15 21:38:06 +05:00
Boria138 fed6aafed5 feat: trigger emulation by Xbox + B
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-15 21:38:06 +05:00
Dervart 2e8be13437 WINETRICKS_TABBLE_STYLE more fixes 2025-11-15 16:22:59 +07:00
Dervart ea272c29b6 WINETRICKS_TABBLE_STYLE reworked 2025-11-13 15:43:13 +07:00
Dervart 17262f6c9f Play Button & Settings Button in row 2025-11-07 12:17:36 +07:00
Boria138 e07f3f06bc chore(build): return QtSvg to appimage
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-04 12:28:09 +05:00
Boria138 16a3f4e09a chore(build): added udev rule to allow create virtual devices
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-04 11:14:17 +05:00
Boria138 a448ba29b0 feat(input_manager): added mouse emulation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-03 12:34:27 +05:00
Boria138 06e55db54d feat(settings): update styles
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-02 16:05:22 +05:00
Boria138 5fce23f261 chore: disable pre-commit auto update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-11-02 15:31:01 +05:00
Renovate Bot 96ad40d625 chore(deps): update pre-commit hook astral-sh/ruff-pre-commit to v0.14.3 2025-11-02 00:01:26 +00:00
Gitea Actions a30f6f2e74 chore: update steam apps list 2025-11-01T00:01:57Z 2025-11-01 00:01:58 +00:00
Boria138 0231073b19 feat(settings): added advanced
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-30 16:27:45 +05:00
Boria138 dec24429f5 chore: separate start.sh to new function
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-28 15:34:01 +05:00
Boria138 4a758f3b3c chore: use flatpak run for flatpak not start.sh
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-27 23:13:48 +05:00
Boria138 0853dd1579 chore: use CLI for clear pfx
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-27 22:36:14 +05:00
Boria138 bbb87c0455 feat(settings): added icon to button thanks to @Dervart
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-27 12:17:00 +05:00
Boria138 b32a71a125 feat(settings): block settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-27 12:16:54 +05:00
Renovate Bot bddf9f850a chore(deps): update pre-commit hook astral-sh/uv-pre-commit to v0.9.5 2025-10-26 00:01:29 +00:00
Renovate Bot a9c3cfa167 chore(deps): update pre-commit hook astral-sh/ruff-pre-commit to v0.14.2 2025-10-26 00:01:19 +00:00
Boria138 7675bc4cdc feat: added initial exe settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-26 00:12:00 +05:00
Boria138 ffa203f019 feat: restore instance from tray
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-22 15:46:57 +05:00
Boria138 3eed25ecee feat: update grid on update_favorite_icon
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-21 20:41:21 +05:00
Boria138 3736bb279e feat: use SGDB for cover too
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-20 13:07:09 +05:00
Renovate Bot b59ee5ae8e chore(deps): update archlinux:base-devel docker digest to 87a967f 2025-10-19 12:07:20 +00:00
Boria138 33176590fd feat: Make autoinstall games loading asynchronous with caching
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-19 17:03:26 +05:00
Boria138 8046065929 refactor(gamepad): replace busy-wait with threading.Event for monitor readiness
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-19 11:00:22 +05:00
Renovate Bot fbad5add6c chore(deps): update pre-commit hook astral-sh/ruff-pre-commit to v0.14.1 2025-10-19 00:01:23 +00:00
Boria138 438e9737ea chore(release): drop sha256 sums
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-18 21:07:37 +05:00
Boria138 2d39a4c740 fix: fix CloseEvent on native package
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-18 21:06:23 +05:00
Boria138 567203b0b0 chore: bump to 0.1.8
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-18 18:22:32 +05:00
Boria138 502cbc5030 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-18 18:20:50 +05:00
Boria138 9b61215152 chore(theme): update screenshots
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-18 18:17:47 +05:00
Boria138 10d3fe8ab4 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-18 13:40:56 +05:00
Boria138 a568ad9ef8 fix(add_game_dialog): prevent overwriting manually entered game name
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-18 13:09:58 +05:00
Boria138 f074843fc8 fix: prevent udev monitor hang by using non-blocking poll with timeout
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-18 12:53:47 +05:00
Boria138 4ab078b93e fix: sync card_width between GameLibraryManager and MainWindow to prevent config overwrite
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-18 12:17:17 +05:00
Boria138 7df6ad3b80 feat(autoinstalls): added slider
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-17 13:55:17 +05:00
Boria138 464ad0fe9c chore: optimize and clean code
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-17 13:09:02 +05:00
Boria138 cde92885d4 feat(virtual_keybord): added gamepad hint
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-17 00:04:47 +05:00
Boria138 120c7b319c fix: improve gamepad detection using udev ID_INPUT_JOYSTICK property 2025-10-16 23:20:48 +05:00
Boria138 596aed0077 chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-16 14:54:30 +05:00
Boria138 6fc6cb1e02 feat: added minimize to tray
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-16 14:53:08 +05:00
Boria138 186e28a19b fix(gamepad): resolve MonitorObserver blocking issue causing application hang
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-16 14:43:49 +05:00
Boria138 28e4d1e77c Revert "chore: broke autorelease for tasting purpose"
This reverts commit fff1f888c4.
2025-10-16 14:11:36 +05:00
Boria138 fff1f888c4 chore: broke autorelease for tasting purpose
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-16 12:48:21 +05:00
Boria138 fdd5a0a3d5 chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-16 10:44:30 +05:00
Boria138 792e52d981 feat(dialogs): added controller hints
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-16 10:39:24 +05:00
Boria138 84d5e46a74 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-15 22:53:08 +05:00
Boria138 4bc764d568 partially revert b1047ba18e
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-15 22:31:35 +05:00
Boria138 9a18aa037e feat(autoinstall): no restart on autoinstall finished
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-15 21:58:40 +05:00
Boria138 ed62d2d1c4 fix: resolve lambda variable capture issue in switchTab method
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-15 21:47:14 +05:00
Boria138 accc9b18b6 chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-15 15:31:56 +05:00
Boria138 82249d7eab feat(settings): Added Gamepad type settings
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-15 15:30:31 +05:00
Boria138 476c896940 chore(TODO): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-15 12:44:01 +05:00
Boria138 b1047ba18e fix: fix card overlap on display_filter change
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-13 12:14:54 +05:00
Boria138 987199d8e6 chore(release): enable node experimental-fetch
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-13 11:52:43 +05:00
Renovate Bot ef1acd4581 chore(deps): update archlinux:base-devel docker digest to 06ab929 2025-10-12 17:46:27 +00:00
Boria138 96f884904c chore: bump ver to v0.1.7
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 17:33:56 +05:00
Boria138 b856a2afae chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 17:33:12 +05:00
Boria138 55ef0030e6 feat: added version and commit on WindowTitle
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 17:31:23 +05:00
Boria138 8aaeaa4824 chore(localization): add localization for auto-install progress status message
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 17:14:06 +05:00
Boria138 f55372b480 fix(autoinstall): fix scrollbar sticking to the right edge
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 17:10:44 +05:00
Boria138 4d6f32f053 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 15:25:04 +05:00
Boria138 a2f5141b20 chore localization update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 15:21:14 +05:00
Boria138 e3cb2857e7 fix(pyright): fix pyright errors
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 15:14:02 +05:00
Boria138 efe8a35832 feat(autoinstall): rework gamepad navigation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 14:57:43 +05:00
Boria138 61fae97dad fix(autoinstall): fix virtual keyboard open
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 14:45:52 +05:00
Boria138 5442100f64 feat: use GameCard on autonstall tab
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 13:56:18 +05:00
Boria138 2d6ef84798 chore: rename metadata to use pw_create_unique_exe
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 12:14:31 +05:00
Renovate Bot f4aee15b5d chore(deps): update pre-commit hook astral-sh/ruff-pre-commit to v0.14.0 2025-10-12 00:01:35 +00:00
Boria138 87a65108a5 feat(autoinstall): added covers
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-12 00:48:09 +05:00
Boria138 bb617708ac feat: initial add of autoinstall tab
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-11 19:19:47 +05:00
Boria138 1cf332cd87 feat(winetab): added progress bar
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-11 13:24:58 +05:00
Boria138 577ad4d3a3 feat: adapt WineTab to new cli
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-10 23:07:48 +05:00
Boria138 ef3f2d6e96 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 21:01:30 +05:00
Boria138 657d7728a6 fix(gamepad): exit fullscreen on disconnect only if auto-fullscreen enabled and fullscreen disabled
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 20:59:51 +05:00
Boria138 9452bfda2e chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 11:41:53 +00:00
Boria138 7eb2db0d68 chore localization update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 11:41:53 +00:00
Boria138 6ef7a03366 feat: added search to controller hints
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 11:41:53 +00:00
Boria138 e5af354b56 fix(virtual-keyboard): turn off caps lock when disabling shift while caps is enabled
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 11:41:53 +00:00
Boria138 e6e5f6c8ea feat(virtual_keyboard): make keyboard bigger
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 11:41:53 +00:00
Boria138 84306bb31b feat(virtual_keyboard): added dpad reapeat movement
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 11:41:53 +00:00
Boria138 60af4d1482 feat(virtual_keyboard): press X to backspace
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 11:41:53 +00:00
Boria138 692e11b21d chore(virtual_keyboard): move styles to style.py
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 11:41:53 +00:00
Boria138 b1a804811e chore(keyboard): drop connect_keyboard_to_lineedit
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 11:41:53 +00:00
Boria138 9a30cfaea7 chore(keyboard): drop unneded key events
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 11:41:53 +00:00
Boria138 5dd2f71f5e feat: added virtual keyboard
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 11:41:53 +00:00
Boria138 dba172361b fix(ui): resolve layout issues during search filtering
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 12:52:34 +05:00
Boria138 a9c70b8818 chore(winetricks): use curl for download
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 08:59:03 +05:00
Boria138 135ace732f chore(deps): added Winetricks deps copied from upstream control
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-09 08:47:22 +05:00
Boria138 8b727f64e1 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-08 19:26:21 +05:00
Boria138 a8eb591da5 fix: update ControlHints and NavButtons together
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-08 19:23:58 +05:00
Boria138 fe4ca1ee87 fix: revert signals to pyside 6.9.1
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-08 19:12:37 +05:00
Boria138 ffe3e9d3d6 chore(deps): revert Pyside6 to 6.9.1
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-08 19:04:45 +05:00
Boria138 49d39b5d61 chore(pyright): fix code for new version
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-08 18:37:31 +05:00
Renovate Bot 03566da704 fix(deps): lock file maintenance python dependencies 2025-10-08 18:21:53 +05:00
Renovate Bot 7f996ab6a0 chore(deps): update archlinux:base-devel docker digest to b380991 2025-10-08 12:09:42 +00:00
Renovate Bot 9e17978155 chore(deps): update ghcr.io/renovatebot/renovate:latest docker digest to 17c8966 2025-10-08 12:05:09 +00:00
Boria138 5d0185b1b4 feat(winetricks): added preloader to tabble
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-08 16:41:32 +05:00
Boria138 5c134be04e chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-07 15:54:05 +05:00
Boria138 8c66695192 chore(winetricks): fix typo on translate and added forget icon
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-07 15:49:48 +05:00
Boria138 7a141d8e46 fix(winetricks): resolve QProcess channel mode warning in install handler
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-07 15:43:16 +05:00
Boria138 abb2377fb7 fix(winetricks): remove duplicate entries in winetricks.log
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-07 15:37:41 +05:00
Boria138 75f4f346de chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-07 15:27:31 +05:00
Boria138 87a9f85272 feat(wine settings): make winetricks work with gamepad
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-07 15:18:48 +05:00
Boria138 240f685ece feat(wine settings): make winetricks work
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-07 12:06:35 +05:00
Boria138 af4e3e95bb chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-06 17:57:52 +05:00
Boria138 017d9a42cf feat(wine settings): make prefix and wine delete work
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-06 17:55:24 +05:00
Boria138 18b7c4054b chore(localization): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-06 17:47:45 +05:00
Boria138 dd7f71b70a feat(wine settings): make pfx_backup work
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-06 17:29:06 +05:00
Boria138 8fd44c575b fix: expose gamesListWidget from GameLibraryManager to fix gamepad navigation
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-06 13:21:58 +05:00
Boria138 65b43c1572 chore(changelog): update
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-06 00:04:55 +05:00
Boria138 f35276abfe fix: reject candidate if normalized name equals "game"
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-06 00:02:06 +05:00
Boria138 6fea9a9a7e chore(wine settings): rework layout
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-05 20:01:00 +05:00
Boria138 5189474631 feat(wine settings): initial introdouce
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2025-10-05 16:19:06 +05:00
Renovate Bot 416cc6a268 chore(deps): update archlinux:base-devel docker digest to 5d95edc 2025-10-05 08:20:07 +00:00
Renovate Bot 3b44ed5252 chore(deps): update ghcr.io/renovatebot/renovate:latest docker digest to e459af1 2025-10-05 00:01:07 +00:00
275 changed files with 123848 additions and 17860 deletions

No files matched your search

+35 -36
View File
@@ -4,6 +4,7 @@ on:
workflow_dispatch:
env:
BUILD_BRANCH: ${{ github.ref_name }}
PKGDEST: "/tmp/portprotonqt"
PACKAGE: "portprotonqt"
@@ -11,40 +12,36 @@ jobs:
build-appimage:
name: Build AppImage
runs-on: ubuntu-22.04
container:
image: archlinux:base-devel@sha256:b3c1ff749031ca2e06df1cd83fda74df13206a047b7b0f96b818825d9dc60785
options: --privileged --device /dev/fuse
steps:
- uses: https://gitea.com/actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
- name: Install required dependencies
- name: Prepare container
run: |
sudo apt update
sudo apt install -y binutils coreutils desktop-file-utils gtk-update-icon-cache fakeroot fuse libgdk-pixbuf2.0-dev patchelf python3-pip python3-dev python3-setuptools python3-build python3-venv squashfs-tools strace util-linux zsync git zstd adwaita-icon-theme
pacman-key --init
pacman -Sy --noconfirm archlinux-keyring
pacman -Syu --noconfirm --disable-download-timeout --needed git wget gnupg nodejs npm xorg-server-xvfb zsync
- name: Upgrade pip toolchain
run: |
python3 -m pip install --upgrade \
pip setuptools setuptools-scm wheel packaging build
- uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
ref: ${{ env.BUILD_BRANCH }}
- name: Install appimage-builder
- name: Install appimage dependencies
run: |
git clone https://github.com/Boria138/appimage-builder
cd appimage-builder
pip install .
- name: Install uv
run: |
pip install uv
cd build-aux/AppImage
chmod +x get-dependencies.sh portprotonqt-appimage.sh
./get-dependencies.sh --local --branch "${{ env.BUILD_BRANCH }}"
- name: Build AppImage
run: |
cd build-aux
sed -i '/app_info:/,/- exec:/ s/^\(\s*version:\s*\).*/\1"0"/' AppImageBuilder.yml
appimage-builder
cd build-aux/AppImage
./portprotonqt-appimage.sh
- name: Upload AppImage
uses: https://gitea.com/actions/gitea-upload-artifact@v4
with:
name: PortProtonQt-AppImage
path: build-aux/PortProtonQt*.AppImage
path: build-aux/AppImage/dist/*.AppImage
build-fedora:
name: Build Fedora RPM
@@ -61,9 +58,9 @@ jobs:
steps:
- name: Install build dependencies
run: |
dnf install -y git rpmdevtools python3-devel python3-wheel python3-pip \
python3-build pyproject-rpm-macros python3-setuptools \
redhat-rpm-config nodejs npm
dnf install -y git rpmdevtools meson ninja-build python3-devel \
systemd-rpm-macros vulkan-loader-devel redhat-rpm-config nodejs npm \
gcc gettext
- name: Setup rpmbuild environment
run: |
@@ -73,11 +70,14 @@ jobs:
echo '%_topdir /home/rpmbuild' > /home/rpmbuild/.rpmmacros
- name: Checkout repo
uses: https://gitea.com/actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
ref: ${{ env.BUILD_BRANCH }}
- name: Copy fedora.spec
run: |
cp build-aux/fedora-git.spec /home/rpmbuild/SPECS/${{ env.PACKAGE }}.spec
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|" \
build-aux/fedora-git.spec > /home/rpmbuild/SPECS/${{ env.PACKAGE }}.spec
chown -R rpmbuild:users /home/rpmbuild
- name: Build RPM
@@ -94,16 +94,12 @@ jobs:
name: Build Arch Package
runs-on: ubuntu-22.04
container:
image: archlinux:base-devel@sha256:0589aa8f31d8f64c630a2d1cc0b4c3847a1a63c988abd63d78d3c9bd94764f64
volumes:
- /usr:/usr-host
- /opt:/opt-host
options: --privileged
image: archlinux:base-devel@sha256:b3c1ff749031ca2e06df1cd83fda74df13206a047b7b0f96b818825d9dc60785
steps:
- name: Prepare container
run: |
pacman -Sy --noconfirm --disable-download-timeout --needed git wget gnupg nodejs npm
pacman -Syuu --noconfirm --disable-download-timeout --needed git wget gnupg nodejs npm
sed -i 's/#MAKEFLAGS="-j2"/MAKEFLAGS="-j$(nproc) -l$(nproc)"/g' /etc/makepkg.conf
sed -i 's/OPTIONS=(.*)/OPTIONS=(strip docs !libtool !staticlibs emptydirs zipman purge lto)/g' /etc/makepkg.conf
yes | pacman -Scc
@@ -125,17 +121,20 @@ jobs:
chown user -R /tmp
chown user -R ..
- name: Checkout
uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
ref: ${{ env.BUILD_BRANCH }}
- name: Build
run: |
cd /__w/portproton-repo
git clone https://git.linux-gaming.ru/Boria138/PortProtonQt.git
cp -r "$GITHUB_WORKSPACE" PortProtonQt
cd /__w/portproton-repo/PortProtonQt/build-aux
sed -i "s|source=(\"git+https://git.linux-gaming.ru/Boria138/PortProtonQt.git\")|source=(\"git+https://git.linux-gaming.ru/Boria138/PortProtonQt.git#branch=${{ env.BUILD_BRANCH }}\")|" PKGBUILD-git
chown user -R ..
su user -c "yes '' | makepkg --noconfirm -s -p PKGBUILD-git"
- name: Checkout
uses: https://gitea.com/actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
- name: Upload Arch package
uses: https://gitea.com/actions/gitea-upload-artifact@v4
with:
@@ -0,0 +1,56 @@
name: Build vk_gpu_info on Debian 11
on:
workflow_dispatch:
push:
branches:
- main
paths:
- 'build-aux/vk_gpu_info.c'
- '.gitea/workflows/build-vk-gpu-info-debian.yml'
jobs:
build-debian11:
name: Build vk_gpu_info on Debian 11
runs-on: ubuntu-latest
container:
image: debian:11
options: --privileged
steps:
- name: Install dependencies
run: |
apt-get update
apt-get install -y build-essential pkg-config libvulkan-dev git curl wget nodejs npm
- name: Set up Node.js
uses: https://gitea.com/actions/setup-node@v2
with:
node-version: 20
- name: Checkout code
uses: https://gitea.com/actions/checkout@v3
- name: Compile vk_gpu_info
run: |
cd build-aux
gcc -o vk_gpu_info vk_gpu_info.c -lvulkan
- name: Test vk_gpu_info execution
run: |
cd build-aux
# Check if the executable was created
if [ -f "./vk_gpu_info" ]; then
echo "vk_gpu_info executable created successfully"
# Try to run it (may fail if no Vulkan devices present, but that's OK for build test)
timeout 10s ./vk_gpu_info || echo "vk_gpu_info ran but may have failed due to lack of Vulkan hardware (expected in CI)"
else
echo "ERROR: vk_gpu_info executable was not created"
exit 1
fi
- name: Upload vk_gpu_info binary
uses: https://gitea.com/actions/gitea-upload-artifact@v4
with:
name: vk_gpu_info-debian11-binary
path: build-aux/vk_gpu_info
+29 -36
View File
@@ -8,7 +8,7 @@ on:
env:
# Common version, will be used for tagging the release
VERSION: 0.1.6
VERSION: 0.1.12
PKGDEST: "/tmp/portprotonqt"
PACKAGE: "portprotonqt"
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
@@ -17,54 +17,45 @@ jobs:
build-appimage:
name: Build AppImage
runs-on: ubuntu-22.04
container:
image: archlinux:base-devel
options: --privileged --device /dev/fuse
steps:
- name: Prepare container
run: |
pacman-key --init
pacman -Sy --noconfirm archlinux-keyring
pacman -Syu --noconfirm --disable-download-timeout --needed git wget gnupg nodejs npm xorg-server-xvfb zsync
- uses: https://gitea.com/actions/checkout@v4
- name: Install required dependencies
- name: Install appimage dependencies
run: |
sudo apt update
sudo apt install -y binutils coreutils desktop-file-utils gtk-update-icon-cache fakeroot fuse libgdk-pixbuf2.0-dev patchelf python3-pip python3-dev python3-setuptools python3-build python3-venv squashfs-tools strace util-linux zsync git zstd adwaita-icon-theme
- name: Upgrade pip toolchain
run: |
python3 -m pip install --upgrade \
pip setuptools setuptools-scm wheel packaging build
- name: Install appimage-builder
run: |
git clone https://github.com/Boria138/appimage-builder
cd appimage-builder
pip install .
- name: Install uv
run: |
pip install uv
cd build-aux/AppImage
chmod +x get-dependencies.sh portprotonqt-appimage.sh
./get-dependencies.sh
- name: Build AppImage
run: |
cd build-aux
appimage-builder
cd build-aux/AppImage
./portprotonqt-appimage.sh
- name: Upload AppImage
uses: https://gitea.com/actions/gitea-upload-artifact@v4
with:
name: PortProtonQt-AppImage
path: build-aux/PortProtonQt*.AppImage*
path: build-aux/AppImage/dist/*.AppImage
build-arch:
name: Build Arch Package
runs-on: ubuntu-22.04
container:
image: archlinux:base-devel
volumes:
- /usr:/usr-host
- /opt:/opt-host
options: --privileged
steps:
- name: Prepare container
run: |
pacman -Sy --noconfirm --disable-download-timeout --needed git wget gnupg nodejs npm
pacman -Syuu --noconfirm --disable-download-timeout --needed git wget gnupg nodejs npm
sed -i 's/#MAKEFLAGS="-j2"/MAKEFLAGS="-j$(nproc) -l$(nproc)"/g' /etc/makepkg.conf
sed -i 's/OPTIONS=(.*)/OPTIONS=(strip docs !libtool !staticlibs emptydirs zipman purge lto)/g' /etc/makepkg.conf
yes | pacman -Scc
@@ -86,17 +77,17 @@ jobs:
chown user -R /tmp
chown user -R ..
- name: Checkout
uses: https://gitea.com/actions/checkout@v4
- name: Build
run: |
cd /__w/portproton-repo
git clone https://git.linux-gaming.ru/Boria138/PortProtonQt.git
cp -r "$GITHUB_WORKSPACE" PortProtonQt
cd /__w/portproton-repo/PortProtonQt/build-aux
chown user -R ..
su user -c "yes '' | makepkg --noconfirm -s"
- name: Checkout
uses: https://gitea.com/actions/checkout@v4
- name: Upload Arch package
uses: https://gitea.com/actions/gitea-upload-artifact@v4
with:
@@ -118,9 +109,9 @@ jobs:
steps:
- name: Install build dependencies
run: |
dnf install -y git rpmdevtools python3-devel python3-wheel python3-pip \
python3-build pyproject-rpm-macros python3-setuptools \
redhat-rpm-config nodejs npm
dnf install -y git rpmdevtools meson ninja-build python3-devel \
systemd-rpm-macros vulkan-loader-devel redhat-rpm-config nodejs npm \
gcc gettext
- name: Setup rpmbuild environment
run: |
@@ -149,7 +140,6 @@ jobs:
release:
name: Create and Publish Release
needs: [build-appimage, build-arch, build-fedora]
runs-on: ubuntu-latest
steps:
- uses: https://gitea.com/actions/checkout@v4
@@ -161,6 +151,7 @@ jobs:
- name: Download all artifacts
uses: https://gitea.com/actions/download-artifact@v3
continue-on-error: true
with:
path: release/
@@ -180,10 +171,12 @@ jobs:
- name: Release
uses: https://gitea.com/actions/gitea-release-action@v1
env:
NODE_OPTIONS: '--experimental-fetch' # if nodejs < 18
with:
body_path: changelog.txt
token: ${{ env.GITEA_TOKEN }}
tag_name: v${{ env.VERSION }}
prerelease: true
files: release/**/*
sha256sum: true
sha256sum: false
+3 -4
View File
@@ -1,4 +1,4 @@
name: Check Translations (disabled until yaspeller is fixed)
name: Check Translations
run-name: Check spelling in translation files
on:
push:
@@ -12,14 +12,13 @@ on:
jobs:
check-translations:
if: false
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: https://gitea.com/actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Set up Python
uses: https://gitea.com/actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
uses: https://gitea.com/actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
with:
python-version-file: "pyproject.toml"
+32 -27
View File
@@ -9,6 +9,8 @@ on:
env:
PKGDEST: "/tmp/portprotonqt"
PACKAGE: "portprotonqt"
PR_REPO_URL: ${{ github.event.pull_request.head.repo.clone_url }}
PR_BRANCH: ${{ github.head_ref }}
jobs:
changes:
@@ -18,7 +20,7 @@ jobs:
fedora: ${{ steps.check.outputs.fedora }}
arch: ${{ steps.check.outputs.arch }}
steps:
- uses: https://gitea.com/actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
- uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
with:
fetch-depth: 0
@@ -37,7 +39,7 @@ jobs:
cat changed_files.txt
# Check AppImage files
if grep -q "build-aux/AppImageBuilder.yml" changed_files.txt; then
if grep -q "build-aux/AppImage/" changed_files.txt; then
echo "appimage=true" >> $GITHUB_OUTPUT
else
echo "appimage=false" >> $GITHUB_OUTPUT
@@ -62,29 +64,34 @@ jobs:
runs-on: ubuntu-22.04
needs: changes
if: needs.changes.outputs.appimage == 'true' || github.event_name == 'workflow_dispatch'
container:
image: archlinux:base-devel@sha256:b3c1ff749031ca2e06df1cd83fda74df13206a047b7b0f96b818825d9dc60785
options: --privileged --device /dev/fuse
steps:
- uses: https://gitea.com/actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
- name: Install required dependencies
- name: Prepare container
run: |
sudo apt update
sudo apt install -y binutils coreutils desktop-file-utils gtk-update-icon-cache fakeroot fuse libgdk-pixbuf2.0-dev patchelf python3-pip python3-dev python3-setuptools squashfs-tools strace util-linux zsync zstd git
pacman-key --init
pacman -Sy --noconfirm --disable-download-timeout --needed archlinux-keyring
pacman -Syu --noconfirm --disable-download-timeout --needed git wget gnupg nodejs npm xorg-server-xvfb zsync
- name: Install tools
- uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Install appimage dependencies
run: |
pip3 install git+https://github.com/Boria138/appimage-builder.git
pip3 install uv
cd build-aux/AppImage
chmod +x get-dependencies.sh portprotonqt-appimage.sh
./get-dependencies.sh --local --branch "${{ env.PR_BRANCH }}" --repo "${{ env.PR_REPO_URL }}"
- name: Build AppImage
run: |
cd build-aux
appimage-builder
cd build-aux/AppImage
./portprotonqt-appimage.sh
- name: Upload AppImage
uses: https://gitea.com/actions/gitea-upload-artifact@v4
with:
name: PortProtonQt-AppImage
path: build-aux/PortProtonQt*.AppImage
path: build-aux/AppImage/dist/*.AppImage
build-fedora:
name: Build Fedora RPM
@@ -103,9 +110,9 @@ jobs:
steps:
- name: Install build dependencies
run: |
dnf install -y git rpmdevtools python3-devel python3-wheel python3-pip \
python3-build pyproject-rpm-macros python3-setuptools \
redhat-rpm-config nodejs npm
dnf install -y git rpmdevtools meson ninja-build python3-devel \
systemd-rpm-macros redhat-rpm-config nodejs npm \
gcc vulkan-loader-devel
- name: Setup rpmbuild environment
run: |
@@ -115,11 +122,12 @@ jobs:
echo '%_topdir /home/rpmbuild' > /home/rpmbuild/.rpmmacros
- name: Checkout repo
uses: https://gitea.com/actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Copy fedora-git.spec
run: |
cp build-aux/fedora-git.spec /home/rpmbuild/SPECS/${{ env.PACKAGE }}.spec
sed "s|git clone https://git.linux-gaming.ru/Boria138/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
- name: Build RPM
@@ -138,11 +146,7 @@ jobs:
needs: changes
if: needs.changes.outputs.arch == 'true' || github.event_name == 'workflow_dispatch'
container:
image: archlinux:base-devel@sha256:0589aa8f31d8f64c630a2d1cc0b4c3847a1a63c988abd63d78d3c9bd94764f64
volumes:
- /usr:/usr-host
- /opt:/opt-host
options: --privileged
image: archlinux:base-devel@sha256:b3c1ff749031ca2e06df1cd83fda74df13206a047b7b0f96b818825d9dc60785
steps:
- name: Prepare container
@@ -169,17 +173,18 @@ jobs:
chown user -R /tmp
chown user -R ..
- name: Checkout
uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Build
run: |
cd /__w/portproton-repo
git clone https://git.linux-gaming.ru/Boria138/PortProtonQt.git
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
chown user -R ..
su user -c "yes '' | makepkg --noconfirm -s -p PKGBUILD-git"
- name: Checkout
uses: https://gitea.com/actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
- name: Upload Arch package
uses: https://gitea.com/actions/gitea-upload-artifact@v4
with:
+2 -2
View File
@@ -20,10 +20,10 @@ jobs:
name: Check code
runs-on: ubuntu-latest
steps:
- uses: https://gitea.com/actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
- uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Set up Node.js
uses: https://gitea.com/actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
uses: https://gitea.com/actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6
with:
node-version: 20
+2 -2
View File
@@ -11,10 +11,10 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: https://gitea.com/actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
uses: https://gitea.com/actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- name: Set up Python
uses: https://gitea.com/actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
uses: https://gitea.com/actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
with:
python-version-file: "pyproject.toml"
-38
View File
@@ -1,38 +0,0 @@
name: renovate
on:
workflow_dispatch:
schedule:
- cron: '0 0 * * 0'
jobs:
renovate:
runs-on: ubuntu-latest
container: ghcr.io/renovatebot/renovate:latest@sha256:dd5721b9a686a40d81687643e4b71b82a0ca31fb653fd727538af69104fd388d
steps:
- uses: https://gitea.com/actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
- name: Set up Node.js
uses: https://gitea.com/actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5
with:
node-version: 20
- name: Install uv manually
run: |
curl -LsSf https://astral.sh/uv/install.sh | sh
. $HOME/.local/bin/env
uv --version
- name: Download external renovate config
run: |
mkdir -p /tmp/renovate-config
curl -fsSL "https://git.linux-gaming.ru/Linux-Gaming/renovate-config/raw/branch/main/config.js" \
-o /tmp/renovate-config/config.js
- name: Run Renovate
run: renovate
env:
RENOVATE_CONFIG_FILE: "/tmp/renovate-config/config.js"
LOG_LEVEL: "debug"
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
RENOVATE_GITHUB_COM_TOKEN: ${{ secrets.RENOVATE_GITHUB_COM_TOKEN }}
+17
View File
@@ -6,6 +6,9 @@ dist/
wheels/
*.egg-info
# Meson
builddir/
# Virtual environments
.venv
venv
@@ -33,3 +36,17 @@ Thumbs.db
.vscode
.ropeproject
.zed
# get_wine debug folder
proton_downloads
# Need for refactoring
REFRACTORING_PLAN.md
AUDIT_CHECKLIST.md
# Compiled gettext catalogs
portprotonqt/locales/*/LC_MESSAGES/*.mo
# AI
.codex
+12 -3
View File
@@ -11,12 +11,12 @@ repos:
- id: check-yaml
- repo: https://github.com/astral-sh/uv-pre-commit
rev: 0.8.22
rev: 0.9.5
hooks:
- id: uv-lock
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.13.2
rev: v0.14.3
hooks:
- id: ruff-check
@@ -28,7 +28,7 @@ repos:
language: system
types_or: [python, pyi]
require_serial: true
exclude: '^portprotonqt/themes/[^/]+/styles\.py$'
exclude: 'themes/.*/styles\.py$'
- repo: local
hooks:
@@ -39,3 +39,12 @@ repos:
types: [file]
files: ^portprotonqt/themes/[^/]+/styles\.py$
pass_filenames: false
- repo: local
hooks:
- id: check-meson
name: Check meson.build syntax and file inclusion
entry: ./dev-scripts/check_meson_files.py
language: system
files: (^portprotonqt/.*\.py$|meson\.build$)
pass_filenames: false
+816
View File
@@ -0,0 +1,816 @@
# PortProtonQt — AI Agent Guidelines
**Project:** PortProtonQt — GUI for PortProton, Steam, Epic Games Store
**Language:** Python 3.10+
**Platform:** Linux (POSIX)
**License:** GPL-3.0
**Build:** Meson + uv
---
**Summary:** AI agents MUST behave as conservative patching assistants, prioritizing minimal changes and existing patterns over architectural refactoring or code cleanup. AI MUST NOT perform architectural improvements unless explicitly requested.
**Scope:** These guidelines apply exclusively to AI-generated code. Documentation updates and human maintainers are exempt from line limits and these constraints.
## License and Attribution
- All code MUST be compatible with GPL-3.0.
- Use appropriate SPDX license identifiers where applicable.
- AI agents MUST NOT add `Signed-off-by` tags.
When AI contributes to the project, add an `Assisted-by` tag:
`Assisted-by: AGENT_NAME:MODEL_VERSION`
Where:
- `AGENT_NAME` is the AI agent or framework name.
- `MODEL_VERSION` is the specific model version.
Example:
`Assisted-by: Claude:claude-3-opus`
---
## Core Principles
| Principle | Required | Forbidden |
|-----------|----------|-----------|
| KISS | New/rewritten functions ≤50 lines | Deep nesting |
| YAGNI | Concrete code | Future abstractions |
| DRY | Extract methods (if directly related to task) | Copy-paste |
| SRP | 1 task per method | God functions |
| Linux | POSIX paths, shebangs | Windows-specific code |
| Minimal changes | Modify relevant section only | Rewrite entire files |
**Priority order (highest to lowest):**
1. Minimal changes (overrides DRY, SRP)
2. Security (no shell=True, no hardcoded credentials)
3. Linux compatibility
4. KISS / YAGNI
5. DRY / SRP
**When principles conflict:**
- Prefer minimal diff over extracting methods
- Prefer existing patterns over "correct" refactoring
- Prefer small targeted fix over comprehensive cleanup
- Never break security for code quality
- Remove duplicates only if directly related to current task
- Do not split untouched legacy functions only to satisfy line limits
- Do not rewrite untouched legacy files or blocks only to satisfy metrics
---
## Code Metrics
| Check | Limit |
|-------|-------|
| Functions | ≤50 lines, ≤4 params (required for new/fully rewritten functions) |
| Files | ≤800 lines (required for new/fully rewritten files) |
| Nesting | ≤4 levels (required in new/modified code) |
| Comments | English, 1-2 lines max |
| Indentation | 4 spaces (no tabs) |
| Whitespace | No trailing spaces |
| Blank lines | No excessive blank lines |
| EOF | Exactly one newline |
| Commits | English, ≤72 chars |
---
## Forbidden Patterns
```python
# NEVER: 6+ parameters
def process_game(user, ctx, log, val, map, cache): ...
# NEVER: Deep nesting
if c1:
if c2:
if c3:
if c4: ...
# NEVER: print statements
print(f"Game {name} started")
# NEVER: shell=True
subprocess.run(cmd, shell=True)
# NEVER: Hardcoded credentials
API_KEY = "sk-abc123"
# NEVER: Path traversal
file_path = f"/data/{user_filename}"
# NEVER: Hardcoded styles or constants (colors, sizes, etc.)
shadow.setBlurRadius(20)
shadow.setColor(QColor(0, 0, 0, 150))
label.setStyleSheet("color: #bbbbbb;")
QColor(128, 128, 128)
```
```python
# ALWAYS: ≤4 parameters
def process_game(game_id: str, config: dict) -> Game:
"""Process game data."""
...
# ALWAYS: Early returns
if not condition1:
return
if not condition2:
return
# ALWAYS: Logging
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
logger.info("Game %s started", name)
# ALWAYS: Explicit subprocess arguments
subprocess.run(["cmd", "arg1", "arg2"])
# ALWAYS: Environment variables
API_KEY = os.getenv("API_KEY")
# ALWAYS: Sanitize paths
file_path = os.path.join(BASE_DIR, os.path.basename(user_filename))
# ALWAYS: Use theme constants for styles
shadow.setBlurRadius(self.theme.shadow_blur_radius)
shadow.setColor(QColor(self.theme.color_shadow_card))
label.setStyleSheet(self.theme.CONTENT_STYLE)
QColor(self.theme.color_disabled_text)
# ALWAYS: Add new constants to theme files
# New colors → portprotonqt/themes/standart/styles/constants.py
# New QSS styles → portprotonqt/themes/standart/styles/base.py or submodule
# Never add style constants to application code
```
---
## Code Modification Rules
- NEVER rewrite entire file unless explicitly requested
- Modify only the relevant section
- Preserve existing architecture and naming
- Do not auto-format unrelated code
- Do not reorder imports unless necessary
- Do not introduce abstractions without request
- Do not change logging system
- Do not change public APIs without reason
- Do not add dependencies unless required
- Do not refactor unrelated code
- Do not add comments for obvious code
- **NEVER leave outdated comments after refactoring** (e.g., "without numpy" after numpy removal, "legacy" after rewrite)
- **ALWAYS update or remove comments that reference removed dependencies, patterns, or context**
- **NEVER leave stub/no-op functions** (e.g., `def func(): pass` with comment "removed")
- **When removing a feature, delete the function entirely, not stub it**
- Never invent modules
- Do not move files unless requested
- Do not create new files for organization (unless task requires a new module)
- No circular imports
- Prefer dedicated functions for subprocess calls when practical within task scope
- No shared mutable global state (except logger and explicit cache/session infrastructure)
**ALWAYS:**
- Minimal diff
- Targeted changes only
- Preserve existing patterns
- Keep surrounding code unchanged
---
## LLM Prohibitions
**Specific prohibitions for AI-generated code:**
- Add type hints to existing code unless requested (new code MUST include type hints)
- Replace existing patterns with "better" alternatives
- Consolidate similar code blocks
- Extract methods or functions without request
- Add validation or error handling outside the modified block unless it fixes a security issue or directly supports the current change
- Generate boilerplate or scaffolding
- Add configuration options
- Create new files for "organization" (unless explicitly requested for a new module)
- Split or merge existing modules
- Change function signatures
- Modify docstrings unnecessarily
- Add or remove blank lines for "style"
- Normalize or standardize code patterns
- Invent CLI arguments, config files, API endpoints, environment variables, theme structures, or localization keys
---
## AI Permissions
AI agents MAY:
- Fix obvious bugs within the modified block
- Improve variable naming inside the modified block
- Add missing logging if required by policy
- Add missing validation or error handling in new/modified code when required by this policy
- Add missing type hints in new functions
---
## Performance Rules
- No blocking I/O in UI thread
- No synchronous HTTP in UI thread
- Cache API responses in `~/.cache/PortProtonQt`
- Avoid repeated disk reads in loops
- Avoid O(n²) in game lists
- Lazy load images
- Limit threads to CPU cores
### Clarification: "No Shared Mutable Global State" Does NOT Mean Removing Caches
Rule intent: avoid shared mutable globals that hold application state or cause hidden side effects.
This does not prohibit:
- Module-level cache constants (e.g., cache TTL values)
- Dedicated cache managers or classes with explicit lifecycle
- Disk caches under `~/.cache/PortProtonQt`
- `requests.Session()` objects if they are encapsulated and not mutated unpredictably
Do not delete or disable caching or downloaders to satisfy this rule. Caching is required by the Performance Rules ("Cache API responses in `~/.cache/PortProtonQt`" and "Avoid repeated disk reads in loops").
---
## PySide6 Rules
- No business logic in widgets
- Use signals/slots (no direct coupling)
- No heavy operations in paintEvent
- Use methods instead of lambda for complex logic
- Use QThread for long tasks
---
## Refactoring Constraints
- Max 1 business module per task (unless explicitly requested)
- Related technical files are allowed in the same task (`meson.build`, tests, theme constants)
- Preserve git blame
- Avoid renaming unless necessary
---
## When Uncertain
Ask before proceeding if unsure about:
- Architecture
- Naming
- Design decisions
Do not assume conventions. Never invent behavior.
---
## Development Workflow
```bash
# Setup
uv python install 3.10
uv sync
source .venv/bin/activate
pre-commit install --install-hooks
# Run
portprotonqt
# Manual checks
pre-commit run --all-files
# Build
meson setup builddir && meson compile -C builddir
# Localization
python dev-scripts/l10n.py --update-all
python dev-scripts/l10n.py
# Commit
git commit -m "feat: description in English ≤72 chars"
```
### Pre-commit Hooks
| Hook | Checks |
|------|--------|
| uv-lock | uv.lock up to date |
| ruff-check | Linting (E, W, F, B, C4, UP) |
| pyright | Type checking |
| check-meson | meson.build syntax + files |
| check-qss-properties | Theme QSS validation |
| trailing-whitespace | Whitespace cleanup |
| end-of-file-fixer | EOF newline |
### Linting and Type-Checking
AI agents MUST NOT run linting or type-checking tools directly.
#### Forbidden
- Running `ruff`
- Running `pyright`
- Running `uv run ruff`
- Running `uv run pyright`
- Running any linter/type checker binary directly
- Installing dev tools automatically
These tools are executed ONLY via pre-commit hooks.
#### Allowed
- `pre-commit run --all-files`
- `pre-commit run ruff-check`
- `pre-commit run pyright`
#### Rationale
`ruff` and `pyright` are managed by pre-commit.
Direct execution bypasses project configuration and is forbidden.
Do not attempt to execute binaries manually.
---
## AI Agent Checklist
### Writing Code
- [ ] New/rewritten functions ≤50 lines, ≤4 params
- [ ] New/modified code nesting ≤4 levels
- [ ] LF line endings, 4-space indent
- [ ] No excessive blank lines, no trailing whitespace
- [ ] Type hints (required for new code)
- [ ] Logging via `portprotonqt.logger`
- [ ] New/modified code handles expected/recoverable failures
- [ ] New installable Python files added to `portprotonqt/meson.build`
- [ ] Comments in English, concise
- [ ] No circular imports introduced by the change
- [ ] Prefer dedicated functions for subprocess calls when practical within task scope
- [ ] No shared mutable global state (except logger and explicit cache/session infrastructure)
- [ ] No blocking calls introduced in the UI thread
- [ ] **No hardcoded styles or constants (use theme constants)**
- [ ] **New constants added to theme files only**
### Refactoring
- [ ] No code duplicates (only if directly related to current task)
- [ ] No unused imports
- [ ] No commented-out code
- [ ] No TODO without tickets
- [ ] Clear variable names
### Dependencies
- [ ] Prefer standard library
- [ ] No heavy frameworks
- [ ] No async frameworks (use QThread instead)
- [ ] No additional logging libraries
- [ ] License GPL-3.0 compatible
- [ ] If dependencies are added: added to `pyproject.toml`
- [ ] If dependencies change: `uv lock` run
---
## Error Handling Policy
### When to Rethrow
| Condition | Action | Example |
|-----------|--------|---------|
| Cannot handle locally | Rethrow | API errors in business logic |
| Need to add context | Wrap & rethrow | `raise ValueError(f"Invalid game ID: {game_id}") from e` |
| Public API boundary | Rethrow | Let caller decide |
| Expected & recoverable | Handle with fallback (log when useful) | Cache miss → fetch from source |
```python
# Bad: Silent swallow
try:
data = load_config()
except Exception:
pass
# Good: Rethrow with context
try:
data = load_config()
except FileNotFoundError as e:
raise ConfigError(f"Config not found: {path}") from e
```
### When to Log and Continue
| Condition | Action | Example |
|-----------|--------|---------|
| Non-critical failure | Log, continue | Thumbnail download failed |
| Fallback available | Log, use fallback | Cache miss → network request |
| Best-effort operation | Log, skip | Optional metadata |
| User notification only | Log, notify UI | Network timeout |
```python
# Log and continue for non-critical
try:
cover = download_cover(url)
except requests.RequestException as e:
logger.warning("Cover download failed: %s", e)
cover = QPixmap() # Use placeholder
```
### When to Fail Fast
| Condition | Action | Example |
|-----------|--------|---------|
| Critical dependency | Raise immediately | Database connection lost |
| Data corruption | Raise immediately | Invalid config format |
| Security violation | Raise immediately | Path traversal attempt |
| Unrecoverable state | Raise immediately | Missing required file |
```python
# Fail fast for critical
if not config_path.exists():
raise ConfigError(f"Required config missing: {config_path}")
```
### Exception Hierarchy
```python
# Base exception for application errors
class PortProtonError(Exception):
"""Base exception for PortProtonQt."""
# Domain-specific exceptions
class ConfigError(PortProtonError):
"""Configuration-related errors."""
class APIError(PortProtonError):
"""External API errors."""
class ValidationError(PortProtonError):
"""Input validation errors."""
class ParseError(PortProtonError):
"""Parsing-related errors."""
```
### Error Handling Patterns
```python
# Pattern 1: Guard clauses for validation
def process_game(game_id: str) -> Game:
if not game_id:
raise ValidationError("Game ID required")
...
# Pattern 2: Context manager for resources
with open(path) as f:
data = json.load(f)
# Pattern 3: Specific exception handling
try:
response = requests.get(url, timeout=5)
except requests.Timeout:
logger.warning("Request timeout for %s", url)
return None
except requests.ConnectionError:
logger.error("Connection failed for %s", url)
raise APIError("Network unavailable") from None
# Pattern 4: Exception chaining
try:
value = int(text)
except ValueError as e:
raise ParseError(f"Invalid integer: {text}") from e
```
### UI Thread Rules
| Context | Strategy |
|---------|----------|
| UI thread | Never block, use signals for errors |
| Worker thread | Catch, emit error signal |
| Async operations | Return error in result tuple |
```python
# Worker thread pattern
def run_in_thread():
try:
result = long_operation()
success_signal.emit(result)
except Exception as e:
logger.error("Operation failed: %s", e)
error_signal.emit(str(e))
```
### Logging Guidelines
| Level | When to Use |
|-------|-------------|
| DEBUG | Detailed diagnostic info |
| INFO | Normal operation events |
| WARNING | Recoverable issues |
| ERROR | Failures requiring attention |
| CRITICAL | System-wide failures |
```python
# Log with context
logger.error("Failed to load game %s: %s", game_id, e)
# Include stack trace for unexpected errors
try:
...
except Exception as e:
logger.exception("Unexpected error processing %s", game_id)
```
### Forbidden Patterns
```python
# NEVER: Bare except
try:
...
except:
pass
# NEVER: Catch Exception without logging
try:
...
except Exception:
pass
# NEVER: Silent failures in critical paths
if not critical_file.exists():
return None # Should raise
# NEVER: Multiple exceptions in one handler (unless re-throwing as a unified domain exception)
try:
...
except (FileNotFoundError, ValueError, TypeError, KeyError):
pass # Each needs separate handling
```
---
## Code Style
### Imports
```python
# Standard library
import os
from pathlib import Path
# Third-party
from PySide6.QtWidgets import QApplication
import requests
# Local
from portprotonqt.steam_api import SteamAPI
from portprotonqt.logger import get_logger
```
### Type Hints
```python
def get_game(game_id: str, cache: dict | None = None) -> Game | None:
...
class Game:
name: str
playtime: int
cover_url: str | None
```
### Theme Constants
All style-related constants MUST be defined in theme files, not in application code.
**File structure for theme constants:**
- `portprotonqt/themes/standart/styles/constants.py` — Color constants, sizes, shadow values
- `portprotonqt/themes/standart/styles/base.py` — Global widget styles (MAIN_WINDOW_STYLE, etc.)
- `portprotonqt/themes/standart/styles/game_card.py` — Game card specific styles
- `portprotonqt/themes/standart/styles/detail_page.py` — Detail page styles
- `portprotonqt/themes/standart/styles/settings.py` — Settings dialog styles
- `portprotonqt/themes/standart/styles/get_wine.py` — Wine manager styles
- `portprotonqt/themes/standart/styles/winetricks.py` — Winetricks styles
- `portprotonqt/themes/standart/styles/theme_utils.py` — Utility styles (context menus, etc.)
**Adding new constants:**
```python
# In constants.py — add color constant
color_new_feature = "#FF5733"
# In constants.py — add size constant
new_widget_size = 42
# In base.py or submodule — add QSS style
NEW_WIDGET_STYLE = f"""
QWidget {{
background: {color_new_feature};
border-radius: {border_radius_a};
}}
"""
```
**Usage in application code:**
```python
# Bad: Hardcoded in application code
shadow.setBlurRadius(20)
label.setStyleSheet("color: #bbbbbb;")
# Good: Use theme constants
shadow.setBlurRadius(self.theme.shadow_blur_radius)
label.setStyleSheet(self.theme.CONTENT_STYLE)
```
### Comments
```python
# NEVER: Russian or verbose
# Проверить существование файла
# ALWAYS: Concise English
# Check if file exists
if os.path.exists(path):
...
# ALWAYS: Docstrings for public APIs
def check_file_exists(path: str) -> bool:
"""Check if file exists at given path."""
...
```
---
## Code Review Guidelines
Review scope: prioritize new/modified code. Existing unrelated legacy issues should not block unless they are CRITICAL security issues. Development scripts under `dev-scripts/` follow their exemption rules unless explicitly requested.
### Security (CRITICAL)
- Hardcoded credentials
- SQL injection risks
- Missing input validation on external boundaries (user input, files, network, subprocess args)
- Insecure dependencies
- Path traversal risks
- `shell=True` in subprocess
### Code Quality (HIGH)
- New/rewritten functions >50 lines
- New/rewritten functions >4 params
- New/rewritten files >800 lines
- New/modified code nesting >4 levels
- Missing error handling for expected/recoverable failures in new/modified code
- Circular imports introduced by the change
- Shared mutable global state introduced in new/modified code (except logger and explicit cache/session infrastructure)
- Blocking calls introduced in the UI thread
### Performance (MEDIUM)
- O(n²) when O(n log n) possible
- Missing caching
- N+1 queries
### Best Practices (MEDIUM)
- Emoji usage
- TODO without tickets
- Poor variable naming (x, tmp, data)
- Magic numbers
- Non-English comments
- **Hardcoded styles or constants (colors, sizes, shadow values, etc.)**
### Review Output
```
[CRITICAL] Hardcoded API key
File: portprotonqt/steam_api.py:42
Issue: API key exposed in source code
Fix: Use environment variable
API_KEY = "sk-abc123" # Bad
API_KEY = os.getenv("API_KEY") # Good
[MEDIUM] Hardcoded style value
File: portprotonqt/game_card.py:81
Issue: Shadow color hardcoded instead of using theme
Fix: Use theme constant
shadow.setColor(QColor(0, 0, 0, 150)) # Bad
shadow.setColor(QColor(self.theme.color_shadow_card)) # Good
```
### Approval
- **Approve:** No CRITICAL or HIGH issues
- **Warning:** MEDIUM issues only
- **Block:** CRITICAL or HIGH issues found
---
## Meson Build Guidelines
The `check-meson` hook validates `meson.build` on commit.
**Checks:**
- Syntax: brackets, quotes, commas, control structures
- All `.py` files in `install_data()`
- No duplicates or missing files
### Adding Files
```meson
# portprotonqt/meson.build
install_data(
['existing.py',
'new_module.py',
],
install_dir: pythondir / meson.project_name(),
)
```
### Common Errors
```meson
# Bad: Missing comma # Bad: Unclosed
install_data( install_data(
'file1.py' 'file1.py',
'file2.py' 'file2.py'
) # Missing )
# Good
install_data(
'file1.py',
'file2.py',
)
```
---
## Project Structure
```
PortProtonQt/
├── portprotonqt/ # Python package
│ ├── app.py # Entry point
│ ├── main_window.py # Main window
│ ├── game_card.py # Game card widget
│ ├── steam_api.py # Steam integration
│ ├── egs_api.py # Epic Games integration
│ ├── theme_manager.py # Theme management
│ ├── logger.py # Logging
│ └── themes/ # Theme files
├── build-aux/ # Build resources
├── dev-scripts/ # Development scripts
├── documentation/ # Documentation
├── meson.build # Meson config
├── pyproject.toml # Python config
└── .pre-commit-config.yaml
```
---
## Development Scripts
**`dev-scripts/`** contains development utilities that are not part of the application codebase.
**Policy:**
- Scripts in `dev-scripts/` are exempt from code quality guidelines
- No type hints, linting, or code style requirements apply
- These scripts are for developer convenience only
- Do not refactor or improve dev-scripts unless explicitly requested
---
## Dependencies
### Core
| Package | Purpose | License |
|---------|---------|---------|
| PySide6 | GUI | LGPL |
| Legendary | EGS integration | GPL-3.0 |
| Icoextract | Icon extraction | MIT |
| Requests | HTTP | Apache-2.0 |
| Pillow | Image handling | MIT |
**License compatibility:**
- MIT, Apache-2.0, BSD: Compatible
- LGPL: Requires dynamic linking
- Proprietary: Incompatible
---
## Resources
- [Theme documentation](documentation/theme_guide)
- [Localization guide](documentation/localization_guide)
- [Metadata override guide](documentation/metadata_override)
- [TODO list](TODO.md)
- [Changelog](CHANGELOG.md)
---
**Last updated:** 2026-03-10
**Version:** 1.2
**Status:** Release
+225 -4
View File
@@ -3,20 +3,240 @@
Все заметные изменения в этом проекте фиксируются в этом файле.
Формат основан на [Keep a Changelog](https://keepachangelog.com/) и придерживается принципов [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [0.1.12] - 2026-04-17
### Added
- В настройки PortProton добавлена галочка добавления/удаления инструмента совместимости Steam
- В настройки библиотеки добавлен скрытый тип отображения бейджей
- Добавлена валидация конфига
- Аргумент командной строки `--add-steam-compat-tool` для использования PortProtonQt как инструмента совместимости Steam
- Аргумент командной строки `--reinstall-steam-compat-tool` для переустановки инструмента совместимости Steam в пользовательском каталоге
- Аргумент командной строки `--remove-steam-compat-tool` для удаления инструмента совместимости Steam из пользовательского каталога
- В репозиторий добавлен пакет `portprotonqt-steam-compat` для глобального добавления PortProtonQt как инструмента совместимости Steam
- Добавлена кнопка настроек для игр из Steam, если PortProtonQt используется как инструмент совместимости
- Добавлен прогресс-бар скачивания Wine на детальной странице игры
- Возможность прямого запуска `.exe` через CLI
- Ленивая загрузка данных автоустановок: обложки и метаданные не загружаются, если вкладка скрыта в настройках или пользователь на неё не заходит
- Добавлена кнопка Cancel в диалог управления Wine/Proton для закрытия в WM без рамок окна
- Аргумент командной строки `--resolution` для запуска приложения с определённым разрешением (например, 1920x1080)
- В настройки `.exe` добавлены параметры MangoHud
- В настройки `.exe` добавлены параметры Gamescope
- В настройки `.exe` добавлен выбор второго `.exe` через встроенный файловый менеджер
- В настройки библиотеки добавлен выбор типа бейджей: `Детальный` и `Компактный`
- Создания нового префикса
- Автодополнение fish и zsh для команды `portprotonqt`.
- В диалог добавления/редактирования игры добавлены галочки добавления в Steam, меню и на рабочий стол
- В настройки добавлены опции автозапуска и запуска приложения сразу в трей
- Добавлена поддержка запуска `.iso` (CLI, drag-and-drop и диалог добавления игры)
- На вкладке MangoHud добавлена кнопка записи системного `MangoHud.conf` из текущего env-конфига
- Добавлена вкладка `System` с разделами WIFI, VPN, Bluetooth, Storage, Audio и Power (включается через `--ppqtos`)
- Добавлен аргумент командной строки `--ppqtos` для открытия вкладки `System`
### Changed
- Проверка подключения к интернету теперь использует Yandex как основной сервер с Google в качестве fallback
- Переработан внешний вид вкладки «Настройки PortProton»
- Детальная страница игры адаптирована под маленькие экраны
- На детальной странице Steam-игр добавлена кнопка «Открыть папку с игрой»
- При добавлении и удалении игры из Steam теперь не пишется о необходимости перезапуска, если используется CEF, а не VDF
- Все комментарии в коде переведены на английский язык
- Все комментарии в коде теперь используют модуль logger
- При включении MangoHud в настройках exe также добавляется `MANGOHUD_CONFIG`, если его нет
- Начат рефакторинг скриптов
- Ускорен запуск программы на ~47%
- Снижение потребления памяти на ~17%
- pyproject теперь используется только как менеджер зависимостей для UV, сборка через него больше невозможна
- Скриншоты в metainfo теперь размера 1000x700 для соответствия стандартам Flathub
- Все подсказки при наведении теперь имеют общий вид
- Все константы теперь вынесены в файлы тем
- Все контекстные меню теперь имеют общий вид
- Все таблицы теперь имеют общий вид
- На вкладке «Темы» добавлена явная подсветка фокуса для списка тем, карусели скриншотов и кнопки применения
- Удалены подписи скриншотов тем
- Системный оверлей переработан и перенесён в отдельную вкладку `System`
### Fixed
- Исправлены высокая нагрузка на CPU и утечка памяти при изменении размера карточек
- Скачивание обложек со SteamGridDB теперь асинхронное и не вызывает зависание окна
- Уменьшен таймаут запроса к SteamGridDB с 10 до 3 секунд, чтобы не тормозить запуск при медленном 404
- Запуск игр из трея
- Исправлено обновление сетки библиотеки при удалении карточки игры
- Исправлено отображение пустых вложенных подменю в трее в Dank Material Shell и GNOME.
- Получение статуса античита для игр из Steam
- Кэш обложек со SteamCDN
- Исправлена эмуляция прокрутки через Bluetooth-геймпад в режиме эмуляции мыши
- Исправлен выбор статистики времени: теперь приоритет у совпадающего `sha256` `.exe`, затем у точного пути, а при удалении игры очищается её запись в `data/tmp/statistics`
- Исправлены некорректные комментарии в CSS для combobox
- Исправлена валидация синтаксиса комментариев CSS и опечатки в winetricks.py
- Перевод кнопок «Yes»/«No» в QMessageBox
- Виртуальная клавиатура теперь открывается сверху, если перекрывает поле ввода
- Кнопка «Загрузить резервную копию префикса» больше не выходит за границы окна
- Подсказки управления больше не накладываются друг на друга в маленьком окне
- Исправлено некорректное попадание фокуса на метаинформацию темы при навигации геймпадом
- Навигация геймпадом на вкладке «Темы» ограничена элементами: список тем, карусель скриншотов и кнопка «Применить тему»
- При наличии `custom_data` отключены сетевые запросы обложек к SGDB и SteamCDN для карточек игр
- Отключён автоскролл `QComboBox` колесом мыши, когда выпадающий список закрыт
- Исправлен поиск `.desktop` при несовпадении имени карточки и файла (в том числе после редактирования): добавлено сопоставление через `custom_data/*/metadata.txt` (`name`) с fallback по данным `.desktop`
- Виртуальная клавиатура теперь адаптирует ширину кнопок под размер окна
- Усилена общая безопасность механизма пользовательских тем, включая валидацию, проверки загрузки и устойчивость к некорректным/потенциально опасным темам
- Улучшено формирование ссылок WeAntiCheatYet
### Contributors
- @Simple16
- @Dervart
---
## [0.1.11] - 2026-02-18
### Added
- Настройка для скрытия вкладки автоустановок
- Запуск в режиме лога
- Экспериментальная поддержка ARM через запуск в muvm
- Аргумент командной строки --force-muvm (автоматический запуск в muvm происходит только при наличии Apple Silicon)
- Утилита vk_gpu_info для использования в логе
- Выбор GPU для запуска игр в настройках
- Выбор системного WINE в настройках игры
- Кнопка открыть PPDB в настройках игры
### Changed
- qt6-svg теперь обязательная зависимость
- Проект теперь собирается с использованием meson
- Виртуальная клавиатура теперь открывается при нажатии на любое поле для ввода
- Удалена настройка для выбора поставщика Vulkan AMD
- Бейдж PortProton теперь открывает ppdb.linux-gaming.ru, а не linux-gaming.ru
- Изменена структура тем для поддержки вложенных папок
- После скачивания Wine список выбранных Wine теперь очищается
- Эмуляция мыши через геймпад теперь не зависит от окна в фокусе и работает всегда
- У настроек убран префикс PW и _ заменены на пробелы
- Кнопки создания лога и настроек теперь не отображаются на карточках Steam игр
### Fixed
- Подсказки на виртуальной клавиатуре изменяются сразу при смене gamepad_type в настройках без необходимости перезапуска
- Исправлено определение Flatpak версии PortProton
- Исправлена работа модульных локальных тем
- Исправлена упаковка локалей
### Contributors
- @Simple16
---
## [0.1.10] - 2026-01-14
### Added
- Детальная страница для автоустановок с описанием игры и возможности переустановки
- Менеджер версий Wine для скачивания и удаления различных версий Wine и Proton
- Возможность перевода описаний, названий тем на другие языки
- Возможность перевода подписи к скриншотам тем на другие языки
### Changed
- Проведена чистка мёртвого кода
- Улучшена проверка сторонних тем
- В документации по созданию тем добавлены примеры dropin тем
- Проведена редактура перевода
- Переработана сортировка вайнов и префиксов во всех комбобоксах
- Список Wine и префиксов теперь обновляется на лету, а не при запуске приложения
- AppImage теперь работает на дистрибутивах, использующих альтернативный libc, а также на тех, что не следуют стандарту FHS
### Fixed
- Изменение размера карточек автоустановок через геймпад
- Проведена работа по исправлению утечек памяти
- Время игры теперь парсится даже если файл статистики повреждён
- При наличии битых обложек они теперь перекачиваются, а не провоцируют ошибки libpng
- Управление QMessageBox через стрелки клавиатуры
### Contributors
- @Vector_null
- @Dervart
- @Simple16
---
## [0.1.9] - 2025-12-08
### Added
- Добавлены основные и расширенные настройки для `.exe`-файлов
- Добавлена кнопка обновления сетки без необходимости перезапуска PortProtonQt (F5 на клавиатуре, GUIDE + Select на геймпаде)
- Добавлена эмуляция мыши по GUIDE (Xbox или PS) + Start для установки приложений или взаимодействия с инструментами Wine, не адаптированными под геймпад (работает только если PortProtonQt вне фокуса)
- При сворачивании приложения в трей оно теперь корректно восстанавливается, вместо запуска нового экземпляра
- Добавлена поддержка SteamGridDB в качестве дополнительного источника обложек
- При добавлении карточки в избранное она автоматически становится первой без необходимости перезапуска
### Changed
- Изменено оформление виртуальной клавиатуры для лучшего соответствия общей теме
- Ускорено чтение конфигов за счёт уменьшения количества обращений к файловой системе.
- Из стандартной темы удалены неиспользуемые шрифты
- Улучшена совместимость с Qt 6.10
- Ускорен запуск программы
- В диалог редактирования ярлыка добавлен placeholder с уточнением того, что в качестве обложки можно использовать и ссылку, а не только файл
- Ссылку на обложку в диалоге редактирования ярлыка теперь можно указывать без протокола вроде http или https
### Fixed
- Добавлено больше проверок на None для избежания вылетов
- Улучшена работа с потоками для избежания вылетов
- Исправлен запуск PortProton из Flatpak: теперь используется `flatpak run`, а не `start.sh`
- Исправлено применение обложки по ссылке например со steamgriddb.com/
- Исправлено множественное открытие окон в X11
### Contributors
- @Vector_null
- @Dervart
---
## [0.1.8] - 2025-10-18
### Added
- В настройки добавлен пункт для выбора типа геймпада для подсказок по управлению
- В настройки добавлен пункт для выбора сворачивать ли приложение в трей или нет
- К диалогу добавления игры, Winetricks, диалогу выбора файлов и виртуальной клавиатуре добавлены подсказки по управлению с геймпада
- Во вкладку автоустановок добавлен слайдер изменения размера карточек (они со слайдером в библиотеке независимы)
### Changed
- При завершении автоустановки приложение больше не перезапускается
- Выбор exe в диалоге добавления игры больше не перезаписывает введенное в поле название
- Обновлены и дополнены скриншоты темы
### Fixed
- Исправлено наложение карточек при смене фильтра игр
- Исправлена невозможность запуска приложения без подключённого геймпада
- Исправлена невозможность установки компонентов Winetricks через геймпад
- Ресиверы и виртуальные устройства больше не считаются за геймпад
### Contributors
- @Vector_null
---
## [0.1.7] - 2025-10-12
### Added
- Возможность скроллинга библиотеки мышью или пальцем
- Импорт и экспорт бекапа префикса
- Диалог для управление Winetricks
- Кнопки для удаления префикса, wine или proton
- Все настройки Wine с оригинального PortProton
- Виртуальная клавиатура в диалог добавления игры и поиск по библиотеке и автоустановках
- Вкладка автоустановок
- В заголовке окна теперь отображается версия приложения и хеш коммита если запуск идёт с гита
### Changed
- Проведён рефакторинг и оптимизация всего что связано с карточками и библиотекой игр
- В диалог выбора файлов в режиме directory_only (при выборе куда сохранить бекап префикса) добавлена кнопка ./ обозначающая нынешнюю папку
### Fixed
- Исправлен вылет диалога выбора файлов при выборе обложки если в папке более сотни изображений
- Исправлено зависание при добавлении или удалении игры в Wayland
- Исправлено зависание при поиске игр
- Исправлено ошибочное присвоение ID игры с названием "GAME", возникавшее, если исполняемый файл находился в подпапке `game/` (часто встречается у игр на Unity)
- Исправлена ошибка из-за которой подсказки по управлению снизу и сверху могли не совпадать с друг другом, из-за чего возле вкладок были стрелки клавиатуры, а снизу кнопки геймпада
- Исправлен выход из полноэкранного режима при отключении геймпада подключённого по USB даже если настройка "Режим полноэкранного отображения приложения при подключении геймпада" выключена
- При сохранении настроек теперь не меняется размер окна
### Contributors
- @wmigor (Igor Akulov)
- @Vector_null
---
@@ -31,7 +251,7 @@
- Аргумент cli --debug-level для указания уровня дебага
### Changed
- Управления с геймпада теперь перехватывается только если окно в фокусе
- Управление с геймпада теперь перехватывается, только если окно в фокусе
### Fixed
- Исправлена проблема с устаревшими кэш-файлами, вызывающими несоответствия при обновлении JSON
@@ -39,6 +259,7 @@
### Contributors
- @wmigor (Igor Akulov)
- @Vector_null
---
@@ -68,7 +289,7 @@
- Добавление и удаление игр из Steam больше не требует перезапуска клиента.
- Обновлены все зависимости (затрагивает только AppImage).
- Приложение теперь не закрывается полностью, а сворачивается в трей.
- Карточки теперь все находятся друг под другом, а не в разнабой
- Карточки теперь все находятся друг под другом, а не вразброс
- Изменено соотношение сторон карточек
### Fixed
@@ -218,7 +439,7 @@
---
## [0.1.1] – 2025-05-17
## [0.1.1] — 2025-05-17
### Added
- Алфавитная сортировка библиотеки.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+6 -2
View File
@@ -9,7 +9,9 @@
```sh
uv python install 3.10
uv sync
source .venv/bin/activate
source .venv/bin/activate # For bash/zsh
# or
source .venv/bin/activate.fish # For fish
```
Запуск производится по команде portprotonqt
@@ -27,7 +29,9 @@ source .venv/bin/activate
```sh
uv python install 3.10
uv sync --all-extras --dev
source .venv/bin/activate
source .venv/bin/activate # For bash/zsh
# or
source .venv/bin/activate.fish # For fish
pre-commit install
```
+9 -11
View File
@@ -1,28 +1,27 @@
- [X] Адаптировать структуру проекта для поддержки инструментов сборки
- [X] Добавить возможность управления с геймпада
- [ ] Добавить возможность управления с тачскрина
- [X] Добавить возможность управления с тачскрина (Формально и так есть)
- [X] Добавить возможность управления с мыши и клавиатуры
- [X] Добавить систему тем [Документация](documentation/theme_guide)
- [X] Вынести все константы, такие как уровень закругления карточек, в темы (частично выполнено)
- [X] Добавить метаданные для тем (скриншоты, описание, домашняя страница и автор)
- [ ] Продумать систему вкладок вместо текущей
- [X] [Добавить сессию Gamescope, аналогичную той, что используется в SteamOS](https://git.linux-gaming.ru/Boria138/gamescope-session-portprotonqt)
- [X] Разобраться почему теряется часть стилей в Gamescope
- [ ] Разработать адаптивный дизайн (за эталон берётся Steam Deck с разрешением 1280×800)
- [ ] Переделать скриншоты для соответствия [гайдлайнам Flathub](https://docs.flathub.org/docs/for-app-authors/metainfo-guidelines/quality-guidelines#screenshots)
- [x] Разработать адаптивный дизайн (за эталон берётся 1000x700 из гайдлайнов Flathub)
- [x] Переделать скриншоты для соответствия [гайдлайнам Flathub](https://docs.flathub.org/docs/for-app-authors/metainfo-guidelines/quality-guidelines#screenshots)
- [X] Получать описания и названия игр из базы данных Steam
- [X] Получать обложки для игр из SteamGridDB или CDN Steam
- [X] Получать обложки для игр из CDN Steam
- [X] Оптимизировать работу со Steam API для ускорения времени запуска
- [X] Улучшить функцию поиска в Steam API для исправления некорректного определения ID (например, Graven определялся как ENGRAVEN или GRAVENFALL, Spore — как SporeBound или Spore Valley)
- [ ] Убрать логи Steam API в релизной версии, так как они замедляют выполнение кода
- [X] Убрать логи Steam API в релизной версии, так как они замедляют выполнение кода
- [X] Решить проблему с ограничением Steam API в 50 тысяч игр за один запрос (иногда нужные игры не попадают в выборку и остаются без обложки)
- [X] Избавиться от вызовов yad
- [X] Реализовать собственный системный трей вместо использования трея PortProton
- [X] Добавить экранную клавиатуру в поиск (реализация собственной клавиатуры слишком затратна, поэтому используется встроенная в DE клавиатура: Maliit в KDE, gjs-osk в GNOME, Squeekboard в Phosh, клавиатура SteamOS и т.д.)
- [X] Добавить экранную клавиатуру в поиск
- [X] Добавить сортировку карточек по различным критериям (доступны: по недавности, количеству наигранного времени, избранному или алфавиту)
- [X] Добавить индикацию запуска приложения
- [X] Достигнуть паритета функциональности с Ingame
- [ ] Достигнуть паритета функциональности с PortProton
- [ ] Достигнуть паритета функциональности с PortProton (остались обновление скриптов)
- [X] Добавить возможность изменения названия, описания и обложки через файлы `.local/share/PortProtonQT/custom_data/exe_name/{desc,name,cover}`
- [X] Добавить встроенное переопределение названия, описания и обложки, например, по пути `portprotonqt/custom_data` [Документация](documentation/metadata_override/)
- [X] Добавить переводы в переопределения
@@ -49,7 +48,7 @@
- [X] Добавить недокументированные параметры конфигурации в GUI (time_detail_level, games_sort_method, games_display_filter)
- [X] Добавить систему избранного для карточек
- [X] Заменить все `print` на `logging`
- [ ] Привести все логи к единому языку
- [X] Привести все логи к единому языку
- [X] Уменьшить количество подстановок в переводах
- [X] Стилизовать все элементы без стилей (QMessageBox, QSlider, QDialog)
- [X] Убрать жёсткую привязку путей к стрелочкам QComboBox в `styles.py`
@@ -62,7 +61,6 @@
- [X] Исправить некорректную работу слайдера увеличения размера карточек([Последствия регрессии после этого коммита](https://github.com/Boria138/PortProtonQt/commit/aebdd60b5537280f06a922ff80469cd4ab27bc63)
- [X] Исправить баг с наложением карточек друг на друга при изменении фильтра отображения ([Последствия регрессии после этого коммита](https://github.com/Boria138/PortProtonQt/commit/aebdd60b5537280f06a922ff80469cd4ab27bc63))
- [X] Скопировать логику управления с D-pad на стрелки с клавиатуры
- [ ] Доделать светлую тему
- [ ] Добавить подсказки к управлению с геймпада
- [X] Добавить подсказки к управлению с геймпада
- [X] Добавить миниатюры к выбору файлов в диалоге добавления игры
- [X] Добавить быстрый доступ к смонтированным дискам к выбору файлов в диалоге добавления игры
+115
View File
@@ -0,0 +1,115 @@
#!/bin/sh
set -eu
# Initialize variables
LOCAL_MODE=false
BRANCH="main"
REPO_URL="https://git.linux-gaming.ru/Boria138/PortProtonQt.git"
# Parse arguments
while [ $# -gt 0 ]; do
case "$1" in
--local|-l)
LOCAL_MODE=true
;;
--branch)
if [ -n "${2:-}" ] && [ "${2#-}" = "$2" ]; then
BRANCH="$2"
shift
else
echo "Error: --branch requires an argument"
exit 1
fi
;;
--repo)
if [ -n "${2:-}" ] && [ "${2#-}" = "$2" ]; then
REPO_URL="$2"
shift
else
echo "Error: --repo requires an argument"
exit 1
fi
;;
*)
echo "Unknown option: $1"
exit 1
;;
esac
shift
done
ARCH="$(uname -m)"
EXTRA_PACKAGES="https://raw.githubusercontent.com/pkgforge-dev/Anylinux-AppImages/refs/heads/main/useful-tools/get-debloated-pkgs.sh"
if [ "$LOCAL_MODE" = true ]; then
echo "Using local PKGBUILD-git from repository..."
PPQT_PKGBUILD=""
else
echo "Using stable version of PortProtonQt from main branch..."
PPQT_PKGBUILD="https://git.linux-gaming.ru/Boria138/PortProtonQt/raw/branch/main/build-aux/PKGBUILD"
fi
echo "Tweak makepkg..."
echo "---------------------------------------------------------------"
# Disable creating debug packages
sed -i 's/OPTIONS=(.*)/OPTIONS=(strip docs !libtool !staticlibs emptydirs zipman purge lto)/g' /etc/makepkg.conf
# Setup packager name
sed -i 's/#PACKAGER=".*"/PACKAGER="Linux Gaming Team"/g' /etc/makepkg.conf
# Use all threads for building
sed -i 's/#MAKEFLAGS="-j2"/MAKEFLAGS="-j$(nproc) -l$(nproc)"/g' /etc/makepkg.conf
# makepkg cannot not as root by default
sed -i -e 's|EUID == 0|EUID == 69|g' /usr/bin/makepkg
# always disable this nonsense that was recently added to makepkg
sed -i -e 's/(( ${#arch\[@\]} != $(printf "%s\\n" ${arch\[@\]} | sort -u | wc -l) ))/false/' /usr/share/makepkg/lint_pkgbuild/arch.sh 2>/dev/null || :
echo "Tweak pacman..."
echo "---------------------------------------------------------------"
pacman-key --init
pacman -S --noconfirm archlinux-keyring
# Chaotic-AUR keys
pacman-key --recv-key 3056513887B78AEB --keyserver keyserver.ubuntu.com
pacman-key --lsign-key 3056513887B78AEB
pacman -U --noconfirm 'https://cdn-mirror.chaotic.cx/chaotic-aur/chaotic-keyring.pkg.tar.zst'
pacman -U --noconfirm 'https://cdn-mirror.chaotic.cx/chaotic-aur/chaotic-mirrorlist.pkg.tar.zst'
# Enable the multilib repository
cat << EOM >> /etc/pacman.conf
[multilib]
Include = /etc/pacman.d/mirrorlist
[chaotic-aur]
Include = /etc/pacman.d/chaotic-mirrorlist
SigLevel = Never
EOM
# Disable locale noextract
sed -i -E 's@[[:space:]]*usr/share/locale/\*@@g; s@[[:space:]]+@ @g; s@[[:space:]]+$@@' /etc/pacman.conf
pacman -Syy
echo "Building PortProtonQt from PKGBUILD..."
echo "---------------------------------------------------------------"
if [ "$LOCAL_MODE" = true ]; then
cp ../PKGBUILD-git ./PKGBUILD
else
wget --retry-connrefused --tries=30 "$PPQT_PKGBUILD" -O ./PKGBUILD
fi
sed -i "s|source=(\"git+https://git.linux-gaming.ru/Boria138/PortProtonQt.git\")|source=(\"git+${REPO_URL}#branch=$BRANCH\")|" PKGBUILD
makepkg -si --noconfirm
echo "Installing debloated packages..."
echo "---------------------------------------------------------------"
wget --retry-connrefused --tries=30 "$EXTRA_PACKAGES" -O ./get-debloated-pkgs.sh
chmod +x ./get-debloated-pkgs.sh
./get-debloated-pkgs.sh --add-common --prefer-nano
if [ "$LOCAL_MODE" = true ]; then
# For git version, we use portprotonqt-git
pacman -Q portprotonqt-git | awk '{print $2}' | cut -d- -f1 > ~/version
else
# For stable version, we use portprotonqt
pacman -Q portprotonqt | awk '{print $2}' | cut -d- -f1 > ~/version
fi
+38
View File
@@ -0,0 +1,38 @@
#!/bin/sh
set -eu
SHARUN="https://raw.githubusercontent.com/pkgforge-dev/Anylinux-AppImages/refs/heads/main/useful-tools/quick-sharun.sh"
ARCH="$(uname -m)"
VERSION="$(cat ~/version)"
export ARCH VERSION
export OUTPATH=./dist
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_SYS_PYTHON=1
export OPTIMIZE_LAUNCH=1
# Adjust comp settings to bypass oom-killer
export DWARFS_COMP="zstd:level=15 -S22 -B5"
# DEPLOY ALL LIBS
wget --retry-connrefused --tries=30 "$SHARUN" -O ./quick-sharun
chmod +x ./quick-sharun
# Add udev rules
mkdir -p ./AppDir/etc/udev/rules.d
cp /usr/lib/udev/rules.d/60-portprotonqt.rules ./AppDir/etc/udev/rules.d
# Deploy dependencies
# Qt libs have to be passed manually due to the app being a python script
./quick-sharun \
/usr/bin/portprotonqt* \
/usr/lib/libQt6Core.so* \
/usr/lib/libQt6Gui.so* \
/usr/lib/libQt6Network.so* \
/usr/lib/libudev.so*
# Turn AppDir into AppImage
./quick-sharun --make-appimage
-74
View File
@@ -1,74 +0,0 @@
version: 1
script:
- rm -rf AppDir || true
- mkdir -p AppDir/usr/local/lib/python3.10/dist-packages
- uv venv
- uv pip install --no-cache-dir ../
- cp -r .venv/lib/python3.10/site-packages/* AppDir/usr/local/lib/python3.10/dist-packages
- cp -r share AppDir/usr
- rm -rf AppDir/usr/local/lib/python3.10/dist-packages/PySide6/Qt/qml/
- rm -f AppDir/usr/local/lib/python3.10/dist-packages/PySide6/{assistant,designer,linguist,lrelease,lupdate}
- rm -f AppDir/usr/local/lib/python3.10/dist-packages/PySide6/{Qt3DAnimation*,Qt3DCore*,Qt3DExtras*,Qt3DInput*,Qt3DLogic*,Qt3DRender*,QtBluetooth*,QtCharts*,QtConcurrent*,QtDataVisualization*,QtDesigner*,QtExampleIcons*,QtGraphs*,QtGraphsWidgets*,QtHelp*,QtHttpServer*,QtLocation*,QtMultimedia*,QtMultimediaWidgets*,QtNetwork*,QtNetworkAuth*,QtNfc*,QtOpenGL*,QtOpenGLWidgets*,QtPdf*,QtPdfWidgets*,QtPositioning*,QtPrintSupport*,QtQml*,QtQuick*,QtQuick3D*,QtQuickControls2*,QtQuickTest*,QtQuickWidgets*,QtRemoteObjects*,QtScxml*,QtSensors*,QtSerialBus*,QtSerialPort*,QtSpatialAudio*,QtSql*,QtStateMachine*,QtSvgWidgets*,QtTest*,QtTextToSpeech*,QtUiTools*,QtWebChannel*,QtWebEngineCore*,QtWebEngineQuick*,QtWebEngineWidgets*,QtWebSockets*,QtWebView*,QtXml*}
- shopt -s extglob
- rm -rf AppDir/usr/local/lib/python3.10/dist-packages/PySide6/Qt/lib/!(libQt6Core*|libQt6DBus*|libQt6Egl*|libQt6Gui*|libQt6Svg*|libQt6Wayland*|libQt6Widgets*|libQt6XcbQpa*|libicudata*|libicui18n*|libicuuc*)
AppDir:
path: ./AppDir
after_bundle:
- rm -rf $TARGET_APPDIR/usr/share/man || true
- rm -rf $TARGET_APPDIR/usr/share/doc || true
- rm -rf $TARGET_APPDIR/usr/share/doc-base || true
- rm -rf $TARGET_APPDIR/usr/share/info || true
- rm -rf $TARGET_APPDIR/usr/share/help || true
- rm -rf $TARGET_APPDIR/usr/share/gtk-doc || true
- rm -rf $TARGET_APPDIR/usr/share/devhelp || true
- rm -rf $TARGET_APPDIR/usr/share/examples || true
- rm -rf $TARGET_APPDIR/usr/share/pkgconfig || true
- rm -rf $TARGET_APPDIR/usr/share/bash-completion || true
- rm -rf $TARGET_APPDIR/usr/share/pixmaps || true
- rm -rf $TARGET_APPDIR/usr/share/mime || true
- rm -rf $TARGET_APPDIR/usr/share/metainfo || true
- rm -rf $TARGET_APPDIR/usr/include || true
- rm -rf $TARGET_APPDIR/usr/lib/pkgconfig || true
- find $TARGET_APPDIR -type f \( -name '*.a' -o -name '*.la' -o -name '*.h' -o -name '*.cmake' -o -name '*.pdb' \) -delete || true
- "find $TARGET_APPDIR -type f -executable -exec file {} \\; | grep ELF | grep -v '/dist-packages/' | grep -v '/site-packages/' | cut -d: -f1 | xargs strip --strip-unneeded || true"
- find $TARGET_APPDIR -type d -empty -delete || true
app_info:
id: ru.linux_gaming.PortProtonQt
name: PortProtonQt
icon: ru.linux_gaming.PortProtonQt
version: 0.1.6
exec: usr/bin/python3
exec_args: "-m portprotonqt.app $@"
apt:
arch: amd64
sources:
- sourceline: 'deb [arch=amd64] http://archive.ubuntu.com/ubuntu/ jammy main restricted universe multiverse'
key_url: 'http://keyserver.ubuntu.com/pks/lookup?op=get&search=0x871920d1991bc93c'
include:
- python3-minimal
- python3-pkg-resources
- libopengl0
- libk5crypto3
- libkrb5-3
- libgssapi-krb5-2
- libxcb-cursor0
- libimage-exiftool-perl
- xdg-utils
exclude:
- "*-doc"
- "*-man"
- manpages
- mandb
- "*-dev"
- "*-static"
- "*-dbg"
- "*-dbgsym"
runtime:
env:
PYTHONHOME: '${APPDIR}/usr'
PYTHONPATH: '${APPDIR}/usr/local/lib/python3.10/dist-packages'
PERLLIB: '${APPDIR}/usr/share/perl5:${APPDIR}/usr/lib/x86_64-linux-gnu/perl/5.34:${APPDIR}/usr/share/perl/5.34'
AppImage:
sign-key: None
arch: x86_64
comp: zstd
+39 -11
View File
@@ -1,23 +1,51 @@
pkgname=portprotonqt
pkgver=0.1.6
pkgname=('portprotonqt' 'portprotonqt-steam-compat')
pkgver=0.1.12
pkgrel=1
pkgdesc="Modern GUI for managing and launching games from PortProton, Steam, and Epic Games Store"
arch=('any')
url="https://git.linux-gaming.ru/Boria138/PortProtonQt"
license=('GPL-3.0')
depends=('python-numpy' 'python-requests' 'python-babel' 'python-evdev' 'python-pyudev' 'python-orjson'
'python-psutil' 'python-tqdm' 'python-vdf' 'pyside6' 'icoextract' 'python-pillow' 'perl-image-exiftool' 'xdg-utils' 'python-beautifulsoup4' 'python-websocket-client')
makedepends=('python-'{'build','installer','setuptools','wheel'})
depends=('python-requests' 'python-babel' 'python-evdev' 'python-pyudev' 'python-orjson'
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'icoextract' 'python-pillow' 'perl-image-exiftool' 'python-beautifulsoup4' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'unrar' 'qt6-svg' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' '7zip')
depends_aarch64=('muvm')
makedepends=('meson' 'ninja' 'vulkan-headers' 'gettext')
source=("git+https://git.linux-gaming.ru/Boria138/PortProtonQt#tag=v$pkgver")
sha256sums=('SKIP')
build() {
cd "$srcdir/PortProtonQt"
python -m build --wheel --no-isolation
arch-meson PortProtonQt build
meson compile -C build
}
package() {
cd "$srcdir/PortProtonQt"
python -m installer --destdir="$pkgdir" dist/*.whl
cp -r build-aux/share "$pkgdir/usr/"
package_portprotonqt() {
pkgdesc="Modern GUI for managing and launching games from PortProton, Steam, and Epic Games Store"
optdepends=(
'networkmanager: System tab network management'
'bluez: System tab bluetooth management'
'upower: System tab bluetooth battery level'
'libpulse: System tab audio volume/output management'
'python-dbus-fast: System tab D-Bus integration'
'python-qrcode: Wi-Fi QR code generation'
)
DESTDIR="$pkgdir" meson install -C build --skip-subprojects
bash "$srcdir/PortProtonQt/dev-scripts/generate-completions.sh"
install -Dpm 0644 "$srcdir/PortProtonQt/completions/portprotonqt" -t "$pkgdir/usr/share/bash-completion/completions"
install -Dpm 0644 "$srcdir/PortProtonQt/completions/portprotonqt.fish" -t "$pkgdir/usr/share/fish/vendor_completions.d"
install -Dpm 0644 "$srcdir/PortProtonQt/completions/_portprotonqt" -t "$pkgdir/usr/share/zsh/site-functions"
# Remove steam-compat files from main package
rm -rf "$pkgdir/usr/share/steam"
}
package_portprotonqt-steam-compat() {
pkgdesc="Steam compatibility tool for PortProtonQt"
depends=('portprotonqt')
DESTDIR="$pkgdir" meson install -C build --skip-subprojects
# Keep only steam-compat files
find "$pkgdir/usr" -mindepth 1 -type f -not -path "${pkgdir}/usr/share/steam*" -print0 | xargs -0 rm -f
find "$pkgdir/usr" -mindepth 1 -type d -not -path "${pkgdir}/usr/share/steam*" -empty -delete
}
+39 -11
View File
@@ -1,13 +1,14 @@
pkgname=portprotonqt-git
pkgname=('portprotonqt-git' 'portprotonqt-git-steam-compat')
pkgver=.
pkgrel=1
pkgdesc="Modern GUI for managing and launching games from PortProton, Steam, and Epic Games Store.(developerment build)"
pkgdesc="Modern GUI for managing and launching games from PortProton, Steam, and Epic Games Store (development build)"
arch=('any')
url="https://git.linux-gaming.ru/Boria138/PortProtonQt"
license=('GPL-3.0')
depends=('python-numpy' 'python-requests' 'python-babel' 'python-evdev' 'python-pyudev' 'python-orjson'
'python-psutil' 'python-tqdm' 'python-vdf' 'pyside6' 'icoextract' 'python-pillow' 'perl-image-exiftool' 'xdg-utils' 'python-beautifulsoup4' 'python-websocket-client')
makedepends=('python-'{'build','installer','setuptools','wheel'})
depends=('python-requests' 'python-babel' 'python-evdev' 'python-pyudev' 'python-orjson'
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'icoextract' 'python-pillow' 'perl-image-exiftool' 'python-beautifulsoup4' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'unrar' 'qt6-svg' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' '7zip')
depends_aarch64=('muvm')
makedepends=('meson' 'ninja' 'vulkan-headers' 'gettext')
source=("git+https://git.linux-gaming.ru/Boria138/PortProtonQt.git")
sha256sums=('SKIP')
@@ -17,12 +18,39 @@ pkgver() {
}
build() {
cd "$srcdir/PortProtonQt"
python -m build --wheel --no-isolation
arch-meson PortProtonQt build
meson compile -C build
}
package() {
cd "$srcdir/PortProtonQt"
python -m installer --destdir="$pkgdir" dist/*.whl
cp -r build-aux/share "$pkgdir/usr/"
package_portprotonqt-git() {
pkgdesc="Modern GUI for managing and launching games from PortProton, Steam, and Epic Games Store (development build)"
optdepends=(
'networkmanager: System tab network management'
'bluez: System tab bluetooth management'
'upower: System tab bluetooth battery level'
'libpulse: System tab audio volume/output management'
'python-dbus-fast: System tab D-Bus integration'
'python-qrcode: Wi-Fi QR code generation'
)
DESTDIR="$pkgdir" meson install -C build --skip-subprojects
bash "$srcdir/PortProtonQt/dev-scripts/generate-completions.sh"
install -Dpm 0644 "$srcdir/PortProtonQt/completions/portprotonqt" -t "$pkgdir/usr/share/bash-completion/completions"
install -Dpm 0644 "$srcdir/PortProtonQt/completions/portprotonqt.fish" -t "$pkgdir/usr/share/fish/vendor_completions.d"
install -Dpm 0644 "$srcdir/PortProtonQt/completions/_portprotonqt" -t "$pkgdir/usr/share/zsh/site-functions"
# Remove steam-compat files from main package
rm -rf "$pkgdir/usr/share/steam"
}
package_portprotonqt-git-steam-compat() {
pkgdesc="Steam compatibility tool for PortProtonQt (development build)"
depends=('portprotonqt-git')
DESTDIR="$pkgdir" meson install -C build --skip-subprojects
# Keep only steam-compat files
find "$pkgdir/usr" -mindepth 1 -type f -not -path "${pkgdir}/usr/share/steam*" -print0 | xargs -0 rm -f
find "$pkgdir/usr" -mindepth 1 -type d -not -path "${pkgdir}/usr/share/steam*" -empty -delete
}
+66 -22
View File
@@ -1,38 +1,35 @@
%global pypi_name portprotonqt
%global pypi_version 0.1.1
%global pypi_version 0.1.12
%global oname PortProtonQt
%global build_timestamp %(date +"%Y%m%d")
%global _python_no_extras_requires 1
%global rel_build 1.git.%{build_timestamp}%{?dist}
Name: python-%{pypi_name}-git
Name: %{pypi_name}-git
Version: %{pypi_version}
Release: %{rel_build}
Summary: Modern GUI for managing and launching games from PortProton, Steam, and Epic Games Store (development build)
License: GPL-3.0
URL: https://git.linux-gaming.ru/Boria138/PortProtonQt
BuildArch: noarch
ExclusiveArch: x86_64 aarch64
BuildRequires: meson >= 0.61.2
BuildRequires: ninja-build
BuildRequires: python3-devel
BuildRequires: python3-wheel
BuildRequires: python3-pip
BuildRequires: python3-build
BuildRequires: pyproject-rpm-macros
BuildRequires: python3dist(setuptools)
BuildRequires: git
BuildRequires: gettext
BuildRequires: systemd-rpm-macros
BuildRequires: vulkan-loader-devel
BuildRequires: gcc
%description
%{summary}
Obsoletes: python3-%{pypi_name}-git < %{version}-%{release}
Provides: python3-%{pypi_name}-git = %{version}-%{release}
%package -n python3-%{pypi_name}-git
Summary: %{summary}
%{?python_provide:%python_provide python3-%{pypi_name}}
Requires: python3-babel
Requires: python3-evdev
Requires: python3-icoextract
Requires: python3-numpy
Requires: python3-websocket-client
Requires: python3-orjson
Requires: python3-psutil
@@ -43,13 +40,45 @@ Requires: python3-tqdm
Requires: python3-vdf
Requires: python3-pefile
Requires: python3-pillow
Requires: perl-Image-ExifTool
Requires: xdg-utils
Requires: python3-beautifulsoup4
Requires: python3-rapidfuzz
Requires: python3-libarchive-c
Requires: perl-Image-ExifTool
Requires: qt6-qtsvg
Requires: cabextract
Requires: gzip
Requires: unzip
Requires: curl
Requires: unrar
Requires: glx-utils
Requires: pciutils
Requires: vulkan-loader
Requires: 7zip
%description -n python3-%{pypi_name}-git
# System Tab
Recommends: NetworkManager
Recommends: bluez
Recommends: upower
Recommends: pulseaudio-utils
Recommends: python3-dbus-fast
Recommends: python3-qrcode
%ifarch aarch64
Requires: muvm
%endif
%description
This application provides a sleek, intuitive graphical interface for managing and launching games from PortProton, Steam, and Epic Games Store. It consolidates your game libraries into a single, user-friendly hub for seamless navigation and organization. Its lightweight structure and cross-platform support deliver a cohesive gaming experience, eliminating the need for multiple launchers. Unique PortProton integration enhances Linux gaming, enabling effortless play of Windows-based titles with minimal setup.
%package -n %{pypi_name}-git-steam-compat
Summary: Steam compatibility tool for PortProtonQt (development build)
License: GPL-3.0
Requires: %{pypi_name}-git = %{version}-%{release}
%description -n %{pypi_name}-git-steam-compat
Steam compatibility tool integration for PortProtonQt. This package installs
the necessary files to use PortProtonQt as a Proton compatibility tool in Steam.
%{?python_disable_dependency_generator}
%prep
@@ -57,19 +86,34 @@ git clone https://git.linux-gaming.ru/Boria138/PortProtonQt.git
%build
cd %{oname}
%pyproject_wheel
%meson \
-Dpython_purelibdir=%{python3_sitelib} \
-Dudev_rulesdir=%{_udevrulesdir}
%meson_build
%install
cd %{oname}
%pyproject_install
%pyproject_save_files %{pypi_name}
cp -r build-aux/share %{buildroot}/usr/
%meson_install
bash ./dev-scripts/generate-completions.sh
install -Dpm 0644 ./completions/portprotonqt -t %{buildroot}%{bash_completions_dir}
install -Dpm 0644 ./completions/portprotonqt.fish -t %{buildroot}%{fish_completions_dir}
install -Dpm 0644 ./completions/_portprotonqt -t %{buildroot}%{zsh_completions_dir}
%find_lang %{pypi_name}
%files -n python3-%{pypi_name}-git -f %{pyproject_files}
%files -f %{oname}/%{pypi_name}.lang
%{_bindir}/%{pypi_name}
%{_bindir}/vk_gpu_info
%{python3_sitelib}/%{pypi_name}/
%{_datadir}/icons/hicolor/scalable/apps/ru.linux_gaming.PortProtonQt.svg
%{_metainfodir}/ru.linux_gaming.PortProtonQt.metainfo.xml
%{_udevrulesdir}/60-portprotonqt.rules
%{_datadir}/polkit-1/rules.d/ru.linux_gaming.PortProtonQt.rules
%{_datadir}/applications/ru.linux_gaming.PortProtonQt.desktop
%{bash_completions_dir}/portprotonqt
%{fish_completions_dir}/portprotonqt.fish
%{zsh_completions_dir}/_portprotonqt
%files -n %{pypi_name}-git-steam-compat
%{_datadir}/steam/compatibilitytools.d/PortProtonQt/
%changelog
+66 -22
View File
@@ -1,35 +1,32 @@
%global pypi_name portprotonqt
%global pypi_version 0.1.6
%global pypi_version 0.1.12
%global oname PortProtonQt
%global _python_no_extras_requires 1
Name: python-%{pypi_name}
Name: %{pypi_name}
Version: %{pypi_version}
Release: 1%{?dist}
Summary: Modern GUI for managing and launching games from PortProton, Steam, and Epic Games Store
License: GPL-3.0
URL: https://git.linux-gaming.ru/Boria138/PortProtonQt
BuildArch: noarch
ExclusiveArch: x86_64 aarch64
BuildRequires: meson >= 0.61.2
BuildRequires: ninja-build
BuildRequires: python3-devel
BuildRequires: python3-wheel
BuildRequires: python3-pip
BuildRequires: python3-build
BuildRequires: pyproject-rpm-macros
BuildRequires: python3dist(setuptools)
BuildRequires: git
BuildRequires: gettext
BuildRequires: systemd-rpm-macros
BuildRequires: vulkan-loader-devel
BuildRequires: gcc
%description
%{summary}
Obsoletes: python3-%{pypi_name} < %{version}-%{release}
Provides: python3-%{pypi_name} = %{version}-%{release}
%package -n python3-%{pypi_name}
Summary: %{summary}
%{?python_provide:%python_provide python3-%{pypi_name}}
Requires: python3-babel
Requires: python3-evdev
Requires: python3-icoextract
Requires: python3-numpy
Requires: python3-websocket-client
Requires: python3-orjson
Requires: python3-psutil
@@ -40,13 +37,45 @@ Requires: python3-tqdm
Requires: python3-vdf
Requires: python3-pefile
Requires: python3-pillow
Requires: perl-Image-ExifTool
Requires: xdg-utils
Requires: python3-beautifulsoup4
Requires: python3-rapidfuzz
Requires: python3-libarchive-c
Requires: perl-Image-ExifTool
Requires: qt6-qtsvg
Requires: cabextract
Requires: gzip
Requires: unzip
Requires: curl
Requires: unrar
Requires: glx-utils
Requires: pciutils
Requires: vulkan-loader
Requires: 7zip
%description -n python3-%{pypi_name}
# System Tab
Recommends: NetworkManager
Recommends: bluez
Recommends: upower
Recommends: pulseaudio-utils
Recommends: python3-dbus-fast
Recommends: python3-qrcode
%ifarch aarch64
Requires: muvm
%endif
%description
This application provides a sleek, intuitive graphical interface for managing and launching games from PortProton, Steam, and Epic Games Store. It consolidates your game libraries into a single, user-friendly hub for seamless navigation and organization. Its lightweight structure and cross-platform support deliver a cohesive gaming experience, eliminating the need for multiple launchers. Unique PortProton integration enhances Linux gaming, enabling effortless play of Windows-based titles with minimal setup.
%package -n %{pypi_name}-steam-compat
Summary: Steam compatibility tool for PortProtonQt
License: GPL-3.0
Requires: %{pypi_name} = %{version}-%{release}
%description -n %{pypi_name}-steam-compat
Steam compatibility tool integration for PortProtonQt. This package installs
the necessary files to use PortProtonQt as a Proton compatibility tool in Steam.
%{?python_disable_dependency_generator}
%prep
@@ -56,19 +85,34 @@ git checkout v%{pypi_version}
%build
cd %{oname}
%pyproject_wheel
%meson \
-Dpython_purelibdir=%{python3_sitelib} \
-Dudev_rulesdir=%{_udevrulesdir}
%meson_build
%install
cd %{oname}
%pyproject_install
%pyproject_save_files %{pypi_name}
cp -r build-aux/share %{buildroot}/usr/
%meson_install
bash ./dev-scripts/generate-completions.sh
install -Dpm 0644 ./completions/portprotonqt -t %{buildroot}%{bash_completions_dir}
install -Dpm 0644 ./completions/portprotonqt.fish -t %{buildroot}%{fish_completions_dir}
install -Dpm 0644 ./completions/_portprotonqt -t %{buildroot}%{zsh_completions_dir}
%find_lang %{pypi_name}
%files -n python3-%{pypi_name} -f %{pyproject_files}
%files -f %{oname}/%{pypi_name}.lang
%{_bindir}/%{pypi_name}
%{_bindir}/vk_gpu_info
%{python3_sitelib}/%{pypi_name}/
%{_datadir}/icons/hicolor/scalable/apps/ru.linux_gaming.PortProtonQt.svg
%{_metainfodir}/ru.linux_gaming.PortProtonQt.metainfo.xml
%{_udevrulesdir}/60-portprotonqt.rules
%{_datadir}/polkit-1/rules.d/ru.linux_gaming.PortProtonQt.rules
%{_datadir}/applications/ru.linux_gaming.PortProtonQt.desktop
%{bash_completions_dir}/portprotonqt
%{fish_completions_dir}/portprotonqt.fish
%{zsh_completions_dir}/_portprotonqt
%files -n %{pypi_name}-steam-compat
%{_datadir}/steam/compatibilitytools.d/PortProtonQt/
%changelog
+4
View File
@@ -0,0 +1,4 @@
int main(void)
{
return 0;
}
@@ -0,0 +1 @@
KERNEL=="uinput", SUBSYSTEM=="misc", OPTIONS+="static_node=uinput", TAG+="uaccess"
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env python3
import sys
from portprotonqt.app import main
if __name__ == "__main__":
sys.exit(main())
@@ -1,9 +1,14 @@
[Desktop Entry]
Name=PortProtonQt
Exec=portprotonqt
Exec=portprotonqt %u
Type=Application
Comment=A modern GUI for PortProton project
Comment[ru]=Современный графический интерфейс для проекта PortProton
Comment[es]=Una interfaz gráfica moderna para el proyecto PortProton
Comment[pt]=Uma interface gráfica moderna para o projeto PortProton
Comment[de]=Eine moderne grafische Benutzeroberfläche für das PortProton-Projekt
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;
@@ -1,30 +0,0 @@
_portprotonqt_completions() {
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
# Available options
opts="--fullscreen --debug-level --help -h"
# Debug level choices
debug_levels="ALL DEBUG INFO WARNING ERROR CRITICAL"
case "${prev}" in
--debug-level)
# Complete debug levels
COMPREPLY=( $(compgen -W "${debug_levels}" -- ${cur}) )
return 0
;;
*)
;;
esac
# Complete options
if [[ ${cur} == -* ]]; then
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
fi
}
complete -F _portprotonqt_completions portprotonqt
@@ -33,31 +33,37 @@
</categories>
<url type="homepage">https://git.linux-gaming.ru/Boria138/PortProtonQt</url>
<url type="bugtracker">https://git.linux-gaming.ru/Boria138/PortProtonQt/issues</url>
<url type="translate">https://translate.codeberg.org/engage/portprotonqt</url>
<screenshots>
<screenshot type="default">
<image>https://git.linux-gaming.ru/Boria138/PortProtonQt/raw/branch/main/portprotonqt/themes/standart/images/screenshots/%D0%91%D0%B8%D0%B1%D0%BB%D0%B8%D0%BE%D1%82%D0%B5%D0%BA%D0%B0.png</image>
<image>https://git.linux-gaming.ru/Boria138/PortProtonQt/raw/branch/main/portprotonqt/themes/standart/images/screenshots/library.jpg</image>
<caption>Library</caption>
<caption xml:lang="ru">Библиотека</caption>
</screenshot>
<screenshot>
<image>https://git.linux-gaming.ru/Boria138/PortProtonQt/raw/branch/main/portprotonqt/themes/standart/images/screenshots/%D0%9A%D0%B0%D1%80%D1%82%D0%BE%D1%87%D0%BA%D0%B0.png</image>
<image>https://git.linux-gaming.ru/Boria138/PortProtonQt/raw/branch/main/portprotonqt/themes/standart/images/screenshots/game_card.jpg</image>
<caption>Card detail page</caption>
<caption xml:lang="ru">Детали игры</caption>
</screenshot>
<screenshot>
<image>https://git.linux-gaming.ru/Boria138/PortProtonQt/raw/branch/main/portprotonqt/themes/standart/images/screenshots/%D0%9D%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B8.png</image>
<image>https://git.linux-gaming.ru/Boria138/PortProtonQt/raw/branch/main/portprotonqt/themes/standart/images/screenshots/portproton_settings.jpg</image>
<caption>Settings</caption>
<caption xml:lang="ru">Настройки</caption>
</screenshot>
<screenshot>
<image>https://git.linux-gaming.ru/Boria138/PortProtonQt/raw/branch/main/portprotonqt/themes/standart/images/screenshots/%D0%9A%D0%BE%D0%BD%D1%82%D0%B5%D0%BA%D1%81%D1%82%D0%BD%D0%BE%D0%B5%20%D0%BC%D0%B5%D0%BD%D1%8E.png</image>
<image>https://git.linux-gaming.ru/Boria138/PortProtonQt/raw/branch/main/portprotonqt/themes/standart/images/screenshots/context_menu.jpg</image>
<caption>Context Menu</caption>
<caption xml:lang="ru">Контекстное меню</caption>
</screenshot>
<screenshot>
<image>https://git.linux-gaming.ru/Boria138/PortProtonQt/src/branch/main/portprotonqt/themes/standart/images/screenshots/%D0%9E%D0%B2%D0%B5%D1%80%D0%BB%D0%B5%D0%B9.png</image>
<caption>Overlay</caption>
<caption xml:lang="ru">Оверлей</caption>
<image>https://git.linux-gaming.ru/Boria138/PortProtonQt/raw/branch/main/portprotonqt/themes/standart/images/screenshots/exe_settings.jpg</image>
<caption>Exe Settings</caption>
<caption xml:lang="ru">Настройки exe</caption>
</screenshot>
<screenshot>
<image>https://git.linux-gaming.ru/Boria138/PortProtonQt/raw/branch/main/portprotonqt/themes/standart/images/screenshots/wine_settings.jpg</image>
<caption>Wine Settings</caption>
<caption xml:lang="ru">Настройки Wine</caption>
</screenshot>
</screenshots>
<keywords>
@@ -0,0 +1,21 @@
polkit.addRule(function(action, subject) {
var cmd_line = polkit.spawn(["ps", "-o", "args=", "-p", String(subject.pid)]);
var ppid = polkit.spawn(["ps", "-o", "ppid=", "-p", String(subject.pid)]).trim();
var parent_cmd_line = "";
if (ppid) {
parent_cmd_line = polkit.spawn(["ps", "-o", "args=", "-p", ppid]);
}
var is_ppqt_call =
cmd_line.includes("ppqtos") ||
parent_cmd_line.includes("ppqtos");
if ( (
action.id === "org.freedesktop.NetworkManager.settings.modify.system" ||
action.id == "org.freedesktop.udisks2.filesystem-mount-system" ||
action.id == "org.freedesktop.udisks2.filesystem-mount-other-seat" ||
action.id == "org.freedesktop.udisks2.filesystem-unmount-others" ) &&
is_ppqt_call)
{
return polkit.Result.YES;
}
});
@@ -0,0 +1,14 @@
"compatibilitytools"
{
"compat_tools"
{
"PortProtonQt"
{
"install_path" "."
"display_name" "PortProtonQt"
"from_oslist" "windows"
"to_oslist" "linux"
"Priority" "75"
}
}
}
@@ -0,0 +1,12 @@
# Install PortProtonQt Steam compatibility tool
install_data(
'compatibilitytool.vdf',
'toolmanifest.vdf',
install_dir: prefix / get_option('datadir') / 'steam' / 'compatibilitytools.d' / 'PortProtonQt',
)
install_data(
'portproton',
install_dir: prefix / get_option('datadir') / 'steam' / 'compatibilitytools.d' / 'PortProtonQt',
install_mode: 'rwxr-xr-x',
)
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Remove Steam Runtime libraries
unset LD_LIBRARY_PATH
export STEAM_COMPAT=1
exe_name="$(basename "$1")"
exe_dir="$(dirname "$1")"
# Ignore specific executables
if [[ "$exe_name" == "iscriptevaluator.exe" ]] || \
[[ "$exe_name" == "d3ddriverquery64.exe" ]]; then
exit 0
fi
# Copy PPDB file from steam_scripts to exe directory if it exists
# Steam passes the appid via SteamAppId environment variable
if [[ -n "$SteamAppId" ]]; then
# Get PortProton directory from config file or Flatpak default
portproton_dir=""
config_file="$HOME/.config/PortProton.conf"
if [[ -f "$config_file" ]]; then
portproton_dir="$(cat "$config_file" | tr -d '\n')"
fi
if [[ -z "$portproton_dir" ]] || [[ ! -d "$portproton_dir" ]]; then
# Fallback to Flatpak default
portproton_dir="$HOME/.var/app/ru.linux_gaming.PortProton"
fi
ppdb_source="$portproton_dir/steam_scripts/${SteamAppId}.exe.ppdb"
ppdb_dest="$exe_dir/${exe_name}.ppdb"
if [[ -f "$ppdb_source" ]]; then
cp "$ppdb_source" "$ppdb_dest"
echo "Copied PPDB from $ppdb_source to $ppdb_dest"
fi
fi
# Activate virtual environment if available
if [[ -n "$PPQT_VENV_PATH" ]]; then
cd "$PPQT_VENV_PATH" || exit 1
source .venv/bin/activate || exit 1
fi
# Use AppImage if specified, otherwise use portprotonqt from PATH
if [[ -n "$PPQT_BIN_PATH" ]]; then
"$PPQT_BIN_PATH" --debug-level INFO "$@"
else
portprotonqt --debug-level INFO "$@"
fi
@@ -0,0 +1,4 @@
"manifest"
{
"commandline" "/portproton"
}
+225
View File
@@ -0,0 +1,225 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vulkan/vulkan.h>
// Функция для безопасного извлечения строк из структур Vulkan
void decode_str(const char* src, char* dst, size_t dst_size) {
if (!src || !dst || dst_size == 0) {
if (dst && dst_size > 0) dst[0] = '\0';
return;
}
// Найти нулевой символ или первый символ null terminator
size_t len = 0;
while (len < dst_size - 1 && src[len] != '\0') {
len++;
}
// Копируем строку до нулевого символа или до заполнения буфера
memcpy(dst, src, len);
dst[len] = '\0';
}
// Функция для определения типа устройства
const char* device_type_name(VkPhysicalDeviceType device_type) {
switch (device_type) {
case VK_PHYSICAL_DEVICE_TYPE_OTHER:
return "OTHER";
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
return "INTEGRATED_GPU";
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
return "DISCRETE_GPU";
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
return "VIRTUAL_GPU";
case VK_PHYSICAL_DEVICE_TYPE_CPU:
return "CPU";
default:
return "UNKNOWN";
}
}
// Проверка поддержки расширения для получения свойств драйвера
VkBool32 device_supports_driver_props(VkPhysicalDevice device) {
uint32_t extension_count;
VkResult result = vkEnumerateDeviceExtensionProperties(device, NULL, &extension_count, NULL);
if (result != VK_SUCCESS) {
return VK_FALSE;
}
if (extension_count == 0) {
return VK_FALSE;
}
VkExtensionProperties* extensions = malloc(sizeof(VkExtensionProperties) * extension_count);
result = vkEnumerateDeviceExtensionProperties(device, NULL, &extension_count, extensions);
if (result != VK_SUCCESS) {
free(extensions);
return VK_FALSE;
}
VkBool32 supports = VK_FALSE;
for (uint32_t i = 0; i < extension_count; i++) {
if (strcmp(extensions[i].extensionName, VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME) == 0) {
supports = VK_TRUE;
break;
}
}
free(extensions);
return supports;
}
int main() {
// Инициализация Vulkan
VkApplicationInfo app_info = {
.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
.pNext = NULL,
.pApplicationName = "GPUInfo",
.applicationVersion = VK_MAKE_VERSION(1, 0, 0),
.pEngineName = "NoEngine",
.engineVersion = VK_MAKE_VERSION(1, 0, 0),
.apiVersion = VK_API_VERSION_1_0
};
// Проверим, какие расширения доступны
uint32_t instance_extension_count;
VkResult result = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, NULL);
if (result != VK_SUCCESS) {
fprintf(stderr, "Failed to get instance extension count\n");
return -1;
}
VkExtensionProperties* instance_extensions = NULL;
if (instance_extension_count > 0) {
instance_extensions = malloc(sizeof(VkExtensionProperties) * instance_extension_count);
result = vkEnumerateInstanceExtensionProperties(NULL, &instance_extension_count, instance_extensions);
if (result != VK_SUCCESS) {
fprintf(stderr, "Failed to enumerate instance extensions\n");
free(instance_extensions);
return -1;
}
}
// Проверим, поддерживается ли нужное расширение
const char* required_instance_extensions[] = {
VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME
};
uint32_t enabled_extension_count = 0;
const char** enabled_extensions = NULL;
if (instance_extensions) {
for (uint32_t i = 0; i < instance_extension_count; i++) {
if (strcmp(instance_extensions[i].extensionName, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME) == 0) {
enabled_extensions = required_instance_extensions;
enabled_extension_count = 1;
break;
}
}
free(instance_extensions);
}
VkInstanceCreateInfo create_info = {
.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
.pNext = NULL,
.flags = 0,
.pApplicationInfo = &app_info,
.enabledLayerCount = 0,
.ppEnabledLayerNames = NULL,
.enabledExtensionCount = enabled_extension_count,
.ppEnabledExtensionNames = enabled_extensions
};
VkInstance instance;
result = vkCreateInstance(&create_info, NULL, &instance);
if (result != VK_SUCCESS) {
fprintf(stderr, "Failed to create Vulkan instance\n");
return -1;
}
// Получаем список физических устройств
uint32_t device_count;
result = vkEnumeratePhysicalDevices(instance, &device_count, NULL);
if (result != VK_SUCCESS) {
fprintf(stderr, "Failed to get physical device count\n");
vkDestroyInstance(instance, NULL);
return -1;
}
if (device_count == 0) {
printf("No Vulkan-compatible GPUs found\n");
vkDestroyInstance(instance, NULL);
return 0;
}
VkPhysicalDevice* devices = malloc(sizeof(VkPhysicalDevice) * device_count);
result = vkEnumeratePhysicalDevices(instance, &device_count, devices);
if (result != VK_SUCCESS) {
fprintf(stderr, "Failed to enumerate physical devices\n");
vkDestroyInstance(instance, NULL);
free(devices);
return -1;
}
// Обрабатываем каждое устройство
for (uint32_t i = 0; i < device_count; i++) {
VkPhysicalDeviceProperties props;
vkGetPhysicalDeviceProperties(devices[i], &props);
uint32_t gpu_id = props.deviceID;
char device_name[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE];
decode_str(props.deviceName, device_name, sizeof(device_name));
uint32_t api_version = props.apiVersion;
uint32_t driver_version = props.driverVersion;
const char* device_type = device_type_name(props.deviceType);
char driver_name[VK_MAX_EXTENSION_NAME_SIZE] = "Unknown";
char driver_info[VK_MAX_EXTENSION_NAME_SIZE] = "Unknown";
if (device_supports_driver_props(devices[i])) {
// Используем VkPhysicalDeviceProperties2 для получения дополнительной информации
VkPhysicalDeviceDriverProperties driver_props = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES,
.pNext = NULL
};
VkPhysicalDeviceProperties2 props2 = {
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,
.pNext = &driver_props
};
// Получаем расширенные свойства
PFN_vkGetPhysicalDeviceProperties2 vkGetPhysicalDeviceProperties2 =
(PFN_vkGetPhysicalDeviceProperties2)vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceProperties2");
if (vkGetPhysicalDeviceProperties2 != NULL) {
vkGetPhysicalDeviceProperties2(devices[i], &props2);
decode_str(driver_props.driverName, driver_name, sizeof(driver_name));
decode_str(driver_props.driverInfo, driver_info, sizeof(driver_info));
}
}
printf("GPU #%u\n", i);
printf("gpu_id: %u\n", gpu_id);
printf("device_name: %s\n", device_name);
printf("driver_name: %s\n", driver_name);
printf("driver_info: %s\n", driver_info);
printf("api_version: %u.%u.%u\n",
VK_VERSION_MAJOR(api_version),
VK_VERSION_MINOR(api_version),
VK_VERSION_PATCH(api_version));
printf("driver_version: %u.%u.%u\n",
VK_VERSION_MAJOR(driver_version),
VK_VERSION_MINOR(driver_version),
VK_VERSION_PATCH(driver_version));
printf("device_type: %s\n", device_type);
printf("\n");
}
// Освобождаем ресурсы
free(devices);
vkDestroyInstance(instance, NULL);
return 0;
}
+2427 -1141
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+75879 -5791
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.
+4 -160
View File
@@ -1,111 +1,11 @@
[
{
"normalized_title": "dirt rally 2.0 game of the year",
"slug": "dirt-rally-2-0-game-of-the-year-edition"
"normalized_title": "описание категории «portprotongames»",
"slug": "opisanie-kategorii-portprotongames"
},
{
"normalized_title": "deus ex human revolution director’s cut",
"slug": "deus-ex-human-revolution-director-s-cut"
},
{
"normalized_title": "freelancer",
"slug": "freelancer"
},
{
"normalized_title": "everspace",
"slug": "everspace"
},
{
"normalized_title": "blades of time limited",
"slug": "blades-of-time-limited-edition"
},
{
"normalized_title": "chorus",
"slug": "chorus"
},
{
"normalized_title": "tom clancy's splinter cell pandora tomorrow",
"slug": "tom-clancys-splinter-cell-pandora-tomorrow"
},
{
"normalized_title": "the alters",
"slug": "the-alters"
},
{
"normalized_title": "hard reset redux",
"slug": "hard-reset-redux"
},
{
"normalized_title": "far cry 5",
"slug": "far-cry-5"
},
{
"normalized_title": "metal eden",
"slug": "metal-eden"
},
{
"normalized_title": "indiana jones and the great circle",
"slug": "indiana-jones-and-the-great-circle"
},
{
"normalized_title": "old world",
"slug": "old-world"
},
{
"normalized_title": "witchfire",
"slug": "witchfire"
},
{
"normalized_title": "prototype",
"slug": "prototype"
},
{
"normalized_title": "mandragora whispers of the witch tree",
"slug": "mandragora-whispers-of-the-witch-tree"
},
{
"normalized_title": "grand theft auto v (gta 5)",
"slug": "grand-theft-auto-v-gta-5"
},
{
"normalized_title": "lifeless planet premier",
"slug": "lifeless-planet-premier-edition"
},
{
"normalized_title": "warcraft iii the frozen throne",
"slug": "warcraft-iii-the-frozen-throne"
},
{
"normalized_title": "star wars republic commando",
"slug": "star-wars-republic-commando"
},
{
"normalized_title": "hollow knight silksong",
"slug": "hollow-knight-silksong"
},
{
"normalized_title": "arma reforger",
"slug": "arma-reforger"
},
{
"normalized_title": "arma 3",
"slug": "arma-3"
},
{
"normalized_title": "astroneer",
"slug": "astroneer"
},
{
"normalized_title": "anno 2205",
"slug": "anno-2205"
},
{
"normalized_title": "anno 2070",
"slug": "anno-2070"
},
{
"normalized_title": "kompas 3d v23 / компас 3d v23",
"slug": "kompas-3d-v23-kompas-3d-v23"
"normalized_title": "о закрытии категории portprotondb",
"slug": "o-zakrytii-kategorii-portprotondb"
},
{
"normalized_title": "ultrakill (early access)",
@@ -119,10 +19,6 @@
"normalized_title": "disco elysium the finul cut",
"slug": "disco-elysium-the-finul-cut"
},
{
"normalized_title": "warcraft iii reign of chaos",
"slug": "warcraft-iii-reign-of-chaos"
},
{
"normalized_title": "dying light",
"slug": "dying-light"
@@ -247,10 +143,6 @@
"normalized_title": "battle of space raiders",
"slug": "battle-of-space-raiders"
},
{
"normalized_title": "gzdoom",
"slug": "gzdoom"
},
{
"normalized_title": "rain on your parade",
"slug": "rain-on-your-parade"
@@ -271,10 +163,6 @@
"normalized_title": "steins;gate the distant valhalla",
"slug": "steins-gate-the-distant-valhalla"
},
{
"normalized_title": "hogwarts legacy",
"slug": "hogwarts-legacy"
},
{
"normalized_title": "osu!",
"slug": "osu"
@@ -359,10 +247,6 @@
"normalized_title": "the last of us part ii",
"slug": "the-last-of-us-part-ii-remastered"
},
{
"normalized_title": "doom 3",
"slug": "doom-3"
},
{
"normalized_title": "cardlife creative survival",
"slug": "cardlife-creative-survival"
@@ -407,10 +291,6 @@
"normalized_title": "vampire the masquerade redemption",
"slug": "vampire-the-masquerade-redemption"
},
{
"normalized_title": "need for speed the run",
"slug": "need-for-speed-the-run"
},
{
"normalized_title": "new star gp",
"slug": "new-star-gp"
@@ -1059,10 +939,6 @@
"normalized_title": "mafia",
"slug": "mafia-definitive-edition"
},
{
"normalized_title": "teardown",
"slug": "teardown"
},
{
"normalized_title": "spellforce conquest of eo",
"slug": "spellforce-conquest-of-eo"
@@ -1203,10 +1079,6 @@
"normalized_title": "mass effect",
"slug": "mass-effect"
},
{
"normalized_title": "doom (2016)",
"slug": "doom-2016"
},
{
"normalized_title": "致命解药 (the killing antidote)",
"slug": "the-killing-antidote"
@@ -1311,10 +1183,6 @@
"normalized_title": "world of sea battle",
"slug": "world-of-sea-battle"
},
{
"normalized_title": "escape from tarkov",
"slug": "escape-from-tarkov"
},
{
"normalized_title": "bayonetta",
"slug": "bayonetta"
@@ -1439,10 +1307,6 @@
"normalized_title": "call of duty 2",
"slug": "call-of-duty-2"
},
{
"normalized_title": "call of duty infinite warfare",
"slug": "call-of-duty-infinite-warfare"
},
{
"normalized_title": "call of duty world at war",
"slug": "call-of-duty-world-at-war"
@@ -1583,10 +1447,6 @@
"normalized_title": "the witcher 3 wild hunt (ведьмак 3)",
"slug": "the-witcher-3-wild-hunt-vedmak-3"
},
{
"normalized_title": "resident evil 4 (2023)",
"slug": "resident-evil-4-2023"
},
{
"normalized_title": "god of war (2018)",
"slug": "god-of-war-2018"
@@ -1635,10 +1495,6 @@
"normalized_title": "elden ring",
"slug": "elden-ring"
},
{
"normalized_title": "starcraft",
"slug": "starcraft-remastered"
},
{
"normalized_title": "cataclismo",
"slug": "cataclismo"
@@ -1963,10 +1819,6 @@
"normalized_title": "передний край front edge (catslauncher)",
"slug": "perednij-kraj-front-edge-catslauncher"
},
{
"normalized_title": "league of legends",
"slug": "league-of-legends"
},
{
"normalized_title": "civilization vi",
"slug": "civilization-vi"
@@ -1991,10 +1843,6 @@
"normalized_title": "phantom fury",
"slug": "phantom-fury"
},
{
"normalized_title": "factorio",
"slug": "factorio"
},
{
"normalized_title": "signalis",
"slug": "signalis"
@@ -2119,10 +1967,6 @@
"normalized_title": "battle.net",
"slug": "battle-net"
},
{
"normalized_title": "valorant",
"slug": "valorant"
},
{
"normalized_title": "русы против ящеров",
"slug": "rusy-protiv-yashherov"
Binary file not shown.
+54
View File
@@ -20,3 +20,57 @@ Stop Game
Fullscreen
Fulscreen
\t
Горячая
vkbasalt
dgVoodoo2
Zink
Vulkan
VKD3D
DirectX12
Prev Dir
Forced
GOverlay
Glide
all
futex
DLSS
fullscreen
ProtonGE
window
compositing
Zink
Use
bundled
dxvk
older games
versions
DLL Overrides
COMP
VKD3D
Select needed
CPUs
cores
PPDB
WINE
Proton
MangoHud
vkBasalt
logs
RAM
Process
GPU
frametime
temperature
Horizontal stretch
HDR10
sync
XWayland
servers
HDR
SDR
most
args
нт
initting
Signal
State
-378
View File
@@ -1,378 +0,0 @@
#!/usr/bin/env python3
"""
PySide6 Dependencies Analyzer with ldd support
Анализирует зависимости PySide6 модулей используя ldd для определения
реальных зависимостей скомпилированных библиотек.
"""
import ast
import os
import sys
import subprocess
import re
from pathlib import Path
from typing import Set, Dict, List
import argparse
import json
class PySide6DependencyAnalyzer:
def __init__(self):
# Системные библиотеки, которые нужно всегда оставлять
self.system_libs = {
'libQt6XcbQpa', 'libQt6Wayland', 'libQt6Egl',
'libicudata', 'libicuuc', 'libicui18n', 'libQt6DBus'
}
self.real_dependencies = {}
self.used_modules_code = set()
self.used_modules_ldd = set()
self.all_required_modules = set()
def find_python_files(self, directory: Path) -> List[Path]:
"""Находит все Python файлы в директории"""
python_files = []
for root, dirs, files in os.walk(directory):
dirs[:] = [d for d in dirs if d not in {'.venv', '__pycache__', '.git'}]
for file in files:
if file.endswith('.py'):
python_files.append(Path(root) / file)
return python_files
def find_pyside6_libs(self, base_path: Path) -> Dict[str, Path]:
"""Находит все PySide6 библиотеки (.so файлы)"""
libs = {}
# Поиск в единственной локации
search_path = Path("../.venv/lib/python3.10/site-packages/PySide6")
print(f"Поиск PySide6 библиотек в: {search_path}")
if search_path.exists():
# Ищем .so файлы модулей
for so_file in search_path.glob("Qt*.*.so"):
module_name = so_file.stem.split('.')[0] # QtCore.abi3.so -> QtCore
if module_name.startswith('Qt'):
libs[module_name] = so_file
# Также ищем в подпапках
for subdir in search_path.iterdir():
if subdir.is_dir() and subdir.name.startswith('Qt'):
for so_file in subdir.glob("*.so*"):
if 'Qt' in so_file.name:
libs[subdir.name] = so_file
break
return libs
def analyze_ldd_dependencies(self, lib_path: Path) -> Set[str]:
"""Анализирует зависимости библиотеки с помощью ldd"""
qt_deps = set()
try:
result = subprocess.run(['ldd', str(lib_path)],
capture_output=True, text=True, check=True)
# Парсим вывод ldd и ищем Qt библиотеки
for line in result.stdout.split('\n'):
# Ищем строки вида: libQt6Core.so.6 => /path/to/lib
match = re.search(r'libQt6(\w+)\.so', line)
if match:
qt_module = f"Qt{match.group(1)}"
qt_deps.add(qt_module)
except (subprocess.CalledProcessError, FileNotFoundError) as e:
print(f"Предупреждение: не удалось выполнить ldd для {lib_path}: {e}")
return qt_deps
def build_real_dependency_graph(self, pyside_libs: Dict[str, Path]) -> Dict[str, Set[str]]:
"""Строит граф зависимостей на основе ldd анализа"""
dependencies = {}
print("Анализ реальных зависимостей с помощью ldd...")
for module, lib_path in pyside_libs.items():
print(f" Анализируется {module}...")
deps = self.analyze_ldd_dependencies(lib_path)
dependencies[module] = deps
if deps:
print(f" Зависимости: {', '.join(sorted(deps))}")
return dependencies
def analyze_file_imports(self, file_path: Path) -> Set[str]:
"""Анализирует один Python файл и возвращает используемые PySide6 модули"""
modules = set()
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
tree = ast.parse(content)
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
if alias.name.startswith('PySide6.'):
module = alias.name.split('.', 2)[1]
if module.startswith('Qt'):
modules.add(module)
elif isinstance(node, ast.ImportFrom):
if node.module and node.module.startswith('PySide6.'):
module = node.module.split('.', 2)[1]
if module.startswith('Qt'):
modules.add(module)
except Exception as e:
print(f"Ошибка при анализе {file_path}: {e}")
return modules
def get_all_dependencies(self, modules: Set[str], dependency_graph: Dict[str, Set[str]]) -> Set[str]:
"""Получает все зависимости для набора модулей, используя граф зависимостей из ldd"""
all_deps = set(modules)
if not dependency_graph:
return all_deps
# Повторяем до тех пор, пока не найдем все транзитивные зависимости
changed = True
iteration = 0
while changed and iteration < 10: # Защита от бесконечного цикла
changed = False
current_deps = set(all_deps)
for module in current_deps:
if module in dependency_graph:
new_deps = dependency_graph[module] - all_deps
if new_deps:
all_deps.update(new_deps)
changed = True
iteration += 1
return all_deps
def analyze_project(self, project_path: Path, appdir_path: Path = None) -> Dict:
"""Анализирует весь проект"""
python_files = self.find_python_files(project_path)
print(f"Найдено {len(python_files)} Python файлов")
# Анализ статических импортов
used_modules_code = set()
file_modules = {}
for file_path in python_files:
modules = self.analyze_file_imports(file_path)
if modules:
file_modules[str(file_path.relative_to(project_path))] = list(modules)
used_modules_code.update(modules)
print(f"Найдено {len(used_modules_code)} модулей в коде: {', '.join(sorted(used_modules_code))}")
# Поиск PySide6 библиотек
search_base = appdir_path if appdir_path else project_path
pyside_libs = self.find_pyside6_libs(search_base)
if not pyside_libs:
print("ОШИБКА: PySide6 библиотеки не найдены! Анализ невозможен.")
return {
'error': 'PySide6 библиотеки не найдены',
'analysis_method': 'failed',
'found_libraries': 0,
'directly_used_code': sorted(used_modules_code),
'all_required': [],
'removable': [],
'available_modules': [],
'file_usage': file_modules
}
print(f"Найдено {len(pyside_libs)} PySide6 библиотек")
# Анализ реальных зависимостей с ldd
real_dependencies = self.build_real_dependency_graph(pyside_libs)
# Определяем модули, которые реально используются через ldd
used_modules_ldd = set()
for module in used_modules_code:
if module in real_dependencies:
used_modules_ldd.update(real_dependencies[module])
used_modules_ldd.add(module)
print(f"Реальные зависимости через ldd: {', '.join(sorted(used_modules_ldd))}")
# Объединяем результаты анализа кода и ldd
all_used_modules = used_modules_code | used_modules_ldd
# Получаем все необходимые модули включая зависимости
all_required = self.get_all_dependencies(all_used_modules, real_dependencies)
# Все доступные PySide6 модули
available_modules = set(pyside_libs.keys())
# Модули, которые можно удалить
removable = available_modules - all_required
return {
'analysis_method': 'ldd + static analysis',
'found_libraries': len(pyside_libs),
'directly_used_code': sorted(used_modules_code),
'directly_used_ldd': sorted(used_modules_ldd),
'all_required': sorted(all_required),
'removable': sorted(removable),
'available_modules': sorted(available_modules),
'file_usage': file_modules,
'real_dependencies': {k: sorted(v) for k, v in real_dependencies.items()},
'library_paths': {k: str(v) for k, v in pyside_libs.items()},
'analysis_summary': {
'total_modules': len(available_modules),
'required_modules': len(all_required),
'removable_modules': len(removable),
'space_saving_potential': f"{len(removable)/len(available_modules)*100:.1f}%" if available_modules else "0%"
}
}
def generate_appimage_recipe(self, removable_modules: List[str], template_path: Path) -> str:
"""Генерирует обновленный AppImage рецепт с командами очистки"""
# Читаем существующий рецепт
try:
with open(template_path, 'r', encoding='utf-8') as f:
recipe_content = f.read()
except FileNotFoundError:
print(f"Шаблон рецепта не найден: {template_path}")
return ""
# Генерируем новые команды очистки
cleanup_lines = []
# QML удаляем только если не используется
qml_modules = {'QtQml', 'QtQuick', 'QtQuickWidgets'}
if qml_modules.issubset(set(removable_modules)):
cleanup_lines.append(" - rm -rf AppDir/usr/local/lib/python3.10/dist-packages/PySide6/Qt/qml/")
# Инструменты разработки (всегда удаляем)
cleanup_lines.append(" - rm -f AppDir/usr/local/lib/python3.10/dist-packages/PySide6/{assistant,designer,linguist,lrelease,lupdate}")
# Модули для удаления
if removable_modules:
modules_list = ','.join([f"{mod}*" for mod in sorted(removable_modules)])
cleanup_lines.append(f" - rm -f AppDir/usr/local/lib/python3.10/dist-packages/PySide6/{{{modules_list}}}")
# Генерируем команду для удаления нативных библиотек с сохранением нужных
required_libs = set()
for module in sorted(set(self.all_required_modules)):
required_libs.add(f"libQt6{module.replace('Qt', '')}*")
# Добавляем системные библиотеки
for lib in self.system_libs:
required_libs.add(f"{lib}*")
keep_pattern = '|'.join(sorted(required_libs))
cleanup_lines.extend([
" - shopt -s extglob",
f" - rm -rf AppDir/usr/local/lib/python3.10/dist-packages/PySide6/Qt/lib/!({keep_pattern})"
])
# Заменяем блок очистки в рецепте
import re
# Ищем блок "# 5) чистим от ненужных модулей и бинарников" до следующего комментария или до AppDir:
pattern = r'( # 5\) чистим от ненужных модулей и бинарников\n).*?(?=\nAppDir:|\n # [0-9]+\)|$)'
new_cleanup_block = " # 5) чистим от ненужных модулей и бинарников\n" + '\n'.join(cleanup_lines)
updated_recipe = re.sub(pattern, new_cleanup_block, recipe_content, flags=re.DOTALL)
return updated_recipe
def main():
parser = argparse.ArgumentParser(description='Анализ зависимостей PySide6 модулей с использованием ldd')
parser.add_argument('project_path', help='Путь к проекту для анализа')
parser.add_argument('--appdir', help='Путь к AppDir для поиска PySide6 библиотек')
parser.add_argument('--output', '-o', help='Путь для сохранения результатов (JSON)')
parser.add_argument('--verbose', '-v', action='store_true', help='Подробный вывод')
args = parser.parse_args()
project_path = Path(args.project_path)
if not project_path.exists():
print(f"Ошибка: путь {project_path} не существует")
sys.exit(1)
appdir_path = Path(args.appdir) if args.appdir else None
if appdir_path and not appdir_path.exists():
print(f"Предупреждение: AppDir путь {appdir_path} не существует")
appdir_path = None
analyzer = PySide6DependencyAnalyzer()
results = analyzer.analyze_project(project_path, appdir_path)
# Сохраняем в анализатор для генерации команд
analyzer.all_required_modules = set(results.get('all_required', []))
# Выводим результаты
print("\n" + "="*60)
print("АНАЛИЗ ЗАВИСИМОСТЕЙ PYSIDE6 (ldd analysis)")
print("="*60)
if 'error' in results:
print(f"\nОШИБКА: {results['error']}")
sys.exit(1)
print(f"\nМетод анализа: {results['analysis_method']}")
print(f"Найдено библиотек: {results['found_libraries']}")
if results['directly_used_code']:
print(f"\nИспользуемые модули в коде ({len(results['directly_used_code'])}):")
for module in results['directly_used_code']:
print(f" • {module}")
if results['directly_used_ldd']:
print(f"\nРеальные зависимости через ldd ({len(results['directly_used_ldd'])}):")
for module in results['directly_used_ldd']:
print(f" • {module}")
print(f"\nВсе необходимые модули ({len(results['all_required'])}):")
for module in results['all_required']:
print(f" • {module}")
print(f"\nМодули, которые можно удалить ({len(results['removable'])}):")
for module in results['removable']:
print(f" • {module}")
print(f"\nПотенциальная экономия места: {results['analysis_summary']['space_saving_potential']}")
if args.verbose and results['real_dependencies']:
Devlin(f"\nРеальные зависимости (ldd):")
for module, deps in results['real_dependencies'].items():
if deps:
print(f" {module} → {', '.join(deps)}")
# Обновляем AppImage рецепт
recipe_path = Path("../build-aux/AppImageBuilder.yml")
if recipe_path.exists():
updated_recipe = analyzer.generate_appimage_recipe(results['removable'], recipe_path)
if updated_recipe:
with open(recipe_path, 'w', encoding='utf-8') as f:
f.write(updated_recipe)
print(f"\nAppImage рецепт обновлен: {recipe_path}")
else:
print(f"\nОШИБКА: не удалось обновить рецепт")
else:
print(f"\nПредупреждение: рецепт AppImage не найден в {recipe_path}")
# Сохраняем результаты в JSON
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f"Результаты сохранены в: {args.output}")
print("\n" + "="*60)
if __name__ == "__main__":
main()
+18
View File
@@ -12,7 +12,9 @@ BASE_DIR = Path(__file__).parent.parent
APPIMAGE_RECIPE = BASE_DIR / "build-aux" / "AppImageBuilder.yml"
ARCH_PKGBUILD = BASE_DIR / "build-aux" / "PKGBUILD"
FEDORA_SPEC = BASE_DIR / "build-aux" / "fedora.spec"
FEDORA_GIT_SPEC = BASE_DIR / "build-aux" / "fedora-git.spec"
PYPROJECT = BASE_DIR / "pyproject.toml"
MESON_BUILD = BASE_DIR / "meson.build"
APP_PY = BASE_DIR / "portprotonqt" / "app.py"
GITEA_WORKFLOW = BASE_DIR / ".gitea" / "workflows" / "build.yml"
CHANGELOG = BASE_DIR / "CHANGELOG.md"
@@ -56,6 +58,7 @@ def bump_fedora(path: Path, old: str, new: str) -> bool:
path.write_text(new_text, encoding='utf-8')
return bool(count)
def bump_pyproject(path: Path, old: str, new: str) -> bool:
"""
Update version in pyproject.toml under [project]
@@ -69,6 +72,19 @@ def bump_pyproject(path: Path, old: str, new: str) -> bool:
path.write_text(new_text, encoding='utf-8')
return bool(count)
def bump_meson(path: Path, old: str, new: str) -> bool:
"""
Update version in meson.build
"""
if not path.exists():
return False
text = path.read_text(encoding='utf-8')
pattern = re.compile(r"(version:\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')
return bool(count)
def bump_app_py(path: Path, old: str, new: str) -> bool:
"""
Update __app_version__ in app.py
@@ -120,7 +136,9 @@ def main():
(APPIMAGE_RECIPE, bump_appimage),
(ARCH_PKGBUILD, bump_arch),
(FEDORA_SPEC, bump_fedora),
(FEDORA_GIT_SPEC, bump_fedora),
(PYPROJECT, bump_pyproject),
(MESON_BUILD, bump_meson),
(APP_PY, bump_app_py),
(GITEA_WORKFLOW, bump_workflow),
(CHANGELOG, bump_changelog)
+786
View File
@@ -0,0 +1,786 @@
#!/usr/bin/env python3
"""
Pre-commit hook to check if all Python files in the portprotonqt directory are included in meson.build
and to validate proper syntax in meson.build files.
Checks for:
- Missing files in install_data
- Unbalanced brackets: (), [], {}
- Unclosed quotes: ', "
- Missing/extra commas
- Syntax errors with colons, semicolons
- Duplicate entries
- Invalid control structures (if/endif, foreach/endforeach)
- Common typos and formatting issues
"""
import sys
import re
from pathlib import Path
from collections import Counter
from dataclasses import dataclass
@dataclass
class SyntaxError:
"""Represents a syntax error found in a meson file."""
line_num: int
message: str
severity: str = "error" # error, warning
def __str__(self):
prefix = "WARNING" if self.severity == "warning" else "ERROR"
return f"Line {self.line_num}: [{prefix}] {self.message}"
class MesonLinter:
"""Linter for meson.build files."""
# Known meson functions
KNOWN_FUNCTIONS = {
'project', 'executable', 'library', 'shared_library', 'static_library',
'install_data', 'install_subdir', 'install_headers', 'install_man',
'configure_file', 'custom_target', 'run_command', 'find_program',
'dependency', 'declare_dependency', 'include_directories',
'subdir', 'subproject', 'import', 'files', 'join_paths',
'get_option', 'configuration_data', 'vcs_tag', 'environment',
'generator', 'test', 'benchmark', 'alias_target', 'both_libraries',
'build_target', 'jar', 'run_target', 'summary', 'message', 'warning', 'error',
'assert', 'range', 'meson', 'host_machine', 'target_machine', 'build_machine',
}
# Known meson methods that can be called on objects
KNOWN_METHODS = {
'found', 'get_variable', 'full_path', 'get_path', 'get',
'set', 'set_quoted', 'has_key', 'keys', 'version', 'name',
'project_name', 'project_version', 'current_source_dir',
'current_build_dir', 'source_root', 'build_root', 'add_install_script',
'add_postconf_script', 'add_dist_script', 'install_dependency_manifest',
'override_dependency', 'override_find_program', 'is_cross_build',
'is_unity', 'is_subproject', 'get_compiler', 'backend', 'global_source_root',
'global_build_root', 'project_source_root', 'project_build_root',
'find_installation', 'get_id', 'get_linker_id', 'system', 'cpu_family', 'cpu', 'endian',
}
# Keywords that must have matching end keywords
BLOCK_KEYWORDS = {
'if': 'endif',
'foreach': 'endforeach',
}
def __init__(self, file_path: Path):
self.file_path = file_path
self.errors: list[SyntaxError] = []
self.content = ""
self.lines: list[str] = []
def lint(self) -> list[SyntaxError]:
"""Run all linting checks and return list of errors."""
with open(self.file_path, 'r', encoding='utf-8') as f:
self.content = f.read()
self.lines = self.content.split('\n')
# Run all checks
self._check_balanced_brackets()
self._check_quotes()
self._check_commas()
self._check_colons()
self._check_semicolons()
self._check_control_structures()
self._check_duplicate_entries()
self._check_string_concatenation()
self._check_operator_spacing()
self._check_trailing_whitespace()
self._check_empty_function_calls()
self._check_assignment_syntax()
self._check_comparison_operators()
self._check_common_typos()
return sorted(self.errors, key=lambda e: e.line_num)
def _is_in_string(self, line: str, pos: int) -> bool:
"""Check if position is inside a string literal."""
in_single = False
in_double = False
i = 0
while i < pos and i < len(line):
char = line[i]
if char == "'" and not in_double:
in_single = not in_single
elif char == '"' and not in_single:
in_double = not in_double
i += 1
return in_single or in_double
def _is_in_comment(self, line: str, pos: int) -> bool:
"""Check if position is inside a comment."""
comment_pos = -1
in_single = False
in_double = False
for i, char in enumerate(line):
if char == "'" and not in_double:
in_single = not in_single
elif char == '"' and not in_single:
in_double = not in_double
elif char == '#' and not in_single and not in_double:
comment_pos = i
break
return comment_pos != -1 and pos >= comment_pos
def _strip_strings_and_comments(self, line: str) -> str:
"""Remove string literals and comments from line for analysis."""
result = []
in_single = False
in_double = False
i = 0
while i < len(line):
char = line[i]
# Check for comment start (outside strings)
if char == '#' and not in_single and not in_double:
break
# Handle string delimiters
if char == "'" and not in_double:
in_single = not in_single
result.append(' ') # Replace with space to preserve positions
elif char == '"' and not in_single:
in_double = not in_double
result.append(' ')
elif in_single or in_double:
result.append(' ') # Replace string content with spaces
else:
result.append(char)
i += 1
return ''.join(result)
def _check_balanced_brackets(self):
"""Check for balanced parentheses, square brackets, and curly braces."""
bracket_pairs = {'(': ')', '[': ']', '{': '}'}
bracket_names = {'(': 'parenthesis', '[': 'square bracket', '{': 'curly brace'}
# Track opening brackets with their positions
stacks = {'(': [], '[': [], '{': []}
for line_num, line in enumerate(self.lines, 1):
stripped = self._strip_strings_and_comments(line)
for i, char in enumerate(stripped):
if char in '([{':
stacks[char].append((line_num, i))
elif char in ')]}':
opener = {'(': ')', '[': ']', '{': '}'}
for open_char, close_char in opener.items():
if char == close_char:
if not stacks[open_char]:
self.errors.append(SyntaxError(
line_num,
f"Unmatched closing {bracket_names[open_char]} '{char}'"
))
else:
stacks[open_char].pop()
# Check for unclosed brackets
for open_char, positions in stacks.items():
for line_num, col in positions:
self.errors.append(SyntaxError(
line_num,
f"Unclosed {bracket_names[open_char]} '{open_char}'"
))
def _check_quotes(self):
"""Check for unclosed or mismatched quotes."""
for line_num, line in enumerate(self.lines, 1):
# Skip comment-only lines
stripped = line.strip()
if stripped.startswith('#'):
continue
# Find comment position
comment_pos = len(line)
in_single = False
in_double = False
for i, char in enumerate(line):
if char == "'" and not in_double:
in_single = not in_single
elif char == '"' and not in_single:
in_double = not in_double
elif char == '#' and not in_single and not in_double:
comment_pos = i
break
# Analyze only the code part (before comment)
code_part = line[:comment_pos]
# Count quotes (simplified check)
single_quotes = 0
double_quotes = 0
in_single = False
in_double = False
i = 0
while i < len(code_part):
char = code_part[i]
if char == "'" and not in_double:
single_quotes += 1
in_single = not in_single
elif char == '"' and not in_single:
double_quotes += 1
in_double = not in_double
i += 1
if single_quotes % 2 != 0:
self.errors.append(SyntaxError(
line_num,
"Unclosed single quote (') - odd number of quotes on line"
))
if double_quotes % 2 != 0:
self.errors.append(SyntaxError(
line_num,
'Unclosed double quote (") - odd number of quotes on line'
))
def _check_commas(self):
"""Check for missing, extra, or misplaced commas."""
# Track if we're inside a function call or list
paren_depth = 0
bracket_depth = 0
for line_num, line in enumerate(self.lines, 1):
stripped = self._strip_strings_and_comments(line)
line_stripped = stripped.strip()
original_stripped = line.strip()
if not line_stripped:
continue
# Check for double commas
if ',,' in line: # Use original line
self.errors.append(SyntaxError(
line_num,
"Double comma ',,'"
))
# Check for comma at start of line (usually wrong)
# Use original line - meson uses trailing commas on separate lines
if original_stripped.startswith(',') and not original_stripped.startswith("',") and not original_stripped.startswith('",'):
self.errors.append(SyntaxError(
line_num,
"Comma at start of line - likely misplaced or missing from previous line"
))
# Check for space before comma (but not after string/closing bracket)
# Pattern like `foo ,` is wrong, but `'file.py',` is fine
# Only flag if there's whitespace directly before comma, not inside quotes
space_comma_match = re.search(r'([^\s\'"\]\)])\s+,', line)
if space_comma_match:
self.errors.append(SyntaxError(
line_num,
"Space before comma",
severity="warning"
))
# Update bracket depth
for i, char in enumerate(stripped):
if char == '(':
paren_depth += 1
elif char == ')':
paren_depth -= 1
elif char == '[':
bracket_depth += 1
elif char == ']':
bracket_depth -= 1
# Second pass: check for missing commas between string literals
self._check_missing_commas_between_strings()
def _check_missing_commas_between_strings(self):
"""Check for missing commas between consecutive string literals in lists."""
# Track bracket depth to know when we're in a function call or list
paren_depth = 0
bracket_depth = 0
for line_num, line in enumerate(self.lines, 1):
stripped = self._strip_strings_and_comments(line)
original = line.strip()
# Update bracket depth
for char in stripped:
if char == '(':
paren_depth += 1
elif char == ')':
paren_depth -= 1
elif char == '[':
bracket_depth += 1
elif char == ']':
bracket_depth -= 1
# Skip if not inside brackets
if paren_depth <= 0 and bracket_depth <= 0:
continue
# Check if line ends with a string literal WITHOUT trailing comma
# Pattern: 'something' or "something" at end of line (possibly with comment)
ends_with_string_no_comma = re.search(r"['\"]([^'\"]*)['\"](?:\s*#.*)?$", original)
if ends_with_string_no_comma and not re.search(r"['\"],\s*(?:#.*)?$", original):
# Check next non-empty line
for next_num in range(line_num, len(self.lines)):
next_line = self.lines[next_num].strip()
if not next_line or next_line.startswith('#'):
continue
# If next line starts with a string literal, missing comma!
if re.match(r"^['\"]", next_line):
self.errors.append(SyntaxError(
line_num,
f"Missing comma after string literal - next line starts with another string"
))
break
def _check_colons(self):
"""Check for colon syntax errors."""
for line_num, line in enumerate(self.lines, 1):
stripped = self._strip_strings_and_comments(line)
line_stripped = stripped.strip()
if not line_stripped:
continue
# Check for double colons (not valid in meson)
if '::' in stripped:
self.errors.append(SyntaxError(
line_num,
"Double colon '::' - not valid meson syntax"
))
# Check for colon without space after (in keyword arguments)
# Pattern: word: followed by non-space
matches = re.finditer(r'(\w+):(\S)', stripped)
for match in matches:
# Skip if it's a path separator like '/dir'
if match.group(2) != ' ':
keyword = match.group(1)
# Common keyword arguments
if keyword in ['install_dir', 'install_mode', 'rename', 'version',
'meson_version', 'license', 'input', 'output',
'configuration', 'exclude_directories', 'exclude_files',
'required', 'native', 'method', 'pkgconfig']:
self.errors.append(SyntaxError(
line_num,
f"Missing space after colon in keyword argument '{keyword}:'",
severity="warning"
))
# Check for space before colon in keyword arguments
# But exclude foreach syntax: foreach var : list
if re.search(r'\w\s+:', stripped) and not re.match(r'^\s*foreach\s+', stripped):
self.errors.append(SyntaxError(
line_num,
"Space before colon in keyword argument",
severity="warning"
))
def _check_semicolons(self):
"""Check for semicolons which are not valid in meson."""
for line_num, line in enumerate(self.lines, 1):
stripped = self._strip_strings_and_comments(line)
if ';' in stripped:
self.errors.append(SyntaxError(
line_num,
"Semicolon ';' found - meson does not use semicolons"
))
def _check_control_structures(self):
"""Check if/endif and foreach/endforeach are properly matched."""
stack = [] # (keyword, line_num)
for line_num, line in enumerate(self.lines, 1):
stripped = self._strip_strings_and_comments(line).strip()
if not stripped:
continue
# Check for if statement
if re.match(r'^if\s+', stripped) or stripped == 'if':
stack.append(('if', line_num))
elif stripped == 'else' or re.match(r'^else\s*$', stripped):
if not stack or stack[-1][0] != 'if':
self.errors.append(SyntaxError(
line_num,
"'else' without matching 'if'"
))
elif re.match(r'^elif\s+', stripped):
if not stack or stack[-1][0] != 'if':
self.errors.append(SyntaxError(
line_num,
"'elif' without matching 'if'"
))
elif stripped == 'endif' or re.match(r'^endif\s*$', stripped):
if not stack or stack[-1][0] != 'if':
self.errors.append(SyntaxError(
line_num,
"'endif' without matching 'if'"
))
elif stack:
stack.pop()
# Check for foreach statement
elif re.match(r'^foreach\s+', stripped):
stack.append(('foreach', line_num))
elif stripped == 'endforeach' or re.match(r'^endforeach\s*$', stripped):
if not stack or stack[-1][0] != 'foreach':
self.errors.append(SyntaxError(
line_num,
"'endforeach' without matching 'foreach'"
))
elif stack:
stack.pop()
# Check for unclosed blocks
for keyword, line_num in stack:
end_keyword = self.BLOCK_KEYWORDS.get(keyword, f'end{keyword}')
self.errors.append(SyntaxError(
line_num,
f"'{keyword}' without matching '{end_keyword}'"
))
def _check_duplicate_entries(self):
"""Check for duplicate file entries in install_data calls."""
# Find all install_data blocks
pattern = r'install_data\s*\(((?:[^()]|\((?:[^()]|\([^()]*\))*\))*)\)'
matches = re.finditer(pattern, self.content, re.DOTALL)
for match in matches:
block = match.group(1)
# Find line number of this block
start_pos = match.start()
line_num = self.content[:start_pos].count('\n') + 1
# Extract all string entries - only standalone file names, not paths
# Split by newlines and extract file entries
entries = []
for entry_match in re.finditer(r"^\s*'([^'/]+\.[a-z]+)'", block, re.MULTILINE):
entries.append(entry_match.group(1))
# Find duplicates
counter = Counter(entries)
for entry, count in counter.items():
if count > 1:
self.errors.append(SyntaxError(
line_num,
f"Duplicate entry '{entry}' appears {count} times in install_data",
severity="warning"
))
def _check_string_concatenation(self):
"""Check for incorrect string concatenation."""
for line_num, line in enumerate(self.lines, 1):
# Check for + between strings (should use / for paths)
if re.search(r"'\s*\+\s*'", line):
self.errors.append(SyntaxError(
line_num,
"String concatenation with '+' - consider using '/' for paths",
severity="warning"
))
# Check for missing operator between strings
# Pattern: 'string' 'string' without operator
stripped = self._strip_strings_and_comments(line)
if re.search(r"'\s+'", line) and "'" in line:
# More precise check
in_call = '(' in stripped
if in_call:
# Could be separate arguments - that's ok
pass
def _check_operator_spacing(self):
"""Check for proper spacing around operators."""
for line_num, line in enumerate(self.lines, 1):
stripped = self._strip_strings_and_comments(line)
if not stripped.strip():
continue
# Check for missing space around = (but not ==, !=, <=, >=)
# Pattern: identifier=value without spaces
if re.search(r'[a-zA-Z_]\w*=[^=]', stripped):
# But allow keyword arguments with colon
if not re.search(r'[a-zA-Z_]\w*\s*:', stripped):
# Check it's not inside a function call keyword arg
if '(' not in stripped or stripped.index('=') < stripped.index('('):
pass # This might be intentional in some contexts
# Check for == used for assignment (common mistake)
if re.search(r'^[a-zA-Z_]\w*\s*==\s*[^=]', stripped.strip()):
self.errors.append(SyntaxError(
line_num,
"Possible incorrect use of '==' instead of '=' for assignment",
severity="warning"
))
def _check_trailing_whitespace(self):
"""Check for trailing whitespace."""
for line_num, line in enumerate(self.lines, 1):
if line != line.rstrip():
self.errors.append(SyntaxError(
line_num,
"Trailing whitespace",
severity="warning"
))
def _check_empty_function_calls(self):
"""Check for potentially erroneous empty function calls."""
for line_num, line in enumerate(self.lines, 1):
# Use original line - we want to check if there are actual arguments
# Skip comment part
code_line = line.split('#')[0] if '#' in line else line
# Check for function calls with nothing (not even keyword args)
# Pattern: function_name() with no arguments where arguments are typically required
required_arg_functions = ['install_data', 'install_subdir', 'dependency',
'executable', 'library', 'project', 'subdir']
for func in required_arg_functions:
if re.search(rf'\b{func}\s*\(\s*\)', code_line):
self.errors.append(SyntaxError(
line_num,
f"'{func}()' called with no arguments - this is likely an error"
))
def _check_assignment_syntax(self):
"""Check for common assignment syntax errors."""
for line_num, line in enumerate(self.lines, 1):
stripped = self._strip_strings_and_comments(line).strip()
if not stripped:
continue
# Check for := (not valid in meson)
if ':=' in stripped:
self.errors.append(SyntaxError(
line_num,
"':=' is not valid meson syntax - use '=' for assignment"
))
# Check for => (not valid in meson)
if '=>' in stripped:
self.errors.append(SyntaxError(
line_num,
"'=>' is not valid meson syntax"
))
def _check_comparison_operators(self):
"""Check for valid comparison operators."""
for line_num, line in enumerate(self.lines, 1):
stripped = self._strip_strings_and_comments(line)
# Check for === (not valid in meson)
if '===' in stripped:
self.errors.append(SyntaxError(
line_num,
"'===' is not valid meson syntax - use '==' for comparison"
))
# Check for !== (not valid in meson)
if '!==' in stripped:
self.errors.append(SyntaxError(
line_num,
"'!==' is not valid meson syntax - use '!=' for comparison"
))
# Check for <> (old not equal syntax)
if '<>' in stripped:
self.errors.append(SyntaxError(
line_num,
"'<>' is not valid meson syntax - use '!=' for not equal"
))
def _check_common_typos(self):
"""Check for common typos in meson keywords and functions."""
common_typos = {
'instal_data': 'install_data',
'install_dataa': 'install_data',
'instlal_data': 'install_data',
'install_subdr': 'install_subdir',
'install_suddir': 'install_subdir',
'depedency': 'dependency',
'dependecy': 'dependency',
'dependancy': 'dependency',
'excutable': 'executable',
'executalbe': 'executable',
'configrue_file': 'configure_file',
'configure_fiel': 'configure_file',
'configuartion_data': 'configuration_data',
'configuration_dataa': 'configuration_data',
'get_optin': 'get_option',
'get_optoin': 'get_option',
'joint_paths': 'join_paths',
'join_pathss': 'join_paths',
'forech': 'foreach',
'foreahc': 'foreach',
'enforeach': 'endforeach',
'endforach': 'endforeach',
'ednif': 'endif',
'enidif': 'endif',
'elseif': 'elif',
'else if': 'elif',
'porject': 'project',
'projcet': 'project',
'mesno': 'meson',
'meosn': 'meson',
'vesion': 'version',
'verison': 'version',
'licnese': 'license',
'lisence': 'license',
'licence': 'license',
}
for line_num, line in enumerate(self.lines, 1):
stripped = self._strip_strings_and_comments(line).lower()
for typo, correct in common_typos.items():
if typo in stripped:
self.errors.append(SyntaxError(
line_num,
f"Possible typo '{typo}' - did you mean '{correct}'?"
))
def get_python_files_from_directory(directory):
"""Get all Python files from a directory (excluding __pycache__ and other non-source files)"""
python_files = []
for file_path in Path(directory).iterdir():
if (file_path.is_file() and
file_path.suffix == '.py' and
file_path.name != '__pycache__' and
not file_path.name.startswith('.') and # Skip hidden files
file_path.name != 'meson.build'): # Exclude meson.build itself
python_files.append(file_path.name)
return sorted(python_files)
def get_files_from_meson_build(meson_file_path):
"""Extract file names from all install_* sections in meson.build"""
with open(meson_file_path, 'r', encoding='utf-8') as f:
content = f.read()
files = []
# Define all possible install functions that could contain files
install_functions = [
'install_data', # Standard data installation
'install_sources', # Source files installation
'install_subdir', # Subdirectory installation (doesn't list individual files)
'install_headers', # Header files installation
'install_man', # Manual pages installation
'install_symlink', # Symlinks installation
'install_emptydir' # Empty directories installation
]
# Process each install function
for func_name in install_functions:
# Skip install_subdir since it installs whole directories, not individual files
if func_name == 'install_subdir':
continue
# Create regex pattern for this function
pattern = rf'{func_name}\(\s*((?:[^()]|\((?:[^()]|\([^()]*\))*\))*)\s*\)'
matches = re.findall(pattern, content, re.DOTALL)
for match in matches:
# Extract individual file names (strings between quotes)
# Looking for common file extensions used in the project
file_matches = re.findall(r"'([^']*(?:\.py|\.ui|\.qml|\.js|\.css|\.svg|\.json|\.txt|\.md|\.h|\.c|\.cpp|\.hpp|\.xml|\.ini|\.desktop|\.metainfo|\.pot|\.po))'", match)
files.extend(file_matches)
for match in matches:
# Extract individual file names (strings between quotes)
file_matches = re.findall(r"'([^']*(?:\.py|\.ui|\.qml|\.js|\.css|\.svg|\.json|\.txt|\.md))'", match)
files.extend(file_matches)
return sorted(set(files)) # Use set to remove duplicates
def check_syntax(repo_root: Path) -> tuple[list[str], list[str]]:
"""Check meson.build syntax and return (errors, warnings)."""
meson_files_list = list(repo_root.glob("**/meson.build"))
all_errors = []
all_warnings = []
for meson_file in meson_files_list:
linter = MesonLinter(meson_file)
errors = linter.lint()
for error in errors:
full_msg = f"{meson_file}: {error}"
if error.severity == "warning":
all_warnings.append(full_msg)
else:
all_errors.append(full_msg)
return all_errors, all_warnings
def check_files(repo_root: Path) -> list[str]:
"""Check if all Python files are included in meson.build. Return list of missing files."""
portprotonqt_dir = repo_root / 'portprotonqt'
portprotonqt_meson = portprotonqt_dir / 'meson.build'
if not portprotonqt_meson.exists():
return []
dir_files = get_python_files_from_directory(portprotonqt_dir)
meson_files = get_files_from_meson_build(portprotonqt_meson)
return [f for f in dir_files if f not in meson_files]
def main():
repo_root = Path(__file__).parent.parent
exit_code = 0
# Check syntax
all_errors, all_warnings = check_syntax(repo_root)
if all_warnings:
print("WARNINGS found in meson.build files:")
for warning in all_warnings:
print(f" - {warning}")
print()
if all_errors:
print("ERRORS found in meson.build files:")
for error in all_errors:
print(f" - {error}")
print("\nPlease fix these syntax errors in the respective meson.build files")
exit_code = 1
# Check files inclusion (only if syntax is OK)
if exit_code == 0:
missing_files = check_files(repo_root)
if missing_files:
print("ERROR: The following files are present in the directory but missing from meson.build:")
for file in missing_files:
print(f" - {file}")
print("\nPlease add these files to the install_data section in portprotonqt/meson.build")
exit_code = 1
# Success message
if exit_code == 0:
if all_warnings:
print("All checks passed (with warnings)")
else:
print("All checks passed: syntax is valid and all files are listed")
return exit_code
if __name__ == "__main__":
sys.exit(main())
+68 -43
View File
@@ -3,7 +3,10 @@
import sys
from pathlib import Path
import re
import ast
# Import the security checker from the main module
sys.path.insert(0, str(Path(__file__).parent.parent)) # Add project root to path
from portprotonqt.theme_security import ThemeSecurityChecker
# Запрещенные QSS-свойства
FORBIDDEN_PROPERTIES = {
@@ -13,57 +16,79 @@ FORBIDDEN_PROPERTIES = {
"text-shadow",
}
# Запрещенные модули и функции
FORBIDDEN_MODULES = {
"os",
"subprocess",
"shutil",
"sys",
"socket",
"ctypes",
"pathlib",
"glob",
}
FORBIDDEN_FUNCTIONS = {
"exec",
"eval",
"open",
"__import__",
}
def check_css_comments(content: str, file_path: Path) -> list[str]:
"""
Проверка синтаксиса CSS-комментариев.
Возвращает список ошибок.
"""
errors = []
# Ищем незавершённые комментарии: /* без закрывающего */
# Исключаем корректные комментарии /* ... */
in_comment = False
comment_start = 0
i = 0
while i < len(content) - 1:
if content[i:i+2] == '/*':
if in_comment:
errors.append(f"Nested comment start at position {i}")
in_comment = True
comment_start = i
i += 2
elif content[i:i+2] == '*/':
if not in_comment:
errors.append(f"Unexpected comment end '*/' without matching '/*' at position {i}")
in_comment = False
i += 2
else:
i += 1
if in_comment:
errors.append(f"Unclosed comment starting at position {comment_start}")
# Ищем опечатки: * ... */ без открывающего /*
# Паттерн: пробел/символ, затем *, затем текст, затем */
pattern = r'(?<!/)\*\s+[^*]*\*/'
for match in re.finditer(pattern, content):
# Проверяем, не часть строки ли это (внутри f-строки)
line_start = content.rfind('\n', 0, match.start()) + 1
line_prefix = content[line_start:match.start()]
# Пропускаем, если это внутри строки (после кавычки)
if '"' in line_prefix or "'" in line_prefix:
continue
errors.append(f"Invalid comment '{match.group()}' - missing opening '/*'")
return errors
def check_qss_files():
has_errors = False
for qss_file in Path("portprotonqt/themes").glob("**/*.py"):
with open(qss_file, "r") as f:
# Check for forbidden QSS properties first
with open(qss_file, "r", encoding='utf-8') as f:
content = f.read()
# Проверка на запрещённые QSS-свойства
for prop in FORBIDDEN_PROPERTIES:
if re.search(rf"{prop}\s*:", content, re.IGNORECASE):
print(f"ERROR: Unknown QSS property found '{prop}' in file {qss_file}")
has_errors = True
# Проверка на опасные импорты и функции
try:
tree = ast.parse(content)
for node in ast.walk(tree):
# Проверка импортов
if isinstance(node, (ast.Import, ast.ImportFrom)):
for name in node.names:
if name.name in FORBIDDEN_MODULES:
print(f"ERROR: Forbidden module '{name.name}' found in file {qss_file}")
has_errors = True
# Проверка вызовов функций
if isinstance(node, ast.Call):
if isinstance(node.func, ast.Name) and node.func.id in FORBIDDEN_FUNCTIONS:
print(f"ERROR: Forbidden function '{node.func.id}' found in file {qss_file}")
has_errors = True
except SyntaxError as e:
print(f"ERROR: Syntax error in file {qss_file}: {e}")
for prop in FORBIDDEN_PROPERTIES:
if re.search(rf"{prop}\s*:", content, re.IGNORECASE):
print(f"ERROR: Unknown QSS property found '{prop}' in file {qss_file}")
has_errors = True
# Check CSS comment syntax
comment_errors = check_css_comments(content, qss_file)
for error in comment_errors:
print(f"ERROR: CSS comment syntax error in {qss_file}: {error}")
has_errors = True
# Use the imported ThemeSecurityChecker to check for dangerous imports and functions
checker = ThemeSecurityChecker()
is_safe, errors = checker.check_theme_safety(str(qss_file))
if not is_safe:
for error in errors:
print(error)
has_errors = True
return has_errors
if __name__ == "__main__":
if check_qss_files():
sys.exit(1)
sys.exit(1)
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env bash
# Generate shell completion files for bash, zsh, and fish
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
OUTPUT_DIR="$PROJECT_ROOT/completions"
mkdir -p "$OUTPUT_DIR"
# Bash completion
cat > "$OUTPUT_DIR/portprotonqt" << 'EOF'
_portprotonqt_completions() {
local cur prev opts long_opts flags
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
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 --help -h"
long_opts="--fullscreen --resolution --debug-level --force-muvm --add-steam-compat-tool --reinstall-steam-compat-tool --remove-steam-compat-tool --ppqtos --help"
# Values for options with arguments
local debug_levels="ALL DEBUG INFO WARNING ERROR CRITICAL"
local resolutions="1920x1080 1280x720 2560x1440 3840x2160"
# Handle option arguments
case "${prev}" in
--debug-level)
COMPREPLY=( $(compgen -W "${debug_levels}" -- "${cur}") )
return 0
;;
--resolution)
COMPREPLY=( $(compgen -W "${resolutions}" -- "${cur}") )
return 0
;;
esac
# At command start, complete only long options to allow "--" prefix completion
if [[ -z "${cur}" ]]; then
COMPREPLY=( $(compgen -W "${long_opts}" -- "${cur}") )
return 0
fi
# Complete flags when option prefix is used
if [[ "${cur}" == -* ]]; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
fi
return 0
}
complete -F _portprotonqt_completions portprotonqt
EOF
# Zsh completion
cat > "$OUTPUT_DIR/_portprotonqt" << 'EOF'
#compdef portprotonqt
_portprotonqt() {
local -a opts
opts=(
'--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]'
'--ppqtos[Show the system tab]'
'(-h --help)'{-h,--help}'[Show help message]'
)
_arguments -s "${opts[@]}" && return 0
_files -g "*.exe"
}
EOF
# Fish completion
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 --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 ppqtos -d "Show the system tab"
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"
EOF
echo "Generated completions in $OUTPUT_DIR"
PKGDIR="${PKGDIR:-${DESTDIR:-}}"
if [[ -n "$PKGDIR" ]]; then
# Shell completions
install -d "$PKGDIR/usr/share/bash-completion/completions"
install -d "$PKGDIR/usr/share/zsh/site-functions"
install -d "$PKGDIR/usr/share/fish/vendor_completions.d"
install -m 644 "$OUTPUT_DIR/portprotonqt.bash" \
"$PKGDIR/usr/share/bash-completion/completions/portprotonqt" || :
install -m 644 "$OUTPUT_DIR/_portprotonqt" \
"$PKGDIR/usr/share/zsh/site-functions/_portprotonqt" || :
install -m 644 "$OUTPUT_DIR/portprotonqt.fish" \
"$PKGDIR/usr/share/fish/vendor_completions.d/portprotonqt.fish" || :
echo "Installed completions into $PKGDIR"
fi
+11 -162
View File
@@ -9,24 +9,15 @@ import ssl
# Получаем ключи и данные из переменных окружения
STEAM_KEY = os.environ.get('STEAM_KEY')
LINUX_GAMING_API_KEY = os.environ.get('LINUX_GAMING_API_KEY')
LINUX_GAMING_API_USERNAME = os.environ.get('LINUX_GAMING_API_USERNAME')
# Флаги для включения/отключения источников
ENABLE_STEAM = os.environ.get('ENABLE_STEAM', 'true').lower() == 'true'
ENABLE_ANTICHEAT = os.environ.get('ENABLE_ANTICHEAT', 'true').lower() == 'true'
ENABLE_LINUX_GAMING = os.environ.get('ENABLE_LINUX_GAMING', 'true').lower() == 'true'
DEBUG_MODE = os.environ.get('DEBUG_MODE', 'false').lower() == 'true'
# Конфигурация API
STEAM_BASE_URL = "https://api.steampowered.com/IStoreService/GetAppList/v1/?"
LINUX_GAMING_BASE_URL = "https://linux-gaming.ru"
CATEGORY_STEAM = "games"
CATEGORY_LINUX_GAMING = "ppdb"
LINUX_GAMING_HEADERS = {
"Api-Key": LINUX_GAMING_API_KEY,
"Api-Username": LINUX_GAMING_API_USERNAME
}
# Отключаем предупреждения об SSL в дебаг-режиме
if DEBUG_MODE:
@@ -86,7 +77,7 @@ async def get_app_list(session, last_appid, endpoint):
async def fetch_games_json(session):
"""
Загружает JSON с данными из AreWeAntiCheatYet и извлекает поля normalized_name и status.
Загружает JSON с данными из AreWeAntiCheatYet и извлекает normalized_name, status и slug.
"""
url = "https://raw.githubusercontent.com/AreWeAntiCheatYet/AreWeAntiCheatYet/HEAD/games.json"
try:
@@ -94,139 +85,26 @@ async def fetch_games_json(session):
response.raise_for_status()
text = await response.text()
data = json.loads(text)
return [{"normalized_name": normalize_name(game["name"]), "status": game["status"]} for game in data]
result = []
for game in data:
slug = game.get("slug") or game.get("id") or ""
result.append({
"normalized_name": normalize_name(game["name"]),
"status": game["status"],
"slug": slug,
})
return result
except Exception as error:
print(f"Ошибка загрузки games.json: {error}")
return []
async def get_linux_gaming_topics(session, category_slug):
page = 0
all_topics = []
max_pages = 100
while page < max_pages:
# Пробуем несколько вариантов URL
urls_to_try = [
f"{LINUX_GAMING_BASE_URL}/c/{category_slug}/5/l/latest.json", # с id категории
f"{LINUX_GAMING_BASE_URL}/c/{category_slug}/l/latest.json", # только slug
f"{LINUX_GAMING_BASE_URL}/c/5/l/latest.json", # только id
f"{LINUX_GAMING_BASE_URL}/latest.json" # все темы
]
success = False
data = None
for url in urls_to_try:
try:
# Добавляем параметры пагинации
params = {
'page': page,
'order': 'default'
}
async with session.get(url, headers=LINUX_GAMING_HEADERS,
params=params, verify_ssl=not DEBUG_MODE) as response:
if response.status == 429:
print(f"Слишком много запросов на странице {page}, ожидание...")
await asyncio.sleep(5)
continue
if response.status == 404:
if DEBUG_MODE:
print(f"URL не найден: {url}")
continue
response.raise_for_status()
data = await response.json()
# Проверяем структуру ответа
topic_list = data.get("topic_list", {})
topics = topic_list.get("topics", [])
if not topics:
if page == 0:
if DEBUG_MODE:
print(f"Нет тем в URL: {url}")
continue
else:
print(f"Страница {page} пуста, завершаем пагинацию.")
return all_topics
if DEBUG_MODE and page == 0:
print(f"Успешно подключились к URL: {url}")
success = True
break
except Exception as e:
if DEBUG_MODE:
print(f"Ошибка с URL {url}: {e}")
continue
if not success:
print(f"Не удалось загрузить страницу {page}")
break
# Обрабатываем темы (этот блок должен быть внутри основного цикла)
try:
topic_list = data.get("topic_list", {})
topics = topic_list.get("topics", [])
page_topics_added = 0
for topic in topics:
slug = topic["slug"]
# Пропускаем тему описания категории
if slug is None or slug == "opisanie-kategorii-portprotondb":
if DEBUG_MODE:
print(f"Пропущена тема описания категории")
continue
normalized_title = normalize_name(topic["title"])
# Добавляем только валидные темы
all_topics.append({
"normalized_title": normalized_title,
"slug": slug,
})
page_topics_added += 1
if DEBUG_MODE and page_topics_added <= 3: # Показываем первые 3 темы
print(f"Добавлена тема: {normalized_title} (slug: {slug}")
print(f"Обработано {len(topics)} тем на странице {page}, добавлено: {page_topics_added}, всего: {len(all_topics)}.")
# Проверяем, есть ли еще страницы
more_topics_url = topic_list.get("more_topics_url")
if not more_topics_url:
print("Больше тем нет, завершаем пагинацию.")
break
page += 1
# Добавляем небольшую задержку между запросами
await asyncio.sleep(0.5)
except Exception as e:
print(f"Ошибка при обработке тем на странице {page}: {e}")
break
if not all_topics:
print("Предупреждение: не удалось получить ни одной темы из linux-gaming.ru.")
else:
print(f"Всего получено {len(all_topics)} тем из категории {category_slug}")
return all_topics
async def request_data():
"""
Получает данные из Steam, AreWeAntiCheatYet и linux-gaming.ru,
Получает данные из Steam и AreWeAntiCheatYet,
обрабатывает их и сохраняет в JSON-файлы и tar.xz архивы.
"""
output_json = []
total_parsed = 0
linux_gaming_topics = []
anticheat_games = []
try:
@@ -266,15 +144,6 @@ async def request_data():
else:
print("Пропущена загрузка данных AreWeAntiCheatYet (ENABLE_ANTICHEAT=false).")
# Загружаем данные linux-gaming.ru
if ENABLE_LINUX_GAMING:
if LINUX_GAMING_API_KEY and LINUX_GAMING_API_USERNAME:
linux_gaming_topics = await get_linux_gaming_topics(session, CATEGORY_LINUX_GAMING)
else:
print("Предупреждение: LINUX_GAMING_API_KEY или LINUX_GAMING_API_USERNAME не установлены.")
else:
print("Пропущена загрузка данных linux-gaming.ru (ENABLE_LINUX_GAMING=false).")
except Exception as error:
print(f"Ошибка получения данных: {error}")
return False
@@ -323,26 +192,6 @@ async def request_data():
print(f"Ошибка при упаковке архива AreWeAntiCheatYet: {e}")
return False
# Сохранение данных linux-gaming.ru
if ENABLE_LINUX_GAMING and linux_gaming_topics:
linux_gaming_json_full = os.path.join(data_dir, "linux_gaming_topics.json")
linux_gaming_json_min = os.path.join(data_dir, "linux_gaming_topics_min.json")
with open(linux_gaming_json_full, "w", encoding="utf-8") as f:
json.dump(linux_gaming_topics, f, ensure_ascii=False, indent=2)
with open(linux_gaming_json_min, "w", encoding="utf-8") as f:
json.dump(linux_gaming_topics, f, ensure_ascii=False, separators=(',',':'))
# Упаковка минифицированного JSON linux-gaming.ru в tar.xz архив
linux_gaming_archive_path = os.path.join(data_dir, "linux_gaming_topics.tar.xz")
try:
with tarfile.open(linux_gaming_archive_path, "w:xz", preset=9) as tar:
tar.add(linux_gaming_json_min, arcname=os.path.basename(linux_gaming_json_min))
print(f"Упаковано минифицированное JSON linux-gaming.ru в архив: {linux_gaming_archive_path}")
os.remove(linux_gaming_json_min)
except Exception as e:
print(f"Ошибка при упаковке архива linux-gaming.ru: {e}")
return False
return True
async def run():
+237 -92
View File
@@ -2,9 +2,8 @@
import argparse
import sys
import io
import contextlib
import re
import ast
from pathlib import Path
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
@@ -12,95 +11,20 @@ from babel.messages.frontend import CommandLineInterface
from pyaspeller import YandexSpeller
# ---------- Пути ----------
GUIDE_DIR = Path(__file__).parent.parent / "documentation" / "localization_guide"
README_EN = GUIDE_DIR / "README.md"
README_RU = GUIDE_DIR / "README.ru.md"
LOCALES_PATH = Path(__file__).parent.parent / "portprotonqt" / "locales"
THEMES_PATH = Path(__file__).parent.parent / "portprotonqt" / "themes"
README_FILES = [README_EN, README_RU]
POT_FILE = LOCALES_PATH / "messages.pot"
MESON_BUILD = Path(__file__).parent.parent / "portprotonqt" / "meson.build"
POT_FILE = LOCALES_PATH / "portprotonqt.pot"
# ---------- Версия проекта ----------
def _get_version() -> str:
return "0.1.1"
# ---------- Обновление README ----------
def _update_coverage(lines: list[str]) -> None:
# Парсим статистику из вывода pybabel --statistics
locales_stats = [line for line in lines if line.endswith(".po")]
# Извлекаем (count, pct, locale) и сортируем
rows = sorted(
(m := re.search(
r"""(\d+\ of\ \d+).* # message counts
\((\d+\%)\).* # message percentage
locales\/(.*)\/LC_MESSAGES # locale name""",
stat, re.VERBOSE
)) and m.groups()
for stat in locales_stats
)
for md_file in README_FILES:
if not md_file.exists():
continue
text = md_file.read_text(encoding="utf-8")
is_ru = (md_file == README_RU)
# Выбираем заголовок раздела
status_header = (
"Current translation status:" if not is_ru
else "Текущий статус перевода:"
)
# Формируем шапку и строки таблицы
if is_ru:
table_header = (
"<!-- Сгенерировано автоматически! -->\n\n"
"| Локаль | Прогресс | Переведено |\n"
"| :----- | -------: | ---------: |\n"
)
fmt = lambda count, pct, loc: f"| [{loc}](./{loc}/LC_MESSAGES/messages.po) | {pct} | {count.replace(' of ', ' из ')} |"
else:
table_header = (
"<!-- Auto-generated coverage table -->\n\n"
"| Locale | Progress | Translated |\n"
"| :----- | -------: | ---------: |\n"
)
fmt = lambda count, pct, loc: f"| [{loc}](./{loc}/LC_MESSAGES/messages.po) | {pct} | {count} |"
# Собираем строки и добавляем '---' в конце
coverage_table = (
table_header
+ "\n".join(fmt(c, p, l) for c, p, l in rows)
+ "\n\n---"
)
# Удаляем старую автоматически сгенерированную таблицу
old_block = (
r"<!--\s*(?:Сгенерировано автоматически!|Auto-generated coverage table)\s*-->"
r".*?(?=\n(?:##|\Z))"
)
cleaned = re.sub(old_block, "", text, flags=re.DOTALL)
# Вставляем новую таблицу сразу после строки с заголовком
insert_pattern = rf"(^.*{re.escape(status_header)}.*$)"
new_text = re.sub(
insert_pattern,
lambda m: m.group(1) + "\n\n" + coverage_table,
cleaned,
count=1,
flags=re.MULTILINE
)
# Записываем файл, если были изменения
if new_text != text:
md_file.write_text(new_text, encoding="utf-8")
# ---------- PyBabel команды ----------
def compile_locales() -> None:
CommandLineInterface().run([
"pybabel", "compile", "--use-fuzzy", "--directory",
f"{LOCALES_PATH.resolve()}", "--statistics"
f"{LOCALES_PATH.resolve()}", "--domain=portprotonqt", "--statistics"
])
def extract_strings() -> None:
@@ -117,14 +41,184 @@ def extract_strings() -> None:
])
def update_locales() -> None:
saved_headers: dict[Path, list[str]] = {}
saved_po_texts: dict[Path, str] = {}
for po_file in LOCALES_PATH.glob("**/portprotonqt.po"):
saved_po_texts[po_file] = po_file.read_text(encoding="utf-8")
header_block = _get_po_header_block(po_file)
if header_block:
saved_headers[po_file] = header_block
CommandLineInterface().run([
"pybabel", "update",
f"--input-file={POT_FILE.resolve()}",
f"--output-dir={LOCALES_PATH.resolve()}",
"--domain=portprotonqt",
"--ignore-obsolete",
"--ignore-pot-creation-date",
"--update-header-comment",
])
for po_file, header_block in saved_headers.items():
_set_po_header_block(po_file, header_block)
for po_file, original_text in saved_po_texts.items():
_restore_unchanged_po_entries(po_file, original_text)
def _get_po_header_block(po_path: Path) -> list[str] | None:
lines = po_path.read_text(encoding="utf-8").splitlines()
in_header = False
header_start = None
header_end = None
for i, line in enumerate(lines):
if line == 'msgstr ""':
in_header = True
header_start = i + 1
continue
if not in_header:
continue
if not line.startswith('"'):
header_end = i
break
if header_start is None or header_end is None or header_end <= header_start:
return None
return lines[header_start:header_end]
def _set_po_header_block(po_path: Path, block: list[str]) -> None:
lines = po_path.read_text(encoding="utf-8").splitlines()
in_header = False
header_start = None
header_end = None
for i, line in enumerate(lines):
if line == 'msgstr ""':
in_header = True
header_start = i + 1
continue
if not in_header:
continue
if not line.startswith('"'):
header_end = i
break
if header_start is None or header_end is None:
return
lines[header_start:header_end] = block
po_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def _parse_po_entry_signature(block: list[str]) -> tuple[str, tuple[tuple[str, str], ...]] | None:
msgctxt = ""
msgid = None
msgstr_values: dict[str, str] = {}
i = 0
while i < len(block):
line = block[i]
if line.startswith("msgctxt "):
msgctxt, i = _read_po_value(block, i, "msgctxt ")
continue
if line.startswith("msgid "):
msgid, i = _read_po_value(block, i, "msgid ")
continue
if line.startswith("msgstr "):
value, i = _read_po_value(block, i, "msgstr ")
msgstr_values["msgstr"] = value
continue
if line.startswith("msgstr["):
key = line.split(" ", maxsplit=1)[0]
value, i = _read_po_value(block, i, f"{key} ")
msgstr_values[key] = value
continue
i += 1
if msgid is None or msgid == "":
return None
return f"{msgctxt}\x04{msgid}", tuple(sorted(msgstr_values.items()))
def _read_po_value(block: list[str], idx: int, prefix: str) -> tuple[str, int]:
value = _unquote_po_string(block[idx][len(prefix):])
idx += 1
while idx < len(block) and block[idx].startswith('"'):
value += _unquote_po_string(block[idx])
idx += 1
return value, idx
def _unquote_po_string(value: str) -> str:
value = value.strip()
if not value.startswith('"'):
return ""
return ast.literal_eval(value)
def _split_po_blocks(text: str) -> list[list[str]]:
blocks: list[list[str]] = []
current: list[str] = []
for line in text.splitlines():
if line == "":
if current:
blocks.append(current)
current = []
continue
current.append(line)
if current:
blocks.append(current)
return blocks
def _restore_unchanged_po_entries(po_path: Path, original_text: str) -> None:
original_blocks = _split_po_blocks(original_text)
original_entries: dict[str, tuple[tuple[tuple[str, str], ...], list[str]]] = {}
for block in original_blocks:
signature = _parse_po_entry_signature(block)
if signature is None:
continue
key, values = signature
original_entries[key] = (values, block)
current_blocks = _split_po_blocks(po_path.read_text(encoding="utf-8"))
changed = False
for i, block in enumerate(current_blocks):
signature = _parse_po_entry_signature(block)
if signature is None:
continue
key, values = signature
if key not in original_entries:
continue
original_values, original_block = original_entries[key]
if values != original_values:
continue
if block == original_block:
continue
current_blocks[i] = original_block
changed = True
if not changed:
return
rebuilt = "\n\n".join("\n".join(block) for block in current_blocks)
po_path.write_text(rebuilt + "\n", encoding="utf-8")
def _update_meson_locales(new_locales: list[str]) -> None:
"""Обновляет список языков в meson.build."""
if not MESON_BUILD.exists():
return
text = MESON_BUILD.read_text(encoding="utf-8")
# Ищем foreach lang : ['de', 'es', 'pt', 'ru']
pattern = r"(foreach\s+lang\s*:\s*\[)([^\]]+)(\])"
match = re.search(pattern, text)
if not match:
return
# Парсим текущий список языков
current_langs_str = match.group(2)
current_langs = re.findall(r"'([^']+)'", current_langs_str)
# Добавляем новые языки и сортируем
all_langs = sorted(set(current_langs) | set(new_locales))
# Формируем новый список
new_langs_str = ", ".join(f"'{lang}'" for lang in all_langs)
new_text = text[:match.start()] + match.group(1) + new_langs_str + match.group(3) + text[match.end():]
if new_text != text:
MESON_BUILD.write_text(new_text, encoding="utf-8")
print(f"Updated meson.build with locales: {all_langs}")
def create_new(locales: list[str]) -> None:
if not POT_FILE.exists():
extract_strings()
@@ -133,8 +227,12 @@ def create_new(locales: list[str]) -> None:
"pybabel", "init",
f"--input-file={POT_FILE.resolve()}",
f"--output-dir={LOCALES_PATH.resolve()}",
"--domain=portprotonqt",
"--no-wrap",
f"--locale={locale}"
])
# Обновляем meson.build с новыми локалями
_update_meson_locales(locales)
# ---------- Игнорируемые префиксы для spellcheck ----------
IGNORED_PREFIXES = ()
@@ -148,6 +246,41 @@ def load_ignored_prefixes(ignore_file=".spellignore"):
IGNORED_PREFIXES = load_ignored_prefixes() + ("PortProton", "flatpak")
# ---------- Проверка fuzzy строк ----------
def find_fuzzy_entries(filepath: Path) -> list[tuple[int, str, str]]:
"""Находит fuzzy записи в .po файле. Возвращает список (номер_строки, msgid, флаги)."""
fuzzy_entries = []
lines = filepath.read_text(encoding='utf-8').splitlines()
i = 0
while i < len(lines):
line = lines[i].strip()
# Ищем комментарий с флагами, содержащий fuzzy
if line.startswith('#,') and 'fuzzy' in line:
flags = line[2:].strip()
line_num = i + 1
# Ищем следующий msgid
msgid = ""
i += 1
while i < len(lines):
next_line = lines[i].strip()
if next_line.startswith('msgid '):
match = re.match(r'^msgid\s+"(.*)"', next_line)
if match:
msgid = match.group(1)
i += 1
# Собираем многострочный msgid
while i < len(lines) and lines[i].strip().startswith('"'):
msgid += lines[i].strip()[1:-1]
i += 1
break
i += 1
# Пропускаем пустой msgid (заголовок PO файла)
if msgid:
fuzzy_entries.append((line_num, msgid, flags))
else:
i += 1
return fuzzy_entries
# ---------- Проверка орфографии с параллелизмом ----------
speller = YandexSpeller()
MSGID_RE = re.compile(r'^msgid\s+"(.*)"')
@@ -208,17 +341,36 @@ def main(args) -> int:
if args.create_new:
create_new(args.create_new)
if args.spellcheck:
files = list(LOCALES_PATH.glob("**/*.po")) + [POT_FILE]
files = list(LOCALES_PATH.glob("**/portprotonqt.po")) + [POT_FILE]
seen = set(); has_err = False
issues_summary = defaultdict(list)
fuzzy_summary = defaultdict(list)
for f in files:
if not f.exists() or f in seen: continue
seen.add(f)
# Проверка fuzzy строк (только для .po файлов)
if f.suffix == '.po':
fuzzy_entries = find_fuzzy_entries(f)
if fuzzy_entries:
fuzzy_summary[f] = fuzzy_entries
has_err = True
if check_file(f, issues_summary):
has_err = True
else:
print(f"✅ {f} — no errors found.")
if has_err:
if f not in fuzzy_summary:
print(f"✅ {f} — no errors found.")
# Вывод fuzzy строк
if fuzzy_summary:
print("\n⚠️ Fuzzy Entries (require review before release):")
for file, entries in fuzzy_summary.items():
print(f"\n⚠ {file}")
print("-----")
for idx, (line_num, msgid, flags) in enumerate(entries, 1):
print(f"{idx}. Line {line_num}: [{flags}]")
print(f" msgid: \"{msgid[:80]}{'...' if len(msgid) > 80 else ''}\"")
print("-----")
# Вывод орфографических ошибок
if issues_summary:
print("\n📋 Summary of Spelling Errors:")
for file, errs in issues_summary.items():
print(f"\n✗ {file}")
@@ -233,14 +385,7 @@ def main(args) -> int:
if __name__ == "__main__":
parser = argparse.ArgumentParser(prog="l10n", description="Localization utility for PortProtonQt.")
parser.add_argument("--create-new", nargs='+', type=str, default=False, help="Create .po for new locales")
parser.add_argument("--update-all", action='store_true', help="Extract/update locales and update README coverage")
parser.add_argument("--update-all", action='store_true', help="Extract/update locales")
parser.add_argument("--spellcheck", action='store_true', help="Run spellcheck on POT and PO files")
args = parser.parse_args()
if args.spellcheck:
sys.exit(main(args))
f = io.StringIO()
with contextlib.redirect_stdout(f), contextlib.redirect_stderr(f):
main(args)
output = f.getvalue().splitlines()
_update_coverage(output)
sys.exit(0)
sys.exit(main(args))
BIN
View File
Binary file not shown.
+29 -17
View File
@@ -4,29 +4,41 @@
## 📋 Contents
- [Overview](#-overview)
- [Translate Online](#-translate-online)
- [Adding a New Translation](#-adding-a-new-translation)
- [Updating Existing Translations](#-updating-existing-translations)
- [Compiling Translations](#-compiling-translations)
- [Spell Check](#-spell-check)
---
## 📖 Overview
Localization in `PortProtonQT` is powered by `Babel` using `.po/.mo` files stored under `LC_MESSAGES/messages.po` for each language.
Localization in `PortProtonQT` is powered by `Babel` using `.po` files stored under `LC_MESSAGES/portprotonqt.po` for each language.
To see updated translations in the app, you must generate `.mo` files after editing `.po`.
Current translation status:
<!-- Auto-generated coverage table -->
| Locale | Progress | Translated |
| :----- | -------: | ---------: |
| [de_DE](./de_DE/LC_MESSAGES/messages.po) | 0% | 0 of 193 |
| [es_ES](./es_ES/LC_MESSAGES/messages.po) | 0% | 0 of 193 |
| [ru_RU](./ru_RU/LC_MESSAGES/messages.po) | 100% | 193 of 193 |
<a href="https://translate.codeberg.org/engage/portprotonqt/">
<img src="https://translate.codeberg.org/widget/portprotonqt/multi-auto.svg" alt="Translation status" />
</a>
---
## 🌐 Translate Online
You can help translate PortProtonQt using our web-based translation platform:
**[translate.codeberg.org/engage/portprotonqt](https://translate.codeberg.org/engage/portprotonqt)**
Benefits of using the web platform:
- No need to set up a development environment
- Work directly in your browser
- See context and suggestions from other translators
- Collaborate with the community
Translations submitted online are periodically reviewed and merged into the main repository.
---
## 🏁 Adding a New Translation
@@ -39,7 +51,12 @@ source .venv/bin/activate
python dev-scripts/l10n.py --create-new <locale_code>
```
2. Edit the file `portprotonqt/locales/<locale>/LC_MESSAGES/messages.po` in Poedit or any text editor.
2. Edit the file `portprotonqt/locales/<locale>/LC_MESSAGES/portprotonqt.po` in Poedit or GTranslator.
3. Generate `.mo` files:
```bash
python dev-scripts/l10n.py
```
---
@@ -54,17 +71,13 @@ source .venv/bin/activate
python dev-scripts/l10n.py --update-all
```
---
## 🧵 Compiling Translations
After editing `.po` files, generate `.mo`; otherwise new translations will not be visible in the UI:
```bash
uv python install 3.10
uv sync --all-extras --dev
source .venv/bin/activate
python dev-scripts/l10n.py
```
---
## 🔍 Spell Check
@@ -78,4 +91,3 @@ python dev-scripts/l10n.py --spellcheck
```
The script performs parallel spellchecking of strings in `.po` and `.pot` files. For each file, it prints the list of strings being checked and highlights any spelling errors with suggestions. Words listed in `dev-scripts/.spellignore` are ignored and not treated as typos.
+30 -16
View File
@@ -4,29 +4,41 @@
## 📋 Содержание
- [Обзор](#-обзор)
- [Перевод онлайн](#-перевод-онлайн)
- [Добавление нового перевода](#-добавление-нового-перевода)
- [Обновление существующих переводов](#-обновление-существующих-переводов)
- [Компиляция переводов](#-компиляция-переводов)
- [Проверка орфографии](#-проверка-орфографии)
---
## 📖 Обзор
Локализация в `PortProtonQT` осуществляется через систему `.po/.mo` файлов и управляется утилитой `Babel`. Все переводы находятся в подкаталогах вида `LC_MESSAGES/messages.po` для каждой поддерживаемой локали.
Локализация в `PortProtonQT` осуществляется через систему `.po` файлов и управляется утилитой `Babel`. Все переводы находятся в подкаталогах вида `LC_MESSAGES/portprotonqt.po` для каждой поддерживаемой локали.
Для отображения изменений в приложении необходимо сгенерировать `.mo` файлы после правок в `.po`.
Текущий статус перевода:
<!-- Сгенерировано автоматически! -->
| Локаль | Прогресс | Переведено |
| :----- | -------: | ---------: |
| [de_DE](./de_DE/LC_MESSAGES/messages.po) | 0% | 0 из 193 |
| [es_ES](./es_ES/LC_MESSAGES/messages.po) | 0% | 0 из 193 |
| [ru_RU](./ru_RU/LC_MESSAGES/messages.po) | 100% | 193 из 193 |
<a href="https://translate.codeberg.org/engage/portprotonqt/">
<img src="https://translate.codeberg.org/widget/portprotonqt/multi-auto.svg" alt="Состояние перевода" />
</a>
---
## 🌐 Перевод онлайн
Вы можете помочь перевести PortProtonQt через нашу веб-платформу:
**[translate.codeberg.org/engage/portprotonqt](https://translate.codeberg.org/engage/portprotonqt)**
Преимущества веб-платформы:
- Не нужно настраивать окружение разработки
- Работа прямо в браузере
- Видно контекст и варианты от других переводчиков
- Совместная работа с сообществом
Переводы, отправленные через веб-платформу, периодически проверяются и объединяются с основным репозиторием.
---
## 🏁 Добавление нового перевода
@@ -39,7 +51,12 @@ source .venv/bin/activate
python dev-scripts/l10n.py --create-new <код_локали>
```
2. Отредактируйте файл `portprotonqt/locales/<локаль>/LC_MESSAGES/messages.po` в Poedit или любом текстовом редакторе.
2. Отредактируйте файл `portprotonqt/locales/<локаль>/LC_MESSAGES/portprotonqt.po` в Poedit или GTranslator.
3. Сгенерируйте `.mo` файлы:
```bash
python dev-scripts/l10n.py
```
---
@@ -54,17 +71,14 @@ source .venv/bin/activate
python dev-scripts/l10n.py --update-all
```
---
## 🧵 Компиляция переводов
После изменения `.po` файлов сгенерируйте `.mo`, иначе новые переводы не появятся в интерфейсе:
```bash
uv python install 3.10
uv sync --all-extras --dev
source .venv/bin/activate
python dev-scripts/l10n.py
```
---
## 🔍 Проверка орфографии
Для проверки орфографии используйте команду:
+79 -12
View File
@@ -31,17 +31,63 @@ mkdir -p ~/.local/share/PortProtonQT/themes/my_custom_theme
## 🎨 Style File (`styles.py`)
Create a `styles.py` in the theme root. It should define variables or functions that return CSS.
Create a `styles.py` in the theme root. It should define variables or functions that return QSS (Qt Style Sheets). For better organization, you can split your theme into multiple submodules by creating a subdirectory (e.g., `styles`, `components`, etc.) with separate Python files for different components, and import them in `styles.py`.
**Example:**
**Example of modular structure:**
```
my_custom_theme/
├── styles.py
├── metainfo.ini
├── fonts/
├── images/
└── styles/ # This can be named anything (e.g., components, modules, etc.)
├── __init__.py # This empty file makes the directory a Python package
├── constants.py
├── base.py
├── game_card.py
├── detail_page.py
├── settings.py
├── winetricks.py
└── theme_utils.py
```
**Main styles.py file:**
You can use either absolute imports (recommended for built-in themes):
```python
def custom_button_style(color1, color2):
return f"""
QPushButton {{
background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
stop:0 {color1}, stop:1 {color2});
}}
"""
# Import from the theme's submodules using absolute paths relative to the package
# Replace 'my_custom_theme' with your actual theme folder name and 'styles' with your subdirectory name
from portprotonqt.themes.my_custom_theme.styles.constants import *
from portprotonqt.themes.my_custom_theme.styles.base import *
from portprotonqt.themes.my_custom_theme.styles.game_card import *
from portprotonqt.themes.my_custom_theme.styles.detail_page import *
from portprotonqt.themes.my_custom_theme.styles.settings import *
from portprotonqt.themes.my_custom_theme.styles.winetricks import *
from portprotonqt.themes.my_custom_theme.styles.theme_utils import *
```
Or you can use relative imports (recommended for custom user themes):
```python
# Import from the theme's submodules using relative paths
from .styles.constants import *
from .styles.base import *
from .styles.game_card import *
from .styles.detail_page import *
from .styles.settings import *
from .styles.winetricks import *
from .styles.theme_utils import *
```
**Example submodule (styles/constants.py):**
```python
# Theme constants
font_family = "Play"
font_size_a = "16px"
font_size_b = "24px"
border_radius_a = "10px"
color_a = "#409EFF"
color_b = "#282a33"
# ... other constants
```
---
@@ -207,23 +253,44 @@ GAME_CARD_ANIMATION = {
```ini
[Metainfo]
name = My Custom Theme
name_en = My Custom Theme
name_ru = Моя пользовательская тема
author = Your Name
author_link = https://example.com
description = Description of your theme.
description_en = Description of your theme.
description_ru = Описание вашей темы.
```
### Translation Support
You must provide translations for your theme's name and description by adding language-specific fields:
- `name_en`, `name_ru`, etc. for theme names
- `description_en`, `description_ru`, etc. for theme descriptions
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.
---
## 🖼 Screenshots
Folder: `images/screenshots/` — place UI screenshots there.
Screenshot files can have any convenient names.
---
## 🔡 Fonts and Icons (optional)
- Fonts: `fonts/*.ttf` or `.otf`
- Icons: `images/icons/*.svg/.png`
- Icons and Images: `images/` directory for all visual assets:
- `images/icons/` - Main application icons (organized in subdirectories like actions/, navigation/, platforms/, etc.)
- `images/icons/buttons/` - Button icons for UI elements
- `images/icons/keyboards/` - Keyboard key icons (key_+, key_enter, etc.)
- `images/icons/controllers/` - Controller button icons
- `images/icons/controllers/xbox/` - Xbox controller button icons (xbox_a, xbox_b, etc.)
- `images/icons/controllers/playstation/` - PlayStation controller button icons (ps_circle, ps_cross, etc.)
- `images/ui_elements/` - UI elements (placeholder images, etc.)
- `images/screenshots/` - Theme preview screenshots
Icons and images can be referenced by name without specifying the subdirectory, as the system will search through all subdirectories automatically. Theme creators can organize images in any logical subdirectory structure.
---
+79 -12
View File
@@ -31,17 +31,63 @@ mkdir -p ~/.local/share/PortProtonQT/themes/my_custom_theme
## 🎨 Файл стилей (`styles.py`)
Создайте `styles.py` в корне темы. В нём определите переменные и/или функции, возвращающие CSS-оформление.
Создайте `styles.py` в корне темы. В нём определите переменные и/или функции, возвращающие QSS-оформление (Qt Style Sheets). Для лучшей организации кода, вы можете разделить тему на несколько подмодулей, создав поддиректорию (например, `styles`, `components` и т.д.) с отдельными Python-файлами для разных компонентов, и импортировать их в `styles.py`.
**Пример функции:**
**Пример модульной структуры:**
```
my_custom_theme/
├── styles.py
├── metainfo.ini
├── fonts/
├── images/
└── styles/ # Это может быть названо как угодно (например, components, modules и т.д.)
├── __init__.py # Этот пустой файл делает директорию Python-пакетом
├── constants.py
├── base.py
├── game_card.py
├── detail_page.py
├── settings.py
├── winetricks.py
└── theme_utils.py
```
**Основной файл styles.py:**
Вы можете использовать абсолютные импорты (рекомендуется для встроенных тем):
```python
def custom_button_style(color1, color2):
return f"""
QPushButton {{
background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
stop:0 {color1}, stop:1 {color2});
}}
"""
# Импорт из подмодулей темы с использованием абсолютных путей относительно пакета
# Замените 'my_custom_theme' на фактическое имя папки вашей темы и 'styles' на имя вашей поддиректории
from portprotonqt.themes.my_custom_theme.styles.constants import *
from portprotonqt.themes.my_custom_theme.styles.base import *
from portprotonqt.themes.my_custom_theme.styles.game_card import *
from portprotonqt.themes.my_custom_theme.styles.detail_page import *
from portprotonqt.themes.my_custom_theme.styles.settings import *
from portprotonqt.themes.my_custom_theme.styles.winetricks import *
from portprotonqt.themes.my_custom_theme.styles.theme_utils import *
```
Или вы можете использовать относительные импорты (рекомендуется для пользовательских тем):
```python
# Импорт из подмодулей темы с использованием относительных путей
from .styles.constants import *
from .styles.base import *
from .styles.game_card import *
from .styles.detail_page import *
from .styles.settings import *
from .styles.winetricks import *
from .styles.theme_utils import *
```
**Пример подмодуля (styles/constants.py):**
```python
# Константы темы
font_family = "Play"
font_size_a = "16px"
font_size_b = "24px"
border_radius_a = "10px"
color_a = "#409EFF"
color_b = "#282a33"
# ... другие константы
```
---
@@ -207,23 +253,44 @@ GAME_CARD_ANIMATION = {
```ini
[Metainfo]
name = My Custom Theme
name_en = My Custom Theme
name_ru = Моя пользовательская тема
author = Ваше имя
author_link = https://example.com
description = Описание вашей темы.
description_en = Description of your theme.
description_ru = Описание вашей темы.
```
### Поддержка переводов
Вы должны предоставить переводы для названия и описания вашей темы, добавив поля с указанием языка:
- `name_en`, `name_ru` и т.д. для названий тем
- `description_en`, `description_ru` и т.д. для описаний тем
Приложение автоматически выберет соответствующий перевод на основе языка системы пользователя, с откатом к английскому языку, если переводы недоступны для языка пользователя.
---
## 🖼 Скриншоты
Папка: `images/screenshots/` — любые изображения оформления темы.
Файлы скриншотов можно называть в удобном для вас формате.
---
## 🔡 Шрифты и иконки (опционально)
- Шрифты: `fonts/*.ttf` или `.otf`
- Иконки: `images/icons/*.svg/.png`
- Иконки и изображения: `images/` директория для всех визуальных ресурсов:
- `images/icons/` - Основные иконки приложения (организованные в поддиректории: actions/, navigation/, platforms/ и т.д.)
- `images/icons/buttons/` - Иконки кнопок для элементов интерфейса
- `images/icons/keyboards/` - Иконки клавиш клавиатуры (key_+, key_enter и т.д.)
- `images/icons/controllers/` - Иконки кнопок контроллеров
- `images/icons/controllers/xbox/` - Иконки кнопок Xbox контроллера (xbox_a, xbox_b и т.д.)
- `images/icons/controllers/playstation/` - Иконки кнопок PlayStation контроллера (ps_circle, ps_cross и т.д.)
- `images/ui_elements/` - Элементы интерфейса (заглушка и т.д.)
- `images/screenshots/` - Скриншоты предварительного просмотра темы
Иконки и изображения могут быть вызваны по имени без указания поддиректории, так как система будет автоматически искать во всех поддиректориях. Создатели тем могут организовывать изображения в любую логическую структуру поддиректорий.
---
+114
View File
@@ -0,0 +1,114 @@
project('portprotonqt', 'c',
version: '0.1.12',
meson_version: '>= 0.61.2',
license: 'GPL-3.0',
)
# Python installation
python3 = import('python').find_installation('python3')
# Configuration
conf = configuration_data()
conf.set('PYTHON', python3.full_path())
# Directories
prefix = get_option('prefix')
datadir = prefix / get_option('datadir')
bindir = prefix / get_option('bindir')
# Use custom purelibdir if specified, otherwise use default
purelibdir_opt = get_option('python_purelibdir')
pythondir = purelibdir_opt != '' ? purelibdir_opt : join_paths(prefix, python3.get_path('purelib'))
pkgdatadir = pythondir / meson.project_name()
# C compiler for vk_gpu_info
cc = meson.get_compiler('c')
# Install Python package
subdir('portprotonqt')
# Install entry point script
configured_portprotonqt = configure_file(
input: 'build-aux/portprotonqt',
output: 'portprotonqt-script',
configuration: conf,
)
install_data(configured_portprotonqt,
install_dir: bindir,
install_mode: 'rwxr-xr-x',
rename: 'portprotonqt',
)
# Build and install vk_gpu_info executable
vk_gpu_info_sources = files('build-aux/vk_gpu_info.c')
vk_gpu_info_deps = [dependency('vulkan', required: true)]
executable('vk_gpu_info',
sources: vk_gpu_info_sources,
dependencies: vk_gpu_info_deps,
install: true,
install_dir: bindir,
c_args: ['-std=c99'],
)
if get_option('build_i586_req_dummy')
i586_req_dummy_link_args = [
'-Wl,--no-as-needed',
'-l:libGL.so.1',
'-l:libgio-2.0.so.0',
'-l:libnm.so.0',
'-l:libnss3.so',
'-l:libunwind.so.8',
'-l:libVkLayer_MESA_device_select.so',
'-l:libnsl.so.1',
'-l:libvulkan_intel.so',
'-l:libvulkan_radeon.so',
'-l:libvulkan_nouveau.so',
]
executable('portprotonqt_i586_req_dummy',
sources: files('build-aux/i586_req_dummy.c'),
install: true,
install_dir: pkgdatadir,
c_args: ['-std=c99'],
link_args: i586_req_dummy_link_args,
)
endif
# Install desktop file
install_data(
'build-aux/share/applications/ru.linux_gaming.PortProtonQt.desktop',
install_dir: datadir / 'applications',
)
# Install icon
install_data(
'build-aux/share/icons/hicolor/scalable/apps/ru.linux_gaming.PortProtonQt.svg',
install_dir: datadir / 'icons/hicolor/scalable/apps',
)
# Install metainfo
install_data(
'build-aux/share/metainfo/ru.linux_gaming.PortProtonQt.metainfo.xml',
install_dir: datadir / 'metainfo',
)
# Install Steam compatibility tool
subdir('build-aux/share/steam/compatibilitytools.d/PortProtonQt')
# Install udev rules
udev_rulesdir_opt = get_option('udev_rulesdir')
udevdir = udev_rulesdir_opt != '' ? udev_rulesdir_opt : prefix / 'lib' / 'udev' / 'rules.d'
install_data(
'build-aux/lib/udev/rules.d/60-portprotonqt.rules',
install_dir: udevdir,
)
# Install polkit rules
install_data(
'build-aux/share/polkit-1/rules.d/ru.linux_gaming.PortProtonQt.rules',
install_dir: prefix / 'share' / 'polkit-1' / 'rules.d',
)
+5
View File
@@ -0,0 +1,5 @@
# Meson options for PortProtonQt
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('build_i586_req_dummy', type: 'boolean', value: false, description: 'Build dummy binary linked with i586 auto-requirement libraries')
+333 -43
View File
@@ -1,3 +1,4 @@
from typing import Any, cast
from PySide6.QtCore import QPropertyAnimation, QByteArray, QEasingCurve, QAbstractAnimation, QParallelAnimationGroup, QRect, Qt, QPoint
from PySide6.QtGui import QPainter, QPen, QColor, QConicalGradient, QBrush
from PySide6.QtWidgets import QWidget, QGraphicsOpacityEffect
@@ -32,6 +33,47 @@ class GameCardAnimations:
self.pulse_anim: QPropertyAnimation | None = None
self._isPulseAnimationConnected = False
def cleanup(self):
"""Clean up all animation objects to prevent memory leaks."""
if self.thickness_anim:
try:
self.thickness_anim.stop()
if self._isPulseAnimationConnected:
try:
self.thickness_anim.finished.disconnect(self.start_pulse_animation)
except RuntimeError:
pass # Signal was already disconnected
self.thickness_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.thickness_anim = None
if self.gradient_anim:
try:
self.gradient_anim.stop()
self.gradient_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.gradient_anim = None
if self.scale_anim:
try:
self.scale_anim.stop()
self.scale_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.scale_anim = None
if self.pulse_anim:
try:
self.pulse_anim.stop()
self.pulse_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.pulse_anim = None
self._isPulseAnimationConnected = False
def setup_animations(self):
"""Initialize animation properties based on theme."""
self.thickness_anim = QPropertyAnimation(self.game_card, QByteArray(b"borderWidth"))
@@ -49,8 +91,16 @@ class GameCardAnimations:
"""Start pulse animation for border width when hovered or focused."""
if not (self.game_card._hovered or self.game_card._focused):
return
# Clean up existing pulse animation to prevent memory leaks
if self.pulse_anim:
self.pulse_anim.stop()
try:
self.pulse_anim.stop()
self.pulse_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.pulse_anim = None
self.pulse_anim = QPropertyAnimation(self.game_card, QByteArray(b"borderWidth"))
self.pulse_anim.setDuration(self.theme.GAME_CARD_ANIMATION["pulse_anim_duration"])
self.pulse_anim.setLoopCount(0)
@@ -73,7 +123,10 @@ class GameCardAnimations:
if self.thickness_anim:
self.thickness_anim.stop()
if self._isPulseAnimationConnected:
self.thickness_anim.finished.disconnect(self.start_pulse_animation)
try:
self.thickness_anim.finished.disconnect(self.start_pulse_animation)
except RuntimeError:
pass # Signal was already disconnected
self._isPulseAnimationConnected = False
self.thickness_anim.setEasingCurve(QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION["thickness_easing_curve"]]))
self.thickness_anim.setStartValue(self.game_card._borderWidth)
@@ -83,8 +136,15 @@ class GameCardAnimations:
self.thickness_anim.start()
if animation_type == "gradient":
# Clean up existing gradient animation to prevent memory leaks
if self.gradient_anim:
self.gradient_anim.stop()
try:
self.gradient_anim.stop()
self.gradient_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.gradient_anim = None
self.gradient_anim = QPropertyAnimation(self.game_card, QByteArray(b"gradientAngle"))
self.gradient_anim.setDuration(self.theme.GAME_CARD_ANIMATION["gradient_anim_duration"])
self.gradient_anim.setStartValue(self.theme.GAME_CARD_ANIMATION["gradient_start_angle"])
@@ -92,8 +152,15 @@ class GameCardAnimations:
self.gradient_anim.setLoopCount(-1)
self.gradient_anim.start()
elif animation_type == "scale":
# Clean up existing scale animation to prevent memory leaks
if self.scale_anim:
self.scale_anim.stop()
try:
self.scale_anim.stop()
self.scale_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.scale_anim = None
self.scale_anim = QPropertyAnimation(self.game_card, QByteArray(b"scale"))
self.scale_anim.setDuration(self.theme.GAME_CARD_ANIMATION["scale_anim_duration"])
self.scale_anim.setEasingCurve(QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION["scale_easing_curve"]]))
@@ -109,11 +176,21 @@ class GameCardAnimations:
animation_type = self.theme.GAME_CARD_ANIMATION.get("card_animation_type", "gradient")
if animation_type == "gradient":
if self.gradient_anim:
self.gradient_anim.stop()
try:
self.gradient_anim.stop()
self.gradient_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.gradient_anim = None
elif animation_type == "scale":
if self.scale_anim:
self.scale_anim.stop()
try:
self.scale_anim.stop()
self.scale_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.scale_anim = None
self.scale_anim = QPropertyAnimation(self.game_card, QByteArray(b"scale"))
self.scale_anim.setDuration(self.theme.GAME_CARD_ANIMATION["scale_anim_duration"])
self.scale_anim.setEasingCurve(QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION["scale_easing_curve_out"]]))
@@ -121,12 +198,19 @@ class GameCardAnimations:
self.scale_anim.setEndValue(self.theme.GAME_CARD_ANIMATION["default_scale"])
self.scale_anim.start()
if self.pulse_anim:
self.pulse_anim.stop()
try:
self.pulse_anim.stop()
self.pulse_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.pulse_anim = None
if self.thickness_anim:
self.thickness_anim.stop()
if self._isPulseAnimationConnected:
self.thickness_anim.finished.disconnect(self.start_pulse_animation)
try:
self.thickness_anim.finished.disconnect(self.start_pulse_animation)
except RuntimeError:
pass # Signal was already disconnected
self._isPulseAnimationConnected = False
self.thickness_anim.setEasingCurve(QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION["thickness_easing_curve_out"]]))
self.thickness_anim.setStartValue(self.game_card._borderWidth)
@@ -147,7 +231,10 @@ class GameCardAnimations:
if self.thickness_anim:
self.thickness_anim.stop()
if self._isPulseAnimationConnected:
self.thickness_anim.finished.disconnect(self.start_pulse_animation)
try:
self.thickness_anim.finished.disconnect(self.start_pulse_animation)
except RuntimeError:
pass # Signal was already disconnected
self._isPulseAnimationConnected = False
self.thickness_anim.setEasingCurve(QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION["thickness_easing_curve"]]))
self.thickness_anim.setStartValue(self.game_card._borderWidth)
@@ -157,8 +244,15 @@ class GameCardAnimations:
self.thickness_anim.start()
if animation_type == "gradient":
# Clean up existing gradient animation to prevent memory leaks
if self.gradient_anim:
self.gradient_anim.stop()
try:
self.gradient_anim.stop()
self.gradient_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.gradient_anim = None
self.gradient_anim = QPropertyAnimation(self.game_card, QByteArray(b"gradientAngle"))
self.gradient_anim.setDuration(self.theme.GAME_CARD_ANIMATION["gradient_anim_duration"])
self.gradient_anim.setStartValue(self.theme.GAME_CARD_ANIMATION["gradient_start_angle"])
@@ -166,8 +260,15 @@ class GameCardAnimations:
self.gradient_anim.setLoopCount(-1)
self.gradient_anim.start()
elif animation_type == "scale":
# Clean up existing scale animation to prevent memory leaks
if self.scale_anim:
self.scale_anim.stop()
try:
self.scale_anim.stop()
self.scale_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.scale_anim = None
self.scale_anim = QPropertyAnimation(self.game_card, QByteArray(b"scale"))
self.scale_anim.setDuration(self.theme.GAME_CARD_ANIMATION["scale_anim_duration"])
self.scale_anim.setEasingCurve(QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION["scale_easing_curve"]]))
@@ -183,11 +284,21 @@ class GameCardAnimations:
animation_type = self.theme.GAME_CARD_ANIMATION.get("card_animation_type", "gradient")
if animation_type == "gradient":
if self.gradient_anim:
self.gradient_anim.stop()
try:
self.gradient_anim.stop()
self.gradient_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.gradient_anim = None
elif animation_type == "scale":
if self.scale_anim:
self.scale_anim.stop()
try:
self.scale_anim.stop()
self.scale_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.scale_anim = None
self.scale_anim = QPropertyAnimation(self.game_card, QByteArray(b"scale"))
self.scale_anim.setDuration(self.theme.GAME_CARD_ANIMATION["scale_anim_duration"])
self.scale_anim.setEasingCurve(QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION["scale_easing_curve_out"]]))
@@ -195,12 +306,19 @@ class GameCardAnimations:
self.scale_anim.setEndValue(self.theme.GAME_CARD_ANIMATION["default_scale"])
self.scale_anim.start()
if self.pulse_anim:
self.pulse_anim.stop()
try:
self.pulse_anim.stop()
self.pulse_anim.deleteLater()
except RuntimeError:
pass # Object already deleted
self.pulse_anim = None
if self.thickness_anim:
self.thickness_anim.stop()
if self._isPulseAnimationConnected:
self.thickness_anim.finished.disconnect(self.start_pulse_animation)
try:
self.thickness_anim.finished.disconnect(self.start_pulse_animation)
except RuntimeError:
pass # Signal was already disconnected
self._isPulseAnimationConnected = False
self.thickness_anim.setEasingCurve(QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION["thickness_easing_curve_out"]]))
self.thickness_anim.setStartValue(self.game_card._borderWidth)
@@ -236,14 +354,57 @@ class DetailPageAnimations:
self.main_window = main_window
self.theme_manager = ThemeManager()
self.theme = theme if theme is not None else self.theme_manager.apply_theme(read_theme_from_config())
self.animations = main_window._animations if hasattr(main_window, '_animations') else {}
# Ensure the main window has an animations dict
if not hasattr(main_window, '_animations'):
main_window._animations = {}
self.animations = main_window._animations
def cleanup(self):
"""Clean up all animations to prevent memory leaks."""
# Stop and clean up all animations in the dict
for _detail_page, animation in list(self.animations.items()):
try:
if isinstance(animation, QAbstractAnimation):
animation.stop()
animation.deleteLater()
except RuntimeError:
pass # Object already deleted
self.animations.clear()
def animate_detail_page(self, detail_page: QWidget, load_image_and_restore_effect: Callable, cleanup_animation: Callable):
"""Animate the detail page based on theme settings."""
# Check if the detail page is still valid before proceeding
if not detail_page or detail_page.isHidden() or detail_page.parent() is None:
logger.warning("Detail page is not valid, skipping enter animation")
load_image_and_restore_effect()
cleanup_animation()
return
animation_type = self.theme.GAME_CARD_ANIMATION.get("detail_page_animation_type", "fade")
duration = self.theme.GAME_CARD_ANIMATION.get("detail_page_fade_duration", 350)
# Safely stop and remove any existing animation for this detail page
if detail_page in self.animations:
try:
existing_animation = self.animations[detail_page]
if isinstance(existing_animation, QAbstractAnimation) and existing_animation.state() == QAbstractAnimation.State.Running:
existing_animation.stop()
existing_animation.deleteLater()
except RuntimeError:
logger.debug("Existing animation already deleted")
except Exception as e:
logger.error(f"Error stopping existing animation: {e}", exc_info=True)
finally:
self.animations.pop(detail_page, None)
if animation_type == "fade":
# Check again if page is still valid before starting animation
if not detail_page or detail_page.isHidden():
logger.warning("Detail page became invalid during fade setup, skipping animation")
load_image_and_restore_effect()
cleanup_animation()
return
original_effect = detail_page.graphicsEffect()
opacity_effect = SafeOpacityEffect(detail_page, disable_at_full=True)
opacity_effect.setOpacity(0.0)
@@ -252,17 +413,36 @@ class DetailPageAnimations:
animation.setDuration(duration)
animation.setStartValue(0.0)
animation.setEndValue(0.999)
animation.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
self.animations[detail_page] = animation
def restore_effect():
try:
detail_page.setGraphicsEffect(original_effect) # type: ignore
# Check if page is still valid before restoring effect
if detail_page and not detail_page.isHidden():
detail_page.setGraphicsEffect(cast(Any, original_effect))
except RuntimeError:
logger.warning("Original effect already deleted")
animation.finished.connect(restore_effect)
animation.finished.connect(load_image_and_restore_effect)
animation.finished.connect(opacity_effect.deleteLater)
# Only start animation if page is still valid
if detail_page and not detail_page.isHidden():
animation.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
self.animations[detail_page] = animation
animation.finished.connect(restore_effect)
animation.finished.connect(load_image_and_restore_effect)
animation.finished.connect(opacity_effect.deleteLater)
else:
logger.warning("Detail page invalid when starting fade, cleaning up")
restore_effect()
load_image_and_restore_effect()
opacity_effect.deleteLater()
cleanup_animation()
elif animation_type in ["slide_left", "slide_right", "slide_up", "slide_down"]:
# Check again if page is still valid before starting animation
if not detail_page or detail_page.isHidden():
logger.warning("Detail page became invalid during slide setup, skipping animation")
load_image_and_restore_effect()
cleanup_animation()
return
duration = self.theme.GAME_CARD_ANIMATION.get("detail_page_slide_duration", 500)
easing_curve = QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION.get("detail_page_easing_curve", "OutCubic")])
start_pos = {
@@ -277,11 +457,25 @@ class DetailPageAnimations:
animation.setStartValue(start_pos)
animation.setEndValue(self.main_window.stackedWidget.rect().topLeft())
animation.setEasingCurve(easing_curve)
animation.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
self.animations[detail_page] = animation
animation.finished.connect(cleanup_animation)
animation.finished.connect(load_image_and_restore_effect)
# Only start animation if page is still valid
if detail_page and not detail_page.isHidden():
animation.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
self.animations[detail_page] = animation
animation.finished.connect(cleanup_animation)
animation.finished.connect(load_image_and_restore_effect)
else:
logger.warning("Detail page invalid when starting slide, cleaning up")
load_image_and_restore_effect()
cleanup_animation()
elif animation_type == "bounce":
# Check again if page is still valid before starting animation
if not detail_page or detail_page.isHidden():
logger.warning("Detail page became invalid during bounce setup, skipping animation")
load_image_and_restore_effect()
cleanup_animation()
return
duration = self.theme.GAME_CARD_ANIMATION.get("detail_page_bounce_duration", 400)
easing_curve = QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION.get("detail_page_easing_curve", "OutCubic")])
detail_page.setWindowOpacity(0.0)
@@ -300,14 +494,27 @@ class DetailPageAnimations:
group_anim = QParallelAnimationGroup()
group_anim.addAnimation(opacity_anim)
group_anim.addAnimation(geometry_anim)
group_anim.finished.connect(load_image_and_restore_effect)
group_anim.finished.connect(cleanup_animation)
group_anim.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
self.animations[detail_page] = group_anim
# Only start animation if page is still valid
if detail_page and not detail_page.isHidden():
group_anim.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
self.animations[detail_page] = group_anim
group_anim.finished.connect(load_image_and_restore_effect)
group_anim.finished.connect(cleanup_animation)
else:
logger.warning("Detail page invalid when starting bounce, cleaning up")
load_image_and_restore_effect()
cleanup_animation()
def animate_detail_page_exit(self, detail_page: QWidget, cleanup_callback: Callable):
"""Animate the detail page exit based on theme settings."""
try:
# Check if the detail page is still valid before proceeding
if not detail_page or detail_page.isHidden() or detail_page.parent() is None:
logger.warning("Detail page is not valid, skipping exit animation")
cleanup_callback()
return
animation_type = self.theme.GAME_CARD_ANIMATION.get("detail_page_animation_type", "fade")
# Safely stop and remove any existing animation
@@ -316,6 +523,7 @@ class DetailPageAnimations:
animation = self.animations[detail_page]
if isinstance(animation, QAbstractAnimation) and animation.state() == QAbstractAnimation.State.Running:
animation.stop()
animation.deleteLater()
except RuntimeError:
logger.warning("Animation already deleted for page")
except Exception as e:
@@ -326,6 +534,13 @@ class DetailPageAnimations:
# Define animation based on type
if animation_type == "fade":
duration = self.theme.GAME_CARD_ANIMATION.get("detail_page_fade_duration_exit", 350)
# Check if page is still valid before accessing properties
if not detail_page or detail_page.isHidden():
logger.warning("Detail page became invalid during fade exit setup, skipping animation")
cleanup_callback()
return
original_effect = detail_page.graphicsEffect()
opacity_effect = SafeOpacityEffect(detail_page, disable_at_full=False)
opacity_effect.setOpacity(0.999)
@@ -334,18 +549,39 @@ class DetailPageAnimations:
animation.setDuration(duration)
animation.setStartValue(0.999)
animation.setEndValue(0.0)
animation.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
self.animations[detail_page] = animation
def restore_and_cleanup():
try:
detail_page.setGraphicsEffect(original_effect) # type: ignore
# Check if page is still valid before restoring effect
if detail_page and not detail_page.isHidden():
detail_page.setGraphicsEffect(cast(Any, original_effect))
except RuntimeError:
logger.debug("Original effect already deleted")
cleanup_callback()
animation.finished.connect(restore_and_cleanup)
animation.finished.connect(opacity_effect.deleteLater)
logger.debug("Detail page or effect already deleted")
try:
cleanup_callback()
except RuntimeError:
logger.debug("Error during cleanup callback")
# Check if animation is still valid before starting
if animation and not detail_page.isHidden():
animation.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
self.animations[detail_page] = animation
animation.finished.connect(restore_and_cleanup)
animation.finished.connect(opacity_effect.deleteLater)
else:
logger.warning("Animation or detail page invalid when starting fade exit, cleaning up")
restore_and_cleanup()
opacity_effect.deleteLater()
elif animation_type in ["slide_left", "slide_right", "slide_up", "slide_down"]:
duration = self.theme.GAME_CARD_ANIMATION.get("detail_page_slide_duration_exit", 500)
# Check if page is still valid before accessing properties
if not detail_page or detail_page.isHidden():
logger.warning("Detail page became invalid during slide exit setup, skipping animation")
cleanup_callback()
return
easing_curve = QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION.get("detail_page_easing_curve_exit", "InCubic")])
end_pos = {
"slide_left": QPoint(-self.main_window.width(), 0),
@@ -353,16 +589,37 @@ class DetailPageAnimations:
"slide_up": QPoint(0, self.main_window.height()),
"slide_down": QPoint(0, -self.main_window.height())
}[animation_type]
animation = QPropertyAnimation(detail_page, QByteArray(b"pos"))
animation.setDuration(duration)
animation.setStartValue(detail_page.pos())
animation.setEndValue(end_pos)
animation.setEasingCurve(easing_curve)
animation.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
self.animations[detail_page] = animation
animation.finished.connect(cleanup_callback)
def slide_cleanup():
try:
cleanup_callback()
except RuntimeError:
logger.debug("Error during slide cleanup callback")
# Check if animation is still valid before starting
if animation and not detail_page.isHidden():
animation.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
self.animations[detail_page] = animation
animation.finished.connect(slide_cleanup)
else:
logger.warning("Animation or detail page invalid when starting slide exit, cleaning up")
slide_cleanup()
elif animation_type == "bounce":
duration = self.theme.GAME_CARD_ANIMATION.get("detail_page_bounce_duration_exit", 400)
# Check if page is still valid before accessing properties
if not detail_page or detail_page.isHidden():
logger.warning("Detail page became invalid during bounce exit setup, skipping animation")
cleanup_callback()
return
easing_curve = QEasingCurve(QEasingCurve.Type[self.theme.GAME_CARD_ANIMATION.get("detail_page_easing_curve_exit", "InCubic")])
opacity_anim = QPropertyAnimation(detail_page, QByteArray(b"windowOpacity"))
opacity_anim.setDuration(duration)
@@ -375,13 +632,46 @@ class DetailPageAnimations:
geometry_anim.setStartValue(detail_page.geometry())
geometry_anim.setEndValue(final_rect)
geometry_anim.setEasingCurve(easing_curve)
# Check if animations are still valid before creating group
if not detail_page or detail_page.isHidden():
logger.warning("Detail page became invalid during bounce exit setup, cleaning up")
cleanup_callback()
return
group_anim = QParallelAnimationGroup()
group_anim.addAnimation(opacity_anim)
group_anim.addAnimation(geometry_anim)
group_anim.finished.connect(cleanup_callback)
# Check if group animation is still valid before connecting
if not detail_page or detail_page.isHidden():
logger.warning("Detail page became invalid during group animation setup, cleaning up")
cleanup_callback()
return
def bounce_cleanup():
try:
cleanup_callback()
except RuntimeError:
logger.debug("Error during bounce cleanup callback")
group_anim.start(QAbstractAnimation.DeletionPolicy.DeleteWhenStopped)
self.animations[detail_page] = group_anim
group_anim.finished.connect(bounce_cleanup)
except RuntimeError:
logger.debug("Detail page already deleted during animation setup")
try:
cleanup_callback()
except RuntimeError:
pass
except Exception as e:
logger.error(f"Error in animate_detail_page_exit: {e}", exc_info=True)
self.animations.pop(detail_page, None)
cleanup_callback()
try:
if detail_page in self.animations:
self.animations.pop(detail_page, None)
except RuntimeError:
pass
try:
cleanup_callback()
except RuntimeError:
pass
+325 -30
View File
@@ -1,58 +1,353 @@
import sys
from PySide6.QtCore import QLocale, QTranslator, QLibraryInfo
from PySide6.QtWidgets import QApplication
from PySide6.QtGui import QIcon
from portprotonqt.main_window import MainWindow
from portprotonqt.config_utils import save_fullscreen_config
from portprotonqt.logger import get_logger, setup_logger
from portprotonqt.cli import parse_args
import os
import subprocess
import shutil
__app_id__ = "ru.linux_gaming.PortProtonQt"
__app_name__ = "PortProtonQt"
__app_version__ = "0.1.6"
__app_version__ = "0.1.12"
from PySide6.QtCore import QTimer, Qt, QThread, Signal
from PySide6.QtWidgets import QApplication
from PySide6.QtGui import QIcon
from PySide6.QtNetwork import QLocalServer, QLocalSocket
from portprotonqt.main_window import MainWindow
from portprotonqt.config_utils import (
save_fullscreen_config,
read_fullscreen_config,
get_portproton_start_command,
read_start_minimized,
)
from portprotonqt.logger import get_logger, setup_logger
from portprotonqt.cli import (
parse_args,
is_portproton_url,
parse_portproton_url,
is_launch_file,
normalize_launch_path,
add_steam_compat_tool,
reinstall_steam_compat_tool,
remove_steam_compat_tool,
parse_resolution,
)
from portprotonqt.portproton_api import PortProtonAPI, set_user_conf_setting
from portprotonqt.downloader import Downloader
from portprotonqt.debug_utils import get_screen_info
def get_version():
try:
commit = subprocess.check_output(
["git", "rev-parse", "--short", "HEAD"],
stderr=subprocess.DEVNULL,
).decode("utf-8").strip()
return f"{__app_version__} ({commit})"
except (subprocess.CalledProcessError, FileNotFoundError, OSError):
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 main():
# Parse args early to check for force-muvm flag
parsed_args = parse_args()
# Handle --reinstall-steam-compat-tool flag
if parsed_args.reinstall_steam_compat_tool:
success = reinstall_steam_compat_tool()
sys.exit(0 if success else 1)
# Handle --add-steam-compat-tool flag
if parsed_args.add_steam_compat_tool:
success = add_steam_compat_tool()
sys.exit(0 if success else 1)
# Handle --remove-steam-compat-tool flag
if parsed_args.remove_steam_compat_tool:
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)
os.environ["PW_CLI"] = "1"
os.environ["PROCESS_LOG"] = "1"
os.environ["START_FROM_STEAM"] = "1"
# Check if running as Steam compatibility tool (STEAM_COMPAT=1)
# In this mode, launch game immediately without GUI
is_steam_compat = os.environ.get("STEAM_COMPAT") == "1"
# Get the PortProton start command
start_sh = get_portproton_start_command()
if start_sh is None:
return
# Handle Steam compatibility mode - launch game directly without GUI
if is_steam_compat:
# In Steam compatibility mode, launch file path is passed as first argument
exe_path = parsed_args.file_or_url if parsed_args.file_or_url else None
if exe_path and is_launch_file(exe_path):
exe_path = normalize_launch_path(exe_path)
logger = get_logger(__name__)
setup_logger(parsed_args.debug_level)
logger.info("Running in Steam compatibility mode, launching: %s", exe_path)
# Launch game via PortProton without GUI
env_vars = os.environ.copy()
cmd = start_sh + [exe_path]
try:
subprocess.run(cmd, env=env_vars)
except Exception as e:
logger.error("Failed to launch game in Steam compatibility mode: %s", e)
sys.exit(1)
sys.exit(0)
else:
# No launch file provided, fall back to GUI mode
is_steam_compat = False
app = QApplication(sys.argv)
app.setWindowIcon(QIcon.fromTheme(__app_id__))
app.setDesktopFileName(__app_id__)
app.setApplicationName(__app_name__)
app.setApplicationVersion(__app_version__)
args = parse_args()
# Setup logger with specified debug level
args = parsed_args
setup_logger(args.debug_level)
# Reinitialize logger after setup to ensure it uses the new configuration
logger = get_logger(__name__)
system_locale = QLocale.system()
qt_translator = QTranslator()
translations_path = QLibraryInfo.path(QLibraryInfo.LibraryPath.TranslationsPath)
if qt_translator.load(system_locale, "qtbase", "_", translations_path):
app.installTranslator(qt_translator)
fullscreen = args.fullscreen or read_fullscreen_config()
ipc_message = "show:fullscreen" if fullscreen else "show"
if args.file_or_url and is_launch_file(args.file_or_url):
ipc_message = f"open:{normalize_launch_path(args.file_or_url)}"
# --- Single-instance logic ---
server_name = __app_id__
socket = QLocalSocket()
socket.connectToServer(server_name)
if socket.waitForConnected(200):
# Second instance — send command to the first one
socket.write(ipc_message.encode("utf-8"))
socket.flush()
socket.waitForBytesWritten(500)
socket.disconnectFromServer()
logger.info("Restored existing instance from tray")
return
# Remove old socket if it exists
QLocalServer.removeServer(server_name)
local_server = QLocalServer()
if not local_server.listen(server_name):
logger.warning(f"Failed to start local server: {local_server.errorString()}")
return
# Check if we have a portproton:// URL or launch file to handle
if args.file_or_url:
if is_portproton_url(args.file_or_url):
# Parse the portproton:// URL to get the full download URL
download_url = parse_portproton_url(args.file_or_url)
if download_url:
# Create PortProtonAPI instance to handle the download
downloader = Downloader(max_workers=4)
api = PortProtonAPI(downloader=downloader)
# Perform the PPDB download - user will select the .exe file via FileExplorer
success = api.download_ppdb_from_url(download_url)
if success:
logger.info(f"Successfully downloaded PPDB from {download_url}")
else:
logger.error(f"Failed to download PPDB from {download_url}")
# Exit after handling the URL
return
else:
logger.error(f"Failed to parse portproton:// URL: {args.file_or_url}")
return
elif is_launch_file(args.file_or_url):
# Store launch file path for later processing after window is created
exe_path = normalize_launch_path(args.file_or_url)
else:
logger.warning(f"Unknown file or URL format: {args.file_or_url}")
exe_path = None
else:
logger.warning(f"Qt translations for {system_locale.name()} not found in {translations_path}, using english language")
exe_path = None
window = MainWindow(app_name=__app_name__)
# --- Main Window ---
version = get_version()
if args.fullscreen:
logger.info("Launching in fullscreen mode due to --fullscreen flag")
# Parse resolution if provided
window_resolution = None
if args.resolution:
window_resolution = parse_resolution(args.resolution)
if window_resolution is None:
logger.warning(f"Invalid resolution format: {args.resolution}, expected WIDTHxHEIGHT (e.g., 1920x1080)")
window = MainWindow(app_name=__app_name__, version=version, launch_exe=exe_path, resolution=window_resolution, show_system_tab=args.ppqtos)
# Handle launch file if provided
if exe_path:
# Defer the call until after the window is shown
def handle_launch_exe():
window.handle_launch_exe(exe_path)
QTimer.singleShot(0, handle_launch_exe)
# --- Handle incoming connections ---
def handle_new_connection():
conn = local_server.nextPendingConnection()
if not conn:
return
if conn.waitForReadyRead(1000):
data = conn.readAll().data()
msg = bytes(data).decode("utf-8", errors="ignore")
logger.info(f"IPC message received: {msg}")
def restore_window():
try:
if msg.startswith("show") or msg.startswith("open:"):
# Ensure the window is visible and not minimized
window.setWindowState(window.windowState() & ~Qt.WindowState.WindowMinimized)
window.show()
window.raise_()
window.activateWindow()
# Ensure window is in active state for systems with strict focus policies
window.setWindowState(window.windowState() | Qt.WindowState.WindowActive)
if ":fullscreen" in msg:
logger.info("Switching to fullscreen via IPC")
save_fullscreen_config(True)
window.showFullScreen()
else:
if msg.startswith("show"):
logger.info("Switching to normal window via IPC")
save_fullscreen_config(False)
window.showNormal()
if msg.startswith("open:"):
launch_path = msg[5:].strip()
if launch_path and is_launch_file(launch_path):
logger.info("Opening launch file via IPC: %s", launch_path)
window.handle_launch_exe(launch_path)
else:
logger.warning("Invalid launch file via IPC: %s", launch_path)
except Exception as e:
logger.warning(f"Failed to restore window: {e}")
# Execute in the main thread
QTimer.singleShot(0, restore_window)
conn.disconnectFromServer()
local_server.newConnection.connect(handle_new_connection)
# --- Initial fullscreen state ---
launch_fullscreen = args.fullscreen or read_fullscreen_config()
launch_minimized = (
read_start_minimized()
and not args.fullscreen
and window_resolution is None
and exe_path is None
)
if launch_minimized:
logger.info("Launching in tray (config)")
window.hide()
elif launch_fullscreen:
logger.info(
f"Launching in fullscreen mode ({'--fullscreen' if args.fullscreen else 'config'})"
)
save_fullscreen_config(True)
window.showFullScreen()
elif window_resolution:
logger.info(f"Launching with resolution: {window_resolution[0]}x{window_resolution[1]}")
window.resize(window_resolution[0], window_resolution[1])
window.showNormal()
else:
logger.info("Launching in normal mode")
save_fullscreen_config(False)
window.showNormal()
# Execute the initial PortProton command after the UI is set up
class InitialCommandWorker(QThread):
"""Worker thread to run initial PortProton command without blocking UI."""
finished = Signal()
def __init__(self, start_cmd: list[str]):
super().__init__()
self.start_cmd = start_cmd
def run(self):
try:
# Get screen information before running the initial command
# Hack: avoid script from dependency on xorg-xrandr
from portprotonqt.config_utils import get_portproton_location
portproton_path = get_portproton_location()
if portproton_path:
screen_resolution, screen_primary = get_screen_info(portproton_path)
# Store screen information in user.conf
if screen_resolution and '=' in screen_resolution:
var_name, var_value = screen_resolution.split('=', 1)
set_user_conf_setting(var_name, var_value)
if screen_primary and '=' in screen_primary:
var_name, var_value = screen_primary.split('=', 1)
set_user_conf_setting(var_name, var_value)
# Run the initial PortProton command
subprocess.run(self.start_cmd + ["cli", "--initial"], timeout=10)
except subprocess.TimeoutExpired:
logger.warning("Initial PortProton command timed out")
except Exception as e:
logger.error(f"Error running initial PortProton command: {e}")
finally:
self.finished.emit()
if start_sh:
worker = InitialCommandWorker(start_sh)
worker.start()
else:
logger.warning("PortProton start command not available, skipping initial command")
# --- Cleanup ---
def cleanup_on_exit():
nonlocal window
app.aboutToQuit.disconnect()
if window:
window.close()
app.quit()
try:
local_server.close()
QLocalServer.removeServer(server_name)
if window:
window.close()
except Exception as e:
logger.warning(f"Cleanup error: {e}")
app.aboutToQuit.connect(cleanup_on_exit)
window.show()
sys.exit(app.exec())
if __name__ == '__main__':
if __name__ == "__main__":
main()
+327 -1
View File
@@ -1,4 +1,10 @@
import argparse
import os
import re
import shutil
from pathlib import Path
from portprotonqt.steam_api import get_steam_home
def parse_args():
@@ -11,10 +17,330 @@ def parse_args():
action="store_true",
help="Launch the application in fullscreen mode and save this setting"
)
parser.add_argument(
"--resolution",
type=str,
metavar="WIDTHxHEIGHT",
help="Launch the application with a specific resolution (e.g., 1920x1080)"
)
parser.add_argument(
"--debug-level",
choices=['ALL', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
default='NOTSET',
help="Установить уровень логирования (ALL для всех сообщений, по умолчанию: без логов)"
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",
help="Add PortProtonQt as a Steam compatibility tool if not already installed"
)
parser.add_argument(
"--reinstall-steam-compat-tool",
action="store_true",
help="Reinstall PortProtonQt Steam compatibility tool in user Steam directory"
)
parser.add_argument(
"--remove-steam-compat-tool",
action="store_true",
help="Remove PortProtonQt Steam compatibility tool from user Steam directory"
)
parser.add_argument(
"--ppqtos",
action="store_true",
help="Show the system tab in the application"
)
# Add positional argument to accept launch files or portproton:// URLs
parser.add_argument(
'file_or_url',
nargs='?',
help="Launch file path (.exe/.iso) or portproton:// URL"
)
return parser.parse_args()
def add_steam_compat_tool(force_install: bool = False) -> bool:
"""
Add PortProtonQt as a Steam compatibility tool.
Creates the following files in Steam's compatibilitytools.d directory:
- compatibilitytool.vdf
- toolmanifest.vdf
- portproton (launch script)
Returns:
True if successful, False otherwise
"""
steam_home = get_steam_home()
if not steam_home:
print("Steam directory not found")
return False
compat_tools_dir = steam_home / "compatibilitytools.d" / "PortProtonQt"
system_compat_dir = Path("/usr/share/steam/compatibilitytools.d/PortProtonQt")
# Check if already installed in user or system directory
if compat_tools_dir.exists():
if not force_install:
print("PortProtonQt is already installed as a Steam compatibility tool")
return True
shutil.rmtree(compat_tools_dir)
if system_compat_dir.exists() and not force_install:
print("PortProtonQt is already installed as a Steam compatibility tool (system-wide)")
return True
# Create directory structure
compat_tools_dir.mkdir(parents=True, exist_ok=True)
# Create compatibilitytool.vdf
compatibilitytool_vdf = compat_tools_dir / "compatibilitytool.vdf"
compatibilitytool_vdf.write_text('''"compatibilitytools"
{
"compat_tools"
{
"PortProtonQt"
{
"install_path" "."
"display_name" "PortProtonQt"
"from_oslist" "windows"
"to_oslist" "linux"
"Priority" "75"
}
}
}
''')
# Create toolmanifest.vdf
toolmanifest_vdf = compat_tools_dir / "toolmanifest.vdf"
toolmanifest_vdf.write_text('''"manifest"
{
"commandline" "/portproton"
}
''')
# Create portproton launch script
portproton_script = compat_tools_dir / "portproton"
portproton_script.write_text('''#!/usr/bin/env bash
# Remove Steam Runtime libraries
unset LD_LIBRARY_PATH
export STEAM_COMPAT=1
exe_name="$(basename "$1")"
exe_dir="$(dirname "$1")"
# Ignore specific executables
if [[ "$exe_name" == "iscriptevaluator.exe" ]] || \\
[[ "$exe_name" == "d3ddriverquery64.exe" ]]; then
exit 0
fi
# Copy PPDB file from steam_scripts to exe directory if it exists
# Steam passes the appid via SteamAppId environment variable
if [[ -n "$SteamAppId" ]]; then
# Get PortProton directory from config file or Flatpak default
portproton_dir=""
config_file="$HOME/.config/PortProton.conf"
if [[ -f "$config_file" ]]; then
portproton_dir="$(cat "$config_file" | tr -d '\\n')"
fi
if [[ -z "$portproton_dir" ]] || [[ ! -d "$portproton_dir" ]]; then
# Fallback to Flatpak default
portproton_dir="$HOME/.var/app/ru.linux_gaming.PortProton"
fi
ppdb_source="$portproton_dir/steam_scripts/${SteamAppId}.exe.ppdb"
ppdb_dest="$exe_dir/${exe_name}.ppdb"
if [[ -f "$ppdb_source" ]]; then
cp "$ppdb_source" "$ppdb_dest"
echo "Copied PPDB from $ppdb_source to $ppdb_dest"
fi
fi
# Activate virtual environment if available
if [[ -n "$PPQT_VENV_PATH" ]]; then
cd "$PPQT_VENV_PATH" || exit 1
source .venv/bin/activate || exit 1
fi
# Use AppImage if specified, otherwise use portprotonqt from PATH
if [[ -n "$PPQT_BIN_PATH" ]]; then
"$PPQT_BIN_PATH" --debug-level INFO "$@"
else
portprotonqt --debug-level INFO "$@"
fi
''')
# Make script executable
os.chmod(portproton_script, 0o755)
print("PortProtonQt has been added as a Steam compatibility tool")
print(f"Installed to: {compat_tools_dir}")
print("Restart Steam to use the new compatibility tool")
return True
def reinstall_steam_compat_tool() -> bool:
"""Reinstall PortProtonQt as a Steam compatibility tool."""
steam_home = get_steam_home()
if not steam_home:
print("Steam directory not found")
return False
compat_tools_dir = steam_home / "compatibilitytools.d" / "PortProtonQt"
if compat_tools_dir.exists():
try:
shutil.rmtree(compat_tools_dir)
except OSError as e:
print(f"Failed to remove existing compatibility tool: {e}")
return False
return add_steam_compat_tool(force_install=True)
def remove_steam_compat_tool() -> bool:
"""Remove PortProtonQt Steam compatibility tool from user Steam directory."""
steam_home = get_steam_home()
if not steam_home:
print("Steam directory not found")
return False
compat_tools_dir = steam_home / "compatibilitytools.d" / "PortProtonQt"
if not compat_tools_dir.exists():
print("PortProtonQt Steam compatibility tool is not installed in user directory")
return True
try:
shutil.rmtree(compat_tools_dir)
except OSError as e:
print(f"Failed to remove compatibility tool: {e}")
return False
print("PortProtonQt Steam compatibility tool removed")
print("Restart Steam to apply changes")
return True
def is_steam_compat_tool_installed() -> bool:
"""Check if PortProtonQt is installed as Steam compatibility tool."""
steam_home = get_steam_home()
if not steam_home:
return False
compat_tools_dir = steam_home / "compatibilitytools.d" / "PortProtonQt"
system_compat_dir = Path("/usr/share/steam/compatibilitytools.d/PortProtonQt")
return compat_tools_dir.exists() or system_compat_dir.exists()
def is_portproton_url(url: str) -> bool:
"""Check if the given URL is a portproton:// URL.
Args:
url: The URL to check
Returns:
True if it's a portproton:// URL, False otherwise
"""
return url.lower().startswith('portproton://')
def is_exe_file(path: str) -> bool:
"""Check if the given path is an exe file.
Args:
path: The path to check
Returns:
True if it's an exe file, False otherwise
"""
normalized_path = normalize_launch_path(path)
return normalized_path.lower().endswith('.exe') and os.path.isfile(normalized_path)
def normalize_launch_path(path: str) -> str:
"""Normalize path and convert file:// URI to local filesystem path."""
if path.lower().startswith("file://"):
path = path[7:]
path = path.replace("%20", " ")
return os.path.abspath(os.path.expanduser(path))
def is_launch_file(path: str) -> bool:
"""Check if the given path is a supported launch file (.exe or .iso)."""
normalized_path = normalize_launch_path(path)
return normalized_path.lower().endswith(('.exe', '.iso')) and os.path.isfile(normalized_path)
def parse_portproton_url(url: str) -> str | None:
"""Parse a portproton:// URL to extract the full download URL.
Expected format: portproton://https//ppdb.linux-gaming.ru/api/games/130127/ppdb/download
Args:
url: The portproton:// URL to parse
Returns:
The full download URL if parsing is successful, None otherwise
"""
# Remove the portproton:// prefix
if not url.lower().startswith('portproton://'):
return None
# Extract the actual URL part after portproton://
actual_url = url[13:] # Length of 'portproton://'
# Check if the URL starts with 'https//' (without colon) and fix it
if actual_url.startswith('https//'):
# Replace 'https//' with 'https://'
corrected_url = 'https://' + actual_url[7:] # Remove 'https//' (7 chars) and add '://'
elif actual_url.startswith('http//'):
# Replace 'http//' with 'http://'
corrected_url = 'http://' + actual_url[6:] # Remove 'http//' (6 chars) and add '://'
elif not actual_url.startswith(('http://', 'https://')):
# Add the protocol if it's missing
corrected_url = 'https://' + actual_url
else:
corrected_url = actual_url
return corrected_url
def parse_resolution(resolution: str) -> tuple[int, int] | None:
"""Parse a resolution string in the format WIDTHxHEIGHT.
Args:
resolution: Resolution string (e.g., "1920x1080")
Returns:
Tuple of (width, height) if valid, None otherwise
"""
try:
# Match pattern like "1920x1080"
match = re.match(r'^(\d+)x(\d+)$', resolution, re.IGNORECASE)
if not match:
return None
width = int(match.group(1))
height = int(match.group(2))
# Validate reasonable resolution bounds
if width < 320 or height < 200:
return None
if width > 7680 or height > 4320:
return None
return (width, height)
except (ValueError, AttributeError):
return None
+40
View File
@@ -0,0 +1,40 @@
"""Configuration hierarchy for PortProtonQt."""
from portprotonqt.config.base import (
BaseConfig,
CONFIG_FILE,
PORTPROTON_CONFIG_FILE,
CONFIG_DIR,
THEMES_DIRS,
CACHE_DIR,
)
from portprotonqt.config.ui import UIConfig
from portprotonqt.config.game import GameConfig
from portprotonqt.config.cache import CacheConfig, CacheManager
from portprotonqt.config.gamepad import GamepadConfig
from portprotonqt.config.proxy import ProxyConfig
from portprotonqt.config.display import DisplayConfig
from portprotonqt.config.window import MainWindowConfig
from portprotonqt.config.favorites import FavoritesConfig, FavoritesFoldersConfig
from portprotonqt.config.portproton import PortProtonConfig
from portprotonqt.config.validators import ValidationError
__all__ = [
"BaseConfig",
"UIConfig",
"GameConfig",
"CacheConfig",
"CacheManager",
"GamepadConfig",
"ProxyConfig",
"DisplayConfig",
"MainWindowConfig",
"FavoritesConfig",
"FavoritesFoldersConfig",
"PortProtonConfig",
"CONFIG_FILE",
"PORTPROTON_CONFIG_FILE",
"CONFIG_DIR",
"THEMES_DIRS",
"CACHE_DIR",
"ValidationError",
]
+134
View File
@@ -0,0 +1,134 @@
"""Base configuration class for PortProtonQt."""
import os
import configparser
from pathlib import Path
from portprotonqt.logger import get_logger
from portprotonqt.config.validators import validate_string, validate_int, validate_bool, ValidationError
logger = get_logger(__name__)
# Export configparser for use in other modules
__all__ = ["configparser"]
# Configuration file paths
CONFIG_DIR = Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config"))
CONFIG_FILE = CONFIG_DIR / "PortProtonQt.conf"
PORTPROTON_CONFIG_FILE = CONFIG_DIR / "PortProton.conf"
# Theme directories
XDG_DATA_HOME = Path(os.getenv("XDG_DATA_HOME", Path.home() / ".local" / "share"))
THEMES_DIRS = [
XDG_DATA_HOME / "PortProtonQt" / "themes",
Path(__file__).parent.parent / "themes",
]
# Cache paths
CACHE_DIR = Path(os.getenv("XDG_CACHE_HOME", Path.home() / ".cache")) / "PortProtonQt"
# Module-level cache storage
_config_cache: dict[str, configparser.ConfigParser] = {}
_config_mtime: dict[str, float] = {}
class BaseConfig:
"""Base configuration class providing common functionality."""
_section: str = ""
def __init__(self, config_file: Path = CONFIG_FILE):
self._config_file = config_file
def _read_config(self) -> configparser.ConfigParser | None:
"""Read configuration file with caching."""
config_path = str(self._config_file)
if not self._config_file.exists():
logger.debug("Configuration file %s not found", config_path)
return None
try:
current_mtime = self._config_file.stat().st_mtime
except OSError:
logger.warning("Failed to get modification time for %s", config_path)
return None
if config_path in _config_cache and config_path in _config_mtime:
if _config_mtime[config_path] == current_mtime:
return _config_cache[config_path]
cp = configparser.ConfigParser()
try:
cp.read(config_path, encoding="utf-8")
_config_cache[config_path] = cp
_config_mtime[config_path] = current_mtime
return cp
except (configparser.DuplicateSectionError, configparser.DuplicateOptionError) as e:
logger.warning("Invalid configuration file format: %s", e)
return None
except Exception as e:
logger.warning("Failed to read configuration file: %s", e)
return None
def _save_config(self, cp: configparser.ConfigParser):
"""Save configuration to file."""
with open(self._config_file, "w", encoding="utf-8") as f:
cp.write(f)
self._invalidate_cache()
def _invalidate_cache(self):
"""Invalidate configuration cache."""
config_path = str(self._config_file)
if config_path in _config_cache:
del _config_cache[config_path]
if config_path in _config_mtime:
del _config_mtime[config_path]
def _get_value(self, option: str, default, value_type: str = "str"):
"""Get a configuration value with type conversion."""
cp = self._read_config()
if cp is None or not cp.has_section(self._section):
return self._save_value(option, default, value_type)
try:
if value_type == "int":
return cp.getint(self._section, option, fallback=default)
elif value_type == "bool":
return cp.getboolean(self._section, option, fallback=default)
else:
return cp.get(self._section, option, fallback=default)
except (ValueError, configparser.Error) as e:
logger.warning("Error reading %s: %s", option, e)
return self._save_value(option, default, value_type)
def _get_str(self, option: str, default: str) -> str:
"""Get a string configuration value."""
return str(self._get_value(option, default, "str"))
def _get_int(self, option: str, default: int) -> int:
"""Get an integer configuration value."""
return int(self._get_value(option, default, "int"))
def _get_bool(self, option: str, default: bool) -> bool:
"""Get a boolean configuration value."""
return bool(self._get_value(option, default, "bool"))
def _save_value(self, option: str, value, value_type: str = "str"):
"""Save a configuration value with validation."""
try:
if value_type == "int":
validate_int(value, option)
elif value_type == "bool":
validate_bool(value, option)
else:
validate_string(value, option)
except ValidationError as e:
logger.warning("Validation failed for %s: %s", option, e)
raise
cp = self._read_config() or configparser.ConfigParser()
if self._section not in cp:
cp[self._section] = {}
cp[self._section][option] = str(value)
self._save_config(cp)
return value
+341
View File
@@ -0,0 +1,341 @@
"""Cache configuration and management."""
import json
import shutil
import threading
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any
import orjson
from portprotonqt.config.base import BaseConfig, CACHE_DIR
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
class CacheConfig(BaseConfig):
"""Cache configuration and management."""
_section = "Cache"
def __init__(self):
super().__init__()
self._cache_dir = CACHE_DIR
def get_cache_dir(self) -> Path:
"""Get cache directory path."""
return self._cache_dir
def clear_cache(self):
"""Clear the cache directory."""
if self._cache_dir.exists():
try:
shutil.rmtree(self._cache_dir)
logger.info("Cache directory deleted: %s", self._cache_dir)
except Exception as e:
logger.warning("Failed to delete cache: %s", e)
self._invalidate_cache()
class CacheManager:
"""Unified cache manager for PortProtonQt with disk and memory caching."""
def __init__(self, cache_dir: Path | None = None, name: str | None = None):
"""Initialize cache manager.
Args:
cache_dir: Cache directory path. Uses default CACHE_DIR if None.
name: Optional name for in-memory cache instance.
"""
self._cache_dir = cache_dir or CACHE_DIR
self._cache_dir.mkdir(parents=True, exist_ok=True)
self._name = name
self._memory_cache: dict[str, Any] = {
'data': None,
'index': None,
'timestamp': 0
}
self._lock = threading.RLock() if threading else None
self._loading = False
self._pending_callbacks: list[Callable] = []
@property
def cache_dir(self) -> Path:
"""Get cache directory path."""
return self._cache_dir
def _get_cache_file_path(self, name: str, extension: str = ".json") -> Path:
"""Get cache file path for given name.
Args:
name: File name (will be sanitized).
extension: File extension (default: .json).
Returns:
Full path to cache file.
"""
safe_name = "".join(c for c in name if c.isalnum() or c in " _-").strip().replace(" ", "_").lower()
return self._cache_dir / f"{safe_name}{extension}"
def load_json(self, name: str) -> Any | None:
"""Load JSON data from disk cache.
Args:
name: Cache file name.
Returns:
Parsed JSON data or None if not found/invalid.
"""
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:
logger.warning("Failed to load cache %s: %s", cache_file, e)
return None
def save_json(self, name: str, data: Any, pretty: bool = False) -> bool:
"""Save JSON data to disk cache.
Args:
name: Cache file name.
data: Data to cache (will be JSON-serialized).
pretty: Use pretty-printing (default: False).
Returns:
True if saved successfully, False otherwise.
"""
cache_file = self._get_cache_file_path(name)
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))
return True
except (OSError, TypeError) as e:
logger.warning("Failed to save cache %s: %s", cache_file, e)
return False
def load_text(self, name: str) -> str | None:
"""Load text data from disk cache.
Args:
name: Cache file name.
Returns:
Text content or None if not found/invalid.
"""
cache_file = self._get_cache_file_path(name)
try:
if cache_file.exists():
with open(cache_file, encoding="utf-8") as f:
return f.read()
except (OSError, UnicodeDecodeError) as e:
logger.warning("Failed to load text cache %s: %s", cache_file, e)
return None
def save_text(self, name: str, content: str) -> bool:
"""Save text data to disk cache.
Args:
name: Cache file name.
content: Text content to cache.
Returns:
True if saved successfully, False otherwise.
"""
cache_file = self._get_cache_file_path(name)
try:
with open(cache_file, "w", encoding="utf-8") as f:
f.write(content)
return True
except (OSError, TypeError) as e:
logger.warning("Failed to save text cache %s: %s", cache_file, e)
return False
def load_binary(self, name: str) -> bytes | None:
"""Load binary data from disk cache.
Args:
name: Cache file name.
Returns:
Binary content or None if not found.
"""
cache_file = self._get_cache_file_path(name, extension=".dat")
try:
if cache_file.exists():
with open(cache_file, "rb") as f:
return f.read()
except OSError as e:
logger.warning("Failed to load binary cache %s: %s", cache_file, e)
return None
def save_binary(self, name: str, content: bytes) -> bool:
"""Save binary data to disk cache.
Args:
name: Cache file name.
content: Binary content to cache.
Returns:
True if saved successfully, False otherwise.
"""
cache_file = self._get_cache_file_path(name, extension=".dat")
try:
with open(cache_file, "wb") as f:
f.write(content)
return True
except OSError as e:
logger.warning("Failed to save binary cache %s: %s", cache_file, e)
return False
def exists(self, name: str, extension: str = ".json") -> bool:
"""Check if cache file exists.
Args:
name: Cache file name.
extension: File extension to check.
Returns:
True if cache file exists, False otherwise.
"""
cache_file = self._get_cache_file_path(name, extension)
return cache_file.exists()
def remove(self, name: str, extension: str = ".json") -> bool:
"""Remove cache file.
Args:
name: Cache file name.
extension: File extension.
Returns:
True if removed successfully, False otherwise.
"""
cache_file = self._get_cache_file_path(name, extension)
try:
if cache_file.exists():
cache_file.unlink()
logger.debug("Cache file removed: %s", cache_file)
return True
except OSError as e:
logger.warning("Failed to remove cache %s: %s", cache_file, e)
return False
def clear(self):
"""Clear all cache files in the cache directory."""
if self._cache_dir.exists():
try:
shutil.rmtree(self._cache_dir)
self._cache_dir.mkdir(parents=True, exist_ok=True)
logger.info("Cache directory cleared: %s", self._cache_dir)
except Exception as e:
logger.warning("Failed to clear cache: %s", e)
def get_file_age(self, name: str, extension: str = ".json") -> float | None:
"""Get age of cache file in seconds.
Args:
name: Cache file name.
extension: File extension.
Returns:
File age in seconds, or None if file doesn't exist.
"""
cache_file = self._get_cache_file_path(name, extension)
try:
if cache_file.exists():
mtime = cache_file.stat().st_mtime
return time.time() - mtime
except OSError:
pass
return None
def is_fresh(self, name: str, max_age: int, extension: str = ".json") -> bool:
"""Check if cache file is fresh (not older than max_age seconds).
Args:
name: Cache file name.
max_age: Maximum age in seconds.
extension: File extension.
Returns:
True if cache is fresh, False otherwise.
"""
age = self.get_file_age(name, extension)
return age is not None and age < max_age
def get_data_and_index_async(
self,
load_func: Callable[[Callable[[list], None]], None],
build_index_func: Callable[[list], dict],
callback: Callable[[tuple[list | None, dict | None]], None],
cache_duration: float = 30 * 24 * 60 * 60
) -> None:
"""Asynchronously load and cache data with index (in-memory caching).
Args:
load_func: Function to load data asynchronously.
build_index_func: Function to build index from data.
callback: Callback with (data, index) tuple.
cache_duration: Cache TTL in seconds.
"""
import threading as threading_module
current_time = time.time()
if self._lock is None:
self._lock = threading_module.RLock()
with self._lock:
if (self._memory_cache['data'] is not None and
self._memory_cache['index'] is not None and
current_time - self._memory_cache['timestamp'] < cache_duration):
callback((self._memory_cache['data'], self._memory_cache['index']))
return
if self._loading:
self._pending_callbacks.append(callback)
return
self._loading = True
self._pending_callbacks = []
def on_data(data: list) -> None:
current_time = time.time()
if self._lock:
with self._lock:
if data:
self._memory_cache['data'] = data
self._memory_cache['index'] = build_index_func(data)
self._memory_cache['timestamp'] = current_time
cached_data = (self._memory_cache['data'], self._memory_cache['index'])
else:
self._memory_cache['data'] = None
self._memory_cache['index'] = None
self._memory_cache['timestamp'] = 0
cached_data = (None, None)
self._loading = False
pending_callbacks = self._pending_callbacks
self._pending_callbacks = []
callback(cached_data)
for pending_callback in pending_callbacks:
pending_callback(cached_data)
load_func(on_data)
def clear_memory_cache(self) -> None:
"""Clear in-memory cache."""
if self._lock:
with self._lock:
self._memory_cache = {
'data': None,
'index': None,
'timestamp': 0
}
if self._name:
logger.info("Cleared %s in-memory cache", self._name)
+54
View File
@@ -0,0 +1,54 @@
"""Display configuration settings."""
from portprotonqt.config.base import BaseConfig
from portprotonqt.config.validators import validate_bool
class DisplayConfig(BaseConfig):
"""Display configuration settings."""
_section = "Display"
def get_fullscreen(self) -> bool:
"""Get fullscreen mode setting."""
return self._get_bool("fullscreen", False)
def set_fullscreen(self, fullscreen: bool):
"""Set fullscreen mode."""
validate_bool(fullscreen, "fullscreen")
self._save_value("fullscreen", fullscreen, "bool")
def get_auto_fullscreen_gamepad(self) -> bool:
"""Get auto-fullscreen for gamepad setting."""
return self._get_bool("auto_fullscreen_gamepad", False)
def set_auto_fullscreen_gamepad(self, auto: bool):
"""Set auto-fullscreen for gamepad."""
validate_bool(auto, "auto_fullscreen_gamepad")
self._save_value("auto_fullscreen_gamepad", auto, "bool")
def get_minimize_to_tray(self) -> bool:
"""Get minimize-to-tray setting."""
return self._get_bool("minimize_to_tray", True)
def set_minimize_to_tray(self, minimize: bool):
"""Set minimize-to-tray setting."""
validate_bool(minimize, "minimize_to_tray")
self._save_value("minimize_to_tray", minimize, "bool")
def get_autostart_enabled(self) -> bool:
"""Get autostart on login setting."""
return self._get_bool("autostart_enabled", False)
def set_autostart_enabled(self, enabled: bool):
"""Set autostart on login setting."""
validate_bool(enabled, "autostart_enabled")
self._save_value("autostart_enabled", enabled, "bool")
def get_start_minimized(self) -> bool:
"""Get start minimized setting."""
return self._get_bool("start_minimized", False)
def set_start_minimized(self, minimized: bool):
"""Set start minimized setting."""
validate_bool(minimized, "start_minimized")
self._save_value("start_minimized", minimized, "bool")
+70
View File
@@ -0,0 +1,70 @@
"""Favorites configuration settings."""
import os
from portprotonqt.config.base import BaseConfig, configparser
from portprotonqt.config.validators import validate_string, validate_path, ValidationError
class FavoritesConfig(BaseConfig):
"""Favorites configuration settings."""
_section = "Favorites"
def get_games(self) -> list[str]:
"""Get list of favorite games."""
cp = self._read_config()
if cp is None or not cp.has_section(self._section):
return []
favs = cp.get(self._section, "games", fallback="").strip()
if favs.startswith('"') and favs.endswith('"'):
favs = favs[1:-1]
return [s.strip() for s in favs.split(",") if s.strip()]
def set_games(self, games: list[str]):
"""Set list of favorite games."""
if not isinstance(games, list):
raise ValidationError("games must be a list", "games", games)
for game in games:
validate_string(game, "game", min_len=1, max_len=255)
cp = self._read_config() or configparser.ConfigParser()
if self._section not in cp:
cp[self._section] = {}
fav_str = ", ".join(games)
cp[self._section]["games"] = f'"{fav_str}"'
self._save_config(cp)
class FavoritesFoldersConfig(BaseConfig):
"""Favorite folders configuration settings."""
_section = "FavoritesFolders"
def get_folders(self) -> list[str]:
"""Get list of favorite folders."""
cp = self._read_config()
if cp is None or not cp.has_section(self._section):
return []
favs = cp.get(self._section, "folders", fallback="").strip()
if favs.startswith('"') and favs.endswith('"'):
favs = favs[1:-1]
return [
os.path.normpath(s.strip())
for s in favs.split(",")
if s.strip() and os.path.isdir(os.path.normpath(s.strip()))
]
def set_folders(self, folders: list[str]):
"""Set list of favorite folders."""
if not isinstance(folders, list):
raise ValidationError("folders must be a list", "folders", folders)
for folder in folders:
validate_path(folder, "folder", must_exist=True)
cp = self._read_config() or configparser.ConfigParser()
if self._section not in cp:
cp[self._section] = {}
fav_str = ", ".join([os.path.normpath(f) for f in folders])
cp[self._section]["folders"] = f'"{fav_str}"'
self._save_config(cp)
+27
View File
@@ -0,0 +1,27 @@
"""Game-related configuration settings."""
from portprotonqt.config.base import BaseConfig
from portprotonqt.config.validators import validate_string
class GameConfig(BaseConfig):
"""Game-related configuration settings."""
_section = "Games"
def get_sort_method(self) -> str:
"""Get game sort method."""
return self._get_str("sort_method", "last_launch")
def set_sort_method(self, method: str):
"""Set game sort method."""
validate_string(method, "sort_method", min_len=1, max_len=50)
self._save_value("sort_method", method, "str")
def get_display_filter(self) -> str:
"""Get game display filter."""
return self._get_str("display_filter", "all")
def set_display_filter(self, filter_value: str):
"""Set game display filter."""
validate_string(filter_value, "display_filter", min_len=1, max_len=50)
self._save_value("display_filter", filter_value, "str")
+27
View File
@@ -0,0 +1,27 @@
"""Gamepad configuration settings."""
from portprotonqt.config.base import BaseConfig
from portprotonqt.config.validators import validate_bool, validate_string
class GamepadConfig(BaseConfig):
"""Gamepad configuration settings."""
_section = "Gamepad"
def get_rumble_enabled(self) -> bool:
"""Get gamepad rumble setting."""
return self._get_bool("rumble_enabled", False)
def set_rumble_enabled(self, enabled: bool):
"""Set gamepad rumble setting."""
validate_bool(enabled, "rumble_enabled")
self._save_value("rumble_enabled", enabled, "bool")
def get_type(self) -> str:
"""Get gamepad type."""
return self._get_str("type", "xbox")
def set_type(self, gpad_type: str):
"""Set gamepad type."""
validate_string(gpad_type, "type", min_len=1, max_len=20)
self._save_value("type", gpad_type, "str")
+55
View File
@@ -0,0 +1,55 @@
"""PortProton location configuration."""
import os
from pathlib import Path
from portprotonqt.config.base import BaseConfig, PORTPROTON_CONFIG_FILE
from portprotonqt.config.validators import validate_path
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
class PortProtonConfig(BaseConfig):
"""PortProton location configuration."""
_section = "PortProton"
_portproton_location: str | None = None
def __init__(self):
super().__init__()
self._config_file = PORTPROTON_CONFIG_FILE
def get_location(self) -> str | None:
"""Get PortProton directory location."""
if self._portproton_location is not None:
return self._portproton_location
location = None
if self._config_file.exists():
try:
location = self._config_file.read_text(encoding="utf-8").strip()
if location and os.path.isdir(location):
self._portproton_location = location
logger.info("PortProton path from configuration: %s", location)
return self._portproton_location
logger.warning("Invalid PortProton path in configuration: %s", location)
except (OSError, PermissionError) as e:
logger.warning("Failed to read PortProton configuration file: %s", e)
except Exception as e:
logger.warning("Unexpected error reading PortProton configuration file: %s", e)
default_flatpak_dir = Path.home() / ".var" / "app" / "ru.linux_gaming.PortProton"
if default_flatpak_dir.is_dir():
self._portproton_location = str(default_flatpak_dir)
logger.info("Using Flatpak PortProton directory: %s", default_flatpak_dir)
return self._portproton_location
logger.warning("PortProton configuration and Flatpak directory not found")
return None
def set_location(self, location: str):
"""Set PortProton directory location."""
validate_path(location, "portproton_location", must_exist=True)
self._config_file.write_text(location, encoding="utf-8")
self._portproton_location = location
logger.info("PortProton location set to: %s", location)
+53
View File
@@ -0,0 +1,53 @@
"""Proxy configuration settings."""
from portprotonqt.config.base import BaseConfig, configparser
from portprotonqt.config.validators import validate_url, validate_string
class ProxyConfig(BaseConfig):
"""Proxy configuration settings."""
_section = "Proxy"
def ensure_section(self):
"""Ensure Proxy section exists."""
cp = self._read_config() or configparser.ConfigParser()
if self._section not in cp:
cp.add_section(self._section)
cp[self._section]["proxy_url"] = ""
cp[self._section]["proxy_user"] = ""
cp[self._section]["proxy_password"] = ""
self._save_config(cp)
def get_proxy(self) -> dict[str, str]:
"""Get proxy settings as dict."""
self.ensure_section()
cp = self._read_config()
if cp is None:
return {}
proxy_url = cp.get(self._section, "proxy_url", fallback="").strip()
if not proxy_url:
return {}
proxy_user = cp.get(self._section, "proxy_user", fallback="").strip()
proxy_password = cp.get(self._section, "proxy_password", fallback="").strip()
if "://" in proxy_url and "@" not in proxy_url and proxy_user and proxy_password:
protocol, rest = proxy_url.split("://", 1)
proxy_url = f"{protocol}://{proxy_user}:{proxy_password}@{rest}"
return {"http": proxy_url, "https": proxy_url}
def set_proxy(self, proxy_url: str = "", proxy_user: str = "", proxy_password: str = ""):
"""Set proxy settings."""
validate_url(proxy_url, "proxy_url", allow_empty=True)
validate_string(proxy_user, "proxy_user", max_len=100)
validate_string(proxy_password, "proxy_password", max_len=100)
cp = self._read_config() or configparser.ConfigParser()
if self._section not in cp:
cp[self._section] = {}
cp[self._section]["proxy_url"] = proxy_url
cp[self._section]["proxy_user"] = proxy_user
cp[self._section]["proxy_password"] = proxy_password
self._save_config(cp)
+75
View File
@@ -0,0 +1,75 @@
"""UI configuration settings."""
from portprotonqt.config.base import BaseConfig, configparser
from portprotonqt.config.validators import validate_string, validate_int, validate_bool
class UIConfig(BaseConfig):
"""UI configuration settings."""
_section = "Appearance"
def get_theme(self) -> str:
"""Get the current theme name."""
return self._get_str("theme", "standart")
def set_theme(self, theme_name: str):
"""Set the theme name."""
validate_string(theme_name, "theme", min_len=1, max_len=50)
self._save_value("theme", theme_name, "str")
def get_time_detail_level(self) -> str:
"""Get time detail level ('detailed' or 'simple')."""
cp = self._read_config()
if cp is None or not cp.has_section("Time"):
return self._save_time_detail("detailed")
return cp.get("Time", "detail_level", fallback="detailed").lower()
def _save_time_detail(self, detail_level: str) -> str:
"""Save time detail level."""
validate_string(detail_level, "detail_level", min_len=1, max_len=20)
cp = self._read_config() or configparser.ConfigParser()
if "Time" not in cp:
cp["Time"] = {}
cp["Time"]["detail_level"] = detail_level
self._save_config(cp)
return detail_level
def set_time_detail_level(self, detail_level: str):
"""Set time detail level."""
self._save_time_detail(detail_level)
def get_card_width(self) -> int:
"""Get card width for game cards."""
return self._get_int("card_width", 250)
def set_card_width(self, width: int):
"""Set card width."""
validate_int(width, "card_width", min_val=100, max_val=1000)
self._save_value("card_width", width, "int")
def get_auto_card_width(self) -> int:
"""Get card width for auto-install."""
return self._get_int("auto_card_width", 250)
def set_auto_card_width(self, width: int):
"""Set card width for auto-install."""
validate_int(width, "auto_card_width", min_val=100, max_val=1000)
self._save_value("auto_card_width", width, "int")
def get_hide_autoinstall_tab(self) -> bool:
"""Get hide auto-install tab setting."""
return self._get_bool("hide_autoinstall_tab", False)
def set_hide_autoinstall_tab(self, hide: bool):
"""Set hide auto-install tab setting."""
validate_bool(hide, "hide_autoinstall_tab")
self._save_value("hide_autoinstall_tab", hide, "bool")
def get_badge_view_mode(self) -> str:
"""Get badge view mode ('detailed' or 'compact')."""
return self._get_str("badge_view_mode", "detailed")
def set_badge_view_mode(self, mode: str):
"""Set badge view mode."""
validate_string(mode, "badge_view_mode", min_len=1, max_len=20)
self._save_value("badge_view_mode", mode, "str")
+68
View File
@@ -0,0 +1,68 @@
"""Configuration exceptions and validation utilities."""
import os
class ConfigError(Exception):
"""Base exception for configuration errors."""
class ValidationError(ConfigError):
"""Raised when configuration value validation fails."""
def __init__(self, message: str, option: str, value):
super().__init__(message)
self.option = option
self.value = value
def validate_string(value: str, option: str, min_len: int = 0, max_len: int = 255) -> str:
"""Validate string configuration value."""
if not isinstance(value, str):
raise ValidationError(f"{option} must be a string", option, value)
if len(value) < min_len:
raise ValidationError(f"{option} must be at least {min_len} characters", option, value)
if len(value) > max_len:
raise ValidationError(f"{option} must not exceed {max_len} characters", option, value)
return value
def validate_int(value: int, option: str, min_val: int | None = None, max_val: int | None = None) -> int:
"""Validate integer configuration value."""
if not isinstance(value, int):
raise ValidationError(f"{option} must be an integer", option, value)
if min_val is not None and value < min_val:
raise ValidationError(f"{option} must be at least {min_val}", option, value)
if max_val is not None and value > max_val:
raise ValidationError(f"{option} must not exceed {max_val}", option, value)
return value
def validate_bool(value: bool, option: str) -> bool:
"""Validate boolean configuration value."""
if not isinstance(value, bool):
raise ValidationError(f"{option} must be a boolean", option, value)
return value
def validate_path(value: str, option: str, must_exist: bool = False) -> str:
"""Validate path configuration value."""
if not isinstance(value, str):
raise ValidationError(f"{option} must be a string path", option, value)
if not value:
raise ValidationError(f"{option} cannot be empty", option, value)
if must_exist and not os.path.exists(value):
raise ValidationError(f"{option} path does not exist: {value}", option, value)
return value
def validate_url(value: str, option: str, allow_empty: bool = True) -> str:
"""Validate URL configuration value."""
if allow_empty and not value:
return value
if not isinstance(value, str):
raise ValidationError(f"{option} must be a string URL", option, value)
if not value:
raise ValidationError(f"{option} cannot be empty", option, value)
if "://" not in value and value:
raise ValidationError(f"{option} must be a valid URL with protocol", option, value)
return value
+30
View File
@@ -0,0 +1,30 @@
"""Main window configuration settings."""
from portprotonqt.config.base import BaseConfig, configparser
from portprotonqt.config.validators import validate_int
class MainWindowConfig(BaseConfig):
"""Main window configuration settings."""
_section = "MainWindow"
def get_geometry(self) -> tuple[int, int]:
"""Get window width and height."""
cp = self._read_config()
if cp is None or not cp.has_section(self._section):
return (0, 0)
width = cp.getint(self._section, "width", fallback=0)
height = cp.getint(self._section, "height", fallback=0)
return (width, height)
def set_geometry(self, width: int, height: int):
"""Set window width and height."""
validate_int(width, "width", min_val=0, max_val=7680)
validate_int(height, "height", min_val=0, max_val=4320)
cp = self._read_config() or configparser.ConfigParser()
if self._section not in cp:
cp[self._section] = {}
cp[self._section]["width"] = str(width)
cp[self._section]["height"] = str(height)
self._save_config(cp)
+583 -361
View File
@@ -1,410 +1,632 @@
"""Backward compatibility module for config_utils.
This module provides legacy function names that wrap the new config classes.
New code should use portprotonqt.config directly.
"""
import os
import configparser
import shutil
import subprocess
from pathlib import Path
from portprotonqt.logger import get_logger
from portprotonqt.localization import _
from portprotonqt.config import (
UIConfig,
GameConfig,
CacheConfig,
GamepadConfig,
ProxyConfig,
DisplayConfig,
MainWindowConfig,
FavoritesConfig,
FavoritesFoldersConfig,
PortProtonConfig,
CONFIG_FILE,
THEMES_DIRS,
)
logger = get_logger(__name__)
AUTOSTART_DIR = Path(os.getenv("XDG_CONFIG_HOME", Path.home() / ".config")) / "autostart"
AUTOSTART_FILE = AUTOSTART_DIR / "ru.linux_gaming.PortProtonQt.desktop"
_portproton_location = None
# Legacy module-level instances for backward compatibility
_ui_config = None
_game_config = None
_cache_config = None
_gamepad_config = None
_proxy_config = None
_display_config = None
_window_config = None
_favorites_config = None
_favorites_folders_config = None
_portproton_config = None
_portproton_start_sh = None
# Paths to configuration files
CONFIG_FILE = os.path.join(
os.getenv("XDG_CONFIG_HOME", os.path.join(os.path.expanduser("~"), ".config")),
"PortProtonQt.conf"
)
PORTPROTON_CONFIG_FILE = os.path.join(
os.getenv("XDG_CONFIG_HOME", os.path.join(os.path.expanduser("~"), ".config")),
"PortProton.conf"
)
def _get_ui_config() -> UIConfig:
"""Get or create UIConfig instance."""
global _ui_config
if _ui_config is None:
_ui_config = UIConfig()
return _ui_config
# Paths to theme directories
xdg_data_home = os.getenv("XDG_DATA_HOME", os.path.join(os.path.expanduser("~"), ".local", "share"))
THEMES_DIRS = [
os.path.join(xdg_data_home, "PortProtonQt", "themes"),
os.path.join(os.path.dirname(os.path.abspath(__file__)), "themes")
]
def read_config_safely(config_file: str) -> configparser.ConfigParser | None:
"""Safely reads a configuration file and returns a ConfigParser object or None if reading fails."""
cp = configparser.ConfigParser()
if not os.path.exists(config_file):
logger.debug(f"Configuration file {config_file} not found")
return None
def _get_game_config() -> GameConfig:
"""Get or create GameConfig instance."""
global _game_config
if _game_config is None:
_game_config = GameConfig()
return _game_config
def _get_cache_config() -> CacheConfig:
"""Get or create CacheConfig instance."""
global _cache_config
if _cache_config is None:
_cache_config = CacheConfig()
return _cache_config
def _get_gamepad_config() -> GamepadConfig:
"""Get or create GamepadConfig instance."""
global _gamepad_config
if _gamepad_config is None:
_gamepad_config = GamepadConfig()
return _gamepad_config
def _get_proxy_config() -> ProxyConfig:
"""Get or create ProxyConfig instance."""
global _proxy_config
if _proxy_config is None:
_proxy_config = ProxyConfig()
return _proxy_config
def _get_display_config() -> DisplayConfig:
"""Get or create DisplayConfig instance."""
global _display_config
if _display_config is None:
_display_config = DisplayConfig()
return _display_config
def _get_window_config() -> MainWindowConfig:
"""Get or create MainWindowConfig instance."""
global _window_config
if _window_config is None:
_window_config = MainWindowConfig()
return _window_config
def _get_favorites_config() -> FavoritesConfig:
"""Get or create FavoritesConfig instance."""
global _favorites_config
if _favorites_config is None:
_favorites_config = FavoritesConfig()
return _favorites_config
def _get_favorites_folders_config() -> FavoritesFoldersConfig:
"""Get or create FavoritesFoldersConfig instance."""
global _favorites_folders_config
if _favorites_folders_config is None:
_favorites_folders_config = FavoritesFoldersConfig()
return _favorites_folders_config
def _get_portproton_config() -> PortProtonConfig:
"""Get or create PortProtonConfig instance."""
global _portproton_config
if _portproton_config is None:
_portproton_config = PortProtonConfig()
return _portproton_config
# Legacy functions for theme/appearance settings
def read_theme_from_config() -> str:
"""Reads the theme from the [Appearance] section."""
return _get_ui_config().get_theme()
def save_theme_to_config(theme_name: str):
"""Saves the selected theme name to the [Appearance] section."""
_get_ui_config().set_theme(theme_name)
def read_time_config() -> str:
"""Reads time settings from the [Time] section."""
return _get_ui_config().get_time_detail_level()
def save_time_config(detail_level: str):
"""Saves the time detail level to the [Time] section."""
_get_ui_config().set_time_detail_level(detail_level)
def read_card_size() -> int:
"""Reads the card size (width) from the [Cards] section."""
return _get_ui_config().get_card_width()
def save_card_size(card_width: int):
"""Saves the card size (width) to the [Cards] section."""
_get_ui_config().set_card_width(card_width)
def read_auto_card_size() -> int:
"""Reads the card size (width) for Auto Install."""
return _get_ui_config().get_auto_card_width()
def save_auto_card_size(card_width: int):
"""Saves the card size (width) for Auto Install."""
_get_ui_config().set_auto_card_width(card_width)
def read_hide_autoinstall_tab() -> bool:
"""Reads the hide auto-install tab setting."""
return _get_ui_config().get_hide_autoinstall_tab()
def save_hide_autoinstall_tab(hide_autoinstall_tab: bool):
"""Saves the hide auto-install tab setting."""
_get_ui_config().set_hide_autoinstall_tab(hide_autoinstall_tab)
def read_badge_view_mode() -> str:
"""Reads badge view mode from the [Appearance] section."""
mode = _get_ui_config().get_badge_view_mode()
return mode if mode in ("detailed", "compact", "hidden") else "detailed"
def save_badge_view_mode(mode: str):
"""Saves badge view mode to the [Appearance] section."""
_get_ui_config().set_badge_view_mode(mode)
def load_theme_metainfo(theme_name: str) -> dict:
"""Loads theme metadata from metainfo.ini."""
from portprotonqt.localization import get_theme_translations
meta = {}
for themes_dir in THEMES_DIRS:
theme_folder = os.path.join(themes_dir, theme_name)
metainfo_file = os.path.join(theme_folder, "metainfo.ini")
if os.path.exists(metainfo_file):
theme_translations = get_theme_translations(metainfo_file)
cp = configparser.ConfigParser()
cp.read(metainfo_file, encoding="utf-8")
if "Metainfo" in cp:
meta["author"] = cp.get("Metainfo", "author", fallback="Unknown")
meta["author_link"] = cp.get("Metainfo", "author_link", fallback="")
meta["name"] = theme_translations.get("name", theme_name)
meta["description"] = theme_translations.get("description", "")
break
return meta
# Legacy functions for game settings
def read_sort_method() -> str:
"""Reads the sort method from the [Games] section."""
return _get_game_config().get_sort_method()
def save_sort_method(sort_method: str):
"""Saves the sort method to the [Games] section."""
_get_game_config().set_sort_method(sort_method)
def read_display_filter() -> str:
"""Reads the display_filter parameter from the [Games] section."""
return _get_game_config().get_display_filter()
def save_display_filter(filter_value: str):
"""Saves the display_filter parameter to the [Games] section."""
_get_game_config().set_display_filter(filter_value)
# Legacy functions for favorites
def read_favorites() -> list[str]:
"""Reads the list of favorite games."""
return _get_favorites_config().get_games()
def save_favorites(favorites: list[str]):
"""Saves the list of favorite games."""
_get_favorites_config().set_games(favorites)
def read_favorite_folders() -> list[str]:
"""Reads the list of favorite folders."""
return _get_favorites_folders_config().get_folders()
def save_favorite_folders(folders: list[str]):
"""Saves the list of favorite folders."""
_get_favorites_folders_config().set_folders(folders)
# Legacy functions for gamepad settings
def read_rumble_config() -> bool:
"""Reads the gamepad rumble setting."""
return _get_gamepad_config().get_rumble_enabled()
def save_rumble_config(rumble_enabled: bool):
"""Saves the gamepad rumble setting."""
_get_gamepad_config().set_rumble_enabled(rumble_enabled)
def read_gamepad_type() -> str:
"""Reads the gamepad type."""
return _get_gamepad_config().get_type()
def save_gamepad_type(gpad_type: str):
"""Saves the gamepad type."""
_get_gamepad_config().set_type(gpad_type)
# Legacy functions for proxy settings
def read_proxy_config() -> dict[str, str]:
"""Reads proxy settings."""
return _get_proxy_config().get_proxy()
def save_proxy_config(proxy_url: str = "", proxy_user: str = "", proxy_password: str = ""):
"""Saves proxy settings."""
_get_proxy_config().set_proxy(proxy_url, proxy_user, proxy_password)
def ensure_default_proxy_config():
"""Ensures the [Proxy] section exists."""
_get_proxy_config().ensure_section()
# Legacy functions for display settings
def read_fullscreen_config() -> bool:
"""Reads the fullscreen mode setting."""
return _get_display_config().get_fullscreen()
def save_fullscreen_config(fullscreen: bool):
"""Saves the fullscreen mode setting."""
_get_display_config().set_fullscreen(fullscreen)
def read_auto_fullscreen_gamepad() -> bool:
"""Reads the auto-fullscreen setting for gamepad."""
return _get_display_config().get_auto_fullscreen_gamepad()
def save_auto_fullscreen_gamepad(auto_fullscreen: bool):
"""Saves the auto-fullscreen setting for gamepad."""
_get_display_config().set_auto_fullscreen_gamepad(auto_fullscreen)
def read_minimize_to_tray() -> bool:
"""Reads the minimize-to-tray setting."""
return _get_display_config().get_minimize_to_tray()
def save_minimize_to_tray(minimize_to_tray: bool):
"""Saves the minimize-to-tray setting."""
_get_display_config().set_minimize_to_tray(minimize_to_tray)
def read_autostart_enabled() -> bool:
"""Reads the autostart setting."""
autostart_enabled = _get_display_config().get_autostart_enabled()
if autostart_enabled and not AUTOSTART_FILE.exists():
_get_display_config().set_autostart_enabled(False)
return False
return autostart_enabled
def save_autostart_enabled(autostart_enabled: bool):
"""Saves the autostart setting."""
_get_display_config().set_autostart_enabled(autostart_enabled)
def read_start_minimized() -> bool:
"""Reads the start minimized setting."""
return _get_display_config().get_start_minimized()
def save_start_minimized(start_minimized: bool):
"""Saves the start minimized setting."""
_get_display_config().set_start_minimized(start_minimized)
def apply_xdg_autostart(enabled: bool) -> bool:
"""Create or remove xdg-autostart desktop entry."""
try:
cp.read(config_file, encoding="utf-8")
return cp
except (configparser.DuplicateSectionError, configparser.DuplicateOptionError) as e:
logger.warning(f"Invalid configuration file format: {e}")
return None
if enabled:
AUTOSTART_DIR.mkdir(parents=True, exist_ok=True)
exec_command = "portprotonqt"
repo_root = Path(__file__).resolve().parent.parent
venv_portprotonqt = repo_root / ".venv" / "bin" / "portprotonqt"
if repo_root.joinpath(".git").exists() and venv_portprotonqt.exists():
exec_command = f'"{venv_portprotonqt}"'
desktop_entry = (
"[Desktop Entry]\n"
"Type=Application\n"
"Name=PortProtonQt\n"
f"Exec={exec_command}\n"
"Terminal=false\n"
"X-GNOME-Autostart-enabled=true\n"
)
AUTOSTART_FILE.write_text(desktop_entry, encoding="utf-8")
logger.info("Enabled xdg-autostart at %s", AUTOSTART_FILE)
return True
if AUTOSTART_FILE.exists():
AUTOSTART_FILE.unlink()
logger.info("Disabled xdg-autostart at %s", AUTOSTART_FILE)
return True
except OSError as e:
logger.error("Failed to update xdg-autostart: %s", e)
return False
# Legacy functions for window settings
def read_window_geometry() -> tuple[int, int]:
"""Reads the window width and height."""
return _get_window_config().get_geometry()
def save_window_geometry(width: int, height: int):
"""Saves the window width and height."""
_get_window_config().set_geometry(width, height)
# Legacy functions for PortProton location
def get_portproton_location() -> str | None:
"""Return PortProton directory path."""
return _get_portproton_config().get_location()
def get_portproton_start_command() -> list[str] | None:
"""Return command list for PortProton launch."""
global _portproton_start_sh
if _portproton_start_sh is not None:
return _portproton_start_sh
# Check if flatpak command exists
try:
subprocess.run(
["flatpak", "--version"],
capture_output=True,
text=True,
check=False,
timeout=5,
)
flatpak_available = True
except FileNotFoundError:
flatpak_available = False
except Exception as e:
logger.warning(f"Failed to read configuration file: {e}")
logger.debug("Flatpak version check failed: %s", e)
flatpak_available = False
if flatpak_available:
try:
result = subprocess.run(
["flatpak", "list"],
capture_output=True,
text=True,
check=False,
timeout=10,
)
if "ru.linux_gaming.PortProton" in result.stdout:
logger.info("Detected Flatpak installation")
_portproton_start_sh = ["flatpak", "run", "ru.linux_gaming.PortProton"]
return _portproton_start_sh
except subprocess.TimeoutExpired:
logger.warning("Flatpak list command timed out")
return None
except Exception as e:
logger.warning("Error checking flatpak list: %s", e)
pass
portproton_path = get_portproton_location()
if not portproton_path:
return None
def read_config():
"""Reads the configuration file and returns a dictionary of parameters.
Example line in config (no sections):
detail_level = detailed
"""
config_dict = {}
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
key, sep, value = line.partition("=")
if sep:
config_dict[key.strip()] = value.strip()
return config_dict
start_sh_path = os.path.join(portproton_path, "data", "scripts", "start.sh")
if os.path.exists(start_sh_path):
_portproton_start_sh = [start_sh_path]
return _portproton_start_sh
def read_theme_from_config():
"""Reads the theme from the [Appearance] section of the configuration file.
Returns 'standart' if the parameter is not set.
"""
cp = read_config_safely(CONFIG_FILE)
if cp is None:
return "standart"
return cp.get("Appearance", "theme", fallback="standart")
def save_theme_to_config(theme_name):
"""Saves the selected theme name to the [Appearance] section of the configuration file."""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "Appearance" not in cp:
cp["Appearance"] = {}
cp["Appearance"]["theme"] = theme_name
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
def read_time_config():
"""Reads time settings from the [Time] section of the configuration file.
If the section or parameter is missing, saves and returns 'detailed' as default.
"""
cp = read_config_safely(CONFIG_FILE)
if cp is None or not cp.has_section("Time") or not cp.has_option("Time", "detail_level"):
save_time_config("detailed")
return "detailed"
return cp.get("Time", "detail_level", fallback="detailed").lower()
def save_time_config(detail_level):
"""Saves the time detail level to the [Time] section of the configuration file."""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "Time" not in cp:
cp["Time"] = {}
cp["Time"]["detail_level"] = detail_level
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
def read_file_content(file_path):
"""Reads the content of a file and returns it as a string."""
with open(file_path, encoding="utf-8") as f:
return f.read().strip()
def get_portproton_location():
"""Returns the path to the PortProton directory.
Checks the cached path first. If not set, reads from PORTPROTON_CONFIG_FILE.
If the path is invalid, uses the default directory.
"""
global _portproton_location
if _portproton_location is not None:
return _portproton_location
if os.path.isfile(PORTPROTON_CONFIG_FILE):
try:
location = read_file_content(PORTPROTON_CONFIG_FILE).strip()
if location and os.path.isdir(location):
_portproton_location = location
logger.info(f"PortProton path from configuration: {location}")
return _portproton_location
logger.warning(f"Invalid PortProton path in configuration: {location}, using default path")
except (OSError, PermissionError) as e:
logger.warning(f"Failed to read PortProton configuration file: {e}, using default path")
default_dir = os.path.join(os.path.expanduser("~"), ".var", "app", "ru.linux_gaming.PortProton")
if os.path.isdir(default_dir):
_portproton_location = default_dir
logger.info(f"Using flatpak PortProton directory: {default_dir}")
return _portproton_location
logger.warning("PortProton configuration and flatpak directory not found")
logger.warning("Neither flatpak nor start.sh found for PortProton")
return None
def parse_desktop_entry(file_path):
"""Reads and parses a .desktop file using configparser.
Returns None if the [Desktop Entry] section is missing.
"""
# Legacy utility functions
def parse_desktop_entry(file_path: str) -> configparser.SectionProxy | None:
"""Reads and parses a .desktop file using configparser."""
cp = configparser.ConfigParser(interpolation=None)
cp.read(file_path, encoding="utf-8")
if "Desktop Entry" not in cp:
return None
return cp["Desktop Entry"]
def load_theme_metainfo(theme_name):
"""Loads theme metadata from metainfo.ini in the theme's root directory.
Expected fields: author, author_link, description, name.
def find_game_by_exe(exe_path: str) -> configparser.SectionProxy | None:
"""Find a game in the library by its executable path.
Args:
exe_path: Full path to the executable file
Returns:
Parsed desktop entry if found, None otherwise
"""
meta = {}
for themes_dir in THEMES_DIRS:
theme_folder = os.path.join(themes_dir, theme_name)
metainfo_file = os.path.join(theme_folder, "metainfo.ini")
if os.path.exists(metainfo_file):
cp = configparser.ConfigParser()
cp.read(metainfo_file, encoding="utf-8")
if "Metainfo" in cp:
meta["author"] = cp.get("Metainfo", "author", fallback="Unknown")
meta["author_link"] = cp.get("Metainfo", "author_link", fallback="")
meta["description"] = cp.get("Metainfo", "description", fallback="")
meta["name"] = cp.get("Metainfo", "name", fallback=theme_name)
break
return meta
import shlex
def read_card_size():
"""Reads the card size (width) from the [Cards] section.
Returns 250 if the parameter is not set.
portproton_path = get_portproton_location()
if not portproton_path:
return None
desktop_files = [entry.path for entry in os.scandir(portproton_path)
if entry.name.endswith(".desktop")]
# Normalize the target exe path for comparison
target_exe = os.path.abspath(exe_path)
for desktop_path in desktop_files:
desktop_name = os.path.basename(desktop_path)
# Skip system desktop files
if desktop_name.lower() in ["portproton.desktop", "readme.desktop"]:
continue
entry = parse_desktop_entry(desktop_path)
if not entry:
continue
exec_line = entry.get("Exec", "")
if not exec_line:
continue
# Parse exec line to extract the game executable
try:
parts = shlex.split(exec_line)
# For PortProton: env "/path/to/start.sh" "/path/to/game.exe"
# The game exe is typically the 4th element (index 3)
game_exe = None
if len(parts) >= 4:
game_exe = os.path.expanduser(parts[3])
elif len(parts) >= 2:
# Try to find .exe in any part
for part in parts:
if part.endswith(".exe"):
game_exe = part
break
if not game_exe:
continue
# Compare paths (normalize for comparison)
if os.path.abspath(game_exe) == target_exe:
return entry
except (ValueError, IndexError):
# shlex.split can fail on malformed exec lines
continue
return None
def create_desktop_file(exe_path: str, game_name: str | None = None) -> tuple[str, str] | None:
"""Create a .desktop file for a game.
Args:
exe_path: Full path to the executable file
game_name: Optional game name (defaults to exe filename without extension)
Returns:
Tuple of (desktop_entry_content, desktop_file_path) if successful, None otherwise
"""
cp = read_config_safely(CONFIG_FILE)
if cp is None or not cp.has_section("Cards") or not cp.has_option("Cards", "card_width"):
save_card_size(250)
return 250
return cp.getint("Cards", "card_width", fallback=250)
if not os.path.isfile(exe_path):
logger.error(f"Executable not found: {exe_path}")
return None
def save_card_size(card_width):
"""Saves the card size (width) to the [Cards] section."""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "Cards" not in cp:
cp["Cards"] = {}
cp["Cards"]["card_width"] = str(card_width)
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
if not game_name:
game_name = os.path.splitext(os.path.basename(exe_path))[0]
def read_sort_method():
"""Reads the sort method from the [Games] section.
Returns 'last_launch' if the parameter is not set.
"""
cp = read_config_safely(CONFIG_FILE)
if cp is None or not cp.has_section("Games") or not cp.has_option("Games", "sort_method"):
save_sort_method("last_launch")
return "last_launch"
return cp.get("Games", "sort_method", fallback="last_launch").lower()
portproton_path = get_portproton_location()
if not portproton_path:
logger.error("PortProton location not found")
return None
def save_sort_method(sort_method):
"""Saves the sort method to the [Games] section."""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "Games" not in cp:
cp["Games"] = {}
cp["Games"]["sort_method"] = sort_method
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
is_flatpak = ".var" in portproton_path
base_path = os.path.join(portproton_path, "data")
def read_display_filter():
"""Reads the display_filter parameter from the [Games] section.
Returns 'all' if the parameter is missing.
"""
cp = read_config_safely(CONFIG_FILE)
if cp is None or not cp.has_section("Games") or not cp.has_option("Games", "display_filter"):
save_display_filter("all")
return "all"
return cp.get("Games", "display_filter", fallback="all").lower()
if is_flatpak:
exec_str = f'flatpak run ru.linux_gaming.PortProton "{exe_path}"'
else:
start_sh = os.path.join(base_path, "scripts", "start.sh")
exec_str = f'env "{start_sh}" "{exe_path}"'
def save_display_filter(filter_value):
"""Saves the display_filter parameter to the [Games] section."""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "Games" not in cp:
cp["Games"] = {}
cp["Games"]["display_filter"] = filter_value
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
icon_path = os.path.join(base_path, "img", f"{game_name}.png")
desktop_path = os.path.join(portproton_path, f"{game_name}.desktop")
working_dir = os.path.join(base_path, "scripts")
def read_favorites():
"""Reads the list of favorite games from the [Favorites] section.
The list is stored as a quoted string with comma-separated names.
Returns an empty list if the section or parameter is missing.
"""
cp = read_config_safely(CONFIG_FILE)
if cp is None or not cp.has_section("Favorites") or not cp.has_option("Favorites", "games"):
return []
favs = cp.get("Favorites", "games", fallback="").strip()
if favs.startswith('"') and favs.endswith('"'):
favs = favs[1:-1]
return [s.strip() for s in favs.split(",") if s.strip()]
os.makedirs(os.path.dirname(icon_path), exist_ok=True)
def save_favorites(favorites):
"""Saves the list of favorite games to the [Favorites] section.
The list is stored as a quoted string with comma-separated names.
"""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "Favorites" not in cp:
cp["Favorites"] = {}
fav_str = ", ".join(favorites)
cp["Favorites"]["games"] = f'"{fav_str}"'
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
comment = _('Launch game "{name}" with PortProton').format(name=game_name)
def read_rumble_config():
"""Reads the gamepad rumble setting from the [Gamepad] section.
Returns False if the parameter is missing.
"""
cp = read_config_safely(CONFIG_FILE)
if cp is None or not cp.has_section("Gamepad") or not cp.has_option("Gamepad", "rumble_enabled"):
save_rumble_config(False)
return False
return cp.getboolean("Gamepad", "rumble_enabled", fallback=False)
desktop_entry = f"""[Desktop Entry]
Name={game_name}
Comment={comment}
Exec={exec_str}
Terminal=false
Type=Application
Categories=Game;
StartupNotify=true
Path={working_dir}
Icon={icon_path}
"""
def save_rumble_config(rumble_enabled):
"""Saves the gamepad rumble setting to the [Gamepad] section."""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "Gamepad" not in cp:
cp["Gamepad"] = {}
cp["Gamepad"]["rumble_enabled"] = str(rumble_enabled)
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
return desktop_entry, desktop_path
def ensure_default_proxy_config():
"""Ensures the [Proxy] section exists in the configuration file.
Creates it with empty values if missing.
"""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "Proxy" not in cp:
cp.add_section("Proxy")
cp["Proxy"]["proxy_url"] = ""
cp["Proxy"]["proxy_user"] = ""
cp["Proxy"]["proxy_password"] = ""
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
def read_proxy_config():
"""Reads proxy settings from the [Proxy] section.
Returns an empty dict if proxy_url is not set or empty.
"""
ensure_default_proxy_config()
cp = read_config_safely(CONFIG_FILE)
if cp is None:
return {}
proxy_url = cp.get("Proxy", "proxy_url", fallback="").strip()
if proxy_url:
proxy_user = cp.get("Proxy", "proxy_user", fallback="").strip()
proxy_password = cp.get("Proxy", "proxy_password", fallback="").strip()
if "://" in proxy_url and "@" not in proxy_url and proxy_user and proxy_password:
protocol, rest = proxy_url.split("://", 1)
proxy_url = f"{protocol}://{proxy_user}:{proxy_password}@{rest}"
return {"http": proxy_url, "https": proxy_url}
return {}
def read_config_safely(config_file: str | Path = CONFIG_FILE) -> configparser.ConfigParser | None:
"""Safely reads a configuration file."""
from portprotonqt.config.base import _config_cache, _config_mtime
def save_proxy_config(proxy_url="", proxy_user="", proxy_password=""):
"""Saves proxy settings to the [Proxy] section.
Creates the section if it does not exist.
"""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "Proxy" not in cp:
cp["Proxy"] = {}
cp["Proxy"]["proxy_url"] = proxy_url
cp["Proxy"]["proxy_user"] = proxy_user
cp["Proxy"]["proxy_password"] = proxy_password
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
config_path = str(config_file)
config_path_obj = Path(config_file)
def read_fullscreen_config():
"""Reads the fullscreen mode setting from the [Display] section.
Returns False if the parameter is missing.
"""
cp = read_config_safely(CONFIG_FILE)
if cp is None or not cp.has_section("Display") or not cp.has_option("Display", "fullscreen"):
save_fullscreen_config(False)
return False
return cp.getboolean("Display", "fullscreen", fallback=False)
if not config_path_obj.exists():
logger.debug("Configuration file %s not found", config_path)
return None
def save_fullscreen_config(fullscreen):
"""Saves the fullscreen mode setting to the [Display] section."""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "Display" not in cp:
cp["Display"] = {}
cp["Display"]["fullscreen"] = str(fullscreen)
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
try:
current_mtime = config_path_obj.stat().st_mtime
except OSError:
logger.warning("Failed to get modification time for %s", config_path)
return None
def read_window_geometry() -> tuple[int, int]:
"""Reads the window width and height from the [MainWindow] section.
Returns (0, 0) if the parameters are missing.
"""
cp = read_config_safely(CONFIG_FILE)
if cp is None or not cp.has_section("MainWindow"):
return (0, 0)
width = cp.getint("MainWindow", "width", fallback=0)
height = cp.getint("MainWindow", "height", fallback=0)
return (width, height)
if config_path in _config_cache and config_path in _config_mtime:
if _config_mtime[config_path] == current_mtime:
logger.debug("Using cached config for %s", config_path)
return _config_cache[config_path]
cp = configparser.ConfigParser()
try:
cp.read(config_path, encoding="utf-8")
_config_cache[config_path] = cp
_config_mtime[config_path] = current_mtime
logger.debug("Config file %s loaded and cached", config_path)
return cp
except (configparser.DuplicateSectionError, configparser.DuplicateOptionError) as e:
logger.warning("Invalid configuration file format: %s", e)
return None
except Exception as e:
logger.warning("Failed to read configuration file: %s", e)
return None
def clear_cache():
"""Clears the PortProtonQt cache."""
_get_cache_config().clear_cache()
def save_window_geometry(width: int, height: int):
"""Saves the window width and height to the [MainWindow] section."""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "MainWindow" not in cp:
cp["MainWindow"] = {}
cp["MainWindow"]["width"] = str(width)
cp["MainWindow"]["height"] = str(height)
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
def reset_config():
"""Resets the configuration file by deleting it.
Subsequent reads will use default values.
"""
"""Resets the configuration file by deleting it."""
if os.path.exists(CONFIG_FILE):
try:
os.remove(CONFIG_FILE)
logger.info("Configuration file %s deleted", CONFIG_FILE)
from portprotonqt.config.base import _config_cache, _config_mtime
config_path = str(CONFIG_FILE)
if config_path in _config_cache:
del _config_cache[config_path]
if config_path in _config_mtime:
del _config_mtime[config_path]
except Exception as e:
logger.warning(f"Failed to delete configuration file: {e}")
def clear_cache():
"""Clears the PortProtonQt cache by deleting the cache directory."""
xdg_cache_home = os.getenv("XDG_CACHE_HOME", os.path.join(os.path.expanduser("~"), ".cache"))
cache_dir = os.path.join(xdg_cache_home, "PortProtonQt")
if os.path.exists(cache_dir):
try:
shutil.rmtree(cache_dir)
logger.info("PortProtonQt cache deleted: %s", cache_dir)
except Exception as e:
logger.warning(f"Failed to delete cache: {e}")
def read_auto_fullscreen_gamepad():
"""Reads the auto-fullscreen setting for gamepad from the [Display] section.
Returns False if the parameter is missing.
"""
cp = read_config_safely(CONFIG_FILE)
if cp is None or not cp.has_section("Display") or not cp.has_option("Display", "auto_fullscreen_gamepad"):
save_auto_fullscreen_gamepad(False)
return False
return cp.getboolean("Display", "auto_fullscreen_gamepad", fallback=False)
def save_auto_fullscreen_gamepad(auto_fullscreen):
"""Saves the auto-fullscreen setting for gamepad to the [Display] section."""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "Display" not in cp:
cp["Display"] = {}
cp["Display"]["auto_fullscreen_gamepad"] = str(auto_fullscreen)
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
def read_favorite_folders():
"""Reads the list of favorite folders from the [FavoritesFolders] section.
The list is stored as a quoted string with comma-separated paths.
Returns an empty list if the section or parameter is missing.
"""
cp = read_config_safely(CONFIG_FILE)
if cp is None or not cp.has_section("FavoritesFolders") or not cp.has_option("FavoritesFolders", "folders"):
return []
favs = cp.get("FavoritesFolders", "folders", fallback="").strip()
if favs.startswith('"') and favs.endswith('"'):
favs = favs[1:-1]
return [os.path.normpath(s.strip()) for s in favs.split(",") if s.strip() and os.path.isdir(os.path.normpath(s.strip()))]
def save_favorite_folders(folders):
"""Saves the list of favorite folders to the [FavoritesFolders] section.
The list is stored as a quoted string with comma-separated paths.
"""
cp = read_config_safely(CONFIG_FILE) or configparser.ConfigParser()
if "FavoritesFolders" not in cp:
cp["FavoritesFolders"] = {}
fav_str = ", ".join([os.path.normpath(folder) for folder in folders])
cp["FavoritesFolders"]["folders"] = f'"{fav_str}"'
with open(CONFIG_FILE, "w", encoding="utf-8") as configfile:
cp.write(configfile)
logger.warning("Failed to delete configuration file: %s", e)
+294 -94
View File
@@ -8,10 +8,10 @@ import orjson
import psutil
import signal
from PySide6.QtWidgets import QMessageBox, QDialog, QMenu, QLineEdit, QApplication
from PySide6.QtCore import QUrl, QPoint, QObject, Signal, Qt
from PySide6.QtCore import QUrl, QPoint, QObject, Signal, Qt, QStandardPaths
from PySide6.QtGui import QDesktopServices, QIcon, QKeySequence
from portprotonqt.localization import _
from portprotonqt.config_utils import parse_desktop_entry, read_favorites, save_favorites, read_favorite_folders, save_favorite_folders
from portprotonqt.config_utils import parse_desktop_entry, read_favorites, save_favorites, read_favorite_folders, save_favorite_folders, get_portproton_start_command
from portprotonqt.steam_api import is_game_in_steam, add_to_steam, remove_from_steam
from portprotonqt.egs_api import add_egs_to_steam, get_egs_executable, remove_egs_from_steam
from portprotonqt.dialogs import AddGameDialog, FileExplorer, generate_thumbnail
@@ -29,7 +29,7 @@ class ContextMenuSignals(QObject):
class ContextMenuManager:
"""Manages context menu actions for game management in PortProtonQt."""
def __init__(self, parent, portproton_location, theme, load_games_callback, game_library_manager):
def __init__(self, parent, portproton_location, theme, game_library_manager):
"""
Initialize the ContextMenuManager.
@@ -44,7 +44,6 @@ class ContextMenuManager:
self.portproton_location = portproton_location
self.theme = theme
self.theme_manager = ThemeManager()
self.load_games = load_games_callback
self.game_library_manager = game_library_manager
self.update_game_grid = game_library_manager.update_game_grid
self.legendary_path = os.path.join(
@@ -286,7 +285,7 @@ class ContextMenuManager:
open_folder_action.triggered.connect(
lambda: self.open_egs_game_folder(game_card.appid)
)
desktop_dir = subprocess.check_output(['xdg-user-dir', 'DESKTOP']).decode('utf-8').strip()
desktop_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DesktopLocation)
desktop_path = os.path.join(desktop_dir, f"{game_card.name}.desktop")
icon_name = "delete" if os.path.exists(desktop_path) else "desktop"
text = _("Remove from Desktop") if os.path.exists(desktop_path) else _("Add to Desktop")
@@ -309,7 +308,7 @@ class ContextMenuManager:
)
if game_card.game_source not in ("steam", "epic"):
desktop_dir = subprocess.check_output(['xdg-user-dir', 'DESKTOP']).decode('utf-8').strip()
desktop_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DesktopLocation)
desktop_path = os.path.join(desktop_dir, f"{game_card.name}.desktop")
icon_name = "delete" if os.path.exists(desktop_path) else "desktop"
text = _("Remove from Desktop") if os.path.exists(desktop_path) else _("Add to Desktop")
@@ -406,16 +405,7 @@ class ContextMenuManager:
)
return
# Construct EGS launch command
wrapper = "flatpak run ru.linux_gaming.PortProton"
start_sh_path = os.path.join(self.portproton_location, "data", "scripts", "start.sh")
if self.portproton_location and ".var" not in self.portproton_location:
wrapper = start_sh_path
if not os.path.exists(start_sh_path):
self.signals.show_warning_dialog.emit(
_("Error"),
_("start.sh not found at {path}").format(path=start_sh_path)
)
return
wrapper = get_portproton_start_command()
exec_line = f'"{self.legendary_path}" launch {game_card.appid} --no-wine --wrapper "env START_FROM_STEAM=1 {wrapper}"'
else:
exec_line = self._get_exec_line(game_card.name, game_card.exec_line)
@@ -442,10 +432,22 @@ class ContextMenuManager:
def on_add_to_steam_result(result: tuple[bool, str]):
success, message = result
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was added to Steam. Please restart Steam for changes to take effect.").format(game_name=game_name)
)
if success:
if "restart" in message.lower():
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was added to Steam. Please restart Steam for changes to take effect.").format(game_name=game_name)
)
else:
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was added to Steam.").format(game_name=game_name)
)
else:
self.signals.show_warning_dialog.emit(
_("Error"),
_(message).format(game_name=game_name)
)
logger.debug("Adding EGS game '%s' to Steam", game_name)
add_egs_to_steam(app_name, game_name, self.legendary_path, on_add_to_steam_result)
@@ -561,11 +563,83 @@ class ContextMenuManager:
self._show_status_message(message)
def _get_desktop_path(self, game_name):
"""Construct the .desktop file path, trying both original and sanitized game names."""
"""Construct the .desktop file path, trying direct and fallback matching."""
desktop_path = os.path.join(self.portproton_location, f"{game_name}.desktop")
if not os.path.exists(desktop_path):
sanitized_name = game_name.replace("/", "_").replace(":", "_").replace(" ", "_")
desktop_path = os.path.join(self.portproton_location, f"{sanitized_name}.desktop")
if os.path.exists(desktop_path):
return desktop_path
sanitized_name = game_name.replace("/", "_").replace(":", "_").replace(" ", "_")
desktop_path = os.path.join(self.portproton_location, f"{sanitized_name}.desktop")
if os.path.exists(desktop_path):
return desktop_path
normalized_game_name = "".join(ch for ch in game_name.lower() if ch.isalnum())
desktop_files = glob.glob(os.path.join(self.portproton_location, "*.desktop"))
if normalized_game_name:
repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
xdg_data_home = os.getenv(
"XDG_DATA_HOME",
os.path.join(os.path.expanduser("~"), ".local", "share")
)
custom_roots = [
os.path.join(xdg_data_home, "PortProtonQt", "custom_data"),
os.path.join(repo_root, "portprotonqt", "custom_data"),
]
for custom_root in custom_roots:
if not os.path.isdir(custom_root):
continue
metadata_files = glob.glob(
os.path.join(custom_root, "**", "metadata.txt"),
recursive=True,
)
for metadata_path in metadata_files:
try:
metadata_name = ""
with open(metadata_path, encoding="utf-8") as metadata_file:
for line in metadata_file:
if line.startswith("name="):
metadata_name = line[5:].strip()
break
if not metadata_name:
continue
normalized_metadata_name = "".join(
ch for ch in metadata_name.lower() if ch.isalnum()
)
if normalized_metadata_name != normalized_game_name:
continue
script_name = os.path.basename(os.path.dirname(metadata_path))
for file_path in desktop_files:
entry = parse_desktop_entry(file_path)
if not entry:
continue
exec_line = entry.get("Exec", entry.get("exec", ""))
if script_name.lower() in exec_line.lower():
return file_path
except OSError:
continue
for file_path in desktop_files:
entry = parse_desktop_entry(file_path)
if entry:
entry_name = entry.get("Name", entry.get("name", "")).strip()
normalized_entry_name = "".join(ch for ch in entry_name.lower() if ch.isalnum())
if normalized_entry_name and (
normalized_entry_name == normalized_game_name
or normalized_entry_name in normalized_game_name
or normalized_game_name in normalized_entry_name
):
return file_path
stem = os.path.splitext(os.path.basename(file_path))[0]
normalized_stem = "".join(ch for ch in stem.lower() if ch.isalnum())
if normalized_stem and (
normalized_stem == normalized_game_name
or normalized_stem in normalized_game_name
or normalized_game_name in normalized_stem
):
return file_path
return desktop_path
def _get_egs_desktop_path(self, game_name):
@@ -656,7 +730,7 @@ Icon={icon_path}
if not os.path.exists(desktop_path):
if not self._create_egs_desktop_file(game_name, app_name):
return
desktop_dir = subprocess.check_output(['xdg-user-dir', 'DESKTOP']).decode('utf-8').strip()
desktop_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DesktopLocation)
os.makedirs(desktop_dir, exist_ok=True)
dest_path = os.path.join(desktop_dir, f"{game_name}.desktop")
try:
@@ -680,7 +754,7 @@ Icon={icon_path}
Args:
game_name: The display name of the game.
"""
desktop_dir = subprocess.check_output(['xdg-user-dir', 'DESKTOP']).decode('utf-8').strip()
desktop_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DesktopLocation)
desktop_path = os.path.join(desktop_dir, f"{game_name}.desktop")
self._remove_file(
desktop_path,
@@ -814,14 +888,50 @@ Icon={icon_path}
)
return False
def _remove_statistics_entry(self, exe_path, game_name):
"""Remove statistics entry for exact executable path."""
if not exe_path or not self.portproton_location:
return
statistics_file = os.path.join(self.portproton_location, "data", "tmp", "statistics")
if not os.path.exists(statistics_file):
return
target_path = os.path.normpath(exe_path)
kept_lines = []
removed = False
try:
with open(statistics_file, encoding="utf-8") as f:
for line in f:
token = line.strip().split(maxsplit=1)
if not token:
kept_lines.append(line)
continue
stat_path = os.path.normpath(token[0].replace("#@_@#", " "))
if stat_path == target_path:
removed = True
continue
kept_lines.append(line)
if removed:
with open(statistics_file, "w", encoding="utf-8") as f:
f.writelines(kept_lines)
logger.info("Removed statistics entry for '%s' (%s)", game_name, exe_path)
except OSError as e:
logger.warning("Failed to clean statistics for '%s': %s", game_name, e)
def delete_game(self, game_name, exec_line):
reply = QMessageBox.question(
self.parent,
_("Confirm Deletion"),
_("Are you sure you want to delete '{game_name}'? This will remove the .desktop file and custom data.").format(game_name=game_name),
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No
)
card_exec_line = exec_line
msg_box = QMessageBox(self.parent)
msg_box.setIcon(QMessageBox.Icon.Question)
msg_box.setWindowTitle(_("Confirm Deletion"))
msg_box.setText(_("Are you sure you want to delete '{game_name}'? This will remove the .desktop file and custom data.").format(game_name=game_name))
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"))
reply = msg_box.exec()
if reply != QMessageBox.StandardButton.Yes:
return
if not self._check_portproton():
@@ -833,10 +943,10 @@ Icon={icon_path}
_("No .desktop file found for '{game_name}'").format(game_name=game_name)
)
return
exec_line = self._get_exec_line(game_name, exec_line)
if not exec_line:
resolved_exec_line = self._get_exec_line(game_name, exec_line)
if not resolved_exec_line:
return
exe_path = self._parse_exe_path(exec_line, game_name)
exe_path = self._parse_exe_path(resolved_exec_line, game_name)
exe_name = os.path.splitext(os.path.basename(exe_path))[0] if exe_path else None
if not self._remove_file(
desktop_path,
@@ -845,6 +955,7 @@ Icon={icon_path}
game_name
):
return
self._remove_statistics_entry(exe_path, game_name)
if exe_name:
xdg_data_home = os.getenv(
"XDG_DATA_HOME",
@@ -860,8 +971,7 @@ Icon={icon_path}
_("Failed to delete custom data: {error}").format(error=str(e))
)
self.update_game_grid = self.game_library_manager.remove_game_incremental
self.game_library_manager.remove_game_incremental(game_name, exec_line)
self.game_library_manager.remove_game_incremental(game_name, card_exec_line or resolved_exec_line)
def add_game_incremental(self, game_data: tuple):
"""Add game after .desktop creation."""
@@ -946,7 +1056,7 @@ Icon={icon_path}
if not generate_thumbnail(exe_path, icon_path, size=128):
logger.error("Failed to generate thumbnail for game: %s", exe_path)
desktop_dir = subprocess.check_output(['xdg-user-dir', 'DESKTOP']).decode('utf-8').strip()
desktop_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DesktopLocation)
os.makedirs(desktop_dir, exist_ok=True)
dest_path = os.path.join(desktop_dir, f"{game_name}.desktop")
try:
@@ -970,7 +1080,7 @@ Icon={icon_path}
Args:
game_name: The display name of the game.
"""
desktop_dir = subprocess.check_output(['xdg-user-dir', 'DESKTOP']).decode('utf-8').strip()
desktop_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DesktopLocation)
desktop_path = os.path.join(desktop_dir, f"{game_name}.desktop")
self._remove_file(
desktop_path,
@@ -1043,8 +1153,22 @@ Icon={icon_path}
_("Failed to save .desktop file: {error}").format(error=str(e))
)
return
saved_entry = parse_desktop_entry(new_desktop_path)
updated_exec_line = new_exe_path
if saved_entry:
parsed_exec = saved_entry.get("Exec", saved_entry.get("exec", "")).strip()
if parsed_exec:
updated_exec_line = parsed_exec
if os.path.isfile(new_cover_path):
# Check if new_cover_path is a URL by checking for common image extensions
image_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp')
has_image_extension = any(new_cover_path.lower().endswith(ext) for ext in image_extensions)
# Consider it a URL if it has image extension and is not a local file
is_url = has_image_extension and not os.path.isfile(new_cover_path)
# Use the downloaded file path if we have a URL and the file was downloaded, otherwise use the local file
if os.path.isfile(new_cover_path) or (is_url and dialog.last_cover_path and os.path.isfile(dialog.last_cover_path)):
exe_name = os.path.splitext(os.path.basename(new_exe_path))[0]
xdg_data_home = os.getenv(
"XDG_DATA_HOME",
@@ -1052,16 +1176,66 @@ Icon={icon_path}
)
custom_folder = os.path.join(xdg_data_home, "PortProtonQt", "custom_data", exe_name)
os.makedirs(custom_folder, exist_ok=True)
ext = os.path.splitext(new_cover_path)[1].lower()
# Use the actual cover file path (either from URL download or local file)
cover_to_copy = dialog.last_cover_path if is_url and dialog.last_cover_path and os.path.isfile(dialog.last_cover_path) else new_cover_path
ext = os.path.splitext(cover_to_copy)[1].lower()
if ext in [".png", ".jpg", ".jpeg", ".bmp"]:
target_cover_path = os.path.join(custom_folder, f"cover{ext}")
try:
shutil.copyfile(new_cover_path, os.path.join(custom_folder, f"cover{ext}"))
if os.path.exists(target_cover_path) and os.path.samefile(cover_to_copy, target_cover_path):
logger.debug(
"Skipping cover copy for %s: source and destination are identical",
new_name,
)
else:
shutil.copyfile(cover_to_copy, target_cover_path)
except OSError as e:
self.signals.show_warning_dialog.emit(
_("Error"),
_("Failed to copy cover image: {error}").format(error=str(e))
)
return
else:
self.signals.show_warning_dialog.emit(
_("Error"),
_("Unsupported image format: {extension}").format(extension=ext)
)
return
applications_dir = os.path.join(os.path.expanduser("~"), ".local", "share", "applications")
old_menu_path = os.path.join(applications_dir, f"{game_name}.desktop")
new_menu_path = os.path.join(applications_dir, f"{new_name}.desktop")
desktop_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DesktopLocation)
old_desktop_path = os.path.join(desktop_dir, f"{game_name}.desktop")
new_desktop_path_target = os.path.join(desktop_dir, f"{new_name}.desktop")
if game_name != new_name:
if os.path.exists(old_menu_path):
self.remove_from_menu(game_name)
if os.path.exists(old_desktop_path):
self.remove_from_desktop(game_name)
if is_game_in_steam(game_name):
self.remove_from_steam(game_name, new_exe_path, "portproton")
if dialog.add_to_menu_checkbox.isChecked():
if not os.path.exists(new_menu_path):
self.add_to_menu(new_name, updated_exec_line)
elif os.path.exists(new_menu_path):
self.remove_from_menu(new_name)
if dialog.add_to_desktop_checkbox.isChecked():
if not os.path.exists(new_desktop_path_target):
self.add_to_desktop(new_name, updated_exec_line)
elif os.path.exists(new_desktop_path_target):
self.remove_from_desktop(new_name)
is_in_steam = is_game_in_steam(new_name)
if dialog.add_to_steam_checkbox.isChecked():
if not is_in_steam:
self.add_to_steam(new_name, updated_exec_line, new_cover_path)
elif is_in_steam:
self.remove_from_steam(new_name, updated_exec_line, "portproton")
def add_to_steam(self, game_name, exec_line, cover_path):
"""
@@ -1083,10 +1257,22 @@ Icon={icon_path}
logger.debug("Adding game '%s' to Steam", game_name)
try:
success, message = add_to_steam(game_name, exec_line, cover_path)
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was added to Steam. Please restart Steam for changes to take effect.").format(game_name=game_name)
)
if success:
if "restart" in message.lower():
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was added to Steam. Please restart Steam for changes to take effect.").format(game_name=game_name)
)
else:
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was added to Steam.").format(game_name=game_name)
)
else:
self.signals.show_warning_dialog.emit(
_("Error"),
_(message).format(game_name=game_name)
)
except Exception as e:
self.signals.show_warning_dialog.emit(
_("Error"),
@@ -1103,10 +1289,16 @@ Icon={icon_path}
def on_remove_from_steam_result(result: tuple[bool, str]):
success, message = result
if success:
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was removed from Steam. Please restart Steam for changes to take effect.").format(game_name=game_name)
)
if "restart" in message.lower():
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was removed from Steam. Please restart Steam for changes to take effect.").format(game_name=game_name)
)
else:
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was removed from Steam.").format(game_name=game_name)
)
else:
self.signals.show_warning_dialog.emit(
_("Error"),
@@ -1126,10 +1318,22 @@ Icon={icon_path}
logger.debug("Removing game '%s' from Steam", game_name)
try:
success, message = remove_from_steam(game_name, exec_line)
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was removed from Steam. Please restart Steam for changes to take effect.").format(game_name=game_name)
)
if success:
if "restart" in message.lower():
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was removed from Steam. Please restart Steam for changes to take effect.").format(game_name=game_name)
)
else:
self.signals.show_info_dialog.emit(
_("Success"),
_("'{game_name}' was removed from Steam.").format(game_name=game_name)
)
else:
self.signals.show_warning_dialog.emit(
_("Error"),
_(message).format(game_name=game_name)
)
except Exception as e:
self.signals.show_warning_dialog.emit(
_("Error"),
@@ -1169,49 +1373,45 @@ class CustomLineEdit(QLineEdit):
def __init__(self, *args, theme=None, **kwargs):
super().__init__(*args, **kwargs)
self.theme = theme
self.theme_manager = ThemeManager()
def contextMenuEvent(self, event):
def get_safe_icon(icon_name: str) -> QIcon:
icon = self.theme_manager.get_icon(icon_name)
if isinstance(icon, QIcon):
return icon
elif isinstance(icon, str) and os.path.exists(icon):
return QIcon(icon)
return QIcon()
def add_action(text: str, shortcut: QKeySequence.StandardKey, icon_name: str, slot, enabled=True):
icon = get_safe_icon(icon_name)
shortcut_str = QKeySequence(shortcut).toString(QKeySequence.SequenceFormat.NativeText)
action_text = f"{text}\t{shortcut_str}"
action = menu.addAction(icon, action_text)
action.triggered.connect(slot)
action.setEnabled(enabled)
menu = QMenu(self)
if self.theme and hasattr(self.theme, "CONTEXT_MENU_STYLE"):
menu.setStyleSheet(self.theme.CONTEXT_MENU_STYLE)
add_action(_("Undo"), QKeySequence.StandardKey.Undo, "undo", self.undo, self.isUndoAvailable())
add_action(_("Redo"), QKeySequence.StandardKey.Redo, "redo", self.redo, self.isRedoAvailable())
menu.addSeparator()
add_action(_("Cut"), QKeySequence.StandardKey.Cut, "cut", self.cut, self.hasSelectedText())
add_action(_("Copy"), QKeySequence.StandardKey.Copy, "copy", self.copy, self.hasSelectedText())
add_action(_("Paste"), QKeySequence.StandardKey.Paste, "paste", self.paste,
QApplication.clipboard().mimeData().hasText())
add_action(_("Delete"), QKeySequence.StandardKey.Delete, "delete", self._delete_selected_text,
self.hasSelectedText())
menu.addSeparator()
add_action(_("Select All"), QKeySequence.StandardKey.SelectAll, "select_all", self.selectAll, bool(self.text()))
menu.exec(event.globalPos())
show_themed_line_edit_context_menu(self, event.globalPos(), self.theme)
def _delete_selected_text(self):
cursor_pos = self.cursorPosition()
self.backspace()
self.setCursorPosition(cursor_pos)
def show_themed_line_edit_context_menu(line_edit: QLineEdit, global_pos: QPoint, theme=None) -> None:
"""Show a themed context menu for any line edit widget."""
theme_manager = ThemeManager()
def add_action(menu: QMenu, text: str, shortcut: QKeySequence.StandardKey,
icon_name: str, slot, enabled: bool = True) -> None:
raw_icon = theme_manager.get_icon(icon_name)
icon = raw_icon if isinstance(raw_icon, QIcon) else QIcon(raw_icon) if isinstance(raw_icon, str) else QIcon()
shortcut_str = QKeySequence(shortcut).toString(QKeySequence.SequenceFormat.NativeText)
action = menu.addAction(icon, f"{text}\t{shortcut_str}")
action.triggered.connect(slot)
action.setEnabled(enabled)
menu = QMenu(line_edit)
current_theme = theme if theme is not None else getattr(line_edit, "theme", None)
if current_theme and hasattr(current_theme, "CONTEXT_MENU_STYLE"):
menu.setStyleSheet(current_theme.CONTEXT_MENU_STYLE)
add_action(menu, _("Undo"), QKeySequence.StandardKey.Undo, "undo", line_edit.undo, line_edit.isUndoAvailable())
add_action(menu, _("Redo"), QKeySequence.StandardKey.Redo, "redo", line_edit.redo, line_edit.isRedoAvailable())
menu.addSeparator()
add_action(menu, _("Cut"), QKeySequence.StandardKey.Cut, "cut", line_edit.cut, line_edit.hasSelectedText())
add_action(menu, _("Copy"), QKeySequence.StandardKey.Copy, "copy", line_edit.copy, line_edit.hasSelectedText())
add_action(menu, _("Paste"), QKeySequence.StandardKey.Paste, "paste", line_edit.paste,
QApplication.clipboard().mimeData().hasText())
add_action(menu, _("Delete"), QKeySequence.StandardKey.Delete, "delete", line_edit.backspace,
line_edit.hasSelectedText())
menu.addSeparator()
add_action(menu, _("Select All"), QKeySequence.StandardKey.SelectAll, "select_all", line_edit.selectAll,
bool(line_edit.text()))
menu.exec(global_pos)
File renamed without changes.

Before

Width:  |  Height:  |  Size: 634 KiB

After

Width:  |  Height:  |  Size: 634 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 315 KiB

After

Width:  |  Height:  |  Size: 315 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 978 KiB

After

Width:  |  Height:  |  Size: 978 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 649 KiB

After

Width:  |  Height:  |  Size: 649 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 391 KiB

After

Width:  |  Height:  |  Size: 391 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 710 KiB

After

Width:  |  Height:  |  Size: 710 KiB

File renamed without changes.

Before

Width:  |  Height:  |  Size: 627 KiB

After

Width:  |  Height:  |  Size: 627 KiB

+274 -89
View File
@@ -1,116 +1,166 @@
import numpy as np
from PySide6.QtWidgets import QLabel, QPushButton, QWidget, QLayout, QLayoutItem
from PySide6.QtCore import Qt, Signal, QRect, QPoint, QSize
from PySide6.QtCore import Qt, Signal, QRect, QSize, Property, QPropertyAnimation, QEasingCurve
from PySide6.QtGui import QFont, QFontMetrics, QPainter
def compute_layout(nat_sizes, rect_width, spacing, max_scale):
def compute_layout(nat_sizes, rect_width, spacing, max_scale, center_rows=True):
"""
Computes the layout of elements considering spacing and potential scaling of cards.
nat_sizes: Array (N, 2) with natural sizes of elements (width, height).
rect_width: Available container width.
spacing: Spacing between elements (horizontal and vertical).
max_scale: Maximum scaling factor (e.g., 1.0).
Returns:
result: Array (N, 4), where each row contains [x, y, new_width, new_height].
total_height: Total height of all rows.
Compute layout for flow arrangement.
nat_sizes: list of tuples [(width, height), ...]
"""
N = nat_sizes.shape[0]
result = np.zeros((N, 4), dtype=np.int32)
y = 0
i = 0
min_margin = 20 # Minimum margin on edges
N = len(nat_sizes)
if N == 0:
return [], 0
# Determine the maximum number of items per row and overall scale
max_items_per_row = 0
result = [[0, 0, 0, 0] for _ in range(N)]
min_margin = 20
available_width = rect_width - 2 * min_margin
# Fast search for max items per row
max_items_per_row = 1
global_scale = 1.0
max_row_x_start = min_margin # Starting x position of the widest row
temp_i = 0
max_row_x_start = min_margin
# First pass: Find the maximum number of items in a row
while temp_i < N:
sum_width = 0
count = 0
temp_j = temp_i
while temp_j < N:
w = nat_sizes[temp_j, 0]
if count > 0 and (sum_width + spacing + w) > rect_width - 2 * min_margin:
break
sum_width += w
count += 1
temp_j += 1
i = 0
while i < N:
# Binary search for max items count
left, right = 1, N - i
best_count = 1
while left <= right:
mid = (left + right) // 2
end_idx = min(i + mid, N)
sum_w = sum(nat_sizes[j][0] for j in range(i, end_idx))
needed_width = sum_w + spacing * (mid - 1)
if needed_width <= available_width:
best_count = mid
left = mid + 1
else:
right = mid - 1
count = best_count
sum_width = sum(nat_sizes[j][0] for j in range(i, i + count))
if count > max_items_per_row:
max_items_per_row = count
# Calculate scale for the most populated row
available_width = rect_width - spacing * (count - 1) - 2 * min_margin
desired_scale = available_width / sum_width if sum_width > 0 else 1.0
global_scale = desired_scale if desired_scale < max_scale else max_scale
# Store starting x position for the widest row
desired_scale = available_width / (sum_width + spacing * (count - 1)) if sum_width > 0 else 1.0
global_scale = min(desired_scale, max_scale)
scaled_row_width = int(sum_width * global_scale) + spacing * (count - 1)
max_row_x_start = max(min_margin, (rect_width - scaled_row_width) // 2)
temp_i = temp_j
if center_rows:
max_row_x_start = max(min_margin, (rect_width - scaled_row_width) // 2)
i += count
# Second pass: place elements
y = 0
i = 0
# Second pass: Place elements
while i < N:
# Binary search for current row
left, right = 1, N - i
best_count = 1
while left <= right:
mid = (left + right) // 2
end_idx = min(i + mid, N)
sum_w = sum(nat_sizes[j][0] for j in range(i, end_idx))
needed_width = sum_w + spacing * (mid - 1)
if needed_width <= available_width:
best_count = mid
left = mid + 1
else:
right = mid - 1
count = best_count
j = i + count
# Calculate sizes for row
sum_width = 0
row_max_height = 0
count = 0
j = i
# Determine the number of items for the current row
while j < N:
w = nat_sizes[j, 0]
if count > 0 and (sum_width + spacing + w) > rect_width - 2 * min_margin:
break
for k in range(i, j):
w, h = nat_sizes[k]
sum_width += w
count += 1
h = nat_sizes[j, 1]
if h > row_max_height:
row_max_height = h
j += 1
# Use global scale for all rows
scale = global_scale
scaled_row_width = int(sum_width * scale) + spacing * (count - 1)
scaled_row_width = int(sum_width * global_scale) + spacing * (count - 1)
# Determine starting x coordinate
if count == max_items_per_row:
# Center the full row
x = max(min_margin, (rect_width - scaled_row_width) // 2)
# Determine starting position
if center_rows:
if count == max_items_per_row:
x = max(min_margin, (rect_width - scaled_row_width) // 2)
else:
x = max_row_x_start
else:
# Align incomplete row to the left, matching the widest row's start
x = max_row_x_start
x = min_margin
# Place elements in row
for k in range(i, j):
new_w = int(nat_sizes[k, 0] * scale)
new_h = int(nat_sizes[k, 1] * scale)
result[k, 0] = x
result[k, 1] = y
result[k, 2] = new_w
result[k, 3] = new_h
w, h = nat_sizes[k]
new_w = int(w * global_scale)
new_h = int(h * global_scale)
result[k][0] = x
result[k][1] = y
result[k][2] = new_w
result[k][3] = new_h
x += new_w + spacing
y += int(row_max_height * scale) + spacing
y += int(row_max_height * global_scale) + spacing
i = j
return result, y
class FlowLayout(QLayout):
def __init__(self, parent=None):
def __init__(self, parent=None, center_rows=True):
super().__init__(parent)
self.itemList = []
self.setContentsMargins(20, 20, 20, 20) # Margins around the layout
self._spacing = 20 # Spacing for animation and overlap prevention
self._max_scale = 1.0 # Scaling disabled in layout
self.setContentsMargins(20, 20, 20, 20)
self._spacing = 20
self._max_scale = 1.0
self._center_rows = center_rows
# Simple cache
self._cache_width = None
self._cache_visible_hash = None
self._cache_result = None
def _get_visible_data(self):
"""Return list of visible items and their sizes"""
visible_items = []
visible_indices = []
visible_sizes = []
for i, item in enumerate(self.itemList):
widget = item.widget()
if widget and widget.isVisible():
visible_items.append(item)
visible_indices.append(i)
s = item.sizeHint()
visible_sizes.append((s.width(), s.height()))
return visible_items, visible_indices, visible_sizes
def _make_visible_hash(self, visible_sizes):
"""Create hash for change detection"""
return hash(tuple(visible_sizes))
def addItem(self, item: QLayoutItem) -> None:
self.itemList.append(item)
self._invalidate_cache()
def takeAt(self, index: int) -> QLayoutItem:
if 0 <= index < len(self.itemList):
self._invalidate_cache()
return self.itemList.pop(index)
raise IndexError("Index out of range")
def _invalidate_cache(self):
self._cache_width = None
self._cache_visible_hash = None
self._cache_result = None
def count(self) -> int:
return len(self.itemList)
@@ -126,7 +176,33 @@ class FlowLayout(QLayout):
return True
def heightForWidth(self, width):
return self.doLayout(QRect(0, 0, width, 0), True)
_, _, visible_sizes = self._get_visible_data()
if not visible_sizes:
return 0
# Check cache
visible_hash = self._make_visible_hash(visible_sizes)
if (self._cache_width == width and
self._cache_visible_hash == visible_hash and
self._cache_result is not None):
return self._cache_result[1]
# Calculate
geom_array, total_height = compute_layout(
visible_sizes,
width,
self._spacing,
self._max_scale,
self._center_rows,
)
# Save to cache
self._cache_width = width
self._cache_visible_hash = visible_hash
self._cache_result = (geom_array, total_height)
return total_height
def setGeometry(self, rect):
super().setGeometry(rect)
@@ -145,25 +221,52 @@ class FlowLayout(QLayout):
return size
def doLayout(self, rect, testOnly):
N = len(self.itemList)
if N == 0:
N_total = len(self.itemList)
if N_total == 0:
return 0
nat_sizes = np.empty((N, 2), dtype=np.int32)
for i, item in enumerate(self.itemList):
s = item.sizeHint()
nat_sizes[i, 0] = s.width()
nat_sizes[i, 1] = s.height()
visible_items, visible_indices, visible_sizes = self._get_visible_data()
geom_array, total_height = compute_layout(nat_sizes, rect.width(), self._spacing, self._max_scale)
if not visible_sizes:
if not testOnly:
for item in self.itemList:
item.setGeometry(QRect())
return 0
# Check cache
visible_hash = self._make_visible_hash(visible_sizes)
if (self._cache_width == rect.width() and
self._cache_visible_hash == visible_hash and
self._cache_result is not None):
geom_array, total_height = self._cache_result
else:
# Calculate layout
geom_array, total_height = compute_layout(
visible_sizes,
rect.width(),
self._spacing,
self._max_scale,
self._center_rows,
)
# Save to cache
self._cache_width = rect.width()
self._cache_visible_hash = visible_hash
self._cache_result = (geom_array, total_height)
if not testOnly:
for i, item in enumerate(self.itemList):
x = geom_array[i, 0] + rect.x()
y = geom_array[i, 1] + rect.y()
w = geom_array[i, 2]
h = geom_array[i, 3]
item.setGeometry(QRect(QPoint(x, y), QSize(w, h)))
rx, ry = rect.x(), rect.y()
# Set geometry for visible items
for idx, item in enumerate(visible_items):
x, y, w, h = geom_array[idx]
item.setGeometry(QRect(x + rx, y + ry, w, h))
# Hide invisible items
visible_set = set(visible_indices)
for i in range(N_total):
if i not in visible_set:
self.itemList[i].setGeometry(QRect())
return total_height
@@ -188,8 +291,18 @@ class ClickableLabel(QLabel):
self._icon = icon
self._icon_size = icon_size
self._icon_space = icon_space
self._base_icon_size = icon_size
self._base_icon_space = icon_space
self._font_scale_factor = font_scale_factor
self._card_width = 250
self._compact_mode = False
self._compact_collapsed_width = 0
self._compact_expanded_width = 0
self._compact_relayout_callback = None
self._animated_width = 0
self._width_animation = QPropertyAnimation(self, b"animatedWidth")
self._width_animation.setDuration(160)
self._width_animation.setEasingCurve(QEasingCurve.Type.OutCubic)
if change_cursor:
self.setCursor(Qt.CursorShape.PointingHandCursor)
self.updateFontSize()
@@ -202,14 +315,76 @@ class ClickableLabel(QLabel):
return self._icon
def setIconSize(self, icon_size: int, icon_space: int):
self._icon_size = icon_size
self._icon_space = icon_space
self._base_icon_size = icon_size
self._base_icon_space = icon_space
if self._compact_mode:
self._icon_size = max(1, int(self._base_icon_size * 1.5))
self._icon_space = 0
else:
self._icon_size = self._base_icon_size
self._icon_space = self._base_icon_space
self.update()
def setCardWidth(self, card_width: int):
self._card_width = card_width
self.updateFontSize()
def _set_animated_width(self, width: int):
width = max(1, int(width))
if self.width() == width:
return
self.setFixedWidth(width)
self._animated_width = width
if self._compact_relayout_callback:
self._compact_relayout_callback()
def _get_animated_width(self) -> int:
if self._animated_width > 0:
return self._animated_width
return self.width()
animatedWidth = Property(int, _get_animated_width, _set_animated_width)
def _animate_width_to(self, target_width: int):
target_width = max(1, int(target_width))
if self.width() == target_width:
return
self._width_animation.stop()
self._width_animation.setStartValue(self.width())
self._width_animation.setEndValue(target_width)
self._width_animation.start()
def setCompactMode(
self,
enabled: bool,
collapsed_width: int,
expanded_width: int,
relayout_callback=None,
):
self._compact_mode = bool(enabled)
if self._compact_mode:
self._icon_size = max(1, int(self._base_icon_size * 1.5))
self._icon_space = 0
compact_min_width = self._icon_size + 8
self._compact_collapsed_width = max(1, int(collapsed_width), compact_min_width)
self.setAlignment(Qt.AlignmentFlag.AlignCenter)
else:
self._icon_size = self._base_icon_size
self._icon_space = self._base_icon_space
self._compact_collapsed_width = max(0, int(collapsed_width))
self._compact_expanded_width = max(self._compact_collapsed_width, int(expanded_width))
self._compact_relayout_callback = relayout_callback
if self._compact_mode:
target_width = self._compact_expanded_width if self.underMouse() else self._compact_collapsed_width
else:
target_width = self._compact_expanded_width
self._set_animated_width(target_width)
self.update()
def setCompactRelayoutCallback(self, relayout_callback):
self._compact_relayout_callback = relayout_callback
def updateFontSize(self):
font = self.font()
font_size = int(self._card_width * self._font_scale_factor)
@@ -274,6 +449,16 @@ class ClickableLabel(QLabel):
else:
super().mousePressEvent(event)
def enterEvent(self, event):
if self._compact_mode:
self._animate_width_to(self._compact_expanded_width)
super().enterEvent(event)
def leaveEvent(self, event):
if self._compact_mode:
self._animate_width_to(self._compact_collapsed_width)
super().leaveEvent(event)
class AutoSizeButton(QPushButton):
def __init__(self, *args, icon=None, icon_size=16,
min_font_size=6, max_font_size=14, padding=20, update_size=True, **kwargs):
+83
View File
@@ -0,0 +1,83 @@
"""Debug utilities package for system information and log management."""
from portprotonqt.debug_utils.gpu_info import (
get_gpu_list,
get_cached_vk_gpu_info,
get_graphics_info_detailed,
)
from portprotonqt.debug_utils.system_info import (
get_os_info,
get_cpu_info,
get_ram_info,
get_ram_info_detailed,
get_desktop_environment,
get_locale_info,
get_locale_available,
get_libc_version,
get_program_bit_depth,
get_filesystem_info,
get_screen_info,
generate_system_info,
)
from portprotonqt.debug_utils.game_debug import (
get_ppdb_content,
get_user_overrides,
get_prefix_name,
get_winetricks_log,
)
from portprotonqt.debug_utils.env_utils import (
get_file_content,
get_portproton_env,
get_runtime_status,
get_vulkan_use_info,
get_wine_version,
get_d3d_extras_status,
)
from portprotonqt.debug_utils.log_processor import (
process_portproton_log,
)
from portprotonqt.debug_utils.debug_log_manager import (
DebugLogManager,
)
from portprotonqt.debug_utils.xorg_utils import (
get_xorg_version,
decode_xorg_release,
)
__all__ = [
"get_gpu_list",
"get_cached_vk_gpu_info",
"get_graphics_info_detailed",
"get_os_info",
"get_cpu_info",
"get_ram_info",
"get_ram_info_detailed",
"get_desktop_environment",
"get_locale_info",
"get_locale_available",
"get_libc_version",
"get_program_bit_depth",
"get_filesystem_info",
"get_screen_info",
"get_ppdb_content",
"get_user_overrides",
"get_prefix_name",
"get_winetricks_log",
"generate_system_info",
"get_file_content",
"get_portproton_env",
"get_runtime_status",
"get_vulkan_use_info",
"get_wine_version",
"get_d3d_extras_status",
"process_portproton_log",
"DebugLogManager",
"get_xorg_version",
"decode_xorg_release",
]
@@ -0,0 +1,202 @@
"""Debug log manager for game launch and output capture."""
import os
import queue
import signal
import subprocess
import threading
import time
from portprotonqt.logger import get_logger
from portprotonqt.config_utils import get_portproton_location
from portprotonqt.debug_utils.system_info import generate_system_info
from portprotonqt.debug_utils.log_processor import process_portproton_log
logger = get_logger(__name__)
class DebugLogManager:
"""Manages debug log creation with game launch and Wine output capture."""
def __init__(self):
self.process: subprocess.Popen | None = None
self.exe_path: str | None = None
self.start_command: list[str] | None = None
self.wine_output: list[str] = []
self.is_running = False
self.output_queue = queue.Queue()
self.output_thread = None
self._stop_event = threading.Event()
def start(self, exe_path: str, start_command: list[str]) -> bool:
"""Start game with PW_LOG=1 and capture output."""
if self.is_running:
return False
self.exe_path = exe_path
self.start_command = start_command
self.wine_output = []
self._stop_event.clear()
portproton_path = get_portproton_location()
if portproton_path:
portproton_log_path = os.path.join(portproton_path, "PortProton.log")
try:
if os.path.exists(portproton_log_path):
os.remove(portproton_log_path)
logger.debug(
"Deleted existing PortProton.log at %s",
portproton_log_path
)
except OSError as e:
logger.debug(
"Could not delete PortProton.log at %s: %s",
portproton_log_path, e
)
env_vars = os.environ.copy()
env_vars["PW_LOG"] = "1"
cmd = start_command + [exe_path]
try:
self.process = subprocess.Popen(
cmd,
env=env_vars,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
preexec_fn=os.setsid
)
self.output_thread = threading.Thread(
target=self._read_output, daemon=True
)
self.output_thread.start()
self.is_running = True
logger.info("Started debug session for %s", exe_path)
return True
except Exception as e:
logger.error("Failed to start debug session: %s", e)
return False
def _read_output(self):
"""Read output from subprocess in a separate thread."""
if self.process and self.process.stdout:
try:
for line in iter(self.process.stdout.readline, ''):
if self._stop_event.is_set():
break
self.output_queue.put(line)
except Exception as e:
logger.debug("Error reading output: %s", e)
def stop(self) -> str | None:
"""Stop game and save debug log with captured Wine output."""
self._stop_event.set()
if self.is_running and self.process:
try:
os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
try:
time.sleep(0.1)
if self.process.poll() is None:
os.killpg(os.getpgid(self.process.pid), signal.SIGKILL)
except ProcessLookupError:
pass
except Exception as e:
logger.debug("Error terminating process: %s", e)
try:
while True:
line = self.output_queue.get_nowait()
self.wine_output.append(line)
except queue.Empty:
pass
log_file = self._save_log()
if self.process and self.process.stdout:
try:
self.process.stdout.close()
except (AttributeError, OSError):
pass
self.process = None
self.is_running = False
return log_file
def check_running(self) -> bool:
"""Check if process is still running."""
if self.process is None:
self.is_running = False
return False
poll = self.process.poll()
if poll is not None:
self.is_running = False
return False
return True
def _save_log(self) -> str | None:
"""Save complete debug log to file."""
portproton_path = get_portproton_location()
if not portproton_path:
return None
system_info = generate_system_info(self.exe_path, self.start_command)
lines = [system_info]
portproton_log_content = ""
if portproton_path:
portproton_log_path = os.path.join(portproton_path, "PortProton.log")
if os.path.exists(portproton_log_path):
try:
with open(
portproton_log_path,
encoding="utf-8",
errors="ignore"
) as f:
portproton_log_content = f.read()
except OSError as e:
logger.debug(
"Could not read PortProton log file %s: %s",
portproton_log_path, e
)
if portproton_log_content.strip():
lines.append(portproton_log_content)
log_content = "\n".join(lines)
log_content = process_portproton_log(log_content)
if self.exe_path and os.path.exists(self.exe_path):
game_dir = os.path.dirname(self.exe_path)
log_file = os.path.join(game_dir, "PortProtonQt.log")
else:
log_file = os.path.join(portproton_path, "PortProtonQt.log")
try:
with open(log_file, "w", encoding="utf-8") as f:
f.write(log_content)
logger.info("Debug log saved to %s", log_file)
return log_file
except OSError as e:
logger.error("Failed to save debug log: %s", e)
return None
def cleanup_on_exit(self):
"""Clean up resources and save log when application exits."""
if self.is_running:
logger.info("Cleaning up debug log manager on application exit...")
self.stop()
+174
View File
@@ -0,0 +1,174 @@
"""Environment variables and configuration utilities."""
import os
import subprocess
from portprotonqt.logger import get_logger
from portprotonqt.config_utils import get_portproton_location
logger = get_logger(__name__)
def get_file_content(file_path: str, default: str = "") -> str:
"""Safely read file content, removing comments and empty lines."""
try:
with open(file_path, encoding="utf-8", errors="ignore") as f:
content = f.read()
lines = content.split('\n')
filtered_lines = []
for line in lines:
stripped_line = line.strip()
if not stripped_line.startswith('#') and stripped_line:
filtered_lines.append(line)
content = '\n'.join(filtered_lines)
return content.strip()
except OSError as e:
logger.debug("Failed to read %s: %s", file_path, e)
return default
def get_portproton_env(exe_path: str | None) -> dict[str, str]:
"""Get environment variables as exported by PortProton.
Priority order:
1. /tmp/PortProton_$USER/var.log (runtime variables from active session)
2. var file + user.conf + .ppdb (static configuration)
"""
env_vars: dict[str, str] = {}
# Priority 1: Read from /tmp/PortProton_$USER/var.log (most authoritative)
user = os.getenv('USER', 'unknown')
var_log_path = f'/tmp/PortProton_{user}/var.log'
if os.path.exists(var_log_path):
logger.debug("Reading variables from %s", var_log_path)
try:
with open(var_log_path, encoding='utf-8', errors='ignore') as f:
content = f.read()
for line in content.split('\n'):
line = line.strip()
if '=' in line:
key, val = line.split('=', 1)
env_vars[key.strip()] = val.strip()
logger.debug("Found %d variables from var.log", len(env_vars))
return env_vars
except Exception as e:
logger.debug("Error reading var.log: %s", e)
# Priority 2: Read from static configuration files
portproton_path = get_portproton_location()
if not portproton_path:
return {}
scripts_path = os.path.join(portproton_path, "data", "scripts")
var_file = os.path.join(scripts_path, "var")
user_conf = os.path.join(portproton_path, "data", "user.conf")
if not os.path.exists(var_file):
logger.debug("var file not found: %s", var_file)
return {}
bash_script = f'source "{var_file}" 2>/dev/null; '
if os.path.exists(user_conf):
bash_script += f'source "{user_conf}" 2>/dev/null; '
if exe_path:
ppdb_file = f"{exe_path}.ppdb"
if os.path.exists(ppdb_file):
logger.debug("Found .ppdb file: %s", ppdb_file)
bash_script += f'source "{ppdb_file}" 2>/dev/null; '
else:
logger.debug(".ppdb file not found: %s", ppdb_file)
bash_script += 'env | grep -E "^(PW_|DXVK_|VKD3D_)"'
try:
result = subprocess.run(
["bash", "-c", bash_script],
capture_output=True,
text=True,
timeout=5,
check=False
)
env_vars: dict[str, str] = {}
for line in result.stdout.strip().split("\n"):
if "=" in line:
key, val = line.split("=", 1)
env_vars[key] = val
logger.debug("Environment variables found: %s", env_vars)
return env_vars
except Exception as e:
logger.debug("Error getting portproton env: %s", e)
return {}
def get_runtime_status(
portproton_path: str,
exe_path: str | None = None,
start_cmd: list[str] | None = None
) -> str:
"""Check if RUNTIME is enabled and detect Flatpak usage."""
env_vars = get_portproton_env(exe_path)
runtime_val = env_vars.get("PW_USE_RUNTIME", "1")
is_flatpak = False
if start_cmd:
start_cmd_str = " ".join(start_cmd)
is_flatpak = "flatpak run" in start_cmd_str
if is_flatpak:
return "FLATPAK in used"
elif runtime_val == "0":
return "RUNTIME is disabled"
else:
return "RUNTIME is enabled"
def get_vulkan_use_info(portproton_path: str, exe_path: str | None = None) -> str:
"""Get PW_VULKAN_USE info with DXVK and VKD3D versions."""
env_vars = get_portproton_env(exe_path)
pw_vulkan_use = env_vars.get("PW_VULKAN_USE")
if pw_vulkan_use is None:
return "PW_VULKAN_USE: Variable not found (stub)"
elif pw_vulkan_use == "6":
dxvk = f"DXVK v.{env_vars.get('DXVK_NEW_VER', '')}"
vkd3d = f"VKD3D-PROTON v.{env_vars.get('VKD3D_NEW_VER', '')}"
elif pw_vulkan_use == "2":
dxvk = f"DXVK v.{env_vars.get('DXVK_OLD_VER', '')}"
vkd3d = f"VKD3D-PROTON v.{env_vars.get('VKD3D_OLD_VER', '')}"
elif pw_vulkan_use == "1":
dxvk = f"DXVK {env_vars.get('DXVK_SAREK_VER', 'Sarek')}"
vkd3d = f"VKD3D {env_vars.get('VKD3D_SAREK_VER', 'Sarek')}"
elif pw_vulkan_use == "0":
dxvk = "WINED3D"
vkd3d = "OpenGL"
else:
dxvk = "DXVK"
vkd3d = "VKD3D-PROTON"
return f"PW_VULKAN_USE={pw_vulkan_use} - {dxvk}, {vkd3d}"
def get_wine_version(portproton_path: str, exe_path: str | None = None) -> str:
"""Get Wine/Proton version in use."""
env_vars = get_portproton_env(exe_path)
return env_vars.get("PW_WINE_USE", "Unknown")
def get_d3d_extras_status(portproton_path: str, exe_path: str | None = None) -> str:
"""Check if D3D_EXTRAS is enabled."""
env_vars = get_portproton_env(exe_path)
d3d_extras_val = env_vars.get("PW_USE_D3D_EXTRAS", "1")
if d3d_extras_val == "1":
return "D3D_EXTRAS - enabled"
return "D3D_EXTRAS - disabled"
+94
View File
@@ -0,0 +1,94 @@
"""Game-specific debug information: PPDB, winetricks, overrides."""
import os
from portprotonqt.logger import get_logger
from portprotonqt.config_utils import get_portproton_location
from portprotonqt.debug_utils.env_utils import get_file_content
logger = get_logger(__name__)
def get_ppdb_content(exe_path: str | None, start_cmd: list[str] | None = None) -> str:
"""Get content of PPDB file for the executable."""
if not exe_path:
return ""
ppdb_path = f"{exe_path}.ppdb"
content = ""
if os.path.exists(ppdb_path):
content = get_file_content(ppdb_path)
else:
portproton_path = get_portproton_location()
if portproton_path:
default_ppdb_path = os.path.join(
portproton_path, "data", "scripts", "portwine_db", "default"
)
if os.path.exists(default_ppdb_path):
content = get_file_content(default_ppdb_path)
return content if content else ""
def get_user_overrides(portproton_path: str) -> str:
"""Get user override settings from user.conf."""
user_conf = os.path.join(portproton_path, "data", "user.conf")
if not os.path.exists(user_conf):
return ""
content = get_file_content(user_conf)
if not content:
return ""
lines = []
lines.append('# User overrides db and var settings...')
for line in content.split("\n"):
line = line.strip()
if line and not line.startswith("#") and "bash" not in line.lower():
if line.startswith("export "):
lines.append(line)
else:
lines.append(f"export {line}")
return "\n".join(lines)
def get_prefix_name(exe_path: str | None) -> str:
"""Get prefix name from PPDB file."""
if not exe_path:
return "DEFAULT"
ppdb_path = f"{exe_path}.ppdb"
if os.path.exists(ppdb_path):
content = get_file_content(ppdb_path)
for line in content.split("\n"):
if line.startswith("export PW_PREFIX_NAME="):
return line.split("=", 1)[1].strip().strip('"')
return "DEFAULT"
def get_winetricks_log(portproton_path: str, prefix_name: str = "DEFAULT") -> str:
"""Get winetricks log content for a prefix."""
winetricks_log = os.path.join(
portproton_path, "data", "prefixes", prefix_name, "winetricks.log"
)
if not os.path.exists(winetricks_log):
winetricks_log = os.path.join(
portproton_path, "data", "prefixes", "DEFAULT", "winetricks.log"
)
content = get_file_content(winetricks_log)
if not content:
return ""
lines = content.split('\n')
filtered_lines = []
for line in lines:
if not (line.startswith('d3dcomp') or line.startswith('d3dx')):
filtered_lines.append(line)
return '\n'.join(filtered_lines)
+378
View File
@@ -0,0 +1,378 @@
"""GPU information gathering functions."""
import os
import re
import subprocess
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
_vk_gpu_info_output: str | None = None
def get_cached_vk_gpu_info() -> str:
"""Get cached vk_gpu_info output, running it only once."""
global _vk_gpu_info_output
if _vk_gpu_info_output is None:
try:
dev_scripts_path = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
"dev-scripts",
"vk_gpu_info"
)
if os.path.exists(dev_scripts_path):
result = subprocess.run(
[dev_scripts_path],
capture_output=True,
text=True,
timeout=10,
check=False
)
else:
result = subprocess.run(
["vk_gpu_info"],
capture_output=True,
text=True,
timeout=10,
check=False
)
if result.returncode == 0:
_vk_gpu_info_output = result.stdout
else:
_vk_gpu_info_output = ""
except FileNotFoundError:
_vk_gpu_info_output = ""
except Exception as e:
logger.error("Error running vk_gpu_info: %s", e)
_vk_gpu_info_output = ""
return _vk_gpu_info_output
def get_gpu_list() -> list[str]:
"""Get list of available GPUs, sorted by type (discrete first)."""
gpu_list: list[str] = []
discrete_gpus: list[str] = []
integrated_gpus: list[str] = []
other_gpus: list[str] = []
vk_gpu_info_output = get_cached_vk_gpu_info()
if not vk_gpu_info_output:
return gpu_list
lines = vk_gpu_info_output.split("\n")
i = 0
while i < len(lines):
line = lines[i].strip()
if line.startswith("GPU #"):
gpu_info: dict[str, str] = {}
gpu_num_match = re.search(r'GPU #(\d+)', line)
if gpu_num_match:
gpu_info['id'] = gpu_num_match.group(1)
i += 1
while i < len(lines) and lines[i].strip() and not lines[i].startswith("GPU #"):
prop_line = lines[i].strip()
if ':' in prop_line:
key_value = prop_line.split(':', 1)
if len(key_value) == 2:
key = key_value[0].strip()
value = key_value[1].strip()
if key == 'device_name':
gpu_info['deviceName'] = value
elif key == 'device_type':
gpu_info['deviceType'] = value
i += 1
device_name = gpu_info.get('deviceName', 'Unknown')
device_type = gpu_info.get('deviceType', 'Unknown')
if device_type in ['CPU', 'VIRTUAL_GPU']:
continue
if device_type == 'DISCRETE_GPU':
discrete_gpus.append(device_name)
elif device_type == 'INTEGRATED_GPU':
integrated_gpus.append(device_name)
else:
other_gpus.append(device_name)
else:
i += 1
gpu_list = discrete_gpus + integrated_gpus + other_gpus
return gpu_list
def _format_gpu_description(device_desc: str) -> str:
"""Format GPU description from lspci output."""
if "NVIDIA" in device_desc:
gpu_match = re.search(r'NVIDIA Corporation (.+)', device_desc)
if gpu_match:
return f"NVIDIA {gpu_match.group(1)}"
elif "AMD" in device_desc or "ATI" in device_desc:
gpu_match = re.search(
r'Advanced Micro Devices, Inc. \[AMD/ATI\] (.+)',
device_desc
)
if gpu_match:
return f"AMD {gpu_match.group(1)}"
gpu_match = re.search(r'(AMD|ATI) (.+)', device_desc)
if gpu_match:
return f"{gpu_match.group(1)} {gpu_match.group(2)}"
elif "Intel" in device_desc:
gpu_match = re.search(r'Intel Corporation (.+)', device_desc)
if gpu_match:
return f"Intel {gpu_match.group(1)}"
return device_desc
def _extract_driver_info(all_lines: list[str], start_idx: int) -> str:
"""Extract driver info from lspci output lines."""
for j in range(start_idx + 1, min(start_idx + 4, len(all_lines))):
next_line = all_lines[j]
if "Kernel driver in use:" in next_line:
return next_line.split("Kernel driver in use:")[1].strip()
return ""
def _get_nvidia_driver_version() -> str | None:
"""Get NVIDIA driver version from sysfs."""
try:
with open('/sys/module/nvidia/version') as f:
return f.read().strip()
except FileNotFoundError:
return None
def _build_device_line(
device_count: int,
device_desc: str,
driver_info: str
) -> str:
"""Build formatted device line with driver and version info."""
formatted_device_desc = _format_gpu_description(device_desc)
device_line = f"Device-{device_count}: {formatted_device_desc}"
if driver_info:
device_line += f" driver: {driver_info}"
if "NVIDIA" in device_desc:
version = _get_nvidia_driver_version()
if version:
device_line += f" v: {version}"
return device_line
def _parse_lspci_output(stdout: str) -> list[str]:
"""Parse lspci -k output and return formatted graphics device lines."""
device_count = 1
all_lines = stdout.split("\n")
devices_info = []
i = 0
while i < len(all_lines):
line = all_lines[i]
if any(x in line for x in ["VGA", "3D", "Display"]):
parts = line.split(maxsplit=1)
device_desc = parts[1] if len(parts) > 1 else ""
driver_info = _extract_driver_info(all_lines, i)
device_line = _build_device_line(
device_count, device_desc, driver_info
)
devices_info.append(device_line)
device_count += 1
i += 1
return devices_info
def _build_graphics_section(devices_info: list[str]) -> list[str]:
"""Build Graphics section with devices and display info."""
graphics_lines = [f"Graphics: {device}" for device in devices_info]
if not graphics_lines:
return graphics_lines
session_type = os.environ.get("XDG_SESSION_TYPE", "unknown")
display_info = f"Display: {session_type}"
if session_type == "wayland":
display_info += f" server: {os.environ.get('WAYLAND_DISPLAY', 'N/A')}"
else:
display_info += f" server: {os.environ.get('DISPLAY', 'N/A')}"
try:
from portprotonqt.debug_utils.xorg_utils import get_xorg_version
xorg_version = get_xorg_version()
display_info += f" X.Org version: {xorg_version}"
except SystemExit:
pass
first_device = devices_info[0]
if "driver: " in first_device:
driver_part = first_device.split("driver: ")[1]
driver_name = driver_part.split(" ")[0] if " " in driver_part else driver_part
display_info += f" driver: loaded: {driver_name}"
graphics_lines.append(f" {display_info}")
return graphics_lines
def _parse_glxinfo_output(stdout: str) -> list[str]:
"""Parse glxinfo output and return relevant lines."""
keep_patterns = [
"name of display",
"display:",
"direct rendering",
"Memory info",
"Dedicated video memory",
"Total available memory",
"Currently available",
"OpenGL vendor",
"OpenGL renderer",
"OpenGL core profile version",
"OpenGL core profile shading",
"OpenGL core profile context",
"OpenGL core profile profile",
"OpenGL version string",
"OpenGL shading language",
"OpenGL context flags",
"OpenGL profile mask",
"OpenGL ES profile",
]
return [
line for line in stdout.split("\n")
if any(p in line for p in keep_patterns)
]
def _parse_gpu_properties(
lines_vk: list[str],
start_idx: int
) -> tuple[dict[str, str], int]:
"""Parse GPU properties from vk_gpu_info output."""
gpu_info: dict[str, str] = {}
i = start_idx
while i < len(lines_vk) and lines_vk[i].strip() and not lines_vk[i].startswith("GPU #"):
prop_line = lines_vk[i].strip()
if ':' in prop_line:
key_value = prop_line.split(':', 1)
if len(key_value) == 2:
key = key_value[0].strip()
value = key_value[1].strip()
gpu_info[key] = value
i += 1
return gpu_info, i
def _format_vulkan_gpu_line(gpu_info: dict[str, str]) -> str | None:
"""Format a single GPU line for vulkan output."""
device_type = gpu_info.get('device_type', 'Unknown')
if device_type in ['CPU', 'VIRTUAL_GPU']:
return None
gpu_id = gpu_info.get('id', 'Unknown')
device_name = gpu_info.get('device_name', 'Unknown')
driver_name = gpu_info.get('driver_name', 'Unknown')
api_version = gpu_info.get('api_version', 'Unknown')
if 'NVIDIA' in device_name.upper():
driver_version = gpu_info.get('driver_info', 'Unknown')
else:
driver_version = gpu_info.get('driver_version', 'Unknown')
return (
f"GPU {gpu_id}: {device_name} deviceType: {device_type} "
f"driverName: {driver_name} apiVersion: {api_version} "
f"driverVersion: {driver_version}"
)
def _parse_vulkan_output(vk_output: str) -> list[str]:
"""Parse vk_gpu_info output and return formatted GPU lines."""
lines = []
lines_vk = vk_output.split("\n")
i = 0
while i < len(lines_vk):
line = lines_vk[i].strip()
if line.startswith("GPU #"):
gpu_num_match = re.search(r'GPU #(\d+)', line)
gpu_id = gpu_num_match.group(1) if gpu_num_match else 'Unknown'
gpu_info, i = _parse_gpu_properties(lines_vk, i + 1)
gpu_info['id'] = gpu_id
gpu_line = _format_vulkan_gpu_line(gpu_info)
if gpu_line:
lines.append(gpu_line)
continue
i += 1
return lines
def get_graphics_info_detailed() -> str:
"""Get detailed graphics card info using lspci, glxinfo, and vk_gpu_info."""
lines = []
try:
result = subprocess.run(
["lspci", "-k"],
capture_output=True,
text=True,
timeout=10,
check=False
)
if result.returncode == 0:
devices_info = _parse_lspci_output(result.stdout)
lines.extend(_build_graphics_section(devices_info))
except Exception as e:
lines.append(f"lspci error: {e}")
lines.append("----")
try:
result = subprocess.run(
["glxinfo"],
capture_output=True,
text=True,
timeout=10,
check=False
)
if result.returncode == 0:
lines.extend(_parse_glxinfo_output(result.stdout))
except FileNotFoundError:
lines.append("glxinfo not found")
except Exception as e:
lines.append(f"glxinfo error: {e}")
lines.append("-----")
try:
vk_gpu_info_output = get_cached_vk_gpu_info()
if vk_gpu_info_output:
lines.append("Vulkan:")
lines.extend(_parse_vulkan_output(vk_gpu_info_output))
else:
lines.append("vk_gpu_info not found")
except FileNotFoundError:
lines.append("vk_gpu_info not found")
return "\n".join(lines) if lines else "Unable to retrieve graphics info"
+110
View File
@@ -0,0 +1,110 @@
"""PortProton log processing utilities."""
import os
import re
def process_portproton_log(log_content: str) -> str:
"""Process PortProton log: remove duplicates, anonymize, filter noise."""
if not log_content:
return log_content
lines = log_content.split('\n')
seen_lines: set[str] = set()
unique_lines: list[str] = []
section_start_patterns = [
"export PW_BASE_PFX=",
"WINEDLLOVERRIDES=",
"Log WINE:",
]
separator_pattern = r'^-{10,}$'
i = 0
while i < len(lines):
line = lines[i].strip()
is_section_start = any(
line.startswith(pattern) for pattern in section_start_patterns
)
is_separator = bool(re.match(separator_pattern, line))
if is_section_start:
if line in seen_lines:
j = i + 1
while j < len(lines):
next_line = lines[j].strip()
if any(
next_line.startswith(pattern)
for pattern in section_start_patterns
):
break
j += 1
i = j
continue
else:
seen_lines.add(line)
unique_lines.append(lines[i])
i += 1
elif is_separator:
unique_lines.append(lines[i])
i += 1
else:
if line not in seen_lines:
seen_lines.add(line)
unique_lines.append(lines[i])
i += 1
deduplicated_content = '\n'.join(unique_lines)
username = os.environ.get("USER", "")
if username:
deduplicated_content = deduplicated_content.replace(
f"/home/{username}", "/home/xuser"
)
deduplicated_content = deduplicated_content.replace(
f"PortProton_{username}", "PortProton_xuser"
)
deduplicated_content = deduplicated_content.replace(
f"#Author: {username}", "#Author: xuser"
)
deduplicated_content = deduplicated_content.replace(
f"/run/media/{username}", "/run/media/xuser"
)
deduplicated_content = deduplicated_content.replace(
f"/media/{username}", "/media/xuser"
)
is_flatpak_used = "FLATPAK in used" in deduplicated_content
filtered_lines = []
for line in deduplicated_content.split("\n"):
skip_line = False
if any(x in line.lower() for x in [
"kerberos",
"ntlm",
"hack_does_openvr_work",
"uploading is disabled",
"wine: rlimit_nice is <= 20",
"are assuming",
"to be private",
"udev monitor"
]):
skip_line = True
if not skip_line and line.rstrip().lower().endswith('.fx'):
skip_line = True
if not skip_line and is_flatpak_used:
stripped_line = line.strip()
if (
stripped_line.startswith("PW_USE_RUNTIME=") or
stripped_line.startswith("export PW_USE_RUNTIME=")
):
skip_line = True
if not skip_line:
filtered_lines.append(line)
return '\n'.join(filtered_lines)
+491
View File
@@ -0,0 +1,491 @@
"""System information gathering: OS, CPU, RAM, locale, filesystem, screen."""
import os
import platform
import re
import subprocess
from datetime import datetime
import psutil
from PySide6.QtWidgets import QApplication
from PySide6.QtCore import QRect
from PySide6.QtGui import QGuiApplication
from portprotonqt.logger import get_logger
from portprotonqt.localization import _
from portprotonqt.debug_utils.env_utils import get_file_content
from portprotonqt.debug_utils.gpu_info import get_graphics_info_detailed
from portprotonqt.debug_utils.game_debug import (
get_ppdb_content,
get_user_overrides,
get_prefix_name,
get_winetricks_log,
)
logger = get_logger(__name__)
def get_os_info() -> str:
"""Get operating system info using platform module."""
try:
info = platform.freedesktop_os_release()
return info.get("PRETTY_NAME", platform.platform())
except Exception as e:
logger.debug("Failed to get OS info: %s", e)
return platform.platform()
def get_cpu_info() -> dict[str, str]:
"""Get CPU information from /proc/cpuinfo."""
info: dict[str, str] = {
"model": "Unknown",
"physical_cores": "0",
"logical_cores": "0"
}
content = get_file_content("/proc/cpuinfo")
if not content:
return info
model_names: set[str] = set()
cpu_cores: set[str] = set()
processors = 0
for line in content.split("\n"):
if line.startswith("model name"):
parts = line.split(":", 1)
if len(parts) > 1:
model_names.add(parts[1].strip())
elif line.startswith("cpu cores"):
parts = line.split(":", 1)
if len(parts) > 1:
cpu_cores.add(parts[1].strip())
elif line.startswith("processor"):
processors += 1
if model_names:
info["model"] = list(model_names)[0]
if cpu_cores:
info["physical_cores"] = list(cpu_cores)[0]
info["logical_cores"] = str(processors)
return info
def get_ram_info() -> str:
"""Get RAM information using psutil."""
try:
mem = psutil.virtual_memory()
swap = psutil.swap_memory()
mem_total = f"{mem.total // 1024} kB"
mem_available = f"{mem.available // 1024} kB"
swap_total = f"{swap.total // 1024} kB"
return f"MemTotal: {mem_total}\nMemAvailable: {mem_available}\nSwapTotal: {swap_total}"
except Exception as e:
logger.debug("Failed to get RAM info: %s", e)
return "Unable to retrieve RAM info"
def get_ram_info_detailed() -> str:
"""Get RAM info in free command format."""
try:
result = subprocess.run(
["free", "-m"],
capture_output=True,
text=True,
timeout=5,
check=False
)
if result.returncode == 0:
return result.stdout.strip()
except Exception as e:
logger.debug("Failed to get free memory info: %s", e)
return get_ram_info()
def get_desktop_environment() -> dict[str, str]:
"""Get desktop environment information."""
return {
"session": os.environ.get("DESKTOP_SESSION", "Unknown"),
"current_desktop": os.environ.get("XDG_CURRENT_DESKTOP", "Unknown"),
"session_type": os.environ.get("XDG_SESSION_TYPE", "Unknown")
}
def get_locale_info() -> str:
"""Get locale info, filling missing LC_* from LANG if empty."""
try:
lang = os.environ.get("LANG", "")
locale_vars = [
"LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES", "LC_COLLATE",
"LC_TIME", "LC_NUMERIC", "LC_MONETARY", "LC_PAPER",
"LC_NAME", "LC_ADDRESS", "LC_TELEPHONE", "LC_MEASUREMENT",
"LC_IDENTIFICATION"
]
lines = []
for var in locale_vars:
value = os.environ.get(var, "")
if not value and var != "LC_ALL" and lang:
value = lang
lines.append(f"{var}={value}")
return "\n".join(lines) if lines else "No locale info available"
except Exception as e:
return f"Error getting locale info: {e}"
def get_locale_available() -> str:
"""Get available locales matching current LANG."""
try:
lang = os.environ.get("LANG", "")
if not lang:
return ""
base_locale = lang.replace("-8", "").replace(".UTF", "").replace(".utf", "")
result = subprocess.run(
["locale", "-a"],
capture_output=True,
text=True,
timeout=5,
check=False
)
if result.returncode == 0:
locales = result.stdout.strip().split("\n")
matching = [
loc for loc in locales
if base_locale.lower().replace(".utf-8", "") in loc.lower()
]
if matching:
return "\n".join(matching)
except Exception as e:
logger.debug("Failed to get available locales: %s", e)
return ""
def get_libc_version() -> str:
"""Get C library version (musl or glibc)."""
try:
result = subprocess.run(
['ldd', '--version'],
capture_output=True,
text=True,
check=False
)
libc_version_output = result.stdout or result.stderr
if 'musl' in libc_version_output.lower():
lines = libc_version_output.split('\n')
for line in lines:
if 'version' in line.lower() and re.search(r'\d+\.\d+', line):
version_match = re.search(r'(\d+\.\d+(?:\.\d+)?)', line)
if version_match:
return f"musl {version_match.group(1)}"
return "musl (version unknown)"
else:
for line in libc_version_output.split('\n'):
if 'ldd' in line.lower():
version_match = re.search(r'(\d+\.\d+(?:\.\d+)?)', line)
if version_match:
return f"glibc {version_match.group(1)}"
version_match = re.search(
r'(\d+\.\d+(?:\.\d+)?)', libc_version_output
)
if version_match:
return f"glibc {version_match.group(1)}"
return "glibc (version unknown)"
except Exception as e:
logger.debug("Failed to get libc version: %s", e)
return "Unknown"
def get_program_bit_depth(exe_path: str | None) -> str:
"""Get program bit depth (32 or 64 bit) from PE header."""
if not exe_path or not os.path.exists(exe_path):
return "Unknown"
try:
with open(exe_path, 'rb') as f:
dos_header = f.read(64)
if len(dos_header) < 64 or dos_header[:2] != b'MZ':
return "Not a valid PE file"
pe_offset = int.from_bytes(dos_header[60:64], 'little')
f.seek(pe_offset)
pe_sig = f.read(4)
if pe_sig != b'PE\x00\x00':
return "Not a valid PE file"
machine = f.read(2)
machine_type = int.from_bytes(machine, 'little')
if machine_type == 0x014c:
return "32 bit"
elif machine_type == 0x8664:
return "64 bit"
elif machine_type == 0x01c4:
return "32 bit (ARM)"
elif machine_type == 0xAA64:
return "64 bit (ARM64)"
else:
return f"Unknown (0x{machine_type:04x})"
except Exception as e:
logger.debug("Failed to detect bit depth: %s", e)
return "Unknown"
def get_filesystem_info(exe_path: str | None, portproton_path: str) -> str:
"""Get filesystem info for game and PortProton directories."""
def get_fs_type(path: str) -> str:
"""Get filesystem type using psutil, with lsblk fallback for fuseblk."""
try:
path = os.path.realpath(path)
partitions = {
p.mountpoint: (p.device, p.fstype)
for p in psutil.disk_partitions(all=True)
}
device, fstype = None, None
check_path = path
while check_path != "/":
if check_path in partitions:
device, fstype = partitions[check_path]
break
check_path = os.path.dirname(check_path)
if fstype is None:
device, fstype = partitions.get("/", (None, "Unknown"))
if fstype == "fuseblk" and device:
try:
result = subprocess.run(
["lsblk", "-no", "FSTYPE", device],
capture_output=True,
text=True,
timeout=2,
check=False
)
if result.returncode == 0 and result.stdout.strip():
fstype = result.stdout.strip()
except Exception as e:
logger.debug("Failed to get fstype for %s: %s", device, e)
return fstype
except Exception as e:
logger.debug("Failed to get filesystem info: %s", e)
return "Unknown"
lines = []
if exe_path:
game_dir = os.path.dirname(exe_path)
lines.append(f"Filesystem {game_dir} - {get_fs_type(game_dir)}")
lines.append(f"Filesystem {portproton_path} - {get_fs_type(portproton_path)}")
tmp_dir = f"/tmp/PortProton_{os.environ.get('USER', 'user')}"
if os.path.exists(tmp_dir):
lines.append(f"Filesystem {tmp_dir} - {get_fs_type(tmp_dir)}")
return "\n".join(lines) if lines else "Unable to retrieve filesystem info"
def get_screen_info(portproton_path: str, exe_path: str | None = None) -> tuple[str, str]:
"""Get screen resolution and primary info using PySide6."""
resolution = ""
primary = ""
app_instance = QApplication.instance()
if app_instance is None:
return "PW_SCREEN_RESOLUTION=1920x1080", "PW_SCREEN_PRIMARY=unknown"
if not isinstance(app_instance, QGuiApplication):
return "PW_SCREEN_RESOLUTION=1920x1080", "PW_SCREEN_PRIMARY=unknown"
screens = app_instance.screens()
primary_screen = app_instance.primaryScreen()
for screen in screens:
geometry: QRect = screen.geometry()
is_primary = screen == primary_screen
if is_primary:
resolution = f"{geometry.width()}x{geometry.height()}"
primary = screen.name()
break
if not resolution and screens:
first_screen = screens[0]
geometry = first_screen.geometry()
resolution = f"{geometry.width()}x{geometry.height()}"
primary = first_screen.name()
if not resolution or 'x' not in resolution:
resolution = "1920x1080"
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
) -> str:
"""Generate system information part of debug log."""
from portprotonqt.config_utils import get_portproton_location
from portprotonqt.debug_utils.env_utils import (
get_runtime_status,
get_vulkan_use_info,
get_wine_version,
get_d3d_extras_status,
)
portproton_path = get_portproton_location()
if not portproton_path:
return "Error: PortProton location not found"
lines = []
lines.append(_("Debug log mode was launched"))
lines.append(
_("To diagnose the problem, copy the ENTIRE log to the site:") +
" https://linux-gaming.ru/t/opisanie-kategorii-portproton-pomoshh/1642"
)
lines.append("-" * 61)
lines.append("PortProtonQt version:")
from portprotonqt.app import get_version
ppqt_version = get_version()
lines.append(ppqt_version)
lines.append("-" * 61)
lines.append("Scripts version:")
scripts_ver_file = os.path.join(portproton_path, "data", "tmp", "scripts_ver")
scripts_version = get_file_content(scripts_ver_file, "Unknown")
lines.append(scripts_version)
lines.append("-" * 61)
lines.append(get_runtime_status(portproton_path, exe_path, start_cmd))
lines.append("-" * 61)
if exe_path:
lines.append("Debug for programm:")
lines.append(exe_path)
lines.append("-" * 61)
lines.append("libc version:")
lines.append(get_libc_version())
lines.append("-" * 61)
lines.append(get_vulkan_use_info(portproton_path, exe_path))
lines.append("-" * 61)
lines.append("Version WINE in use:")
lines.append(get_wine_version(portproton_path, exe_path))
lines.append("-" * 61)
lines.append("Program bit depth:")
lines.append(get_program_bit_depth(exe_path))
lines.append("-" * 61)
lines.append("Date and time of start debug for PortProton:")
lines.append(datetime.now().strftime("%c %z"))
lines.append("-" * 61)
lines.append("The installation path of the PortProton:")
lines.append(portproton_path)
lines.append("-" * 61)
lines.append("Operating system:")
lines.append(get_os_info())
lines.append("-" * 61)
lines.append("Desktop environment:")
desktop = get_desktop_environment()
lines.append(f"Desktop session: {desktop['session']}")
lines.append(f"Current desktop: {desktop['current_desktop']}")
lines.append(f"Session type: {desktop['session_type']}")
lines.append("-" * 61)
lines.append("Kernel:")
lines.append(platform.release())
lines.append("-" * 61)
lines.append("CPU:")
cpu = get_cpu_info()
lines.append(f"CPU physical cores: {cpu['physical_cores']}")
lines.append(f"CPU logical cores: {cpu['logical_cores']}")
lines.append(f"CPU model name: {cpu['model']}")
lines.append("-" * 61)
lines.append("RAM:")
lines.append(get_ram_info_detailed())
lines.append("-" * 61)
lines.append(get_filesystem_info(exe_path, portproton_path))
lines.append("-" * 61)
lines.append("Graphic cards and drivers:")
lines.append(get_graphics_info_detailed())
lines.append("-" * 61)
screen_resolution, screen_primary = get_screen_info(portproton_path, exe_path)
if screen_resolution:
lines.append(screen_resolution)
if screen_primary:
lines.append(screen_primary)
lines.append("-" * 61)
lines.append("locale:")
lines.append(get_locale_info())
lines.append("-" * 61)
locale_avail = get_locale_available()
if locale_avail:
lines.append(locale_avail)
lines.append("-" * 61)
lines.append(get_d3d_extras_status(portproton_path, exe_path))
lines.append("-" * 61)
prefix_name = get_prefix_name(exe_path)
winetricks_content = get_winetricks_log(portproton_path, prefix_name)
if winetricks_content:
lines.append("winetricks.log:")
lines.append(winetricks_content)
lines.append("-" * 61)
if exe_path:
ppdb_content = get_ppdb_content(exe_path, start_cmd)
if ppdb_content:
lines.append(f"Use {exe_path}.ppdb db file:")
lines.append(ppdb_content)
lines.append("-" * 61)
user_overrides = get_user_overrides(portproton_path)
if user_overrides:
lines.append(user_overrides)
lines.append("-" * 61)
lines.append("-" * 61)
safe_lines = []
for i, line in enumerate(lines):
if line is None:
logger.warning("None value found at index %d in generate_system_info", i)
safe_lines.append("")
else:
safe_lines.append(str(line))
return "\n".join(safe_lines)
+41
View File
@@ -0,0 +1,41 @@
"""Xorg version detection utilities."""
import ctypes
from ctypes import c_char_p, c_int, c_void_p
def decode_xorg_release(rel: int) -> str:
"""Decode Xorg version from integer format."""
a = rel // 10_000_000
b = (rel // 100_000) % 100
c = (rel // 1_000) % 100
d = rel % 1_000
return f"{a}.{b}.{c}.{d}"
def get_xorg_version() -> str:
"""Get Xorg server version via X11 library."""
lib = ctypes.cdll.LoadLibrary("libX11.so.6")
lib.XOpenDisplay.argtypes = [c_char_p]
lib.XOpenDisplay.restype = c_void_p
lib.XCloseDisplay.argtypes = [c_void_p]
lib.XCloseDisplay.restype = c_int
lib.XServerVendor.argtypes = [c_void_p]
lib.XServerVendor.restype = c_char_p
lib.XVendorRelease.argtypes = [c_void_p]
lib.XVendorRelease.restype = c_int
display_name = __import__("os").environ.get("DISPLAY")
dpy = lib.XOpenDisplay(display_name.encode() if display_name else None)
if not dpy:
raise SystemExit("Failed to open X Display. Check DISPLAY.")
try:
release = lib.XVendorRelease(dpy)
return decode_xorg_release(release)
finally:
lib.XCloseDisplay(dpy)
+912
View File
@@ -0,0 +1,912 @@
"""Detail pages for PortProtonQt."""
import os
import shlex
from PySide6.QtWidgets import (
QWidget,
QLabel,
QHBoxLayout,
QVBoxLayout,
QFrame,
QMessageBox,
QScrollArea,
QBoxLayout,
)
from PySide6.QtCore import Qt, QUrl, QTimer
from PySide6.QtGui import QDesktopServices
from portprotonqt.detail_pages.widgets import (
create_scroll_area,
create_back_button,
create_content_frame,
setup_adaptive_layout,
create_cover_frame,
create_protondb_badge,
create_steam_badge,
create_egs_badge,
create_portproton_badge,
create_anticheat_badge,
create_details_widget,
)
from portprotonqt.detail_pages.utils import (
setup_image_loading,
validate_detail_page,
set_opacity_safe,
create_focus_helper,
toggle_favorite,
check_autoinstall_installed,
)
from portprotonqt.howlongtobeat_api import HowLongToBeat, GameEntry
from portprotonqt.config_utils import (
read_favorites,
get_portproton_start_command,
)
from portprotonqt.custom_widgets import AutoSizeButton, ClickableLabel, FlowLayout
from portprotonqt.localization import _
from portprotonqt.logger import get_logger
from portprotonqt.portproton_api import PortProtonAPI
from portprotonqt.downloader import Downloader
from portprotonqt.animations import DetailPageAnimations
from portprotonqt.debug_utils import DebugLogManager
from portprotonqt.steam_api import get_steam_compat_tool, get_steam_home, get_steam_libs, safe_vdf_load
logger = get_logger(__name__)
class DetailPageManager:
"""Manages detail pages for games."""
def __init__(self, main_window) -> None:
self.main_window = main_window
self._detail_page_active = False
self._current_detail_page: QWidget | None = None
self._exit_animation_in_progress = False
self._animations: dict = {}
self.portproton_api = PortProtonAPI(Downloader(max_workers=4))
self.debug_log_manager = DebugLogManager()
self._debug_log_button: AutoSizeButton | None = None
self._debug_log_timer = None
def openGameDetailPage(self, game_data: dict) -> None:
"""Open detailed game information page."""
detail_page = QWidget()
image_label = QLabel()
image_label.setFixedSize(300, 450)
self._setup_detail_page_common(detail_page, image_label, 0)
badges = self._create_game_badges(detail_page, game_data)
favorite_text = self._get_favorite_text(game_data["name"])
cover_frame = create_cover_frame(
parent=detail_page,
theme=self.main_window.theme,
image_label=image_label,
favorite_label_text=favorite_text,
on_favorite_click=lambda: self._on_favorite_click(game_data["name"]),
badges=badges,
)
game_info_layout = self._create_game_info_layout(game_data)
buttons_layout = self._create_game_buttons_layout(game_data)
details_widget = create_details_widget(
parent=detail_page,
main_window=self.main_window,
title=game_data["name"],
description=game_data["description"],
game_info_layout=game_info_layout,
controller_support=game_data.get("controller_support"),
buttons_layout=buttons_layout,
)
self._finalize_detail_page(
detail_page, cover_frame, details_widget, image_label,
game_data.get("exec_line", ""), game_data.get("cover_path")
)
def _get_favorite_text(self, name: str) -> str:
return "★" if name in read_favorites() else "☆"
def _create_game_badges(self, parent: QWidget, game_data: dict) -> list:
from portprotonqt.config_utils import read_display_filter
display_filter = read_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")
egs_visible = game_source == "epic" and display_filter in ("all", "favorites")
portproton_visible = game_source == "portproton" and display_filter in ("all", "favorites")
badges = []
protondb_badge = self._create_protondb_badge(parent, game_data)
if protondb_badge:
badges.append(protondb_badge)
if steam_visible:
badges.append(self._create_steam_badge(parent, appid))
if egs_visible:
badges.append(self._create_egs_badge(parent))
if portproton_visible:
badges.append(self._create_portproton_badge(parent, name, exec_line))
anticheat_badge = self._create_anticheat_badge(parent, game_data)
if anticheat_badge:
badges.append(anticheat_badge)
return badges
def _create_protondb_badge(self, parent: QWidget, game_data: dict) -> dict | None:
badge, visible = create_protondb_badge(
parent, game_data.get("protondb_tier", ""), game_data.get("appid", ""),
self.main_window
)
return {"label": badge, "visible": True} if badge and visible else None
def _create_steam_badge(self, parent: QWidget, appid: str) -> dict:
badge = create_steam_badge(parent, appid, self.main_window)
return {"label": badge, "visible": True}
def _create_egs_badge(self, parent: QWidget) -> dict:
badge = create_egs_badge(parent, self.main_window)
return {"label": badge, "visible": True}
def _create_portproton_badge(self, parent: QWidget, name: str, exec_line: str) -> dict:
badge = create_portproton_badge(parent, lambda: self.portproton_api.open_ppdb_page(name, exec_line), self.main_window)
return {"label": badge, "visible": True}
def _create_anticheat_badge(self, parent: QWidget, game_data: dict) -> dict | None:
badge, visible = create_anticheat_badge(
parent,
game_data.get("anticheat_status", ""),
game_data.get("name", ""),
game_data.get("anticheat_slug", ""),
self.main_window
)
return {"label": badge, "visible": True} if badge and visible else None
def _create_game_info_layout(self, game_data: dict) -> QVBoxLayout:
game_info_layout = QVBoxLayout()
game_info_layout.setSpacing(10)
first_row = self._create_playtime_row(
game_data.get("last_launch", ""), game_data.get("formatted_playtime", "")
)
game_info_layout.addLayout(first_row)
hltb_layout = QHBoxLayout()
hltb_layout.setSpacing(10)
self._setup_hltb_data(game_data.get("name", ""), hltb_layout, game_info_layout)
return game_info_layout
def _create_playtime_row(self, last_launch: str, formatted_playtime: str) -> QHBoxLayout:
"""Create first row with last launch and playtime."""
first_row = QHBoxLayout()
first_row.setSpacing(10)
last_launch_title = QLabel(_("LAST LAUNCH"))
last_launch_title.setStyleSheet(self.main_window.theme.LAST_LAUNCH_TITLE_STYLE)
last_launch_value = QLabel(last_launch)
last_launch_value.setStyleSheet(self.main_window.theme.LAST_LAUNCH_VALUE_STYLE)
playtime_title = QLabel(_("PLAY TIME"))
playtime_title.setStyleSheet(self.main_window.theme.PLAY_TIME_TITLE_STYLE)
playtime_value = QLabel(formatted_playtime)
playtime_value.setStyleSheet(self.main_window.theme.PLAY_TIME_VALUE_STYLE)
first_row.addWidget(last_launch_title)
first_row.addWidget(last_launch_value)
first_row.addSpacing(30)
first_row.addWidget(playtime_title)
first_row.addWidget(playtime_value)
return first_row
def _setup_hltb_data(
self, name: str, hltb_layout: QHBoxLayout, game_info_layout: QVBoxLayout
) -> None:
"""Setup HowLongToBeat data loading."""
hltb = HowLongToBeat(parent=self.main_window)
def on_hltb_results(results: list) -> None:
self._on_hltb_results(results, hltb, hltb_layout, game_info_layout)
hltb.searchCompleted.connect(on_hltb_results)
hltb.search_with_callback(name, case_sensitive=False)
def _on_hltb_results(
self,
results: list,
hltb: HowLongToBeat,
hltb_layout: QHBoxLayout,
game_info_layout: QVBoxLayout,
) -> None:
"""Handle HLTB search results."""
if not self._detail_page_active or not self._current_detail_page:
return
if not self._current_detail_page.parent() or self._current_detail_page.isHidden():
return
if not results:
return
game = results[0]
has_data = self._add_hltb_times(game, hltb, hltb_layout)
if has_data:
game_info_layout.addLayout(hltb_layout)
def _add_hltb_times(
self, game: GameEntry, hltb: HowLongToBeat, hltb_layout: QHBoxLayout
) -> bool:
"""Add HLTB time displays to layout."""
self._add_hltb_time_field(game, hltb, hltb_layout, "main_story", _("MAIN STORY"))
self._add_hltb_time_field(game, hltb, hltb_layout, "main_extra", _("MAIN + SIDES"))
self._add_hltb_time_field(game, hltb, hltb_layout, "completionist", _("COMPLETIONIST"))
return hltb_layout.count() > 0
def _add_hltb_time_field(
self,
game: GameEntry,
hltb: HowLongToBeat,
layout: QHBoxLayout,
field: str,
title_text: str,
) -> None:
"""Add single HLTB time field to layout."""
time_value = hltb.format_game_time(game, field)
if not time_value:
return
title_style = self.main_window.theme.LAST_LAUNCH_TITLE_STYLE
value_style = self.main_window.theme.LAST_LAUNCH_VALUE_STYLE
if field == "main_extra":
title_style = self.main_window.theme.PLAY_TIME_TITLE_STYLE
value_style = self.main_window.theme.PLAY_TIME_VALUE_STYLE
title = QLabel(title_text)
title.setStyleSheet(title_style)
value = QLabel(time_value)
value.setStyleSheet(value_style)
layout.addWidget(title)
layout.addWidget(value)
layout.addSpacing(30)
def _create_game_buttons_layout(self, game_data: dict) -> FlowLayout:
"""Create buttons layout for game detail page."""
buttons_layout = FlowLayout(center_rows=False)
buttons_layout.setContentsMargins(0, 0, 0, 0)
exec_line = game_data.get("exec_line", "")
game_source = game_data.get("game_source", "")
appid = game_data.get("appid", "")
game_name = game_data.get("name", "")
cover_path = game_data.get("cover_path", "")
current_exe = self._get_current_exe(exec_line)
play_button = self._create_play_button(exec_line, current_exe)
buttons_layout.addWidget(play_button)
if self._has_game_shortcut(game_name):
edit_button = self._make_action_button(
_("Edit Game"),
self.main_window.theme_manager.get_icon("edit"),
)
edit_button.clicked.connect(
lambda: self.main_window.context_menu_manager.edit_game_shortcut(
game_name, exec_line, cover_path
)
)
buttons_layout.addWidget(edit_button)
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"),
)
open_folder_button.clicked.connect(
lambda: self._open_steam_game_folder(str(appid))
)
buttons_layout.addWidget(open_folder_button)
else:
add_button = self._make_action_button(
_("Add Game"),
self.main_window.theme_manager.get_icon("addgame"),
)
add_button.clicked.connect(
lambda: self.main_window.openAddGameDialog(
self._get_file_from_exec(exec_line) or exec_line
)
)
buttons_layout.addWidget(add_button)
# Show settings button for PortProton games or Steam games using PortProtonQt
if str(game_source).lower() == "portproton":
self._add_portproton_buttons(buttons_layout, exec_line)
elif str(game_source).lower() == "steam" and appid:
try:
compat_tool = get_steam_compat_tool(int(appid))
if compat_tool == "PortProtonQt":
self._add_steam_settings_button(buttons_layout, exec_line, str(appid))
except (ValueError, TypeError):
pass
return buttons_layout
def _get_current_exe(self, exec_line: str) -> str | None:
"""Extract current executable from exec line."""
entry_exec_split = shlex.split(exec_line)
if not entry_exec_split:
return None
if entry_exec_split[0] == "env":
file_to_check = entry_exec_split[2] if len(entry_exec_split) >= 3 else None
elif entry_exec_split[0] == "flatpak":
file_to_check = entry_exec_split[3] if len(entry_exec_split) >= 4 else None
else:
file_to_check = entry_exec_split[0]
return os.path.basename(file_to_check) if file_to_check else None
def _create_play_button(self, exec_line: str, current_exe: str | None) -> AutoSizeButton:
"""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")
else:
text = _("Play")
icon = self.main_window.theme_manager.get_icon("play")
play_button = self._make_action_button(text, icon)
play_button.clicked.connect(lambda: self.main_window.toggleGame(exec_line, play_button))
return play_button
def _add_portproton_buttons(self, buttons_layout: FlowLayout, exec_line: str) -> None:
"""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_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_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)
self._debug_log_button = log_button
def _add_steam_settings_button(self, buttons_layout: FlowLayout, exec_line: str, appid: str) -> None:
"""Add only settings button for Steam games."""
# Create fake exe path in steam_scripts folder
portproton_location = self.main_window.portproton_location
if not portproton_location:
return
steam_scripts_dir = os.path.join(portproton_location, "steam_scripts")
os.makedirs(steam_scripts_dir, exist_ok=True)
fake_exe_path = os.path.join(steam_scripts_dir, f"{appid}.exe")
# Create empty file if it doesn't exist
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_button = self._make_action_button(_("Settings"), settings_icon)
settings_button.clicked.connect(
lambda: self.main_window.open_exe_settings(fake_exe_path, appid, "steam")
)
buttons_layout.addWidget(settings_button)
def _get_file_from_exec(self, exec_line: str) -> str | None:
"""Get file path from exec line."""
entry_exec_split = shlex.split(exec_line)
if not entry_exec_split:
return None
if entry_exec_split[0] == "env":
return entry_exec_split[2] if len(entry_exec_split) >= 3 else None
elif entry_exec_split[0] == "flatpak":
return entry_exec_split[3] if len(entry_exec_split) >= 4 else None
return entry_exec_split[0]
def _open_steam_game_folder(self, appid: str) -> None:
"""Open Steam game installation folder by appid."""
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}.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
def _has_game_shortcut(self, game_name: str) -> bool:
"""Check whether game has a desktop shortcut in PortProton location."""
context_menu_manager = getattr(self.main_window, "context_menu_manager", None)
if context_menu_manager is None:
return False
desktop_path = context_menu_manager._get_desktop_path(game_name)
return bool(desktop_path and os.path.exists(desktop_path))
def _make_action_button(self, text: str, icon) -> AutoSizeButton:
"""Create styled action button."""
button = AutoSizeButton(text, icon=icon)
button.setFixedHeight(40)
button.setMinimumWidth(120)
button.setStyleSheet(self.main_window.theme.PLAY_BUTTON_STYLE)
button.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
return button
def _setup_detail_page_common(
self, detail_page: QWidget, image_label: QLabel, return_tab_index: int
) -> None:
"""Common setup for all detail pages."""
self._detail_page_active = True
self._current_detail_page = detail_page
self._return_to_tab_index = return_tab_index
scroll_area, scroll_content, main_layout = create_scroll_area(
detail_page, self.main_window.theme
)
create_back_button(
main_layout,
self.main_window.theme,
self.main_window.theme_manager,
lambda: self.goBackDetailPage(detail_page),
)
content_frame, content_frame_layout = create_content_frame(
main_layout, self.main_window.theme
)
setup_adaptive_layout(detail_page, content_frame_layout)
self.main_window.stackedWidget.addWidget(detail_page)
self.main_window.stackedWidget.setCurrentWidget(detail_page)
self.main_window.currentDetailPage = detail_page
def _finalize_detail_page(
self,
detail_page: QWidget,
cover_frame: QWidget,
details_widget: QWidget,
image_label: QLabel,
exec_line: str,
cover_path: str | None,
) -> None:
"""Finalize detail page setup with animations and focus."""
content_frame_layout = self._get_content_frame_layout(detail_page)
if content_frame_layout:
content_frame_layout.addWidget(cover_frame)
content_frame_layout.addWidget(details_widget)
main_layout = self._get_main_layout(detail_page)
if main_layout:
main_layout.addStretch()
self.main_window.current_exec_line = exec_line
self._setup_detail_page_animation(detail_page, image_label, details_widget, cover_path)
def _setup_detail_page_animation(
self, detail_page: QWidget, image_label: QLabel, details_widget: QWidget, cover_path: str | None
) -> None:
"""Setup animation for detail page."""
detail_animations = DetailPageAnimations(self.main_window, self.main_window.theme)
play_button = self._find_play_button(details_widget)
def load_image_and_restore() -> None:
if not validate_detail_page(detail_page):
return
if not set_opacity_safe(detail_page):
return
setup_image_loading(
detail_page, image_label, cover_path, self.main_window
)
if play_button:
self._setup_focus_after_animation(detail_page, play_button)
def cleanup_animation() -> None:
if detail_page in self._animations:
del self._animations[detail_page]
detail_animations.animate_detail_page(
detail_page, load_image_and_restore, cleanup_animation
)
def _get_content_frame_layout(self, detail_page: QWidget) -> QBoxLayout | None:
"""Get content frame layout from detail page."""
scroll_area = detail_page.findChild(QScrollArea)
if not scroll_area:
return None
scroll_content = scroll_area.widget()
if not scroll_content or not scroll_content.layout():
return None
return self._find_content_layout_in_frame(scroll_content.layout())
def _find_content_layout_in_frame(self, layout) -> QBoxLayout | None:
"""Find content layout inside frame."""
for i in range(layout.count()):
item = layout.itemAt(i)
widget = item.widget() if item else None
if isinstance(widget, QFrame):
return self._find_box_layout_in_widget(widget)
return None
def _find_box_layout_in_widget(self, widget: QWidget) -> QBoxLayout | None:
"""Find QBoxLayout in widget children."""
for child in widget.children():
if isinstance(child, QBoxLayout):
return child
return None
def _get_main_layout(self, detail_page: QWidget) -> QVBoxLayout | None:
"""Get main layout from detail page."""
scroll_area = detail_page.findChild(QScrollArea)
if not scroll_area:
return None
scroll_content = scroll_area.widget()
if not scroll_content:
return None
layout = scroll_content.layout()
return layout if isinstance(layout, QVBoxLayout) else None
def _setup_focus_after_animation(self, detail_page: QWidget, play_button: QWidget) -> None:
"""Setup focus on play button after animation."""
focus_helper = create_focus_helper(
detail_page, self.main_window, play_button, self.main_window.stackedWidget
)
QTimer.singleShot(50, focus_helper)
def _find_play_button(self, details_widget: QWidget) -> QWidget | None:
"""Find play button in details widget."""
for child in details_widget.children():
if isinstance(child, AutoSizeButton) and self._is_action_button_text(child.text()):
return child
return None
def _is_action_button_text(self, text: str) -> bool:
"""Check if button text is Play or Stop."""
return text in (_("Play"), _("Stop"))
def _on_favorite_click(self, name: str) -> None:
"""Handle favorite toggle click."""
toggle_favorite(name, self.main_window)
def openAutoInstallDetailPage(self, game_data: dict) -> None:
"""Open minimal detail page for auto-install games."""
detail_page = QWidget()
image_label = QLabel()
image_label.setFixedSize(300, 450)
self._setup_detail_page_common(detail_page, image_label, 1)
exec_line = game_data.get("exec_line", "")
script_name = self._extract_script_name(exec_line)
description = self._get_enhanced_description(
script_name, game_data.get("description", "")
)
cover_frame = create_cover_frame(
parent=detail_page,
theme=self.main_window.theme,
image_label=image_label,
)
buttons_layout = FlowLayout(center_rows=False)
buttons_layout.setContentsMargins(0, 0, 0, 0)
install_button = self._create_autoinstall_buttons_layout(
script_name, game_data.get("name", ""), buttons_layout
)
details_widget = create_details_widget(
parent=detail_page,
main_window=self.main_window,
title=game_data.get("name", ""),
description=description,
buttons_layout=buttons_layout,
)
self._finalize_autoinstall_page(detail_page, cover_frame, details_widget, image_label, game_data.get("cover_path"), install_button)
def _extract_script_name(self, exec_line: str) -> str:
"""Extract script name from exec line."""
if exec_line and exec_line.startswith("autoinstall:"):
return exec_line[11:].lstrip(":").strip()
return ""
def _get_enhanced_description(self, script_name: str, description: str) -> str:
"""Get enhanced description from metadata if available."""
if not script_name:
return description
import locale
try:
current_locale = locale.getlocale()[0] or "en"
except Exception as e:
logger.debug("Failed to get current locale: %s", e)
current_locale = "en"
lang_code = "ru" if current_locale and "ru" in current_locale.lower() else "en"
metadata_description = self.portproton_api.get_autoinstall_description(
script_name, lang_code
)
return metadata_description if metadata_description else description
def _create_autoinstall_buttons_layout(
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.clicked.connect(lambda: self.main_window.launch_autoinstall(script_name))
buttons_layout.addWidget(install_button)
self._check_install_status(script_name, name, install_button)
return install_button
def _check_install_status(
self, script_name: str, name: str, install_button: AutoSizeButton
) -> None:
"""Check install status asynchronously and update button."""
def on_result(is_installed: bool) -> None:
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)
if icon:
install_button.setIcon(icon)
# Update text without changing button size drastically
install_button.setText(text)
check_autoinstall_installed(
script_name, name, self.main_window.portproton_location, callback=on_result
)
def _finalize_autoinstall_page(
self,
detail_page: QWidget,
cover_frame: QWidget,
details_widget: QWidget,
image_label: QLabel,
cover_path: str | None,
install_button: AutoSizeButton,
) -> None:
"""Finalize auto-install detail page."""
content_frame_layout = self._get_content_frame_layout(detail_page)
if content_frame_layout:
content_frame_layout.addWidget(cover_frame)
content_frame_layout.addWidget(details_widget)
main_layout = self._get_main_layout(detail_page)
if main_layout:
main_layout.addStretch()
self._setup_autoinstall_animation(detail_page, image_label, cover_path, install_button)
def _setup_autoinstall_animation(self, detail_page: QWidget, image_label: QLabel, cover_path: str | None, install_button: AutoSizeButton) -> None:
"""Setup animation for auto-install page."""
def load_image_and_restore() -> None:
if not validate_detail_page(detail_page):
return
if not set_opacity_safe(detail_page):
return
setup_image_loading(
detail_page, image_label, cover_path, self.main_window
)
self._setup_autoinstall_focus(detail_page, install_button)
def cleanup_animation() -> None:
if detail_page in self._animations:
del self._animations[detail_page]
detail_animations = DetailPageAnimations(self.main_window, self.main_window.theme)
detail_animations.animate_detail_page(
detail_page, load_image_and_restore, cleanup_animation
)
def _setup_autoinstall_focus(self, detail_page: QWidget, install_button: AutoSizeButton) -> None:
"""Setup focus on install button after animation."""
focus_helper = create_focus_helper(
detail_page, self.main_window, install_button, self.main_window.stackedWidget
)
QTimer.singleShot(50, focus_helper)
def toggleFavoriteInDetailPage(self, game_name: str, label: ClickableLabel) -> None:
"""Toggle favorite status from detail page."""
favorite_text = toggle_favorite(game_name, self.main_window)
label.setText(favorite_text)
def toggleDebugLog(self, exe_path: str | None, button: AutoSizeButton) -> None:
"""Toggle debug log creation."""
if self.debug_log_manager.is_running:
self._stop_debug_log(button)
else:
self._start_debug_log(exe_path, button)
def _stop_debug_log(self, button: AutoSizeButton) -> None:
"""Stop debug logging and save log."""
self._stopDebugTimer()
log_file = self.debug_log_manager.stop()
button.setText(_("Create Log"))
icon = self.main_window.theme_manager.get_icon("edit")
if icon:
button.setIcon(icon)
if log_file:
self._show_log_saved_dialog(log_file)
def _start_debug_log(self, exe_path: str | None, button: AutoSizeButton) -> None:
"""Start debug logging session."""
if exe_path is None:
return
resolved_exe_path = self.main_window.resolve_launch_file_path(exe_path)
if resolved_exe_path is None:
return
start_command = get_portproton_start_command()
if not start_command:
return
if self.debug_log_manager.start(resolved_exe_path, start_command):
button.setText(_("Stop Log"))
icon = self.main_window.theme_manager.get_icon("stop")
if icon:
button.setIcon(icon)
self._startDebugTimer()
else:
QMessageBox.warning(
self.main_window,
_("Error"),
_("Failed to start debug session"),
)
def _show_log_saved_dialog(self, log_file: str) -> None:
"""Show dialog with log file location."""
msg_box = QMessageBox(self.main_window)
msg_box.setWindowTitle(_("Log Saved"))
msg_box.setText(_("Debug log saved to:") + f"\n{log_file}")
msg_box.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Open)
msg_box.setButtonText(QMessageBox.StandardButton.Open, _("Open Folder"))
result = msg_box.exec()
if result == QMessageBox.StandardButton.Open:
log_folder = os.path.dirname(log_file)
try:
QDesktopServices.openUrl(QUrl.fromLocalFile(log_folder))
except Exception as e:
logger.error("Failed to open folder %s: %s", log_folder, e)
def _startDebugTimer(self) -> None:
"""Start timer to periodically read debug output."""
if self._debug_log_timer is not None:
self._debug_log_timer.stop()
self._debug_log_timer = QTimer(self.main_window)
self._debug_log_timer.timeout.connect(self._onDebugTimerTick)
self._debug_log_timer.start(500)
def _stopDebugTimer(self) -> None:
"""Stop debug output timer."""
if self._debug_log_timer is not None:
self._debug_log_timer.stop()
self._debug_log_timer.deleteLater()
self._debug_log_timer = None
def _onDebugTimerTick(self) -> None:
"""Handle debug timer tick."""
if not self.debug_log_manager.check_running():
self._stopDebugTimer()
log_file = self.debug_log_manager.stop()
self._update_debug_log_button(log_file)
def _update_debug_log_button(self, log_file: str | None) -> None:
"""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")
if icon:
self._debug_log_button.setIcon(icon)
if log_file:
logger.info("Debug session ended. Log saved to %s", log_file)
self._show_log_saved_dialog(log_file)
def goBackDetailPage(self, page: QWidget | None) -> None:
"""Navigate back from detail page."""
if page is None or not self._is_valid_page(page) or self._exit_animation_in_progress:
return
self._exit_animation_in_progress = True
self._detail_page_active = False
self._current_detail_page = None
def cleanup() -> None:
self._cleanup_page(page)
if page and not page.isHidden() and page.parent() is not None:
detail_animations = DetailPageAnimations(self.main_window, self.main_window.theme)
detail_animations.animate_detail_page_exit(page, cleanup)
else:
logger.warning("Detail page not valid, bypassing animation")
self._exit_animation_in_progress = False
cleanup()
def _is_valid_page(self, page: QWidget) -> bool:
"""Check if page is valid and current."""
return page == self.main_window.stackedWidget.currentWidget()
def _cleanup_page(self, page: QWidget) -> None:
"""Clean up detail page and return to tab."""
try:
self._cleanup_animations(page)
if not self._page_in_stacked(page):
logger.debug("Page not found in stacked widget")
self._finalize_cleanup()
return
self.main_window.stackedWidget.removeWidget(page)
return_tab_index = getattr(self, "_return_to_tab_index", 0)
self.main_window.stackedWidget.setCurrentIndex(return_tab_index)
self._refresh_tab_content(return_tab_index)
self._finalize_cleanup()
except RuntimeError:
logger.debug("Detail page already deleted during cleanup")
self._exit_animation_in_progress = False
except Exception as e:
logger.error("Unexpected error in cleanup: %s", e, exc_info=True)
self._exit_animation_in_progress = False
def _cleanup_animations(self, page: QWidget) -> None:
"""Clean up animations for page."""
if not hasattr(self, "_animations") or page not in self._animations:
return
try:
animation = self._animations[page]
self._stop_animation_if_running(animation)
del self._animations[page]
except (KeyError, RuntimeError):
pass
def _stop_animation_if_running(self, animation) -> None:
if hasattr(animation, "state") and animation.state() == 1:
animation.stop()
def _page_in_stacked(self, page: QWidget) -> bool:
for i in range(self.main_window.stackedWidget.count()):
if self.main_window.stackedWidget.widget(i) is page:
return True
return False
def _refresh_tab_content(self, tab_index: int) -> None:
if tab_index == 0 and hasattr(self.main_window, "game_library_manager"):
if self.main_window.launch_exe and not self.main_window.games:
QTimer.singleShot(10, lambda: self.main_window.loadGames(force_load=True))
else:
QTimer.singleShot(10, lambda: self.main_window.game_library_manager.update_game_grid())
elif tab_index == 1 and hasattr(self.main_window, "autoInstallContainer"):
QTimer.singleShot(10, lambda: self.main_window.autoInstallContainer.updateGeometry())
if hasattr(self.main_window, "autoInstallContainerLayout"):
QTimer.singleShot(15, lambda: self.main_window.autoInstallContainerLayout.update())
def _finalize_cleanup(self) -> None:
self.main_window.currentDetailPage = None
self.main_window.current_exec_line = None
self.main_window.current_play_button = None
self._exit_animation_in_progress = False
+268
View File
@@ -0,0 +1,268 @@
"""Detail page utilities for PortProtonQt."""
import os
from collections.abc import Callable
from PySide6.QtWidgets import QWidget, QApplication, QLabel
from PySide6.QtCore import QTimer, Qt
from PySide6.QtGui import QPixmap
from portprotonqt.image_utils import load_pixmap_async, round_corners
from portprotonqt.config_utils import read_favorites, save_favorites
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
def setup_image_loading(
detail_page: QWidget,
image_label: QLabel,
cover_path: str | None,
main_window,
) -> None:
"""Setup async image loading with palette-based stylesheet."""
if cover_path:
load_pixmap_async(cover_path, 300, 450, lambda pixmap: _on_pixmap_ready(
pixmap, detail_page, image_label, main_window
))
else:
_apply_no_cover_style(detail_page, main_window.theme)
def _on_pixmap_ready(pixmap: QPixmap, detail_page: QWidget, image_label: QLabel, main_window) -> None:
"""Handle pixmap loaded callback."""
if not _is_detail_page_valid(detail_page):
return
try:
rounded = round_corners(pixmap, 10)
image_label.setPixmap(rounded)
logger.debug("Pixmap set for imageLabel")
_setup_palette_stylesheet(detail_page, pixmap, main_window)
except RuntimeError:
logger.warning("Detail page already deleted, skipping pixmap update")
def _setup_palette_stylesheet(detail_page: QWidget, pixmap: QPixmap | None, main_window) -> None:
"""Setup palette-based stylesheet after image load."""
if pixmap is None:
return
def on_palette_ready(palette: list) -> None:
_on_palette_ready(palette, detail_page, main_window)
main_window.getColorPalette_from_pixmap(pixmap, num_colors=5, callback=on_palette_ready)
def _on_palette_ready(palette: list, detail_page: QWidget, main_window) -> None:
"""Handle palette ready callback."""
if not _is_detail_page_valid(detail_page):
return
_apply_palette_stylesheet(detail_page, palette, main_window)
def _apply_palette_stylesheet(detail_page: QWidget, palette: list, main_window) -> None:
"""Apply palette-based stylesheet to detail page."""
try:
dark_palette = [
main_window.darkenColor(color, factor=200) for color in palette
]
stops = ",\n".join(
[
f"stop:{i/(len(dark_palette)-1):.2f} {dark_palette[i].name()}"
for i in range(len(dark_palette))
]
)
detail_page.setStyleSheet(main_window.theme.detail_page_style(stops))
detail_page.update()
logger.debug("Stylesheet updated with palette")
except RuntimeError:
logger.warning("Detail page already deleted, skipping palette update")
def _apply_no_cover_style(detail_page: QWidget, theme) -> None:
"""Apply no-cover stylesheet to detail page."""
try:
detail_page.setStyleSheet(theme.DETAIL_PAGE_NO_COVER_STYLE)
detail_page.update()
except RuntimeError:
logger.warning("Detail page already deleted, skipping no-cover stylesheet update")
def _is_detail_page_valid(detail_page: QWidget) -> bool:
"""Check if detail page is still valid and visible."""
return (
detail_page is not None
and not detail_page.isHidden()
and detail_page.parent() is not None
)
def validate_detail_page(detail_page: QWidget) -> bool:
"""Validate detail page before operations."""
if not _is_detail_page_valid(detail_page):
logger.warning("Detail page is None, hidden, or no longer valid")
return False
return True
def set_opacity_safe(detail_page: QWidget) -> bool:
"""Safely set window opacity on detail page."""
try:
detail_page.setWindowOpacity(1.0)
return True
except RuntimeError:
logger.warning("Detail page is None, hidden, or no longer valid, skipping opacity set")
return False
def create_focus_helper(
detail_page: QWidget,
main_window,
button: QWidget,
stacked_widget,
) -> Callable[[], None]:
"""Create focus helper function for detail page buttons."""
def try_set_focus() -> None:
if not (button and not button.isHidden()):
return
stacked_widget.setCurrentWidget(detail_page)
detail_page.setFocus(Qt.FocusReason.OtherFocusReason)
button.setFocus(Qt.FocusReason.OtherFocusReason)
button.update()
detail_page.raise_()
main_window.activateWindow()
if button.hasFocus():
logger.debug("Button successfully received focus")
else:
logger.debug("Retrying focus...")
QTimer.singleShot(20, retry_focus)
def retry_focus() -> None:
if not (button and not button.isHidden() and not button.hasFocus()):
return
QApplication.processEvents()
main_window.activateWindow()
stacked_widget.setCurrentWidget(detail_page)
detail_page.raise_()
button.setFocus(Qt.FocusReason.OtherFocusReason)
button.update()
if not button.hasFocus():
logger.debug("Final retry...")
button.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
button.setFocus(Qt.FocusReason.OtherFocusReason)
QApplication.processEvents()
if button.hasFocus():
logger.debug("Button received focus after final retry")
else:
logger.debug("Button still doesn't have focus")
return try_set_focus
def toggle_favorite(game_name: str, main_window) -> str:
"""Toggle favorite status for a game."""
favorites = read_favorites()
if game_name in favorites:
favorites.remove(game_name)
favorite_text = "☆"
else:
favorites.append(game_name)
favorite_text = "★"
save_favorites(favorites)
if hasattr(main_window, "game_library_manager"):
main_window.game_library_manager.update_game_grid()
return favorite_text
def check_autoinstall_installed(
script_name: str,
game_name: str,
portproton_location: str | None,
callback: Callable[..., None] | None = None,
) -> bool | None:
"""Check if auto-install game is already installed.
If callback is provided, runs asynchronously and calls callback with result.
If callback is None, runs synchronously and returns result.
"""
if not portproton_location:
if callback:
callback(False)
return None
return False
if callback:
_check_autoinstall_installed_async(
script_name, game_name, portproton_location, callback
)
return None
return _check_autoinstall_installed_sync(
script_name, game_name, portproton_location
)
def _check_autoinstall_installed_sync(
script_name: str,
game_name: str,
portproton_location: str,
) -> bool:
"""Synchronous check for installed autoinstall game."""
try:
desktop_files = os.listdir(portproton_location)
except (OSError, AttributeError):
return False
for file in desktop_files:
if _check_desktop_file(file, portproton_location, script_name, game_name):
return True
return False
def _check_autoinstall_installed_async(
script_name: str,
game_name: str,
portproton_location: str,
callback: Callable[[bool], None],
) -> None:
"""Asynchronous check for installed autoinstall game."""
from threading import Thread
from PySide6.QtCore import QTimer
def worker() -> None:
result = _check_autoinstall_installed_sync(
script_name, game_name, portproton_location
)
QTimer.singleShot(0, lambda: callback(result))
thread = Thread(target=worker, daemon=True)
thread.start()
def _check_desktop_file(
filename: str,
location: str,
script_name: str,
game_name: str,
) -> bool:
"""Check if desktop file contains script or game name."""
if not filename.endswith(".desktop"):
return False
try:
with open(os.path.join(location, filename), encoding="utf-8") as f:
content = f.read()
return (
script_name.lower() in content.lower()
or game_name.lower() in content.lower()
)
except (OSError, UnicodeDecodeError):
return False
+391
View File
@@ -0,0 +1,391 @@
"""Detail page widgets for PortProtonQt."""
from collections.abc import Callable
from PySide6.QtWidgets import (
QFrame,
QGraphicsDropShadowEffect,
QVBoxLayout,
QLabel,
QWidget,
QScrollArea,
QBoxLayout,
QSizePolicy,
QScroller,
QLayout,
)
from PySide6.QtCore import Qt, QUrl
from PySide6.QtGui import QColor, QDesktopServices
from portprotonqt.custom_widgets import ClickableLabel, AutoSizeButton
from portprotonqt.game_card import GameCard
from portprotonqt.localization import _
from portprotonqt.config_utils import read_badge_view_mode
COVER_WIDTH = 300
COVER_HEIGHT = 450
BADGE_WIDTH = int(COVER_WIDTH * 2 / 3)
BADGE_ICON_SIZE = 16
BADGE_COMPACT_WIDTH = BADGE_ICON_SIZE + 14
BADGE_RIGHT_MARGIN = 8
BADGE_SPACING = 5
BADGE_TOP_Y = 10
def _apply_badge_view_mode(badge: ClickableLabel) -> None:
"""Apply configured badge view mode."""
mode = read_badge_view_mode()
compact_mode = mode == "compact"
badge.setCompactMode(compact_mode, BADGE_COMPACT_WIDTH, BADGE_WIDTH)
badge.setVisible(mode != "hidden")
def create_scroll_area(parent: QWidget, theme) -> tuple[QScrollArea, QWidget, QVBoxLayout]:
"""Create scroll area with content widget and main layout."""
page_layout = QVBoxLayout(parent)
page_layout.setContentsMargins(0, 0, 0, 0)
page_layout.setSpacing(0)
scroll_area = QScrollArea()
scroll_area.setWidgetResizable(True)
scroll_area.setFrameShape(QFrame.Shape.NoFrame)
scroll_area.setStyleSheet(theme.SCROLL_STYLE + theme.TRANSPARENT_BACKGROUND_STYLE)
QScroller.grabGesture(scroll_area.viewport(), QScroller.ScrollerGestureType.LeftMouseButtonGesture)
scroll_content = QWidget()
scroll_area.setWidget(scroll_content)
page_layout.addWidget(scroll_area)
main_layout = QVBoxLayout(scroll_content)
main_layout.setContentsMargins(30, 30, 30, 30)
main_layout.setSpacing(20)
return scroll_area, scroll_content, main_layout
def create_back_button(
parent_layout: QVBoxLayout,
theme,
theme_manager,
on_click: Callable[..., None],
) -> AutoSizeButton:
"""Create back button with standard styling."""
back_button = AutoSizeButton(_("Back"), icon=theme_manager.get_icon("back"))
back_button.setFixedWidth(100)
back_button.setStyleSheet(theme.ADDGAME_BACK_BUTTON_STYLE)
back_button.clicked.connect(on_click)
parent_layout.addWidget(back_button, alignment=Qt.AlignmentFlag.AlignLeft)
return back_button
def create_content_frame(
parent_layout: QVBoxLayout,
theme,
) -> tuple[QFrame, QBoxLayout]:
"""Create content frame with adaptive layout."""
content_frame = QFrame()
content_frame.setStyleSheet(theme.DETAIL_CONTENT_FRAME_STYLE)
content_frame_layout = QBoxLayout(QBoxLayout.Direction.LeftToRight, content_frame)
content_frame_layout.setContentsMargins(20, 20, 20, 20)
content_frame_layout.setSpacing(40)
parent_layout.addWidget(content_frame)
return content_frame, content_frame_layout
def setup_adaptive_layout(
detail_page: QWidget,
content_frame_layout: QBoxLayout,
) -> None:
"""Setup adaptive layout switching on resize."""
def on_detail_page_resize(event) -> None:
if detail_page.width() < 900:
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
)
QWidget.resizeEvent(detail_page, event)
detail_page.resizeEvent = on_detail_page_resize
def create_cover_frame(
parent: QWidget,
theme,
image_label: QLabel,
favorite_label_text: str | None = None,
on_favorite_click: Callable[..., None] | None = None,
badges: list | None = None,
) -> QFrame:
"""Create cover frame with image, favorite icon, and badges."""
cover_frame = QFrame()
cover_frame.setFixedSize(COVER_WIDTH, COVER_HEIGHT)
cover_frame.setStyleSheet(theme.COVER_FRAME_STYLE)
_setup_cover_shadow(cover_frame, theme)
cover_layout = QVBoxLayout(cover_frame)
cover_layout.setContentsMargins(0, 0, 0, 0)
cover_layout.addWidget(image_label)
if favorite_label_text and on_favorite_click:
_add_favorite_label(cover_frame, favorite_label_text, theme, on_favorite_click)
if badges:
_position_badges(cover_frame, badges)
return cover_frame
def _setup_cover_shadow(cover_frame: QFrame, theme) -> None:
"""Add shadow effect to cover frame."""
shadow = QGraphicsDropShadowEffect(cover_frame)
shadow.setBlurRadius(theme.shadow_blur_radius)
shadow.setColor(QColor(theme.color_shadow_detail))
shadow.setOffset(*theme.shadow_offset)
cover_frame.setGraphicsEffect(shadow)
def _add_favorite_label(
cover_frame: QFrame, favorite_label_text: str, theme, on_favorite_click: Callable[[], None] | None = None
) -> None:
"""Add favorite label to cover frame."""
favorite_label = ClickableLabel(cover_frame)
favorite_label.setFixedSize(*theme.favoriteLabelSize)
favorite_label.setStyleSheet(theme.FAVORITE_LABEL_STYLE)
favorite_label.setText(favorite_label_text)
if on_favorite_click:
favorite_label.clicked.connect(on_favorite_click)
favorite_label.move(8, 8)
favorite_label.raise_()
def _position_badges(cover_frame: QFrame, badges: list) -> None:
"""Position badges on cover frame."""
badge_y_positions = []
for badge_data in badges:
badge = badge_data["label"]
# Reparent badge to cover_frame
badge.setParent(cover_frame)
badge.setCompactRelayoutCallback(lambda: _position_badges(cover_frame, badges))
badge_x = COVER_WIDTH - badge.width() - BADGE_RIGHT_MARGIN
if badge_y_positions:
badge_y = badge_y_positions[-1] + BADGE_SPACING
else:
badge_y = BADGE_TOP_Y
badge.move(badge_x, badge_y)
badge_y_positions.append(badge_y + badge.height())
badge.raise_()
def create_protondb_badge(
parent: QWidget,
protondb_tier: str,
appid: str,
main_window,
) -> tuple[ClickableLabel | None, bool]:
"""Create ProtonDB badge."""
protondb_text = GameCard.getProtonDBText(protondb_tier)
if not protondb_text:
return None, False
icon_filename = GameCard.getProtonDBIconFilename(protondb_tier)
icon = main_window.theme_manager.get_icon(icon_filename, main_window.current_theme_name)
badge = ClickableLabel(
protondb_text,
icon=icon,
parent=parent,
icon_size=BADGE_ICON_SIZE,
icon_space=3,
)
badge.setStyleSheet(main_window.theme.get_protondb_badge_style(protondb_tier))
_apply_badge_view_mode(badge)
badge.clicked.connect(
lambda: QDesktopServices.openUrl(QUrl(f"https://www.protondb.com/app/{appid}"))
)
return badge, True
def create_steam_badge(
parent: QWidget,
appid: str,
main_window,
) -> ClickableLabel:
"""Create Steam badge."""
steam_icon = main_window.theme_manager.get_icon("steam")
badge = ClickableLabel(
"Steam",
icon=steam_icon,
parent=parent,
icon_size=BADGE_ICON_SIZE,
icon_space=5,
)
badge.setStyleSheet(main_window.theme.STEAM_BADGE_STYLE)
_apply_badge_view_mode(badge)
badge.clicked.connect(
lambda: QDesktopServices.openUrl(QUrl(f"https://steamcommunity.com/app/{appid}"))
)
return badge
def create_egs_badge(
parent: QWidget,
main_window,
) -> ClickableLabel:
"""Create Epic Games Store badge."""
egs_icon = main_window.theme_manager.get_icon("epic_games")
badge = ClickableLabel(
"Epic Games",
icon=egs_icon,
parent=parent,
icon_size=BADGE_ICON_SIZE,
icon_space=5,
change_cursor=False,
)
badge.setStyleSheet(main_window.theme.STEAM_BADGE_STYLE)
_apply_badge_view_mode(badge)
return badge
def create_portproton_badge(
parent: QWidget,
on_click: Callable[..., None],
main_window,
) -> ClickableLabel:
"""Create PortProton badge."""
portproton_icon = main_window.theme_manager.get_icon("portproton")
badge = ClickableLabel(
"PortProton",
icon=portproton_icon,
parent=parent,
icon_size=BADGE_ICON_SIZE,
icon_space=5,
)
badge.setStyleSheet(main_window.theme.STEAM_BADGE_STYLE)
_apply_badge_view_mode(badge)
badge.clicked.connect(on_click)
return badge
def create_anticheat_badge(
parent: QWidget,
anticheat_status: str,
game_name: str,
anticheat_slug: str,
main_window,
) -> tuple[ClickableLabel | None, bool]:
"""Create WeAntiCheatYet badge."""
anticheat_text = GameCard.getAntiCheatText(anticheat_status)
if not anticheat_text:
return None, False
icon_filename = GameCard.getAntiCheatIconFilename(anticheat_status)
icon = main_window.theme_manager.get_icon(icon_filename, main_window.current_theme_name)
badge = ClickableLabel(
anticheat_text,
icon=icon,
parent=parent,
icon_size=BADGE_ICON_SIZE,
icon_space=3,
)
badge.setStyleSheet(main_window.theme.get_anticheat_badge_style(anticheat_status))
_apply_badge_view_mode(badge)
if anticheat_slug:
anticheat_url = f"https://areweanticheatyet.com/game/{anticheat_slug}"
else:
anticheat_url = f"https://areweanticheatyet.com/game/{game_name.lower().replace(' ', '-')}"
badge.clicked.connect(
lambda: QDesktopServices.openUrl(
QUrl(anticheat_url)
)
)
return badge, True
def create_details_widget(
parent: QWidget,
main_window,
title: str,
description: str,
game_info_layout: QVBoxLayout | None = None,
controller_support: str | None = None,
buttons_layout: QLayout | None = None,
) -> QWidget:
"""Create details widget with title, description, and optional content."""
details_widget = QWidget()
details_widget.setStyleSheet(main_window.theme.DETAILS_WIDGET_STYLE)
details_widget.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred
)
details_layout = QVBoxLayout(details_widget)
details_layout.setContentsMargins(20, 20, 20, 20)
details_layout.setSpacing(15)
_add_details_header(details_layout, main_window.theme, title)
_add_details_description(details_layout, main_window.theme, description)
if game_info_layout:
details_layout.addLayout(game_info_layout)
if controller_support:
_add_controller_support(details_layout, main_window.theme, controller_support)
details_layout.addStretch(1)
if buttons_layout:
details_layout.addLayout(buttons_layout)
return details_widget
def _add_details_header(layout: QVBoxLayout, theme, title: str) -> None:
"""Add title and divider line to details layout."""
title_label = QLabel(title)
title_label.setStyleSheet(theme.DETAIL_PAGE_TITLE_STYLE)
layout.addWidget(title_label)
line = QFrame()
line.setFrameShape(QFrame.Shape.HLine)
line.setStyleSheet(theme.DETAIL_PAGE_LINE_STYLE)
layout.addWidget(line)
def _add_details_description(layout: QVBoxLayout, theme, description: str) -> None:
"""Add description label to details layout."""
desc_label = QLabel(description)
desc_label.setWordWrap(True)
desc_label.setStyleSheet(theme.DETAIL_PAGE_DESC_STYLE)
layout.addWidget(desc_label)
def _add_controller_support(layout: QVBoxLayout, theme, controller_support: str) -> None:
"""Add controller support label to details layout."""
cs = controller_support.lower()
translated_cs = _get_controller_support_text(cs)
gamepad_label = QLabel(_("Gamepad Support: {0}").format(translated_cs))
gamepad_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
gamepad_label.setStyleSheet(theme.GAMEPAD_SUPPORT_VALUE_STYLE)
layout.addWidget(gamepad_label, alignment=Qt.AlignmentFlag.AlignCenter)
def _get_controller_support_text(cs: str) -> str:
"""Get translated controller support text."""
if cs == "full":
return _("full")
elif cs == "partial":
return _("partial")
elif cs == "none":
return _("none")
return ""
Loaded 100 of 275 files, more files were not shown because too many files have changed in this diff. Show more