Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7a97b4e191
|
No files matched your search
@@ -22,7 +22,7 @@ jobs:
|
||||
name: Check code
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: archlinux:base-devel@sha256:624bdc7fc6615155d67bc34cf7146c0c9fd0e3c92943977da63a630e4ca49c30
|
||||
image: archlinux:base-devel@sha256:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1
|
||||
steps:
|
||||
- name: Configure Arch mirrors
|
||||
run: |
|
||||
|
||||
@@ -80,7 +80,7 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.appimage == 'true' || github.event_name == 'workflow_dispatch'
|
||||
container:
|
||||
image: archlinux:base-devel@sha256:624bdc7fc6615155d67bc34cf7146c0c9fd0e3c92943977da63a630e4ca49c30
|
||||
image: archlinux:base-devel@sha256:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1
|
||||
options: --privileged --device /dev/fuse
|
||||
steps:
|
||||
- name: Configure Arch mirrors
|
||||
@@ -210,7 +210,7 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.arch == 'true' || github.event_name == 'workflow_dispatch'
|
||||
container:
|
||||
image: archlinux:base-devel@sha256:624bdc7fc6615155d67bc34cf7146c0c9fd0e3c92943977da63a630e4ca49c30
|
||||
image: archlinux:base-devel@sha256:3cbf69d2d5958d6a294f3722c5668e6187c4df8e00fa27f72352f0bf83e495e1
|
||||
|
||||
steps:
|
||||
- name: Configure Arch mirrors
|
||||
@@ -296,7 +296,7 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.debian == 'true' || github.event_name == 'workflow_dispatch'
|
||||
container:
|
||||
image: debian:trixie-20261027@sha256:2dc419c6d7fe3dad0a2f9fd469c34cc90b0f9ba642d8fde837fe3d7d34a0e7f1
|
||||
image: debian:trixie-20261005@sha256:913f6706df59a68922d1dd08f78c2476560a8d367897200a6005b00e5f67c2d5
|
||||
options: --privileged
|
||||
|
||||
steps:
|
||||
|
||||
@@ -7,8 +7,6 @@
|
||||
|
||||
### Added
|
||||
|
||||
- Добавлена поддержка нативных Linux-игр: библиотека обнаруживает игры по ярлыкам `.desktop`, а через диалог добавления игры можно выбрать исполняемый файл Linux
|
||||
- Добавлена системная экранная клавиатура с управлением геймпадом: её можно открыть из меню в системном трее или сочетанием `Start` + верхняя кнопка геймпада (`Y` на Xbox, `△` на PlayStation)
|
||||
- В Run After / Wrapper добавлена поддержка `%command%` для передачи команды игры обёртке, например `mako-launch %command%`, без повторного запуска игры
|
||||
- Добавлено отслеживание запуска Steam-игр на странице игры
|
||||
- Добавлен CLI для получения локальных данных библиотеки
|
||||
@@ -26,7 +24,6 @@
|
||||
|
||||
### Changed
|
||||
|
||||
- Интерфейс меньше подвисает: в тесте на 100 играх задержка реакции при чтении данных из кеша снизилась на 93% (с 10,6 до 0,7 мс)
|
||||
- Для игр GOG и EGS папка установки выбирается до добавления в очередь
|
||||
- Ускорено получение списка DLC для GOG
|
||||
- В Run After / Wrapper выбор файлов ограничен `.exe` и файлами с правом исполнения в Linux
|
||||
@@ -47,14 +44,6 @@
|
||||
|
||||
### Fixed
|
||||
|
||||
- Пустые файлы в кеше загрузчика больше не считаются успешно загруженными
|
||||
- При очистке библиотеки освобождаются ссылки на удалённые карточки, которые были в фокусе или под курсором
|
||||
- Исправлено неполное меню PortProtonQt в системном трее Budgie
|
||||
- Обложки заполняют отведённую область без растягивания
|
||||
- Исправлена загрузка оценок времени прохождения с HowLongToBeat в карточках игр
|
||||
- При нажатии вниз на D-pad с верхней панели библиотеки фокус переходит на первую карточку верхнего ряда, а не перескакивает на нижние ряды
|
||||
- В карточках игр GOG отображается краткое описание без рекламы, баннеров и списков особенностей
|
||||
- Недокачанные JPEG-обложки больше не попадают в кэш
|
||||
- Исправлена фильтрация видеокарт DXVK и VKD3D при расхождении нативного имени GPU с именем Wine
|
||||
- Запросы установки других игр GOG и EGS во время получения списка DLC добавляются в очередь вместо ошибки «Другая загрузка уже выполняется»
|
||||
- Виртуальная мышь создаётся только при включении эмуляции геймпадом и удаляется при её выключении
|
||||
@@ -77,7 +66,6 @@
|
||||
- Исправлена гонка при запуске игры с `--silent`
|
||||
- Исправлено обрезание значений в избранных настройках
|
||||
- При выключенной опции «Fix video in game» больше не блокируется создание DXGI Device Manager в Wine/Proton
|
||||
- Исправлено аварийное завершение при выборе «Выход» в меню системного трея с включённой настройкой «Сворачивать в область уведомления при закрытии»
|
||||
|
||||
### Contributors
|
||||
- @Dervart
|
||||
@@ -85,7 +73,6 @@
|
||||
- @rogerio-mattos
|
||||
- @Rubin13
|
||||
- @iodnoorov
|
||||
- @gstkein
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
<p>
|
||||
<a href="https://github.com/linux-gaming-ru/PortProtonQt/releases"><img src="https://img.shields.io/github/v/release/linux-gaming-ru/PortProtonQt?style=flat-square&label=Release" alt="Releases"></a>
|
||||
<a href="https://github.com/linux-gaming-ru/PortProtonQt/releases"><img src="https://img.shields.io/badge/Downloads-18.9k-green?style=flat-square" alt="Total Downloads"></a>
|
||||
<a href="https://github.com/linux-gaming-ru/PortProtonQt/releases"><img src="https://img.shields.io/badge/Downloads-17.9k-green?style=flat-square" alt="Total Downloads"></a>
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/License-GPL--3.0-blue?style=flat-square" alt="License: GPL-3.0"></a>
|
||||
<a href="pyproject.toml"><img src="https://img.shields.io/badge/Python-3.11%2B-blue?style=flat-square&logo=python" alt="Python 3.11+"></a>
|
||||
<a href="https://github.com/linux-gaming-ru/PortProtonQt"><img src="https://img.shields.io/badge/Platform-Linux-blue?style=flat-square&logo=linux" alt="Platform: Linux"></a>
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
|
||||
<p>
|
||||
<a href="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt/releases"><img src="https://img.shields.io/github/v/release/linux-gaming-ru/PortProtonQt?style=flat-square&label=Релиз" alt="Релизы"></a>
|
||||
<a href="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt/releases"><img src="https://img.shields.io/badge/Загрузки-18.9k-green?style=flat-square" alt="Всего загрузок"></a>
|
||||
<a href="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt/releases"><img src="https://img.shields.io/badge/Загрузки-17.9k-green?style=flat-square" alt="Всего загрузок"></a>
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/Лицензия-GPL--3.0-blue?style=flat-square" alt="Лицензия: GPL-3.0"></a>
|
||||
<a href="pyproject.toml"><img src="https://img.shields.io/badge/Python-3.11+-blue?style=flat-square&logo=python" alt="Python 3.11+"></a>
|
||||
<a href="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt"><img src="https://img.shields.io/badge/Платформа-Linux-blue?style=flat-square&logo=linux" alt="Платформа: Linux"></a>
|
||||
|
||||
@@ -943,13 +943,13 @@ get_and_set_reg_file () {
|
||||
esac
|
||||
name_block=${name_block//\\/\\\\\\\\}
|
||||
if [[ -n $name_for_new_block ]] ; then
|
||||
find_block=$(grep -n "\[$name_block\]" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/$name_for_new_block.reg")
|
||||
find_block=$(grep -n "\[$name_block\]" "${WINEPREFIX}/$name_for_new_block.reg")
|
||||
else
|
||||
find_block=$(grep -n "\[$name_block\]" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/"*.reg)
|
||||
find_block=$(grep -n "\[$name_block\]" "${WINEPREFIX}/"*.reg)
|
||||
fi
|
||||
if [[ -n $find_block ]] ; then
|
||||
if [[ -n $name_for_new_block ]] ; then
|
||||
find_file="${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/$name_for_new_block.reg"
|
||||
find_file="${WINEPREFIX}/$name_for_new_block.reg"
|
||||
find_line=${find_block//:*/}
|
||||
else
|
||||
find_file=${find_block//:*/}
|
||||
@@ -974,8 +974,8 @@ get_and_set_reg_file () {
|
||||
if [[ $name_add_or_del == --add ]] ; then
|
||||
if [[ -z $find_block ]] ; then
|
||||
if [[ -n $name_for_new_block ]] ; then
|
||||
sed -i '$a\\n'\["$name_block"\] "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/$name_for_new_block.reg"
|
||||
find_file="${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/$name_for_new_block.reg"
|
||||
sed -i '$a\\n'\["$name_block"\] "${WINEPREFIX}/$name_for_new_block.reg"
|
||||
find_file="${WINEPREFIX}/$name_for_new_block.reg"
|
||||
find_line=$(wc -l "$find_file" | awk -F" " '{print $1}')
|
||||
find_line=$(( find_line - 1 ))
|
||||
else
|
||||
@@ -1199,6 +1199,23 @@ init_wine_ver () {
|
||||
if [[ -d "${WINEDIR}"/share/espeak-ng-data ]] ; then
|
||||
export ESPEAK_DATA_PATH="${WINEDIR}"/share/
|
||||
fi
|
||||
|
||||
if [[ "${PW_STEAMPLAY:-}" == "1" ]] ; then
|
||||
if [[ -x "${STEAM_COMPAT_TOOL_PATHS%%:*}/proton" ]] ; then
|
||||
PROTON_RUNNER="${STEAM_COMPAT_TOOL_PATHS%%:*}/proton"
|
||||
elif [[ "${PW_WINE_USE:-}" = /* && -x "${PW_WINE_USE}/proton" ]] ; then
|
||||
PROTON_RUNNER="${PW_WINE_USE}/proton"
|
||||
elif [[ -x "${PORT_DATA_PATH}/data/dist/${PW_WINE_USE^^}/proton" ]] ; then
|
||||
PROTON_RUNNER="${PORT_DATA_PATH}/data/dist/${PW_WINE_USE^^}/proton"
|
||||
elif [[ -x "${WINEDIR}/proton" ]] ; then
|
||||
PROTON_RUNNER="${WINEDIR}/proton"
|
||||
elif [[ -x "${WINEDIR%/files}/proton" ]] ; then
|
||||
PROTON_RUNNER="${WINEDIR%/files}/proton"
|
||||
else
|
||||
fatal "$PW_WINE_USE not found!"
|
||||
fi
|
||||
export PROTON_RUNNER
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -1572,7 +1589,6 @@ pw_kill_autostart () {
|
||||
export -f pw_kill_autostart
|
||||
|
||||
stop_portproton () {
|
||||
pw_remove_session_env
|
||||
[[ "$int_xneur" == "1" ]] && xneur &
|
||||
|
||||
if [[ "$PW_USE_US_LAYOUT" == "1" ]] \
|
||||
@@ -1858,6 +1874,10 @@ check_dirs_and_files_in_pfx () {
|
||||
}
|
||||
|
||||
pw_init_db () {
|
||||
if [[ "${PW_STEAMPLAY:-}" == "1" ]] ; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
[[ -n "${PW_DEFAULT_WINE_USE:-}" ]] && export PW_WINE_USE="${PW_DEFAULT_WINE_USE}"
|
||||
[[ -n "${PW_DEFAULT_PREFIX_NAME:-}" ]] && export PW_PREFIX_NAME="${PW_DEFAULT_PREFIX_NAME}"
|
||||
[[ -n "${PW_DEFAULT_VULKAN_USE:-}" ]] && export PW_VULKAN_USE="${PW_DEFAULT_VULKAN_USE}"
|
||||
@@ -2677,15 +2697,27 @@ pw_enable_gamemode_basic () {
|
||||
}
|
||||
|
||||
start_portproton () {
|
||||
pw_check_and_download_plugins
|
||||
|
||||
if [[ "${PW_DISABLE_RUNTIME_DOWNLOAD}" == "1" ]] ; then
|
||||
try_remove_dir "${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}"
|
||||
else
|
||||
pw_check_and_download_runtime
|
||||
if [[ "${PW_STEAMPLAY:-}" == "1" ]] ; then
|
||||
PATH_TO_GAME="$(dirname "$(realpath "${PW_EXE_FILE}")")"
|
||||
export PATH_TO_GAME
|
||||
export PORTWINE_DB_FILE="${PW_EXE_FILE}.ppdb"
|
||||
[[ -f "${PORTWINE_DB_FILE}" ]] && source "${PORTWINE_DB_FILE}"
|
||||
unset PW_PREFIX_NAME
|
||||
export WINEPREFIX="${STEAM_COMPAT_DATA_PATH}/pfx"
|
||||
fi
|
||||
|
||||
pw_check_and_download_dxvk_and_vkd3d
|
||||
pw_check_and_download_plugins
|
||||
|
||||
if [[ "${PW_STEAMPLAY:-}" == "1" ]] ; then
|
||||
export PW_USE_RUNTIME="0"
|
||||
export PW_USE_SUPPLIED_DXVK_VKD3D="1"
|
||||
elif [[ "${PW_DISABLE_RUNTIME_DOWNLOAD}" == "1" ]] ; then
|
||||
try_remove_dir "${PORT_WINE_TMP_PATH}/libs${PW_LIBS_VER}"
|
||||
pw_check_and_download_dxvk_and_vkd3d
|
||||
else
|
||||
pw_check_and_download_runtime
|
||||
pw_check_and_download_dxvk_and_vkd3d
|
||||
fi
|
||||
|
||||
pw_skip_get_info
|
||||
if echo "$LSPCI_VGA" | grep -i -q 'nvidia.*rtx' ; then
|
||||
@@ -2701,7 +2733,9 @@ start_portproton () {
|
||||
export PW_LOCALE_SELECT="disabled"
|
||||
fi
|
||||
|
||||
WINEPREFIX="$(readlink -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}")"
|
||||
if [[ "${PW_STEAMPLAY:-}" != "1" ]] ; then
|
||||
WINEPREFIX="$(readlink -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}")"
|
||||
fi
|
||||
export WINEPREFIX
|
||||
|
||||
pw_get_pfx () {
|
||||
@@ -2738,7 +2772,7 @@ start_portproton () {
|
||||
return 0
|
||||
}
|
||||
|
||||
pw_get_pfx
|
||||
[[ "${PW_STEAMPLAY:-}" != "1" ]] && pw_get_pfx
|
||||
|
||||
var_winedlloverride_update "${PW_MUST_WINEDLLOVERRIDES}"
|
||||
pw_list_install_dll_in_prefix
|
||||
@@ -2854,53 +2888,55 @@ start_portproton () {
|
||||
print_info "The prefix has been updated."
|
||||
}
|
||||
|
||||
if [[ ! -d "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}"/drive_c/windows ]] \
|
||||
|| [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}"/userdef.reg ]] \
|
||||
|| [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}"/system.reg ]] \
|
||||
|| [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}"/user.reg ]]
|
||||
then
|
||||
pw_clear_pfx
|
||||
check_dirs_and_files_in_pfx
|
||||
if [[ "${PW_PREFIX_NAME}" == "DEFAULT" ]] ; then
|
||||
unpack "${PW_PLUGINS_PATH}/default_pfx.tar.xz" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/" silent
|
||||
pw_wineboot -r
|
||||
echo "based_on_default" >> "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
elif [[ "${PW_CHECK_AUTOINSTALL}" == 1 ]] \
|
||||
&& [[ "${DISABLE_CP_DEFPFX}" != 1 ]] ; then
|
||||
unpack "${PW_PLUGINS_PATH}/default_pfx.tar.xz" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/" silent
|
||||
pw_wineboot -r
|
||||
echo "based_on_default" >> "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
elif [[ "${PW_CHECK_AUTOINSTALL}" == 1 ]] \
|
||||
&& [[ "${DISABLE_CP_DEFPFX}" == 1 ]] ; then
|
||||
pw_wineboot -i
|
||||
elif [[ "${DISABLE_CP_DEFPFX}" == "1" ]]; then
|
||||
pw_wineboot -i
|
||||
else
|
||||
unpack "${PW_PLUGINS_PATH}/default_pfx.tar.xz" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/" silent
|
||||
pw_wineboot -r
|
||||
echo "based_on_default" >> "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
fi
|
||||
get_and_set_reg_file --add 'Control Panel\Desktop' 'LogPixels' 'REG_DWORD' "96" "user"
|
||||
else
|
||||
check_dirs_and_files_in_pfx
|
||||
if [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/.wine_ver" ]] \
|
||||
|| [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/windows/system32/shell32.dll" ]] \
|
||||
|| ! grep "${PW_WINE_USE}" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/.wine_ver" &>/dev/null
|
||||
if [[ "${PW_STEAMPLAY:-}" != "1" ]] ; then
|
||||
if [[ ! -d "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}"/drive_c/windows ]] \
|
||||
|| [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}"/userdef.reg ]] \
|
||||
|| [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}"/system.reg ]] \
|
||||
|| [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}"/user.reg ]]
|
||||
then
|
||||
pw_wineboot -r
|
||||
pw_clear_pfx
|
||||
check_dirs_and_files_in_pfx
|
||||
if [[ "${PW_PREFIX_NAME}" == "DEFAULT" ]] ; then
|
||||
unpack "${PW_PLUGINS_PATH}/default_pfx.tar.xz" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/" silent
|
||||
pw_wineboot -r
|
||||
echo "based_on_default" >> "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
elif [[ "${PW_CHECK_AUTOINSTALL}" == 1 ]] \
|
||||
&& [[ "${DISABLE_CP_DEFPFX}" != 1 ]] ; then
|
||||
unpack "${PW_PLUGINS_PATH}/default_pfx.tar.xz" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/" silent
|
||||
pw_wineboot -r
|
||||
echo "based_on_default" >> "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
elif [[ "${PW_CHECK_AUTOINSTALL}" == 1 ]] \
|
||||
&& [[ "${DISABLE_CP_DEFPFX}" == 1 ]] ; then
|
||||
pw_wineboot -i
|
||||
elif [[ "${DISABLE_CP_DEFPFX}" == "1" ]]; then
|
||||
pw_wineboot -i
|
||||
else
|
||||
unpack "${PW_PLUGINS_PATH}/default_pfx.tar.xz" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/" silent
|
||||
pw_wineboot -r
|
||||
echo "based_on_default" >> "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
fi
|
||||
get_and_set_reg_file --add 'Control Panel\Desktop' 'LogPixels' 'REG_DWORD' "96" "user"
|
||||
else
|
||||
check_dirs_and_files_in_pfx
|
||||
if [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/.wine_ver" ]] \
|
||||
|| [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c/windows/system32/shell32.dll" ]] \
|
||||
|| ! grep "${PW_WINE_USE}" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/.wine_ver" &>/dev/null
|
||||
then
|
||||
pw_wineboot -r
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" ]] \
|
||||
&& grep -q "based_on" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
then export PW_BASE_PFX="$(awk -F'based_on_' '$2 != "" {print $2}' "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log")"
|
||||
else export PW_BASE_PFX="none"
|
||||
fi
|
||||
|
||||
rm -f "${PORT_DATA_PATH}"/data/prefixes/*/drive_c/users/*/Desktop/*.lnk
|
||||
|
||||
echo "${PW_WINE_USE}" > "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/.wine_ver"
|
||||
fi
|
||||
|
||||
if [[ -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" ]] \
|
||||
&& grep -q "based_on" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
then export PW_BASE_PFX="$(awk -F'based_on_' '$2 != "" {print $2}' "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log")"
|
||||
else export PW_BASE_PFX="none"
|
||||
fi
|
||||
|
||||
rm -f "${PORT_DATA_PATH}"/data/prefixes/*/drive_c/users/*/Desktop/*.lnk
|
||||
|
||||
echo "${PW_WINE_USE}" > "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/.wine_ver"
|
||||
|
||||
pw_set_sync_runtime_vars
|
||||
|
||||
# export WINE_SIMULATE_ASYNC_READ=1
|
||||
@@ -3005,8 +3041,13 @@ start_portproton () {
|
||||
fi
|
||||
|
||||
if [[ "${PW_USE_NVAPI_AND_DLSS}" == "1" ]] ; then
|
||||
export DXVK_ENABLE_NVAPI="1"
|
||||
if echo "$LSPCI_VGA" | grep -i -q 'nvidia' ; then
|
||||
if [[ "${PW_STEAMPLAY:-}" == "1" ]] ; then
|
||||
export PROTON_FORCE_NVAPI="1"
|
||||
export PROTON_HIDE_NVIDIA_GPU="0"
|
||||
else
|
||||
export DXVK_ENABLE_NVAPI="1"
|
||||
fi
|
||||
if [[ "${PW_STEAMPLAY:-}" != "1" ]] && echo "$LSPCI_VGA" | grep -i -q 'nvidia' ; then
|
||||
FIND_NVNGX="$(dirname $(find /usr/* -type f -name "nvngx.dll" 2>/dev/null | head -n 1 | awk '{print $1}'))"
|
||||
if [[ -n "$FIND_NVNGX" ]] ; then
|
||||
try_copy_file_with_checksums "${FIND_NVNGX}/nvngx.dll" "${WINEPREFIX}/drive_c/windows/system32/nvngx.dll"
|
||||
@@ -3015,7 +3056,7 @@ start_portproton () {
|
||||
export NVIDIA_WINE_DLL_DIR="${FIND_NVNGX}"
|
||||
fi
|
||||
fi
|
||||
else
|
||||
elif [[ "${PW_STEAMPLAY:-}" != "1" ]] ; then
|
||||
export DXVK_ENABLE_NVAPI="0"
|
||||
fi
|
||||
|
||||
@@ -3029,9 +3070,11 @@ start_portproton () {
|
||||
else export WINE_ALLOW_XIM="0"
|
||||
fi
|
||||
|
||||
if [[ "${PW_FIX_VIDEO_IN_GAME}" == 1 ]]
|
||||
then export WINE_DO_NOT_CREATE_DXGI_DEVICE_MANAGER="1"
|
||||
else unset WINE_DO_NOT_CREATE_DXGI_DEVICE_MANAGER
|
||||
if [[ "${PW_STEAMPLAY:-}" != "1" ]] ; then
|
||||
if [[ "${PW_FIX_VIDEO_IN_GAME}" == 1 ]]
|
||||
then export WINE_DO_NOT_CREATE_DXGI_DEVICE_MANAGER="1"
|
||||
else unset WINE_DO_NOT_CREATE_DXGI_DEVICE_MANAGER
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -f "$PATH_TO_GAME/MangoHud.conf" ]] ; then
|
||||
@@ -3129,16 +3172,17 @@ start_portproton () {
|
||||
export PW_USE_US_LAYOUT="0"
|
||||
fi
|
||||
|
||||
if [[ "${PW_STEAMPLAY:-}" != "1" ]] ; then
|
||||
D3D_EXTRAS_LIBS="d3dcompiler_33 d3dcompiler_34 d3dcompiler_35 d3dcompiler_36 d3dcompiler_37
|
||||
d3dcompiler_38 d3dcompiler_39 d3dcompiler_40 d3dcompiler_41 d3dcompiler_42 d3dcompiler_43 d3dcompiler_46
|
||||
d3dcompiler_47 d3dx10_33 d3dx10_34 d3dx10_35 d3dx10_36 d3dx10_37 d3dx10_38 d3dx10_39 d3dx10_40 d3dx10_41
|
||||
d3dx10_42 d3dx10_43 d3dx10 d3dx11_42 d3dx11_43 d3dx9_24 d3dx9_25 d3dx9_26 d3dx9_27 d3dx9_28 d3dx9_29 d3dx9_30
|
||||
d3dx9_31 d3dx9_32 d3dx9_33 d3dx9_34 d3dx9_35 d3dx9_36 d3dx9_37 d3dx9_38 d3dx9_39 d3dx9_40 d3dx9_41 d3dx9_42 d3dx9_43"
|
||||
if [[ "${PW_USE_D3D_EXTRAS}" == "1" ]] ; then
|
||||
if [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" ]] \
|
||||
|| [[ -z "$(grep d3dx9 "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log")" ]]
|
||||
if [[ ! -f "${WINEPREFIX}/winetricks.log" ]] \
|
||||
|| [[ -z "$(grep d3dx9 "${WINEPREFIX}/winetricks.log")" ]]
|
||||
then
|
||||
echo "d3dx9" >> "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
echo "d3dx9" >> "${WINEPREFIX}/winetricks.log"
|
||||
fi
|
||||
# try link d3d extras libs
|
||||
PATH_TO_D3DEXTRAS="${PW_PLUGINS_PATH}/d3d_extras"
|
||||
@@ -3146,8 +3190,8 @@ start_portproton () {
|
||||
try_force_link_file "${PATH_TO_D3DEXTRAS}/x64/${d3d_extras_from_plugins}.dll" "${WINEPREFIX}/drive_c/windows/system32/${d3d_extras_from_plugins}.dll"
|
||||
try_force_link_file "${PATH_TO_D3DEXTRAS}/x32/${d3d_extras_from_plugins}.dll" "${WINEPREFIX}/drive_c/windows/syswow64/${d3d_extras_from_plugins}.dll"
|
||||
var_winedlloverride_update "${d3d_extras_from_plugins}=n"
|
||||
if [[ -z "$(grep "${d3d_extras_from_plugins}" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log")" ]] ; then
|
||||
echo "${d3d_extras_from_plugins}" >> "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
if [[ -z "$(grep "${d3d_extras_from_plugins}" "${WINEPREFIX}/winetricks.log")" ]] ; then
|
||||
echo "${d3d_extras_from_plugins}" >> "${WINEPREFIX}/winetricks.log"
|
||||
fi
|
||||
done
|
||||
else
|
||||
@@ -3647,6 +3691,7 @@ start_portproton () {
|
||||
else
|
||||
var_winedlloverride_update "wineopenxr,vrclient,vrclient_x64,openvr_api_dxvk="
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ "${PW_USE_SHADER_CACHE}" == "1" ]] ; then
|
||||
create_new_dir "${PW_VULKAN_DIR}/gl_shader_cache"
|
||||
@@ -3720,59 +3765,65 @@ start_portproton () {
|
||||
fi
|
||||
export LSFGVK_EXPERIMENTAL_PRESENT_MODE="$MESA_VK_WSI_PRESENT_MODE"
|
||||
|
||||
#run_winetricks_from_db
|
||||
if [[ -n "${PW_MUST_HAVE_DLL}" ]] ; then
|
||||
PW_DLL_INSTALL="$(echo "${PW_MUST_HAVE_DLL} ${PW_DLL_INSTALL}" | awk '{ for(i=1;i<=NF;i++){a[$i]++} }END{ for(i in a){printf("%s ",i)} }' )"
|
||||
export PW_DLL_INSTALL
|
||||
fi
|
||||
|
||||
if [[ -n "${PW_DLL_INSTALL}" ]] ; then
|
||||
export PW_DLL_NEED_INSTALL=""
|
||||
export USE_WT_FROM_DB=0
|
||||
if [[ ! -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" ]] ; then
|
||||
touch "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
if [[ "${PW_STEAMPLAY:-}" != "1" ]] ; then
|
||||
#run_winetricks_from_db
|
||||
if [[ -n "${PW_MUST_HAVE_DLL}" ]] ; then
|
||||
PW_DLL_INSTALL="$(echo "${PW_MUST_HAVE_DLL} ${PW_DLL_INSTALL}" | awk '{ for(i=1;i<=NF;i++){a[$i]++} }END{ for(i in a){printf("%s ",i)} }' )"
|
||||
export PW_DLL_INSTALL
|
||||
fi
|
||||
for need_install_dll_to_pfx in ${PW_DLL_INSTALL} ; do
|
||||
if [[ "${need_install_dll_to_pfx}" == vcrun201[5-9] ]] \
|
||||
|| [[ "${need_install_dll_to_pfx}" == vcrun2022 ]] ; then
|
||||
need_install_dll_to_pfx="vcrun2022"
|
||||
sed -i '/vcrun2015/d' "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
sed -i '/vcrun2017/d' "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
sed -i '/vcrun2019/d' "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log"
|
||||
|
||||
if [[ -n "${PW_DLL_INSTALL}" ]] ; then
|
||||
export PW_DLL_NEED_INSTALL=""
|
||||
export USE_WT_FROM_DB=0
|
||||
if [[ ! -f "${WINEPREFIX}/winetricks.log" ]] ; then
|
||||
touch "${WINEPREFIX}/winetricks.log"
|
||||
fi
|
||||
grep "${need_install_dll_to_pfx}" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/winetricks.log" &>/dev/null
|
||||
if [[ "$?" == "1" ]] ; then
|
||||
if [[ -z "${PW_DLL_NEED_INSTALL}" ]]
|
||||
then export PW_DLL_NEED_INSTALL="${need_install_dll_to_pfx}"
|
||||
else export PW_DLL_NEED_INSTALL="${need_install_dll_to_pfx} ${PW_DLL_NEED_INSTALL}"
|
||||
for need_install_dll_to_pfx in ${PW_DLL_INSTALL} ; do
|
||||
if [[ "${need_install_dll_to_pfx}" == vcrun201[5-9] ]] \
|
||||
|| [[ "${need_install_dll_to_pfx}" == vcrun2022 ]] ; then
|
||||
need_install_dll_to_pfx="vcrun2022"
|
||||
sed -i '/vcrun2015/d' "${WINEPREFIX}/winetricks.log"
|
||||
sed -i '/vcrun2017/d' "${WINEPREFIX}/winetricks.log"
|
||||
sed -i '/vcrun2019/d' "${WINEPREFIX}/winetricks.log"
|
||||
fi
|
||||
export USE_WT_FROM_DB=1
|
||||
grep "${need_install_dll_to_pfx}" "${WINEPREFIX}/winetricks.log" &>/dev/null
|
||||
if [[ "$?" == "1" ]] ; then
|
||||
if [[ -z "${PW_DLL_NEED_INSTALL}" ]]
|
||||
then export PW_DLL_NEED_INSTALL="${need_install_dll_to_pfx}"
|
||||
else export PW_DLL_NEED_INSTALL="${need_install_dll_to_pfx} ${PW_DLL_NEED_INSTALL}"
|
||||
fi
|
||||
export USE_WT_FROM_DB=1
|
||||
fi
|
||||
done
|
||||
if [[ "${USE_WT_FROM_DB}" == "1" ]] ; then
|
||||
update_winetricks
|
||||
echo "START WINETRICKS..." >> "${PW_TMPFS_PATH}/update_pfx_log"
|
||||
echo "Try to install DLL in prefix: ${PW_DLL_NEED_INSTALL}" >> "${PW_TMPFS_PATH}/update_pfx_log"
|
||||
print_info "Try to install DLL in prefix: ${PW_DLL_NEED_INSTALL}"
|
||||
${pw_runtime} LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}" GST_PLUGIN_SYSTEM_PATH_1_0="" \
|
||||
"${PORT_WINE_TMP_PATH}/winetricks" -q -f ${PW_DLL_NEED_INSTALL} | tee -a "${PW_TMPFS_PATH}/update_pfx_log"
|
||||
wait_wineserver
|
||||
kill_portwine
|
||||
fi
|
||||
done
|
||||
if [[ "${USE_WT_FROM_DB}" == "1" ]] ; then
|
||||
update_winetricks
|
||||
echo "START WINETRICKS..." >> "${PW_TMPFS_PATH}/update_pfx_log"
|
||||
echo "Try to install DLL in prefix: ${PW_DLL_NEED_INSTALL}" >> "${PW_TMPFS_PATH}/update_pfx_log"
|
||||
print_info "Try to install DLL in prefix: ${PW_DLL_NEED_INSTALL}"
|
||||
${pw_runtime} LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}" GST_PLUGIN_SYSTEM_PATH_1_0="" \
|
||||
"${PORT_WINE_TMP_PATH}/winetricks" -q -f ${PW_DLL_NEED_INSTALL} | tee -a "${PW_TMPFS_PATH}/update_pfx_log"
|
||||
wait_wineserver
|
||||
kill_portwine
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -f "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/system.reg" ]] \
|
||||
&& ! grep -iq "Microsoft Windows $PW_WINDOWS_VER" "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/system.reg"
|
||||
if [[ -f "${WINEPREFIX}/system.reg" ]] \
|
||||
&& ! grep -iq "Microsoft Windows $PW_WINDOWS_VER" "${WINEPREFIX}/system.reg"
|
||||
then
|
||||
if [[ -n $PW_WINDOWS_VER ]] \
|
||||
&& [[ $(echo "$PW_WINDOWS_VER" | sed 's/.*/\L&/') == "xp" ]]
|
||||
then
|
||||
export PW_WINDOWS_VER="xp64"
|
||||
fi
|
||||
${pw_runtime} LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}:${WINE_LIBRARY_PATH}" GST_PLUGIN_SYSTEM_PATH_1_0="" \
|
||||
"${WINELOADER}" winecfg -v $(echo "win${PW_WINDOWS_VER}" | sed 's/.*/\L&/')
|
||||
wait_wineserver
|
||||
kill_portwine
|
||||
if [[ "${PW_STEAMPLAY:-}" == "1" ]] ; then
|
||||
"${PROTON_RUNNER}" run winecfg -v "$(echo "win${PW_WINDOWS_VER}" | sed 's/.*/\L&/')"
|
||||
else
|
||||
${pw_runtime} LD_LIBRARY_PATH="${PW_LD_LIBRARY_PATH}:${WINE_LIBRARY_PATH}" GST_PLUGIN_SYSTEM_PATH_1_0="" \
|
||||
"${WINELOADER}" winecfg -v "$(echo "win${PW_WINDOWS_VER}" | sed 's/.*/\L&/')"
|
||||
wait_wineserver
|
||||
kill_portwine
|
||||
fi
|
||||
echo "Set to win${PW_WINDOWS_VER}"
|
||||
fi
|
||||
|
||||
@@ -3872,7 +3923,6 @@ start_portproton () {
|
||||
pw_mangohud_check
|
||||
pw_vkbasalt_check
|
||||
pw_lsfg_vk_check
|
||||
pw_save_session_env || print_warning "Could not save Wine session environment"
|
||||
}
|
||||
|
||||
pw_run () {
|
||||
@@ -4024,80 +4074,6 @@ pw_run () {
|
||||
}
|
||||
export -f pw_run
|
||||
|
||||
pw_save_session_env () {
|
||||
local session_dir="${PORT_DATA_PATH}/data/tmp/wine-session-$(id -u)"
|
||||
local session_tmp
|
||||
|
||||
( umask 077; mkdir -p "$session_dir" ) || return 1
|
||||
[[ ! -L "$session_dir" && -O "$session_dir" ]] || return 1
|
||||
[[ "$(stat -c %a "$session_dir")" == 700 ]] || return 1
|
||||
|
||||
session_tmp="$(mktemp "$session_dir/env.XXXXXX")" || return 1
|
||||
if ( export PW_TERM; export -p > "$session_tmp" ) \
|
||||
&& mv -fT "$session_tmp" "$session_dir/session.env" ; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
rm -f "$session_tmp"
|
||||
return 1
|
||||
}
|
||||
|
||||
pw_remove_session_env () {
|
||||
local session_dir="${PORT_DATA_PATH}/data/tmp/wine-session-$(id -u)"
|
||||
[[ ! -L "$session_dir" && -O "$session_dir" ]] || return 0
|
||||
local session_env="$session_dir/session.env"
|
||||
[[ ! -L "$session_env" && -O "$session_env" ]] || return 0
|
||||
if grep -qsx "declare -x PW_START_PID=\"${PW_START_PID}\"" "$session_env" ; then
|
||||
rm -f "$session_env"
|
||||
fi
|
||||
}
|
||||
|
||||
pw_session_tool () {
|
||||
local tool="$1" session_pid session_env
|
||||
local session_dir="${PORT_DATA_PATH}/data/tmp/wine-session-$(id -u)"
|
||||
local session_wait_seconds="${2:-30}" wait_left
|
||||
wait_left="$session_wait_seconds"
|
||||
|
||||
case "$tool" in
|
||||
winefile|taskmgr|winecfg|regedit|cmd|uninstaller) ;;
|
||||
*) print_error "Unsupported Wine tool: $tool" ; return 1 ;;
|
||||
esac
|
||||
|
||||
session_env="$session_dir/session.env"
|
||||
while (( wait_left > 0 )) ; do
|
||||
if [[ ! -L "$session_dir" && -O "$session_dir" ]] \
|
||||
&& [[ "$(stat -c %a "$session_dir")" == 700 ]] \
|
||||
&& [[ ! -L "$session_env" && -O "$session_env" ]] \
|
||||
&& [[ "$(stat -c %a "$session_env")" == 600 ]] \
|
||||
&& session_pid="$(sed -n 's/^declare -x PW_START_PID="\([0-9]*\)"$/\1/p' "$session_env")" \
|
||||
&& [[ -n "$session_pid" ]] \
|
||||
&& kill -0 "$session_pid" 2>/dev/null ; then
|
||||
break
|
||||
fi
|
||||
|
||||
sleep 1
|
||||
(( --wait_left ))
|
||||
done
|
||||
|
||||
if (( wait_left == 0 )) ; then
|
||||
print_error "Wine session unavailable after ${session_wait_seconds} seconds"
|
||||
return 2
|
||||
fi
|
||||
|
||||
source "$session_env" || return 1
|
||||
PATH_TO_GAME="${WINEPREFIX}/drive_c"
|
||||
[[ -d "$PATH_TO_GAME" ]] || return 1
|
||||
|
||||
unset LAUNCH_PARAMETERS PW_RUN_AFTER_EXE PW_RUN_GAMESCOPE PW_USE_TERMINAL
|
||||
PW_TMPFS_PATH="$(mktemp -d "$session_dir/tool.XXXXXX")" || return 1
|
||||
export PW_TMPFS_PATH
|
||||
export PW_LOG_FILE="$PW_TMPFS_PATH/wine.log"
|
||||
|
||||
[[ "$tool" == cmd ]] && PW_USE_TERMINAL=1
|
||||
[[ "$tool" == winecfg || "$tool" == regedit ]] && export GST_PLUGIN_SYSTEM_PATH_1_0=""
|
||||
pw_run "$tool" || return 1
|
||||
}
|
||||
|
||||
pw_launch_wrapper () {
|
||||
if [[ -z "${PW_RUN_AFTER_EXE:-}" ]] ; then
|
||||
"$@"
|
||||
@@ -4166,153 +4142,54 @@ pw_launch_wrapper () {
|
||||
}
|
||||
export -f pw_launch_wrapper
|
||||
|
||||
steamplay_launch () {
|
||||
pw_check_and_download_plugins
|
||||
|
||||
if [[ -n "${PW_EXE_FILE:-}" ]]; then
|
||||
local proton_runner
|
||||
local steamplay_ld_library_path
|
||||
cd "$(dirname "${PW_EXE_FILE}")"
|
||||
export PATH_TO_GAME="$(pwd)"
|
||||
export PORTWINE_DB_FILE="${PW_EXE_FILE}.ppdb"
|
||||
[[ -f "${PORTWINE_DB_FILE}" ]] && source "${PORTWINE_DB_FILE}"
|
||||
export PW_USE_SUPPLIED_DXVK_VKD3D="1"
|
||||
|
||||
steamplay_ld_library_path="${LD_LIBRARY_PATH}:${STEAM_RUNTIME_LIBRARY_PATH}:${PW_PLUGINS_PATH}/portable/lib/lib64:${PW_PLUGINS_PATH}/portable/lib/lib32"
|
||||
[[ -d "${HOME}/.local/share/Steam/ubuntu12_32" ]] && steamplay_ld_library_path="${steamplay_ld_library_path}:${HOME}/.local/share/Steam/ubuntu12_32"
|
||||
[[ -d "${HOME}/.local/share/Steam/ubuntu12_64" ]] && steamplay_ld_library_path="${steamplay_ld_library_path}:${HOME}/.local/share/Steam/ubuntu12_64"
|
||||
|
||||
if [[ -f "$PATH_TO_GAME/MangoHud.conf" ]] ; then
|
||||
unset MANGOHUD_CONFIG
|
||||
export MANGOHUD_CONFIGFILE="$PATH_TO_GAME/MangoHud.conf"
|
||||
print_info "Custom MangoHud.conf in use: $MANGOHUD_CONFIGFILE"
|
||||
elif [[ "${PW_MANGOHUD_USER_CONF}" == 1 ]] ; then
|
||||
pw_select_mangohud_user_conf
|
||||
fi
|
||||
|
||||
[[ "${PW_VKBASALT_USER_CONF}" == 1 ]] && pw_select_vkbasalt_user_conf
|
||||
|
||||
pw_optiscaler_sync_files
|
||||
pw_specialk_sync_files
|
||||
|
||||
PORT_WINE_PREFIX="$STEAM_COMPAT_DATA_PATH/pfx"
|
||||
|
||||
pw_prepare_gamescope_launch
|
||||
|
||||
if check_gamescope_session ; then
|
||||
export PW_GAMEMODERUN_SLR=""
|
||||
elif [[ "$PW_USE_GAMEMODE" = "1" ]] \
|
||||
&& [[ -n "$DBUS_SESSION_BUS_ADDRESS" ]]
|
||||
then
|
||||
pw_enable_gamemode_basic
|
||||
fi
|
||||
|
||||
pw_enable_idle_inhibit
|
||||
|
||||
pw_set_sync_runtime_vars
|
||||
|
||||
# Mangohud, VkBasalt, LSFG
|
||||
if [[ "$PW_USE_SYSTEM_VK_LAYERS" == "1" ]] ; then
|
||||
unset PW_VK_LAYER_PATH
|
||||
else
|
||||
export PW_VK_LAYER_PATH="${PW_PLUGINS_PATH}/portable/share/vulkan/implicit_layer.d"
|
||||
fi
|
||||
|
||||
pw_mangohud_check
|
||||
pw_vkbasalt_check
|
||||
pw_lsfg_vk_check
|
||||
|
||||
export VK_ADD_IMPLICIT_LAYER_PATH="${PW_VK_LAYER_PATH}"
|
||||
export VK_ADD_LAYER_PATH="${PW_VK_LAYER_PATH}"
|
||||
export VK_INSTANCE_LAYERS="${PW_VK_INSTANCE_LAYERS}"
|
||||
|
||||
[[ $PW_LOG != 1 ]] && debug_timer --start -s "PW_TIME_IN_GAME"
|
||||
|
||||
if [[ "${PW_WINE_USE,,}" != *proton* ]] ; then
|
||||
fatal "Steamplay don\`t work with ${PW_WINE_USE}!"
|
||||
else
|
||||
init_wine_ver
|
||||
fi
|
||||
|
||||
check_proton_runner () {
|
||||
if [[ -x "${STEAM_COMPAT_TOOL_PATHS%%:*}/proton" ]] ; then
|
||||
proton_runner="${STEAM_COMPAT_TOOL_PATHS%%:*}/proton"
|
||||
elif [[ "${PW_WINE_USE:-}" = /* ]] && [[ -x "${PW_WINE_USE}/proton" ]] ; then
|
||||
proton_runner="${PW_WINE_USE}/proton"
|
||||
elif [[ -x "${PORT_DATA_PATH}/data/dist/${PW_WINE_USE^^}/proton" ]] ; then
|
||||
proton_runner="${PORT_DATA_PATH}/data/dist/${PW_WINE_USE^^}/proton"
|
||||
export PW_WINE_USE="${PW_WINE_USE^^}"
|
||||
elif [[ -x "${WINEDIR}/proton" ]] ; then
|
||||
proton_runner="${WINEDIR}/proton"
|
||||
elif [[ -x "${WINEDIR%/files}/proton" ]] ; then
|
||||
proton_runner="${WINEDIR%/files}/proton"
|
||||
else
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
if ! check_proton_runner ; then
|
||||
gui_proton_downloader "${PW_WINE_USE}"
|
||||
init_wine_ver
|
||||
if ! check_proton_runner ; then
|
||||
fatal "$PW_WINE_USE not found!"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Winetricks
|
||||
if [[ -n "${PW_DLL_INSTALL:-}" ]] ; then
|
||||
update_winetricks
|
||||
PATH="${PATH}:${PW_PLUGINS_PATH}/portable/bin" LD_LIBRARY_PATH="${steamplay_ld_library_path}" \
|
||||
"${PORT_WINE_TMP_PATH}/winetricks" -q ${PW_DLL_INSTALL}
|
||||
fi
|
||||
|
||||
# Virtual Desktop
|
||||
if [[ "${PW_VIRTUAL_DESKTOP}" == "1" ]] ; then
|
||||
if [[ "${PW_SCREEN_RESOLUTION:-}" != *x* ]] ; then
|
||||
if [[ -f "${PW_TMPFS_PATH}/xrandr.tmp" ]] ; then
|
||||
PW_SCREEN_RESOLUTION="$(sed -rn 's/^.*primary.* ([0-9]+x[0-9]+).*$/\1/p' "${PW_TMPFS_PATH}/xrandr.tmp")"
|
||||
fi
|
||||
[[ "${PW_SCREEN_RESOLUTION:-}" != *x* ]] && PW_SCREEN_RESOLUTION="1920x1080"
|
||||
fi
|
||||
"${proton_runner}" "run" reg add "HKEY_CURRENT_USER\\Software\\Wine\\Explorer\\Desktops" /v "PortProton" /d "${PW_SCREEN_RESOLUTION}" /f &>/dev/null
|
||||
"${proton_runner}" "run" reg add "HKEY_CURRENT_USER\\Software\\Wine\\Explorer" /v "Desktop" /d "PortProton" /f &>/dev/null
|
||||
print_info "Steam Play virtual desktop enabled in registry: ${PW_SCREEN_RESOLUTION}"
|
||||
else
|
||||
"${proton_runner}" "run" reg delete "HKEY_CURRENT_USER\\Software\\Wine\\Explorer" /v "Desktop" /f &>/dev/null
|
||||
"${proton_runner}" "run" reg delete "HKEY_CURRENT_USER\\Software\\Wine\\Explorer\\Desktops" /v "PortProton" /f &>/dev/null
|
||||
print_info "Steam Play virtual desktop disabled in registry"
|
||||
fi
|
||||
|
||||
print_info "$proton_runner in use."
|
||||
printf '%s\n' 'PORTPROTONQT_GAME_LAUNCH_STARTED'
|
||||
pw_launch_wrapper \
|
||||
${PW_RUN_GAMESCOPE} \
|
||||
env \
|
||||
LD_LIBRARY_PATH="${steamplay_ld_library_path}" \
|
||||
LD_PRELOAD="${LD_PRELOAD:+$LD_PRELOAD:}${PW_LD_PRELOAD}" \
|
||||
${PW_ADD_VAR_SLR} \
|
||||
${PW_GAMEMODERUN_SLR} \
|
||||
${PW_TASKSET_SLR} \
|
||||
"${proton_runner}" waitforexitandrun "${PW_EXE_FILE}" "$@"
|
||||
printf 'PORTPROTONQT_GAME_EXIT_CODE=%s\n' "$?"
|
||||
if [[ $PW_LOG != 1 ]] && [[ -n $START_PW_TIME_IN_GAME ]] ; then
|
||||
debug_timer --end -s "PW_TIME_IN_GAME"
|
||||
PW_TIME_IN_GAME=$(( PW_TIME_IN_GAME / 1000 ))
|
||||
search_desktop_file
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
portwine_launch () {
|
||||
start_portproton
|
||||
unset PW_VD_TMP
|
||||
if [[ "${PW_VIRTUAL_DESKTOP}" == "1" ]] ; then
|
||||
if [[ "${PW_STEAMPLAY:-}" == "1" ]] ; then
|
||||
if [[ "${PW_VIRTUAL_DESKTOP}" == "1" ]] ; then
|
||||
[[ "${PW_SCREEN_RESOLUTION:-}" != *x* ]] && PW_SCREEN_RESOLUTION="1920x1080"
|
||||
get_and_set_reg_file --add 'Software\Wine\Explorer\Desktops' 'PortProton' 'REG_SZ' "${PW_SCREEN_RESOLUTION}" "user"
|
||||
get_and_set_reg_file --add 'Software\Wine\Explorer' 'Desktop' 'REG_SZ' "PortProton" "user"
|
||||
else
|
||||
get_and_set_reg_file --delete 'Software\Wine\Explorer' 'Desktop' '' '' "user"
|
||||
get_and_set_reg_file --delete 'Software\Wine\Explorer\Desktops' 'PortProton' '' '' "user"
|
||||
fi
|
||||
elif [[ "${PW_VIRTUAL_DESKTOP}" == "1" ]] ; then
|
||||
PW_VD_TMP=(explorer "/desktop=PortProton,${PW_SCREEN_RESOLUTION}")
|
||||
fi
|
||||
|
||||
[[ $PW_LOG != 1 ]] && debug_timer --start -s "PW_TIME_IN_GAME"
|
||||
printf '%s\n' 'PORTPROTONQT_GAME_LAUNCH_STARTED'
|
||||
if [[ "${PW_STEAMPLAY:-}" == "1" ]] \
|
||||
&& [[ -n "${PW_RUN_AFTER_EXE:-}" ]] \
|
||||
&& [[ -f "${PW_RUN_AFTER_EXE}" ]] \
|
||||
&& [[ "${PW_RUN_AFTER_EXE,,}" =~ \.exe$ ]] \
|
||||
&& [[ "${PW_RUN_AFTER_EXE}" != "${PW_EXE_FILE}" ]]
|
||||
then
|
||||
printf -v PROTON_REMOTE_DEBUG_CMD '%q' "${PW_RUN_AFTER_EXE}"
|
||||
export PROTON_REMOTE_DEBUG_CMD
|
||||
export PRESSURE_VESSEL_FILESYSTEMS_RW="${PRESSURE_VESSEL_FILESYSTEMS_RW:+$PRESSURE_VESSEL_FILESYSTEMS_RW:}$(dirname "${PW_RUN_AFTER_EXE}")"
|
||||
fi
|
||||
|
||||
if [[ "${PW_STEAMPLAY:-}" == "1" ]] ; then
|
||||
local steamplay_ld_library_path
|
||||
cd "${PATH_TO_GAME}" || fatal "${PATH_TO_GAME} not found"
|
||||
steamplay_ld_library_path="${LD_LIBRARY_PATH}:${STEAM_RUNTIME_LIBRARY_PATH}:${PW_PLUGINS_PATH}/portable/lib/lib64:${PW_PLUGINS_PATH}/portable/lib/lib32"
|
||||
${PW_RUN_GAMESCOPE} \
|
||||
env \
|
||||
LD_LIBRARY_PATH="${steamplay_ld_library_path}" \
|
||||
LD_PRELOAD="${LD_PRELOAD:+$LD_PRELOAD:}${PW_LD_PRELOAD}" \
|
||||
VK_ADD_IMPLICIT_LAYER_PATH="${PW_VK_LAYER_PATH}" \
|
||||
VK_ADD_LAYER_PATH="${PW_VK_LAYER_PATH}" \
|
||||
VK_INSTANCE_LAYERS="${PW_VK_INSTANCE_LAYERS}" \
|
||||
${PW_ADD_VAR_SLR} \
|
||||
${PW_GAMEMODERUN_SLR} \
|
||||
${PW_INHIBIT_SLR} \
|
||||
${PW_TASKSET_SLR} \
|
||||
"${PROTON_RUNNER}" waitforexitandrun "${PW_EXE_FILE}" "$@"
|
||||
return $?
|
||||
fi
|
||||
|
||||
if [[ -n "${LAUNCH_URI}" ]] ; then
|
||||
export WINEFSYNC="1"
|
||||
pw_run start /high /b "${LAUNCH_URI}" &
|
||||
|
||||
@@ -67,21 +67,6 @@ export PW_LOG_FILE="${PORT_DATA_PATH}/PortProton.log"
|
||||
# shellcheck source=/dev/null
|
||||
source "$PORT_SCRIPTS_PATH/functions_helper"
|
||||
|
||||
if [[ "${1:-}" == "cli" && "${2:-}" == "--wine-session-tool" ]] ; then
|
||||
session_unavailable_status=2
|
||||
session_wait_seconds=30
|
||||
[[ -n "${4:-}" && -n "${5:-}" ]] && session_wait_seconds=1
|
||||
if pw_session_tool "${3:-}" "$session_wait_seconds" ; then
|
||||
exit 0
|
||||
else
|
||||
session_tool_status=$?
|
||||
fi
|
||||
if [[ "$session_tool_status" != "$session_unavailable_status" || -z "${4:-}" || -z "${5:-}" ]] ; then
|
||||
python_module dbus_tools notify -i error "Wine" "Failed to start Wine tool: ${3:-}" &>/dev/null
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
export PORT_WINE_TMP_PATH="${PORT_DATA_PATH}/data/tmp"
|
||||
create_new_dir "$PORT_WINE_TMP_PATH"
|
||||
rm -f "$PORT_WINE_TMP_PATH"/*.{exe,msi,tar}*
|
||||
@@ -213,10 +198,11 @@ try_remove_file "${PW_TMPFS_PATH}/update_pfx_log"
|
||||
[[ ! -f "$PORT_WINE_TMP_PATH/statistics" ]] && touch "$PORT_WINE_TMP_PATH/statistics"
|
||||
|
||||
if [[ -n "${STEAM_COMPAT_DATA_PATH:-}" ]]; then
|
||||
steamplay_launch "${@:2}"
|
||||
exit
|
||||
export PW_STEAMPLAY="1"
|
||||
export WINEPREFIX="${STEAM_COMPAT_DATA_PATH}/pfx"
|
||||
else
|
||||
unset WINEPREFIX
|
||||
fi
|
||||
unset WINEPREFIX
|
||||
|
||||
# choose mirror
|
||||
if [[ -z "$MIRROR" ]] \
|
||||
@@ -295,7 +281,11 @@ case "$1" in
|
||||
--show-ppdb Show the content of .ppdb file for specified .exe file
|
||||
--backup-prefix Backup specified prefix to a file
|
||||
--restore-prefix Restore prefix from backup file
|
||||
--wine-session-tool Open a Wine tool in the current session, or use optional WINE and prefix
|
||||
--winefile Open wine file explorer, requires WINE version and prefix name
|
||||
--winecfg Open wine configuration, requires WINE version and prefix name
|
||||
--winecmd Open wine command prompt, requires WINE version and prefix name
|
||||
--winereg Open wine registry editor, requires WINE version and prefix name
|
||||
--wine_uninstaller Open wine uninstaller, requires WINE version and prefix name
|
||||
--winetricks-list-all List winetricks DLLs, fonts, and settings
|
||||
--winetricks-install Install winetricks items, requires WINE version and prefix name
|
||||
--clear_pfx Clear specified prefix, requires WINE version and prefix name
|
||||
@@ -311,7 +301,7 @@ Usage examples:
|
||||
portproton cli --del-user-conf PW_MANGOHUD
|
||||
portproton cli --backup-prefix DEFAULT /path/to/backup/directory
|
||||
portproton cli --restore-prefix /path/to/backup/file.ppack
|
||||
portproton cli --wine-session-tool winecfg WINE_LG DEFAULT
|
||||
portproton cli --winecfg WINE_LG DEFAULT
|
||||
portproton cli --winetricks-list-all WINE_LG DEFAULT
|
||||
portproton cli --winetricks-install WINE_LG DEFAULT --no-force corefonts
|
||||
portproton cli --mangohud-preview \"fps,frametime,cpu_temp,gpu_temp\"
|
||||
@@ -473,21 +463,37 @@ Usage examples:
|
||||
pw_unpack_prefix "$2"
|
||||
exit $?
|
||||
;;
|
||||
--wine-session-tool)
|
||||
tool="$2"
|
||||
case "$tool" in
|
||||
winefile|taskmgr|winecfg|regedit|cmd|uninstaller) ;;
|
||||
*) print_error "Unsupported Wine tool: $tool" ; exit 1 ;;
|
||||
esac
|
||||
get_wine_and_pfx "$3" "$4"
|
||||
--winefile)
|
||||
get_wine_and_pfx "$2" "$3"
|
||||
start_portproton
|
||||
[[ "$tool" == winecfg || "$tool" == regedit ]] && export GST_PLUGIN_SYSTEM_PATH_1_0=""
|
||||
if [[ "$tool" == cmd ]] ; then
|
||||
cd "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c" || fatal "Prefix drive_c directory not found"
|
||||
PW_USE_TERMINAL=1 pw_run "$tool"
|
||||
else
|
||||
pw_run "$tool"
|
||||
fi
|
||||
pw_run winefile
|
||||
stop_portproton
|
||||
;;
|
||||
--winecfg)
|
||||
get_wine_and_pfx "$2" "$3"
|
||||
start_portproton
|
||||
export GST_PLUGIN_SYSTEM_PATH_1_0=""
|
||||
pw_run winecfg
|
||||
stop_portproton
|
||||
;;
|
||||
--winecmd)
|
||||
get_wine_and_pfx "$2" "$3"
|
||||
start_portproton
|
||||
cd "${PORT_DATA_PATH}/data/prefixes/${PW_PREFIX_NAME}/drive_c" || fatal "Prefix drive_c directory not found"
|
||||
PW_USE_TERMINAL=1 pw_run cmd
|
||||
stop_portproton
|
||||
;;
|
||||
--winereg)
|
||||
get_wine_and_pfx "$2" "$3"
|
||||
start_portproton
|
||||
export GST_PLUGIN_SYSTEM_PATH_1_0=""
|
||||
pw_run regedit
|
||||
stop_portproton
|
||||
;;
|
||||
--wine_uninstaller)
|
||||
get_wine_and_pfx "$2" "$3"
|
||||
start_portproton
|
||||
pw_run uninstaller
|
||||
stop_portproton
|
||||
;;
|
||||
--winetricks-list-all)
|
||||
@@ -575,7 +581,11 @@ Usage examples:
|
||||
exit 0
|
||||
;;
|
||||
--launch)
|
||||
portwine_launch
|
||||
if [[ "${PW_STEAMPLAY:-}" == "1" ]] ; then
|
||||
portwine_launch "${@:3}"
|
||||
else
|
||||
portwine_launch
|
||||
fi
|
||||
stop_portproton
|
||||
;;
|
||||
--stop)
|
||||
@@ -589,7 +599,11 @@ Usage examples:
|
||||
;;
|
||||
*)
|
||||
if [[ -f "$PW_EXE_FILE" ]] ; then
|
||||
portwine_launch
|
||||
if [[ "${PW_STEAMPLAY:-}" == "1" ]] ; then
|
||||
portwine_launch "${@:2}"
|
||||
else
|
||||
portwine_launch
|
||||
fi
|
||||
stop_portproton
|
||||
else
|
||||
fatal "File not found: $PW_EXE_FILE"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# Generate shell completion files for bash, zsh, and fish
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
|
||||
@@ -251,6 +251,13 @@ def main():
|
||||
|
||||
# Launch game via PortProton without GUI
|
||||
env_vars = os.environ.copy()
|
||||
from portprotonqt.steam_api import get_steam_runtime_library_paths
|
||||
steam_runtime_paths = get_steam_runtime_library_paths()
|
||||
if steam_runtime_paths:
|
||||
runtime_path = env_vars.get("STEAM_RUNTIME_LIBRARY_PATH", "")
|
||||
env_vars["STEAM_RUNTIME_LIBRARY_PATH"] = os.pathsep.join(
|
||||
path for path in [runtime_path, *steam_runtime_paths] if path
|
||||
)
|
||||
cmd = start_sh + [exe_path] + parsed_args.launch_args
|
||||
try:
|
||||
subprocess.run(cmd, env=env_vars)
|
||||
|
||||
@@ -237,17 +237,13 @@ class AppImageUpdateWorker(QThread):
|
||||
def _read_pty_output(self, master_fd: int, process: subprocess.Popen[bytes]) -> None:
|
||||
buffer = ""
|
||||
start_time = time.monotonic()
|
||||
while True:
|
||||
exited = process.poll() is not None
|
||||
while process.poll() is None:
|
||||
if time.monotonic() - start_time > APPIMAGE_UPDATE_TIMEOUT:
|
||||
process.kill()
|
||||
logger.warning("AppImage update timed out")
|
||||
return
|
||||
# The PTY can still contain output after the process exits.
|
||||
ready, _, _ = select.select([master_fd], [], [], 0 if exited else 0.2)
|
||||
ready, _, _ = select.select([master_fd], [], [], 0.2)
|
||||
if not ready:
|
||||
if exited:
|
||||
break
|
||||
continue
|
||||
try:
|
||||
data = os.read(master_fd, TOOL_OUTPUT_CHUNK_SIZE)
|
||||
|
||||
@@ -3,14 +3,12 @@
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from threading import Lock
|
||||
|
||||
from portprotonqt.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
_vk_gpu_info_output: str | None = None
|
||||
_vk_gpu_info_lock = Lock()
|
||||
_ANSI_RE = re.compile(r'\x1b\[[0-9;]*m|\[[0-9;]{1,8}m')
|
||||
_LOG_PREFIXES = ("Info:", "Warning:", "Error:")
|
||||
|
||||
@@ -19,9 +17,7 @@ def get_cached_vk_gpu_info() -> str:
|
||||
"""Get cached vk_gpu_info output, running it only once."""
|
||||
global _vk_gpu_info_output
|
||||
|
||||
with _vk_gpu_info_lock:
|
||||
if _vk_gpu_info_output is not None:
|
||||
return _vk_gpu_info_output
|
||||
if _vk_gpu_info_output is None:
|
||||
try:
|
||||
vk_gpu_info_path = os.path.join(
|
||||
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
|
||||
@@ -61,7 +57,7 @@ def get_cached_vk_gpu_info() -> str:
|
||||
logger.error("Error running vk_gpu_info: %s", e)
|
||||
_vk_gpu_info_output = ""
|
||||
|
||||
return _vk_gpu_info_output
|
||||
return _vk_gpu_info_output
|
||||
|
||||
|
||||
def _clean_vk_gpu_value(value: str) -> str:
|
||||
|
||||
@@ -140,7 +140,7 @@ def _add_source_corner(
|
||||
) -> None:
|
||||
"""Add source corner badge to cover frame."""
|
||||
source = game_source.lower()
|
||||
if source not in ("steam", "gog", "egs", "portproton", "native") or theme_manager is None:
|
||||
if source not in ("steam", "gog", "egs", "portproton") or theme_manager is None:
|
||||
return
|
||||
|
||||
icon_name = f"badge_{source}"
|
||||
|
||||
@@ -665,6 +665,11 @@ class ExeSettingsDialog(
|
||||
"PW_USE_GALLIUM_NINE",
|
||||
"PW_USE_SUPPLIED_DXVK_VKD3D",
|
||||
"PW_USE_INHIBIT_SLEEP",
|
||||
"PW_FIX_VIDEO_IN_GAME",
|
||||
"PW_USE_D7VK",
|
||||
"PW_USE_WINE_DXGI",
|
||||
"PW_USE_WINED3D_VULKAN",
|
||||
"PW_USE_GALLIUM_ZINK",
|
||||
})
|
||||
if exit_code != 0 or exit_status != QProcess.ExitStatus.NormalExit:
|
||||
for key in self.toggle_settings:
|
||||
|
||||
+77
-82
@@ -1,6 +1,5 @@
|
||||
from PySide6.QtCore import QObject, Signal, QThread, Qt, QCoreApplication
|
||||
import threading
|
||||
from tempfile import NamedTemporaryFile
|
||||
import os
|
||||
import time
|
||||
import requests
|
||||
@@ -12,9 +11,6 @@ from portprotonqt.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
FAILURE_RETRY_SECONDS = 30
|
||||
MAX_CACHED_FAILURES = 1024
|
||||
|
||||
|
||||
def get_default_user_agent() -> str:
|
||||
from portprotonqt.app import __app_version__
|
||||
@@ -30,58 +26,36 @@ def get_requests_session():
|
||||
session.verify = True
|
||||
return session
|
||||
|
||||
def is_complete_download(path: str | Path) -> bool:
|
||||
"""Check for a cached file, rejecting JPEGs without an end marker."""
|
||||
jpeg_start = b"\xff\xd8"
|
||||
jpeg_end = b"\xff\xd9"
|
||||
try:
|
||||
with open(path, "rb") as stream:
|
||||
header = stream.read(len(jpeg_start))
|
||||
if header != jpeg_start:
|
||||
return bool(header)
|
||||
stream.seek(-len(jpeg_end), os.SEEK_END)
|
||||
return stream.read() == jpeg_end
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _save_download(response: requests.Response, local_path: str, timeout: float) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
total_size = int(response.headers.get('Content-Length', 0))
|
||||
destination = Path(local_path)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
with NamedTemporaryFile(dir=destination.parent, delete=False) as stream:
|
||||
temporary = Path(stream.name)
|
||||
try:
|
||||
with tqdm(total=total_size or None, unit='B', unit_scale=True,
|
||||
unit_divisor=1024, desc=f"Downloading {destination.name}", ascii=True) as pbar:
|
||||
for chunk in response.iter_content(chunk_size=8192):
|
||||
if time.monotonic() > deadline:
|
||||
raise requests.exceptions.ReadTimeout(f"Download exceeded {timeout}s total timeout")
|
||||
if chunk:
|
||||
stream.write(chunk)
|
||||
pbar.update(len(chunk))
|
||||
stream.close()
|
||||
if not is_complete_download(temporary):
|
||||
raise OSError("Incomplete JPEG download")
|
||||
temporary.replace(destination)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def download_with_cache(url, local_path, timeout=5, downloader_instance=None):
|
||||
if is_complete_download(local_path):
|
||||
if os.path.exists(local_path):
|
||||
return local_path
|
||||
session = get_requests_session()
|
||||
try:
|
||||
with session.get(url, stream=True, timeout=timeout) as response:
|
||||
response.raise_for_status()
|
||||
_save_download(response, local_path, timeout)
|
||||
deadline = time.monotonic() + timeout
|
||||
total_size = int(response.headers.get('Content-Length', 0))
|
||||
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
||||
desc = Path(local_path).name
|
||||
with tqdm(total=total_size if total_size > 0 else None,
|
||||
unit='B', unit_scale=True, unit_divisor=1024,
|
||||
desc=f"Downloading {desc}", ascii=True) as pbar:
|
||||
with open(local_path, 'wb') as f:
|
||||
for chunk in response.iter_content(chunk_size=8192):
|
||||
if time.monotonic() > deadline:
|
||||
raise requests.exceptions.ReadTimeout(
|
||||
f"Download exceeded {timeout}s total timeout for {url}"
|
||||
)
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
pbar.update(len(chunk))
|
||||
return local_path
|
||||
except Exception as e:
|
||||
logger.error(f"Download error {url}: {e}")
|
||||
if downloader_instance is not None:
|
||||
downloader_instance._record_failure(url)
|
||||
if downloader_instance and hasattr(downloader_instance, '_last_error'):
|
||||
downloader_instance._last_error[url] = True
|
||||
if os.path.exists(local_path):
|
||||
os.remove(local_path)
|
||||
return None
|
||||
|
||||
class Downloader(QObject):
|
||||
@@ -92,7 +66,7 @@ class Downloader(QObject):
|
||||
super().__init__()
|
||||
self.max_workers = max_workers
|
||||
self._cache = {}
|
||||
self._last_error: dict[str, float] = {}
|
||||
self._last_error = {}
|
||||
self._locks = {}
|
||||
self._active_threads: list[QThread] = []
|
||||
self._global_lock = threading.Lock()
|
||||
@@ -102,23 +76,6 @@ class Downloader(QObject):
|
||||
if callback:
|
||||
callback(result)
|
||||
|
||||
def _record_failure(self, url: str) -> None:
|
||||
with self._global_lock:
|
||||
self._last_error.pop(url, None)
|
||||
self._last_error[url] = time.monotonic() + FAILURE_RETRY_SECONDS
|
||||
if len(self._last_error) > MAX_CACHED_FAILURES:
|
||||
del self._last_error[next(iter(self._last_error))]
|
||||
|
||||
def _has_recent_failure(self, url: str) -> bool:
|
||||
# Call with the global lock held.
|
||||
expires = self._last_error.get(url)
|
||||
if expires is None:
|
||||
return False
|
||||
if time.monotonic() < expires:
|
||||
return True
|
||||
del self._last_error[url]
|
||||
return False
|
||||
|
||||
def _get_url_lock(self, url):
|
||||
with self._global_lock:
|
||||
if url not in self._locks:
|
||||
@@ -144,7 +101,7 @@ class Downloader(QObject):
|
||||
last_request_time = [0.0]
|
||||
|
||||
def _download_one(url, local_path):
|
||||
if is_complete_download(local_path):
|
||||
if os.path.exists(local_path):
|
||||
return local_path
|
||||
try:
|
||||
with rate_limit_lock:
|
||||
@@ -155,7 +112,22 @@ class Downloader(QObject):
|
||||
|
||||
with session.get(url, stream=True, timeout=timeout) as response:
|
||||
response.raise_for_status()
|
||||
_save_download(response, local_path, timeout)
|
||||
deadline = time.monotonic() + timeout
|
||||
total_size = int(response.headers.get('Content-Length', 0))
|
||||
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
||||
desc = Path(local_path).name
|
||||
with tqdm(total=total_size if total_size > 0 else None,
|
||||
unit='B', unit_scale=True, unit_divisor=1024,
|
||||
desc=f"Downloading {desc}", ascii=True) as pbar:
|
||||
with open(local_path, 'wb') as f:
|
||||
for chunk in response.iter_content(chunk_size=8192):
|
||||
if time.monotonic() > deadline:
|
||||
raise requests.exceptions.ReadTimeout(
|
||||
f"Download exceeded {timeout}s total timeout for {url}"
|
||||
)
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
pbar.update(len(chunk))
|
||||
return local_path
|
||||
except requests.exceptions.HTTPError as e:
|
||||
if e.response is not None and e.response.status_code == 429:
|
||||
@@ -164,19 +136,43 @@ class Downloader(QObject):
|
||||
try:
|
||||
with session.get(url, stream=True, timeout=timeout) as response:
|
||||
response.raise_for_status()
|
||||
_save_download(response, local_path, timeout)
|
||||
deadline = time.monotonic() + timeout
|
||||
total_size = int(response.headers.get('Content-Length', 0))
|
||||
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
||||
desc = Path(local_path).name
|
||||
with tqdm(total=total_size if total_size > 0 else None,
|
||||
unit='B', unit_scale=True, unit_divisor=1024,
|
||||
desc=f"Downloading {desc}", ascii=True) as pbar:
|
||||
with open(local_path, 'wb') as f:
|
||||
for chunk in response.iter_content(chunk_size=8192):
|
||||
if time.monotonic() > deadline:
|
||||
raise requests.exceptions.ReadTimeout(
|
||||
f"Download exceeded {timeout}s total timeout for {url}"
|
||||
)
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
pbar.update(len(chunk))
|
||||
return local_path
|
||||
except Exception as retry_e:
|
||||
logger.error(f"Retry download error {url}: {retry_e}")
|
||||
self._record_failure(url)
|
||||
with self._global_lock:
|
||||
self._last_error[url] = True
|
||||
if os.path.exists(local_path):
|
||||
os.remove(local_path)
|
||||
return None
|
||||
else:
|
||||
logger.error(f"Download error {url}: {e}")
|
||||
self._record_failure(url)
|
||||
with self._global_lock:
|
||||
self._last_error[url] = True
|
||||
if os.path.exists(local_path):
|
||||
os.remove(local_path)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Download error {url}: {e}")
|
||||
self._record_failure(url)
|
||||
with self._global_lock:
|
||||
self._last_error[url] = True
|
||||
if os.path.exists(local_path):
|
||||
os.remove(local_path)
|
||||
return None
|
||||
|
||||
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
||||
@@ -197,12 +193,12 @@ class Downloader(QObject):
|
||||
|
||||
def download(self, url, local_path, timeout=5):
|
||||
with self._global_lock:
|
||||
if self._has_recent_failure(url):
|
||||
if url in self._last_error:
|
||||
logger.warning(f"Previous download error for {url}, skipping")
|
||||
return None
|
||||
if url in self._cache:
|
||||
cached_path = self._cache[url]
|
||||
if is_complete_download(cached_path):
|
||||
if os.path.exists(cached_path):
|
||||
if os.path.abspath(cached_path) == os.path.abspath(local_path):
|
||||
return cached_path
|
||||
else:
|
||||
@@ -210,11 +206,11 @@ class Downloader(QObject):
|
||||
url_lock = self._get_url_lock(url)
|
||||
with url_lock:
|
||||
with self._global_lock:
|
||||
if self._has_recent_failure(url):
|
||||
if url in self._last_error:
|
||||
return None
|
||||
if url in self._cache:
|
||||
cached_path = self._cache[url]
|
||||
if is_complete_download(cached_path) and os.path.abspath(cached_path) == os.path.abspath(local_path):
|
||||
if os.path.exists(cached_path) and os.path.abspath(cached_path) == os.path.abspath(local_path):
|
||||
return cached_path
|
||||
result = download_with_cache(url, local_path, timeout, self)
|
||||
with self._global_lock:
|
||||
@@ -238,14 +234,14 @@ class Downloader(QObject):
|
||||
emitted_urls = set()
|
||||
with self._global_lock:
|
||||
for url, path in zip(urls, local_paths, strict=False):
|
||||
if self._has_recent_failure(url):
|
||||
if url in self._last_error:
|
||||
logger.warning(f"Previous download error for {url}, skipping")
|
||||
if on_result and url not in emitted_urls:
|
||||
on_result(url, None)
|
||||
emitted_urls.add(url)
|
||||
continue
|
||||
cached_path = self._cache.get(url)
|
||||
if (cached_path and is_complete_download(cached_path)
|
||||
if (cached_path and os.path.exists(cached_path)
|
||||
and os.path.abspath(cached_path) == os.path.abspath(path)):
|
||||
if on_result and url not in emitted_urls:
|
||||
on_result(url, cached_path)
|
||||
@@ -277,7 +273,7 @@ class Downloader(QObject):
|
||||
final_results = {}
|
||||
with self._global_lock:
|
||||
for url in urls:
|
||||
if self._has_recent_failure(url):
|
||||
if url in self._last_error:
|
||||
final_results[url] = None
|
||||
elif url in self._cache:
|
||||
final_results[url] = self._cache[url]
|
||||
@@ -292,10 +288,9 @@ class Downloader(QObject):
|
||||
|
||||
def download_async(self, url: str, local_path: str, timeout: int = 5, callback: Callable[[str | None], None] | None = None, parallel: bool = False) -> QThread | None:
|
||||
with self._global_lock:
|
||||
previous_error = self._has_recent_failure(url)
|
||||
cached = not previous_error and is_complete_download(local_path)
|
||||
if cached:
|
||||
with self._global_lock:
|
||||
previous_error = url in self._last_error
|
||||
cached = not previous_error and os.path.exists(local_path)
|
||||
if cached:
|
||||
self._cache[url] = local_path
|
||||
if previous_error or cached:
|
||||
result = local_path if cached else None
|
||||
|
||||
@@ -517,7 +517,7 @@ class GameCard(AnimatedCard):
|
||||
self.egsLabel.setVisible(self.egs_visible and not self.vertical_layout)
|
||||
|
||||
self.nativeLabel = SourceCorner(
|
||||
icon=self.theme_manager.get_icon("badge_native", as_path=True),
|
||||
icon=self.theme_manager.get_icon("badge_linux", as_path=True),
|
||||
config=corner_config,
|
||||
parent=self.coverWidget,
|
||||
)
|
||||
@@ -669,7 +669,7 @@ class GameCard(AnimatedCard):
|
||||
(self.steamLabel, "badge_steam"),
|
||||
(self.gogLabel, "badge_gog"),
|
||||
(self.egsLabel, "badge_egs"),
|
||||
(self.nativeLabel, "badge_native"),
|
||||
(self.nativeLabel, "badge_linux"),
|
||||
(self.portprotonLabel, "badge_portproton"),
|
||||
):
|
||||
icon = self.theme_manager.get_icon(
|
||||
@@ -817,8 +817,9 @@ class GameCard(AnimatedCard):
|
||||
radius = int(self.card_layout_cfg.get("cover_radius", 8) * self._scale)
|
||||
aspect_mode = Qt.AspectRatioMode.KeepAspectRatio
|
||||
else:
|
||||
target_width = self.coverLabel.minimumWidth()
|
||||
target_height = self.coverLabel.minimumHeight()
|
||||
target_width = int(self.base_card_width * self._scale)
|
||||
cover_ratio = self.card_layout_cfg.get("cover_aspect_ratio", 1.5)
|
||||
target_height = int(target_width * cover_ratio)
|
||||
radius = int(self.card_layout_cfg.get("cover_radius", 15) * self._scale)
|
||||
aspect_mode = Qt.AspectRatioMode.KeepAspectRatioByExpanding
|
||||
scaled_pixmap = self.base_pixmap.scaled(
|
||||
@@ -827,12 +828,6 @@ class GameCard(AnimatedCard):
|
||||
aspect_mode,
|
||||
Qt.TransformationMode.SmoothTransformation,
|
||||
)
|
||||
if not self.list_layout:
|
||||
scaled_pixmap = scaled_pixmap.copy(
|
||||
(scaled_pixmap.width() - target_width) // 2,
|
||||
(scaled_pixmap.height() - target_height) // 2,
|
||||
target_width, target_height,
|
||||
)
|
||||
rounded_pixmap = round_corners(scaled_pixmap, radius)
|
||||
try:
|
||||
self.coverLabel.setPixmap(rounded_pixmap)
|
||||
|
||||
@@ -699,11 +699,11 @@ class GameLibraryManager:
|
||||
self.gamesListLayout.setEnabled(False) # Disable layout during batch
|
||||
|
||||
try:
|
||||
favorites_set = set(favorites)
|
||||
|
||||
# Optimized sorting: Partition favorites first, then sort subgroups
|
||||
def partition_sort_key(game):
|
||||
name = game[0]
|
||||
fav_order = 0 if name in favorites_set else 1
|
||||
is_fav = name in favorites
|
||||
fav_order = 0 if is_fav else 1
|
||||
if sort_method == "playtime":
|
||||
return (fav_order, -game[11] if game[11] else 0, -game[10] if game[10] else 0)
|
||||
elif sort_method == "alphabetical":
|
||||
@@ -711,7 +711,13 @@ class GameLibraryManager:
|
||||
else:
|
||||
return (fav_order, -game[10] if game[10] else 0, -game[11] if game[11] else 0)
|
||||
|
||||
sorted_games = sorted(games_list, key=partition_sort_key)
|
||||
# Quick partition: Sort favorites and non-favorites separately, then merge
|
||||
favorites_set = set(favorites) # Convert to set for O(1) lookup
|
||||
fav_games = [g for g in games_list if g[0] in favorites_set]
|
||||
non_fav_games = [g for g in games_list if g[0] not in favorites_set]
|
||||
sorted_fav = sorted(fav_games, key=partition_sort_key)
|
||||
sorted_non_fav = sorted(non_fav_games, key=partition_sort_key)
|
||||
sorted_games = sorted_fav + sorted_non_fav
|
||||
if self.layout_mode == "horizontal_top":
|
||||
limit = self.theme.horizontalTopGameLimit
|
||||
tile_games = sorted_games[limit:limit + self.theme.fullLibraryTileGameCount]
|
||||
@@ -964,10 +970,14 @@ class GameLibraryManager:
|
||||
child = layout.takeAt(0)
|
||||
if child.widget():
|
||||
widget = child.widget()
|
||||
if self.main_window.current_focused_card is widget:
|
||||
self.main_window.current_focused_card = None
|
||||
if self.main_window.current_hovered_card is widget:
|
||||
self.main_window.current_hovered_card = None
|
||||
# Clean up cache if widget exists in it
|
||||
for key, card in list(self.game_card_cache.items()):
|
||||
if card == widget:
|
||||
del self.game_card_cache[key]
|
||||
if key in self.pending_images:
|
||||
del self.pending_images[key]
|
||||
break
|
||||
# Always schedule widget for deletion regardless of cache state
|
||||
if isinstance(widget, GameCard):
|
||||
widget.cleanup()
|
||||
if widget is self.fullLibraryTile:
|
||||
|
||||
+14
-68
@@ -10,7 +10,6 @@ import time
|
||||
import zlib
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from html import unescape
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
@@ -316,12 +315,7 @@ class GOGAPI:
|
||||
def load_library(self) -> list[dict]:
|
||||
"""Load the cached GOG library."""
|
||||
data = self._load_json(self.library_path, [])
|
||||
if not isinstance(data, list):
|
||||
return []
|
||||
for game in data:
|
||||
if isinstance(game, dict) and isinstance(game.get("description"), str):
|
||||
game["description"] = self._short_description(game["description"])
|
||||
return data
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
def clear_library_cache(self) -> None:
|
||||
"""Remove cached GOG covers and descriptions."""
|
||||
@@ -696,7 +690,7 @@ class GOGAPI:
|
||||
),
|
||||
{},
|
||||
)
|
||||
description = self._short_description(self._localized_value(data.get("summary")))
|
||||
description = self._localized_value(data.get("summary"))
|
||||
language = get_metadata_language().lower()
|
||||
try:
|
||||
product_response = requests.get(
|
||||
@@ -709,11 +703,18 @@ class GOGAPI:
|
||||
)
|
||||
product_response.raise_for_status()
|
||||
product_description = product_response.json().get("description", {})
|
||||
description = (
|
||||
self._short_description(str(product_description.get("lead") or ""))
|
||||
or self._short_description(str(product_description.get("full") or ""))
|
||||
or description
|
||||
)
|
||||
localized_lead = str(product_description.get("lead") or "")
|
||||
if localized_lead:
|
||||
paragraphs = re.split(
|
||||
r"(?:<br\s*/?>\s*){2,}", localized_lead, flags=re.IGNORECASE
|
||||
)
|
||||
paragraph_count = (
|
||||
2 if re.match(r"\s*<(?:b|strong)>", paragraphs[0], re.IGNORECASE)
|
||||
else 1
|
||||
)
|
||||
description = "<br><br>".join(
|
||||
paragraph.strip() for paragraph in paragraphs[:paragraph_count]
|
||||
)
|
||||
except requests.RequestException as error:
|
||||
logger.warning(
|
||||
"Failed to load localized GOG description for %s: %s",
|
||||
@@ -731,61 +732,6 @@ class GOGAPI:
|
||||
"steam_appid": str(steam_release.get("external_id", "")),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _short_description(description: str) -> str:
|
||||
# GOG uses these modules for storefront callouts, not the synopsis.
|
||||
intro = re.sub(
|
||||
r"<p\b[^>]*\bclass\s*=\s*(['\"])module\1[^>]*>.*?</p\s*>", "",
|
||||
description, flags=re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
# Store cross-sells start with a linked cover inside an overflow box.
|
||||
intro = re.sub(
|
||||
r"<div\s+style=(['\"])overflow:\s*hidden;?\1\s*>\s*"
|
||||
r"<a\b[^>]*>\s*<img\b[^>]*>\s*</a>.*?</div\s*>",
|
||||
"", intro, flags=re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
intro = re.sub(r"<img\b[^>]*>", "", intro, flags=re.IGNORECASE)
|
||||
intro = re.split(r"<(?:ul|ol|li)\b", intro, maxsplit=1, flags=re.IGNORECASE)[0]
|
||||
intro = re.sub(
|
||||
r"(?:<b>\s*)?<h[1-6]\b[^>]*>.*?</h[1-6]\s*>(?:\s*</b>)?",
|
||||
"<br><br>", intro,
|
||||
flags=re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
paragraphs = re.split(
|
||||
r"(?:<br\s*/?>\s*){2,}|</?(?:p|div|hr)\b[^>]*>|\r?\n[ \t]*\r?\n",
|
||||
intro, flags=re.IGNORECASE,
|
||||
)
|
||||
content = []
|
||||
for paragraph in paragraphs:
|
||||
text = unescape(re.sub(r"<[^>]*>", "", paragraph)).strip()
|
||||
if not text or re.fullmatch(
|
||||
r"(?:Внимание!\s*)?В этой игре нет русской локализации\.?"
|
||||
r"|The full version of .+? is available on GOG\.com\.\s+"
|
||||
r"You can (?:buy|purchase) it here[.!]?",
|
||||
text, re.IGNORECASE,
|
||||
):
|
||||
continue
|
||||
paragraph = re.sub(
|
||||
r"^(?:\s*<br\s*/?>)+|(?:(?:<br\s*/?>| )\s*)+$", "", paragraph,
|
||||
flags=re.IGNORECASE,
|
||||
).strip()
|
||||
if re.search(r"</?[a-z][^>]*>", paragraph, re.IGNORECASE):
|
||||
# Qt's AutoText detection stops at the first plain newline.
|
||||
paragraph = re.sub(r"<(/?)strong\s*>", r"<\1b>", paragraph, flags=re.IGNORECASE)
|
||||
paragraph = re.sub(r"(?:\r?\n)+", "<br>", paragraph)
|
||||
content.append(paragraph)
|
||||
paragraphs = content
|
||||
# Prefer the synopsis over a standalone italic epigraph.
|
||||
if len(paragraphs) > 1 and re.fullmatch(
|
||||
r"(?:(?:<b>|<strong>))*<(i|em)>[^<]*</\1>(?:(?:</b>|</strong>))*",
|
||||
paragraphs[0], re.IGNORECASE,
|
||||
):
|
||||
return paragraphs[1]
|
||||
# Keep a standalone bold notice together with the introduction.
|
||||
if paragraphs and re.fullmatch(r"<(b|strong)>[^<]*</\1>", paragraphs[0], re.IGNORECASE):
|
||||
return "<br><br>".join(paragraphs[:2])
|
||||
return paragraphs[0] if paragraphs else ""
|
||||
|
||||
@staticmethod
|
||||
def _localized_value(values: dict | None) -> str:
|
||||
if not isinstance(values, dict):
|
||||
|
||||
@@ -23,22 +23,20 @@ class GameEntry:
|
||||
class SearchConfig:
|
||||
"""Search configuration."""
|
||||
token: str
|
||||
hp_key: str | None = None
|
||||
hp_val: str | None = None
|
||||
hp_key: str
|
||||
hp_val: str
|
||||
|
||||
class HTTPClient:
|
||||
"""HTTP client for HowLongToBeat API."""
|
||||
BASE_URL = 'https://howlongtobeat.com/'
|
||||
SEARCH_URL = BASE_URL + "api/search/site"
|
||||
AUTH_URL = SEARCH_URL + "/init"
|
||||
AUTH_URL = BASE_URL + "api/bleed/init"
|
||||
SEARCH_URL = BASE_URL + "api/bleed"
|
||||
|
||||
def __init__(self, timeout: int = 60):
|
||||
self.timeout = timeout
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update({
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
|
||||
'Accept': 'application/json',
|
||||
'Origin': self.BASE_URL.rstrip('/'),
|
||||
'referer': self.BASE_URL
|
||||
})
|
||||
proxy_settings = proxy_config.get_proxy()
|
||||
@@ -54,18 +52,15 @@ class HTTPClient:
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
except requests.RequestException as exc:
|
||||
status = exc.response.status_code if exc.response is not None else type(exc).__name__
|
||||
logger.warning("HLTB initialization failed: %s", status)
|
||||
except (requests.RequestException, ValueError):
|
||||
return None
|
||||
token = data.get("token") if isinstance(data, dict) else None
|
||||
if not isinstance(token, str) or not token:
|
||||
logger.warning("HLTB initialization returned no token")
|
||||
if not data.get("token") or not data.get("hpKey") or not data.get("hpVal"):
|
||||
return None
|
||||
hp_key, hp_val = data.get("hpKey"), data.get("hpVal")
|
||||
if isinstance(hp_key, str) and hp_key and isinstance(hp_val, str) and hp_val:
|
||||
return SearchConfig(token, hp_key, hp_val)
|
||||
return SearchConfig(token)
|
||||
return SearchConfig(
|
||||
token=data["token"],
|
||||
hp_key=data["hpKey"],
|
||||
hp_val=data["hpVal"]
|
||||
)
|
||||
|
||||
def search_games(self, game_name: str, page: int = 1, config: SearchConfig | None = None) -> str | None:
|
||||
if not config:
|
||||
@@ -76,10 +71,11 @@ class HTTPClient:
|
||||
payload = self._build_search_payload(game_name, page, config)
|
||||
headers = {
|
||||
'content-type': 'application/json',
|
||||
'x-auth-token': config.token
|
||||
'accept': '*/*',
|
||||
'x-auth-token': config.token,
|
||||
'x-hp-key': config.hp_key,
|
||||
'x-hp-val': config.hp_val
|
||||
}
|
||||
if config.hp_key and config.hp_val:
|
||||
headers.update({'x-hp-key': config.hp_key, 'x-hp-val': config.hp_val})
|
||||
try:
|
||||
response = self.session.post(
|
||||
self.SEARCH_URL,
|
||||
@@ -110,15 +106,14 @@ class HTTPClient:
|
||||
'platform': "",
|
||||
'sortCategory': "popular",
|
||||
'rangeCategory': "main",
|
||||
'rangeTime': {'min': None, 'max': None},
|
||||
'rangeTime': {'min': 0, 'max': 0},
|
||||
'gameplay': {
|
||||
'perspective': "",
|
||||
'flow': "",
|
||||
'genre': "",
|
||||
"difficulty": ""
|
||||
},
|
||||
'year': "",
|
||||
'modifier': ""
|
||||
'rangeYear': {'max': "", 'min': ""}
|
||||
},
|
||||
'users': {'sortCategory': "postcount"},
|
||||
'lists': {'sortCategory': "follows"},
|
||||
@@ -126,10 +121,10 @@ class HTTPClient:
|
||||
'sort': 0,
|
||||
'randomizer': 0
|
||||
},
|
||||
'useCache': True
|
||||
'useCache': True,
|
||||
'fields': ["comp_main", "comp_plus", "comp_100"]
|
||||
}
|
||||
if config.hp_key and config.hp_val:
|
||||
payload[config.hp_key] = config.hp_val
|
||||
payload[config.hp_key] = config.hp_val
|
||||
return payload
|
||||
|
||||
class ResultParser:
|
||||
|
||||
@@ -10,7 +10,7 @@ from PySide6.QtWidgets import QSpacerItem, QGraphicsPixmapItem, QDialog, QApplic
|
||||
from PIL import Image, ImageQt, ImageSequence
|
||||
from portprotonqt.config import CACHE_DIR, ui_config
|
||||
from portprotonqt.theme_manager import ThemeManager, load_theme
|
||||
from portprotonqt.downloader import Downloader, is_complete_download
|
||||
from portprotonqt.downloader import Downloader
|
||||
from portprotonqt.icon_extractor import generate_thumbnail
|
||||
from portprotonqt.logger import get_logger
|
||||
from portprotonqt.qt_utils import get_device_pixel_ratio
|
||||
@@ -223,12 +223,10 @@ def set_animated_cover(label: QLabel, path: str, width: int, height: int, radius
|
||||
if not QFile.exists(path):
|
||||
return False
|
||||
if ext in (".png", ".apng") and _is_png_cover(path):
|
||||
_set_cover_mask(label, width, height, radius)
|
||||
animation = _PillowAnimatedCover(label, path, width, height, radius)
|
||||
if not animation.start():
|
||||
label.removeEventFilter(animation)
|
||||
animation.deleteLater()
|
||||
return False
|
||||
_set_cover_mask(label, width, height, radius)
|
||||
_animated_cover_movies[label] = animation
|
||||
_animated_cover_radii[label] = radius
|
||||
return True
|
||||
@@ -471,7 +469,7 @@ def load_pixmap_async(
|
||||
appid = parts[idx + 1]
|
||||
if appid:
|
||||
local_path = os.path.join(image_folder, f"{appid}.jpg")
|
||||
if is_complete_download(local_path):
|
||||
if os.path.exists(local_path):
|
||||
pixmap = QPixmap(local_path)
|
||||
# Check if the pixmap loaded successfully
|
||||
if pixmap.isNull():
|
||||
@@ -508,7 +506,7 @@ def load_pixmap_async(
|
||||
local_path = os.path.join(image_folder, filename)
|
||||
|
||||
logger.debug("SGDB cover check: %s exists=%s", local_path, os.path.exists(local_path))
|
||||
if is_complete_download(local_path):
|
||||
if os.path.exists(local_path):
|
||||
pixmap = QPixmap(local_path)
|
||||
# Check if the pixmap loaded successfully
|
||||
if pixmap.isNull():
|
||||
@@ -545,7 +543,7 @@ def load_pixmap_async(
|
||||
if not filename:
|
||||
filename = f"{app_name}{_get_cover_url_suffix(cover)}"
|
||||
local_path = os.path.join(image_folder, filename)
|
||||
if is_complete_download(local_path):
|
||||
if os.path.exists(local_path):
|
||||
pixmap = QPixmap(local_path)
|
||||
# Check if the pixmap loaded successfully
|
||||
if pixmap.isNull():
|
||||
|
||||
@@ -290,7 +290,6 @@ class InputManager(
|
||||
except Exception as e:
|
||||
logger.error("EMUL: Error closing virtual mouse: %s", e)
|
||||
self.ui = None
|
||||
self._keyboard_mouse_drag = False
|
||||
self.mouse_emulation_thread = None
|
||||
self.stick_x_raw = 0
|
||||
self.stick_y_raw = 0
|
||||
@@ -441,7 +440,6 @@ class InputManager(
|
||||
except Exception as e:
|
||||
logger.error("EMUL: Error closing virtual mouse: %s", e)
|
||||
self.ui = None
|
||||
self._keyboard_mouse_drag = False
|
||||
self.mouse_emulation_enabled = False
|
||||
self.stick_x_raw = 0
|
||||
self.stick_y_raw = 0
|
||||
@@ -524,15 +522,6 @@ class InputManager(
|
||||
self.ui.write(ecodes.EV_REL, ecodes.REL_WHEEL, steps)
|
||||
self.ui.syn()
|
||||
|
||||
def _set_keyboard_mouse_drag(self, held: bool) -> bool:
|
||||
if held == getattr(self, '_keyboard_mouse_drag', False):
|
||||
return False
|
||||
if self.ui:
|
||||
self.ui.write(ecodes.EV_KEY, ecodes.BTN_LEFT, int(held))
|
||||
self.ui.syn()
|
||||
self._keyboard_mouse_drag = held
|
||||
return True
|
||||
|
||||
def click_left(self):
|
||||
"""Left mouse button click"""
|
||||
if self.ui:
|
||||
|
||||
@@ -313,7 +313,7 @@ class DpadInputMixin(InputMixin):
|
||||
def handle_dpad_slot(self, code: int, value: int, current_time: float) -> None:
|
||||
keyboard = getattr(self._parent, 'system_keyboard', None)
|
||||
if keyboard is not None and keyboard.isVisible():
|
||||
if value == 0 or self._should_skip_regular_events():
|
||||
if value == 0:
|
||||
self._reset_dpad_repeat()
|
||||
return
|
||||
directions = {PAD_DPAD_X: ('left', 'right'), PAD_AXIS_LEFT_X: ('left', 'right'),
|
||||
|
||||
@@ -15,6 +15,7 @@ from PySide6.QtWidgets import (
|
||||
QListWidget,
|
||||
QMenu,
|
||||
QMessageBox,
|
||||
QScrollArea,
|
||||
QTableWidget,
|
||||
QWidget,
|
||||
)
|
||||
@@ -472,12 +473,16 @@ class KeyboardInputMixin(InputMixin):
|
||||
def _focus_first_game_card(self, container: QWidget | None) -> bool:
|
||||
if container is None:
|
||||
return False
|
||||
cards = [card for card in container.findChildren(AnimatedCard) if card.isVisible() and card.isEnabled()]
|
||||
if not cards:
|
||||
return False
|
||||
first_card = min(cards, key=lambda card: (card.y(), card.x()))
|
||||
self._focus_grid_card(first_card)
|
||||
return True
|
||||
for card in container.findChildren(AnimatedCard):
|
||||
if card.isVisible() and card.isEnabled():
|
||||
card.setFocus(Qt.FocusReason.OtherFocusReason)
|
||||
scroll_area = container.parentWidget()
|
||||
while scroll_area and not isinstance(scroll_area, QScrollArea):
|
||||
scroll_area = scroll_area.parentWidget()
|
||||
if isinstance(scroll_area, QScrollArea):
|
||||
scroll_area.ensureWidgetVisible(card, 50, 50)
|
||||
return True
|
||||
return False
|
||||
|
||||
def _focus_first_library_card(self) -> bool:
|
||||
container = getattr(self._parent, "gamesListWidget", None)
|
||||
|
||||
@@ -115,7 +115,6 @@ class GamepadRuntimeMixin(InputMixin):
|
||||
|
||||
def _reset_input_state(self) -> None:
|
||||
"""Reset cached joystick state when the active device changes."""
|
||||
self._set_keyboard_mouse_drag(False)
|
||||
self._button_states.clear()
|
||||
self._hat_states.clear()
|
||||
self._axis_states.clear()
|
||||
@@ -234,8 +233,6 @@ class GamepadRuntimeMixin(InputMixin):
|
||||
if self._button_states.get(button_index) == value:
|
||||
return
|
||||
self._button_states[button_index] = value
|
||||
if not value and button_code in BUTTONS['confirm'] and self._set_keyboard_mouse_drag(False):
|
||||
return
|
||||
if getattr(self._parent, "boot_animation", None) is not None:
|
||||
self.button_event.emit(button_code, value)
|
||||
return
|
||||
@@ -269,7 +266,6 @@ class GamepadRuntimeMixin(InputMixin):
|
||||
(button_code == PAD_BUTTON_START and self.select_held)
|
||||
)
|
||||
if emulation_combo:
|
||||
self._set_keyboard_mouse_drag(False)
|
||||
self.emulation_triggered = not self.emulation_triggered
|
||||
self.pending_menu_fullscreen_time = 0.0
|
||||
return emulation_combo
|
||||
@@ -292,9 +288,6 @@ class GamepadRuntimeMixin(InputMixin):
|
||||
keyboard.toggle()
|
||||
return True
|
||||
if keyboard.isVisible():
|
||||
if button_code in BUTTONS['confirm'] and self._is_mouse_emulation_active() and self.ui:
|
||||
self._set_keyboard_mouse_drag(bool(value))
|
||||
return True
|
||||
actions = {'confirm': 'confirm', 'back': 'back', 'menu': 'back',
|
||||
'prev_tab': 'language', 'next_tab': 'shift', 'add_game': 'backspace'}
|
||||
if button_code == PAD_BUTTON_START and not value:
|
||||
@@ -337,9 +330,9 @@ class GamepadRuntimeMixin(InputMixin):
|
||||
elif hat_value[0] > 0:
|
||||
self.move_mouse(10, 0)
|
||||
if previous_value[1] != hat_value[1]:
|
||||
if hat_value[1] < 0:
|
||||
if hat_value[1] > 0:
|
||||
self.move_mouse(0, -10)
|
||||
elif hat_value[1] > 0:
|
||||
elif hat_value[1] < 0:
|
||||
self.move_mouse(0, 10)
|
||||
|
||||
if self._should_skip_regular_events():
|
||||
@@ -394,13 +387,16 @@ class GamepadRuntimeMixin(InputMixin):
|
||||
|
||||
def _is_mouse_emulation_active(self) -> bool:
|
||||
"""Return True when the gamepad currently drives mouse emulation."""
|
||||
keyboard = getattr(getattr(self, '_parent', None), 'system_keyboard', None)
|
||||
if keyboard is not None and keyboard.isVisible():
|
||||
return False
|
||||
return self.mouse_emulation_enabled and self.emulation_active and self.emulation_triggered
|
||||
|
||||
def _should_skip_regular_events(self) -> bool:
|
||||
"""Skip regular UI events while mouse emulation owns the controller."""
|
||||
keyboard = getattr(getattr(self, '_parent', None), 'system_keyboard', None)
|
||||
if keyboard is not None and keyboard.isVisible():
|
||||
return self._is_mouse_emulation_active() and bool(self.ui)
|
||||
return False
|
||||
if getattr(self, '_gamepad_polling_suspended', False):
|
||||
return True
|
||||
return self._is_mouse_emulation_active() and QApplication.activeWindow() is not None
|
||||
|
||||
@@ -420,13 +420,6 @@ msgstr ""
|
||||
msgid "Refresh Grid"
|
||||
msgstr ""
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr ""
|
||||
|
||||
msgid "Never"
|
||||
msgstr ""
|
||||
|
||||
@@ -486,6 +479,9 @@ msgstr ""
|
||||
msgid "PortProton start script not found"
|
||||
msgstr ""
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr ""
|
||||
|
||||
msgid "Invalid command format (empty exec line)"
|
||||
msgstr ""
|
||||
|
||||
@@ -493,7 +489,7 @@ msgid "Invalid command format (native)"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr ""
|
||||
|
||||
msgid "Choose Folder"
|
||||
@@ -696,10 +692,9 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr ""
|
||||
|
||||
#, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
msgstr ""
|
||||
|
||||
msgid "CPU Cores Limit"
|
||||
@@ -800,6 +795,10 @@ msgstr ""
|
||||
msgid "No favorites"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr ""
|
||||
|
||||
msgid "Debug log mode was launched"
|
||||
msgstr ""
|
||||
|
||||
@@ -1063,6 +1062,10 @@ msgstr ""
|
||||
msgid "Download Selected"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Error loading WINE/Proton: {error}"
|
||||
msgstr ""
|
||||
|
||||
msgid "Version WINE/Proton"
|
||||
msgstr ""
|
||||
|
||||
@@ -1082,9 +1085,6 @@ msgstr ""
|
||||
msgid "Select to remove this WINE/Proton"
|
||||
msgstr ""
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Selected {} WINE/Proton:\n"
|
||||
msgstr ""
|
||||
@@ -1189,9 +1189,6 @@ msgstr ""
|
||||
msgid "Exe Settings"
|
||||
msgstr ""
|
||||
|
||||
msgid "Native"
|
||||
msgstr ""
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr ""
|
||||
|
||||
@@ -2006,9 +2003,6 @@ msgstr ""
|
||||
msgid "Mouse Emulation"
|
||||
msgstr ""
|
||||
|
||||
msgid "System Keyboard"
|
||||
msgstr ""
|
||||
|
||||
msgid "Connect"
|
||||
msgstr ""
|
||||
|
||||
@@ -2129,6 +2123,9 @@ msgstr ""
|
||||
msgid "Select installation folder"
|
||||
msgstr ""
|
||||
|
||||
msgid "Another download is running"
|
||||
msgstr ""
|
||||
|
||||
msgid "Another GOG operation is already running"
|
||||
msgstr ""
|
||||
|
||||
@@ -2514,6 +2511,9 @@ msgstr ""
|
||||
msgid "Light"
|
||||
msgstr ""
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr ""
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr ""
|
||||
|
||||
|
||||
@@ -433,13 +433,6 @@ msgstr "Entpacken"
|
||||
msgid "Refresh Grid"
|
||||
msgstr "Ansicht aktualisieren"
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr "Das Spiel kann nicht gestartet werden, während ein anderes Spiel läuft"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Spiel konnte nicht gestartet werden: {0}"
|
||||
|
||||
msgid "Never"
|
||||
msgstr "Niemals"
|
||||
|
||||
@@ -504,6 +497,9 @@ msgstr "Spiel nicht gefunden."
|
||||
msgid "PortProton start script not found"
|
||||
msgstr "PortProton-Startskript nicht gefunden"
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr "Das Spiel kann nicht gestartet werden, während ein anderes Spiel läuft"
|
||||
|
||||
msgid "Invalid command format (empty exec line)"
|
||||
msgstr "Ungültiges Befehlsformat (leere exec-Zeile)"
|
||||
|
||||
@@ -511,8 +507,8 @@ msgid "Invalid command format (native)"
|
||||
msgstr "Ungültiges Befehlsformat"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Ausführen \"{name}\" mit PortProton"
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Spiel konnte nicht gestartet werden: {0}"
|
||||
|
||||
msgid "Choose Folder"
|
||||
msgstr "Ordner auswählen"
|
||||
@@ -754,13 +750,12 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr "Nach Start ausführen / Wrapper"
|
||||
|
||||
#, fuzzy, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
msgstr ""
|
||||
"Pfad zu einer zweiten .exe-Datei, einem Skript oder einem Wrapper-Befehl."
|
||||
" Beispiel: systemd-run --user --scope --slice=app.slice"
|
||||
"Pfad zu einer zweiten .exe-Datei, einem Skript oder einem Wrapper-Befehl. "
|
||||
"Beispiel: systemd-run --user --scope --slice=app.slice"
|
||||
|
||||
msgid "CPU Cores Limit"
|
||||
msgstr "CPU-Kerne-Limit"
|
||||
@@ -877,6 +872,10 @@ msgstr "Keine aktuellen Spiele"
|
||||
msgid "No favorites"
|
||||
msgstr "Keine Favoriten"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Ausführen \"{name}\" mit PortProton"
|
||||
|
||||
msgid "Debug log mode was launched"
|
||||
msgstr "Der Debug-Protokollmodus wurde gestartet"
|
||||
|
||||
@@ -1146,6 +1145,10 @@ msgstr "Herunterladen: "
|
||||
msgid "Download Selected"
|
||||
msgstr "Ausgewählte herunterladen"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Error loading WINE/Proton: {error}"
|
||||
msgstr "Fehler beim Herunterladen von WINE/Proton: {error}"
|
||||
|
||||
msgid "Version WINE/Proton"
|
||||
msgstr "WINE/Proton Version"
|
||||
|
||||
@@ -1165,9 +1168,6 @@ msgstr "Installiert"
|
||||
msgid "Select to remove this WINE/Proton"
|
||||
msgstr "Wähle, um WINE/Proton zu entfernen"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Laden…"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Selected {} WINE/Proton:\n"
|
||||
msgstr "Ausgewählt {} WINE/Proton:\n"
|
||||
@@ -1278,10 +1278,6 @@ msgstr "Globale Spieleinstellungen"
|
||||
msgid "Exe Settings"
|
||||
msgstr "Einstellungen für die exe-Datei"
|
||||
|
||||
#, fuzzy
|
||||
msgid "Native"
|
||||
msgstr "Nach Bildausgabe"
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr "user.conf bearbeiten"
|
||||
|
||||
@@ -2114,10 +2110,6 @@ msgstr "Vollbild"
|
||||
msgid "Mouse Emulation"
|
||||
msgstr "Mausemulation"
|
||||
|
||||
#, fuzzy
|
||||
msgid "System Keyboard"
|
||||
msgstr "Tastatur-Eingabe abfangen"
|
||||
|
||||
msgid "Connect"
|
||||
msgstr "Verbinden"
|
||||
|
||||
@@ -2238,6 +2230,9 @@ msgstr "Aktualisierung der Epic-Bibliothek fehlgeschlagen: {0}"
|
||||
msgid "Select installation folder"
|
||||
msgstr "Installationsordner auswählen"
|
||||
|
||||
msgid "Another download is running"
|
||||
msgstr "Ein weiterer Download läuft"
|
||||
|
||||
msgid "Another GOG operation is already running"
|
||||
msgstr "Eine andere GOG-Aktion läuft bereits"
|
||||
|
||||
@@ -2629,6 +2624,9 @@ msgstr "Dunkel"
|
||||
msgid "Light"
|
||||
msgstr "Hell"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Laden…"
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr "Laden der Themes fehlgeschlagen"
|
||||
|
||||
|
||||
@@ -434,13 +434,6 @@ msgstr "Extrayendo"
|
||||
msgid "Refresh Grid"
|
||||
msgstr "Actualizar cuadrícula"
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr "No se puede iniciar el juego mientras hay otro en ejecución"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Error al iniciar el juego: {0}"
|
||||
|
||||
msgid "Never"
|
||||
msgstr "Nunca"
|
||||
|
||||
@@ -504,6 +497,9 @@ msgstr "Juego no encontrado."
|
||||
msgid "PortProton start script not found"
|
||||
msgstr "No se ha encontrado el script de inicio de PortProton"
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr "No se puede iniciar el juego mientras hay otro en ejecución"
|
||||
|
||||
msgid "Invalid command format (empty exec line)"
|
||||
msgstr "Formato de comando no válido (línea de ejecución vacía)"
|
||||
|
||||
@@ -511,8 +507,8 @@ msgid "Invalid command format (native)"
|
||||
msgstr "Formato de comando no válido (nativo)"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Iniciar «{name}» con PortProton"
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Error al iniciar el juego: {0}"
|
||||
|
||||
msgid "Choose Folder"
|
||||
msgstr "Seleccionar carpeta"
|
||||
@@ -769,10 +765,9 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr "Ejecutar después / Envoltorio"
|
||||
|
||||
#, fuzzy, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
msgstr ""
|
||||
"Ruta a un segundo archivo .exe, script o comando de envoltura. Ejemplo: "
|
||||
"systemd-run --user --scope --slice=app.slice"
|
||||
@@ -892,6 +887,10 @@ msgstr "Sin juegos recientes"
|
||||
msgid "No favorites"
|
||||
msgstr "Sin favoritos"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Iniciar «{name}» con PortProton"
|
||||
|
||||
msgid "Debug log mode was launched"
|
||||
msgstr "Se ha iniciado el modo de registro de depuración"
|
||||
|
||||
@@ -1160,6 +1159,10 @@ msgstr "Descargando: "
|
||||
msgid "Download Selected"
|
||||
msgstr "Descargar seleccionados"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Error loading WINE/Proton: {error}"
|
||||
msgstr "Error al cargar WINE/Proton: {error}"
|
||||
|
||||
msgid "Version WINE/Proton"
|
||||
msgstr "Versión de WINE/Proton"
|
||||
|
||||
@@ -1179,9 +1182,6 @@ msgstr "Instalado"
|
||||
msgid "Select to remove this WINE/Proton"
|
||||
msgstr "Seleccione para eliminar WINE/Proton"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Cargando…"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Selected {} WINE/Proton:\n"
|
||||
msgstr "Seleccionado {} WINE/Proton:\n"
|
||||
@@ -1291,9 +1291,6 @@ msgstr "Ajustes de Wine"
|
||||
msgid "Exe Settings"
|
||||
msgstr ""
|
||||
|
||||
msgid "Native"
|
||||
msgstr ""
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr ""
|
||||
|
||||
@@ -2117,9 +2114,6 @@ msgstr ""
|
||||
msgid "Mouse Emulation"
|
||||
msgstr ""
|
||||
|
||||
msgid "System Keyboard"
|
||||
msgstr ""
|
||||
|
||||
msgid "Connect"
|
||||
msgstr ""
|
||||
|
||||
@@ -2241,6 +2235,10 @@ msgstr "Error al iniciar el juego: {0}"
|
||||
msgid "Select installation folder"
|
||||
msgstr ""
|
||||
|
||||
#, fuzzy
|
||||
msgid "Another download is running"
|
||||
msgstr "Descargando"
|
||||
|
||||
msgid "Another GOG operation is already running"
|
||||
msgstr ""
|
||||
|
||||
@@ -2635,6 +2633,9 @@ msgstr ""
|
||||
msgid "Light"
|
||||
msgstr ""
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Cargando…"
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr "Error al cargar los temas"
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: PortProtonQt 0.1.1\n"
|
||||
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
|
||||
"POT-Creation-Date: 2026-11-20 23:00+0500\n"
|
||||
"POT-Creation-Date: 2026-10-24 18:13+0500\n"
|
||||
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
|
||||
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
|
||||
"Language-Team: LANGUAGE <LL@li.org>\n"
|
||||
@@ -416,13 +416,6 @@ msgstr ""
|
||||
msgid "Refresh Grid"
|
||||
msgstr ""
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr ""
|
||||
|
||||
msgid "Never"
|
||||
msgstr ""
|
||||
|
||||
@@ -482,6 +475,9 @@ msgstr ""
|
||||
msgid "PortProton start script not found"
|
||||
msgstr ""
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr ""
|
||||
|
||||
msgid "Invalid command format (empty exec line)"
|
||||
msgstr ""
|
||||
|
||||
@@ -489,7 +485,7 @@ msgid "Invalid command format (native)"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr ""
|
||||
|
||||
msgid "Choose Folder"
|
||||
@@ -692,10 +688,9 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr ""
|
||||
|
||||
#, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
msgstr ""
|
||||
|
||||
msgid "CPU Cores Limit"
|
||||
@@ -796,6 +791,10 @@ msgstr ""
|
||||
msgid "No favorites"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr ""
|
||||
|
||||
msgid "Debug log mode was launched"
|
||||
msgstr ""
|
||||
|
||||
@@ -1059,6 +1058,10 @@ msgstr ""
|
||||
msgid "Download Selected"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Error loading WINE/Proton: {error}"
|
||||
msgstr ""
|
||||
|
||||
msgid "Version WINE/Proton"
|
||||
msgstr ""
|
||||
|
||||
@@ -1078,9 +1081,6 @@ msgstr ""
|
||||
msgid "Select to remove this WINE/Proton"
|
||||
msgstr ""
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr ""
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Selected {} WINE/Proton:\n"
|
||||
msgstr ""
|
||||
@@ -1185,9 +1185,6 @@ msgstr ""
|
||||
msgid "Exe Settings"
|
||||
msgstr ""
|
||||
|
||||
msgid "Native"
|
||||
msgstr ""
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr ""
|
||||
|
||||
@@ -2002,9 +1999,6 @@ msgstr ""
|
||||
msgid "Mouse Emulation"
|
||||
msgstr ""
|
||||
|
||||
msgid "System Keyboard"
|
||||
msgstr ""
|
||||
|
||||
msgid "Connect"
|
||||
msgstr ""
|
||||
|
||||
@@ -2125,6 +2119,9 @@ msgstr ""
|
||||
msgid "Select installation folder"
|
||||
msgstr ""
|
||||
|
||||
msgid "Another download is running"
|
||||
msgstr ""
|
||||
|
||||
msgid "Another GOG operation is already running"
|
||||
msgstr ""
|
||||
|
||||
@@ -2511,6 +2508,9 @@ msgstr ""
|
||||
msgid "Light"
|
||||
msgstr ""
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr ""
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr ""
|
||||
|
||||
|
||||
@@ -433,13 +433,6 @@ msgstr "Extraindo"
|
||||
msgid "Refresh Grid"
|
||||
msgstr "Atualizar Grade"
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr "Não é possível iniciar o jogo enquanto outro jogo estiver em execução"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Falha ao iniciar o jogo: {0}"
|
||||
|
||||
msgid "Never"
|
||||
msgstr "Nunca"
|
||||
|
||||
@@ -503,6 +496,9 @@ msgstr "Jogo não encontrado."
|
||||
msgid "PortProton start script not found"
|
||||
msgstr "Script de inicialização do PortProton não encontrado"
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr "Não é possível iniciar o jogo enquanto outro jogo estiver em execução"
|
||||
|
||||
msgid "Invalid command format (empty exec line)"
|
||||
msgstr "Formato de comando inválido (linha exec vazia)"
|
||||
|
||||
@@ -510,8 +506,8 @@ msgid "Invalid command format (native)"
|
||||
msgstr "Formato de comando inválido (nativo)"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Iniciar \"{name}\" com o PortProton"
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Falha ao iniciar o jogo: {0}"
|
||||
|
||||
msgid "Choose Folder"
|
||||
msgstr "Escolher Pasta"
|
||||
@@ -754,10 +750,9 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr "Executar após / Wrapper"
|
||||
|
||||
#, fuzzy, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
msgstr ""
|
||||
"Caminho para um segundo arquivo .exe, script ou comando wrapper. Exemplo:"
|
||||
" systemd-run --user --scope --slice=app.slice"
|
||||
@@ -879,6 +874,10 @@ msgstr "Nenhum jogo recente"
|
||||
msgid "No favorites"
|
||||
msgstr "Nenhum favorito"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Iniciar \"{name}\" com o PortProton"
|
||||
|
||||
msgid "Debug log mode was launched"
|
||||
msgstr "O modo de log de depuração foi iniciado"
|
||||
|
||||
@@ -1146,6 +1145,10 @@ msgstr "Baixando: "
|
||||
msgid "Download Selected"
|
||||
msgstr "Baixar Selecionados"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Error loading WINE/Proton: {error}"
|
||||
msgstr "Erro ao carregar WINE/Proton: {error}"
|
||||
|
||||
msgid "Version WINE/Proton"
|
||||
msgstr "Versão WINE/Proton"
|
||||
|
||||
@@ -1165,9 +1168,6 @@ msgstr "Instalado"
|
||||
msgid "Select to remove this WINE/Proton"
|
||||
msgstr "Selecione para remover este WINE/Proton"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Carregando…"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Selected {} WINE/Proton:\n"
|
||||
msgstr "{} WINE/Proton selecionado(s):\n"
|
||||
@@ -1277,10 +1277,6 @@ msgstr "Configurações globais dos jogos"
|
||||
msgid "Exe Settings"
|
||||
msgstr "Configurações do Exe"
|
||||
|
||||
#, fuzzy
|
||||
msgid "Native"
|
||||
msgstr "Tardio"
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr "Editar o arquivo user.conf"
|
||||
|
||||
@@ -2111,10 +2107,6 @@ msgstr "Tela Cheia"
|
||||
msgid "Mouse Emulation"
|
||||
msgstr "Emulação de Mouse"
|
||||
|
||||
#, fuzzy
|
||||
msgid "System Keyboard"
|
||||
msgstr "Capturar o teclado"
|
||||
|
||||
msgid "Connect"
|
||||
msgstr "Conectar"
|
||||
|
||||
@@ -2235,6 +2227,9 @@ msgstr "Falha ao atualizar a biblioteca da Epic: {0}"
|
||||
msgid "Select installation folder"
|
||||
msgstr "Selecionar pasta de instalação"
|
||||
|
||||
msgid "Another download is running"
|
||||
msgstr "Outro download está em andamento"
|
||||
|
||||
msgid "Another GOG operation is already running"
|
||||
msgstr "Outra operação da GOG já está em execução"
|
||||
|
||||
@@ -2624,6 +2619,9 @@ msgstr "Escuro"
|
||||
msgid "Light"
|
||||
msgstr "Claro"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Carregando…"
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr "Falha ao carregar temas"
|
||||
|
||||
|
||||
@@ -431,13 +431,6 @@ msgstr "Распаковка"
|
||||
msgid "Refresh Grid"
|
||||
msgstr "Обновить сетку"
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr "Невозможно запустить игру пока запущена другая"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Не удалось запустить игру: {0}"
|
||||
|
||||
msgid "Never"
|
||||
msgstr "Никогда"
|
||||
|
||||
@@ -500,6 +493,9 @@ msgstr "Игра не найдена."
|
||||
msgid "PortProton start script not found"
|
||||
msgstr "Скрипт запуска PortProton не найден"
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr "Невозможно запустить игру пока запущена другая"
|
||||
|
||||
msgid "Invalid command format (empty exec line)"
|
||||
msgstr "Неправильный формат команды (пустая строка exec)"
|
||||
|
||||
@@ -507,8 +503,8 @@ msgid "Invalid command format (native)"
|
||||
msgstr "Неверный формат команды (нативный)"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Запустить «{name}» с помощью PortProton"
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "Не удалось запустить игру: {0}"
|
||||
|
||||
msgid "Choose Folder"
|
||||
msgstr "Выбрать папку"
|
||||
@@ -750,10 +746,9 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr "Запустить после"
|
||||
|
||||
#, fuzzy, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
msgstr ""
|
||||
"Путь к второму файлу .exe, скрипту или команде-обёртке. Пример: systemd-"
|
||||
"run --user --scope --slice=app.slice"
|
||||
@@ -877,6 +872,10 @@ msgstr "Нет недавних игр"
|
||||
msgid "No favorites"
|
||||
msgstr "Нет избранных"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "Запустить «{name}» с помощью PortProton"
|
||||
|
||||
msgid "Debug log mode was launched"
|
||||
msgstr "Запущен режим логирования"
|
||||
|
||||
@@ -1144,6 +1143,10 @@ msgstr "Скачивание: "
|
||||
msgid "Download Selected"
|
||||
msgstr "Скачать выбранное"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Error loading WINE/Proton: {error}"
|
||||
msgstr "Ошибка загрузки WINE/Proton: {error}"
|
||||
|
||||
msgid "Version WINE/Proton"
|
||||
msgstr "Версия WINE/Proton"
|
||||
|
||||
@@ -1163,9 +1166,6 @@ msgstr "Установленные"
|
||||
msgid "Select to remove this WINE/Proton"
|
||||
msgstr "Выберите, чтобы удалить WINE/Proton"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Загрузка…"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Selected {} WINE/Proton:\n"
|
||||
msgstr "Выбрано {} WINE/Proton:\n"
|
||||
@@ -1275,10 +1275,6 @@ msgstr "Глобальные настройки игры"
|
||||
msgid "Exe Settings"
|
||||
msgstr "Настройки EXE"
|
||||
|
||||
#, fuzzy
|
||||
msgid "Native"
|
||||
msgstr "После отображения кадра"
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr "Изменить user.conf"
|
||||
|
||||
@@ -2107,10 +2103,6 @@ msgstr "Полный экран"
|
||||
msgid "Mouse Emulation"
|
||||
msgstr "Эмуляция мыши"
|
||||
|
||||
#, fuzzy
|
||||
msgid "System Keyboard"
|
||||
msgstr "Перехват нажатий кнопок клавиатуры"
|
||||
|
||||
msgid "Connect"
|
||||
msgstr "Подключиться"
|
||||
|
||||
@@ -2229,6 +2221,9 @@ msgstr "Не удалось обновить библиотеку Epic: {0}"
|
||||
msgid "Select installation folder"
|
||||
msgstr "Выберите папку установки"
|
||||
|
||||
msgid "Another download is running"
|
||||
msgstr "Другая загрузка уже выполняется"
|
||||
|
||||
msgid "Another GOG operation is already running"
|
||||
msgstr "Другая операция GOG уже выполняется"
|
||||
|
||||
@@ -2614,6 +2609,9 @@ msgstr "Тёмная"
|
||||
msgid "Light"
|
||||
msgstr "Светлая"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "Загрузка…"
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr "Не удалось загрузить темы"
|
||||
|
||||
|
||||
@@ -422,13 +422,6 @@ msgstr "正在提取"
|
||||
msgid "Refresh Grid"
|
||||
msgstr "刷新网格"
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr "另一游戏正在运行时无法启动游戏"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "启动游戏失败:{0}"
|
||||
|
||||
msgid "Never"
|
||||
msgstr "从不"
|
||||
|
||||
@@ -493,6 +486,9 @@ msgstr "未找到游戏。"
|
||||
msgid "PortProton start script not found"
|
||||
msgstr "未找到 PortProton 启动脚本"
|
||||
|
||||
msgid "Cannot launch game while another game is running"
|
||||
msgstr "另一游戏正在运行时无法启动游戏"
|
||||
|
||||
msgid "Invalid command format (empty exec line)"
|
||||
msgstr "命令格式无效(exec 行为空)"
|
||||
|
||||
@@ -500,8 +496,8 @@ msgid "Invalid command format (native)"
|
||||
msgstr "命令格式无效(原生)"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "使用 PortProton 启动\"{name}\""
|
||||
msgid "Failed to launch game: {0}"
|
||||
msgstr "启动游戏失败:{0}"
|
||||
|
||||
msgid "Choose Folder"
|
||||
msgstr "选择文件夹"
|
||||
@@ -727,10 +723,9 @@ msgstr ""
|
||||
msgid "Run After / Wrapper"
|
||||
msgstr "运行后 / 包装器"
|
||||
|
||||
#, fuzzy, python-format
|
||||
msgid ""
|
||||
"Path to a second .exe, script, or wrapper command. Use %command% for the "
|
||||
"game command"
|
||||
"Path to a second .exe, script, or wrapper command. Example: systemd-run "
|
||||
"--user --scope --slice=app.slice"
|
||||
msgstr "指向第二个 .exe、脚本或包装器命令的路径。示例:systemd-run --user --scope --slice=app.slice"
|
||||
|
||||
msgid "CPU Cores Limit"
|
||||
@@ -841,6 +836,10 @@ msgstr "无最近游戏"
|
||||
msgid "No favorites"
|
||||
msgstr "无收藏"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Launch \"{name}\" with PortProton"
|
||||
msgstr "使用 PortProton 启动\"{name}\""
|
||||
|
||||
msgid "Debug log mode was launched"
|
||||
msgstr "调试日志模式已启动"
|
||||
|
||||
@@ -1111,6 +1110,10 @@ msgstr "正在下载: "
|
||||
msgid "Download Selected"
|
||||
msgstr "下载选定项"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Error loading WINE/Proton: {error}"
|
||||
msgstr "加载 WINE/Proton 时出错:{error}"
|
||||
|
||||
msgid "Version WINE/Proton"
|
||||
msgstr "WINE/Proton 版本"
|
||||
|
||||
@@ -1130,9 +1133,6 @@ msgstr "已安装"
|
||||
msgid "Select to remove this WINE/Proton"
|
||||
msgstr "选择以移除此 WINE/Proton"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "加载中…"
|
||||
|
||||
#, python-brace-format
|
||||
msgid "Selected {} WINE/Proton:\n"
|
||||
msgstr "已选择 {} 个 WINE/Proton:\n"
|
||||
@@ -1243,10 +1243,6 @@ msgstr "保存设置"
|
||||
msgid "Exe Settings"
|
||||
msgstr "可执行文件设置"
|
||||
|
||||
#, fuzzy
|
||||
msgid "Native"
|
||||
msgstr "晚"
|
||||
|
||||
msgid "Edit user.conf"
|
||||
msgstr "编辑 user.conf"
|
||||
|
||||
@@ -2064,10 +2060,6 @@ msgstr "全屏"
|
||||
msgid "Mouse Emulation"
|
||||
msgstr "鼠标模拟"
|
||||
|
||||
#, fuzzy
|
||||
msgid "System Keyboard"
|
||||
msgstr "捕获键盘"
|
||||
|
||||
msgid "Connect"
|
||||
msgstr "连接"
|
||||
|
||||
@@ -2199,6 +2191,10 @@ msgstr "启动游戏失败:{0}"
|
||||
msgid "Select installation folder"
|
||||
msgstr "选择安装文件夹"
|
||||
|
||||
#, fuzzy
|
||||
msgid "Another download is running"
|
||||
msgstr "正在下载"
|
||||
|
||||
msgid "Another GOG operation is already running"
|
||||
msgstr "另一个 GOG 操作正在运行中"
|
||||
|
||||
@@ -2598,6 +2594,9 @@ msgstr "深色"
|
||||
msgid "Light"
|
||||
msgstr "浅色"
|
||||
|
||||
msgid "Loading…"
|
||||
msgstr "加载中…"
|
||||
|
||||
msgid "Failed to load themes"
|
||||
msgstr "加载主题失败"
|
||||
|
||||
|
||||
+16
-28
@@ -29,7 +29,7 @@ from portprotonqt.detail_pages import DetailPageManager
|
||||
from portprotonqt.portproton_api import PortProtonAPI, remove_empty_custom_data_dirs
|
||||
from portprotonqt.gog_api import GOGAPI
|
||||
from portprotonqt.egs_api import EGSAPI
|
||||
from portprotonqt.native_games import NativeLibraryWorker, NATIVE_URI_PREFIX, get_native_launch, is_native_executable, read_native_game
|
||||
from portprotonqt.native_games import NativeLibraryWorker, NATIVE_URI_PREFIX, get_native_launch, read_native_game
|
||||
from portprotonqt.debug_utils import get_prefix_name
|
||||
from portprotonqt.input_manager import InputManager, MainWindowProtocol
|
||||
from portprotonqt.context_menu_manager import ContextMenuManager
|
||||
@@ -1032,8 +1032,6 @@ class MainWindow(
|
||||
self._on_only_installed_changed(current_filter[1])
|
||||
return
|
||||
self.games = games
|
||||
if self.tray_manager is not None:
|
||||
self.tray_manager.refresh_tray_menu()
|
||||
focus_first_card = not self.game_library_manager.games and not getattr(
|
||||
self, "_preserve_library_focus_after_load", False
|
||||
)
|
||||
@@ -1197,44 +1195,35 @@ class MainWindow(
|
||||
dialog.deleteLater()
|
||||
|
||||
def _launch_native_game(self, exec_line: str, button: QPushButton | None = None) -> None:
|
||||
target = Path(exec_line.removeprefix(NATIVE_URI_PREFIX))
|
||||
is_shortcut = exec_line.startswith(NATIVE_URI_PREFIX)
|
||||
desktop_path = Path(exec_line.removeprefix(NATIVE_URI_PREFIX))
|
||||
if self.game_processes:
|
||||
if getattr(self, "native_game_running", False) and self.game_start_exe == str(target):
|
||||
if getattr(self, "native_game_running", False) and self.game_start_exe == str(desktop_path):
|
||||
self.stop_running_game(button)
|
||||
else:
|
||||
QMessageBox.warning(self, _("Error"), _("Cannot launch game while another game is running"))
|
||||
return
|
||||
try:
|
||||
if not target.is_absolute():
|
||||
raise ValueError("Invalid native launch path")
|
||||
if is_shortcut:
|
||||
if target.suffix != ".desktop":
|
||||
raise ValueError("Invalid native desktop path")
|
||||
command, directory = get_native_launch(str(target))
|
||||
else:
|
||||
if not is_native_executable(str(target)):
|
||||
raise PermissionError(str(target))
|
||||
command, directory = [str(target)], str(target.parent)
|
||||
if not desktop_path.is_absolute() or desktop_path.suffix != ".desktop":
|
||||
raise ValueError("Invalid native desktop path")
|
||||
command, directory = get_native_launch(str(desktop_path))
|
||||
process = subprocess.Popen(command, cwd=directory, start_new_session=True, text=True)
|
||||
except Exception as error:
|
||||
logger.warning("Failed to launch native game %s: %s", target, error)
|
||||
logger.warning("Failed to launch native game %s: %s", desktop_path, error)
|
||||
QMessageBox.warning(self, _("Error"), _("Failed to launch game: {0}").format(error))
|
||||
return
|
||||
self.native_game_running = True
|
||||
self.game_stopped_by_user = False
|
||||
self.game_processes = [process]
|
||||
self.current_running_button = button
|
||||
self.target_exe = target.name
|
||||
self.game_start_exe = str(target)
|
||||
self.target_exe = desktop_path.name
|
||||
self.game_start_exe = str(desktop_path)
|
||||
self.game_start_exact_path = True
|
||||
self.game_start_time = datetime.now()
|
||||
self.game_launch_monotonic = time.monotonic()
|
||||
self.game_launch_started = True
|
||||
self.wine_download_seen = False
|
||||
if is_shortcut:
|
||||
save_last_launch(target.stem, self.game_start_time)
|
||||
self._update_last_launch_after_start(str(target), self.game_start_time)
|
||||
save_last_launch(desktop_path.stem, self.game_start_time)
|
||||
self._update_last_launch_after_start(str(desktop_path), self.game_start_time)
|
||||
self.launch_output_queue = Queue()
|
||||
self.input_manager.suspend_gamepad_polling()
|
||||
self._set_running_button_stop()
|
||||
@@ -3529,19 +3518,18 @@ class MainWindow(
|
||||
self.tray_manager = TrayManager(self, app_name, self.current_theme_name)
|
||||
|
||||
def closeEvent(self, event):
|
||||
"""Minimize on ordinary close when configured, or shut down."""
|
||||
if getattr(self, "_shutdown_started", False):
|
||||
event.accept()
|
||||
return
|
||||
"""Handle window close: check minimize_to_tray setting.
|
||||
If True - minimize to tray. Otherwise - fully close.
|
||||
"""
|
||||
minimize_to_tray = display_config.get_minimize_to_tray()
|
||||
|
||||
if not getattr(self, "_explicit_exit", False) and display_config.get_minimize_to_tray():
|
||||
if minimize_to_tray:
|
||||
# Just minimize to tray
|
||||
event.ignore()
|
||||
self.hide()
|
||||
return
|
||||
|
||||
# Full application close
|
||||
self._shutdown_started = True
|
||||
event.accept()
|
||||
system_keyboard = getattr(self, 'system_keyboard', None)
|
||||
if system_keyboard is not None:
|
||||
|
||||
@@ -32,9 +32,9 @@ NATIVE_ADVANCED_KEYS = frozenset({"LAUNCH_PARAMETERS", "PW_MESA_GL_VERSION_OVERR
|
||||
|
||||
|
||||
def is_native_executable(path: str) -> bool:
|
||||
"""Recognize native executables, not desktop shortcuts or Wine targets."""
|
||||
"""Recognize native launch files while preserving Windows and disc formats."""
|
||||
return (
|
||||
not path.lower().endswith(LAUNCH_FILE_EXTENSIONS + (".desktop",))
|
||||
Path(path).suffix.lower() not in LAUNCH_FILE_EXTENSIONS
|
||||
and os.path.isfile(path)
|
||||
and os.access(path, os.X_OK)
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@ from portprotonqt.steam_api.utils import (
|
||||
safe_vdf_load,
|
||||
decode_text,
|
||||
get_steam_home,
|
||||
get_steam_runtime_library_paths,
|
||||
get_steam_launch_commands,
|
||||
get_steam_compatibilitytools_dir,
|
||||
get_steam_compat_tool,
|
||||
@@ -62,6 +63,7 @@ __all__ = [
|
||||
"safe_vdf_load",
|
||||
"decode_text",
|
||||
"get_steam_home",
|
||||
"get_steam_runtime_library_paths",
|
||||
"get_steam_launch_commands",
|
||||
"get_steam_compatibilitytools_dir",
|
||||
"get_steam_compat_tool",
|
||||
|
||||
+118
-126
@@ -8,11 +8,9 @@ import time
|
||||
import urllib.parse
|
||||
from collections.abc import Callable
|
||||
from functools import lru_cache
|
||||
from typing import TypeVar
|
||||
|
||||
import orjson
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from PySide6.QtCore import QThread, QThreadPool
|
||||
|
||||
from portprotonqt.logger import get_logger
|
||||
from portprotonqt.downloader import Downloader
|
||||
@@ -25,11 +23,11 @@ from portprotonqt.steam_api.cache import (
|
||||
CACHE_DURATION,
|
||||
load_app_details,
|
||||
save_app_details,
|
||||
load_steam_apps,
|
||||
load_steam_apps_async,
|
||||
build_index,
|
||||
search_app,
|
||||
load_weanticheatyet_data,
|
||||
load_ppdb_data,
|
||||
load_weanticheatyet_data_async,
|
||||
load_ppdb_data_async,
|
||||
build_weanticheatyet_index,
|
||||
build_ppdb_index,
|
||||
search_anticheat_entry,
|
||||
@@ -50,98 +48,89 @@ SGDB_CACHE_DURATION = 24 * 60 * 60
|
||||
STEAM_CLIENT_ICON_SIZES = (16, 32, 64, 128, 256)
|
||||
|
||||
|
||||
_METADATA_LOOKUPS = QThreadPool(downloader)
|
||||
_METADATA_LOOKUPS.setMaxThreadCount(min(downloader.max_workers, max(1, QThread.idealThreadCount())))
|
||||
def fetch_sgdb_cover_async(
|
||||
game_name: str, callback: Callable[[str], None], image_type: str = "grids"
|
||||
) -> None:
|
||||
"""Asynchronously fetch cover image URL from steamgrid.usebottles.com."""
|
||||
encoded = urllib.parse.quote(game_name, safe="")
|
||||
url = f"https://steamgrid.usebottles.com/api/search/{encoded}/{image_type}"
|
||||
|
||||
def process_response(result: str | None) -> None:
|
||||
if not result or not os.path.exists(result):
|
||||
logger.warning("Failed to download SGDB data for %s", game_name)
|
||||
try:
|
||||
cache_file.write_text('""', encoding="utf-8")
|
||||
except OSError as e:
|
||||
logger.warning("Failed to save SGDB miss cache for %s: %s", game_name, e)
|
||||
callback("")
|
||||
return
|
||||
try:
|
||||
with open(result, encoding="utf-8") as f:
|
||||
text = f.read().strip()
|
||||
if text.startswith('"') and text.endswith('"'):
|
||||
text = text[1:-1]
|
||||
if text:
|
||||
from portprotonqt.portproton_api import get_user_conf_setting
|
||||
|
||||
def stop_metadata_lookups() -> None:
|
||||
"""Discard queued metadata lookups and join the workers during shutdown."""
|
||||
_METADATA_LOOKUPS.clear()
|
||||
_METADATA_LOOKUPS.waitForDone()
|
||||
|
||||
|
||||
def _read_sgdb_cover(game_name: str, image_type: str) -> str:
|
||||
from portprotonqt.portproton_api import get_user_conf_setting
|
||||
if get_user_conf_setting("MIRROR") == "CLOUD":
|
||||
text = text.replace(
|
||||
"https://cdn2.steamgriddb.com/",
|
||||
"https://deckyloader.ru/sgdb-cdn/",
|
||||
1,
|
||||
)
|
||||
logger.debug("Got SGDB cover URL for %s: %s", game_name, text)
|
||||
callback(text)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to process SGDB data for %s: %s", game_name, e)
|
||||
callback("")
|
||||
|
||||
cache_manager = CacheManager()
|
||||
safe_name = "".join(c for c in game_name if c.isalnum() or c in " -_")[:50]
|
||||
cache_file = cache_manager.cache_dir / f"sgdb_{safe_name}_{image_type}.json"
|
||||
try:
|
||||
cached_mtime = cache_file.stat().st_mtime
|
||||
except OSError:
|
||||
cached_mtime = None
|
||||
result = str(cache_file)
|
||||
if cached_mtime is None or time.time() - cached_mtime >= SGDB_CACHE_DURATION:
|
||||
encoded = urllib.parse.quote(game_name, safe="")
|
||||
url = f"https://steamgrid.usebottles.com/api/search/{encoded}/{image_type}"
|
||||
result = downloader.download(url, result, timeout=3)
|
||||
if not result:
|
||||
logger.warning("Failed to download SGDB data for %s", game_name)
|
||||
return ""
|
||||
with open(result, encoding="utf-8") as stream:
|
||||
text = stream.read().strip()
|
||||
if text.startswith('"') and text.endswith('"'):
|
||||
text = text[1:-1]
|
||||
if text and get_user_conf_setting("MIRROR") == "CLOUD":
|
||||
text = text.replace("https://cdn2.steamgriddb.com/", "https://deckyloader.ru/sgdb-cdn/", 1)
|
||||
return text
|
||||
|
||||
|
||||
_LookupResult = TypeVar("_LookupResult")
|
||||
|
||||
|
||||
def _queue_metadata_lookup(
|
||||
lookup: Callable[[], _LookupResult], callback: Callable[[_LookupResult], None], fallback: _LookupResult,
|
||||
) -> None:
|
||||
def run() -> None:
|
||||
try:
|
||||
result = lookup()
|
||||
except Exception:
|
||||
logger.exception("Failed to load Steam metadata")
|
||||
result = fallback
|
||||
downloader.callback_requested.emit(callback, result)
|
||||
|
||||
_METADATA_LOOKUPS.start(run)
|
||||
|
||||
|
||||
def fetch_sgdb_cover_async(
|
||||
game_name: str, callback: Callable[[str], None], image_type: str = "grids"
|
||||
) -> None:
|
||||
"""Look up artwork off the GUI thread, even when its cache is warm."""
|
||||
_queue_metadata_lookup(lambda: _read_sgdb_cover(game_name, image_type), callback, "")
|
||||
|
||||
|
||||
def _read_app_info(app_id: int) -> dict | None:
|
||||
cached = load_app_details(app_id)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
lang = get_steam_language()
|
||||
url = f"https://store.steampowered.com/api/appdetails?appids={app_id}&l={lang}"
|
||||
cache_file = CacheManager().cache_dir / f"steam_app_{app_id}.json"
|
||||
result = downloader.download(url, str(cache_file), timeout=5)
|
||||
if not result:
|
||||
logger.error("Failed to download Steam app info for appid %s", app_id)
|
||||
return None
|
||||
with open(result, "rb") as stream:
|
||||
data = orjson.loads(stream.read())
|
||||
details = data.get(str(app_id), {})
|
||||
if not details.get("success"):
|
||||
return None
|
||||
app_data_full = details.get("data", {})
|
||||
app_data = {
|
||||
"steam_appid": app_data_full.get("steam_appid", app_id),
|
||||
"name": app_data_full.get("name", ""),
|
||||
"short_description": app_data_full.get("short_description", ""),
|
||||
"controller_support": app_data_full.get("controller_support", ""),
|
||||
}
|
||||
save_app_details(app_id, app_data)
|
||||
return app_data
|
||||
if cache_file.exists() and time.time() - cache_file.stat().st_mtime < SGDB_CACHE_DURATION:
|
||||
process_response(str(cache_file))
|
||||
return
|
||||
downloader.download_async(url, str(cache_file), timeout=3, callback=process_response)
|
||||
|
||||
|
||||
def fetch_app_info_async(app_id: int, callback: Callable[[dict | None], None]) -> None:
|
||||
"""Asynchronously fetch detailed app info from Steam API."""
|
||||
_queue_metadata_lookup(lambda: _read_app_info(app_id), callback, None)
|
||||
cached = load_app_details(app_id)
|
||||
if cached is not None:
|
||||
callback(cached)
|
||||
return
|
||||
|
||||
lang = get_steam_language()
|
||||
url = f"https://store.steampowered.com/api/appdetails?appids={app_id}&l={lang}"
|
||||
|
||||
def process_response(result: str | None) -> None:
|
||||
if not result or not os.path.exists(result):
|
||||
logger.error("Failed to download Steam app info for appid %s", app_id)
|
||||
callback(None)
|
||||
return
|
||||
try:
|
||||
with open(result, "rb") as f:
|
||||
data = orjson.loads(f.read())
|
||||
details = data.get(str(app_id), {})
|
||||
if not details.get("success"):
|
||||
callback(None)
|
||||
return
|
||||
app_data_full = details.get("data", {})
|
||||
app_data = {
|
||||
"steam_appid": app_data_full.get("steam_appid", app_id),
|
||||
"name": app_data_full.get("name", ""),
|
||||
"short_description": app_data_full.get("short_description", ""),
|
||||
"controller_support": app_data_full.get("controller_support", "")
|
||||
}
|
||||
save_app_details(app_id, app_data)
|
||||
callback(app_data)
|
||||
except Exception as e:
|
||||
logger.error("Failed to process Steam app info for appid %s: %s", app_id, e)
|
||||
callback(None)
|
||||
|
||||
cache_manager = CacheManager()
|
||||
cache_file = cache_manager.cache_dir / f"steam_app_{app_id}.json"
|
||||
downloader.download_async(url, str(cache_file), timeout=5, callback=process_response)
|
||||
|
||||
|
||||
def _get_icon_theme_dir() -> str:
|
||||
@@ -245,10 +234,12 @@ def fetch_client_icon_async(appid: int | str, callback: Callable[[str], None]) -
|
||||
downloader.download_async(url, str(info_path), timeout=5, callback=process_info)
|
||||
|
||||
|
||||
def _read_protondb_tier(appid: int) -> str:
|
||||
def get_protondb_tier_async(appid: int, callback: Callable[[str], None]) -> None:
|
||||
"""Asynchronously fetch ProtonDB tier for an app."""
|
||||
cached = load_protondb_status(appid)
|
||||
if cached is not None:
|
||||
return cached.get("tier", "")
|
||||
callback(cached.get("tier", ""))
|
||||
return
|
||||
|
||||
from portprotonqt.portproton_api import get_user_conf_setting
|
||||
|
||||
@@ -257,59 +248,60 @@ def _read_protondb_tier(appid: int) -> str:
|
||||
else:
|
||||
url = f"https://www.protondb.com/api/v1/reports/summaries/{appid}.json"
|
||||
|
||||
cache_file = CacheManager().cache_dir / f"protondb_{appid}.json"
|
||||
result = downloader.download(url, str(cache_file), timeout=5)
|
||||
if not result:
|
||||
logger.info("Failed to download ProtonDB data for appid %s", appid)
|
||||
return ""
|
||||
with open(result, "rb") as stream:
|
||||
data = orjson.loads(stream.read())
|
||||
tier = data.get("tier", "")
|
||||
save_protondb_status(appid, {"tier": tier})
|
||||
return tier
|
||||
|
||||
|
||||
def get_protondb_tier_async(appid: int, callback: Callable[[str], None]) -> None:
|
||||
"""Asynchronously fetch ProtonDB tier for an app."""
|
||||
_queue_metadata_lookup(lambda: _read_protondb_tier(appid), callback, "")
|
||||
|
||||
|
||||
def _queue_catalog_lookup(
|
||||
cache: CacheManager, load: Callable[[Callable[[list], None]], None],
|
||||
build: Callable[[list], dict], callback: Callable[[tuple[list | None, dict | None]], None],
|
||||
) -> None:
|
||||
def load_catalog(on_data: Callable[[list], None]) -> None:
|
||||
def process_response(result: str | None) -> None:
|
||||
if not result or not os.path.exists(result):
|
||||
logger.info("Failed to download ProtonDB data for appid %s", appid)
|
||||
callback("")
|
||||
return
|
||||
try:
|
||||
load(on_data)
|
||||
except Exception:
|
||||
logger.exception("Failed to load metadata catalog")
|
||||
on_data([])
|
||||
with open(result, "rb") as f:
|
||||
data = orjson.loads(f.read())
|
||||
filtered_data = {"tier": data.get("tier", "")}
|
||||
save_protondb_status(appid, filtered_data)
|
||||
callback(filtered_data["tier"])
|
||||
except Exception as e:
|
||||
logger.info("Failed to process ProtonDB data for appid %s: %s", appid, e)
|
||||
callback("")
|
||||
|
||||
def deliver(data: tuple[list | None, dict | None]) -> None:
|
||||
downloader.callback_requested.emit(callback, data)
|
||||
|
||||
_METADATA_LOOKUPS.start(lambda: cache.get_data_and_index_async(load_catalog, build, deliver, CACHE_DURATION))
|
||||
cache_manager = CacheManager()
|
||||
cache_file = cache_manager.cache_dir / f"protondb_{appid}.json"
|
||||
downloader.download_async(url, str(cache_file), timeout=5, callback=process_response)
|
||||
|
||||
|
||||
def get_steam_apps_and_index_async(
|
||||
callback: Callable[[tuple[list | None, dict | None]], None]
|
||||
) -> None:
|
||||
"""Load or reuse the Steam catalog and its index off the GUI thread."""
|
||||
_queue_catalog_lookup(_STEAM_APPS_CACHE, load_steam_apps, build_index, callback)
|
||||
"""Asynchronously load and cache Steam apps and their index."""
|
||||
_STEAM_APPS_CACHE.get_data_and_index_async(
|
||||
load_steam_apps_async,
|
||||
build_index,
|
||||
callback,
|
||||
CACHE_DURATION
|
||||
)
|
||||
|
||||
|
||||
def get_anticheat_data_and_index_async(
|
||||
callback: Callable[[tuple[list | None, dict | None]], None]
|
||||
) -> None:
|
||||
"""Load or reuse the anti-cheat catalog and its index off the GUI thread."""
|
||||
_queue_catalog_lookup(_ANTICHEAT_CACHE, load_weanticheatyet_data, build_weanticheatyet_index, callback)
|
||||
"""Asynchronously load and cache anti-cheat data and their index."""
|
||||
_ANTICHEAT_CACHE.get_data_and_index_async(
|
||||
load_weanticheatyet_data_async,
|
||||
build_weanticheatyet_index,
|
||||
callback,
|
||||
CACHE_DURATION
|
||||
)
|
||||
|
||||
|
||||
def get_ppdb_data_and_index_async(
|
||||
callback: Callable[[tuple[list | None, dict | None]], None]
|
||||
) -> None:
|
||||
"""Load or reuse the PPDB catalog and its index off the GUI thread."""
|
||||
_queue_catalog_lookup(_PPDB_CACHE, load_ppdb_data, build_ppdb_index, callback)
|
||||
"""Asynchronously load and cache PPDB data and their index."""
|
||||
_PPDB_CACHE.get_data_and_index_async(
|
||||
load_ppdb_data_async,
|
||||
build_ppdb_index,
|
||||
callback,
|
||||
CACHE_DURATION
|
||||
)
|
||||
|
||||
|
||||
def get_weanticheatyet_status_async(game_name: str, callback: Callable[[str], None]) -> None:
|
||||
@@ -444,7 +436,7 @@ def get_full_steam_game_info_async(
|
||||
) -> None:
|
||||
"""Asynchronously retrieve full Steam game info, including WeAntiCheatYet status."""
|
||||
if ui_config.get_economy_mode():
|
||||
_queue_metadata_lookup(lambda: get_cached_full_steam_game_info(appid, fallback_name), callback, {})
|
||||
callback(get_cached_full_steam_game_info(appid, fallback_name))
|
||||
return
|
||||
|
||||
def on_app_info(app_info: dict | None) -> None:
|
||||
|
||||
@@ -103,8 +103,8 @@ def save_app_details(app_id: int, data: dict) -> None:
|
||||
cache_manager.save_json(f"steam_app_{app_id}", data)
|
||||
|
||||
|
||||
def load_steam_apps(callback: Callable[[list], None]) -> None:
|
||||
"""Load Steam applications, using cache if available."""
|
||||
def load_steam_apps_async(callback: Callable[[list], None]) -> None:
|
||||
"""Asynchronously load Steam applications, using cache if available."""
|
||||
cache_manager = CacheManager()
|
||||
cache_tar_path = cache_manager.cache_dir / "games_appid.tar.xz"
|
||||
cache_json_path = cache_manager.cache_dir / "steam_apps.json"
|
||||
@@ -160,14 +160,14 @@ def load_steam_apps(callback: Callable[[list], None]) -> None:
|
||||
)
|
||||
delete_cached_app_files(str(cache_manager.cache_dir), "steam_app_*.json")
|
||||
delete_cached_app_files(str(cache_manager.cache_dir), "protondb_*.json")
|
||||
process_tar(downloader.download(app_list_url, str(cache_tar_path), timeout=5))
|
||||
downloader.download_async(app_list_url, str(cache_tar_path), timeout=5, callback=process_tar)
|
||||
else:
|
||||
app_list_url = (
|
||||
"https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt/raw/branch/main/data/games_appid.tar.xz"
|
||||
)
|
||||
delete_cached_app_files(str(cache_manager.cache_dir), "steam_app_*.json")
|
||||
delete_cached_app_files(str(cache_manager.cache_dir), "protondb_*.json")
|
||||
process_tar(downloader.download(app_list_url, str(cache_tar_path), timeout=5))
|
||||
downloader.download_async(app_list_url, str(cache_tar_path), timeout=5, callback=process_tar)
|
||||
|
||||
|
||||
def build_index(steam_apps: list) -> dict:
|
||||
@@ -199,8 +199,8 @@ def search_app(candidate: str, steam_apps_index: dict) -> dict | None:
|
||||
return None
|
||||
|
||||
|
||||
def load_weanticheatyet_data(callback: Callable[[list], None]) -> None:
|
||||
"""Load WeAntiCheatYet data, using cache if available."""
|
||||
def load_weanticheatyet_data_async(callback: Callable[[list], None]) -> None:
|
||||
"""Asynchronously load WeAntiCheatYet data, using cache if available."""
|
||||
cache_manager = CacheManager()
|
||||
cache_tar_path = cache_manager.cache_dir / "anticheat_games.tar.xz"
|
||||
cache_json_path = cache_manager.cache_dir / "anticheat_games.json"
|
||||
@@ -255,12 +255,12 @@ def load_weanticheatyet_data(callback: Callable[[list], None]) -> None:
|
||||
app_list_url = (
|
||||
"https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt/raw/branch/main/data/anticheat_games.tar.xz"
|
||||
)
|
||||
process_tar(downloader.download(app_list_url, str(cache_tar_path), timeout=5))
|
||||
downloader.download_async(app_list_url, str(cache_tar_path), timeout=5, callback=process_tar)
|
||||
else:
|
||||
app_list_url = (
|
||||
"https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt/raw/branch/main/data/anticheat_games.tar.xz"
|
||||
)
|
||||
process_tar(downloader.download(app_list_url, str(cache_tar_path), timeout=5))
|
||||
downloader.download_async(app_list_url, str(cache_tar_path), timeout=5, callback=process_tar)
|
||||
|
||||
|
||||
def _extract_ppdb_archive(
|
||||
@@ -293,8 +293,8 @@ def _extract_ppdb_archive(
|
||||
return []
|
||||
|
||||
|
||||
def load_ppdb_data(callback: Callable[[list], None]) -> None:
|
||||
"""Load PPDB data, using cache if available."""
|
||||
def load_ppdb_data_async(callback: Callable[[list], None]) -> None:
|
||||
"""Asynchronously load PPDB data, using cache if available."""
|
||||
cache_manager = CacheManager()
|
||||
cache_tar_path = cache_manager.cache_dir / "ppdb_games.tar.xz"
|
||||
cache_json_path = cache_manager.cache_dir / "ppdb_games.json"
|
||||
@@ -319,9 +319,9 @@ def load_ppdb_data(callback: Callable[[list], None]) -> None:
|
||||
callback(data)
|
||||
except Exception as e:
|
||||
logger.error("Failed to read or validate cached PPDB JSON %s: %s", cache_json_path, e)
|
||||
process_tar(downloader.download(PPDB_DATA_URL, str(cache_tar_path), timeout=5))
|
||||
downloader.download_async(PPDB_DATA_URL, str(cache_tar_path), timeout=5, callback=process_tar)
|
||||
else:
|
||||
process_tar(downloader.download(PPDB_DATA_URL, str(cache_tar_path), timeout=5))
|
||||
downloader.download_async(PPDB_DATA_URL, str(cache_tar_path), timeout=5, callback=process_tar)
|
||||
|
||||
|
||||
def build_weanticheatyet_index(anti_cheat_data: list) -> dict:
|
||||
|
||||
@@ -89,6 +89,17 @@ def get_steam_home() -> Path | None:
|
||||
return None
|
||||
|
||||
|
||||
def get_steam_runtime_library_paths() -> list[str]:
|
||||
"""Return runtime library directories from all Steam installations."""
|
||||
runtime_paths = []
|
||||
for steam_path in _iter_existing_steam_data_dirs():
|
||||
for runtime_dir in ("ubuntu12_32", "ubuntu12_64"):
|
||||
library_path = steam_path / runtime_dir
|
||||
if library_path.is_dir():
|
||||
runtime_paths.append(str(library_path))
|
||||
return runtime_paths
|
||||
|
||||
|
||||
def get_steam_launch_commands(appid: str) -> list[list[str]]:
|
||||
"""Return Steam launch commands based on detected Steam data dir."""
|
||||
steam_home = get_steam_home()
|
||||
|
||||
@@ -11,7 +11,6 @@ from portprotonqt.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
SHUTDOWN_TIMEOUT_MS = 3000
|
||||
MAX_EMOJI_LENGTH = 16
|
||||
|
||||
|
||||
class SystemKeyboard(QObject):
|
||||
@@ -78,11 +77,6 @@ class SystemKeyboard(QObject):
|
||||
self.shift_pressed = False
|
||||
elif isinstance(data, dict) and data.get('event') == 'shift':
|
||||
self.shift_pressed = bool(data.get('value'))
|
||||
elif isinstance(data, dict) and data.get('event') == 'emoji' and self.visible:
|
||||
value = data.get('value')
|
||||
if (isinstance(value, str) and 0 < len(value) <= MAX_EMOJI_LENGTH
|
||||
and value.isprintable() and not value.isascii()):
|
||||
QApplication.clipboard().setText(value)
|
||||
|
||||
def _process_error(self, error: QProcess.ProcessError) -> None:
|
||||
if error == QProcess.ProcessError.FailedToStart:
|
||||
|
||||
@@ -6,7 +6,6 @@ import ctypes as C
|
||||
import os
|
||||
import re
|
||||
import select
|
||||
import socket
|
||||
import subprocess
|
||||
import xml.etree.ElementTree as ET
|
||||
from collections.abc import Mapping
|
||||
@@ -29,9 +28,6 @@ from portprotonqt.system_keyboard.native import load_library
|
||||
|
||||
logger = get_logger(__name__)
|
||||
LAYOUT_NAME_BUFFER_BYTES = 256
|
||||
WAYFIRE_IPC_HEADER_BYTES = 4
|
||||
WAYFIRE_IPC_MAX_REPLY_BYTES = 64 * 1024
|
||||
WAYFIRE_IPC_TIMEOUT = 1.0
|
||||
IBUS_SCHEMA = 'org.freedesktop.ibus.general'
|
||||
|
||||
|
||||
@@ -141,20 +137,16 @@ class IBusLayout(X11Layout):
|
||||
|
||||
|
||||
class CosmicLayout:
|
||||
use_cosmic_protocol = True
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.display = self.layout = None
|
||||
# Labwc sends the keymap first and may defer the group until a modifier event.
|
||||
self.group = None if self.use_cosmic_protocol else 0
|
||||
self.group = None
|
||||
self.error = None
|
||||
self.callbacks, self.proxies = [], []
|
||||
self.keyboard = self.manager = self.tracker = None
|
||||
self.lib = load_library()
|
||||
self._configure_library()
|
||||
if self.use_cosmic_protocol:
|
||||
self.group_interface = self._interface('zcosmic_keyboard_layout_v1')
|
||||
self.manager_interface = self._interface('zcosmic_keyboard_layout_manager_v1')
|
||||
self.group_interface = self._interface('zcosmic_keyboard_layout_v1')
|
||||
self.manager_interface = self._interface('zcosmic_keyboard_layout_manager_v1')
|
||||
try:
|
||||
self.display = self.lib.portproton_keyboard_wayland_connect(None)
|
||||
if not self.display:
|
||||
@@ -166,7 +158,7 @@ class CosmicLayout:
|
||||
for _ in range(4):
|
||||
self._check(self.lib.wl_display_roundtrip(self.display))
|
||||
if self.layout is None or self.group is None:
|
||||
raise RuntimeError('Wayland keyboard layout or keymap unavailable')
|
||||
raise RuntimeError('COSMIC keyboard layout protocol or keymap unavailable')
|
||||
except Exception:
|
||||
self.close()
|
||||
raise
|
||||
@@ -224,8 +216,7 @@ class CosmicLayout:
|
||||
self.seat = self._new(self.registry, (0, self._interface('wl_seat')),
|
||||
C.c_uint32(name), interface, C.c_uint32(1), C.c_void_p())
|
||||
self._listen(self.seat, [(self._capabilities, [C.c_uint32])])
|
||||
elif (self.use_cosmic_protocol and interface == b'zcosmic_keyboard_layout_manager_v1'
|
||||
and self.manager is None):
|
||||
elif interface == b'zcosmic_keyboard_layout_manager_v1' and self.manager is None:
|
||||
self.manager = self._new(self.registry, (0, self.manager_interface),
|
||||
C.c_uint32(name), interface, C.c_uint32(1), C.c_void_p())
|
||||
self._track()
|
||||
@@ -234,14 +225,12 @@ class CosmicLayout:
|
||||
if capabilities & 2 and self.keyboard is None:
|
||||
self.keyboard = self._new(self.seat, (1, self._interface('wl_keyboard')), C.c_void_p())
|
||||
u, p = C.c_uint32, C.c_void_p
|
||||
modifiers = (lambda *args: None) if self.use_cosmic_protocol else (
|
||||
lambda serial, depressed, latched, locked, group: self._group(group))
|
||||
self._listen(self.keyboard, [
|
||||
(self._keymap, [u, C.c_int, u]),
|
||||
(lambda *args: None, [u, p, p]),
|
||||
(lambda *args: None, [u, p]),
|
||||
(lambda *args: None, [u, u, u, u]),
|
||||
(modifiers, [u, u, u, u, u])])
|
||||
(lambda *args: None, [u, u, u, u, u])])
|
||||
self._track()
|
||||
elif not capabilities & 2 and self.keyboard is not None:
|
||||
self.error = RuntimeError('COSMIC: keyboard disconnected')
|
||||
@@ -300,11 +289,6 @@ class CosmicLayout:
|
||||
self.display = None
|
||||
|
||||
|
||||
class LabwcLayout(CosmicLayout):
|
||||
# Labwc broadcasts wl_keyboard group changes even without keyboard focus.
|
||||
use_cosmic_protocol = False
|
||||
|
||||
|
||||
SOURCE_SCHEMA = 'org.gnome.desktop.input-sources'
|
||||
BINDINGS_SCHEMA = 'org.gnome.desktop.wm.keybindings'
|
||||
SHORTCUT_MODIFIERS = {
|
||||
@@ -394,16 +378,13 @@ def compositor(environment: Any) -> Any:
|
||||
desktop = environment.get('XDG_CURRENT_DESKTOP', '').lower().split(':')
|
||||
for name, variable in [('hyprland', 'HYPRLAND_INSTANCE_SIGNATURE'),
|
||||
('sway', 'SWAYSOCK'), ('niri', 'NIRI_SOCKET'),
|
||||
('umbriel', 'UMBRIEL_SOCKET'), ('mango', 'MANGO_INSTANCE_SIGNATURE'),
|
||||
('wayfire', 'WAYFIRE_SOCKET')]:
|
||||
('umbriel', 'UMBRIEL_SOCKET'), ('mango', 'MANGO_INSTANCE_SIGNATURE')]:
|
||||
if environment.get(variable):
|
||||
return name
|
||||
name = next((name for name in ('hyprland', 'sway', 'niri', 'cosmic', 'umbriel', 'mango', 'wayfire')
|
||||
name = next((name for name in ('hyprland', 'sway', 'niri', 'cosmic', 'umbriel', 'mango')
|
||||
if name in desktop), None)
|
||||
if name is not None:
|
||||
return name
|
||||
if environment.get("WAYLAND_DISPLAY") and (environment.get("LABWC_PID") or "labwc" in desktop):
|
||||
return "labwc"
|
||||
return 'wayland' if environment.get('WAYLAND_DISPLAY') else None
|
||||
|
||||
|
||||
@@ -458,57 +439,6 @@ class NiriLayout:
|
||||
self.layout = None
|
||||
|
||||
|
||||
class WayfireLayout(NiriLayout):
|
||||
@staticmethod
|
||||
def _request(method: str, data: dict[str, int] | None = None) -> dict[str, Any]:
|
||||
path = os.environ.get('WAYFIRE_SOCKET')
|
||||
if not path:
|
||||
raise RuntimeError('Wayfire IPC unavailable: enable the ipc and ipc-rules plugins')
|
||||
payload = orjson.dumps({'method': method, 'data': data or {}})
|
||||
try:
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
|
||||
sock.settimeout(WAYFIRE_IPC_TIMEOUT)
|
||||
sock.connect(path)
|
||||
sock.sendall(len(payload).to_bytes(WAYFIRE_IPC_HEADER_BYTES, 'little') + payload)
|
||||
with sock.makefile('rb') as stream:
|
||||
header = stream.read(WAYFIRE_IPC_HEADER_BYTES)
|
||||
if len(header) != WAYFIRE_IPC_HEADER_BYTES:
|
||||
raise ValueError('incomplete reply header')
|
||||
size = int.from_bytes(header, 'little')
|
||||
if not 0 < size <= WAYFIRE_IPC_MAX_REPLY_BYTES:
|
||||
raise ValueError('invalid reply size')
|
||||
body = stream.read(size)
|
||||
if len(body) != size:
|
||||
raise ValueError('incomplete reply')
|
||||
reply = orjson.loads(body)
|
||||
except (OSError, ValueError) as exc:
|
||||
raise RuntimeError(f'Wayfire IPC error ({method}): {exc}') from exc
|
||||
if not isinstance(reply, dict):
|
||||
raise ValueError('Invalid Wayfire IPC reply')
|
||||
if 'error' in reply:
|
||||
raise RuntimeError(f"Wayfire IPC error ({method}): {reply['error']}")
|
||||
return reply
|
||||
|
||||
def _keyboard_state(self) -> tuple[list[str], int]:
|
||||
reply = self._request('wayfire/get-keyboard-state')
|
||||
names, index = reply.get('possible-layouts'), reply.get('layout-index')
|
||||
if (not isinstance(names, list) or any(not isinstance(name, str) or not name for name in names)
|
||||
or type(index) is not int or not 0 <= index < len(names)):
|
||||
raise ValueError('Invalid Wayfire keyboard layout state')
|
||||
return names, index
|
||||
|
||||
def _query_name(self) -> str:
|
||||
names, index = self._keyboard_state()
|
||||
return names[index]
|
||||
|
||||
def switch(self) -> None:
|
||||
names, index = self._keyboard_state()
|
||||
if len(names) > 1:
|
||||
reply = self._request('wayfire/set-keyboard-state', {'layout-index': (index + 1) % len(names)})
|
||||
if reply.get('result') != 'ok':
|
||||
raise RuntimeError('Wayfire did not confirm the keyboard layout change')
|
||||
|
||||
|
||||
class SwayLayout(NiriLayout):
|
||||
def _query_name(self) -> Any:
|
||||
inputs = orjson.loads(command(['swaymsg', '-t', 'get_inputs', '-r']))
|
||||
@@ -705,8 +635,7 @@ def detect_layout() -> object:
|
||||
logger.warning('IBus layout detection unavailable: %s', error)
|
||||
return X11Layout()
|
||||
adapter = {'cosmic': CosmicLayout, 'niri': NiriLayout, 'sway': SwayLayout,
|
||||
'hyprland': HyprlandLayout, 'umbriel': UmbrielLayout, 'mango': MangoLayout,
|
||||
'labwc': LabwcLayout, 'wayfire': WayfireLayout}.get(name)
|
||||
'hyprland': HyprlandLayout, 'umbriel': UmbrielLayout, 'mango': MangoLayout}.get(name)
|
||||
if adapter is None:
|
||||
raise RuntimeError('No keyboard layout adapter for this compositor')
|
||||
return adapter()
|
||||
@@ -42,7 +42,6 @@ class SystemInputWorker(QThread):
|
||||
self.stopping = Event()
|
||||
self.enabled = Event()
|
||||
self.modifiers: set[int] = set()
|
||||
self.pending_super = False
|
||||
self.caps_lock = False
|
||||
self.layout: Any = None
|
||||
self.manual_layout = False
|
||||
@@ -110,14 +109,11 @@ class SystemInputWorker(QThread):
|
||||
self.warning.emit(f'{error}. Manual US/RU labels; external layout changes are not tracked.')
|
||||
|
||||
def _execute(self, device: UInput, action: str, codes: tuple[int, ...]) -> None:
|
||||
from portprotonqt.system_keyboard.detection import CinnamonLayout, GSettingsLayout, KDELayout, LabwcLayout, X11Layout, is_x11_session
|
||||
from portprotonqt.system_keyboard.detection import CinnamonLayout, GSettingsLayout, KDELayout, X11Layout, is_x11_session
|
||||
import os
|
||||
if action in {'tap', 'caps', 'language', 'modifiers'} and not self.enabled.is_set():
|
||||
return
|
||||
if action == 'modifiers':
|
||||
if isinstance(self.layout, LabwcLayout):
|
||||
self._set_labwc_modifiers(device, codes)
|
||||
return
|
||||
modifier_only = ((self.modifiers == {ecodes.KEY_LEFTMETA}
|
||||
and not is_x11_session(os.environ))
|
||||
or (len(self.modifiers) == 2 and ecodes.KEY_LEFTALT in self.modifiers
|
||||
@@ -130,7 +126,6 @@ class SystemInputWorker(QThread):
|
||||
self.send_keys(device, chord)
|
||||
self._set_modifiers(device, codes)
|
||||
elif action == 'release':
|
||||
self.pending_super = False
|
||||
self._set_modifiers(device, ())
|
||||
elif action == 'caps':
|
||||
if isinstance(self.layout, X11Layout) and is_x11_session(os.environ):
|
||||
@@ -138,7 +133,6 @@ class SystemInputWorker(QThread):
|
||||
else:
|
||||
self.send_keys(device, (ecodes.KEY_CAPSLOCK,))
|
||||
elif action == 'language':
|
||||
self.pending_super = False
|
||||
self._set_modifiers(device, ())
|
||||
if (type(self.layout) is X11Layout
|
||||
and 'gnome' in os.environ.get('XDG_CURRENT_DESKTOP', '').lower().split(':')):
|
||||
@@ -160,32 +154,10 @@ class SystemInputWorker(QThread):
|
||||
self.send_keys(device, (ecodes.KEY_KBD_LAYOUT_NEXT,))
|
||||
elif action == 'tap':
|
||||
try:
|
||||
if self.pending_super:
|
||||
self.pending_super = False
|
||||
self._set_modifiers(device, (ecodes.KEY_LEFTMETA,))
|
||||
self.send_keys(device, tuple(code for code in codes if code not in self.modifiers))
|
||||
finally:
|
||||
self._set_modifiers(device, ())
|
||||
|
||||
def _set_labwc_modifiers(self, device: UInput, codes: tuple[int, ...]) -> None:
|
||||
requested = set(codes)
|
||||
super_key = {ecodes.KEY_LEFTMETA}
|
||||
if self.pending_super and not requested:
|
||||
# Send both edges after the click; labwc cancels release bindings on pointer presses.
|
||||
self.pending_super = False
|
||||
self.send_keys(device, (ecodes.KEY_LEFTMETA,))
|
||||
return
|
||||
self.pending_super = requested == super_key and not self.modifiers
|
||||
if self.pending_super:
|
||||
return
|
||||
shift_keys = {ecodes.KEY_LEFTSHIFT, ecodes.KEY_RIGHTSHIFT}
|
||||
if (len(self.modifiers) == 2 and ecodes.KEY_LEFTALT in self.modifiers
|
||||
and self.modifiers & shift_keys and self.modifiers - requested):
|
||||
# XKB already switched when the chord was pressed; do not replay it.
|
||||
requested.difference_update(self.modifiers)
|
||||
self._set_modifiers(device, (ecodes.KEY_LEFTALT,))
|
||||
self._set_modifiers(device, tuple(requested))
|
||||
|
||||
def _set_modifiers(self, device: UInput, codes: tuple[int, ...]) -> None:
|
||||
requested = set(codes)
|
||||
for code in sorted(self.modifiers - requested, reverse=True):
|
||||
@@ -221,10 +193,9 @@ class SystemInputWorker(QThread):
|
||||
name = current[0] if isinstance(current, tuple) else getattr(self.layout, 'language', 'System')
|
||||
if hasattr(self.layout, 'layout_identifier'):
|
||||
name = self.layout.layout_identifier()
|
||||
active = self.modifiers | ({ecodes.KEY_LEFTMETA} if self.pending_super else set())
|
||||
self.state_changed.emit({'labels': labels, 'caps': caps,
|
||||
'shift': bool(active & {ecodes.KEY_LEFTSHIFT, ecodes.KEY_RIGHTSHIFT}),
|
||||
'modifiers': tuple(sorted(active)), 'layout': name})
|
||||
'shift': bool(self.modifiers & {ecodes.KEY_LEFTSHIFT, ecodes.KEY_RIGHTSHIFT}),
|
||||
'modifiers': tuple(sorted(self.modifiers)), 'layout': name})
|
||||
except Exception as error:
|
||||
logger.warning("Cannot update system keyboard labels: %s", error)
|
||||
self.warning.emit(str(error))
|
||||
|
||||
@@ -14,7 +14,6 @@ from evdev import ecodes
|
||||
from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, QSocketNotifier, Qt, QTimer
|
||||
from PySide6.QtGui import QCloseEvent, QIcon, QMouseEvent, QImage, QRegion
|
||||
from PySide6.QtWidgets import QApplication, QFrame, QLabel, QPushButton, QSizePolicy, QWidget
|
||||
from shiboken6 import isValid
|
||||
|
||||
from portprotonqt.config import gamepad_config, ui_config
|
||||
from portprotonqt.input_manager.constants import GamepadType
|
||||
@@ -44,7 +43,6 @@ class SystemKeyboardPanel(VirtualKeyboard):
|
||||
self.modifiers: set[int] = set()
|
||||
self.layout_name = 'System'
|
||||
self.drag_origin: QPoint | None = None
|
||||
self.emoji_open = False
|
||||
super().__init__(owner, theme)
|
||||
self.set_slide_animation_enabled(False)
|
||||
self.setObjectName('systemKeyboard')
|
||||
@@ -107,8 +105,7 @@ class SystemKeyboardPanel(VirtualKeyboard):
|
||||
for row, codes in zip(keyboard_layouts['us']['normal'], KEY_ROWS, strict=True):
|
||||
self.keycodes.update(zip(row, codes, strict=True))
|
||||
units = self.theme.SYSTEM_KEYBOARD['row_units']
|
||||
rows = self.theme.SYSTEM_KEYBOARD['emoji_rows' if self.emoji_open else 'rows']
|
||||
for row, keys in enumerate(rows):
|
||||
for row, keys in enumerate(self.theme.SYSTEM_KEYBOARD['rows']):
|
||||
column = 0
|
||||
for key, span in keys:
|
||||
if key == '▲▼':
|
||||
@@ -118,8 +115,7 @@ class SystemKeyboardPanel(VirtualKeyboard):
|
||||
self._add_key(key, (row * units, column, units, span))
|
||||
column += span
|
||||
self.apply_key_state()
|
||||
default = rows[0][0][0]
|
||||
self._set_selected_button(self.buttons.get(selected or default, self.buttons[default]))
|
||||
self._set_selected_button(self.buttons.get(selected or 'Esc', self.buttons['Esc']))
|
||||
if self.owner.warning_message:
|
||||
warning = QLabel(self.owner.warning_message)
|
||||
warning.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
|
||||
@@ -190,25 +186,7 @@ class SystemKeyboardPanel(VirtualKeyboard):
|
||||
self.owner.worker.commands.put(('release', ()))
|
||||
self.apply_key_state()
|
||||
|
||||
def close_emoji_panel(self) -> None:
|
||||
if self.emoji_open:
|
||||
self.emoji_open = False
|
||||
self.update_keyboard()
|
||||
self._set_selected_button(self.buttons['🙂'])
|
||||
|
||||
def on_button_click(self, key: str) -> None:
|
||||
if self.emoji_open:
|
||||
if key != 'ABC':
|
||||
report('emoji', key)
|
||||
self.close_emoji_panel()
|
||||
return
|
||||
if key == '🙂':
|
||||
self.stop_backspace_repeat()
|
||||
self._release_modifiers()
|
||||
self.emoji_open = True
|
||||
self.update_keyboard()
|
||||
self._set_selected_button(self.buttons['😀'])
|
||||
return
|
||||
code = ecodes.KEY_SPACE if key == ' ' else self.keycodes.get(key)
|
||||
if code is not None:
|
||||
self.owner.worker.commands.put(('tap', (code,)))
|
||||
@@ -345,7 +323,6 @@ class SystemKeyboardWindow(QWidget, MainWindowControlHintsMixin):
|
||||
self.worker.cancel_pending()
|
||||
self.keyboard.stop_backspace_repeat()
|
||||
self.keyboard._release_modifiers()
|
||||
self.keyboard.close_emoji_panel()
|
||||
if self.native_layer is not None:
|
||||
self.native_layer.hide_layer()
|
||||
self.hide()
|
||||
@@ -403,10 +380,6 @@ class SystemKeyboardWindow(QWidget, MainWindowControlHintsMixin):
|
||||
handlers = {'confirm': self.keyboard.activateFocusedKey, 'back': self.hide_keyboard,
|
||||
'language': self.keyboard.on_lang_click, 'backspace': self.keyboard.on_backspace_pressed,
|
||||
'backspace_release': self.keyboard.stop_backspace_repeat}
|
||||
if self.keyboard.emoji_open and value != 'confirm':
|
||||
if value == 'back':
|
||||
self.keyboard.close_emoji_panel()
|
||||
return
|
||||
if value == 'shift':
|
||||
self.keyboard.on_shift_click(not self.keyboard.shift_pressed)
|
||||
elif value in handlers:
|
||||
@@ -584,8 +557,6 @@ class WaylandWindow(QObject):
|
||||
if not width or not height or width * height > MAX_SURFACE_PIXELS:
|
||||
raise ValueError('Invalid Wayland layer-surface dimensions')
|
||||
self._request(self.layer, (6, None), (C.c_uint32(serial),))
|
||||
if self.configured and (width, height) == (self.window.width(), self.window.height()):
|
||||
return
|
||||
self.window.resize(width, height)
|
||||
self.window._position_keyboard()
|
||||
self.configured = self.dirty = True
|
||||
@@ -745,13 +716,6 @@ class WaylandWindow(QObject):
|
||||
self.window.keyboard.stop_backspace_repeat()
|
||||
|
||||
def _mouse_event(self, kind: QEvent.Type) -> None:
|
||||
pressed = self.pressed_widget
|
||||
if pressed is not None and (not isValid(pressed) or not self.window.isAncestorOf(pressed)):
|
||||
self.pressed_widget = None
|
||||
self.window.keyboard.stop_backspace_repeat()
|
||||
self.dirty = True
|
||||
if kind == QEvent.Type.MouseButtonRelease and self.pressed_widget is None:
|
||||
return
|
||||
point = self.position.toPoint()
|
||||
target = self.pressed_widget or self.window.childAt(point) or self.window.keyboard
|
||||
if isinstance(target, QPushButton) and self.window.keyboard.selected_button is not target:
|
||||
|
||||
@@ -596,12 +596,9 @@ class MainWindowLibraryTabMixin(_MainWindowTypingBase):
|
||||
self.updateDeleteMissingExeButton()
|
||||
|
||||
def quickLaunch(self):
|
||||
"""Open the launch file picker."""
|
||||
def file_filter(path: str) -> bool:
|
||||
return path.lower().endswith(LAUNCH_FILE_EXTENSIONS) or is_native_executable(path)
|
||||
|
||||
file_explorer = FileExplorer(self, self.theme, file_filter=file_filter)
|
||||
file_explorer.file_signal.file_selected.connect(self._quick_launch_selected)
|
||||
"""Open file manager to select executable and then open its detail page."""
|
||||
file_explorer = FileExplorer(self, self.theme, file_filter=LAUNCH_FILE_EXTENSIONS)
|
||||
file_explorer.file_signal.file_selected.connect(self.handle_launch_exe)
|
||||
|
||||
parent_geometry = self.geometry()
|
||||
center_point = parent_geometry.center()
|
||||
@@ -611,13 +608,6 @@ class MainWindowLibraryTabMixin(_MainWindowTypingBase):
|
||||
|
||||
file_explorer.show()
|
||||
|
||||
@Slot(str)
|
||||
def _quick_launch_selected(self, path: str) -> None:
|
||||
if path.lower().endswith(LAUNCH_FILE_EXTENSIONS):
|
||||
self.handle_launch_exe(path)
|
||||
else:
|
||||
self._launch_native_game(os.path.abspath(path))
|
||||
|
||||
def on_search_text_changed(self, text: str):
|
||||
"""Search text change handler with debounce."""
|
||||
self.searchDebounceTimer.stop()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import os
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from PySide6.QtCore import QObject, QRect, QSize, Qt, QThread, QTimer, Signal, Slot
|
||||
from PySide6.QtCore import QObject, QRect, QSize, Qt, QTimer
|
||||
from PySide6.QtGui import QAction
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractButton,
|
||||
@@ -104,20 +104,6 @@ class SettingsButtonsLayout(QBoxLayout):
|
||||
super().setGeometry(rect)
|
||||
|
||||
|
||||
class _GPUSettingsWorker(QThread):
|
||||
loaded = Signal(list, object)
|
||||
|
||||
def run(self) -> None:
|
||||
try:
|
||||
names = get_selectable_gpu_list()
|
||||
current = get_user_conf_setting("PW_GPU_USE") if len(names) > 1 else None
|
||||
except Exception:
|
||||
logger.exception("Failed to load GPU settings")
|
||||
return
|
||||
if not self.isInterruptionRequested():
|
||||
self.loaded.emit(names, current)
|
||||
|
||||
|
||||
class MainWindowSettingsTabMixin(_MainWindowTypingBase):
|
||||
if TYPE_CHECKING:
|
||||
def __getattr__(self, name: str) -> Any: ...
|
||||
@@ -783,12 +769,34 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
|
||||
hwForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
|
||||
scrollLayout.addWidget(hwFrame)
|
||||
|
||||
hwFrame.hide()
|
||||
self._gpu_settings_frame = hwFrame
|
||||
self._gpu_settings_form = hwForm
|
||||
self._gpu_settings_worker = _GPUSettingsWorker(self)
|
||||
self._gpu_settings_worker.loaded.connect(self._populate_gpu_settings, Qt.ConnectionType.QueuedConnection)
|
||||
self._gpu_settings_worker.start()
|
||||
filtered_gpu_list = get_selectable_gpu_list()
|
||||
hwFrame.setVisible(len(filtered_gpu_list) > 1)
|
||||
if len(filtered_gpu_list) > 1:
|
||||
self.gpuCombo = CustomComboBox(theme=self.theme)
|
||||
self.gpuCombo.view().window().setWindowFlags(
|
||||
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
|
||||
)
|
||||
self.gpuCombo.view().window().setAttribute(
|
||||
Qt.WidgetAttribute.WA_TranslucentBackground
|
||||
)
|
||||
self.gpuCombo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
self.gpuCombo.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||
self.gpuCombo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
|
||||
self.gpuCombo.addItems(filtered_gpu_list)
|
||||
current_gpu = get_user_conf_setting('PW_GPU_USE')
|
||||
if current_gpu and current_gpu != "disabled" and current_gpu in filtered_gpu_list:
|
||||
self.gpuCombo.setCurrentText(current_gpu)
|
||||
elif current_gpu and current_gpu != "disabled" and "Info:" not in current_gpu:
|
||||
if current_gpu not in filtered_gpu_list:
|
||||
self.gpuCombo.addItem(current_gpu)
|
||||
self.gpuCombo.setCurrentText(current_gpu)
|
||||
else:
|
||||
self.gpuCombo.setCurrentIndex(0)
|
||||
self.gpuTitle = QLabel(_("GPU to use:"))
|
||||
self.gpuTitle.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
|
||||
self.gpuTitle.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
|
||||
self.gpuTitle.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
hwForm.addRow(self.gpuTitle, self.gpuCombo)
|
||||
|
||||
# 5. Proxy Settings Section
|
||||
proxyFrame, proxyForm = create_section(_("Proxy Settings"), self.theme)
|
||||
@@ -899,36 +907,6 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
|
||||
layout.addLayout(actionsLayout)
|
||||
self.stackedWidget.addWidget(self.portProtonWidget)
|
||||
|
||||
@Slot(list, object)
|
||||
def _populate_gpu_settings(self, filtered_gpu_list: list[str], current_gpu: str | None) -> None:
|
||||
if self._gpu_settings_worker is None or len(filtered_gpu_list) <= 1:
|
||||
return
|
||||
self.gpuCombo = CustomComboBox(theme=self.theme)
|
||||
self.gpuCombo.view().window().setWindowFlags(
|
||||
Qt.WindowType.Popup | Qt.WindowType.FramelessWindowHint
|
||||
)
|
||||
self.gpuCombo.view().window().setAttribute(
|
||||
Qt.WidgetAttribute.WA_TranslucentBackground
|
||||
)
|
||||
self.gpuCombo.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
|
||||
self.gpuCombo.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
||||
self.gpuCombo.setStyleSheet(self.theme.COMBOBOX_STYLE + self.theme.SCROLL_STYLE)
|
||||
self.gpuCombo.addItems(filtered_gpu_list)
|
||||
if current_gpu and current_gpu != "disabled" and current_gpu in filtered_gpu_list:
|
||||
self.gpuCombo.setCurrentText(current_gpu)
|
||||
elif current_gpu and current_gpu != "disabled" and "Info:" not in current_gpu:
|
||||
if current_gpu not in filtered_gpu_list:
|
||||
self.gpuCombo.addItem(current_gpu)
|
||||
self.gpuCombo.setCurrentText(current_gpu)
|
||||
else:
|
||||
self.gpuCombo.setCurrentIndex(0)
|
||||
self.gpuTitle = QLabel(_("GPU to use:"))
|
||||
self.gpuTitle.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
|
||||
self.gpuTitle.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
|
||||
self.gpuTitle.setFocusPolicy(Qt.FocusPolicy.NoFocus)
|
||||
self._gpu_settings_form.addRow(self.gpuTitle, self.gpuCombo)
|
||||
self._gpu_settings_frame.show()
|
||||
|
||||
def openGlobalGameSettings(self) -> None:
|
||||
from portprotonqt.dialogs.settings_dialog import ExeSettingsDialog
|
||||
|
||||
|
||||
@@ -160,12 +160,11 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
|
||||
tools_grid.setSpacing(6)
|
||||
|
||||
tools = [
|
||||
("winecfg", _("Wine Configuration")),
|
||||
("regedit", _("Registry Editor")),
|
||||
("winefile", _("File Explorer")),
|
||||
("cmd", _("Command Prompt")),
|
||||
("uninstaller", _("Uninstaller")),
|
||||
("taskmgr", _("Task Manager")),
|
||||
("--winecfg", _("Wine Configuration")),
|
||||
("--winereg", _("Registry Editor")),
|
||||
("--winefile", _("File Explorer")),
|
||||
("--winecmd", _("Command Prompt")),
|
||||
("--wine_uninstaller", _("Uninstaller")),
|
||||
]
|
||||
|
||||
for i, (tool_cmd, tool_name) in enumerate(tools):
|
||||
@@ -238,7 +237,7 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
|
||||
env_vars = os.environ.copy()
|
||||
self._check_missing_prefix_by_name_before_launch(prefix, env_vars)
|
||||
start_sh = self.start_sh
|
||||
cmd = start_sh + ["cli", "--wine-session-tool", cli_arg, wine, prefix]
|
||||
cmd = start_sh + ["cli", cli_arg, wine, prefix]
|
||||
|
||||
# Show progress bar before launch
|
||||
self.wine_progress_bar.setVisible(True)
|
||||
@@ -270,7 +269,16 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
|
||||
|
||||
def _check_wine_process(self, cli_arg):
|
||||
"""Check if target .exe process started."""
|
||||
target_exe = f"{cli_arg}.exe"
|
||||
exe_map = {
|
||||
"--winecfg": "winecfg.exe",
|
||||
"--winereg": "regedit.exe",
|
||||
"--winefile": "winefile.exe",
|
||||
"--winecmd": "cmd.exe",
|
||||
"--wine_uninstaller": "uninstaller.exe",
|
||||
}
|
||||
target_exe = exe_map.get(cli_arg, "")
|
||||
if not target_exe:
|
||||
return
|
||||
|
||||
# Check processes via psutil
|
||||
for proc in psutil.process_iter(attrs=["name"]):
|
||||
|
||||
@@ -5,9 +5,6 @@ logger = get_logger(__name__)
|
||||
|
||||
class MainWindowWorkersMixin:
|
||||
def _stopBackgroundWorkers(self) -> None:
|
||||
from portprotonqt.steam_api.api import stop_metadata_lookups
|
||||
|
||||
stop_metadata_lookups()
|
||||
context_menu_manager = getattr(self, "context_menu_manager", None)
|
||||
if context_menu_manager is not None:
|
||||
context_menu_manager.stop_card_actions()
|
||||
@@ -31,7 +28,6 @@ class MainWindowWorkersMixin:
|
||||
"appImageIntegrationWorker": None,
|
||||
"gogdlUpdateWorker": None,
|
||||
"initialCommandWorker": None,
|
||||
"_gpu_settings_worker": None,
|
||||
"egs_library_worker": None,
|
||||
"egs_auth_worker": None,
|
||||
"gog_library_worker": None,
|
||||
|
||||
File renamed without changes.
|
Before Width: | Height: | Size: 3.1 KiB After Width: | Height: | Size: 3.1 KiB |
@@ -334,17 +334,9 @@ SYSTEM_KEYBOARD = {
|
||||
("k", 2), ("l", 2), (";", 2), ("'", 2), ("Enter", 4)),
|
||||
(("⬆", 4), ("<", 2), ("z", 2), ("x", 2), ("c", 2), ("v", 2), ("b", 2), ("n", 2),
|
||||
("m", 2), (",", 2), (".", 2), ("/", 2), ("RShift", 4)),
|
||||
(("Ctrl", 2), ("Super", 2), ("Alt", 2), ("Space", 8), ("🙂", 2), ("🌐", 2), ("AltGr", 2),
|
||||
(("Ctrl", 2), ("Super", 2), ("Alt", 2), ("Space", 10), ("🌐", 2), ("AltGr", 2),
|
||||
("RCtrl", 2), ("◄", 2), ("▲▼", 2), ("►", 2), ("Hide", 2)),
|
||||
),
|
||||
"emoji_rows": (
|
||||
(("😀", 3), ("😃", 3), ("😄", 3), ("😁", 3), ("😆", 3), ("😅", 3), ("😂", 3), ("🤣", 3), ("🙂", 3), ("🙃", 3)),
|
||||
(("😉", 3), ("😊", 3), ("😍", 3), ("🥰", 3), ("😘", 3), ("😎", 3), ("🤔", 3), ("😴", 3), ("😭", 3), ("😡", 3)),
|
||||
(("👍", 3), ("👎", 3), ("👏", 3), ("🙌", 3), ("🙏", 3), ("🤝", 3), ("👋", 3), ("✌️", 3), ("💪", 3), ("👌", 3)),
|
||||
(("❤️", 3), ("💔", 3), ("🔥", 3), ("✨", 3), ("⭐", 3), ("🎉", 3), ("🎮", 3), ("🏆", 3), ("✅", 3), ("❌", 3)),
|
||||
(("🐱", 3), ("🐶", 3), ("🌈", 3), ("☀️", 3), ("🌙", 3), ("🌻", 3), ("🍕", 3), ("🍔", 3), ("☕", 3), ("🎵", 3)),
|
||||
(("ABC", 30),),
|
||||
),
|
||||
}
|
||||
DETAIL_PAGE_LAYOUT_MODE = "full"
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ import subprocess
|
||||
import signal
|
||||
import psutil
|
||||
import os
|
||||
from PySide6.QtCore import QProcess
|
||||
from PySide6.QtWidgets import QSystemTrayIcon, QMenu, QApplication, QMessageBox
|
||||
from PySide6.QtGui import QIcon, QAction
|
||||
from portprotonqt.logger import get_logger
|
||||
@@ -46,39 +45,6 @@ def _restart_args(args: list[str]) -> list[str]:
|
||||
return restart_args
|
||||
|
||||
|
||||
def create_wine_tools_menu(parent: QMenu, start_sh: list[str]) -> QMenu:
|
||||
"""Create tools that join the running game's Wine session."""
|
||||
menu = QMenu("Wine", parent)
|
||||
tools = (
|
||||
("winefile", _("File Explorer")),
|
||||
("taskmgr", _("Task Manager")),
|
||||
("winecfg", _("Wine Configuration")),
|
||||
("regedit", _("Registry Editor")),
|
||||
("cmd", _("Command Prompt")),
|
||||
("uninstaller", _("Uninstaller")),
|
||||
)
|
||||
for tool, title in tools:
|
||||
action = menu.addAction(title)
|
||||
action.triggered.connect(
|
||||
lambda checked=False, name=tool: launch_session_wine_tool(start_sh, name)
|
||||
)
|
||||
return menu
|
||||
|
||||
|
||||
def launch_session_wine_tool(start_sh: list[str], tool: str) -> None:
|
||||
"""Start a Wine tool without running the game's startup or cleanup."""
|
||||
if not start_sh:
|
||||
logger.error("Cannot launch Wine tool: PortProton command is missing")
|
||||
QMessageBox.warning(None, _("Error"), _("Failed to start process."))
|
||||
return
|
||||
started, _pid = QProcess.startDetached(
|
||||
start_sh[0], start_sh[1:] + ["cli", "--wine-session-tool", tool]
|
||||
)
|
||||
if not started:
|
||||
logger.error("Failed to start Wine tool %s", tool)
|
||||
QMessageBox.warning(None, _("Error"), _("Failed to start process."))
|
||||
|
||||
|
||||
class TrayManager:
|
||||
"""Tray management module for PortProtonQt.
|
||||
|
||||
@@ -117,10 +83,15 @@ class TrayManager:
|
||||
self.pause_game_action.setEnabled(False)
|
||||
self.pause_game_action.triggered.connect(self.toggle_game_pause)
|
||||
|
||||
self.wine_tools_menu = create_wine_tools_menu(self.tray_menu, self.main_window.start_sh)
|
||||
self.tray_menu.addAction(self.pause_game_action)
|
||||
self.tray_menu.addAction(self.stop_game_action)
|
||||
self.tray_menu.addSeparator()
|
||||
self.tray_menu.addSeparator()
|
||||
|
||||
exit_action = QAction(_("Exit"), self.main_window)
|
||||
exit_action.triggered.connect(self.force_exit)
|
||||
self.tray_menu.addAction(exit_action)
|
||||
|
||||
# Some D-Bus tray hosts read the menu without opening the local QMenu.
|
||||
self.refresh_tray_menu()
|
||||
self.tray_menu.aboutToShow.connect(self.refresh_tray_menu)
|
||||
self.tray_icon.setContextMenu(self.tray_menu)
|
||||
self.tray_icon.show()
|
||||
@@ -132,7 +103,6 @@ class TrayManager:
|
||||
|
||||
self.tray_menu.addAction(self.pause_game_action)
|
||||
self.tray_menu.addAction(self.stop_game_action)
|
||||
self.tray_menu.addMenu(self.wine_tools_menu)
|
||||
self.update_game_actions()
|
||||
system_keyboard = getattr(getattr(self, 'main_window', None), 'system_keyboard', None)
|
||||
if system_keyboard is not None:
|
||||
@@ -185,7 +155,6 @@ class TrayManager:
|
||||
target_exe = getattr(self.main_window, "target_exe", None)
|
||||
has_running_game = bool(game_processes or target_exe)
|
||||
self.stop_game_action.setEnabled(has_running_game)
|
||||
self.wine_tools_menu.setEnabled(has_running_game)
|
||||
self.pause_game_action.setEnabled(bool(processes))
|
||||
paused = self._are_processes_paused(processes)
|
||||
self.pause_game_action.setText(_("Resume Game") if paused else _("Pause Game"))
|
||||
@@ -421,9 +390,8 @@ class TrayManager:
|
||||
self.main_window._apply_theme_live("standart")
|
||||
|
||||
def force_exit(self):
|
||||
self.main_window._explicit_exit = True
|
||||
if self.main_window.close():
|
||||
QApplication.quit()
|
||||
self.main_window.close()
|
||||
sys.exit(0)
|
||||
|
||||
def shutdown(self):
|
||||
if self.tray_icon:
|
||||
|
||||
@@ -235,11 +235,9 @@ def test_appimage_update_worker_uses_github_mirror(
|
||||
assert available == [("Repo changelog", appimage_updater.GITHUB_UPDATE_INFO)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exited_before_read", [False, True])
|
||||
def test_appimage_update_worker_emits_pty_progress(
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
exited_before_read: bool,
|
||||
) -> None:
|
||||
appimage = tmp_path / "PortProtonQt.AppImage"
|
||||
appimage.write_text("old version\n", encoding="utf-8")
|
||||
@@ -269,14 +267,6 @@ def test_appimage_update_worker_emits_pty_progress(
|
||||
worker.update_progress.connect(
|
||||
lambda percent, message: progress_values.append((percent, message))
|
||||
)
|
||||
if exited_before_read:
|
||||
read_pty_output = worker._read_pty_output
|
||||
|
||||
def read_after_exit(master_fd: int, process: subprocess.Popen[bytes]) -> None:
|
||||
assert process.wait(timeout=5) == 0
|
||||
read_pty_output(master_fd, process)
|
||||
|
||||
monkeypatch.setattr(worker, "_read_pty_output", read_after_exit)
|
||||
worker.run()
|
||||
|
||||
assert progress_values == [(25, "25% \u2193 32.0 MB/128.0 MB")]
|
||||
|
||||
@@ -737,57 +737,3 @@ def test_steam_detail_button_attaches_to_existing_game_watch() -> None:
|
||||
window._toggle_steam_game.assert_called_once_with(
|
||||
"steam://rungameid/3263320", button, launch=False
|
||||
)
|
||||
|
||||
|
||||
@mark.parametrize("hp_fields", [{}, {"hpKey": "field"}, {"hpKey": "field", "hpVal": "value"}])
|
||||
def test_hltb_search_accepts_token_without_optional_pair(
|
||||
monkeypatch: MonkeyPatch, hp_fields: dict[str, str]
|
||||
) -> None:
|
||||
import orjson
|
||||
|
||||
from portprotonqt.howlongtobeat_api import HTTPClient, ResultParser
|
||||
|
||||
monkeypatch.setattr("portprotonqt.howlongtobeat_api.proxy_config.get_proxy", lambda: {})
|
||||
client = HTTPClient()
|
||||
session = MagicMock()
|
||||
monkeypatch.setattr(client, "session", session)
|
||||
session.get.return_value.json.return_value = {"token": "test-token", **hp_fields}
|
||||
session.post.return_value = SimpleNamespace(status_code=200, text='{"data": [{"comp_main": 12600}]}')
|
||||
|
||||
raw = client.search_games("MARVEL Cosmic Invasion")
|
||||
assert raw is not None
|
||||
assert ResultParser().parse_results(raw)[0].main_story == 3.5
|
||||
assert session.get.call_args.args[0].endswith("/api/search/site/init")
|
||||
assert session.post.call_args.args[0].endswith("/api/search/site")
|
||||
request = session.post.call_args.kwargs
|
||||
assert request["headers"]["x-auth-token"] == "test-token"
|
||||
payload = orjson.loads(request["data"])
|
||||
assert payload["searchTerms"] == ["MARVEL", "Cosmic", "Invasion"]
|
||||
assert payload.get("field") == hp_fields.get("hpVal")
|
||||
assert request["headers"].get("x-hp-key") == ("field" if "hpVal" in hp_fields else None)
|
||||
assert request["headers"].get("x-hp-val") == hp_fields.get("hpVal")
|
||||
|
||||
|
||||
def test_native_detail_cover_shows_linux_source_corner() -> None:
|
||||
from PySide6.QtWidgets import QApplication, QFrame
|
||||
|
||||
from portprotonqt.detail_pages.widgets import _add_source_corner
|
||||
from portprotonqt.game_card import SourceCorner
|
||||
|
||||
app = QApplication.instance() or QApplication([])
|
||||
cover = QFrame()
|
||||
cover.resize(300, 450)
|
||||
icon_path = Path(__file__).resolve().parents[1] / (
|
||||
"portprotonqt/themes/standart/images/icons/platforms/badge_native.svg"
|
||||
)
|
||||
theme_manager = MagicMock()
|
||||
theme_manager.get_icon.return_value = str(icon_path)
|
||||
theme = SimpleNamespace(get_source_corner_config=lambda: {})
|
||||
|
||||
_add_source_corner(cover, "native", theme, theme_manager, cover.width(), cover.height())
|
||||
app.processEvents()
|
||||
|
||||
theme_manager.get_icon.assert_called_once_with("badge_native", as_path=True)
|
||||
ribbon = cover.findChild(SourceCorner)
|
||||
assert ribbon is not None and not ribbon.isHidden()
|
||||
assert ribbon.geometry().bottomRight() == cover.rect().bottomRight()
|
||||
+2
-114
@@ -1,15 +1,11 @@
|
||||
"""Download cache completion and worker lifecycle regressions."""
|
||||
|
||||
from collections.abc import Iterator
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
import threading
|
||||
from typing import Any, cast
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from PIL import Image
|
||||
import pytest
|
||||
from requests.exceptions import ConnectionError, ReadTimeout
|
||||
from PySide6.QtCore import QCoreApplication, QThread
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
@@ -25,88 +21,6 @@ def application() -> QCoreApplication:
|
||||
return QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("parallel", [False, True])
|
||||
@pytest.mark.parametrize("complete", [False, True])
|
||||
def test_truncated_cached_cover_is_redownloaded(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, parallel: bool, complete: bool,
|
||||
) -> None:
|
||||
url = "https://example.com/cover.jpg"
|
||||
target = tmp_path / "cover.jpg"
|
||||
buffer = BytesIO()
|
||||
Image.new("RGB", (32, 32)).save(buffer, format="JPEG")
|
||||
jpeg = buffer.getvalue()
|
||||
truncated = jpeg[:-30]
|
||||
target.write_bytes(truncated)
|
||||
response = MagicMock()
|
||||
response.headers = {}
|
||||
|
||||
def chunks(chunk_size: int) -> Iterator[bytes]:
|
||||
yield jpeg[:100]
|
||||
assert target.read_bytes() == truncated
|
||||
yield (jpeg if complete else truncated)[100:]
|
||||
|
||||
response.iter_content.side_effect = chunks
|
||||
session = MagicMock()
|
||||
session.get.return_value.__enter__.return_value = response
|
||||
monkeypatch.setattr("portprotonqt.downloader.get_requests_session", lambda: session)
|
||||
downloader = Downloader()
|
||||
downloader._cache[url] = str(target)
|
||||
results: list[str | None] = []
|
||||
|
||||
worker = downloader.download_async(url, str(target), parallel=parallel, callback=results.append)
|
||||
|
||||
assert worker is not None
|
||||
assert worker.wait(THREAD_TIMEOUT_MS)
|
||||
QApplication.processEvents()
|
||||
assert results == [str(target) if complete else None]
|
||||
assert target.read_bytes() == (jpeg if complete else truncated)
|
||||
assert list(tmp_path.iterdir()) == [target]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", [ConnectionError, ReadTimeout, PermissionError])
|
||||
def test_failed_download_can_recover(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, error: type[Exception],
|
||||
) -> None:
|
||||
from portprotonqt import downloader as module
|
||||
|
||||
now = 100.0
|
||||
from types import SimpleNamespace
|
||||
|
||||
monkeypatch.setattr(module, "time", SimpleNamespace(monotonic=lambda: now))
|
||||
session = MagicMock()
|
||||
response = session.get.return_value.__enter__.return_value
|
||||
response.headers = {}
|
||||
monkeypatch.setattr(module, "get_requests_session", lambda: session)
|
||||
|
||||
def interrupted() -> Iterator[bytes]:
|
||||
yield b"partial"
|
||||
if error is not PermissionError:
|
||||
raise error("simulated connection failure")
|
||||
|
||||
if error is PermissionError:
|
||||
replace = Path.replace
|
||||
|
||||
def replace_after_recovery(path: Path, destination: Path) -> Path:
|
||||
if now == 100.0:
|
||||
raise PermissionError("simulated write failure")
|
||||
return replace(path, destination)
|
||||
|
||||
monkeypatch.setattr(Path, "replace", replace_after_recovery)
|
||||
response.iter_content.side_effect = [interrupted(), iter([b"complete"])]
|
||||
downloader = Downloader()
|
||||
url = "https://example.com/data.json"
|
||||
target = tmp_path / "data.json"
|
||||
assert downloader.download(url, str(target)) is None
|
||||
assert not list(tmp_path.iterdir())
|
||||
assert downloader.download(url, str(target)) is None
|
||||
assert session.get.call_count == 1
|
||||
|
||||
now += module.FAILURE_RETRY_SECONDS
|
||||
assert downloader.download(url, str(target)) == str(target)
|
||||
assert target.read_bytes() == b"complete"
|
||||
assert session.get.call_count == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("parallel", [False, True])
|
||||
@pytest.mark.parametrize("failed", [False, True])
|
||||
def test_resolved_download_completes_without_a_worker(
|
||||
@@ -116,7 +30,7 @@ def test_resolved_download_completes_without_a_worker(
|
||||
url = "https://example.com/data.json"
|
||||
path = str(tmp_path / "data.json")
|
||||
if failed:
|
||||
downloader._record_failure(url)
|
||||
downloader._last_error[url] = True
|
||||
else:
|
||||
Path(path).write_text("{}")
|
||||
start = MagicMock()
|
||||
@@ -182,7 +96,7 @@ def test_parallel_known_failure_does_not_create_an_executor(
|
||||
downloader = Downloader()
|
||||
url = "https://example.com/data.json"
|
||||
path = str(tmp_path / "data.json")
|
||||
downloader._record_failure(url)
|
||||
downloader._last_error[url] = True
|
||||
downloader._cache[url] = path
|
||||
download = MagicMock()
|
||||
monkeypatch.setattr(downloader, "_download_with_parallel", download)
|
||||
@@ -261,29 +175,3 @@ def test_shutdown_waits_for_an_active_download(
|
||||
release.set()
|
||||
release_timer.join()
|
||||
worker.wait(THREAD_TIMEOUT_MS)
|
||||
|
||||
|
||||
def test_shutdown_waits_for_active_artwork_lookup(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from portprotonqt.steam_api import api
|
||||
|
||||
entered, release, finished = threading.Event(), threading.Event(), threading.Event()
|
||||
|
||||
def lookup(_game_name: str, _image_type: str) -> str:
|
||||
entered.set()
|
||||
assert release.wait(SYNC_TIMEOUT_SECONDS)
|
||||
finished.set()
|
||||
return ""
|
||||
|
||||
monkeypatch.setattr(api, "_read_sgdb_cover", lookup)
|
||||
api.fetch_sgdb_cover_async("Game", lambda _cover: None)
|
||||
release_timer = threading.Timer(0.05, release.set)
|
||||
try:
|
||||
assert entered.wait(SYNC_TIMEOUT_SECONDS)
|
||||
release_timer.start()
|
||||
MainWindowWorkersMixin()._stopBackgroundWorkers()
|
||||
assert finished.is_set()
|
||||
finally:
|
||||
release.set()
|
||||
if release_timer.ident is not None:
|
||||
release_timer.join()
|
||||
assert api._METADATA_LOOKUPS.waitForDone(THREAD_TIMEOUT_MS)
|
||||
+2
-77
@@ -309,84 +309,9 @@ def test_download_sizes_cache(tmp_path: Path) -> None:
|
||||
assert api.get_cached_download_sizes("123") == (100, 200)
|
||||
|
||||
|
||||
GOG_SECTIONED_DESCRIPTION = (
|
||||
"<h4>Industrial revolution</h4>\n<p>\n<br>\nMagic meets technology.</p>"
|
||||
"<p> </p><h4>Features<br></h4><ul><li>Character development</li></ul>"
|
||||
)
|
||||
|
||||
|
||||
def test_load_library_shortens_cached_description(tmp_path: Path) -> None:
|
||||
api = GOGAPI()
|
||||
api.library_path = tmp_path / "library.json"
|
||||
games = [{"app_id": "1207658829", "description": GOG_SECTIONED_DESCRIPTION}]
|
||||
api._save_json(api.library_path, games)
|
||||
original = api.library_path.read_bytes()
|
||||
|
||||
assert api.load_library() == [{"app_id": "1207658829", "description": "Magic meets technology."}]
|
||||
assert api.library_path.read_bytes() == original
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("lead", "expected"),
|
||||
[
|
||||
(GOG_SECTIONED_DESCRIPTION, "Magic meets technology."),
|
||||
pytest.param(
|
||||
'<div><a href="/game/hellpoint"><img src="banner.jpg"></a>'
|
||||
'<span>The full version of Hellpoint is available on GOG.com. You can buy it '
|
||||
'<a href="/game/hellpoint"><b>here</b></a></span></div><hr>\n<br>\n'
|
||||
'The Thespian Feast — бесплатная глава Hellpoint.',
|
||||
"The Thespian Feast — бесплатная глава Hellpoint.",
|
||||
id="hellpoint-full-version-promo",
|
||||
),
|
||||
pytest.param(
|
||||
"<b><i>Я пишу это в состоянии значительного душевного напряжения.</i></b>"
|
||||
"<br><br>Dagon — трехмерная история по рассказу <b>Лавкрафта</b>.",
|
||||
"Dagon — трехмерная история по рассказу <b>Лавкрафта</b>.",
|
||||
id="dagon-epigraph-before-synopsis",
|
||||
),
|
||||
("<i>Only available description.</i>", "<i>Only available description.</i>"),
|
||||
pytest.param(
|
||||
'<p class="module">Discover <a href="https://example.com">more games</a>.</p>'
|
||||
'<br><hr><b><h4>Game Description</h4></b>\nShortly after landing…\n<br>\n'
|
||||
'<b><h4>About Quake II RTX</h4> </b>Technical details.',
|
||||
"Shortly after landing…",
|
||||
id="quake-rtx-promo",
|
||||
),
|
||||
pytest.param(
|
||||
'<p><img src="banner.jpg"></p><p class="module">В издание входит дополнение.</p>'
|
||||
'<p> </p><p>Реалистичный психологический триллер. ',
|
||||
"Реалистичный психологический триллер.",
|
||||
id="postal-edition-module",
|
||||
),
|
||||
pytest.param(
|
||||
'<b>Внимание! В этой игре нет русской локализации.</b><br><br>Описание игры.',
|
||||
"Описание игры.",
|
||||
id="sang-froid-localization-notice",
|
||||
),
|
||||
pytest.param(
|
||||
'<img src="logo.png" />\n<br>\n<b>Martial Law</b> — визуальная новелла.'
|
||||
'<h4>Особенности:</h4><ul><li>Много вариантов исхода.</li></ul><i>GameJam</i>',
|
||||
"<b>Martial Law</b> — визуальная новелла.",
|
||||
id="martial-law-logo-and-features",
|
||||
),
|
||||
("<p> </p>", "English description"),
|
||||
("Intro\n<strong>War Wind</strong> continues.", "Intro<br><b>War Wind</b> continues."),
|
||||
pytest.param(
|
||||
'<div style="overflow: hidden;"> <a href="/game/demo"><img src="cover.jpg"></a>'
|
||||
'<span>Demo</span></div><hr>Game synopsis.',
|
||||
"Game synopsis.",
|
||||
id="linked-cover-cross-sell",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"lead": '<div><a href="/game/shores_unknown"><img src="banner.jpg"></a><span>',
|
||||
"full": '<div><span>The full version of Shores Unknown is available on GOG.com. '
|
||||
'You can purchase it <a href="/game/shores_unknown">here</a></span></div><hr>'
|
||||
'<i>Shores Unknown: Arrival</i> is a free demo.<br><br>Game features.',
|
||||
},
|
||||
"<i>Shores Unknown: Arrival</i> is a free demo.",
|
||||
id="shores-unknown-truncated-lead",
|
||||
),
|
||||
(
|
||||
"Description française.<br><br>Deuxième paragraphe.",
|
||||
"Description française.",
|
||||
@@ -398,7 +323,7 @@ def test_load_library_shortens_cached_description(tmp_path: Path) -> None:
|
||||
],
|
||||
)
|
||||
def test_get_game_loads_localized_product_description(
|
||||
monkeypatch: pytest.MonkeyPatch, lead: str | dict[str, str], expected: str
|
||||
monkeypatch: pytest.MonkeyPatch, lead: str, expected: str
|
||||
) -> None:
|
||||
gamesdb_response = Mock()
|
||||
gamesdb_response.json.return_value = {
|
||||
@@ -412,7 +337,7 @@ def test_get_game_loads_localized_product_description(
|
||||
}
|
||||
product_response = Mock()
|
||||
product_response.json.return_value = {
|
||||
"description": {"lead": lead} if isinstance(lead, str) else lead,
|
||||
"description": {"lead": lead},
|
||||
}
|
||||
request = Mock(side_effect=[gamesdb_response, product_response])
|
||||
monkeypatch.setattr("portprotonqt.gog_api.get_metadata_language", lambda: "fr")
|
||||
|
||||
@@ -650,8 +650,6 @@ def test_remote_cover_replaces_immediate_exe_fallback_only_on_success(
|
||||
lambda: SimpleNamespace(current_theme_module=theme),
|
||||
)
|
||||
|
||||
downloaded_path = fallback_path.parent / filename
|
||||
downloaded_path.write_bytes(b"\xff\xd8truncated JPEG")
|
||||
image_utils.load_pixmap_async(
|
||||
url, 100, 150,
|
||||
lambda pixmap: loaded_paths.append(cast(FakePixmap, pixmap).path),
|
||||
@@ -659,6 +657,7 @@ def test_remote_cover_replaces_immediate_exe_fallback_only_on_success(
|
||||
fallback_icon_path=str(fallback_path),
|
||||
)
|
||||
callbacks[0](None)
|
||||
downloaded_path = tmp_path / "cache" / "PortProtonQt" / "images" / filename
|
||||
downloaded_path.write_bytes(b"cover")
|
||||
callbacks[0](str(downloaded_path))
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ from shiboken6 import delete
|
||||
import portprotonqt.input_manager as input_manager
|
||||
import portprotonqt.input_manager.buttons as input_buttons
|
||||
import portprotonqt.input_manager.dpad as input_dpad
|
||||
import portprotonqt.input_manager.keyboard as input_keyboard
|
||||
import portprotonqt.input_manager.runtime as input_runtime
|
||||
import portprotonqt.native_gamepad as native_gamepad
|
||||
from portprotonqt.input_manager.constants import (
|
||||
@@ -269,49 +268,6 @@ def test_sdl_dpad_vertical_directions() -> None:
|
||||
assert emitted == [(PAD_DPAD_Y, -1, 1.0), (PAD_DPAD_Y, 1, 2.0)]
|
||||
|
||||
|
||||
@mark.parametrize('emulation', [False, True])
|
||||
@mark.parametrize(('button', 'direction'), [
|
||||
(SDL_GAMEPAD_BUTTON_DPAD_UP, -1),
|
||||
(SDL_GAMEPAD_BUTTON_DPAD_DOWN, 1),
|
||||
])
|
||||
def test_system_keyboard_gamepad_drag(emulation: bool, button: int, direction: int) -> None:
|
||||
manager: Any = InputManager.__new__(InputManager)
|
||||
QObject.__init__(manager)
|
||||
keyboard = MagicMock()
|
||||
keyboard.isVisible.return_value = True
|
||||
manager._parent = SimpleNamespace(system_keyboard=keyboard)
|
||||
manager._button_states = {}
|
||||
manager._hat_states = {}
|
||||
manager.mouse_emulation_enabled = manager.emulation_active = True
|
||||
manager.emulation_triggered = emulation
|
||||
manager.ui = MagicMock()
|
||||
gamepad = cast(SDLGamepad, SimpleNamespace(
|
||||
get_button=lambda code: int(code == button),
|
||||
))
|
||||
dpad = MagicMock()
|
||||
manager.dpad_moved.connect(dpad)
|
||||
codes = input_manager.ecodes
|
||||
|
||||
manager._handle_button_value(0, PAD_BUTTON_SOUTH, 1, 1.0)
|
||||
manager._poll_hat_events(gamepad, 2.0)
|
||||
keyboard.isVisible.return_value = False
|
||||
manager._handle_button_value(0, PAD_BUTTON_SOUTH, 0, 3.0)
|
||||
|
||||
if emulation:
|
||||
keyboard.send.assert_not_called()
|
||||
dpad.assert_not_called()
|
||||
assert [call.args for call in manager.ui.write.call_args_list] == [
|
||||
(codes.EV_KEY, codes.BTN_LEFT, 1),
|
||||
(codes.EV_REL, codes.REL_X, 0),
|
||||
(codes.EV_REL, codes.REL_Y, 10 * direction),
|
||||
(codes.EV_KEY, codes.BTN_LEFT, 0),
|
||||
]
|
||||
else:
|
||||
keyboard.send.assert_called_once_with('button', 'confirm')
|
||||
dpad.assert_called_once_with(PAD_DPAD_Y, direction, 2.0)
|
||||
manager.ui.write.assert_not_called()
|
||||
|
||||
|
||||
def test_disabling_mouse_emulation_keeps_gamepad_events_working() -> None:
|
||||
emitted: list[tuple[int, int]] = []
|
||||
manager = InputManager.__new__(InputManager)
|
||||
@@ -574,32 +530,6 @@ def test_library_toolbar_navigation_includes_delete_missing_button() -> None:
|
||||
assert QApplication.focusWidget() is widgets[4]
|
||||
|
||||
|
||||
def test_dpad_down_from_toolbar_focuses_first_visual_card(monkeypatch: MonkeyPatch) -> None:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
window = QWidget()
|
||||
toolbar_button = QPushButton(window)
|
||||
container = QWidget(window)
|
||||
container.setGeometry(0, 40, 100, 100)
|
||||
lower_card = DummyCard(container, FIRST_CARD_X)
|
||||
lower_card.move(FIRST_CARD_X, 40)
|
||||
right_card = DummyCard(container, NEXT_CARD_X)
|
||||
first_card = DummyCard(container, FIRST_CARD_X)
|
||||
window.show()
|
||||
app.processEvents()
|
||||
monkeypatch.setattr(input_keyboard, "AnimatedCard", DummyCard)
|
||||
manager = InputManager.__new__(InputManager)
|
||||
manager._parent = cast(MainWindowProtocol, SimpleNamespace(
|
||||
quickLaunchButton=toolbar_button,
|
||||
stackedWidget=SimpleNamespace(currentIndex=lambda: 0),
|
||||
gamesListWidget=container,
|
||||
))
|
||||
assert right_card.isVisible()
|
||||
for _ in range(2):
|
||||
toolbar_button.setFocus()
|
||||
assert manager._handle_library_dpad(PAD_DPAD_Y, 1)
|
||||
assert QApplication.focusWidget() is first_card
|
||||
|
||||
|
||||
def test_library_filter_navigation_includes_only_installed_checkbox() -> None:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
controls = QWidget()
|
||||
|
||||
+163
-33
@@ -6,21 +6,21 @@ from typing import Any, cast
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QCoreApplication, QEvent, Qt
|
||||
from PySide6.QtCore import QCoreApplication, QEvent, QEventLoop, QThread, Qt, QTimer
|
||||
from PySide6.QtGui import QMouseEvent, QPixmap
|
||||
from PySide6.QtWidgets import QApplication, QLineEdit, QWidget
|
||||
|
||||
from portprotonqt import image_utils
|
||||
from portprotonqt.game_card import GameCard
|
||||
from portprotonqt.game_library_manager import GameLibraryManager
|
||||
from portprotonqt.theme_manager import ThemeManager, load_theme
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def library_theme() -> Any:
|
||||
return load_theme("standart")
|
||||
LOAD_TIMEOUT_MS = 30000
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def library_scene(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_config_dir: Path, library_theme: Any,
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_config_dir: Path,
|
||||
) -> Generator[tuple[GameLibraryManager, list[Callable[[QPixmap], None]]], None, None]:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
callbacks: list[Callable[[QPixmap], None]] = []
|
||||
@@ -32,7 +32,7 @@ def library_scene(
|
||||
openGameDetailPage=MagicMock(), current_hovered_card=None, current_focused_card=None,
|
||||
))
|
||||
main.createSearchWidget = lambda: (QWidget(), main.searchEdit)
|
||||
manager = GameLibraryManager(main, library_theme, cast(Any, MagicMock()))
|
||||
manager = GameLibraryManager(main, load_theme("standart"), cast(Any, MagicMock()))
|
||||
manager.create_games_library_widget()
|
||||
cast(Any, manager.gamesLibraryWidget).game_library_manager = manager
|
||||
manager.gamesLibraryWidget.resize(1000, 700)
|
||||
@@ -65,7 +65,7 @@ def test_native_card_uses_linux_source_corner(
|
||||
))
|
||||
assert card.native_visible
|
||||
assert isinstance(card.nativeLabel._icon, str)
|
||||
assert Path(card.nativeLabel._icon).name == "badge_native.svg"
|
||||
assert Path(card.nativeLabel._icon).name == "badge_linux.svg"
|
||||
assert Path(card.nativeLabel._icon).is_file()
|
||||
assert not card.portproton_visible
|
||||
card.deleteLater()
|
||||
@@ -105,29 +105,14 @@ def test_library_clear_releases_full_library_tile(
|
||||
library_scene: tuple[GameLibraryManager, list[Callable[[QPixmap], None]]],
|
||||
layout_mode: str,
|
||||
) -> None:
|
||||
manager, callbacks = library_scene
|
||||
manager, _ = library_scene
|
||||
manager.layout_mode = "horizontal_top"
|
||||
manager.filtered_games = [()] * (manager.theme.horizontalTopGameLimit + 1)
|
||||
manager._sync_full_library_tile()
|
||||
tile = manager.fullLibraryTile
|
||||
assert tile is not None
|
||||
assert manager.gamesListLayout is not None
|
||||
key = ("Game", "1")
|
||||
card = manager._create_game_card((key[0], "", "", "", "", key[1], "", "", "", "", 0, 0, "steam"))
|
||||
manager.game_card_cache[key] = card
|
||||
manager.main_window.current_focused_card = card
|
||||
manager.main_window.current_hovered_card = card
|
||||
manager.pending_images[key] = ("cover.png", 1, 1, MagicMock())
|
||||
manager.gamesListLayout.addWidget(card)
|
||||
while callbacks:
|
||||
callbacks.pop(0)(QPixmap())
|
||||
|
||||
manager.clear_layout(manager.gamesListLayout)
|
||||
assert manager.gamesListLayout.count() == 0
|
||||
assert manager.main_window.current_focused_card is None
|
||||
assert manager.main_window.current_hovered_card is None
|
||||
assert not manager.game_card_cache
|
||||
assert not manager.pending_images
|
||||
QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete)
|
||||
manager.layout_mode = layout_mode
|
||||
manager._sync_full_library_tile()
|
||||
@@ -223,6 +208,44 @@ def test_horizontal_batches_keep_existing_cards_in_place(
|
||||
assert all(card.geometry() == previous for card, previous in geometries.items())
|
||||
|
||||
|
||||
def test_batches_keep_drawing_enabled_and_accept_clicks_before_completion(
|
||||
library_scene: tuple[GameLibraryManager, list[Callable[[QPixmap], None]]],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
manager, _ = library_scene
|
||||
assert manager.gamesListWidget is not None and manager.gamesListLayout is not None
|
||||
update_toggle = MagicMock(wraps=manager.gamesListWidget.setUpdatesEnabled)
|
||||
monkeypatch.setattr(manager.gamesListWidget, "setUpdatesEnabled", update_toggle)
|
||||
games = [(f"Game {index}", "", "", "", "", str(index), "", "", "", "", 0, 0, "steam") for index in range(40)]
|
||||
keys = [(game[0], game[5]) for game in games]
|
||||
manager._start_incremental_add(keys, dict(zip(keys, games, strict=True)), "")
|
||||
assert manager._incremental_add_timer is not None
|
||||
manager._incremental_add_timer.stop()
|
||||
if not manager.game_card_cache:
|
||||
manager._process_incremental_add_batch()
|
||||
manager._incremental_add_timer.stop()
|
||||
card = next(iter(manager.game_card_cache.values()))
|
||||
position = card.rect().center().toPointF()
|
||||
for event_type, buttons in ((QEvent.Type.MouseButtonPress, Qt.MouseButton.LeftButton),
|
||||
(QEvent.Type.MouseButtonRelease, Qt.MouseButton.NoButton)):
|
||||
QCoreApplication.postEvent(card, QMouseEvent(event_type, position, position,
|
||||
Qt.MouseButton.LeftButton, buttons, Qt.KeyboardModifier.NoModifier))
|
||||
QApplication.processEvents()
|
||||
manager._incremental_add_timer.stop()
|
||||
|
||||
cast(Any, manager.main_window).openGameDetailPage.assert_called_once()
|
||||
assert manager._incremental_add_queue
|
||||
while manager._incremental_add_queue:
|
||||
count_before = manager.gamesListLayout.count()
|
||||
manager._process_incremental_add_batch()
|
||||
manager._incremental_add_timer.stop()
|
||||
QApplication.processEvents()
|
||||
assert manager.gamesListLayout.count() > count_before
|
||||
assert manager.gamesListWidget.updatesEnabled()
|
||||
assert all(card.isVisible() for card in manager.game_card_cache.values())
|
||||
update_toggle.assert_not_called()
|
||||
|
||||
|
||||
def test_switch_during_loading_cancels_old_cards_and_reuses_cached_cards(
|
||||
library_scene: tuple[GameLibraryManager, list[Callable[[QPixmap], None]]],
|
||||
) -> None:
|
||||
@@ -302,8 +325,7 @@ def test_first_batch_receives_focus_without_waiting_for_remaining_cards(
|
||||
main.searchEdit.setFocus()
|
||||
QApplication.processEvents()
|
||||
manager._focus_first_card_after_update = True
|
||||
games = [(f"Game {i}", "", "", "", "", str(i), "", "", "", "", 0, 0, "steam")
|
||||
for i in range(manager._incremental_batch_size + 2)]
|
||||
games = [(f"Game {i}", "", "", "", "", str(i), "", "", "", "", 0, 0, "steam") for i in range(80)]
|
||||
keys = [(game[0], game[5]) for game in games]
|
||||
manager._start_incremental_add(keys, dict(zip(keys, games, strict=True)), "")
|
||||
assert manager._incremental_add_timer is not None
|
||||
@@ -328,6 +350,117 @@ def test_first_batch_receives_focus_without_waiting_for_remaining_cards(
|
||||
assert main.current_focused_card is second
|
||||
|
||||
|
||||
@pytest.mark.parametrize("layout_mode", ["grid", "horizontal"])
|
||||
def test_scrolling_defers_card_creation_until_scroll_stops(
|
||||
library_scene: tuple[GameLibraryManager, list[Callable[[QPixmap], None]]],
|
||||
layout_mode: str,
|
||||
) -> None:
|
||||
manager, _ = library_scene
|
||||
manager.rebuild_library_layout(layout_mode)
|
||||
QApplication.processEvents()
|
||||
games = [(f"Game {i}", "", "", "", "", str(i), "", "", "", "", 0, 0, "steam") for i in range(80)]
|
||||
keys = [(game[0], game[5]) for game in games]
|
||||
manager._start_incremental_add(keys, dict(zip(keys, games, strict=True)), "")
|
||||
assert manager._incremental_add_timer is not None
|
||||
assert manager.gamesScrollArea is not None
|
||||
scrollbar = (manager.gamesScrollArea.horizontalScrollBar() if layout_mode == "horizontal"
|
||||
else manager.gamesScrollArea.verticalScrollBar())
|
||||
while scrollbar.maximum() < 100:
|
||||
manager._incremental_add_timer.stop()
|
||||
manager._process_incremental_add_batch()
|
||||
QApplication.processEvents()
|
||||
manager._incremental_add_timer.stop()
|
||||
count_before = len(manager.game_card_cache)
|
||||
|
||||
def scroll() -> None:
|
||||
scrollbar.setValue(0 if scrollbar.value() else 50)
|
||||
|
||||
loop = QEventLoop()
|
||||
scroll_timer = QTimer()
|
||||
scroll_timer.timeout.connect(scroll)
|
||||
scroll_timer.start(20)
|
||||
manager._incremental_add_timer.start(manager._incremental_batch_budget_ms)
|
||||
scroll()
|
||||
QTimer.singleShot(manager._incremental_scroll_delay_ms * 2, loop.quit)
|
||||
loop.exec()
|
||||
scroll_timer.stop()
|
||||
assert len(manager.game_card_cache) == count_before
|
||||
assert manager._incremental_add_queue
|
||||
assert manager.gamesListWidget is not None and manager.gamesListWidget.updatesEnabled()
|
||||
|
||||
manager._incremental_add_timer.timeout.connect(loop.quit)
|
||||
QTimer.singleShot(manager._incremental_scroll_delay_ms * 2, loop.quit)
|
||||
loop.exec()
|
||||
manager._incremental_add_timer.timeout.disconnect(loop.quit)
|
||||
manager._incremental_add_timer.stop()
|
||||
assert len(manager.game_card_cache) > count_before
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def real_cover_scene(
|
||||
library_scene: tuple[GameLibraryManager, list[Callable[[QPixmap], None]]],
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
|
||||
) -> tuple[GameLibraryManager, Path]:
|
||||
manager, _ = library_scene
|
||||
main = cast(Any, manager.main_window)
|
||||
main.stackedWidget = SimpleNamespace(currentIndex=lambda: 0)
|
||||
main.getColorPalette_from_pixmap = MagicMock()
|
||||
manager.gamesLibraryWidget.activateWindow()
|
||||
QApplication.processEvents()
|
||||
cover = QPixmap(600, 900)
|
||||
cover.fill(Qt.GlobalColor.darkBlue)
|
||||
cover_path = tmp_path / "cover.jpg"
|
||||
assert cover.save(str(cover_path))
|
||||
monkeypatch.setattr("portprotonqt.game_card.load_pixmap_async", image_utils.load_pixmap_async)
|
||||
return manager, cover_path
|
||||
|
||||
|
||||
@pytest.mark.parametrize("animation_type", ["gradient", "glow"])
|
||||
def test_real_cover_loading_yields_and_focuses_first_paint(
|
||||
real_cover_scene: tuple[GameLibraryManager, Path],
|
||||
monkeypatch: pytest.MonkeyPatch, animation_type: str,
|
||||
) -> None:
|
||||
manager, cover_path = real_cover_scene
|
||||
monkeypatch.setattr(manager.theme, "GAME_CARD_ANIMATION",
|
||||
{**manager.theme.GAME_CARD_ANIMATION, "card_animation_type": animation_type})
|
||||
threads: list[bool] = []
|
||||
paints: list[bool] = []
|
||||
ticks: list[tuple[int, int]] = []
|
||||
original_paint = GameCard.paintEvent
|
||||
original_cover = GameCard.on_cover_loaded
|
||||
|
||||
def record_paint(card: GameCard, event: Any) -> None:
|
||||
if card.name == "Game 0":
|
||||
paints.append(card._focused or card._hovered)
|
||||
original_paint(card, event)
|
||||
|
||||
def record_cover(card: GameCard, pixmap: QPixmap) -> None:
|
||||
threads.append(QThread.currentThread() == card.thread())
|
||||
original_cover(card, pixmap)
|
||||
|
||||
def sample() -> None:
|
||||
ticks.append((len(manager.game_card_cache), len(threads)))
|
||||
if len(threads) == len(games) and not manager._incremental_add_queue:
|
||||
loop.quit()
|
||||
|
||||
monkeypatch.setattr(GameCard, "paintEvent", record_paint)
|
||||
monkeypatch.setattr(GameCard, "on_cover_loaded", record_cover)
|
||||
games = [(f"Game {i}", "", str(cover_path), "", "", str(i), "", "", "", "", 0, 0, "steam") for i in range(16)]
|
||||
loop = QEventLoop()
|
||||
timer = QTimer()
|
||||
timer.setInterval(5)
|
||||
timer.timeout.connect(sample)
|
||||
timer.start()
|
||||
QTimer.singleShot(LOAD_TIMEOUT_MS, loop.quit)
|
||||
manager.set_games(games)
|
||||
loop.exec()
|
||||
timer.stop()
|
||||
assert len(threads) == len(games) and all(threads), threads
|
||||
assert paints and paints[0], paints
|
||||
assert any(0 < cards < len(games) for cards, _ in ticks), ticks
|
||||
assert any(0 < covers < len(games) for _, covers in ticks), ticks
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scenario", [("grid", 0), ("grid", 1), ("vertical", 0), ("vertical", 1)])
|
||||
def test_failed_protondb_completion_preserves_library_scroll(
|
||||
library_scene: tuple[GameLibraryManager, list[Callable[[QPixmap], None]]],
|
||||
@@ -339,19 +472,18 @@ def test_failed_protondb_completion_preserves_library_scroll(
|
||||
|
||||
manager, _ = library_scene
|
||||
manager.rebuild_library_layout(scenario[0])
|
||||
manager.gamesLibraryWidget.resize(640, 400)
|
||||
main = cast(Any, manager.main_window)
|
||||
main.stackedWidget = SimpleNamespace(currentIndex=lambda: 0)
|
||||
main.getColorPalette_from_pixmap = MagicMock()
|
||||
main.game_library_manager = manager
|
||||
main.tray_manager = MagicMock()
|
||||
main._get_portproton_desktop_files = lambda: set()
|
||||
monkeypatch.setattr(portproton_api, "get_user_conf_setting", lambda _key: None)
|
||||
monkeypatch.setattr(api, "load_protondb_status", lambda _appid: None)
|
||||
monkeypatch.setattr(api, "CacheManager", lambda: SimpleNamespace(cache_dir=tmp_path))
|
||||
download = MagicMock(return_value=None)
|
||||
monkeypatch.setattr(api.downloader, "download", download)
|
||||
games = [(f"Game {i}", "", "", "", "", str(i), "", "", "", "", 0, 0, "steam") for i in range(12)]
|
||||
responses: list[Callable[[str | None], None]] = []
|
||||
monkeypatch.setattr(api.downloader, "download_async",
|
||||
lambda *_args, **kwargs: responses.append(kwargs["callback"]))
|
||||
games = [(f"Game {i}", "", "", "", "", str(i), "", "", "", "", 0, 0, "steam") for i in range(40)]
|
||||
manager.set_games(games)
|
||||
QApplication.processEvents()
|
||||
assert manager._incremental_add_timer is not None
|
||||
@@ -367,12 +499,10 @@ def test_failed_protondb_completion_preserves_library_scroll(
|
||||
assert previous_value > 0
|
||||
main.stackedWidget.currentIndex = lambda: scenario[1]
|
||||
|
||||
assert api._METADATA_LOOKUPS.waitForDone(5000)
|
||||
download.assert_called_once()
|
||||
responses[0](None)
|
||||
QApplication.processEvents()
|
||||
QApplication.processEvents()
|
||||
|
||||
main.tray_manager.refresh_tray_menu.assert_called_once_with()
|
||||
assert scrollbar.value() == previous_value
|
||||
assert not manager._focus_first_card_after_update
|
||||
|
||||
|
||||
@@ -207,14 +207,6 @@ def test_horizontal_cards_fit_viewport_height(
|
||||
assert card.nameLabel.height() >= card.nameLabel.sizeHint().height()
|
||||
assert card.base_card_width <= manager.card_width
|
||||
assert card.base_card_width == manager.card_width
|
||||
cover = QPixmap(180, 300)
|
||||
cover.fill(QColor("red"))
|
||||
card.on_cover_loaded(cover)
|
||||
for scale in (1.0, 1.045, 1.25, 1.0):
|
||||
card.setScale(scale)
|
||||
app.processEvents()
|
||||
assert card.coverLabel.pixmap().size() == card.coverLabel.size()
|
||||
assert card.coverLabel.width() == int(card.base_card_width * scale)
|
||||
card.stop_background_activity()
|
||||
scroll.close()
|
||||
app.processEvents()
|
||||
@@ -257,18 +249,3 @@ def test_large_resize_keeps_cards_separate_between_batches(
|
||||
assert all(not geometry.intersects(other) for other in geometries[index + 1:])
|
||||
finally:
|
||||
scroll.close()
|
||||
|
||||
|
||||
def test_static_png_does_not_leave_cover_mask(tmp_path: Path) -> None:
|
||||
from PySide6.QtWidgets import QLabel
|
||||
from portprotonqt.image_utils import set_animated_cover
|
||||
|
||||
app = QApplication.instance() or QApplication([])
|
||||
path = tmp_path / "poster.png"
|
||||
pixmap = QPixmap(40, 60)
|
||||
pixmap.fill(QColor("red"))
|
||||
assert pixmap.save(str(path))
|
||||
label = QLabel()
|
||||
assert not set_animated_cover(label, str(path), 40, 60, 5)
|
||||
assert label.mask().isEmpty()
|
||||
app.processEvents()
|
||||
+5
-176
@@ -13,7 +13,7 @@ from unittest.mock import MagicMock
|
||||
import psutil
|
||||
from pytest import MonkeyPatch, fixture, mark, raises
|
||||
from PySide6.QtCore import QEvent, QEventLoop, QObject, QPoint, QPointF, Qt, QTimer
|
||||
from PySide6.QtGui import QAction, QCloseEvent, QMouseEvent, QPixmap, QWheelEvent
|
||||
from PySide6.QtGui import QAction, QMouseEvent, QPixmap, QWheelEvent
|
||||
from PySide6.QtTest import QTest
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
@@ -42,7 +42,7 @@ from portprotonqt.game_library_manager import FullLibraryTile, GameLibraryManage
|
||||
from portprotonqt.input_manager import InputManager
|
||||
from portprotonqt.main_window import MainWindow
|
||||
from portprotonqt.search_utils import SearchOptimizer, search_index
|
||||
from portprotonqt.tray_manager import TrayManager, create_wine_tools_menu, launch_session_wine_tool
|
||||
from portprotonqt.tray_manager import TrayManager
|
||||
from portprotonqt.themes.standart.styles.constants import GAME_CARD_ANIMATION
|
||||
from portprotonqt.portproton_api import remove_empty_custom_data_dirs
|
||||
import portprotonqt.tabs.autoinstall_tab as autoinstall_tab_module
|
||||
@@ -370,149 +370,22 @@ def test_shutdown_waits_for_compatibility_analysis() -> None:
|
||||
assert window.compatibility_workers == []
|
||||
|
||||
|
||||
def test_tray_exit_shuts_down_after_minimizing(monkeypatch: MonkeyPatch) -> None:
|
||||
from portprotonqt import main_window as window_module
|
||||
|
||||
monkeypatch.setattr(window_module.display_config, "get_minimize_to_tray", lambda: True)
|
||||
monkeypatch.setattr(window_module.display_config, "get_fullscreen", lambda: True)
|
||||
watcher = MagicMock()
|
||||
window = SimpleNamespace(
|
||||
hide=MagicMock(), system_theme_watcher=watcher,
|
||||
theme=SimpleNamespace(), game_library_manager=SimpleNamespace(sizeSlider=object()),
|
||||
game_processes={}, install_process=None, disc_image_manager=MagicMock(),
|
||||
_stopBackgroundWorkers=MagicMock(),
|
||||
)
|
||||
monkeypatch.setattr(window_module.ui_config, "get_library_layout_mode", lambda _: "list")
|
||||
manager = TrayManager.__new__(TrayManager)
|
||||
manager.main_window = cast(Any, window)
|
||||
tray_icon = MagicMock()
|
||||
manager.tray_icon = tray_icon
|
||||
window.tray_manager = manager
|
||||
|
||||
def close() -> bool:
|
||||
event = QCloseEvent()
|
||||
MainWindow.closeEvent(cast(Any, window), event)
|
||||
return event.isAccepted()
|
||||
|
||||
def quit_application() -> None:
|
||||
watcher.wait.assert_called_once_with()
|
||||
window._stopBackgroundWorkers.assert_called_once_with()
|
||||
assert close() # aboutToQuit closes the window again.
|
||||
|
||||
window.close = close
|
||||
quit_mock = MagicMock(side_effect=quit_application)
|
||||
monkeypatch.setattr(QApplication, "quit", quit_mock)
|
||||
|
||||
assert not close()
|
||||
window.hide.assert_called_once_with()
|
||||
watcher.wait.assert_not_called()
|
||||
manager.force_exit()
|
||||
watcher.requestInterruption.assert_called_once_with()
|
||||
watcher.wait.assert_called_once_with()
|
||||
window._stopBackgroundWorkers.assert_called_once_with()
|
||||
tray_icon.hide.assert_called_once_with()
|
||||
tray_icon.deleteLater.assert_called_once_with()
|
||||
quit_mock.assert_called_once_with()
|
||||
|
||||
|
||||
def test_tray_exports_complete_menu_before_first_open(monkeypatch: MonkeyPatch) -> None:
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
from portprotonqt import tray_manager as tray_module
|
||||
|
||||
icon = MagicMock()
|
||||
theme = MagicMock()
|
||||
theme.get_icon.return_value = None
|
||||
monkeypatch.setattr(tray_module, "QSystemTrayIcon", lambda _parent: icon)
|
||||
monkeypatch.setattr(tray_module, "ThemeManager", lambda: theme)
|
||||
monkeypatch.setattr(tray_module.ui_config, "get_theme", lambda: "standart")
|
||||
monkeypatch.setattr(tray_module.display_config, "get_tray_menu_mode", lambda: "detailed")
|
||||
window = cast(Any, QWidget())
|
||||
window.games = []
|
||||
window.start_sh = ["portproton"]
|
||||
|
||||
def check_export(menu: QMenu) -> None:
|
||||
actions = [action for action in menu.actions() if not action.isSeparator()]
|
||||
assert [action.text() for action in actions] == [
|
||||
tray_module._("Pause Game"), tray_module._("Stop Game"), "Wine",
|
||||
tray_module._("No recent games"), tray_module._("Exit"),
|
||||
]
|
||||
assert actions[2].menu() is not None
|
||||
assert not actions[2].isEnabled()
|
||||
|
||||
icon.setContextMenu.side_effect = check_export
|
||||
manager = TrayManager(window)
|
||||
icon.setContextMenu.assert_called_once_with(manager.tray_menu)
|
||||
|
||||
|
||||
def test_minimal_tray_contains_game_actions() -> None:
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
manager = TrayManager.__new__(TrayManager)
|
||||
manager.tray_menu = QMenu()
|
||||
owner = QWidget()
|
||||
manager.pause_game_action = QAction("Pause Game", owner)
|
||||
manager.stop_game_action = QAction("Stop Game", owner)
|
||||
manager.wine_tools_menu = create_wine_tools_menu(manager.tray_menu, ["portproton"])
|
||||
manager.pause_game_action = QAction("Pause Game", manager.tray_menu)
|
||||
manager.stop_game_action = QAction("Stop Game", manager.tray_menu)
|
||||
manager.minimal_mode = True
|
||||
manager.update_game_actions = MagicMock()
|
||||
|
||||
manager.refresh_tray_menu()
|
||||
manager.refresh_tray_menu()
|
||||
|
||||
assert manager.tray_menu.actions() == [
|
||||
manager.pause_game_action,
|
||||
manager.stop_game_action,
|
||||
manager.wine_tools_menu.menuAction(),
|
||||
]
|
||||
assert manager.update_game_actions.call_count == 2
|
||||
|
||||
|
||||
@mark.parametrize("tool_index,tool", list(enumerate(
|
||||
("winefile", "taskmgr", "winecfg", "regedit", "cmd", "uninstaller")
|
||||
)))
|
||||
def test_wine_tools_menu_launches_session_tool(
|
||||
monkeypatch: MonkeyPatch, tool_index: int, tool: str,
|
||||
) -> None:
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
parent = QMenu()
|
||||
start = MagicMock(return_value=(True, 123))
|
||||
monkeypatch.setattr("portprotonqt.tray_manager.QProcess.startDetached", start)
|
||||
menu = create_wine_tools_menu(parent, ["bash", "/path with spaces/start.sh"])
|
||||
|
||||
assert len(menu.actions()) == 6
|
||||
menu.actions()[tool_index].trigger()
|
||||
|
||||
start.assert_called_once_with(
|
||||
"bash", ["/path with spaces/start.sh", "cli", "--wine-session-tool", tool]
|
||||
)
|
||||
|
||||
|
||||
def test_wine_tool_start_failure_is_reported(monkeypatch: MonkeyPatch) -> None:
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
warning = MagicMock()
|
||||
monkeypatch.setattr("portprotonqt.tray_manager.QMessageBox.warning", warning)
|
||||
monkeypatch.setattr(
|
||||
"portprotonqt.tray_manager.QProcess.startDetached", lambda *args: (False, 0)
|
||||
)
|
||||
|
||||
launch_session_wine_tool(["portproton"], "winefile")
|
||||
|
||||
warning.assert_called_once()
|
||||
|
||||
|
||||
@mark.parametrize("running", [False, True])
|
||||
def test_wine_tools_menu_requires_running_game(running: bool) -> None:
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
manager = TrayManager.__new__(TrayManager)
|
||||
manager.main_window = SimpleNamespace(game_processes=[], target_exe="game.exe" if running else None)
|
||||
manager.stop_game_action = QAction()
|
||||
manager.pause_game_action = QAction()
|
||||
manager.wine_tools_menu = QMenu()
|
||||
manager._game_process_tree = MagicMock(return_value=[])
|
||||
|
||||
manager.update_game_actions()
|
||||
|
||||
assert manager.wine_tools_menu.isEnabled() is running
|
||||
|
||||
manager.update_game_actions.assert_called_once_with()
|
||||
|
||||
def test_tray_pauses_game_process_tree(monkeypatch: MonkeyPatch) -> None:
|
||||
child = MagicMock(pid=12)
|
||||
@@ -3706,47 +3579,3 @@ def test_system_keyboard_control_hint_opens_keyboard() -> None:
|
||||
MainWindowControlHintsMixin._triggerControlHintAction(cast(Any, window), "system_keyboard")
|
||||
|
||||
window.system_keyboard.toggle.assert_called_once_with()
|
||||
|
||||
|
||||
@mark.parametrize("tool", ["winecfg", "regedit", "winefile", "cmd", "uninstaller", "taskmgr"])
|
||||
@mark.parametrize("running", [False, True])
|
||||
def test_wine_settings_tools_use_unified_command(
|
||||
monkeypatch: MonkeyPatch, tool: str, running: bool,
|
||||
) -> None:
|
||||
process = MagicMock()
|
||||
monkeypatch.setattr("portprotonqt.tabs.wine_tab.QProcess", MagicMock(return_value=process))
|
||||
window = MagicMock()
|
||||
window.game_processes = [MagicMock()] if running else []
|
||||
window.target_exe = "game.exe" if running else None
|
||||
window.start_sh = ["bash", "/path with spaces/start.sh"]
|
||||
window.wineCombo.currentText.return_value = "WINE_LG"
|
||||
window.prefixCombo.currentText.return_value = "my prefix"
|
||||
|
||||
WineMixin.launch_generic_tool(window, tool)
|
||||
|
||||
process.start.assert_called_once_with(
|
||||
"bash", ["/path with spaces/start.sh", "cli", "--wine-session-tool", tool, "WINE_LG", "MY_PREFIX"],
|
||||
)
|
||||
window._start_wine_process_monitor.assert_called_once_with(tool)
|
||||
|
||||
|
||||
|
||||
def test_silent_tray_includes_wine_tools_menu(monkeypatch: MonkeyPatch) -> None:
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
manager = TrayManager.__new__(TrayManager)
|
||||
manager.tray_menu = QMenu()
|
||||
owner = QWidget()
|
||||
manager.pause_game_action = QAction("Pause Game", owner)
|
||||
manager.stop_game_action = QAction("Stop Game", owner)
|
||||
manager.wine_tools_menu = create_wine_tools_menu(manager.tray_menu, ["portproton"])
|
||||
manager.update_game_actions = MagicMock()
|
||||
start = MagicMock(return_value=(True, 123))
|
||||
monkeypatch.setattr("portprotonqt.tray_manager.QProcess.startDetached", start)
|
||||
|
||||
manager.set_minimal_mode()
|
||||
|
||||
tools = manager.tray_menu.actions()[2].menu()
|
||||
assert isinstance(tools, QMenu)
|
||||
assert len(tools.actions()) == 6
|
||||
tools.actions()[1].trigger()
|
||||
start.assert_called_once_with("portproton", ["cli", "--wine-session-tool", "taskmgr"])
|
||||
+34
-70
@@ -12,7 +12,7 @@ import subprocess
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import QEventLoop, QMimeData, QRect, QStandardPaths, QThread, QTimer, QUrl
|
||||
from PySide6.QtCore import QEventLoop, QStandardPaths, QThread, QTimer, Qt
|
||||
from PySide6.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton
|
||||
from PySide6.QtGui import QIcon
|
||||
|
||||
@@ -169,71 +169,6 @@ def test_native_launch_preserves_desktop_file_and_bypasses_wine(
|
||||
window._set_running_button_stop.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["Game.AppImage", "Game.bin", "Game with spaces", "Game.exe"])
|
||||
def test_quick_launch_file_picker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, name: str) -> None:
|
||||
path = tmp_path / name
|
||||
path.touch(mode=0o755)
|
||||
text = tmp_path / "README"
|
||||
text.touch(mode=0o644)
|
||||
picker = MagicMock()
|
||||
monkeypatch.setattr("portprotonqt.tabs.library_tab.FileExplorer", picker)
|
||||
window = cast(Any, SimpleNamespace(
|
||||
theme=None, geometry=lambda: QRect(), game_processes=[], input_manager=MagicMock(),
|
||||
handle_launch_exe=MagicMock(), _set_running_button_stop=MagicMock(), checkTargetExe=MagicMock(),
|
||||
))
|
||||
window._quick_launch_selected = MainWindow._quick_launch_selected.__get__(window)
|
||||
window._launch_native_game = MainWindow._launch_native_game.__get__(window)
|
||||
popen = MagicMock()
|
||||
monkeypatch.setattr("portprotonqt.main_window.subprocess.Popen", popen)
|
||||
monkeypatch.setattr("portprotonqt.main_window.QTimer", MagicMock())
|
||||
monkeypatch.setattr("portprotonqt.main_window.SoundManager", MagicMock())
|
||||
|
||||
MainWindow.quickLaunch(window)
|
||||
file_filter = picker.call_args.kwargs["file_filter"]
|
||||
assert file_filter(str(path))
|
||||
assert not file_filter(str(text))
|
||||
shortcut = tmp_path / "Launcher.Desktop"
|
||||
shortcut.touch(mode=0o755)
|
||||
assert not file_filter(str(shortcut))
|
||||
callback, = picker.return_value.file_signal.file_selected.connect.call_args.args
|
||||
warning = MagicMock()
|
||||
monkeypatch.setattr("portprotonqt.main_window.QMessageBox.warning", warning)
|
||||
callback(str(shortcut))
|
||||
warning.assert_called_once()
|
||||
popen.assert_not_called()
|
||||
shortcut.unlink()
|
||||
|
||||
callback(str(path))
|
||||
|
||||
if path.suffix == ".exe":
|
||||
window.handle_launch_exe.assert_called_once_with(str(path))
|
||||
popen.assert_not_called()
|
||||
else:
|
||||
window.handle_launch_exe.assert_not_called()
|
||||
popen.assert_called_once_with([str(path)], cwd=str(tmp_path), start_new_session=True, text=True)
|
||||
assert window.native_game_running
|
||||
assert not list(tmp_path.rglob("*.desktop"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["Game.AppImage", "Game.bin", "Game"])
|
||||
def test_drop_native_executable_opens_add_dialog(tmp_path: Path, name: str) -> None:
|
||||
path = tmp_path / name
|
||||
path.touch(mode=0o755)
|
||||
mime = QMimeData()
|
||||
mime.setUrls([QUrl.fromLocalFile(str(path))])
|
||||
event = cast(Any, SimpleNamespace(
|
||||
mimeData=lambda: mime, acceptProposedAction=MagicMock(), ignore=MagicMock(),
|
||||
))
|
||||
window = cast(Any, SimpleNamespace(openAddGameDialog=MagicMock()))
|
||||
|
||||
MainWindow.dragEnterEvent(window, event)
|
||||
MainWindow.dropEvent(window, event)
|
||||
|
||||
assert event.acceptProposedAction.call_count == 2
|
||||
event.ignore.assert_not_called()
|
||||
window.openAddGameDialog.assert_called_once_with(str(path))
|
||||
|
||||
|
||||
def test_native_context_launch_does_not_require_portproton() -> None:
|
||||
parent = SimpleNamespace(toggleGame=MagicMock())
|
||||
manager = cast(Any, SimpleNamespace(parent=parent))
|
||||
@@ -270,9 +205,8 @@ def test_native_scan_completes_once_on_owner_thread(
|
||||
|
||||
@pytest.mark.parametrize("filename", ['start', 'game with spaces', 'game%name$"\\test'])
|
||||
def test_manual_native_shortcut_round_trips_linux_paths(
|
||||
tmp_path: Path, filename: str, monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path, filename: str,
|
||||
) -> None:
|
||||
monkeypatch.setattr("portprotonqt.steam_api.shortcuts._generate_icon", lambda *_args: "")
|
||||
executable = tmp_path / filename
|
||||
executable.write_text("#!/bin/sh\nexit 0\n")
|
||||
executable.chmod(0o755)
|
||||
@@ -431,6 +365,38 @@ def test_native_stop_uses_own_process_group_without_portproton() -> None:
|
||||
stop.assert_called_once()
|
||||
|
||||
|
||||
def test_native_settings_show_linux_tabs_and_ppdb_without_wine(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
from portprotonqt.dialogs.settings_dialog import ExeSettingsDialog
|
||||
from portprotonqt.dialogs.settings_gamescope import GamescopeSettingsMixin
|
||||
from portprotonqt.theme_manager import load_theme
|
||||
_app = QApplication.instance() or QApplication([])
|
||||
path = tmp_path / "native.desktop"
|
||||
path.write_text(f'[Desktop Entry]\nType=Application\nName=Native\nExec="/game/start"\nPath={tmp_path}\n')
|
||||
monkeypatch.setattr("portprotonqt.dialogs.settings_dialog.get_portproton_location", lambda: None)
|
||||
monkeypatch.setattr("portprotonqt.dialogs.settings_dialog.get_portproton_start_command", lambda: None)
|
||||
monkeypatch.setattr("portprotonqt.native_games.get_native_tool_paths", lambda: {})
|
||||
monkeypatch.setattr(GamescopeSettingsMixin, "_detect_gamescope_supported_options", lambda _self: None)
|
||||
monkeypatch.setattr(ExeSettingsDialog, "init_virtual_keyboard", lambda self: setattr(self, "keyboard", QWidget(self)))
|
||||
original_which = shutil.which
|
||||
monkeypatch.setattr(shutil, "which", lambda command: "/fake/gamescope" if command == "gamescope" else original_which(command))
|
||||
dialog = ExeSettingsDialog(theme=load_theme("standart"), exe_path=str(path), game_source="native")
|
||||
keys = {item.data(Qt.ItemDataRole.UserRole) for row in range(dialog.settings_table.rowCount())
|
||||
if (item := dialog.settings_table.item(row, 0)) is not None}
|
||||
assert {"PW_USE_GAMEMODE", "PW_USE_RUNTIME"} <= keys
|
||||
assert not ({"PW_WINE_USE", "PW_PREFIX_NAME", "PW_USE_ESYNC"} & keys)
|
||||
assert not ({"PW_WINE_USE", "WINEDLLOVERRIDES"} & dialog.advanced_settings_by_key.keys())
|
||||
assert not ({"Exec", "Path"} & dialog.advanced_settings_by_key.keys())
|
||||
tabs = {dialog.tab_widget.tabText(index) for index in range(dialog.tab_widget.count())}
|
||||
assert {"MangoHud", "vkBasalt", "Gamescope"} <= tabs
|
||||
assert not dialog.open_ppdb_button.isHidden()
|
||||
assert not dialog.clear_ppdb_button.isHidden()
|
||||
assert dialog.current_settings["Exec"] == '"/game/start"'
|
||||
dialog.close()
|
||||
dialog.deleteLater()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["confirm", "cancel", "missing"])
|
||||
def test_native_clear_ppdb_uses_user_data_path(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, action: str,
|
||||
@@ -551,7 +517,6 @@ def test_manual_native_add_creates_shortcuts_and_respects_late_source_switch(
|
||||
) -> None:
|
||||
import portprotonqt.tabs.library_tab as tab
|
||||
from PySide6.QtWidgets import QDialog
|
||||
monkeypatch.setattr("portprotonqt.steam_api.shortcuts._generate_icon", lambda *_args: "")
|
||||
callbacks, selected = [], ["native"]
|
||||
executable = tmp_path / "start"
|
||||
executable.write_text("#!/bin/sh\nexit 0\n")
|
||||
@@ -1065,7 +1030,6 @@ def test_native_portdata_shortcut_is_only_loaded_as_native(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
original_rglob = Path.rglob
|
||||
monkeypatch.setattr("portprotonqt.steam_api.shortcuts._generate_icon", lambda *_args: "")
|
||||
monkeypatch.setattr(Path, "rglob", lambda path, pattern:
|
||||
original_rglob(path, pattern) if path.is_relative_to(tmp_path) else iter(()))
|
||||
executable = tmp_path / "start"
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""Tests for config/portproton.py — exec_line parsing, icon sanitization, launcher tail extraction."""
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from pytest import MonkeyPatch
|
||||
from pytest import MonkeyPatch, mark
|
||||
|
||||
from portprotonqt.config.portproton import (
|
||||
extract_exec_target_path,
|
||||
@@ -28,11 +29,6 @@ def test_scripts_path_uses_xdg_data_dirs(
|
||||
monkeypatch.setenv("XDG_DATA_DIRS", str(data_dir))
|
||||
monkeypatch.delenv("APPDIR", raising=False)
|
||||
monkeypatch.delenv("SHARUN_DIR", raising=False)
|
||||
monkeypatch.delenv("APPIMAGE", raising=False)
|
||||
is_file = Path.is_file
|
||||
monkeypatch.setattr(
|
||||
Path, "is_file", lambda path: path.is_relative_to(tmp_path) and is_file(path)
|
||||
)
|
||||
|
||||
assert get_portproton_scripts_path() == str(scripts_dir)
|
||||
|
||||
@@ -192,3 +188,131 @@ class TestThemedLaunchIconNames:
|
||||
|
||||
def test_reg_has_icon(self):
|
||||
assert "reg" in THEMED_LAUNCH_ICON_NAMES[".reg"]
|
||||
|
||||
|
||||
def test_run_after_batch_is_created_next_to_exe() -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text(
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
assert 'run_after_dir="$(dirname "${PW_EXE_FILE}")"' in helper
|
||||
assert 'pw_exe_file_win="$("${WINELOADER}" winepath -w "${PW_EXE_FILE}"' in helper
|
||||
assert "chcp 65001 >nul" in helper
|
||||
assert 'start "" "%PW_RUN_AFTER_MAIN_PATH%" ${LAUNCH_PARAMETERS}' in helper
|
||||
assert 'start "" "%PW_RUN_AFTER_SECOND_PATH%"' in helper
|
||||
assert 'PW_RUN_AFTER_MAIN_PATH="${pw_exe_file_win}"' in helper
|
||||
assert 'PW_RUN_AFTER_SECOND_PATH="${run_after_first_win}"' in helper
|
||||
assert 'LAUNCH_PARAMETERS="" proxy_launch_parameters="" \\' in helper
|
||||
assert 'pw_run "${PW_VD_TMP[@]}" "${run_after_bat}"' in helper
|
||||
|
||||
|
||||
def test_user_conf_get_without_name_lists_active_values(tmp_path: Path) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definition = helper.split("manage_user_conf_value () {", 1)[1].split(
|
||||
"use_exiftool () {", 1
|
||||
)[0]
|
||||
user_conf = tmp_path / "user.conf"
|
||||
user_conf.write_text(
|
||||
'# comment\nexport PW_USE_ESYNC="1"\n# export PW_USE_FSYNC="1"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
script = "manage_user_conf_value () {" + definition + '\nmanage_user_conf_value get\n'
|
||||
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script], capture_output=True, text=True,
|
||||
env={"PATH": os.defpath, "USER_CONF": str(user_conf)}, check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert result.stdout == 'PW_USE_ESYNC="1"\n'
|
||||
|
||||
|
||||
@mark.parametrize("runtime,logging", [("0", "0"), ("0", "1"), ("1", "0"), ("1", "1")])
|
||||
def test_wine_exit_code_survives_log_output_and_wineserver_wait(
|
||||
tmp_path: Path, runtime: str, logging: str,
|
||||
) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definition = helper.split("pw_run () {", 1)[1].split("export -f pw_run", 1)[0]
|
||||
script = "pw_run () {" + definition + '''
|
||||
check_variables () { :; }
|
||||
pw_launch_wrapper () { return 37; }
|
||||
wait_wineserver () { return 0; }
|
||||
print_info () { :; }
|
||||
PATH_TO_GAME="$1"
|
||||
PW_TMPFS_PATH="$1"
|
||||
PW_LOG_FILE="$1/wine.log"
|
||||
PW_EXE_FILE="$1/game.exe"
|
||||
PW_USE_RUNTIME="$2"
|
||||
PW_LOG="$3"
|
||||
pw_run "$PW_EXE_FILE"
|
||||
exit $?
|
||||
'''
|
||||
(tmp_path / "game.exe").touch()
|
||||
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script, "bash", str(tmp_path), runtime, logging],
|
||||
capture_output=True, text=True, env={"PATH": os.defpath}, check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 37, result.stderr
|
||||
assert result.stdout.count("PORTPROTONQT_GAME_EXIT_CODE=37") == 1
|
||||
|
||||
|
||||
def test_vk_gpu_info_uses_build_aux_binary() -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text(
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
assert '/../../../bin/vk_gpu_info"' in helper
|
||||
assert "dev-scripts/vk_gpu_info" not in helper
|
||||
|
||||
|
||||
def test_steam_uses_common_portwine_launch() -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text(
|
||||
encoding="utf-8",
|
||||
)
|
||||
start = Path("build-aux/share/portproton/scripts/start.sh").read_text(
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
assert "steamplay_launch ()" not in helper
|
||||
assert 'export PW_STEAMPLAY="1"' in start
|
||||
assert '"${PROTON_RUNNER}" waitforexitandrun "${PW_EXE_FILE}" "$@"' in helper
|
||||
|
||||
|
||||
def test_steam_skips_database_initialization() -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text(
|
||||
encoding="utf-8",
|
||||
)
|
||||
start = Path("build-aux/share/portproton/scripts/start.sh").read_text(
|
||||
encoding="utf-8",
|
||||
)
|
||||
db_init = helper.index("pw_init_db ()")
|
||||
steam_db_return = helper.index("return 0", db_init)
|
||||
normal_db = helper.index('[[ -n "${PW_DEFAULT_WINE_USE:-}" ]]', steam_db_return)
|
||||
portproton_start = helper.index("start_portproton ()")
|
||||
steam_db = helper.index(
|
||||
'export PORTWINE_DB_FILE="${PW_EXE_FILE}.ppdb"',
|
||||
portproton_start,
|
||||
)
|
||||
steam_block_end = helper.index("\n fi\n\n pw_check_and_download_plugins", steam_db)
|
||||
steam_block = helper[steam_db:steam_block_end]
|
||||
prefix_guard = helper.index('if [[ "${PW_STEAMPLAY:-}" != "1" ]] ; then')
|
||||
normal_prefix = helper.index(
|
||||
'data/prefixes/${PW_PREFIX_NAME}"/drive_c/windows',
|
||||
prefix_guard,
|
||||
)
|
||||
api_guard = helper.index('if [[ "${PW_STEAMPLAY:-}" != "1" ]] ; then', normal_prefix)
|
||||
api_symlink = helper.index('print_info "Try create symlink DXVK files..."', api_guard)
|
||||
winetricks_guard = helper.index('if [[ "${PW_STEAMPLAY:-}" != "1" ]] ; then', api_symlink)
|
||||
winetricks_update = helper.index("update_winetricks", winetricks_guard)
|
||||
|
||||
assert steam_db_return < normal_db
|
||||
assert portproton_start < steam_db
|
||||
assert "unset PW_PREFIX_NAME" in steam_block
|
||||
assert 'export WINEPREFIX="${STEAM_COMPAT_DATA_PATH}/pfx"' in steam_block
|
||||
assert "PW_PREFIX_NAME=" not in steam_block
|
||||
assert prefix_guard < normal_prefix
|
||||
assert api_guard < api_symlink
|
||||
assert winetricks_guard < winetricks_update
|
||||
assert "pw_init_db" in start
|
||||
@@ -159,7 +159,7 @@ def test_game_launch_marker_is_emitted_for_wine_and_proton() -> None:
|
||||
)
|
||||
|
||||
marker = "printf '%s\\n' 'PORTPROTONQT_GAME_LAUNCH_STARTED'"
|
||||
assert helper.count(marker) == 2
|
||||
assert helper.count(marker) == 1
|
||||
|
||||
|
||||
def test_user_conf_get_without_name_lists_active_values(tmp_path: Path) -> None:
|
||||
@@ -456,141 +456,3 @@ def test_run_after_command_placeholder_preserves_arguments_and_status(
|
||||
)
|
||||
assert result.returncode == exit_code, result.stderr
|
||||
assert result.stdout == "yes\nаргумент с пробелами\n$(false)\n\n"
|
||||
|
||||
|
||||
def test_wine_session_missing_returns_distinct_status(tmp_path: Path) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definition = helper.split("pw_session_tool () {", 1)[1].split("pw_launch_wrapper () {", 1)[0]
|
||||
script = "pw_session_tool () {" + definition + '''
|
||||
print_error () { echo "$@" >&2; }
|
||||
sleep () { return 0; }
|
||||
pw_session_tool taskmgr 1
|
||||
'''
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script], cwd=tmp_path, capture_output=True, text=True, check=False,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)},
|
||||
)
|
||||
|
||||
assert result.returncode == 2
|
||||
|
||||
|
||||
@mark.parametrize("tool", ["winecfg", "regedit", "winefile", "cmd", "uninstaller", "taskmgr"])
|
||||
def test_wine_session_tool_standalone_uses_selected_wine_and_prefix(tmp_path: Path, tool: str) -> None:
|
||||
start = Path("build-aux/share/portproton/scripts/start.sh").read_text()
|
||||
block = start.split(" --wine-session-tool)\n", 1)[1].split(" --winetricks-list-all)", 1)[0]
|
||||
script = '''
|
||||
get_wine_and_pfx () { printf '%s\\n' "$@"; }
|
||||
start_portproton () { mkdir -p "$PORT_DATA_PATH/data/prefixes/$PW_PREFIX_NAME/drive_c"; echo start; }
|
||||
pw_run () { printf '%s\\n' "$@"; }
|
||||
stop_portproton () { echo stop; }
|
||||
''' + 'case "$1" in --wine-session-tool)\n' + block + '\nesac\n'
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script, "bash", "--wine-session-tool", tool, "WINE_LG", "MY_PREFIX"],
|
||||
cwd=tmp_path, capture_output=True, text=True, check=False,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path), "PW_PREFIX_NAME": "MY_PREFIX"},
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert result.stdout.splitlines() == ["WINE_LG", "MY_PREFIX", "start", tool, "stop"]
|
||||
|
||||
|
||||
@mark.parametrize("tool", ["winefile", "taskmgr", "winecfg", "regedit", "cmd", "uninstaller"])
|
||||
@mark.parametrize("tool_exit_code", [0, 2])
|
||||
def test_wine_session_tools_reuse_prefix_without_game_options(
|
||||
tmp_path: Path, tool: str, tool_exit_code: int,
|
||||
) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definitions = helper.split("pw_save_session_env () {", 1)[1].split("pw_launch_wrapper () {", 1)[0]
|
||||
script = "pw_save_session_env () {" + definitions + '''
|
||||
print_error () { echo "$@" >&2; }
|
||||
pw_run () {
|
||||
printf '%s\\n' "$1" "$WINEPREFIX" "${PW_USE_TERMINAL:-0}" "${LAUNCH_PARAMETERS:-}" \\
|
||||
"${PW_RUN_AFTER_EXE:-}" "${PW_RUN_GAMESCOPE:-}" "$PW_TMPFS_PATH"
|
||||
return "$TOOL_EXIT_CODE"
|
||||
}
|
||||
PW_TERM="test-terminal"
|
||||
export PW_START_PID="$$" WINEPREFIX="$PORT_DATA_PATH/prefix with spaces"
|
||||
export LAUNCH_PARAMETERS="--game-only" PW_RUN_AFTER_EXE=trainer.exe PW_RUN_GAMESCOPE=gamescope
|
||||
pw_save_session_env || exit 2
|
||||
pw_session_tool "$1"
|
||||
'''
|
||||
(tmp_path / "prefix with spaces/drive_c").mkdir(parents=True)
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script, "bash", tool], capture_output=True, text=True,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path),
|
||||
"TOOL_EXIT_CODE": str(tool_exit_code)}, check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == int(tool_exit_code != 0), result.stderr
|
||||
lines = result.stdout.splitlines()
|
||||
assert lines[:6] == [tool, str(tmp_path / "prefix with spaces"), "1" if tool == "cmd" else "0", "", "", ""]
|
||||
assert Path(lines[6]).is_dir()
|
||||
assert Path(lines[6]).stat().st_mode & 0o777 == 0o700
|
||||
session = next((tmp_path / "data/tmp").glob("wine-session-*/session.env"))
|
||||
assert session.stat().st_mode & 0o777 == 0o600
|
||||
assert 'declare -x PW_TERM="test-terminal"' in session.read_text()
|
||||
|
||||
|
||||
@mark.parametrize("unsafe_directory", [False, True])
|
||||
def test_wine_session_save_does_not_follow_symlinks(tmp_path: Path, unsafe_directory: bool) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definition = helper.split("pw_save_session_env () {", 1)[1].split("pw_remove_session_env () {", 1)[0]
|
||||
session_dir = tmp_path / "data/tmp" / f"wine-session-{os.getuid()}"
|
||||
session_dir.parent.mkdir(parents=True)
|
||||
victim = tmp_path / "victim"
|
||||
victim.write_text("keep this")
|
||||
if unsafe_directory:
|
||||
target = tmp_path / "other-directory"
|
||||
target.mkdir(mode=0o700)
|
||||
session_dir.symlink_to(target, target_is_directory=True)
|
||||
else:
|
||||
session_dir.mkdir(mode=0o700)
|
||||
(session_dir / "session.env").symlink_to(victim)
|
||||
result = subprocess.run(
|
||||
["bash", "-c", "pw_save_session_env () {" + definition + "\npw_save_session_env"],
|
||||
capture_output=True, text=True,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)}, check=False,
|
||||
)
|
||||
|
||||
assert victim.read_text() == "keep this"
|
||||
assert result.returncode == (1 if unsafe_directory else 0), result.stderr
|
||||
if not unsafe_directory:
|
||||
assert not (session_dir / "session.env").is_symlink()
|
||||
|
||||
|
||||
def test_wine_session_tool_rejects_unknown_tool_before_reading_environment(tmp_path: Path) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definition = helper.split("pw_session_tool () {", 1)[1].split("pw_launch_wrapper () {", 1)[0]
|
||||
script = "pw_session_tool () {" + definition + '''
|
||||
print_error () { echo "$@" >&2; }
|
||||
sleep () { exit 99; }
|
||||
pw_session_tool '../../other-command'
|
||||
'''
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script], capture_output=True, text=True,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)}, check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 1
|
||||
assert "Unsupported Wine tool" in result.stderr
|
||||
|
||||
|
||||
def test_wine_session_cleanup_preserves_newer_session(tmp_path: Path) -> None:
|
||||
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
|
||||
definitions = helper.split("pw_save_session_env () {", 1)[1].split("pw_session_tool () {", 1)[0]
|
||||
script = "pw_save_session_env () {" + definitions + '''
|
||||
export PW_START_PID="$$"
|
||||
pw_save_session_env || exit 2
|
||||
PW_START_PID=99999999
|
||||
pw_remove_session_env
|
||||
[[ -f "$PORT_DATA_PATH/data/tmp/wine-session-$(id -u)/session.env" ]] || exit 3
|
||||
PW_START_PID="$$"
|
||||
pw_remove_session_env
|
||||
[[ ! -e "$PORT_DATA_PATH/data/tmp/wine-session-$(id -u)/session.env" ]]
|
||||
'''
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script], capture_output=True, text=True,
|
||||
env={"PATH": os.defpath, "PORT_DATA_PATH": str(tmp_path)}, check=False,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
@@ -39,6 +39,7 @@ from portprotonqt.dialogs.settings_mangohud import (
|
||||
from portprotonqt.dialogs.settings_vkbasalt import VkBasaltSettingsMixin
|
||||
|
||||
|
||||
PAINT_SETTLE_MS = 250
|
||||
_application = QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
@@ -678,50 +679,6 @@ def test_settings_selected_row_keeps_text_readable(theme_name: str) -> None:
|
||||
table.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("closing", [False, True])
|
||||
def test_gpu_settings_probe_runs_in_background(monkeypatch: pytest.MonkeyPatch, closing: bool) -> None:
|
||||
from threading import Event, Timer
|
||||
from portprotonqt.tabs import settings_tab
|
||||
from portprotonqt.tabs.workers import MainWindowWorkersMixin
|
||||
|
||||
app = QApplication.instance() or QApplication([])
|
||||
entered, release = Event(), Event()
|
||||
|
||||
def probe() -> list[str]:
|
||||
entered.set()
|
||||
assert release.wait(5)
|
||||
return ["Integrated", "Discrete"]
|
||||
|
||||
monkeypatch.setattr(settings_tab, "get_selectable_gpu_list", probe)
|
||||
monkeypatch.setattr(settings_tab, "get_user_conf_setting", lambda _key: "Discrete")
|
||||
worker = settings_tab._GPUSettingsWorker()
|
||||
results: list[tuple[list[str], str]] = []
|
||||
worker.loaded.connect(lambda names, current: results.append((names, current)), Qt.ConnectionType.QueuedConnection)
|
||||
worker.start()
|
||||
try:
|
||||
assert entered.wait(5)
|
||||
ticks: list[bool] = []
|
||||
QTimer.singleShot(0, lambda: ticks.append(True))
|
||||
app.processEvents()
|
||||
assert ticks == [True]
|
||||
assert results == []
|
||||
if closing:
|
||||
owner = cast(Any, MainWindowWorkersMixin())
|
||||
owner._gpu_settings_worker = worker
|
||||
timer = Timer(0.05, release.set)
|
||||
timer.start()
|
||||
try:
|
||||
owner._stopBackgroundWorkers()
|
||||
assert not worker.isRunning()
|
||||
finally:
|
||||
timer.join()
|
||||
finally:
|
||||
release.set()
|
||||
assert worker.wait(5000)
|
||||
app.processEvents()
|
||||
assert results == ([] if closing else [(["Integrated", "Discrete"], "Discrete")])
|
||||
|
||||
|
||||
def test_settings_buttons_switch_between_one_and_two_rows() -> None:
|
||||
app = QApplication.instance() or QApplication([])
|
||||
parent = QWidget()
|
||||
@@ -806,6 +763,51 @@ def test_winetricks_centered_checkboxes_and_install_selection(
|
||||
dialog.deleteLater()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("theme_name", ["standart", "standart-light", "classic", "classic-light"])
|
||||
def test_settings_table_stops_repainting_when_idle(theme_name: str) -> None:
|
||||
from PySide6.QtCore import QObject
|
||||
from PySide6.QtWidgets import QTableWidgetItem
|
||||
from portprotonqt.dialogs.settings_dialog import ExeSettingsDialog
|
||||
from portprotonqt.theme_manager import ThemeWrapper, load_theme
|
||||
|
||||
theme = ThemeWrapper(load_theme(theme_name))
|
||||
dialog = cast(ExeSettingsDialog, SimpleNamespace(theme=theme))
|
||||
|
||||
class PaintFilter(QObject):
|
||||
paints = 0
|
||||
|
||||
def eventFilter(self, obj: QObject, event: QEvent) -> bool:
|
||||
if event.type() == QEvent.Type.Paint:
|
||||
self.paints += 1
|
||||
return ExeSettingsDialog.eventFilter(dialog, obj, event)
|
||||
return False
|
||||
|
||||
table = QTableWidget(3, 3)
|
||||
table.resize(800, 400)
|
||||
table.setStyleSheet(theme.WINETRICKS_TABBLE_STYLE)
|
||||
table.setColumnWidth(0, 500)
|
||||
table.setColumnHidden(2, True)
|
||||
table.viewport().setProperty("ppqt_settings_values", True)
|
||||
paint_filter = PaintFilter(table)
|
||||
table.viewport().installEventFilter(paint_filter)
|
||||
for row in range(3):
|
||||
table.setItem(row, 0, QTableWidgetItem("Setting\nDescription " * 5))
|
||||
combo = CustomComboBox(theme=theme)
|
||||
combo.addItem("Value")
|
||||
table.setCellWidget(row, 1, combo)
|
||||
table.show()
|
||||
for selected_row, width in ((0, 500), (1, 300)):
|
||||
table.selectRow(selected_row)
|
||||
table.setColumnWidth(0, width)
|
||||
for _ in range(10):
|
||||
QApplication.processEvents()
|
||||
QTest.qWait(PAINT_SETTLE_MS)
|
||||
paints = paint_filter.paints
|
||||
QTest.qWait(PAINT_SETTLE_MS)
|
||||
assert paint_filter.paints == paints
|
||||
table.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def autosave_dialog(request, monkeypatch, tmp_path) -> tuple[QDialog, list[list[str]], bool]:
|
||||
from PySide6.QtCore import QProcess
|
||||
|
||||
+6
-90
@@ -2668,105 +2668,24 @@ def test_sgdb_artwork_cache_separates_types(
|
||||
) -> None:
|
||||
import portprotonqt.steam_api.api as api
|
||||
|
||||
monkeypatch.setattr("portprotonqt.portproton_api.get_user_conf_setting", lambda _key: None)
|
||||
app = QApplication.instance() or QApplication([])
|
||||
monkeypatch.setattr(api, "CacheManager", lambda: SimpleNamespace(cache_dir=tmp_path))
|
||||
downloads = []
|
||||
|
||||
def download(url: str, path: str, timeout: int) -> str | None:
|
||||
def download(url: str, path: str, timeout: int, callback: Any) -> None:
|
||||
downloads.append(url)
|
||||
Path(path).write_text(f'"{url}"', encoding="utf-8")
|
||||
return path
|
||||
callback(path)
|
||||
|
||||
monkeypatch.setattr(api.downloader, "download", download)
|
||||
monkeypatch.setattr(api.downloader, "download_async", download)
|
||||
completed = []
|
||||
for image_type in ("grids", "heroes", "grids", "heroes"):
|
||||
api.fetch_sgdb_cover_async("Portal/2", completed.append, image_type)
|
||||
assert api._METADATA_LOOKUPS.waitForDone(5000)
|
||||
app.processEvents()
|
||||
assert len(downloads) == 2
|
||||
assert downloads[0].endswith("Portal%2F2/grids")
|
||||
assert downloads[1].endswith("Portal%2F2/heroes")
|
||||
assert completed == downloads + downloads
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", ['""', '"https://cdn2.steamgriddb.com/cover.png"'])
|
||||
def test_sgdb_retries_failed_lookup_but_caches_success(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, body: str,
|
||||
) -> None:
|
||||
from portprotonqt.steam_api import api
|
||||
|
||||
app = QApplication.instance() or QApplication([])
|
||||
monkeypatch.setattr(api, "CacheManager", lambda: SimpleNamespace(cache_dir=tmp_path))
|
||||
monkeypatch.setattr("portprotonqt.portproton_api.get_user_conf_setting", lambda _key: None)
|
||||
request_count = 0
|
||||
|
||||
def download(_url: str, path: str, timeout: int) -> str | None:
|
||||
nonlocal request_count
|
||||
request_count += 1
|
||||
if request_count == 1:
|
||||
return None
|
||||
Path(path).write_text(body, encoding="utf-8")
|
||||
return path
|
||||
|
||||
monkeypatch.setattr(api.downloader, "download", download)
|
||||
completed: list[str] = []
|
||||
api.fetch_sgdb_cover_async("Test Game", completed.append)
|
||||
assert api._METADATA_LOOKUPS.waitForDone(5000)
|
||||
app.processEvents()
|
||||
assert not list(tmp_path.iterdir())
|
||||
api.fetch_sgdb_cover_async("Test Game", completed.append)
|
||||
assert api._METADATA_LOOKUPS.waitForDone(5000)
|
||||
app.processEvents()
|
||||
api.fetch_sgdb_cover_async("Test Game", completed.append)
|
||||
assert api._METADATA_LOOKUPS.waitForDone(5000)
|
||||
app.processEvents()
|
||||
assert request_count == 2
|
||||
assert completed == ["", body.strip('"'), body.strip('"')]
|
||||
|
||||
|
||||
def test_sgdb_slow_cache_does_not_block_gui(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
|
||||
) -> None:
|
||||
from threading import Event
|
||||
from portprotonqt.steam_api import api
|
||||
|
||||
app = QApplication.instance() or QApplication([])
|
||||
cache_file = tmp_path / "sgdb_Test Game_grids.json"
|
||||
cache_file.write_text('""', encoding="utf-8")
|
||||
monkeypatch.setattr(api, "CacheManager", lambda: SimpleNamespace(cache_dir=tmp_path))
|
||||
original_stat = Path.stat
|
||||
entered, release = Event(), Event()
|
||||
expired: list[bool] = []
|
||||
|
||||
def slow_stat(path: Path, *args: Any, **kwargs: Any) -> Any:
|
||||
if path == cache_file:
|
||||
entered.set()
|
||||
if not release.wait(5):
|
||||
expired.append(True)
|
||||
return original_stat(path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Path, "stat", slow_stat)
|
||||
download = MagicMock()
|
||||
monkeypatch.setattr(api.downloader, "download", download)
|
||||
completed: list[tuple[str, QThread]] = []
|
||||
try:
|
||||
api.fetch_sgdb_cover_async("Test Game", lambda cover: completed.append((cover, QThread.currentThread())))
|
||||
assert entered.wait(5)
|
||||
tick = MagicMock()
|
||||
QTimer.singleShot(0, tick)
|
||||
app.processEvents()
|
||||
tick.assert_called_once_with()
|
||||
assert completed == []
|
||||
finally:
|
||||
release.set()
|
||||
assert api._METADATA_LOOKUPS.waitForDone(5000)
|
||||
app.processEvents()
|
||||
assert not expired
|
||||
assert completed == [("", QThread.currentThread())]
|
||||
download.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("image_type", ["grids", "heroes", "logos", "hgrids"])
|
||||
def test_sgdb_cloud_urls_use_proxy(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, image_type: str
|
||||
@@ -2774,20 +2693,17 @@ def test_sgdb_cloud_urls_use_proxy(
|
||||
import portprotonqt.steam_api.api as api
|
||||
import portprotonqt.portproton_api as portproton_api
|
||||
|
||||
app = QApplication.instance() or QApplication([])
|
||||
monkeypatch.setattr(api, "CacheManager", lambda: SimpleNamespace(cache_dir=tmp_path))
|
||||
monkeypatch.setattr(portproton_api, "get_user_conf_setting", lambda name: "CLOUD")
|
||||
url = f"https://cdn2.steamgriddb.com/{image_type}/asset.png"
|
||||
|
||||
def download(_url: str, path: str, timeout: int) -> str | None:
|
||||
def download(_url: str, path: str, timeout: int, callback: Any) -> None:
|
||||
Path(path).write_text(f'"{url}"', encoding="utf-8")
|
||||
return path
|
||||
callback(path)
|
||||
|
||||
monkeypatch.setattr(api.downloader, "download", download)
|
||||
monkeypatch.setattr(api.downloader, "download_async", download)
|
||||
completed = []
|
||||
api.fetch_sgdb_cover_async("Portal 2", completed.append, image_type)
|
||||
assert api._METADATA_LOOKUPS.waitForDone(5000)
|
||||
app.processEvents()
|
||||
|
||||
assert completed == [f"https://deckyloader.ru/sgdb-cdn/{image_type}/asset.png"]
|
||||
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
"""Tests for steam_api/cache.py — exiftool skip and search functions."""
|
||||
import time
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from typing import Any
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
@@ -24,67 +21,6 @@ def clear_exiftool_cache():
|
||||
_EXIFTOOL_CACHE.clear()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["app", "protondb", "steam", "anticheat", "ppdb"])
|
||||
def test_slow_metadata_cache_keeps_qt_responsive(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, kind: str,
|
||||
) -> None:
|
||||
import orjson
|
||||
from PySide6.QtCore import QThread, QTimer
|
||||
from PySide6.QtWidgets import QApplication
|
||||
from portprotonqt.steam_api import api, cache
|
||||
|
||||
app = QApplication.instance() or QApplication([])
|
||||
manager = cache.CacheManager(tmp_path)
|
||||
monkeypatch.setattr(cache, "CacheManager", lambda: manager)
|
||||
monkeypatch.setattr(api, "CacheManager", lambda: manager)
|
||||
entry = {"normalized_name": "game", "appid": 1, "id": 1, "status": "works", "slug": "game"}
|
||||
catalogs = {
|
||||
"steam": ("_STEAM_APPS_CACHE", "steam_apps", api.get_steam_apps_and_index_async),
|
||||
"anticheat": ("_ANTICHEAT_CACHE", "anticheat_games", api.get_anticheat_data_and_index_async),
|
||||
"ppdb": ("_PPDB_CACHE", "ppdb_games", api.get_ppdb_data_and_index_async),
|
||||
}
|
||||
if kind in catalogs:
|
||||
name, filename, request = catalogs[kind]
|
||||
monkeypatch.setattr(api, name, manager)
|
||||
payload: Any = [entry]
|
||||
expected: Any = ([entry], {"game": entry})
|
||||
elif kind == "app":
|
||||
filename, payload = "steam_app_1", {"name": "Game"}
|
||||
request = partial(api.fetch_app_info_async, 1)
|
||||
expected = payload
|
||||
else:
|
||||
filename, payload = "protondb_1", {"tier": "gold"}
|
||||
request = partial(api.get_protondb_tier_async, 1)
|
||||
expected = "gold"
|
||||
target = tmp_path / f"{filename}.json"
|
||||
target.write_bytes(orjson.dumps(payload))
|
||||
original_stat = Path.stat
|
||||
entered, release = Event(), Event()
|
||||
|
||||
def slow_stat(path: Path, **kwargs: Any) -> Any:
|
||||
if path == target:
|
||||
assert QThread.currentThread() != app.thread()
|
||||
entered.set()
|
||||
assert release.wait(5)
|
||||
return original_stat(path, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Path, "stat", slow_stat)
|
||||
results: list[tuple[Any, QThread]] = []
|
||||
tick = MagicMock()
|
||||
try:
|
||||
request(lambda result: results.append((result, QThread.currentThread())))
|
||||
assert entered.wait(5)
|
||||
QTimer.singleShot(0, tick)
|
||||
app.processEvents()
|
||||
tick.assert_called_once_with()
|
||||
assert not results
|
||||
finally:
|
||||
release.set()
|
||||
assert api._METADATA_LOOKUPS.waitForDone(5000)
|
||||
app.processEvents()
|
||||
assert results == [(expected, app.thread())]
|
||||
|
||||
|
||||
class TestGetExiftoolData:
|
||||
def test_skips_missing_executable(self, tmp_path: Path):
|
||||
fake_exe = tmp_path / "game.exe"
|
||||
|
||||
@@ -68,38 +68,6 @@ def test_layer_shell_keeps_qt_window_offscreen(
|
||||
window.hide()
|
||||
|
||||
|
||||
def test_builtin_emoji_panel(keyboard_window: SystemKeyboardWindow) -> None:
|
||||
window = keyboard_window
|
||||
keyboard = window.keyboard
|
||||
window.ready = window.wanted_visible = True
|
||||
keyboard.buttons['🙂'].click()
|
||||
assert keyboard.emoji_open
|
||||
assert keyboard.selected_button is keyboard.buttons['😀']
|
||||
window.command('direction', 'right')
|
||||
assert keyboard.selected_button is keyboard.buttons['😃']
|
||||
window.command('button', 'back')
|
||||
assert window.wanted_visible and not keyboard.emoji_open
|
||||
keyboard.buttons['🙂'].click()
|
||||
keyboard.buttons['❤️'].click()
|
||||
cast(MagicMock, system_window.report).assert_called_once_with('emoji', '❤️')
|
||||
assert not keyboard.emoji_open
|
||||
assert keyboard.selected_button is keyboard.buttons['🙂']
|
||||
|
||||
|
||||
def test_emoji_response_copies_to_clipboard(application: QApplication, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
controller = SystemKeyboard(QWidget())
|
||||
clipboard = MagicMock()
|
||||
monkeypatch.setattr(QApplication, 'clipboard', lambda: clipboard)
|
||||
controller.visible = True
|
||||
response = '{"event":"emoji","value":"❤️"}\n'.encode()
|
||||
monkeypatch.setattr(controller.process, 'readAllStandardOutput', lambda: SimpleNamespace(data=lambda: response))
|
||||
controller._read_state()
|
||||
clipboard.setText.assert_called_once_with('❤️')
|
||||
controller.visible = False
|
||||
controller._read_state()
|
||||
clipboard.setText.assert_called_once()
|
||||
|
||||
|
||||
def test_panel_matches_embedded_layout_without_extra_rows(keyboard_window: SystemKeyboardWindow) -> None:
|
||||
keyboard = keyboard_window.keyboard
|
||||
assert keyboard.current_layout == 'us'
|
||||
@@ -297,41 +265,6 @@ def test_modifiers_send_real_press_and_release_events(
|
||||
assert not worker.modifiers
|
||||
|
||||
|
||||
@pytest.mark.parametrize('action, codes, events', [
|
||||
('modifiers', (), [(ecodes.KEY_LEFTMETA, 1), (ecodes.KEY_LEFTMETA, 0)]),
|
||||
('tap', (ecodes.KEY_E,), [(ecodes.KEY_LEFTMETA, 1), (ecodes.KEY_E, 1),
|
||||
(ecodes.KEY_E, 0), (ecodes.KEY_LEFTMETA, 0)]),
|
||||
('release', (), []),
|
||||
])
|
||||
def test_labwc_super_sends_one_chord_after_click(action: str, codes: tuple[int, ...], events: list) -> None:
|
||||
worker = SystemInputWorker()
|
||||
worker.layout = detection.LabwcLayout.__new__(detection.LabwcLayout)
|
||||
worker.enabled.set()
|
||||
device = MagicMock()
|
||||
worker._execute(device, 'modifiers', (ecodes.KEY_LEFTMETA,))
|
||||
device.write.assert_not_called()
|
||||
worker._execute(device, action, codes)
|
||||
assert [call.args for call in device.write.call_args_list] == [
|
||||
(ecodes.EV_KEY, key, value) for key, value in events
|
||||
]
|
||||
assert not worker.modifiers and not worker.pending_super
|
||||
|
||||
|
||||
def test_labwc_alt_shift_releases_both_without_replaying() -> None:
|
||||
worker = SystemInputWorker()
|
||||
worker.layout = detection.LabwcLayout.__new__(detection.LabwcLayout)
|
||||
worker.enabled.set()
|
||||
device = MagicMock()
|
||||
worker._execute(device, 'modifiers', (ecodes.KEY_LEFTALT,))
|
||||
worker._execute(device, 'modifiers', (ecodes.KEY_LEFTALT, ecodes.KEY_LEFTSHIFT))
|
||||
worker._execute(device, 'modifiers', (ecodes.KEY_LEFTALT,))
|
||||
assert [call.args for call in device.write.call_args_list] == [
|
||||
(ecodes.EV_KEY, ecodes.KEY_LEFTALT, 1), (ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1),
|
||||
(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0), (ecodes.EV_KEY, ecodes.KEY_LEFTALT, 0),
|
||||
]
|
||||
assert not worker.modifiers
|
||||
|
||||
|
||||
def test_alt_shift_replay_preserves_remaining_alt(application: QApplication) -> None:
|
||||
worker = SystemInputWorker()
|
||||
worker.enabled.set()
|
||||
@@ -528,7 +461,6 @@ def test_system_keyboard_routes_buttons_without_application_focus(application: Q
|
||||
keyboard = SimpleNamespace(send=MagicMock(), isVisible=lambda: True)
|
||||
manager._parent = SimpleNamespace(system_keyboard=keyboard)
|
||||
manager.start_held = False
|
||||
manager.mouse_emulation_enabled = False
|
||||
assert manager._handle_system_keyboard_input(PAD_BUTTON_SOUTH, 1, False)
|
||||
keyboard.send.assert_called_once_with('button', 'confirm')
|
||||
|
||||
@@ -762,52 +694,18 @@ def test_wayland_protocol_metadata_is_native(application: QApplication) -> None:
|
||||
window._interface('not_a_protocol')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def clean_compositor_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
for variable in ('HYPRLAND_INSTANCE_SIGNATURE', 'SWAYSOCK', 'NIRI_SOCKET',
|
||||
'UMBRIEL_SOCKET', 'MANGO_INSTANCE_SIGNATURE', 'LABWC_PID', 'WAYFIRE_SOCKET'):
|
||||
monkeypatch.delenv(variable, raising=False)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures('clean_compositor_env')
|
||||
def test_budgie_wayland_uses_labwc_layout(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv('XDG_CURRENT_DESKTOP', 'Budgie')
|
||||
monkeypatch.setenv('WAYLAND_DISPLAY', 'wayland-test')
|
||||
monkeypatch.setenv('LABWC_PID', '123')
|
||||
adapter = MagicMock()
|
||||
monkeypatch.setattr(detection, 'LabwcLayout', adapter)
|
||||
assert detection.detect_layout() is adapter.return_value
|
||||
|
||||
|
||||
def test_labwc_updates_group_from_keyboard_modifiers() -> None:
|
||||
layout = detection.LabwcLayout.__new__(detection.LabwcLayout)
|
||||
fake = cast(Any, layout)
|
||||
fake.keyboard = fake.manager = None
|
||||
fake.seat = 1
|
||||
fake._interface = MagicMock()
|
||||
fake._new = MagicMock(return_value=2)
|
||||
fake._listen = MagicMock()
|
||||
layout._capabilities(2)
|
||||
modifiers, _ = fake._listen.call_args.args[1][-1]
|
||||
modifiers(0, 0, 0, 0, 2)
|
||||
assert layout.group == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize('desktop, warning', [
|
||||
('wayfire', 'Wayfire IPC unavailable'),
|
||||
('Qtile', 'No keyboard layout adapter'),
|
||||
('river', 'No keyboard layout adapter'),
|
||||
('unknown', 'No keyboard layout adapter'),
|
||||
])
|
||||
@pytest.mark.usefixtures('clean_compositor_env')
|
||||
@pytest.mark.parametrize('desktop', ['labwc', 'wayfire', 'Qtile', 'river', 'unknown'])
|
||||
def test_generic_wayland_uses_manual_labels_without_xwayland(
|
||||
monkeypatch: pytest.MonkeyPatch, desktop: str, warning: str,
|
||||
monkeypatch: pytest.MonkeyPatch, desktop: str,
|
||||
) -> None:
|
||||
monkeypatch.setenv('XDG_CURRENT_DESKTOP', desktop)
|
||||
monkeypatch.setenv('WAYLAND_DISPLAY', 'wayland-test')
|
||||
for variable in ('HYPRLAND_INSTANCE_SIGNATURE', 'SWAYSOCK', 'NIRI_SOCKET',
|
||||
'UMBRIEL_SOCKET', 'MANGO_INSTANCE_SIGNATURE'):
|
||||
monkeypatch.delenv(variable, raising=False)
|
||||
x11 = MagicMock()
|
||||
monkeypatch.setattr(detection, 'X11Layout', x11)
|
||||
with pytest.raises(RuntimeError, match=warning):
|
||||
with pytest.raises(RuntimeError, match='No keyboard layout adapter'):
|
||||
detection.detect_layout()
|
||||
x11.assert_not_called()
|
||||
|
||||
@@ -878,54 +776,6 @@ def ipc_layout_registry(tmp_path: Any) -> Any:
|
||||
return registry
|
||||
|
||||
|
||||
@pytest.mark.usefixtures('clean_compositor_env')
|
||||
def test_wayfire_detects_session_and_tracks_layout(monkeypatch: pytest.MonkeyPatch, ipc_layout_registry: Any) -> None:
|
||||
monkeypatch.setenv('XDG_CURRENT_DESKTOP', 'Wayfire')
|
||||
monkeypatch.setenv('WAYFIRE_SOCKET', '/test/wayfire.sock')
|
||||
assert detection.compositor({'WAYFIRE_SOCKET': '/test/wayfire.sock'}) == 'wayfire'
|
||||
assert detection.compositor({'XDG_CURRENT_DESKTOP': 'Wayfire'}) == 'wayfire'
|
||||
names = ['English (Dvorak)', 'Russian']
|
||||
request = MagicMock(side_effect=[
|
||||
{'possible-layouts': names, 'layout-index': 0},
|
||||
{'possible-layouts': names, 'layout-index': 1},
|
||||
{'possible-layouts': names, 'layout-index': 1},
|
||||
{'result': 'ok'},
|
||||
])
|
||||
monkeypatch.setattr(detection.WayfireLayout, '_request', request)
|
||||
factory = MagicMock()
|
||||
monkeypatch.setattr(detection, 'Layout', factory)
|
||||
layout = detection.WayfireLayout(ipc_layout_registry)
|
||||
factory.assert_called_once_with('us', 'dvorak')
|
||||
layout.labels()
|
||||
factory.assert_called_with('ru', '')
|
||||
layout.switch()
|
||||
request.assert_called_with('wayfire/set-keyboard-state', {'layout-index': 0})
|
||||
adapter = MagicMock(return_value=layout)
|
||||
monkeypatch.setattr(detection, 'WayfireLayout', adapter)
|
||||
assert detection.detect_layout() is layout
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reply, error', [
|
||||
(b'\x01', 'incomplete reply header'),
|
||||
(b'\x05\0\0\0{}', 'incomplete reply'),
|
||||
(b'\x00\x00\x02\x00', 'invalid reply size'),
|
||||
(b'\x10\0\0\0{"error":"oops"}', 'oops'),
|
||||
])
|
||||
def test_wayfire_ipc_rejects_bad_replies(monkeypatch: pytest.MonkeyPatch, reply: bytes, error: str) -> None:
|
||||
from io import BytesIO
|
||||
|
||||
monkeypatch.setenv('WAYFIRE_SOCKET', '/test/wayfire.sock')
|
||||
socket_factory = MagicMock()
|
||||
monkeypatch.setattr(detection.socket, 'socket', socket_factory)
|
||||
sock = socket_factory.return_value.__enter__.return_value
|
||||
sock.makefile.return_value = BytesIO(reply)
|
||||
with pytest.raises(RuntimeError, match=error):
|
||||
detection.WayfireLayout._request('wayfire/get-keyboard-state')
|
||||
sock.connect.assert_called_once_with('/test/wayfire.sock')
|
||||
payload = b'{"method":"wayfire/get-keyboard-state","data":{}}'
|
||||
sock.sendall.assert_called_once_with(len(payload).to_bytes(4, 'little') + payload)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('adapter', [detection.UmbrielLayout, detection.MangoLayout])
|
||||
def test_ipc_layout_tracks_external_changes_and_variants(
|
||||
monkeypatch: pytest.MonkeyPatch, ipc_layout_registry: Any, adapter: Any,
|
||||
@@ -1101,26 +951,6 @@ def test_kde_selection_uses_native_backend(monkeypatch: pytest.MonkeyPatch) -> N
|
||||
assert detection.detect_layout() is factory.return_value
|
||||
|
||||
|
||||
def test_wayland_repeated_configure_does_not_rebuild_keyboard() -> None:
|
||||
native: Any = system_window.WaylandWindow.__new__(system_window.WaylandWindow)
|
||||
native.layer = 1
|
||||
native._request = MagicMock()
|
||||
native.window = MagicMock()
|
||||
native.window.width.return_value = 1280
|
||||
native.window.height.return_value = 720
|
||||
native.configured = False
|
||||
native._configured(1, 1280, 720)
|
||||
native.dirty = False
|
||||
native._configured(2, 1280, 720)
|
||||
native.window._position_keyboard.assert_called_once_with()
|
||||
assert native._request.call_count == 2
|
||||
assert not native.dirty
|
||||
native._configured(3, 1920, 1080)
|
||||
native.window.resize.assert_called_with(1920, 1080)
|
||||
assert native.window._position_keyboard.call_count == 2
|
||||
assert native.dirty
|
||||
|
||||
|
||||
def test_wayland_mouse_moves_selection_and_shows_pressed_state(
|
||||
keyboard_window: SystemKeyboardWindow, application: QApplication,
|
||||
) -> None:
|
||||
@@ -1149,41 +979,6 @@ def test_wayland_mouse_moves_selection_and_shows_pressed_state(
|
||||
assert keyboard_window.worker.commands.get_nowait() == ('tap', (ecodes.KEY_Q,))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('deleted', [False, True])
|
||||
def test_wayland_release_after_keyboard_rebuild(
|
||||
keyboard_window: SystemKeyboardWindow, application: QApplication, deleted: bool,
|
||||
) -> None:
|
||||
from PySide6.QtCore import QEvent, QPointF
|
||||
from shiboken6 import isValid
|
||||
|
||||
keyboard_window.ready = True
|
||||
keyboard_window.show_keyboard()
|
||||
application.processEvents()
|
||||
keyboard = keyboard_window.keyboard
|
||||
target = keyboard.buttons['q']
|
||||
native: Any = system_window.WaylandWindow.__new__(system_window.WaylandWindow)
|
||||
native.window = keyboard_window
|
||||
native.pressed_widget = None
|
||||
native.position = QPointF(target.mapTo(keyboard_window, target.rect().center()))
|
||||
native._mouse_event(QEvent.Type.MouseButtonPress)
|
||||
keyboard.update_keyboard()
|
||||
if deleted:
|
||||
QApplication.sendPostedEvents(target, QEvent.Type.DeferredDelete)
|
||||
assert isValid(target) is not deleted
|
||||
|
||||
native._mouse_event(QEvent.Type.MouseButtonRelease)
|
||||
assert native.pressed_widget is None
|
||||
assert keyboard_window.worker.commands.empty()
|
||||
|
||||
application.processEvents()
|
||||
replacement = keyboard.buttons['q']
|
||||
native.position = QPointF(replacement.mapTo(keyboard_window, replacement.rect().center()))
|
||||
assert keyboard_window.childAt(native.position.toPoint()) is replacement
|
||||
native._mouse_event(QEvent.Type.MouseButtonPress)
|
||||
native._mouse_event(QEvent.Type.MouseButtonRelease)
|
||||
assert keyboard_window.worker.commands.get_nowait() == ('tap', (ecodes.KEY_Q,))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failed', [False, True])
|
||||
def test_kde_dbus_connection_is_retained_and_closed(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Any, failed: bool,
|
||||
@@ -1427,7 +1222,6 @@ def test_ibus_switch_rejects_unusable_sources(
|
||||
('true', 'xkb:de::deu', False),
|
||||
('false', 'pinyin', False),
|
||||
])
|
||||
@pytest.mark.usefixtures('clean_compositor_env')
|
||||
def test_x11_detects_ibus_managed_layouts(
|
||||
monkeypatch: pytest.MonkeyPatch, system_map: str, engine: str, uses_ibus: bool,
|
||||
) -> None:
|
||||
@@ -1444,7 +1238,6 @@ def test_x11_detects_ibus_managed_layouts(
|
||||
assert ibus.call_count == int(uses_ibus)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures('clean_compositor_env')
|
||||
def test_ibus_detection_failure_keeps_x11_available(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv('XDG_SESSION_TYPE', 'x11')
|
||||
monkeypatch.setenv('XDG_CURRENT_DESKTOP', 'XFCE')
|
||||
|
||||
@@ -4,7 +4,6 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from portprotonqt.theme_security import (
|
||||
MAX_AST_NODES,
|
||||
ThemeSecurityChecker,
|
||||
check_theme_directory_safety,
|
||||
check_theme_safety,
|
||||
@@ -325,8 +324,7 @@ class TestAllowedConstructs:
|
||||
|
||||
class TestAstSizeLimit:
|
||||
def test_huge_file(self, tmp_path: Path) -> None:
|
||||
# Each assignment adds four nodes; the module adds one more.
|
||||
code = "x = 1\n" * (MAX_AST_NODES // 4)
|
||||
code = "x = 1\n" * 25000
|
||||
is_safe, errors = _check(code, tmp_path)
|
||||
assert not is_safe
|
||||
assert any("too many AST nodes" in e for e in errors)
|
||||
|
||||
@@ -18,6 +18,7 @@ from portprotonqt.steam_api.utils import (
|
||||
convert_steam_id,
|
||||
decode_text,
|
||||
get_steam_launch_commands,
|
||||
get_steam_runtime_library_paths,
|
||||
get_steam_compatibilitytools_dir,
|
||||
get_steam_compat_tool,
|
||||
get_last_steam_user,
|
||||
@@ -580,6 +581,19 @@ class TestIterExistingSteamDataDirs:
|
||||
result = _iter_existing_steam_data_dirs()
|
||||
assert len(result) == 1
|
||||
|
||||
def test_runtime_paths_from_all_installations(self, tmp_path: Path):
|
||||
native_steam = tmp_path / "native"
|
||||
snap_steam = tmp_path / "snap"
|
||||
(native_steam / "ubuntu12_32").mkdir(parents=True)
|
||||
(snap_steam / "ubuntu12_64").mkdir(parents=True)
|
||||
steam_dirs = (str(native_steam), str(snap_steam))
|
||||
|
||||
with patch("portprotonqt.steam_api.utils.STEAM_DATA_DIRS", steam_dirs):
|
||||
assert get_steam_runtime_library_paths() == [
|
||||
str(native_steam / "ubuntu12_32"),
|
||||
str(snap_steam / "ubuntu12_64"),
|
||||
]
|
||||
|
||||
def test_skips_nonexistent(self):
|
||||
with patch("portprotonqt.steam_api.utils.STEAM_DATA_DIRS", ("/nonexistent/path",)):
|
||||
result = _iter_existing_steam_data_dirs()
|
||||
|
||||
Reference in new issue
Block a user