Compare commits

..
Author SHA1 Message Date
Boria138 9619e5e369 feat: added MacOS support
Signed-off-by: Boris Yumankulov <boria138@altlinux.org>
2026-11-16 18:31:29 +05:00
63 changed files with 914 additions and 3047 deletions

No files matched your search

@@ -8,7 +8,6 @@ on:
- scripts
paths:
- 'build-aux/src/vk_gpu_info.c'
- 'build-aux/src/wine_gpu_names.h'
- '.gitea/workflows/build-vk-gpu-info-debian.yml'
jobs:
+2
View File
@@ -30,6 +30,8 @@ jobs:
run: python dev-scripts/get_id.py
env:
STEAM_KEY: ${{ secrets.STEAM_KEY }}
LINUX_GAMING_API_KEY: ${{ secrets.LINUX_GAMING_API_KEY }}
LINUX_GAMING_API_USERNAME: ${{ secrets.LINUX_GAMING_API_USERNAME }}
- name: Commit and push changes
env:
+1 -1
View File
@@ -40,6 +40,6 @@ jobs:
env:
RENOVATE_CONFIG_FILE: "/tmp/renovate-config/config.js"
RENOVATE_BINARY_SOURCE: "global"
GITHUB_COM_TOKEN: ${{ secrets.GHP_COM_TOKEN }}
GITHUB_COM_TOKEN: ${{ secrets.GITHUB_COM_TOKEN }}
LOG_LEVEL: "debug"
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
@@ -1,49 +0,0 @@
name: Update Wine GPU names
on:
workflow_dispatch:
schedule:
- cron: '0 4 * * 1'
concurrency:
group: update-wine-gpu-names
cancel-in-progress: false
jobs:
update:
if: gitea.repository == 'Linux-Gaming/PortProtonQt'
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: https://git.linux-gaming.ru/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
ref: main
token: ${{ secrets.GITEA_TOKEN }}
- name: Set up Python
uses: https://git.linux-gaming.ru/actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7
with:
python-version-file: pyproject.toml
- name: Update Wine GPU names
id: update
run: |
python dev-scripts/update_wine_gpu_names.py
if git diff --quiet -- build-aux/src/wine_gpu_names.h; then
echo "changed=false" >> "$GITHUB_OUTPUT"
else
echo "changed=true" >> "$GITHUB_OUTPUT"
fi
- name: Commit and push table changes
if: steps.update.outputs.changed == 'true'
run: |
git add -- build-aux/src/wine_gpu_names.h
if git diff --cached --quiet; then
echo "Wine GPU names are unchanged."
exit 0
fi
git config --local user.name 'Gitea Actions'
git config --local user.email 'gitea-actions@users.noreply.gitea.com'
git commit -m 'chore: sync Wine GPU names'
git push origin HEAD:main
-2
View File
@@ -7,7 +7,6 @@
### Added
- В Run After / Wrapper добавлена поддержка `%command%` для передачи команды игры обёртке, например `mako-launch %command%`, без повторного запуска игры
- Добавлено отслеживание запуска Steam-игр на странице игры
- Добавлен CLI для получения локальных данных библиотеки
- Для Run After / Wrapper добавлен раскрываемый список с отдельным полем для каждой записи, удалением записей и кнопкой полной очистки
@@ -44,7 +43,6 @@
### Fixed
- Исправлена фильтрация видеокарт DXVK и VKD3D при расхождении нативного имени GPU с именем Wine
- Запросы установки других игр GOG и EGS во время получения списка DLC добавляются в очередь вместо ошибки «Другая загрузка уже выполняется»
- Виртуальная мышь создаётся только при включении эмуляции геймпадом и удаляется при её выключении
- При ошибке загрузки каталога WINE/Proton отображаются локально установленные версии
+1 -1
View File
@@ -8,7 +8,7 @@ arch=('x86_64')
url="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt"
license=('GPL-3.0')
depends=('python-requests' 'python-babel' 'python-evdev' 'python-orjson'
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'qt6-imageformats' 'qt6-multimedia' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' '7zip' 'python-dbus-fast' 'sdl3' 'desktop-file-utils' 'wayland' 'libxkbcommon' 'libx11' 'xkeyboard-config')
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'qt6-imageformats' 'qt6-multimedia' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' '7zip' 'python-dbus-fast' 'sdl3' 'desktop-file-utils')
makedepends=('meson' 'ninja' 'vulkan-headers' 'gettext' 'sdl3')
conflicts=("portprotonqt-steam-compat")
provides=('portprotonqt-steam-compat')
+1 -1
View File
@@ -8,7 +8,7 @@ arch=('x86_64')
url="https://git.linux-gaming.ru/Linux-Gaming/PortProtonQt"
license=('GPL-3.0')
depends=('python-requests' 'python-babel' 'python-evdev' 'python-orjson'
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'qt6-imageformats' 'qt6-multimedia' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' '7zip' 'python-dbus-fast' 'sdl3' 'desktop-file-utils' 'wayland' 'libxkbcommon' 'libx11' 'xkeyboard-config')
'python-psutil' 'python-tqdm' 'python-vdf' 'python-libarchive-c' 'pyside6' 'python-rapidfuzz' 'python-pefile' 'python-pillow' 'perl-image-exiftool' 'python-websocket-client' 'cabextract' 'unzip' 'curl' 'file' 'findutils' 'gawk' 'grep' 'tar' 'xz' 'zstd' 'gzip' 'unrar' 'qt6-svg' 'qt6-imageformats' 'qt6-multimedia' 'pciutils' 'mesa-utils' 'vulkan-icd-loader' 'procps-ng' 'psmisc' '7zip' 'python-dbus-fast' 'sdl3' 'desktop-file-utils')
makedepends=('meson' 'ninja' 'vulkan-headers' 'gettext' 'sdl3')
conflicts=("portprotonqt-steam-compat")
provides=('portprotonqt-steam-compat')
Binary file not shown.
-4
View File
@@ -23,9 +23,6 @@ BuildRequires: gettext
BuildRequires: systemd-rpm-macros
BuildRequires: vulkan-loader-devel
BuildRequires: pkgconfig(sdl3)
BuildRequires: pkgconfig(wayland-client)
BuildRequires: pkgconfig(xkbcommon)
BuildRequires: pkgconfig(x11)
BuildRequires: gcc
Obsoletes: python3-%{pypi_name}-git < %{version}-%{release}
@@ -69,7 +66,6 @@ Requires: psmisc
Requires: 7zip
Requires: python3-dbus-fast
Requires: desktop-file-utils
Requires: xkeyboard-config
# System Tab
Recommends: NetworkManager
-4
View File
@@ -20,9 +20,6 @@ BuildRequires: gettext
BuildRequires: systemd-rpm-macros
BuildRequires: vulkan-loader-devel
BuildRequires: pkgconfig(sdl3)
BuildRequires: pkgconfig(wayland-client)
BuildRequires: pkgconfig(xkbcommon)
BuildRequires: pkgconfig(x11)
BuildRequires: gcc
Obsoletes: python3-%{pypi_name} < %{version}-%{release}
@@ -66,7 +63,6 @@ Requires: psmisc
Requires: 7zip
Requires: python3-dbus-fast
Requires: desktop-file-utils
Requires: xkeyboard-config
# System Tab
Recommends: NetworkManager
Binary file not shown.
@@ -2008,37 +2008,6 @@ pw_init_db () {
return 0
}
pw_select_gpu () {
[[ -n "${PW_GPU_USE}" && "${PW_GPU_USE}" != "disabled" ]] || return 0
local vk_gpu_info_cmd vk_info_output line current_device_name="" filter_name="${PW_GPU_USE}"
vk_gpu_info_cmd="$(dirname "${BASH_SOURCE[0]}")/../../../bin/vk_gpu_info"
if [[ ! -x "${vk_gpu_info_cmd}" ]] ; then
vk_gpu_info_cmd="$(command -v vk_gpu_info 2>/dev/null || true)"
fi
if [[ -n "${vk_gpu_info_cmd}" ]] ; then
if vk_info_output="$("${vk_gpu_info_cmd}" 2>/dev/null)" ; then
while IFS= read -r line ; do
case "$line" in
"GPU #"*) current_device_name="" ;;
"device_name: "*) current_device_name="${line#device_name: }" ;;
"wine_device_name: "*)
if [[ "${current_device_name}" == "${PW_GPU_USE}" && -n "${line#wine_device_name: }" ]] ; then
filter_name="${line#wine_device_name: }"
break
fi
;;
esac
done <<< "${vk_info_output}"
else
print_warning "vk_gpu_info failed; using the native GPU name for device filters."
fi
fi
[[ -v DXVK_FILTER_DEVICE_NAME ]] || export DXVK_FILTER_DEVICE_NAME="${filter_name}"
[[ -v VKD3D_FILTER_DEVICE_NAME ]] || export VKD3D_FILTER_DEVICE_NAME="${filter_name}"
export MESA_VK_DEVICE_SELECT_FORCE_DEFAULT_DEVICE="1"
export MESA_VK_DEVICE_SELECT="$PW_vendorID:$PW_deviceID"
}
pw_check_vulkan_extensions () {
local ext_name="$1"
local ext_key
@@ -3043,7 +3012,12 @@ start_portproton () {
[[ "${PW_VKBASALT_USER_CONF}" == 1 ]] && pw_select_vkbasalt_user_conf
pw_select_gpu
if [[ $PW_GPU_USE != "disabled" ]] ; then
export DXVK_FILTER_DEVICE_NAME="$PW_GPU_USE"
export VKD3D_FILTER_DEVICE_NAME="$PW_GPU_USE"
export MESA_VK_DEVICE_SELECT_FORCE_DEFAULT_DEVICE="1"
export MESA_VK_DEVICE_SELECT="$PW_vendorID:$PW_deviceID"
fi
if [[ -f "$PATH_TO_GAME/dxvk.conf" ]] ; then
export DXVK_CONFIG_FILE="$PATH_TO_GAME/dxvk.conf"
@@ -4064,22 +4038,6 @@ pw_launch_wrapper () {
return
fi
local wrapper_arg
local -a launch_cmd=()
local wrapper_command_seen=0
for wrapper_arg in "${wrapper_cmd[@]}" ; do
if [[ "$wrapper_arg" == '%command%' ]] ; then
launch_cmd+=("$@")
wrapper_command_seen=1
else
launch_cmd+=("$wrapper_arg")
fi
done
if [[ "$wrapper_command_seen" == 1 ]] ; then
"${launch_cmd[@]}"
return
fi
if [[ "${wrapper_cmd[0]##*/}" == "systemd-run" ]] ; then
"${wrapper_cmd[@]}" -- "$@"
return
-60
View File
@@ -1,60 +0,0 @@
/* Assisted-by: Codex:GPT-6 */
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <string.h>
#include <wayland-client.h>
#include <xkbcommon/xkbcommon.h>
struct wl_display *portproton_keyboard_wayland_connect(const char *name)
{
return wl_display_connect(name);
}
struct xkb_context *portproton_keyboard_xkb_context_new(enum xkb_context_flags flags)
{
return xkb_context_new(flags);
}
Display *portproton_keyboard_x11_open_display(const char *name)
{
return XOpenDisplay(name);
}
int portproton_keyboard_x11_layout_name(Display *display, unsigned int group,
char *buffer, size_t size)
{
const long property_length = 1024;
Atom property = XInternAtom(display, "_XKB_RULES_NAMES", True);
Atom type;
int format;
unsigned long length, remaining;
unsigned char *data = NULL;
if (!property || !buffer || size == 0)
return 0;
if (XGetWindowProperty(display, DefaultRootWindow(display), property, 0,
property_length, False, XA_STRING, &type, &format,
&length, &remaining, &data) != Success || !data)
return 0;
char *start = (char *)data;
char *end = start + length;
for (unsigned int field = 0; field < 2 && start < end; ++field) {
char *separator = memchr(start, '\0', (size_t)(end - start));
start = separator ? separator + 1 : end;
}
char *layouts_end = memchr(start, '\0', (size_t)(end - start));
if (!layouts_end)
layouts_end = end;
for (unsigned int index = 0; index < group && start < layouts_end; ++index) {
char *separator = memchr(start, ',', (size_t)(layouts_end - start));
start = separator ? separator + 1 : layouts_end;
}
char *separator = memchr(start, ',', (size_t)(layouts_end - start));
size_t count = (size_t)((separator ? separator : layouts_end) - start);
int found = format == 8 && count > 0 && count < size;
if (found) {
memcpy(buffer, start, count);
buffer[count] = '\0';
}
XFree(data);
return found;
}
-2
View File
@@ -2,7 +2,6 @@
#include <stdlib.h>
#include <string.h>
#include <vulkan/vulkan.h>
#include "wine_gpu_names.h"
typedef struct {
uint32_t vendor_id;
@@ -276,7 +275,6 @@ int main() {
printf("vendor_id: 0x%04x\n", props.vendorID);
printf("device_id: 0x%04x\n", props.deviceID);
printf("device_name: %s\n", device_name);
printf("wine_device_name: %s\n", wine_device_name(props.vendorID, props.deviceID, device_name));
printf("driver_name: %s\n", driver_name);
printf("driver_info: %s\n", driver_info);
printf("api_version: %u.%u.%u\n",
-371
View File
@@ -1,371 +0,0 @@
/*
* GPU names derived from Wine gpu_device_name()
*
* Copyright 1994 Alexandre Julliard
* Copyright 2019 Zhiyi Zhang for CodeWeavers
* Copyright 2021 Jacek Caban for CodeWeavers
*
* Adapted from LGPL-2.1-or-later Wine code under section 3 of LGPL-2.1.
* This adaptation is licensed under GPL-3.0.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// Source: wine-mirror/wine, dlls/win32u/sysparams.c
// Revision: 9f8c4ae4d35c7ff4153267aba9618c026f5f5583
#ifndef WINE_GPU_NAMES_H
#define WINE_GPU_NAMES_H
#include <stddef.h>
#include <stdint.h>
static const struct {
uint32_t vendor_id;
uint32_t device_id;
const char *name;
} wine_gpu_names[] = {
{0x10de, 0x0018, "NVIDIA RIVA 128"},
{0x10de, 0x0020, "NVIDIA RIVA TNT"},
{0x10de, 0x0028, "NVIDIA RIVA TNT2/TNT2 Pro"},
{0x10de, 0x0100, "NVIDIA GeForce 256"},
{0x10de, 0x0150, "NVIDIA GeForce2 GTS/GeForce2 Pro"},
{0x10de, 0x0110, "NVIDIA GeForce2 MX/MX 400"},
{0x10de, 0x0200, "NVIDIA GeForce3"},
{0x10de, 0x0170, "NVIDIA GeForce4 MX 460"},
{0x10de, 0x0253, "NVIDIA GeForce4 Ti 4200"},
{0x10de, 0x0320, "NVIDIA GeForce FX 5200"},
{0x10de, 0x0312, "NVIDIA GeForce FX 5600"},
{0x10de, 0x0302, "NVIDIA GeForce FX 5800"},
{0x10de, 0x014f, "NVIDIA GeForce 6200"},
{0x10de, 0x0140, "NVIDIA GeForce 6600 GT"},
{0x10de, 0x0041, "NVIDIA GeForce 6800"},
{0x10de, 0x01d7, "NVIDIA GeForce Go 7300"},
{0x10de, 0x01d8, "NVIDIA GeForce Go 7400"},
{0x10de, 0x0391, "NVIDIA GeForce 7600 GT"},
{0x10de, 0x0092, "NVIDIA GeForce 7800 GT"},
{0x10de, 0x0849, "NVIDIA GeForce 8200"},
{0x10de, 0x084b, "NVIDIA GeForce 8200"},
{0x10de, 0x0423, "NVIDIA GeForce 8300 GS"},
{0x10de, 0x0404, "NVIDIA GeForce 8400 GS"},
{0x10de, 0x0421, "NVIDIA GeForce 8500 GT"},
{0x10de, 0x0402, "NVIDIA GeForce 8600 GT"},
{0x10de, 0x0407, "NVIDIA GeForce 8600M GT"},
{0x10de, 0x0193, "NVIDIA GeForce 8800 GTS"},
{0x10de, 0x0191, "NVIDIA GeForce 8800 GTX"},
{0x10de, 0x086d, "NVIDIA GeForce 9200"},
{0x10de, 0x086c, "NVIDIA GeForce 9300"},
{0x10de, 0x0863, "NVIDIA GeForce 9400M"},
{0x10de, 0x042c, "NVIDIA GeForce 9400 GT"},
{0x10de, 0x0640, "NVIDIA GeForce 9500 GT"},
{0x10de, 0x0622, "NVIDIA GeForce 9600 GT"},
{0x10de, 0x064a, "NVIDIA GeForce 9700M GT"},
{0x10de, 0x0614, "NVIDIA GeForce 9800 GT"},
{0x10de, 0x0a23, "NVIDIA GeForce 210"},
{0x10de, 0x0a20, "NVIDIA GeForce GT 220"},
{0x10de, 0x0ca3, "NVIDIA GeForce GT 240"},
{0x10de, 0x0615, "NVIDIA GeForce GTS 250"},
{0x10de, 0x05e2, "NVIDIA GeForce GTX 260"},
{0x10de, 0x05e6, "NVIDIA GeForce GTX 275"},
{0x10de, 0x05e1, "NVIDIA GeForce GTX 280"},
{0x10de, 0x0a7a, "NVIDIA GeForce 315M"},
{0x10de, 0x08a3, "NVIDIA GeForce 320M"},
{0x10de, 0x0a2d, "NVIDIA GeForce GT 320M"},
{0x10de, 0x0a35, "NVIDIA GeForce GT 325M"},
{0x10de, 0x0ca0, "NVIDIA GeForce GT 330"},
{0x10de, 0x0cb0, "NVIDIA GeForce GTS 350M"},
{0x10de, 0x1055, "NVIDIA GeForce 410M"},
{0x10de, 0x0de2, "NVIDIA GeForce GT 420"},
{0x10de, 0x0df0, "NVIDIA GeForce GT 425M"},
{0x10de, 0x0de1, "NVIDIA GeForce GT 430"},
{0x10de, 0x0de0, "NVIDIA GeForce GT 440"},
{0x10de, 0x0dc4, "NVIDIA GeForce GTS 450"},
{0x10de, 0x0e22, "NVIDIA GeForce GTX 460"},
{0x10de, 0x0dd1, "NVIDIA GeForce GTX 460M"},
{0x10de, 0x06c4, "NVIDIA GeForce GTX 465"},
{0x10de, 0x06cd, "NVIDIA GeForce GTX 470"},
{0x10de, 0x06c0, "NVIDIA GeForce GTX 480"},
{0x10de, 0x1040, "NVIDIA GeForce GT 520"},
{0x10de, 0x0dec, "NVIDIA GeForce GT 525M"},
{0x10de, 0x0df4, "NVIDIA GeForce GT 540M"},
{0x10de, 0x1244, "NVIDIA GeForce GTX 550 Ti"},
{0x10de, 0x04b8, "NVIDIA GeForce GT 555M"},
{0x10de, 0x1200, "NVIDIA GeForce GTX 560 Ti"},
{0x10de, 0x1251, "NVIDIA GeForce GTX 560M"},
{0x10de, 0x1201, "NVIDIA GeForce GTX 560"},
{0x10de, 0x1081, "NVIDIA GeForce GTX 570"},
{0x10de, 0x1080, "NVIDIA GeForce GTX 580"},
{0x10de, 0x104a, "NVIDIA GeForce GT 610"},
{0x10de, 0x0f00, "NVIDIA GeForce GT 630"},
{0x10de, 0x0de9, "NVIDIA GeForce GT 630M"},
{0x10de, 0x0fc1, "NVIDIA GeForce GT 640"},
{0x10de, 0x0fd2, "NVIDIA GeForce GT 640M"},
{0x10de, 0x0fd1, "NVIDIA GeForce GT 650M"},
{0x10de, 0x0fc6, "NVIDIA GeForce GTX 650"},
{0x10de, 0x11c6, "NVIDIA GeForce GTX 650 Ti"},
{0x10de, 0x11c0, "NVIDIA GeForce GTX 660"},
{0x10de, 0x0fd4, "NVIDIA GeForce GTX 660M"},
{0x10de, 0x1183, "NVIDIA GeForce GTX 660 Ti"},
{0x10de, 0x1189, "NVIDIA GeForce GTX 670"},
{0x10de, 0x11a1, "NVIDIA GeForce GTX 670MX"},
{0x10de, 0x11a7, "NVIDIA GeForce GTX 675MX"},
{0x10de, 0x11a2, "NVIDIA GeForce GTX 675MX"},
{0x10de, 0x1180, "NVIDIA GeForce GTX 680"},
{0x10de, 0x1188, "NVIDIA GeForce GTX 690"},
{0x10de, 0x128b, "NVIDIA GeForce GT 720"},
{0x10de, 0x1287, "NVIDIA GeForce GT 730"},
{0x10de, 0x0fe1, "NVIDIA GeForce GT 730M"},
{0x10de, 0x1292, "NVIDIA GeForce GT 740M"},
{0x10de, 0x0fe9, "NVIDIA GeForce GT 750M"},
{0x10de, 0x0fcd, "NVIDIA GeForce GT 755M"},
{0x10de, 0x1381, "NVIDIA GeForce GTX 750"},
{0x10de, 0x1380, "NVIDIA GeForce GTX 750 Ti"},
{0x10de, 0x1187, "NVIDIA GeForce GTX 760"},
{0x10de, 0x1193, "NVIDIA GeForce GTX 760 Ti"},
{0x10de, 0x11e2, "NVIDIA GeForce GTX 765M"},
{0x10de, 0x11e0, "NVIDIA GeForce GTX 770M"},
{0x10de, 0x1184, "NVIDIA GeForce GTX 770"},
{0x10de, 0x119d, "NVIDIA GeForce GTX 775M"},
{0x10de, 0x1004, "NVIDIA GeForce GTX 780"},
{0x10de, 0x119e, "NVIDIA GeForce GTX 780M"},
{0x10de, 0x100a, "NVIDIA GeForce GTX 780 Ti"},
{0x10de, 0x1005, "NVIDIA GeForce GTX TITAN"},
{0x10de, 0x100c, "NVIDIA GeForce GTX TITAN Black"},
{0x10de, 0x17c2, "NVIDIA GeForce GTX TITAN X"},
{0x10de, 0x1001, "NVIDIA GeForce GTX TITAN Z"},
{0x10de, 0x0fed, "NVIDIA GeForce 820M"},
{0x10de, 0x1340, "NVIDIA GeForce 830M"},
{0x10de, 0x1341, "NVIDIA GeForce 840M"},
{0x10de, 0x1344, "NVIDIA GeForce 845M"},
{0x10de, 0x1391, "NVIDIA GeForce GTX 850M"},
{0x10de, 0x1392, "NVIDIA GeForce GTX 860M"},
{0x10de, 0x119a, "NVIDIA GeForce GTX 860M"},
{0x10de, 0x1199, "NVIDIA GeForce GTX 870M"},
{0x10de, 0x1198, "NVIDIA GeForce GTX 880M"},
{0x10de, 0x1347, "NVIDIA GeForce 940M"},
{0x10de, 0x1402, "NVIDIA GeForce GTX 950"},
{0x10de, 0x139a, "NVIDIA GeForce GTX 950M"},
{0x10de, 0x1401, "NVIDIA GeForce GTX 960"},
{0x10de, 0x139b, "NVIDIA GeForce GTX 960M"},
{0x10de, 0x13c2, "NVIDIA GeForce GTX 970"},
{0x10de, 0x13d8, "NVIDIA GeForce GTX 970M"},
{0x10de, 0x13c0, "NVIDIA GeForce GTX 980"},
{0x10de, 0x17c8, "NVIDIA GeForce GTX 980 Ti"},
{0x10de, 0x1d01, "NVIDIA GeForce GT 1030"},
{0x10de, 0x1c81, "NVIDIA GeForce GTX 1050"},
{0x10de, 0x1c82, "NVIDIA GeForce GTX 1050 Ti"},
{0x10de, 0x1c02, "NVIDIA GeForce GTX 1060 3GB"},
{0x10de, 0x1c03, "NVIDIA GeForce GTX 1060"},
{0x10de, 0x1c20, "NVIDIA GeForce GTX 1060M"},
{0x10de, 0x1b81, "NVIDIA GeForce GTX 1070"},
{0x10de, 0x1be1, "NVIDIA GeForce GTX 1070M"},
{0x10de, 0x1b80, "NVIDIA GeForce GTX 1080"},
{0x10de, 0x1be0, "NVIDIA GeForce GTX 1080M"},
{0x10de, 0x1b06, "NVIDIA GeForce GTX 1080 Ti"},
{0x10de, 0x1b00, "NVIDIA TITAN X (Pascal)"},
{0x10de, 0x1d81, "NVIDIA TITAN V"},
{0x10de, 0x1f82, "NVIDIA GeForce GTX 1650"},
{0x10de, 0x2187, "NVIDIA GeForce GTX 1650 SUPER"},
{0x10de, 0x21c4, "NVIDIA GeForce GTX 1660 SUPER"},
{0x10de, 0x2182, "NVIDIA GeForce GTX 1660 Ti"},
{0x10de, 0x1f08, "NVIDIA GeForce RTX 2060"},
{0x10de, 0x1f07, "NVIDIA GeForce RTX 2070"},
{0x10de, 0x1e87, "NVIDIA GeForce RTX 2080"},
{0x10de, 0x1e07, "NVIDIA GeForce RTX 2080 Ti"},
{0x10de, 0x2507, "NVIDIA GeForce RTX 3050"},
{0x10de, 0x2544, "NVIDIA GeForce RTX 3060"},
{0x10de, 0x2504, "NVIDIA GeForce RTX 3060 (Low Hash Rate)"},
{0x10de, 0x2414, "NVIDIA GeForce RTX 3060 Ti (GA103)"},
{0x10de, 0x2486, "NVIDIA GeForce RTX 3060 Ti (GA104)"},
{0x10de, 0x2489, "NVIDIA GeForce RTX 3060 Ti (GA104, Low Hash Rate)"},
{0x10de, 0x2484, "NVIDIA GeForce RTX 3070"},
{0x10de, 0x2488, "NVIDIA GeForce RTX 3070 (Low Hash Rate)"},
{0x10de, 0x249d, "NVIDIA GeForce RTX 3070 (mobile)"},
{0x10de, 0x2482, "NVIDIA GeForce RTX 3070 Ti"},
{0x10de, 0x2206, "NVIDIA GeForce RTX 3080 10GB"},
{0x10de, 0x2216, "NVIDIA GeForce RTX 3080 10GB (Low Hash Rate)"},
{0x10de, 0x220a, "NVIDIA GeForce RTX 3080 12GB"},
{0x10de, 0x2208, "NVIDIA GeForce RTX 3080 Ti"},
{0x10de, 0x2204, "NVIDIA GeForce RTX 3090"},
{0x10de, 0x2203, "NVIDIA GeForce RTX 3090 Ti"},
{0x10de, 0x1eb8, "NVIDIA Tesla T4"},
{0x10de, 0x2236, "NVIDIA Ampere A10"},
{0x10de, 0x2882, "NVIDIA GeForce RTX 4060"},
{0x10de, 0x28a0, "NVIDIA GeForce RTX 4060M"},
{0x10de, 0x2803, "NVIDIA GeForce RTX 4060 Ti 8GB"},
{0x10de, 0x2805, "NVIDIA GeForce RTX 4060 Ti 16GB"},
{0x10de, 0x2786, "NVIDIA GeForce RTX 4070"},
{0x10de, 0x2783, "NVIDIA GeForce RTX 4070 SUPER"},
{0x10de, 0x2782, "NVIDIA GeForce RTX 4070 Ti"},
{0x10de, 0x2705, "NVIDIA GeForce RTX 4070 Ti SUPER"},
{0x10de, 0x2704, "NVIDIA GeForce RTX 4080"},
{0x10de, 0x2702, "NVIDIA GeForce RTX 4080 SUPER"},
{0x10de, 0x2684, "NVIDIA GeForce RTX 4090"},
{0x1002, 0x5246, "ATI Rage Fury"},
{0x1002, 0x5144, "ATI RADEON 7200 SERIES"},
{0x1002, 0x514c, "ATI RADEON 8500 SERIES"},
{0x1002, 0x4144, "ATI Radeon 9500"},
{0x1002, 0x5955, "ATI RADEON XPRESS 200M Series"},
{0x1002, 0x5e4c, "ATI Radeon X700 SE"},
{0x1002, 0x71c2, "ATI Radeon X1600 Series"},
{0x1002, 0x94c7, "ATI Mobility Radeon HD 2350"},
{0x1002, 0x9581, "ATI Mobility Radeon HD 2600"},
{0x1002, 0x9400, "ATI Radeon HD 2900 XT"},
{0x1002, 0x9620, "ATI Radeon HD 3200 Graphics"},
{0x1002, 0x9515, "ATI Radeon HD 3850 AGP"},
{0x1002, 0x9712, "ATI Mobility Radeon HD 4200"},
{0x1002, 0x954f, "ATI Radeon HD 4350"},
{0x1002, 0x9495, "ATI Radeon HD 4600 Series"},
{0x1002, 0x944e, "ATI Radeon HD 4700 Series"},
{0x1002, 0x944c, "ATI Radeon HD 4800 Series"},
{0x1002, 0x68f9, "ATI Radeon HD 5400 Series"},
{0x1002, 0x68d8, "ATI Radeon HD 5600 Series"},
{0x1002, 0x68be, "ATI Radeon HD 5700 Series"},
{0x1002, 0x6898, "ATI Radeon HD 5800 Series"},
{0x1002, 0x689c, "ATI Radeon HD 5900 Series"},
{0x1002, 0x9803, "AMD Radeon HD 6300 series Graphics"},
{0x1002, 0x6770, "AMD Radeon HD 6400 Series"},
{0x1002, 0x9644, "AMD Radeon HD 6410D"},
{0x1002, 0x9648, "AMD Radeon HD 6480G"},
{0x1002, 0x6760, "AMD Radeon HD 6490M"},
{0x1002, 0x9640, "AMD Radeon HD 6550D"},
{0x1002, 0x6758, "AMD Radeon HD 6600 Series"},
{0x1002, 0x6741, "AMD Radeon HD 6600M Series"},
{0x1002, 0x68ba, "AMD Radeon HD 6700 Series"},
{0x1002, 0x6739, "AMD Radeon HD 6800 Series"},
{0x1002, 0x6719, "AMD Radeon HD 6900 Series"},
{0x1002, 0x9901, "AMD Radeon HD 7660D"},
{0x1002, 0x683d, "AMD Radeon HD 7700 Series"},
{0x1002, 0x6819, "AMD Radeon HD 7800 Series"},
{0x1002, 0x6818, "AMD Radeon HD 7870 Series"},
{0x1002, 0x679a, "AMD Radeon HD 7900 Series"},
{0x1002, 0x6660, "AMD Radeon HD 8600M Series"},
{0x1002, 0x6610, "AMD Radeon HD 8670"},
{0x1002, 0x665c, "AMD Radeon HD 8770"},
{0x1002, 0x9830, "AMD Radeon HD 8400 / R3 Series"},
{0x1002, 0x130f, "AMD Radeon(TM) R7 Graphics"},
{0x1002, 0x6939, "AMD Radeon R9 285"},
{0x1002, 0x67b1, "AMD Radeon R9 290"},
{0x1002, 0x67b0, "AMD Radeon R9 290X"},
{0x1002, 0x7300, "AMD Radeon (TM) R9 Fury Series"},
{0x1002, 0x6821, "AMD Radeon R9 M370X"},
{0x1002, 0x6647, "AMD Radeon R9 M380"},
{0x1002, 0x6920, "AMD Radeon R9 M395X"},
{0x1002, 0x67ef, "Radeon(TM) RX 460 Graphics"},
{0x1002, 0x67df, "Radeon (TM) RX 480 Graphics"},
{0x1002, 0x73df, "AMD Radeon RX 6700 XT"},
{0x1002, 0x687f, "Radeon RX Vega"},
{0x1002, 0x69af, "Radeon Pro Vega 20"},
{0x1002, 0x15dd, "AMD Radeon(TM) Vega 10 Mobile Graphics"},
{0x1002, 0x66af, "Radeon RX Vega 20"},
{0x1002, 0x731f, "Radeon RX 5700 / 5700 XT"},
{0x1002, 0x7340, "Radeon RX 5500M"},
{0x1002, 0x73bf, "Radeon RX 6800/6800 XT / 6900 XT"},
{0x1002, 0x7480, "AMD Radeon RX 7600 XT"},
{0x1002, 0x7590, "AMD Radeon RX 9060 XT"},
{0x1002, 0x73a1, "Radeon Pro V620"},
{0x1002, 0x73ae, "Radeon Pro V620 VF"},
{0x1002, 0x163f, "AMD VANGOGH"},
{0x1002, 0x164e, "AMD Radeon(TM) Graphics"},
{0x8086, 0x3577, "Intel(R) 82830M Graphics Controller"},
{0x8086, 0x3582, "Intel(R) 82852/82855 GM/GME Graphics Controller"},
{0x8086, 0x2562, "Intel(R) 845G"},
{0x8086, 0x2572, "Intel(R) 82865G Graphics Controller"},
{0x8086, 0x2582, "Intel(R) 82915G/GV/910GL Express Chipset Family"},
{0x8086, 0x258a, "Intel(R) E7221G"},
{0x8086, 0x2592, "Mobile Intel(R) 915GM/GMS,910GML Express Chipset Family"},
{0x8086, 0x2772, "Intel(R) 945G"},
{0x8086, 0x27a2, "Mobile Intel(R) 945GM Express Chipset Family"},
{0x8086, 0x27ae, "Intel(R) 945GME"},
{0x8086, 0x29b2, "Intel(R) Q35"},
{0x8086, 0x29c2, "Intel(R) G33"},
{0x8086, 0x29d2, "Intel(R) Q33"},
{0x8086, 0xa001, "Intel(R) IGD"},
{0x8086, 0xa011, "Intel(R) IGD"},
{0x8086, 0x2992, "Intel(R) 965Q"},
{0x8086, 0x2982, "Intel(R) 965G"},
{0x8086, 0x2972, "Intel(R) 946GZ"},
{0x8086, 0x2a02, "Mobile Intel(R) 965 Express Chipset Family"},
{0x8086, 0x2a12, "Intel(R) 965GME"},
{0x8086, 0x2a42, "Mobile Intel(R) GM45 Express Chipset Family"},
{0x8086, 0x2e02, "Intel(R) Integrated Graphics Device"},
{0x8086, 0x2e22, "Intel(R) G45/G43"},
{0x8086, 0x2e12, "Intel(R) Q45/Q43"},
{0x8086, 0x2e32, "Intel(R) G41"},
{0x8086, 0x2e92, "Intel(R) B43"},
{0x8086, 0x0042, "Intel(R) HD Graphics"},
{0x8086, 0x0046, "Intel(R) HD Graphics"},
{0x8086, 0x0122, "Intel(R) HD Graphics 3000"},
{0x8086, 0x0126, "Intel(R) HD Graphics 3000"},
{0x8086, 0x010a, "Intel(R) HD Graphics Family"},
{0x8086, 0x0162, "Intel(R) HD Graphics 4000"},
{0x8086, 0x0166, "Intel(R) HD Graphics 4000"},
{0x8086, 0x015a, "Intel(R) HD Graphics Family"},
{0x8086, 0x0412, "Intel(R) HD Graphics 4600"},
{0x8086, 0x0416, "Intel(R) HD Graphics 4600"},
{0x8086, 0x0a26, "Intel(R) HD Graphics 5000"},
{0x8086, 0x0422, "Intel(R) HD Graphics 5000"},
{0x8086, 0x0a22, "Intel(R) Iris(TM) Graphics 5100"},
{0x8086, 0x0a2a, "Intel(R) Iris(TM) Graphics 5100"},
{0x8086, 0x0a2b, "Intel(R) Iris(TM) Graphics 5100"},
{0x8086, 0x0a2e, "Intel(R) Iris(TM) Graphics 5100"},
{0x8086, 0x0d22, "Intel(R) Iris(TM) Pro Graphics 5200"},
{0x8086, 0x0d26, "Intel(R) Iris(TM) Pro Graphics 5200"},
{0x8086, 0x0d2a, "Intel(R) Iris(TM) Pro Graphics 5200"},
{0x8086, 0x0d2b, "Intel(R) Iris(TM) Pro Graphics 5200"},
{0x8086, 0x0d2e, "Intel(R) Iris(TM) Pro Graphics 5200"},
{0x8086, 0x0c22, "Intel(R) Iris(TM) Pro Graphics 5200"},
{0x8086, 0x161e, "Intel(R) HD Graphics 5300"},
{0x8086, 0x1616, "Intel(R) HD Graphics 5500"},
{0x8086, 0x1612, "Intel(R) HD Graphics 5600"},
{0x8086, 0x1626, "Intel(R) HD Graphics 6000"},
{0x8086, 0x162b, "Intel(R) Iris(TM) Graphics 6100"},
{0x8086, 0x1622, "Intel(R) Iris(TM) Pro Graphics 6200"},
{0x8086, 0x162a, "Intel(R) Iris(TM) Pro Graphics P6300"},
{0x8086, 0x1902, "Intel(R) HD Graphics 510"},
{0x8086, 0x1906, "Intel(R) HD Graphics 510"},
{0x8086, 0x190b, "Intel(R) HD Graphics 510"},
{0x8086, 0x191e, "Intel(R) HD Graphics 515"},
{0x8086, 0x1916, "Intel(R) HD Graphics 520"},
{0x8086, 0x1921, "Intel(R) HD Graphics 520"},
{0x8086, 0x1912, "Intel(R) HD Graphics 530"},
{0x8086, 0x191b, "Intel(R) HD Graphics 530"},
{0x8086, 0x191d, "Intel(R) HD Graphics P530"},
{0x8086, 0x1926, "Intel(R) Iris(TM) Graphics 540"},
{0x8086, 0x1927, "Intel(R) Iris(TM) Graphics 550"},
{0x8086, 0x192b, "Intel(R) Iris(TM) Graphics 555"},
{0x8086, 0x192d, "Intel(R) Iris(TM) Graphics P555"},
{0x8086, 0x1932, "Intel(R) Iris(TM) Pro Graphics 580"},
{0x8086, 0x193b, "Intel(R) Iris(TM) Pro Graphics 580"},
{0x8086, 0x193a, "Intel(R) Iris(TM) Pro Graphics P580"},
{0x8086, 0x193d, "Intel(R) Iris(TM) Pro Graphics P580"},
{0x8086, 0x87c0, "Intel(R) UHD Graphics 617"},
{0x8086, 0x3ea0, "Intel(R) UHD Graphics 620"},
{0x8086, 0x5917, "Intel(R) UHD Graphics 620"},
{0x8086, 0x591e, "Intel(R) HD Graphics 615"},
{0x8086, 0x5916, "Intel(R) HD Graphics 620"},
{0x8086, 0x5912, "Intel(R) HD Graphics 630"},
{0x8086, 0x591b, "Intel(R) HD Graphics 630"},
{0x8086, 0x3e9b, "Intel(R) UHD Graphics 630"},
{0x8086, 0x3e91, "Intel(R) UHD Graphics 630"},
};
static inline const char *wine_device_name(uint32_t vendor_id, uint32_t device_id, const char *native_name) {
for (size_t i = 0; i < sizeof(wine_gpu_names) / sizeof(wine_gpu_names[0]); i++) {
if (wine_gpu_names[i].vendor_id == vendor_id && wine_gpu_names[i].device_id == device_id) {
return wine_gpu_names[i].name;
}
}
return native_name;
}
#endif
-104
View File
@@ -1,104 +0,0 @@
#!/usr/bin/env python3
"""Synchronize GPU names with Wine without rewriting the surrounding header."""
import os
from pathlib import Path
import re
import subprocess
import tempfile
from urllib.request import urlopen
ROOT = Path(__file__).resolve().parents[1]
HEADER = ROOT / "build-aux/src/wine_gpu_names.h"
WINE_REPOSITORY = "https://github.com/wine-mirror/wine.git"
WINE_SOURCE = "dlls/win32u/sysparams.c"
NETWORK_TIMEOUT = 30
MAX_SOURCE_BYTES = 2 * 1024 * 1024
C_STRING = r'"(?:[^"\\\r\n]|\\[^\r\n])*"'
WINE_ROW = re.compile(
r'case\s+MAKELONG\(\s*(0x[0-9a-fA-F]+)\s*,\s*(0x[0-9a-fA-F]+)\s*\)'
r'\s*:\s*return\s+(' + C_STRING + r')\s*;'
)
HEADER_ROW = re.compile(
r'^ \{(0x[0-9a-fA-F]+), (0x[0-9a-fA-F]+), (' + C_STRING + r')\},$', re.M,
)
TABLE = re.compile(r'(\} wine_gpu_names\[\] = \{\n)(.*?)(\n\};)', re.S)
def parse_wine_names(source):
function = re.search(
r'\bconst char\s*\*gpu_device_name\([^)]*\)\s*\{(.*?)\n\};', source, re.S,
)
if function is None:
raise ValueError("Wine gpu_device_name() was not found")
body = function.group(1)
rows = WINE_ROW.findall(body)
if not rows or len(rows) != len(re.findall(r'\bcase\b', body)):
raise ValueError("Wine GPU table is empty or contains unsupported cases")
result = []
seen = set()
for vendor, device, name in rows:
identity = (int(vendor, 16), int(device, 16))
if identity in seen or any(value > 0xffff for value in identity) or name == '""':
raise ValueError(f"Invalid or duplicate Wine GPU entry: {vendor}:{device}")
seen.add(identity)
result.append((f"0x{identity[0]:04x}", f"0x{identity[1]:04x}", name))
return result
def update_header(header, source, revision):
if not re.fullmatch(r'[0-9a-f]{40}', revision):
raise ValueError("Invalid Wine source revision")
rows = parse_wine_names(source)
tables = list(TABLE.finditer(header))
if len(tables) != 1:
raise ValueError("Expected exactly one wine_gpu_names array in the header")
table = tables[0]
existing = HEADER_ROW.findall(table.group(2))
if not existing or len(existing) != len(table.group(2).strip().splitlines()):
raise ValueError("Unsupported existing header table format")
if rows == existing:
return header
replacement = "\n".join(f" {{{vendor}, {device}, {name}}}," for vendor, device, name in rows)
updated = header[:table.start(2)] + replacement + header[table.end(2):]
updated, count = re.subn(r'^// Revision: [0-9a-f]{40}$', f"// Revision: {revision}", updated, flags=re.M)
if count != 1:
raise ValueError("Expected exactly one Wine revision comment")
return updated
def main():
print("Resolving Wine master revision...", flush=True)
refs = subprocess.run(
["git", "ls-remote", WINE_REPOSITORY, "refs/heads/master"],
capture_output=True, text=True, check=True, timeout=NETWORK_TIMEOUT,
).stdout.split()
if len(refs) != 2 or not re.fullmatch(r'[0-9a-f]{40}', refs[0]):
raise ValueError("Could not resolve Wine master revision")
revision = refs[0]
url = f"https://raw.githubusercontent.com/wine-mirror/wine/{revision}/{WINE_SOURCE}"
print(f"Fetching Wine GPU names at {revision}...", flush=True)
with urlopen(url, timeout=NETWORK_TIMEOUT) as response:
source = response.read(MAX_SOURCE_BYTES + 1)
if len(source) > MAX_SOURCE_BYTES:
raise ValueError("Wine source exceeds the download size limit")
header = HEADER.read_text(encoding="utf-8")
updated = update_header(header, source.decode("utf-8"), revision)
if updated == header:
print("Wine GPU names are unchanged.")
return
temporary = None
try:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=HEADER.parent, delete=False) as output:
temporary = Path(output.name)
output.write(updated)
temporary.chmod(HEADER.stat().st_mode & 0o777)
os.replace(temporary, HEADER)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
print(f"Updated {len(parse_wine_names(source.decode('utf-8')))} Wine GPU names.")
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
# macOS support (source installation)
The native macOS path uses macOS Wine builds, not the Linux PortProton runtime.
Linux continues to use the existing PortProton scripts. This is an unsigned source
installation, **not** a signed/notarized `.app` or a claim of macOS hardware testing.
## Build and run
Install Python 3.11 or newer, Xcode Command Line Tools, Meson, Ninja, pkg-config,
SDL3 and libarchive. With Homebrew, the native libraries/build tools are available
as `sdl3`, `libarchive`, `meson`, `ninja`, and `pkgconf`. Install the project's Python
dependencies in a virtual environment using the existing project workflow. Ensure
libarchive and SDL3 are discoverable by the dynamic loader/pkg-config; Homebrew's
Apple Silicon prefix is usually `/opt/homebrew`, Intel's is usually `/usr/local`.
Build/install with the virtual environment's Python, for example:
```sh
meson setup builddir --prefix="$VIRTUAL_ENV"
meson compile -C builddir
meson install -C builddir
portprotonqt
```
Meson builds `libportprotonqt_gamepad.dylib` against SDL3 and installs it beside the
Python modules. The Linux Vulkan GPU inspection executable is not built on macOS.
Running directly from an unbuilt checkout still requires the native gamepad
library; do not rename a Linux `.so` to `.dylib`. A distributor must separately
bundle Python/Qt/SDL3/libarchive, set appropriate install names/rpaths, handle
architecture-specific dependencies, and sign/notarize the completed application.
No `.app` packaging, signing identity, or Gatekeeper bypass is supplied here.
## Supported workflow
* Start the application without installing or running the Linux bootstrap.
* Use the existing Wine manager to browse the macOS catalog directly from
<https://git.linux-gaming.ru/Boria138/PortProton-Wine-Metadata/raw/branch/main/macos_wine_metadata.json>.
The catalog groups include Wine Crossover, macOS Wine builds, Sikarugir engines,
and Game Porting Toolkit engines. Catalog inclusion is not a compatibility
guarantee; review each upstream project's license and macOS/CPU requirements.
* Install each catalog version in its own managed directory. Archive extraction
retains the existing traversal/link checks. Plain `bin/wine[64]`, common Wine
`.app` layouts, and `wswine.bundle/bin/wine[64]` are recognized. Entries whose
archive layout does not expose one of those binaries cannot be launched.
* Select installed Wine versions and prefixes in the existing game settings.
Wine/prefix settings are the supported macOS game settings. Linux graphics,
synchronization and anticheat overrides are not silently applied.
* Launch Windows EXEs through the existing game/EXE UI and its owned process
tracking, or directly through the native adapter:
```sh
python -m portprotonqt.macos '/path/to/Game.exe' 'argument with spaces'
```
The adapter preserves arguments without a shell and replaces its own process
with Wine, allowing the normal launcher stop/shutdown path to own the process.
Wine configuration, registry editor, file manager, command prompt and uninstaller
use the selected engine and prefix through the Wine tab. Tool processes are
retained and terminated/waited during application shutdown.
* Remove installed engines through the existing installed-versions manager.
The default data directory is
`~/Library/Application Support/PortProtonQt`; an explicit `PORT_DATA_PATH` overrides
it. Engines live under `data/dist/<catalog name>`, prefixes under
`data/prefixes/<prefix name>`, and global Wine settings in `data/user.conf`.
Per-EXE settings remain `<executable>.ppdb`. Configuration values are parsed as
assignments, never sourced as shell code. If no engine is selected, the adapter
uses the first usable managed engine or `wine` on PATH; an explicitly selected
missing engine fails rather than launching another engine unexpectedly.
On Apple Silicon, x86_64 Wine builds generally require Rosetta 2 and a compatible
macOS release. Install Rosetta using Apple's documented workflow if required.
This project does not install it, choose a CPU architecture automatically, or
make incompatible Wine distributions compatible. No private, machine-specific
application bundle is used. NTLM-enabled applications may additionally need an
upstream-supported `ntlm_auth` installation (for example Samba).
## Limits and verification
Linux D-Bus/system management is disabled on macOS; system power, audio, Bluetooth,
network and storage controls are not ported. SDL gamepad navigation remains available,
but Linux `/dev/uinput` virtual-mouse emulation is disabled. Linux PortProton autoinstall scripts,
runtime downloads, Gamescope, MangoHud, vkBasalt, Linux Steam compatibility-tool
registration, Linux XDG autostart, ISO mounting and store-specific Wine wrappers
are not supported macOS workflows. Use local EXEs and macOS Wine engines. Basic
Wine tools are supported, but prefix reset/default-prefix copying and Linux
runtime-specific tools are not. Unsupported native-adapter CLI operations fail
with an error rather than executing Linux scripts.
The current macOS catalog supplies URLs and human-readable sizes, **not SHA256
checksums**. Downloads use HTTPS and existing extraction checks; this is not
cryptographic artifact verification. Failed/partial extractions may remain for
inspection and can be retried or removed; they count as installed only if a usable
Wine executable is present.
Regression tests mock the host, catalog network, executable handoff, settings and
shutdown. Linux CI cannot validate Mach-O loading, Rosetta, Wine runtime behavior,
Qt appearance, signing or actual macOS gameplay. Those require a real macOS
installation and remain release validation work.
Assisted-by: pz:gpt-6.1-sol
+3 -2
View File
@@ -40,8 +40,6 @@ pkgdatadir = pythondir / meson.project_name()
cc = meson.get_compiler('c')
sdl3_dep = dependency('sdl3', required: true)
gamepad_sources = files('build-aux/src/gamepad_backend.c')
keyboard_deps = [dependency('wayland-client'), dependency('xkbcommon'), dependency('x11')]
keyboard_sources = files('build-aux/src/keyboard_backend.c')
# Install Python package
subdir('portprotonqt')
@@ -59,6 +57,7 @@ install_data(configured_portprotonqt,
rename: 'portprotonqt',
)
if host_machine.system() != 'darwin'
# Build and install vk_gpu_info executable
vk_gpu_info_sources = files('build-aux/src/vk_gpu_info.c')
vk_gpu_info_deps = [dependency('vulkan', required: true)]
@@ -71,6 +70,8 @@ executable('vk_gpu_info',
c_args: ['-std=c99'],
)
endif
# Install desktop file
install_data(
'build-aux/share/applications/ru.linux_gaming.PortProtonQt.desktop',
+9 -8
View File
@@ -816,13 +816,14 @@ def main():
except (OSError, RequestException):
logger.exception("Failed to update gogdl")
gogdl_update_worker = GOGDLUpdateWorker(window.gog_api)
window.gogdlUpdateWorker = gogdl_update_worker
gogdl_update_worker.finished.connect(
lambda: setattr(window, "gogdlUpdateWorker", None)
)
gogdl_update_worker.finished.connect(gogdl_update_worker.deleteLater)
gogdl_update_worker.start()
if sys.platform != "darwin":
gogdl_update_worker = GOGDLUpdateWorker(window.gog_api)
window.gogdlUpdateWorker = gogdl_update_worker
gogdl_update_worker.finished.connect(
lambda: setattr(window, "gogdlUpdateWorker", None)
)
gogdl_update_worker.finished.connect(gogdl_update_worker.deleteLater)
gogdl_update_worker.start()
# Execute the initial PortProton command after the UI is set up
class InitialCommandWorker(QThread):
@@ -889,7 +890,7 @@ def main():
self.finished.emit()
# Initial setup can stop Wine and must not race a silent game launch.
if start_sh and not silent_game_request:
if start_sh and not silent_game_request and sys.platform != "darwin":
worker = InitialCommandWorker(start_sh)
window.initialCommandWorker = worker
worker.finished.connect(
+6
View File
@@ -410,6 +410,8 @@ def add_steam_compat_tool(force_install: bool = False) -> bool:
Returns:
True if successful, False otherwise
"""
if sys.platform == "darwin":
return False
steam_home = get_steam_home()
if not steam_home:
print("Steam directory not found")
@@ -591,6 +593,8 @@ def reinstall_steam_compat_tool() -> bool:
def remove_steam_compat_tool() -> bool:
"""Remove PortProtonQt Steam compatibility tool from user Steam directory."""
if sys.platform == "darwin":
return False
steam_home = get_steam_home()
if not steam_home:
print("Steam directory not found")
@@ -647,6 +651,8 @@ def reset_settings() -> bool:
def is_steam_compat_tool_installed() -> bool:
"""Check if PortProtonQt is installed as Steam compatibility tool."""
if sys.platform == "darwin":
return False
steam_home = get_steam_home()
if not steam_home:
return False
+9
View File
@@ -114,6 +114,11 @@ def read_portdata_path_from_config() -> str | None:
def get_portproton_location() -> str | None:
"""Return PortProton directory path."""
if sys.platform == "darwin":
from portprotonqt.macos import data_root
root = data_root()
root.mkdir(parents=True, exist_ok=True)
return str(root)
if os.getenv("FLATPAK_ID"):
portdata_path = os.getenv("XDG_DATA_HOME", "").strip()
if portdata_path:
@@ -153,6 +158,8 @@ def save_portdata_path_to_config(portdata_path: str) -> bool:
def get_portproton_scripts_path() -> str | None:
"""Return PortProton scripts directory path."""
if sys.platform == "darwin":
return None
appdir_prefix = os.getenv("APPDIR")
sharun_prefix = os.getenv("SHARUN_DIR")
appimage_path = os.getenv("APPIMAGE", "").strip()
@@ -191,6 +198,8 @@ def get_portproton_scripts_path() -> str | None:
def get_portproton_start_command() -> list[str] | None:
"""Return command list for PortProton launch."""
if sys.platform == "darwin":
return [sys.executable, "-m", "portprotonqt.macos"]
global _portproton_start_command
if _portproton_start_command is not None:
return _portproton_start_command
+7 -2
View File
@@ -1,11 +1,10 @@
"""UI configuration settings."""
import asyncio
import os
import sys
import subprocess
from typing import Any, cast
from dbus_fast import BusType
from dbus_fast.aio import MessageBus
from portprotonqt.config.base import BaseConfig, configparser, THEMES_DIRS
from portprotonqt.config.validators import validate_string, validate_int, validate_bool
@@ -13,6 +12,10 @@ from portprotonqt.localization import get_theme_translations
from portprotonqt.logger import get_logger
if sys.platform != "darwin":
from dbus_fast import BusType
from dbus_fast.aio import MessageBus
logger = get_logger(__name__)
THEME_VARIANTS = ("dark", "light", "auto")
DOWNLOADS_SECTION = "Downloads"
@@ -204,6 +207,8 @@ def _is_qt_light_theme() -> bool:
def _is_system_light_theme() -> bool:
if sys.platform == "darwin":
return _is_qt_light_theme()
is_dark = _is_portal_dark_theme()
if is_dark is None:
is_dark = _is_gsettings_dark_theme()
+3
View File
@@ -1,6 +1,7 @@
"""Detail pages for PortProtonQt."""
import os
import sys
import weakref
from collections.abc import Callable, Sequence
@@ -616,6 +617,8 @@ class DetailPageManager:
play_button.setIcon(
self.main_window.theme_manager.get_icon("update", as_path=True)
)
if sys.platform == "darwin" and source in {"gog", "egs"}:
play_button.setEnabled(False)
buttons_layout.addWidget(play_button)
if source in {"steam", "gog", "egs"} and appid:
+16 -3
View File
@@ -1,6 +1,8 @@
"""Proton Manager dialog for PortProtonQt."""
import os
import sys
from pathlib import Path
import platform
import shutil
import tempfile
@@ -374,6 +376,8 @@ class ProtonManager(DraggableDialog):
return True
def filter_entries_by_cpu_level(self, entries, source_name):
if sys.platform == "darwin":
return entries
is_arm = platform.machine().lower().startswith(('arm', 'aarch64'))
filtered_entries = []
for entry in entries:
@@ -471,7 +475,7 @@ class ProtonManager(DraggableDialog):
url = entry.get('url', '')
filename = entry.get('name', '')
size_human = entry.get('size_human', _('Unknown'))
if url:
if url and sys.platform != "darwin":
parsed_url = urllib.parse.urlparse(url)
url_filename = os.path.basename(parsed_url.path)
if url_filename:
@@ -539,6 +543,9 @@ class ProtonManager(DraggableDialog):
def is_asset_installed(self, asset_filename, source_name):
if not self.portproton_location:
return False
if sys.platform == "darwin":
from portprotonqt.macos import find_wine, version_directory
return find_wine(version_directory(Path(self.portproton_location), asset_filename)) is not None
name_without_ext = asset_filename
for ext in ['.tar.gz', '.tar.xz']:
if name_without_ext.lower().endswith(ext):
@@ -562,6 +569,9 @@ class ProtonManager(DraggableDialog):
return source == "proton_lg" and (asset.startswith("wine"))
def get_download_extract_dir(self, asset_data: dict) -> str:
if sys.platform == "darwin":
from portprotonqt.macos import version_directory
return str(version_directory(Path(self.portproton_location), asset_data["asset_name"]))
install_to_dist = self.should_install_to_dist(
asset_data['source_name'], asset_data['asset_name']
)
@@ -629,7 +639,7 @@ class ProtonManager(DraggableDialog):
installed_versions = []
seen_paths = set()
version_dirs = [dist_path]
if not ui_config.get_disable_steam_proton_scanning():
if sys.platform != "darwin" and not ui_config.get_disable_steam_proton_scanning():
steam_dir = get_steam_compatibilitytools_dir()
if steam_dir is not None:
version_dirs.append(str(steam_dir))
@@ -653,6 +663,9 @@ class ProtonManager(DraggableDialog):
return installed_versions
def is_installed_version_dir(self, version_path: str) -> bool:
if sys.platform == "darwin":
from portprotonqt.macos import find_wine
return not Path(version_path).name.startswith(".") and find_wine(Path(version_path)) is not None
if not os.path.isdir(version_path):
return False
if os.path.isfile(os.path.join(version_path, "bin", "wine")):
@@ -1023,7 +1036,7 @@ class ProtonManager(DraggableDialog):
import subprocess
try:
start_cmd = get_portproton_start_command()
if start_cmd and not self.initial_command_executed:
if start_cmd and not self.initial_command_executed and sys.platform != "darwin":
result = subprocess.run(start_cmd + ["cli", "--initial"], timeout=10)
if result.returncode != 0:
logger.warning(f"Initial PortProton command returned non-zero exit code: {result.returncode}")
+6 -4
View File
@@ -1,6 +1,7 @@
"""Settings dialog for PortProtonQt."""
import os
import sys
import re
import subprocess
from html import escape
@@ -418,10 +419,11 @@ class ExeSettingsDialog(
self.tab_widget.addTab(self.main_tab, _("Main"))
self.tab_widget.addTab(self.advanced_tab, _("Advanced"))
self.tab_widget.addTab(self.mangohud_tab, "MangoHud")
self.tab_widget.addTab(self.vkbasalt_tab, "vkBasalt")
if self.gamescope_available:
self.tab_widget.addTab(self.gamescope_tab, "Gamescope")
if sys.platform != "darwin":
self.tab_widget.addTab(self.mangohud_tab, "MangoHud")
self.tab_widget.addTab(self.vkbasalt_tab, "vkBasalt")
if self.gamescope_available:
self.tab_widget.addTab(self.gamescope_tab, "Gamescope")
self.settings_table = QTableWidget()
self.settings_table.setAlternatingRowColors(True)
+21
View File
@@ -1,6 +1,9 @@
"""Wine archive extractor for PortProtonQt."""
import os
import sys
import shutil
import tempfile
import time
import libarchive
from PySide6.QtCore import QThread, Signal, QMutex
@@ -46,7 +49,13 @@ class ExtractionThread(QThread):
return target_path
def run(self):
destination = self.extract_dir
staging = None
try:
if sys.platform == "darwin":
os.makedirs(os.path.dirname(destination), exist_ok=True)
staging = tempfile.mkdtemp(prefix=".wine-install-", dir=os.path.dirname(destination))
self.extract_dir = staging
self.progress.emit(0)
self.speed.emit(0.0)
self.eta.emit(0)
@@ -157,6 +166,14 @@ class ExtractionThread(QThread):
except (OSError, PermissionError):
pass
if self._should_stop():
return
if staging is not None:
from pathlib import Path
from portprotonqt.macos import find_wine
if find_wine(Path(staging)) is None:
raise ValueError("Archive does not contain a macOS Wine executable")
os.rename(staging, destination)
self.progress.emit(100)
self.speed.emit(0.0)
self.eta.emit(0)
@@ -168,6 +185,10 @@ class ExtractionThread(QThread):
except Exception as e:
if not self._should_stop():
self.error.emit(str(e))
finally:
self.extract_dir = destination
if staging is not None:
shutil.rmtree(staging, ignore_errors=True)
def stop(self):
self._mutex.lock()
+8
View File
@@ -1,6 +1,7 @@
"""Wine metadata loader for PortProtonQt."""
import os
import sys
import tempfile
import orjson
@@ -104,6 +105,10 @@ class WineLoadingThread(QThread):
else github_url
)
if sys.platform == "darwin":
from portprotonqt.macos import MACOS_WINE_METADATA_URL
json_url = MACOS_WINE_METADATA_URL
with tempfile.NamedTemporaryFile(delete=False, suffix='.json') as tmp:
temp_path = tmp.name
@@ -120,6 +125,9 @@ class WineLoadingThread(QThread):
with open(temp_path, 'rb') as f:
metadata = orjson.loads(f.read())
if sys.platform == "darwin":
from portprotonqt.macos import validate_catalog
validate_catalog(metadata)
logger.info(f"Successfully loaded JSON metadata with {len(metadata)} entries")
self.loading_complete.emit(metadata)
finally:
+11 -2
View File
@@ -1,8 +1,10 @@
from __future__ import annotations
import time
import os
import sys
import math
from typing import Protocol, cast, Any
from evdev import UInput, ecodes
from typing import TYPE_CHECKING, Protocol, cast, Any
from PySide6.QtWidgets import QWidget, QStackedWidget, QApplication, QScrollArea, QMenu, QMessageBox, QTableWidget, QSlider
from PySide6.QtCore import Qt, QObject, Signal, Slot, QTimer, QThread
from portprotonqt.logger import get_logger
@@ -27,6 +29,9 @@ from portprotonqt.input_manager.runtime import GamepadRuntimeMixin
from portprotonqt.input_manager.settings import SettingsInputMixin
from portprotonqt.input_manager.settings_visual import SettingsVisualNavigationMixin
if sys.platform != "darwin" or TYPE_CHECKING:
from evdev import UInput, ecodes
logger = get_logger(__name__)
class MainWindowProtocol(Protocol):
@@ -253,6 +258,10 @@ class InputManager(
def _async_enable_mouse_emulation(self):
"""Asynchronously enable mouse emulation to avoid blocking startup."""
if sys.platform == "darwin":
self.mouse_emulation_enabled = False
logger.info("Virtual mouse emulation is Linux-only")
return
logger.info("EMUL: Attempting to create UInput virtual mouse...")
self.mouse_emulation_thread = MouseEmulationThread()
self.mouse_emulation_thread.finished.connect(self._on_mouse_emulation_finished)
-11
View File
@@ -311,17 +311,6 @@ class DpadInputMixin(InputMixin):
@Slot(int, int, float)
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:
self._reset_dpad_repeat()
return
directions = {PAD_DPAD_X: ('left', 'right'), PAD_AXIS_LEFT_X: ('left', 'right'),
PAD_DPAD_Y: ('up', 'down'), PAD_AXIS_LEFT_Y: ('up', 'down')}
if code in directions:
self._start_dpad_repeat(code, value, current_time)
keyboard.send('direction', directions[code][value > 0])
return
if self._route_surface_dpad(code, value, current_time):
return
self._handle_default_dpad(code, value, current_time)
+8 -56
View File
@@ -57,6 +57,8 @@ class GamepadRuntimeMixin(InputMixin):
def _on_gamepad_hotplug(self, action: str) -> None:
try:
if self._gamepad_polling_suspended:
return
if action == 'add':
self.check_gamepad()
elif action == 'remove':
@@ -78,6 +80,8 @@ class GamepadRuntimeMixin(InputMixin):
def check_gamepad(self) -> None:
try:
if self._gamepad_polling_suspended:
return
new_gamepad = self.find_gamepad()
if new_gamepad:
@@ -124,7 +128,6 @@ class GamepadRuntimeMixin(InputMixin):
self.lt_pressed = False
self.rt_pressed = False
self.start_held = False
self._start_consumed = False
self.select_held = False
self.pending_menu_fullscreen_time = 0.0
self.guide_held = False
@@ -170,9 +173,6 @@ class GamepadRuntimeMixin(InputMixin):
keyboard = getattr(self._parent, "keyboard", None)
if keyboard and hasattr(keyboard, "update_keyboard"):
keyboard.update_keyboard()
system_keyboard = getattr(self._parent, 'system_keyboard', None)
if system_keyboard is not None:
system_keyboard.send('gamepad', self.gamepad_type.value)
def find_gamepad(self) -> SDLGamepad | None:
"""Open the SDL3 handle that combines all connected gamepads."""
@@ -206,9 +206,6 @@ class GamepadRuntimeMixin(InputMixin):
logger.info("Gamepad axes configured for SDL backend: %s", device.name)
def _handle_pending_menu_fullscreen(self, current_time: float) -> None:
if getattr(self, '_gamepad_polling_suspended', False):
self.pending_menu_fullscreen_time = 0.0
return
if not self.pending_menu_fullscreen_time:
return
if current_time < self.pending_menu_fullscreen_time:
@@ -220,10 +217,10 @@ class GamepadRuntimeMixin(InputMixin):
def _poll_button_events(self, gamepad: SDLGamepad, current_time: float) -> None:
"""Emit button changes using SDL's standardized controller mapping."""
# Deliver modifier buttons before their combinations in the same snapshot.
# Deliver Guide before Select when both change in the same SDL snapshot.
buttons = sorted(
SDL_CONTROLLER_BUTTON_TO_PAD.items(),
key=lambda item: (item[1] not in BUTTONS['guide'], item[1] != PAD_BUTTON_START),
key=lambda item: item[1] not in BUTTONS['guide'],
)
for button_index, button_code in buttons:
value = gamepad.get_button(button_index)
@@ -245,8 +242,6 @@ class GamepadRuntimeMixin(InputMixin):
if button_code == PAD_BUTTON_START:
self.start_held = value == 1
emulation_combo = self._handle_emulation_combo(button_code, value)
if self._handle_system_keyboard_input(button_code, value, emulation_combo):
return
if self._is_mouse_emulation_active() and value == 1:
if button_code in BUTTONS['confirm']:
self.click_left()
@@ -270,41 +265,6 @@ class GamepadRuntimeMixin(InputMixin):
self.pending_menu_fullscreen_time = 0.0
return emulation_combo
def _handle_system_keyboard_input(self, button_code: int, value: int, combo: bool) -> bool:
keyboard = getattr(getattr(self, '_parent', None), 'system_keyboard', None)
if keyboard is None:
return False
if combo:
self._start_consumed = True
return True
if button_code == PAD_BUTTON_START:
if value:
self._start_consumed = False
return True
if getattr(self, '_start_consumed', False):
return True
if value and button_code in BUTTONS['prev_dir'] and self.start_held:
self._start_consumed = True
keyboard.toggle()
return True
if keyboard.isVisible():
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:
keyboard.send('button', 'confirm')
else:
for name, action in actions.items():
if button_code in BUTTONS[name]:
if value:
keyboard.send('button', action)
elif name == 'add_game':
keyboard.send('button', 'backspace_release')
break
return True
if button_code == PAD_BUTTON_START and not value:
self.button_event.emit(PAD_BUTTON_START, 1)
return False
def _should_schedule_menu_fullscreen(self, button_code: int, value: int, emulation_combo: bool) -> bool:
return (
value == 1 and button_code in BUTTONS['menu'] and
@@ -387,22 +347,14 @@ 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 False
if getattr(self, '_gamepad_polling_suspended', False):
return True
return self._is_mouse_emulation_active() and QApplication.activeWindow() is not None
def _poll_gamepad(self) -> None:
if not self.running:
if not self.running or self._gamepad_polling_suspended:
return
current_time = time.time()
active_gamepad = self.gamepad
@@ -430,7 +382,7 @@ class GamepadRuntimeMixin(InputMixin):
self._poll_axis_events(active_gamepad, current_time)
if (
current_time - self.last_update >= self.update_interval and
self._is_mouse_emulation_active()
self.mouse_emulation_enabled and self.emulation_active and self.emulation_triggered
):
self.update_mouse_position()
self.last_update = current_time
+193
View File
@@ -0,0 +1,193 @@
"""Native macOS Wine launching; Linux PortProton scripts are not used."""
import os
from pathlib import Path
import re
import shlex
import shutil
import sys
import tempfile
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
MACOS_WINE_METADATA_URL = (
"https://git.linux-gaming.ru/Boria138/PortProton-Wine-Metadata/"
"raw/branch/main/macos_wine_metadata.json"
)
WINE_TOOLS = {
"--winecfg": "winecfg", "--winereg": "regedit", "--winecmd": "cmd",
"--winefile": "winefile", "--wine_uninstaller": "uninstaller",
}
def data_root() -> Path:
"""Respect explicit data paths, otherwise use macOS Application Support."""
explicit = os.environ.get("PORT_DATA_PATH")
if explicit:
return Path(explicit).expanduser()
return Path.home() / "Library" / "Application Support" / "PortProtonQt"
def version_directory(root: Path, name: str) -> Path:
"""Keep catalog version names inside the managed distribution directory."""
if not name or name in (".", "..") or Path(name).name != name:
raise ValueError(f"Invalid Wine version name: {name}")
destination = root / "data" / "dist" / name
if not destination.resolve().is_relative_to((root / "data" / "dist").resolve()):
raise ValueError(f"Wine version escapes distribution directory: {name}")
return destination
def validate_catalog(metadata: object) -> None:
"""Reject unsafe remote names before they become download paths."""
if not isinstance(metadata, dict):
raise ValueError("Invalid macOS Wine catalog")
for entries in metadata.values():
if not isinstance(entries, list):
raise ValueError("Invalid macOS Wine catalog entries")
for entry in entries:
if not isinstance(entry, dict) or not isinstance(entry.get("name"), str):
raise ValueError("Invalid macOS Wine version")
version_directory(data_root(), entry["name"])
if not isinstance(entry.get("url"), str) or not entry["url"].startswith("https://"):
raise ValueError("macOS Wine downloads require HTTPS")
def find_wine(version: Path) -> Path | None:
"""Find Wine in supported plain, application and Wine wrapper layouts."""
candidates = [version / "bin" / "wine", version / "bin" / "wine64"]
candidates.extend(version.glob("Contents/Resources/wine/bin/wine*"))
candidates.extend(version.glob("*.app/Contents/Resources/wine/bin/wine*"))
candidates.extend(version.glob("*.app/Contents/Resources/wine*/bin/wine64"))
candidates.extend(version.glob("wswine.bundle/bin/wine*"))
candidates.extend(version.glob("*/bin/wine*"))
candidates.extend(version.glob("*.app/Contents/SharedSupport/wine/bin/wine*"))
return next((path for path in candidates if path.name in ("wine", "wine64")
and path.is_file() and os.access(path, os.X_OK)), None)
def read_settings(path: Path) -> dict[str, str]:
"""Read shell-style assignments as data, never execute configuration."""
if not path.exists():
return {}
values = {}
for line in path.read_text(encoding="utf-8").splitlines():
fields = shlex.split(line, comments=True)
if fields and fields[0] == "export":
fields = fields[1:]
if len(fields) == 1 and "=" in fields[0]:
key, value = fields[0].split("=", 1)
values[key] = value
return values
def write_settings(path: Path, values: dict[str, str]) -> None:
"""Persist macOS settings without evaluating shell expressions."""
for key, value in values.items():
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key):
raise ValueError(f"Invalid setting name: {key}")
if "\n" in value or "\r" in value:
raise ValueError(f"Setting must contain a single line: {key}")
path.parent.mkdir(parents=True, exist_ok=True)
temporary = None
try:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8",
dir=path.parent, delete=False) as output:
temporary = Path(output.name)
output.write("".join(f"export {key}={shlex.quote(value)}\n"
for key, value in values.items()))
os.replace(temporary, path)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
def wine_command(root: Path, arguments: list[str], settings: dict[str, str]) -> tuple[list[str], dict[str, str]]:
"""Build the native Wine command and isolated prefix environment."""
version = settings.get("PW_WINE_USE") or settings.get("PW_DEFAULT_WINE_USE", "")
system_wine = version == "USE_SYSTEM_WINE"
wine = find_wine(version_directory(root, version)) if version and not system_wine else None
if wine is None and not version:
wine = next((found for child in sorted((root / "data" / "dist").glob("*"))
if not child.name.startswith(".") and (found := find_wine(child)) is not None), None)
executable = str(wine) if wine else (shutil.which("wine") if not version or system_wine else None)
if not executable:
raise FileNotFoundError("Install and select a macOS Wine version in the Wine manager")
prefix = settings.get("PW_PREFIX_NAME") or settings.get("PW_DEFAULT_PREFIX_NAME") or "DEFAULT"
if Path(prefix).name != prefix or prefix in (".", ".."):
raise ValueError("Invalid Wine prefix name")
prefix_path = root / "data" / "prefixes" / prefix
if not prefix_path.resolve().is_relative_to((root / "data" / "prefixes").resolve()):
raise ValueError("Wine prefix escapes prefix directory")
prefix_path.mkdir(parents=True, exist_ok=True)
environment = os.environ.copy()
environment["WINEPREFIX"] = str(prefix_path)
environment["PATH"] = str(Path(executable).parent) + os.pathsep + environment.get("PATH", "")
return [executable, *arguments], environment
def settings_command(root: Path, arguments: list[str]) -> bool:
"""Implement settings operations used by the existing settings dialog."""
action = arguments[0]
user_conf = root / "data" / "user.conf"
path = Path(arguments[1] + ".ppdb") if action in ("--show-ppdb", "--edit-db") else user_conf
values = read_settings(path)
if action in ("--get-user-conf", "--show-ppdb"):
if action == "--get-user-conf" and len(arguments) > 1:
sys.stdout.write(values.get(arguments[1], "") + "\n")
else:
sys.stdout.write("".join(f'{key}="{value}"\n' for key, value in values.items()))
elif action == "--edit-db":
for change in arguments[2:]:
key, value = change.split("=", 1)
values[key] = value
write_settings(path, values)
elif action == "--set-user-conf":
values[arguments[1]] = arguments[2]
write_settings(path, values)
elif action == "--delete-user-conf":
values.pop(arguments[1], None)
write_settings(path, values)
else:
return False
return True
def main(arguments: list[str] | None = None) -> int:
"""Run the native adapter through the existing PortProton command interface."""
arguments = list(sys.argv[1:] if arguments is None else arguments)
root = data_root()
try:
if not arguments:
raise ValueError("An executable or Wine tool is required")
settings = read_settings(root / "data" / "user.conf")
if arguments[0] == "cli":
arguments = arguments[1:]
if not arguments:
raise ValueError("A CLI operation is required")
if settings_command(root, arguments):
return 0
tool = WINE_TOOLS.get(arguments[0])
if not tool or len(arguments) != 3:
raise ValueError(f"Unsupported macOS operation: {arguments[0]}")
settings.update(PW_WINE_USE=arguments[1], PW_PREFIX_NAME=arguments[2])
arguments = [tool]
else:
settings.update(read_settings(Path(arguments[0] + ".ppdb")))
target = Path(arguments[0]).expanduser().resolve(strict=True)
arguments[0] = str(target)
dispatch = {".msi": ["msiexec", "/i"], ".bat": ["cmd", "/c"],
".cmd": ["cmd", "/c"], ".reg": ["regedit"]}
arguments = [*dispatch.get(target.suffix.lower(), []), *arguments]
os.chdir(target.parent)
command, environment = wine_command(root, arguments, settings)
os.execvpe(command[0], command, environment)
except (OSError, ValueError, IndexError) as error:
logger.error("macOS Wine operation failed: %s", error)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+32 -9
View File
@@ -343,7 +343,7 @@ class MainWindow(
self.setWindowTitle(f"{app_name} {version}")
self.setMinimumSize(890, 600)
self._pending_resolution = resolution # Store resolution for later application
self._show_system_tab = show_system_tab
self._show_system_tab = show_system_tab and sys.platform != "darwin"
self.system_tab_index = -1 # Default, set when system tab is created
self._animated_covers_suspended = False
@@ -579,8 +579,6 @@ class MainWindow(
self.restore_state()
self.keyboard = VirtualKeyboard(self, self.theme)
from portprotonqt.system_keyboard import SystemKeyboard
self.system_keyboard = SystemKeyboard(self)
self.detail_animations = DetailPageAnimations(self, self.theme)
self._animations = {}
@@ -2490,7 +2488,7 @@ class MainWindow(
return extract_exec_target_path(exec_line) or ""
def _has_running_game_process(self) -> bool:
if getattr(self, "native_game_running", False):
if sys.platform == "darwin" or getattr(self, "native_game_running", False):
if any(process.poll() is None for process in self.game_processes):
return True
groups = {process.pid for process in self.game_processes}
@@ -2697,6 +2695,17 @@ class MainWindow(
def _terminate_game_processes(self) -> None:
for proc in self.game_processes:
if sys.platform == "darwin":
try:
os.killpg(proc.pid, signal.SIGKILL)
proc.wait(timeout=0)
except ProcessLookupError:
proc.poll()
except subprocess.TimeoutExpired:
logger.debug("macOS Wine process %s is still exiting", proc.pid)
except OSError as error:
logger.warning("Failed to stop macOS Wine process group %s: %s", proc.pid, error)
continue
if proc.poll() is not None and not getattr(self, "native_game_running", False):
continue
try:
@@ -2710,6 +2719,8 @@ class MainWindow(
def _run_portproton_stop_command(self) -> bool:
"""Run PortProton CLI stop command."""
if sys.platform == "darwin":
return True
if not self.start_sh:
logger.warning("PortProton start command is unavailable for stop")
return False
@@ -2729,13 +2740,16 @@ class MainWindow(
if getattr(self, "native_game_running", False):
self._terminate_game_processes()
return True
if getattr(self, "launcher_process_only", False):
if sys.platform != "darwin" and getattr(self, "launcher_process_only", False):
if self._run_portproton_stop_command():
return True
self._analyze_short_launch()
if sys.platform != "darwin":
self._analyze_short_launch()
self._terminate_game_processes()
if sys.platform == "darwin":
return not any(proc.poll() is None for proc in self.game_processes)
self.game_processes = []
stopped = self._run_portproton_stop_command()
if hasattr(self, 'checkProcessTimer') and self.checkProcessTimer is not None:
@@ -2747,6 +2761,8 @@ class MainWindow(
def _check_missing_prefix_by_name_before_launch(self, prefix_name: str, env_vars: dict[str, str]) -> None:
"""Check prefix presence and optionally disable default recommended libs."""
if sys.platform == "darwin":
return
if not prefix_name or not self.portproton_location:
return
@@ -2768,6 +2784,8 @@ class MainWindow(
def _check_missing_prefix_before_launch(self, game_exe_path: str, env_vars: dict[str, str]) -> None:
"""Check game prefix and optionally disable default recommended libs."""
if sys.platform == "darwin":
return
if not game_exe_path:
return
@@ -3253,6 +3271,10 @@ class MainWindow(
return True
def _launch_egs_game(self, app_id: str, button=None) -> None:
if sys.platform == "darwin":
self._finish_silent_launch()
QMessageBox.warning(self, _("Error"), "Epic store launch wrappers are not supported on macOS. Open the installed Windows executable directly.")
return
target = self.egs_api.get_launch_target(app_id)
if not target:
self._finish_silent_launch()
@@ -3320,6 +3342,10 @@ class MainWindow(
def _launch_gog_game(
self, app_id: str, button=None, play_sound: bool = True
) -> None:
if sys.platform == "darwin":
self._finish_silent_launch()
QMessageBox.warning(self, _("Error"), "GOG store launch wrappers are not supported on macOS. Open the installed Windows executable directly.")
return
self.gog_api.ensure_launch_parameters(app_id)
discovered_path = self.gog_api.get_installed_path(app_id)
install_path = str(discovered_path) if discovered_path else ""
@@ -3531,9 +3557,6 @@ class MainWindow(
# Full application close
event.accept()
system_keyboard = getattr(self, 'system_keyboard', None)
if system_keyboard is not None:
system_keyboard.shutdown()
watcher = getattr(self, "system_theme_watcher", None)
if watcher is not None:
+1 -26
View File
@@ -1,6 +1,7 @@
# Install Python source files
install_data(
['__init__.py',
'macos.py',
'appimage_integration.py',
'appimage_updater.py',
'cli.py',
@@ -77,14 +78,6 @@ shared_library(
install_dir: pkgdatadir,
)
shared_library(
'portprotonqt_keyboard',
keyboard_sources,
dependencies: keyboard_deps,
install: true,
install_dir: pkgdatadir,
)
install_data(
['compatibility_rules.json',
'keyboard_layouts.json',
@@ -93,24 +86,6 @@ install_data(
)
# Install animations package
install_data(
['system_keyboard/__init__.py',
'system_keyboard/__main__.py',
'system_keyboard/input.py',
'system_keyboard/keys.py',
'system_keyboard/layouts.py',
'system_keyboard/detection.py',
'system_keyboard/gsettings_detection.py',
'system_keyboard/wayland_detection.py',
'system_keyboard/cosmic_detection.py',
'system_keyboard/manual_layout.py',
'system_keyboard/native.py',
'system_keyboard/window.py',
'system_keyboard/wayland_window.py',
],
install_dir: pythondir / meson.project_name() / 'system_keyboard',
)
install_data(
['animations/__init__.py',
'animations/detail_background.py',
+2 -1
View File
@@ -1,8 +1,9 @@
import ctypes
import sys
from dataclasses import dataclass
from pathlib import Path
GAMEPAD_LIBRARY_NAME = "libportprotonqt_gamepad.so"
GAMEPAD_LIBRARY_NAME = "libportprotonqt_gamepad.dylib" if sys.platform == "darwin" else "libportprotonqt_gamepad.so"
SYSTEM_GAMEPAD_LIBRARY = Path(__file__).parent / GAMEPAD_LIBRARY_NAME
DEV_GAMEPAD_LIBRARY = (
Path(__file__).parent.parent / "build-aux" / "lib" / GAMEPAD_LIBRARY_NAME
@@ -18,6 +18,11 @@ MOUNT_ESCAPE_PATTERN = re.compile(r"\\([0-7]{3})")
def list_mounted_drive_paths(mounts_path: str = "/proc/mounts") -> list[str]:
"""Return local mounted drive paths available to the user."""
if sys.platform == "darwin":
from pathlib import Path
volumes = Path("/Volumes")
return sorted(str(path) for path in volumes.iterdir()
if path.is_dir() and os.access(path, os.R_OK)) if volumes.is_dir() else []
try:
mounts = _read_mounts(mounts_path)
mounted_drives = set()
+14 -1
View File
@@ -1,4 +1,5 @@
import os
import sys
import shutil
import subprocess
from pathlib import Path
@@ -58,6 +59,13 @@ def get_available_wine_options(
key=version_sort_key
)
if sys.platform == "darwin":
from portprotonqt.macos import find_wine
options = [name for name in options if find_wine(Path(dist_dir, name)) is not None]
if system_wine_label and shutil.which("wine"):
options.append(system_wine_label)
return options
from portprotonqt.config import get_portproton_scripts_path
scripts_path = get_portproton_scripts_path()
if scripts_path:
@@ -143,6 +151,8 @@ def get_toggle_settings():
"""Get predefined toggle settings with descriptions."""
from portprotonqt.localization import _
if sys.platform == "darwin":
return {}
return {
# Graphics enhancements
'PW_DGVOODOO2': _("Enable dgVoodoo2. Forced use all dgVoodoo2 libs (Glide 2.11-3.1, DirectDraw 1-7, Direct3D 2-9) on all 3D API."),
@@ -316,7 +326,7 @@ def get_advanced_settings(disabled_text, logical_core_options=None, locale_optio
advanced_settings.append({
'key': 'PW_RUN_AFTER_EXE',
'name': _("Run After / Wrapper"),
'description': _("Path to a second .exe, script, or wrapper command. Use %command% for the game command: /home/user/.local/bin/mako-launch %command%. Example: systemd-run --user --scope --slice=app.slice"),
'description': _("Path to a second .exe, script, or wrapper command. Example: systemd-run --user --scope --slice=app.slice"),
'type': 'text',
'default': ''
})
@@ -394,6 +404,9 @@ def get_advanced_settings(disabled_text, logical_core_options=None, locale_optio
'default': disabled_text
})
if sys.platform == "darwin":
return [setting for setting in advanced_settings
if setting["key"] in ("PW_WINE_USE", "PW_PREFIX_NAME")]
return advanced_settings
# Keys that should be recognized as advanced settings
+1
View File
@@ -16,6 +16,7 @@ from portprotonqt.image_utils import COVER_IMAGE_EXTENSIONS
logger = get_logger(__name__)
STEAM_DATA_DIRS = (
"~/Library/Application Support/Steam",
"~/.steam/steam",
"~/snap/steam/common/.local/share/Steam",
"~/.var/app/com.valvesoftware.Steam/data/Steam",
-126
View File
@@ -1,126 +0,0 @@
"""Launch and control the system keyboard independently of application focus.
Assisted-by: Codex:GPT-6
"""
import os
import sys
import orjson
from PySide6.QtCore import QObject, QProcess, QProcessEnvironment
from PySide6.QtWidgets import QApplication, QMessageBox, QWidget
from portprotonqt.config import ui_config
from portprotonqt.localization import _
from portprotonqt.logger import get_logger
from .wayland_detection import compositor
logger = get_logger(__name__)
SHUTDOWN_TIMEOUT_MS = 3000
ERROR_OUTPUT_LIMIT = 8192
class SystemKeyboard(QObject):
"""Retain the child process and forward gamepad commands over its stdin."""
def __init__(self, parent: QWidget) -> None:
super().__init__(parent)
self.owner = parent
self.process = QProcess(self)
self.process.started.connect(self._started)
self.process.readyReadStandardOutput.connect(self._read_state)
self.process.readyReadStandardError.connect(self._read_errors)
self.process.errorOccurred.connect(self._process_error)
self.process.finished.connect(self._finished)
self.visible = False
self.shift_pressed = False
self.output = bytearray()
self.errors = ''
self.closing = False
app = QApplication.instance()
if app is not None:
app.aboutToQuit.connect(self.shutdown)
def isVisible(self) -> bool:
return self.visible
def toggle(self) -> None:
if self.visible:
self.hide()
return
self.visible = True
if self.process.state() != QProcess.ProcessState.NotRunning:
self.send('show')
return
self.errors = ''
self.output.clear()
environment = QProcessEnvironment.systemEnvironment()
platform = 'offscreen' if compositor(os.environ) else 'xcb'
environment.insert('QT_QPA_PLATFORM', platform)
self.process.setProcessEnvironment(environment)
self.process.start(sys.executable, ['-m', 'portprotonqt.system_keyboard'])
def _started(self) -> None:
self.send('theme', ui_config.get_theme())
self.send('show' if self.visible else 'hide')
def send(self, action: str, value: object = None) -> None:
if self.process.state() == QProcess.ProcessState.Running:
self.process.write(orjson.dumps({'action': action, 'value': value}) + b'\n')
def hide(self) -> None:
self.visible = False
self.send('hide')
def _read_state(self) -> None:
self.output.extend(bytes(self.process.readAllStandardOutput().data()))
while b'\n' in self.output:
line, _, remainder = self.output.partition(b'\n')
self.output = bytearray(remainder)
try:
data = orjson.loads(line)
except orjson.JSONDecodeError:
logger.warning('Invalid system keyboard response: %r', line)
continue
if isinstance(data, dict) and data.get('event') == 'hidden':
self.visible = False
self.shift_pressed = False
elif isinstance(data, dict) and data.get('event') == 'shift':
self.shift_pressed = bool(data.get('value'))
def _read_errors(self) -> None:
output = bytes(self.process.readAllStandardError().data()).decode(errors='replace')
self.errors = (self.errors + output)[-ERROR_OUTPUT_LIMIT:]
if output.strip():
logger.warning('System keyboard: %s', output.strip())
def _process_error(self, error: QProcess.ProcessError) -> None:
if error == QProcess.ProcessError.FailedToStart:
self.visible = False
self._show_error(self.process.errorString())
def _finished(self, code: int, status: QProcess.ExitStatus) -> None:
self.visible = False
self.shift_pressed = False
self._read_errors()
if not self.closing and (code or status == QProcess.ExitStatus.CrashExit):
self._show_error(self.errors.strip() or self.process.errorString())
def _show_error(self, message: str) -> None:
logger.error('Cannot open system keyboard: %s', message)
if not self.closing:
QMessageBox.warning(self.owner, _('Error'), message)
def shutdown(self) -> None:
self.closing = True
self.visible = False
self.send('quit')
if self.process.state() == QProcess.ProcessState.NotRunning:
return
if self.process.waitForFinished(SHUTDOWN_TIMEOUT_MS):
return
self.process.terminate()
if not self.process.waitForFinished(SHUTDOWN_TIMEOUT_MS):
self.process.kill()
self.process.waitForFinished(SHUTDOWN_TIMEOUT_MS)
-73
View File
@@ -1,73 +0,0 @@
"""Isolated Qt frontend: X11/XWayland or a native Wayland layer surface."""
import os
import sys
import orjson
from typing import Any
from PySide6.QtCore import QSocketNotifier
from PySide6.QtWidgets import QApplication
from portprotonqt.logger import get_logger, setup_logger
logger = get_logger(__name__)
COMMAND_READ_SIZE = 8192
class CommandReader:
def __init__(self, window: Any) -> None:
self.window = window
self.buffer = bytearray()
os.set_blocking(sys.stdin.fileno(), False)
self.notifier = QSocketNotifier(sys.stdin.fileno(), QSocketNotifier.Type.Read)
self.notifier.activated.connect(self.read)
def read(self) -> None:
try:
data = os.read(sys.stdin.fileno(), COMMAND_READ_SIZE)
except BlockingIOError:
return
if not data:
self.notifier.setEnabled(False)
self.window.command('quit')
return
self.buffer.extend(data)
while b'\n' in self.buffer:
line, _, remaining = self.buffer.partition(b'\n')
self.buffer = bytearray(remaining)
try:
command = orjson.loads(line)
if isinstance(command, dict) and isinstance(command.get('action'), str):
self.window.command(command['action'], command.get('value'))
except Exception:
logger.exception('Invalid system keyboard command')
def main() -> int:
setup_logger('WARNING')
from .wayland_detection import compositor
layer_shell = compositor(os.environ) is not None
os.environ['QT_QPA_PLATFORM'] = 'offscreen' if layer_shell else 'xcb'
app = QApplication([sys.argv[0]])
app.setQuitOnLastWindowClosed(False)
from .window import SystemKeyboardWindow
window = SystemKeyboardWindow()
try:
if layer_shell:
from .wayland_window import WaylandWindow
window.native_layer = WaylandWindow(window)
reader = CommandReader(window)
app.aboutToQuit.connect(window.shutdown)
window.worker.start()
result = app.exec()
window.shutdown()
del reader
return result
except Exception:
logger.exception('Failed to start system keyboard')
window.shutdown()
return 1
if __name__ == '__main__':
raise SystemExit(main())
@@ -1,187 +0,0 @@
"""COSMIC layout notifications over Wayland, without focus or OSK ownership."""
from typing import Any
import ctypes as C
import os
import select
from .layouts import Layout
from .native import load_library
class Message(C.Structure):
_fields_ = [('name', C.c_char_p), ('signature', C.c_char_p),
('types', C.c_void_p)]
class Interface(C.Structure):
_fields_ = [('name', C.c_char_p), ('version', C.c_int),
('method_count', C.c_int), ('methods', C.POINTER(Message)),
('event_count', C.c_int), ('events', C.POINTER(Message))]
class CosmicLayout:
def __init__(self) -> None:
self.display = self.layout = None
self.group = None
self.error = None
self.callbacks, self.proxies = [], []
self.keyboard = self.manager = self.tracker = None
self.lib = load_library()
self._configure_library()
self._configure_protocol()
try:
self.display = self.lib.portproton_keyboard_wayland_connect(None)
if not self.display:
raise RuntimeError('Failed to connect to Wayland')
self.registry = self._new(self.display, (1, self._interface('wl_registry')), C.c_void_p())
self._listen(self.registry, [
(self._global, [C.c_uint32, C.c_char_p, C.c_uint32]),
(lambda *args: None, [C.c_uint32])])
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('COSMIC keyboard layout protocol or keymap unavailable')
except Exception:
self.close()
raise
def _configure_library(self) -> None:
p = C.c_void_p
for name, args, result in (
('portproton_keyboard_wayland_connect', [C.c_char_p], p),
('wl_display_disconnect', [p], None),
('wl_display_roundtrip', [p], C.c_int),
('wl_display_dispatch', [p], C.c_int),
('wl_display_dispatch_pending', [p], C.c_int),
('wl_display_get_fd', [p], C.c_int),
('wl_display_flush', [p], C.c_int),
('wl_proxy_destroy', [p], None),
('wl_proxy_add_listener', [p, p, p], C.c_int),
('wl_proxy_marshal_flags', [p, C.c_uint32, C.POINTER(Interface),
C.c_uint32, C.c_uint32], p),
):
fn = getattr(self.lib, name)
fn.argtypes, fn.restype = args, result
def _configure_protocol(self) -> None:
p = C.c_void_p
# Keep protocol metadata alive for the entire connection.
self.group_requests = (Message * 2)(Message(b'set_group', b'u', None),
Message(b'destroy', b'', None))
self.group_events = (Message * 1)(Message(b'group', b'u', None))
self.group_interface = Interface(b'zcosmic_keyboard_layout_v1', 1, 2,
self.group_requests, 1, self.group_events)
self.manager_types = (C.c_void_p * 2)(C.addressof(self.group_interface),
C.addressof(self._interface('wl_keyboard')))
self.manager_requests = (Message * 2)(
Message(b'get_keyboard_layout', b'no', C.cast(self.manager_types, p)),
Message(b'destroy', b'', None))
self.manager_interface = Interface(b'zcosmic_keyboard_layout_manager_v1', 1,
2, self.manager_requests, 0, None)
def _interface(self, name: Any) -> Any:
return Interface.in_dll(self.lib, name + '_interface')
def _new(self, proxy: Any, request: tuple[Any, Any], *args: Any) -> Any:
opcode, interface = request
result = self.lib.wl_proxy_marshal_flags(proxy, opcode, C.byref(interface),
1, 0, *args)
if not result:
raise RuntimeError('COSMIC: не удалось создать объект Wayland')
self.proxies.append(result)
return result
def _listen(self, proxy: Any, handlers: Any) -> None:
callbacks = []
for handler, types in handlers:
def guarded(data: Any, obj: Any, *args: Any, handler: Any = handler) -> None:
try:
handler(*args)
except Exception as exc:
self.error = exc
callbacks.append(C.CFUNCTYPE(None, C.c_void_p, C.c_void_p, *types)(guarded))
table = (C.c_void_p * len(callbacks))(*[C.cast(fn, C.c_void_p) for fn in callbacks])
self.callbacks.append((callbacks, table))
if self.lib.wl_proxy_add_listener(proxy, table, None) != 0:
raise RuntimeError('COSMIC: не удалось подписаться на события Wayland')
def _global(self, name: Any, interface: Any, version: Any) -> None:
if interface == b'wl_seat' and not hasattr(self, 'seat'):
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 interface == self.manager_interface.name 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()
def _capabilities(self, capabilities: Any) -> None:
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
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]),
(lambda *args: None, [u, u, u, u, u])])
self._track()
elif not capabilities & 2 and self.keyboard is not None:
self.error = RuntimeError('COSMIC: клавиатура отключена')
def _track(self) -> None:
if self.keyboard and self.manager and self.tracker is None:
self.tracker = self._new(self.manager, (0, self.group_interface),
C.c_void_p(), C.c_void_p(self.keyboard))
self._listen(self.tracker, [(self._group, [C.c_uint32])])
def _group(self, group: Any) -> None:
self.group = group
def layout_identifier(self) -> str:
if self.layout is None or self.group is None:
return 'System'
return self.layout.layout_identifier(self.group)
def _keymap(self, format: Any, fd: Any, size: Any) -> None:
try:
if format != 1 or not 0 < size <= 16 * 1024 * 1024:
raise RuntimeError('COSMIC: неверная карта Wayland')
text = os.pread(fd, size, 0)
if len(text) != size:
raise RuntimeError('COSMIC: неполная карта Wayland')
replacement = Layout(keymap_text=text)
finally:
os.close(fd)
if self.layout is not None:
self.layout.close()
self.layout = replacement
def _check(self, result: Any) -> None:
if result < 0:
raise RuntimeError('COSMIC: соединение Wayland закрыто')
if self.error is not None:
raise self.error
def labels(self, modifiers: Any=()) -> Any:
self._check(self.lib.wl_display_dispatch_pending(self.display))
fd = self.lib.wl_display_get_fd(self.display)
for _ in range(32):
if not select.select([fd], [], [], 0)[0]:
break
self._check(self.lib.wl_display_dispatch(self.display))
if self.layout is None or self.group is None:
raise RuntimeError('COSMIC: раскладка недоступна')
return self.layout.labels(modifiers, mask=(0, 0, 0, self.group))
def close(self) -> None:
if self.layout is not None:
self.layout.close()
self.layout = None
if self.display:
for proxy in reversed(self.proxies):
self.lib.wl_proxy_destroy(proxy)
self.proxies.clear()
self.lib.wl_display_disconnect(self.display)
self.display = None
-130
View File
@@ -1,130 +0,0 @@
"""Read the X11/XWayland keymap without capturing keyboard focus."""
import ctypes as C
import os
from collections.abc import Mapping
from .keys import (ROWS, MODIFIERS, XKB_KEYCODE_OFFSET, XKB_CORE_KEYBOARD,
XKB_SHIFT_MASK, XKB_LOCK_MASK, XKB_ALTGR_MASK, XKB_GROUP_COUNT, XKB_GROUP_SHIFT)
from evdev import ecodes
from .native import load_library
LAYOUT_NAME_BUFFER_BYTES = 256
def is_x11_session(environment: Mapping[str, str]) -> bool:
if environment.get('XDG_SESSION_TYPE'):
return environment['XDG_SESSION_TYPE'] == 'x11'
return bool(environment.get('DISPLAY')) and not environment.get('WAYLAND_DISPLAY')
class XkbState(C.Structure):
_fields_ = [('group', C.c_ubyte), ('locked_group', C.c_ubyte),
('base_group', C.c_ushort), ('latched_group', C.c_ushort),
*[(name, C.c_ubyte) for name in (
'mods', 'base_mods', 'latched_mods', 'locked_mods',
'compat_state', 'grab_mods', 'compat_grab_mods',
'lookup_mods', 'compat_lookup_mods')],
('ptr_buttons', C.c_ushort)]
class X11Layout:
def __init__(self) -> None:
self.display = None
self.lib = load_library()
functions = {
'portproton_keyboard_x11_open_display': ([C.c_char_p], C.c_void_p),
'XCloseDisplay': ([C.c_void_p], C.c_int),
'XkbGetState': ([C.c_void_p, C.c_uint, C.POINTER(XkbState)], C.c_int),
'XkbLockGroup': ([C.c_void_p, C.c_uint, C.c_uint], C.c_int),
'XkbLockModifiers': ([C.c_void_p, C.c_uint, C.c_uint, C.c_uint], C.c_int),
'XkbLookupKeySym': ([C.c_void_p, C.c_ubyte, C.c_uint,
C.POINTER(C.c_uint), C.POINTER(C.c_ulong)], C.c_int),
'XKeysymToString': ([C.c_ulong], C.c_char_p),
'XStringToKeysym': ([C.c_char_p], C.c_ulong),
'XKeysymToKeycode': ([C.c_void_p, C.c_ulong], C.c_ubyte),
'XSync': ([C.c_void_p, C.c_int], C.c_int),
'portproton_keyboard_x11_layout_name': ([C.c_void_p, C.c_uint, C.c_void_p, C.c_size_t], C.c_int),
}
for name, (args, result) in functions.items():
function = getattr(self.lib, name)
function.argtypes, function.restype = args, result
self.xkb = self.lib
self.xkb.xkb_keysym_to_utf32.argtypes = [C.c_uint]
self.xkb.xkb_keysym_to_utf32.restype = C.c_uint
self.display = self.lib.portproton_keyboard_x11_open_display(None)
if not self.display:
raise RuntimeError('Cannot read the X11 keyboard layout')
def state(self) -> XkbState:
state = XkbState()
if self.lib.XkbGetState(self.display, XKB_CORE_KEYBOARD, C.byref(state)) != 0:
raise RuntimeError('Cannot read XKB state')
return state
def switch(self) -> None:
group = (self.state().group + 1) % XKB_GROUP_COUNT
if not self.lib.XkbLockGroup(self.display, XKB_CORE_KEYBOARD, group):
raise RuntimeError('Cannot switch XKB layout')
self.lib.XSync(self.display, False)
def caps_lock(self) -> bool:
return bool(self.state().locked_mods & XKB_LOCK_MASK)
def layout_identifier(self) -> str:
name = C.create_string_buffer(LAYOUT_NAME_BUFFER_BYTES)
if self.lib.portproton_keyboard_x11_layout_name(self.display, self.state().group, name, len(name)):
return name.value.decode()
return 'System'
def toggle_caps_lock(self) -> None:
value = 0 if self.caps_lock() else XKB_LOCK_MASK
if not self.lib.XkbLockModifiers(self.display, XKB_CORE_KEYBOARD, XKB_LOCK_MASK, value):
raise RuntimeError('Cannot switch XKB Caps Lock')
self.lib.XSync(self.display, False)
def keycode(self, name: str) -> int:
symbol = self.lib.XStringToKeysym(name.encode())
code = self.lib.XKeysymToKeycode(self.display, symbol) if symbol else 0
if code < XKB_KEYCODE_OFFSET:
raise ValueError(f'Unknown shortcut key: {name}')
return code - XKB_KEYCODE_OFFSET
def labels(self, modifiers: set[int] | tuple[int, ...] = ()) -> dict[str, str]:
state = self.state()
mask = state.mods & (XKB_SHIFT_MASK | XKB_LOCK_MASK | XKB_ALTGR_MASK)
for code, bit in ((ecodes.KEY_LEFTSHIFT, XKB_SHIFT_MASK),
(ecodes.KEY_CAPSLOCK, XKB_LOCK_MASK),
(ecodes.KEY_RIGHTALT, XKB_ALTGR_MASK)):
if code in modifiers:
mask |= bit
# Match XkbBuildCoreState from X11/extensions/XKB.h.
mask |= state.group << XKB_GROUP_SHIFT
result = {}
for row in ROWS:
for fallback, code in row:
if code in MODIFIERS or code in {ecodes.KEY_TAB, ecodes.KEY_CAPSLOCK}:
continue
symbol, consumed = C.c_ulong(), C.c_uint()
if self.lib.XkbLookupKeySym(self.display, code + XKB_KEYCODE_OFFSET,
mask, C.byref(consumed), C.byref(symbol)):
value = self.xkb.xkb_keysym_to_utf32(symbol.value)
character = chr(value) if value else ''
result[str(code)] = character if character.isprintable() else fallback
return result
def close(self) -> None:
if self.display:
self.lib.XCloseDisplay(self.display)
self.display = None
def detect_layout() -> object:
desktop = os.environ.get('XDG_CURRENT_DESKTOP', '').lower().split(':')
if 'gnome' in desktop:
from .gsettings_detection import GSettingsLayout
return GSettingsLayout()
from .wayland_detection import compositor, detect_layout as detect_wayland_layout
if compositor(os.environ):
return detect_wayland_layout(os.environ)
return X11Layout()
@@ -1,98 +0,0 @@
"""GNOME source-history labels and the configured switching shortcut."""
import ast
import re
from evdev import ecodes
from .detection import X11Layout
from .layouts import Layout
from .wayland_detection import command
SOURCE_SCHEMA = 'org.gnome.desktop.input-sources'
BINDINGS_SCHEMA = 'org.gnome.desktop.wm.keybindings'
SHORTCUT_MODIFIERS = {
'Control': ecodes.KEY_LEFTCTRL, 'Ctrl': ecodes.KEY_LEFTCTRL,
'Primary': ecodes.KEY_LEFTCTRL, 'Alt': ecodes.KEY_LEFTALT,
'Shift': ecodes.KEY_LEFTSHIFT, 'Super': ecodes.KEY_LEFTMETA,
}
class GSettingsLayout:
def __init__(self) -> None:
self.layout: Layout | None = None
self.current: tuple[str, str] | None = None
description = command(['gsettings', 'describe', SOURCE_SCHEMA, 'current']).lower()
self.legacy_current = 'zero-based index' in description and 'deprecated' not in description
self._update()
def _read(self, key: str) -> object:
text = command(['gsettings', 'get', SOURCE_SCHEMA, key]).strip()
text = re.sub(r'^@[a-z()]+\s+|^uint32\s+', '', text)
if text in ('true', 'false'):
return text == 'true'
return ast.literal_eval(text)
def _source(self) -> tuple[str, str]:
sources = self._read('sources')
if self._read('per-window'):
raise ValueError('GSettings cannot track per-window input sources')
if not isinstance(sources, list) or not sources:
raise ValueError('GSettings has no input sources')
if self.legacy_current:
index = self._read('current')
if type(index) is not int or not 0 <= index < len(sources):
raise ValueError('Invalid GSettings current input-source index')
selected = sources[index]
elif len(sources) == 1:
selected = sources[0]
else:
recent = self._read('mru-sources')
if not isinstance(recent, list) or not recent or recent[0] not in sources:
raise ValueError('GSettings input-source history is unavailable')
selected = recent[0]
kind, name = selected
if kind != 'xkb' or not isinstance(name, str) or not name:
raise ValueError('GSettings input source is not an XKB layout')
layout, _, variant = name.partition('+')
return layout, variant
def _update(self) -> None:
choice = self._source()
if choice == self.current:
return
replacement = Layout(*choice)
if self.layout is not None:
self.layout.close()
self.layout, self.current = replacement, choice
def labels(self, modifiers: set[int] | tuple[int, ...] = ()) -> dict[str, str]:
self._update()
assert self.layout is not None
return self.layout.labels(modifiers)
def switch_codes(self) -> tuple[int, ...]:
text = command(['gsettings', 'get', BINDINGS_SCHEMA, 'switch-input-source']).strip()
bindings = ast.literal_eval(re.sub(r'^@as\s+', '', text))
if not isinstance(bindings, list):
raise ValueError('Invalid GSettings input-source shortcuts')
keymap = X11Layout()
try:
for accelerator in bindings:
modifiers = re.findall(r'<([^>]+)>', accelerator)
name = re.sub(r'<[^>]+>', '', accelerator)
if not name or any(item not in SHORTCUT_MODIFIERS for item in modifiers):
continue
try:
code = keymap.keycode(name)
except ValueError:
continue
return tuple(SHORTCUT_MODIFIERS[item] for item in modifiers) + (code,)
finally:
keymap.close()
raise RuntimeError('No supported GSettings switch-input-source shortcut')
def close(self) -> None:
if self.layout is not None:
self.layout.close()
self.layout = None
-197
View File
@@ -1,197 +0,0 @@
"""System input for the themed on-screen keyboard.
Assisted-by: Codex:GPT-6
"""
from queue import Empty, Queue
from threading import Event
import time
from typing import Any
from evdev import UInput, ecodes
from PySide6.QtCore import QThread, Signal
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
INPUT_POLL_SECONDS = 0.15
KEY_ROWS = (
(ecodes.KEY_GRAVE, *range(ecodes.KEY_1, ecodes.KEY_EQUAL + 1)),
(ecodes.KEY_TAB, *range(ecodes.KEY_Q, ecodes.KEY_RIGHTBRACE + 1), ecodes.KEY_BACKSLASH),
(ecodes.KEY_CAPSLOCK, *range(ecodes.KEY_A, ecodes.KEY_APOSTROPHE + 1)),
(ecodes.KEY_LEFTSHIFT, ecodes.KEY_102ND, *range(ecodes.KEY_Z, ecodes.KEY_SLASH + 1)),
)
SPECIAL_KEYS = (
ecodes.KEY_BACKSPACE, ecodes.KEY_ENTER, ecodes.KEY_SPACE,
ecodes.KEY_HOME, ecodes.KEY_END, ecodes.KEY_LEFT, ecodes.KEY_RIGHT,
ecodes.KEY_UP, ecodes.KEY_DOWN,
ecodes.KEY_LEFTCTRL, ecodes.KEY_KBD_LAYOUT_NEXT, ecodes.KEY_DELETE,
ecodes.KEY_LEFTALT, ecodes.KEY_RIGHTALT, ecodes.KEY_LEFTMETA,
)
class SystemInputWorker(QThread):
"""Own the uinput device and serialize all key events off the UI thread."""
ready = Signal()
failed = Signal(str)
state_changed = Signal(dict)
warning = Signal(str)
def __init__(self) -> None:
super().__init__()
self.commands: Queue[tuple[str, tuple[int, ...]]] = Queue()
self.stopping = Event()
self.enabled = Event()
self.modifiers: set[int] = set()
self.caps_lock = False
self.layout: Any = None
self.manual_layout = False
def run(self) -> None:
device = None
try:
keys = {code for row in KEY_ROWS for code in row} | set(SPECIAL_KEYS)
device = UInput({ecodes.EV_KEY: sorted(keys), ecodes.EV_LED: [ecodes.LED_CAPSL]},
name="PortProtonQt Keyboard", bustype=ecodes.BUS_USB)
self._load_layout()
self.ready.emit()
self._run_commands(device)
except OSError as error:
logger.warning("System keyboard input unavailable: %s", error)
self.failed.emit(str(error))
except Exception as error:
logger.exception("System keyboard input failed")
self.failed.emit(str(error))
finally:
if self.layout is not None:
self.layout.close()
if device is not None:
device.close()
def _run_commands(self, device: UInput) -> None:
next_poll = 0.0
while not self.stopping.is_set():
try:
action, codes = self.commands.get(timeout=INPUT_POLL_SECONDS)
except Empty:
action, codes = '', ()
if self.stopping.is_set():
break
try:
if action:
self._execute(device, action, codes)
except RuntimeError as error:
logger.warning('System keyboard command failed: %s', error)
self.warning.emit(str(error))
except ValueError as error:
logger.warning('Invalid system keyboard command: %s', error)
self.warning.emit(str(error))
if action or time.monotonic() >= next_poll:
self._refresh_state(device)
next_poll = time.monotonic() + INPUT_POLL_SECONDS
def _load_layout(self) -> None:
import os
from .detection import detect_layout
from .manual_layout import ManualLayout
from .wayland_detection import compositor
try:
self.layout = detect_layout()
except Exception as error:
if not compositor(os.environ):
raise
logger.warning("System layout detection unavailable: %s", error)
self.layout = ManualLayout()
self.manual_layout = True
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 .detection import X11Layout, is_x11_session
from .gsettings_detection import GSettingsLayout
import os
if action in {'tap', 'caps', 'language'} and not self.enabled.is_set():
return
if action == 'modifiers':
self.modifiers = set(codes)
elif action == 'release':
self.modifiers.clear()
elif action == 'caps':
if isinstance(self.layout, X11Layout) and is_x11_session(os.environ):
self.layout.toggle_caps_lock()
else:
self.send_keys(device, (ecodes.KEY_CAPSLOCK,))
elif action == 'language':
if isinstance(self.layout, X11Layout) and is_x11_session(os.environ):
self.layout.switch()
elif isinstance(self.layout, GSettingsLayout):
self.send_keys(device, self.layout.switch_codes())
elif self.manual_layout:
self.send_keys(device, (ecodes.KEY_KBD_LAYOUT_NEXT,))
self.layout.switch()
elif hasattr(self.layout, 'switch') and not isinstance(self.layout, X11Layout):
self.layout.switch()
else:
self.send_keys(device, (ecodes.KEY_KBD_LAYOUT_NEXT,))
self.modifiers.clear()
elif action == 'tap':
self.send_keys(device, tuple(sorted(self.modifiers)) + codes)
self.modifiers.clear()
def _refresh_state(self, device: UInput) -> None:
from .detection import X11Layout, is_x11_session
import os
try:
for event in device.read():
if event.type == ecodes.EV_LED and event.code == ecodes.LED_CAPSL:
self.caps_lock = bool(event.value)
except BlockingIOError:
pass
try:
caps = (self.layout.caps_lock() if isinstance(self.layout, X11Layout)
and is_x11_session(os.environ) else self.caps_lock)
modifiers = self.modifiers & {ecodes.KEY_LEFTSHIFT, ecodes.KEY_RIGHTALT}
if caps:
modifiers.add(ecodes.KEY_CAPSLOCK)
labels = self.layout.labels(modifiers)
current = getattr(self.layout, 'current', None)
name = current[0] if isinstance(current, tuple) else getattr(self.layout, 'language', 'System')
if hasattr(self.layout, 'layout_identifier'):
name = self.layout.layout_identifier()
self.state_changed.emit({'labels': labels, 'caps': caps,
'shift': ecodes.KEY_LEFTSHIFT in self.modifiers,
'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))
def send_keys(self, device: UInput, codes: tuple[int, ...]) -> None:
pressed = []
try:
for code in codes:
pressed.append(code)
device.write(ecodes.EV_KEY, code, 1)
device.syn()
finally:
for code in reversed(pressed):
try:
device.write(ecodes.EV_KEY, code, 0)
device.syn()
except OSError:
logger.exception("Failed to release system keyboard key %s", code)
def stop(self) -> None:
self.enabled.clear()
self.stopping.set()
self.commands.put(('', ()))
self.wait()
def cancel_pending(self) -> None:
self.enabled.clear()
while True:
try:
self.commands.get_nowait()
except Empty:
break
self.commands.put(('release', ()))
-17
View File
@@ -1,17 +0,0 @@
"""Physical keys shared by uinput and XKB label readers."""
from evdev import ecodes
from .input import KEY_ROWS
ROWS = [[("", code) for code in row] for row in KEY_ROWS]
MODIFIERS = {ecodes.KEY_LEFTSHIFT, ecodes.KEY_LEFTCTRL, ecodes.KEY_LEFTMETA,
ecodes.KEY_LEFTALT, ecodes.KEY_RIGHTALT}
KEY_KBD_LAYOUT_NEXT = ecodes.KEY_KBD_LAYOUT_NEXT
XKB_KEYCODE_OFFSET = 8
XKB_CORE_KEYBOARD = 0x0100
XKB_SHIFT_MASK = 1
XKB_LOCK_MASK = 2
XKB_ALTGR_MASK = 128
XKB_GROUP_COUNT = 4
XKB_GROUP_SHIFT = 13
-108
View File
@@ -1,108 +0,0 @@
"""Generate labels from the installed XKB database, not a hand-written language list."""
from typing import Any
import ctypes as C
import xml.etree.ElementTree as ET
from .keys import ROWS, MODIFIERS
from .native import load_library
class Names(C.Structure):
_fields_ = [(name, C.c_char_p) for name in ('rules', 'model', 'layout', 'variant', 'options')]
def available_layouts(registry: Any='/usr/share/X11/xkb/rules/evdev.xml') -> Any:
result = []
for layout in ET.parse(registry).findall('./layoutList/layout'):
name = layout.findtext('./configItem/name')
result.append((name, ''))
for variant in layout.findall('./variantList/variant'):
result.append((name, variant.findtext('./configItem/name')))
return result
class Layout:
def __init__(self, layout: Any='us', variant: Any='', *, keymap_text: Any=None) -> None:
self.context = self.keymap = None
self.lib = load_library()
self._configure_library()
self.context = self.lib.portproton_keyboard_xkb_context_new(0)
if not self.context:
raise RuntimeError('Failed to create XKB context')
names = Names(None, b'pc105', layout.encode(), variant.encode(), b'')
if keymap_text is None:
self.keymap = self.lib.xkb_keymap_new_from_names(self.context, C.byref(names), 0)
else:
self.keymap = self.lib.xkb_keymap_new_from_string(self.context, keymap_text, 1, 0)
if not self.keymap:
self.close()
raise ValueError(f'Unknown XKB layout: {layout}+{variant}')
def _configure_library(self) -> None:
functions = {
'portproton_keyboard_xkb_context_new': ([C.c_int], C.c_void_p),
'xkb_keymap_num_layouts': ([C.c_void_p], C.c_uint),
'xkb_keymap_layout_get_name': ([C.c_void_p, C.c_uint], C.c_char_p),
'xkb_context_unref': ([C.c_void_p], None),
'xkb_keymap_new_from_names': ([C.c_void_p, C.POINTER(Names), C.c_int], C.c_void_p),
'xkb_keymap_new_from_string': ([C.c_void_p, C.c_char_p, C.c_int, C.c_int], C.c_void_p),
'xkb_state_update_mask': ([C.c_void_p] + [C.c_uint] * 6, C.c_uint),
'xkb_keymap_unref': ([C.c_void_p], None),
'xkb_state_new': ([C.c_void_p], C.c_void_p),
'xkb_state_unref': ([C.c_void_p], None),
'xkb_state_update_key': ([C.c_void_p, C.c_uint, C.c_int], C.c_uint),
'xkb_state_key_get_utf8': ([C.c_void_p, C.c_uint, C.c_void_p, C.c_size_t], C.c_int),
'xkb_state_key_get_one_sym': ([C.c_void_p, C.c_uint], C.c_uint),
'xkb_keysym_get_name': ([C.c_uint, C.c_void_p, C.c_size_t], C.c_int),
}
for name, (args, result) in functions.items():
function = getattr(self.lib, name)
function.argtypes, function.restype = args, result
def labels(self, modifiers: Any=(), *, mask: Any=None) -> Any:
state = self.lib.xkb_state_new(self.keymap)
if not state:
raise RuntimeError('Не удалось создать состояние XKB')
try:
if mask is not None:
depressed, latched, locked, group = mask
self.lib.xkb_state_update_mask(state, depressed, latched, locked, 0, 0, group)
for code in modifiers:
self.lib.xkb_state_update_key(state, code + 8, 1)
labels = {}
for row in ROWS:
for fallback, code in row:
if code in MODIFIERS or code in {1, 14, 15, 28, 58, 57, 103, 105, 106, 108, 111}:
labels[str(code)] = fallback
continue
buffer = C.create_string_buffer(128)
length = self.lib.xkb_state_key_get_utf8(state, code + 8, buffer, len(buffer))
label = buffer.value.decode() if 0 < length < len(buffer) else ''
if not label or not label.isprintable():
sym = self.lib.xkb_state_key_get_one_sym(state, code + 8)
self.lib.xkb_keysym_get_name(sym, buffer, len(buffer))
label = buffer.value.decode() or fallback
labels[str(code)] = label
return labels
finally:
self.lib.xkb_state_unref(state)
def export(self) -> Any:
return {name: self.labels(mods) for name, mods in
[('normal', ()), ('shift', (42,)), ('altgr', (100,)), ('shift-altgr', (42, 100))]}
def layout_count(self) -> int:
return self.lib.xkb_keymap_num_layouts(self.keymap)
def layout_identifier(self, group: int) -> str:
name = self.lib.xkb_keymap_layout_get_name(self.keymap, group)
return name.decode() if name else 'System'
def close(self) -> None:
if self.keymap:
self.lib.xkb_keymap_unref(self.keymap)
self.keymap = None
if self.context:
self.lib.xkb_context_unref(self.context)
self.context = None
@@ -1,23 +0,0 @@
"""Manual label fallback for compositors without layout detection."""
from typing import Any
from .layouts import Layout
class ManualLayout:
def __init__(self) -> None:
self.layout = Layout('us')
self.language = 'us'
def switch(self) -> Any:
language = 'ru' if self.language == 'us' else 'us'
replacement = Layout(language)
self.layout.close()
self.layout = replacement
self.language = language
def labels(self, modifiers: Any=()) -> Any:
return self.layout.labels(modifiers)
def close(self) -> None:
self.layout.close()
-14
View File
@@ -1,14 +0,0 @@
"""Load the linked keyboard backend using the same paths as the SDL backend."""
import ctypes
from pathlib import Path
KEYBOARD_LIBRARY_NAME = 'libportprotonqt_keyboard.so'
SYSTEM_KEYBOARD_LIBRARY = Path(__file__).parent.parent / KEYBOARD_LIBRARY_NAME
DEV_KEYBOARD_LIBRARY = Path(__file__).parent.parent.parent / 'build-aux' / 'lib' / KEYBOARD_LIBRARY_NAME
KEYBOARD_LIBRARY_PATH = (SYSTEM_KEYBOARD_LIBRARY if SYSTEM_KEYBOARD_LIBRARY.is_file()
else DEV_KEYBOARD_LIBRARY)
def load_library() -> ctypes.CDLL:
return ctypes.CDLL(str(KEYBOARD_LIBRARY_PATH))
@@ -1,123 +0,0 @@
"""Compositor IPC adapters for layer-shell layout labels."""
from typing import Any
import orjson
import subprocess
import xml.etree.ElementTree as ET
from .layouts import Layout
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')]:
if environment.get(variable):
return name
return next((name for name in ('hyprland', 'sway', 'niri', 'cosmic') if name in desktop), None)
def command(args: Any) -> Any:
try:
return subprocess.run(args, capture_output=True, text=True,
timeout=1, check=True).stdout
except (OSError, subprocess.SubprocessError) as exc:
raise RuntimeError(f'Ошибка IPC ({args[0]}): {exc}') from exc
class NiriLayout:
def __init__(self, registry: Any='/usr/share/X11/xkb/rules/evdev.xml') -> None:
self.names = {}
for entry in ET.parse(registry).findall('./layoutList/layout'):
code = entry.findtext('./configItem/name')
self.names[entry.findtext('./configItem/description')] = (code, '')
for variant in entry.findall('./variantList/variant'):
self.names[variant.findtext('./configItem/description')] = (
code, variant.findtext('./configItem/name'))
self.layout = None
self.current = None
self._update()
def _query_name(self) -> Any:
try:
result = subprocess.run(
['niri', 'msg', '--json', 'keyboard-layouts'],
capture_output=True, text=True, timeout=1, check=True)
except (OSError, subprocess.SubprocessError) as exc:
raise RuntimeError(f'Не удалось запросить раскладку через niri IPC: {exc}') from exc
data = orjson.loads(result.stdout)
index = data['current_idx']
if type(index) is not int or not 0 <= index < len(data['names']):
raise ValueError('Некорректный индекс раскладки niri')
return data['names'][index]
def _update(self) -> None:
name = self._query_name()
if name not in self.names:
raise ValueError(f'Раскладка отсутствует в реестре XKB: {name}')
choice = self.names[name]
if choice != self.current:
replacement = Layout(*choice)
if self.layout is not None:
self.layout.close()
self.layout = replacement
self.current = choice
def labels(self, modifiers: Any=()) -> Any:
self._update()
assert self.layout is not None
return self.layout.labels(modifiers)
def switch(self) -> None:
command(['niri', 'msg', 'action', 'switch-layout', 'next'])
def close(self) -> None:
if self.layout is not None:
self.layout.close()
self.layout = None
class SwayLayout(NiriLayout):
def _query_name(self) -> Any:
inputs = orjson.loads(command(['swaymsg', '-t', 'get_inputs', '-r']))
keyboards = [item for item in inputs if item.get('type') == 'keyboard'
and item.get('xkb_active_layout_name')]
if not keyboards:
raise RuntimeError('Sway не сообщил раскладку клавиатуры')
# Never silently display one of several conflicting device layouts.
names = {item['xkb_active_layout_name'] for item in keyboards}
if len(names) != 1:
raise RuntimeError('У клавиатур Sway разные раскладки; задайте --layout')
return keyboards[0]['xkb_active_layout_name']
def switch(self) -> Any:
result = orjson.loads(command(['swaymsg', '-r', 'input type:keyboard xkb_switch_layout next']))
if not result or not all(item.get('success') for item in result):
raise RuntimeError(f'Sway не переключил раскладку: {result}')
class HyprlandLayout(NiriLayout):
def _query_name(self) -> Any:
data = orjson.loads(command(['hyprctl', '-j', 'devices']))
keyboard = next((item for item in data['keyboards'] if item.get('main')), None)
if keyboard is None or not keyboard.get('active_keymap'):
raise RuntimeError('Hyprland не сообщил раскладку основной клавиатуры')
self.keyboard = keyboard['name']
return keyboard['active_keymap']
def switch(self) -> Any:
self._query_name()
result = command(['hyprctl', 'switchxkblayout', self.keyboard, 'next'])
if result.strip() != 'ok':
raise RuntimeError(f'Hyprland не переключил раскладку: {result.strip()}')
def detect_layout(environment: Any) -> Any:
if compositor(environment) == 'cosmic':
from .cosmic_detection import CosmicLayout
return CosmicLayout()
adapter = {'niri': NiriLayout, 'sway': SwayLayout,
'hyprland': HyprlandLayout}.get(compositor(environment))
if adapter is None:
raise RuntimeError('Нет адаптера определения раскладки для этого композитора')
return adapter()
@@ -1,378 +0,0 @@
"""Present the Qt keyboard through native layer-shell and shared memory."""
import ctypes as C
from functools import partial
import mmap
import os
import select
from typing import Any
from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, QSocketNotifier, Qt, QTimer
from PySide6.QtGui import QImage, QMouseEvent, QRegion
from PySide6.QtWidgets import QApplication
from portprotonqt.logger import get_logger
from .cosmic_detection import Interface, Message
from .native import load_library
logger = get_logger(__name__)
WL_VERSION = 1
WL_DESTROY = 1
WL_FIXED_SCALE = 256
LAYER_OVERLAY = 3
ANCHOR_ALL_EDGES = 15
KEYBOARD_INTERACTIVITY_NONE = 0
SHM_ARGB8888 = 0
PIXEL_BYTES = 4
FRAME_INTERVAL_MS = 33
MAX_SURFACE_PIXELS = 33_177_600
POINTER_BUTTON_LEFT = 272
class WaylandWindow(QObject):
"""Keep native surfaces separate from Qt's offscreen platform plugin."""
def __init__(self, window: Any) -> None:
super().__init__(window)
self.window = window
self.callbacks: list[Any] = []
self.proxies: list[int] = []
self.buffers: dict[int, dict[str, Any]] = {}
self.compositor = self.shm = self.shell = None
self.seat: int | None = None
self.surface = self.layer = self.pointer = self.touch = None
self.display = None
self.wanted_visible = self.configured = False
self.dirty = True
self.position = QPointF()
self.pressed_widget: Any = None
self.lib = load_library()
self._configure_library()
self._configure_protocol()
self.display = self.lib.portproton_keyboard_wayland_connect(None)
if not self.display:
raise RuntimeError('Cannot connect to the Wayland compositor')
self.registry = self._request(self.display, (1, self._interface('wl_registry')), (C.c_void_p(),))
self._listen(self.registry, [(self._global, [C.c_uint32, C.c_char_p, C.c_uint32]),
(self._global_removed, [C.c_uint32])])
self.sync = self._request(self.display, (0, self._interface('wl_callback')), (C.c_void_p(),))
self._listen(self.sync, [(self._registry_ready, [C.c_uint32])])
self.notifier = QSocketNotifier(self.lib.wl_display_get_fd(self.display), QSocketNotifier.Type.Read, self)
self.notifier.activated.connect(self._dispatch)
self.timer = QTimer(self)
self.timer.setInterval(FRAME_INTERVAL_MS)
self.timer.timeout.connect(self._render)
self.timer.start()
app = QApplication.instance()
if app is not None:
app.installEventFilter(self)
self.lib.wl_display_flush(self.display)
def _configure_library(self) -> None:
p = C.c_void_p
functions = {
'portproton_keyboard_wayland_connect': ([C.c_char_p], p),
'wl_display_disconnect': ([p], None),
'wl_display_dispatch_pending': ([p], C.c_int),
'wl_display_prepare_read': ([p], C.c_int),
'wl_display_read_events': ([p], C.c_int),
'wl_display_cancel_read': ([p], None),
'wl_display_get_fd': ([p], C.c_int),
'wl_display_flush': ([p], C.c_int),
'wl_proxy_destroy': ([p], None),
'wl_proxy_add_listener': ([p, p, p], C.c_int),
'wl_proxy_marshal_flags': ([p, C.c_uint32, C.POINTER(Interface), C.c_uint32, C.c_uint32], p),
}
for name, (args, result) in functions.items():
function = getattr(self.lib, name)
function.argtypes, function.restype = args, result
def _configure_protocol(self) -> None:
self.layer_methods = (Message * 8)(
Message(b'set_size', b'uu', None), Message(b'set_anchor', b'u', None),
Message(b'set_exclusive_zone', b'i', None), Message(b'set_margin', b'iiii', None),
Message(b'set_keyboard_interactivity', b'u', None), Message(b'get_popup', b'o', None),
Message(b'ack_configure', b'u', None), Message(b'destroy', b'', None))
self.layer_events = (Message * 2)(Message(b'configure', b'uuu', None), Message(b'closed', b'', None))
self.layer_interface = Interface(b'zwlr_layer_surface_v1', WL_VERSION, 8,
self.layer_methods, 2, self.layer_events)
self.shell_types = (C.c_void_p * 5)(C.addressof(self.layer_interface),
C.addressof(self._interface('wl_surface')), C.addressof(self._interface('wl_output')), None, None)
self.shell_methods = (Message * 1)(Message(b'get_layer_surface', b'no?ous',
C.cast(self.shell_types, C.c_void_p)))
self.shell_interface = Interface(b'zwlr_layer_shell_v1', WL_VERSION, 1, self.shell_methods, 0, None)
def _interface(self, name: str) -> Interface:
return Interface.in_dll(self.lib, name + '_interface')
def _request(self, proxy: int | None, request: tuple[int, Any], arguments: tuple[Any, ...] = ()) -> Any:
opcode, interface = request
pointer = C.byref(interface) if interface is not None else None
result = self.lib.wl_proxy_marshal_flags(proxy, opcode, pointer, WL_VERSION, 0, *arguments)
if interface is not None:
if not result:
raise RuntimeError('Cannot create Wayland protocol object')
self.proxies.append(result)
return result
def _listen(self, proxy: int, handlers: list[tuple[Any, list[Any]]]) -> None:
callbacks = []
for handler, types in handlers:
def guarded(data: Any, obj: Any, *args: Any, handler: Any = handler) -> None:
try:
handler(*args)
except Exception:
logger.exception('System keyboard Wayland event failed')
QApplication.exit(1)
callbacks.append(C.CFUNCTYPE(None, C.c_void_p, C.c_void_p, *types)(guarded))
table = (C.c_void_p * len(callbacks))(*[C.cast(callback, C.c_void_p) for callback in callbacks])
self.callbacks.append((callbacks, table))
if self.lib.wl_proxy_add_listener(proxy, table, None) != 0:
raise RuntimeError('Cannot subscribe to Wayland events')
def _global(self, name: int, interface: bytes, version: int) -> None:
interfaces = {b'wl_compositor': ('compositor', self._interface('wl_compositor')),
b'wl_shm': ('shm', self._interface('wl_shm')),
b'zwlr_layer_shell_v1': ('shell', self.shell_interface),
b'wl_seat': ('seat', self._interface('wl_seat'))}
if interface not in interfaces:
return
attribute, metadata = interfaces[interface]
if getattr(self, attribute, None) is not None:
return
proxy = self._request(self.registry, (0, metadata),
(C.c_uint32(name), interface, C.c_uint32(WL_VERSION), C.c_void_p()))
setattr(self, attribute, proxy)
if interface == b'wl_seat':
self._listen(proxy, [(self._seat_capabilities, [C.c_uint32])])
self._create_surface()
def _global_removed(self, name: int) -> None:
logger.debug('Wayland global removed: %s', name)
def _registry_ready(self, serial: int) -> None:
self.lib.wl_proxy_destroy(self.sync)
self.proxies.remove(self.sync)
if not all((self.compositor, self.shm, self.shell)):
logger.error('The compositor does not provide layer-shell or shared-memory surfaces')
QApplication.exit(1)
def show_layer(self) -> None:
self.wanted_visible = True
self._create_surface()
def _create_surface(self) -> None:
if self.surface or not self.wanted_visible or not all((self.compositor, self.shm, self.shell)):
return
self.surface = self._request(self.compositor, (0, self._interface('wl_surface')), (C.c_void_p(),))
self._listen(self.surface, [(self._surface_output, [C.c_void_p]),
(self._surface_output, [C.c_void_p])])
self.layer = self._request(self.shell, (0, self.layer_interface),
(C.c_void_p(), C.c_void_p(self.surface), C.c_void_p(),
C.c_uint32(LAYER_OVERLAY), b'portprotonqt-system-keyboard'))
self._listen(self.layer, [(self._configured, [C.c_uint32, C.c_uint32, C.c_uint32]),
(self.window.hide_keyboard, [])])
self._request(self.layer, (0, None), (C.c_uint32(0), C.c_uint32(0)))
self._request(self.layer, (1, None), (C.c_uint32(ANCHOR_ALL_EDGES),))
self._request(self.layer, (2, None), (C.c_int32(-1),))
self._request(self.layer, (4, None), (C.c_uint32(KEYBOARD_INTERACTIVITY_NONE),))
self._input_region(False)
self._request(self.surface, (6, None))
self.lib.wl_display_flush(self.display)
def _configured(self, serial: int, width: int, height: int) -> None:
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),))
self.window.resize(width, height)
self.window._position_keyboard()
self.configured = self.dirty = True
def _surface_output(self, output: int) -> None:
self.dirty = True
def _input_region(self, include_panel: bool = True) -> None:
region = self._request(self.compositor, (1, self._interface('wl_region')), (C.c_void_p(),))
if include_panel:
rect = self.window.keyboard.geometry()
args = tuple(C.c_int32(value) for value in (rect.x(), rect.y(), rect.width(), rect.height()))
self._request(region, (1, None), args)
self._request(self.surface, (5, None), (C.c_void_p(region),))
self._destroy(region, 0)
def _destroy(self, proxy: int | None, opcode: int) -> None:
if proxy is not None:
self.lib.wl_proxy_marshal_flags(proxy, opcode, None, WL_VERSION, WL_DESTROY)
self.proxies.remove(proxy)
def _buffer(self, width: int, height: int) -> int | None:
size = width * height * PIXEL_BYTES
for proxy, buffer in self.buffers.items():
if buffer['size'] == (width, height) and not buffer['busy']:
return proxy
if sum(buffer['size'] == (width, height) for buffer in self.buffers.values()) >= 2:
return None
fd = os.memfd_create('portprotonqt-keyboard', os.MFD_CLOEXEC)
try:
os.ftruncate(fd, size)
memory = mmap.mmap(fd, size)
pool = self._request(self.shm, (0, self._interface('wl_shm_pool')),
(C.c_void_p(), C.c_int(fd), C.c_int32(size)))
proxy = self._request(pool, (0, self._interface('wl_buffer')),
(C.c_void_p(), C.c_int32(0), C.c_int32(width), C.c_int32(height),
C.c_int32(width * PIXEL_BYTES), C.c_uint32(SHM_ARGB8888)))
self._destroy(pool, 1)
finally:
os.close(fd)
self.buffers[proxy] = {'memory': memory, 'size': (width, height), 'busy': False}
self._listen(proxy, [(partial(self._released, proxy), [])])
return proxy
def _released(self, proxy: int) -> None:
buffer = self.buffers.get(proxy)
if buffer is not None:
buffer['busy'] = False
if buffer['size'] != (self.window.width(), self.window.height()):
self._destroy(proxy, 0)
buffer['memory'].close()
del self.buffers[proxy]
def _render(self) -> None:
if not self.surface or not self.configured or not self.dirty:
return
width, height = self.window.width(), self.window.height()
proxy = self._buffer(width, height)
if proxy is None:
return
image = QImage(width, height, QImage.Format.Format_ARGB32_Premultiplied)
image.fill(Qt.GlobalColor.transparent)
self.dirty = False
self.window.render(image, QPoint(), QRegion(), self.window.RenderFlag.DrawChildren)
buffer = self.buffers[proxy]
buffer['memory'].seek(0)
buffer['memory'].write(image.constBits())
buffer['busy'] = True
self._request(self.surface, (1, None), (C.c_void_p(proxy), C.c_int32(0), C.c_int32(0)))
self._request(self.surface, (2, None), tuple(C.c_int32(v) for v in (0, 0, width, height)))
self._input_region()
self._request(self.surface, (6, None))
self.lib.wl_display_flush(self.display)
def eventFilter(self, obj: QObject, event: QEvent) -> bool:
if event.type() == QEvent.Type.UpdateRequest:
self.dirty = True
return False
def _dispatch(self) -> None:
while self.lib.wl_display_prepare_read(self.display) != 0:
if self.lib.wl_display_dispatch_pending(self.display) < 0:
QApplication.exit(1)
return
fd = self.lib.wl_display_get_fd(self.display)
if select.select([fd], [], [], 0)[0]:
result = self.lib.wl_display_read_events(self.display)
else:
self.lib.wl_display_cancel_read(self.display)
result = 0
if result < 0 or self.lib.wl_display_dispatch_pending(self.display) < 0:
logger.error('System keyboard Wayland connection closed')
QApplication.exit(1)
return
self.lib.wl_display_flush(self.display)
def _seat_capabilities(self, capabilities: int) -> None:
if capabilities & 1 and self.pointer is None:
self.pointer = self._request(self.seat, (0, self._interface('wl_pointer')), (C.c_void_p(),))
u, i, p = C.c_uint32, C.c_int32, C.c_void_p
self._listen(self.pointer, [(self._pointer_enter, [u, p, i, i]),
(self._pointer_leave, [u, p]),
(self._pointer_motion, [u, i, i]),
(self._pointer_button, [u, u, u, u]),
(self._pointer_axis, [u, u, i])])
if capabilities & 4 and self.touch is None:
self.touch = self._request(self.seat, (2, self._interface('wl_touch')), (C.c_void_p(),))
u, i, p = C.c_uint32, C.c_int32, C.c_void_p
self._listen(self.touch, [(self._touch_down, [u, u, p, i, i, i]),
(self._touch_up, [u, u, i]), (self._touch_motion, [u, i, i, i]),
(self._touch_frame, []), (self._touch_cancel, [])])
def _pointer_enter(self, *event: int) -> None:
serial, surface, x, y = event
self.position = QPointF(x / WL_FIXED_SCALE, y / WL_FIXED_SCALE)
def _pointer_leave(self, serial: int, surface: int) -> None:
self.dirty = True
def _pointer_motion(self, timestamp: int, x: int, y: int) -> None:
self.position = QPointF(x / WL_FIXED_SCALE, y / WL_FIXED_SCALE)
self._mouse_event(QEvent.Type.MouseMove)
def _pointer_button(self, *event: int) -> None:
serial, timestamp, button, state = event
if button == POINTER_BUTTON_LEFT:
kind = QEvent.Type.MouseButtonPress if state else QEvent.Type.MouseButtonRelease
self._mouse_event(kind)
def _pointer_axis(self, timestamp: int, axis: int, value: int) -> None:
logger.debug('System keyboard pointer axis: %s', axis)
def _touch_down(self, *event: int) -> None:
serial, timestamp, surface, touch_id, x, y = event
if self.pressed_widget is None:
self.touch_id = touch_id
self.position = QPointF(x / WL_FIXED_SCALE, y / WL_FIXED_SCALE)
self._mouse_event(QEvent.Type.MouseButtonPress)
def _touch_up(self, serial: int, timestamp: int, touch_id: int) -> None:
if touch_id == getattr(self, 'touch_id', None):
self._mouse_event(QEvent.Type.MouseButtonRelease)
self.touch_id = None
def _touch_motion(self, *event: int) -> None:
timestamp, touch_id, x, y = event
if touch_id == getattr(self, 'touch_id', None):
self._pointer_motion(timestamp, x, y)
def _touch_frame(self) -> None:
self.dirty = True
def _touch_cancel(self) -> None:
self.touch_id = None
self.pressed_widget = None
self.window.keyboard.stop_backspace_repeat()
def _mouse_event(self, kind: QEvent.Type) -> None:
point = self.position.toPoint()
target = self.pressed_widget or self.window.childAt(point) or self.window.keyboard
if kind == QEvent.Type.MouseButtonPress:
self.pressed_widget = target
local = QPointF(target.mapFrom(self.window, point))
button = Qt.MouseButton.NoButton if kind == QEvent.Type.MouseMove else Qt.MouseButton.LeftButton
held = self.pressed_widget is not None and kind != QEvent.Type.MouseButtonRelease
buttons = Qt.MouseButton.LeftButton if held else Qt.MouseButton.NoButton
event = QMouseEvent(kind, local, self.position, button, buttons, Qt.KeyboardModifier.NoModifier)
QApplication.sendEvent(target, event)
if kind == QEvent.Type.MouseButtonRelease:
self.pressed_widget = None
self.dirty = True
def hide_layer(self) -> None:
self.wanted_visible = self.configured = False
self.pressed_widget = None
self._destroy(self.layer, 7)
self._destroy(self.surface, 0)
self.layer = self.surface = None
self.lib.wl_display_flush(self.display)
def shutdown(self) -> None:
self.timer.stop()
self.notifier.setEnabled(False)
if self.display:
for proxy in reversed(self.proxies):
self.lib.wl_proxy_destroy(proxy)
self.proxies.clear()
self.lib.wl_display_disconnect(self.display)
self.display = None
for buffer in self.buffers.values():
buffer['memory'].close()
self.buffers.clear()
-336
View File
@@ -1,336 +0,0 @@
"""Reuse the embedded keyboard's buttons and theme for system input."""
import os
import sys
from types import SimpleNamespace
from typing import Any, cast
import orjson
from evdev import ecodes
from PySide6.QtCore import QEvent, QObject, QPoint, Qt
from PySide6.QtGui import QCloseEvent, QMouseEvent
from PySide6.QtWidgets import QApplication, QFrame, QLabel, QPushButton, QWidget
from portprotonqt.config import gamepad_config, ui_config
from portprotonqt.input_manager.constants import GamepadType
from portprotonqt.keyboard_layouts import keyboard_layouts
from portprotonqt.logger import get_logger
from portprotonqt.tabs.control_hints import MainWindowControlHintsMixin
from portprotonqt.theme_manager import ThemeManager
from portprotonqt.virtual_keyboard import VirtualKeyboard, LAYOUT_DISPLAY_NAMES
from .input import KEY_ROWS, SystemInputWorker
from .wayland_detection import compositor
logger = get_logger(__name__)
def report(event: str, value: object = None) -> None:
sys.stdout.buffer.write(orjson.dumps({'event': event, 'value': value}) + b'\n')
sys.stdout.buffer.flush()
class SystemKeyboardPanel(VirtualKeyboard):
def __init__(self, owner: 'SystemKeyboardWindow', theme: Any) -> None:
self.owner = owner
self.keycodes: dict[str, int] = {}
self.labels: dict[str, str] = {}
self.modifiers: set[int] = set()
self.layout_name = 'System'
self.drag_origin: QPoint | None = None
super().__init__(owner, theme)
self.set_slide_animation_enabled(False)
self.setObjectName('systemKeyboard')
self.keyboard_container.setObjectName('systemKeyboardContainer')
self.refresh_theme(theme)
def refresh_theme(self, theme: Any) -> None:
super().refresh_theme(theme)
self.setStyleSheet(theme.VIRTUAL_KEYBOARD_STYLE + theme.SYSTEM_KEYBOARD_BACKGROUND_STYLE)
def get_layouts_setxkbmap(self) -> list[str]:
return ['us']
def _space_button_text(self) -> str:
return f'Space · {LAYOUT_DISPLAY_NAMES.get(self.layout_name, self.layout_name)}'
def _save_focused_coords(self) -> tuple[int, int] | None:
current = self.selected_button
if current is None:
return None
index = self.keyboard_layout.indexOf(current)
if index < 0:
return None
row, column, _, _ = cast(tuple[int, int, int, int], self.keyboard_layout.getItemPosition(index))
return row, column
def _apply_responsive_metrics(self) -> None:
metrics = self.theme.SYSTEM_KEYBOARD
width = min(self.owner.width(), metrics['width'])
available = width - self.margins * 2 - self.spacing * (self.num_cols - 1)
self.button_width = min(self.max_button_width,
max(metrics['minimum_key_width'], available // self.num_cols))
def update_keyboard(self) -> None:
shifted = self.shift_pressed
self.shift_pressed = False
super().update_keyboard()
self.shift_pressed = shifted
self.keycodes.clear()
for row, codes in zip(keyboard_layouts['us']['normal'], KEY_ROWS, strict=True):
self.keycodes.update(zip(row, codes, strict=True))
self.apply_key_state()
if self.owner.warning_message:
warning = QLabel(self.owner.warning_message)
warning.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
warning.setWordWrap(True)
self.keyboard_layout.addWidget(warning, 5, 0, 1, self.num_cols)
for button in self.findChildren(QPushButton):
button.setFocusPolicy(Qt.FocusPolicy.NoFocus)
def apply_key_state(self) -> None:
for key, button in self.buttons.items():
code = self.keycodes.get(key)
if code not in {None, ecodes.KEY_TAB, ecodes.KEY_CAPSLOCK, ecodes.KEY_LEFTSHIFT} and str(code) in self.labels:
text = self.labels[str(code)].replace('&', '&&')
if button.text() != text:
button.setText(text)
for button in self.findChildren(QPushButton):
checked = None
if button.text() == 'CAPS':
checked = self.caps_lock
elif button.text() == '⬆':
checked = self.shift_pressed
elif button.text().startswith('Space · '):
button.setText(self._space_button_text())
if checked is not None and button.isChecked() != checked:
button.setChecked(checked)
button.style().unpolish(button)
button.style().polish(button)
button.update()
def _release_modifiers(self) -> None:
self.modifiers.clear()
self.shift_pressed = False
self.owner.worker.commands.put(('release', ()))
self.apply_key_state()
def on_button_click(self, key: str) -> None:
code = ecodes.KEY_SPACE if key == ' ' else self.keycodes.get(key)
if code is not None:
self.owner.worker.commands.put(('tap', (code,)))
def on_backspace_click(self) -> None:
self.owner.worker.commands.put(('tap', (ecodes.KEY_BACKSPACE,)))
def on_enter_click(self) -> None:
self.owner.worker.commands.put(('tap', (ecodes.KEY_ENTER,)))
def on_clear_click(self) -> None:
self.owner.worker.commands.put(('tap', (ecodes.KEY_LEFTCTRL, ecodes.KEY_A)))
self.owner.worker.commands.put(('tap', (ecodes.KEY_BACKSPACE,)))
def on_caps_click(self) -> None:
self.apply_key_state()
self.owner.worker.commands.put(('caps', ()))
def on_shift_click(self, checked: bool) -> None:
self.shift_pressed = checked
if checked:
self.modifiers.add(ecodes.KEY_LEFTSHIFT)
else:
self.modifiers.discard(ecodes.KEY_LEFTSHIFT)
self.owner.worker.commands.put(('modifiers', tuple(sorted(self.modifiers))))
self.apply_key_state()
def on_lang_click(self) -> None:
self.owner.worker.commands.put(('language', ()))
def up_key(self) -> None:
self.owner.worker.commands.put(('tap', (ecodes.KEY_UP,)))
def down_key(self) -> None:
self.owner.worker.commands.put(('tap', (ecodes.KEY_DOWN,)))
def left_key(self) -> None:
self.owner.worker.commands.put(('tap', (ecodes.KEY_LEFT,)))
def right_key(self) -> None:
self.owner.worker.commands.put(('tap', (ecodes.KEY_RIGHT,)))
def hide(self) -> None:
self.stop_backspace_repeat()
QFrame.hide(self)
if getattr(self.owner, 'keyboard', None) is self:
self.owner.hide_keyboard()
def eventFilter(self, obj: QObject, event: QEvent) -> bool:
return QFrame.eventFilter(self, obj, event)
def mousePressEvent(self, event: QMouseEvent) -> None:
if event.button() == Qt.MouseButton.LeftButton:
self.drag_origin = event.globalPosition().toPoint()
event.accept()
return
super().mousePressEvent(event)
def mouseMoveEvent(self, event: QMouseEvent) -> None:
if self.drag_origin is not None:
position = event.globalPosition().toPoint()
delta = position - self.drag_origin
self.drag_origin = position
if self.owner.layer_shell:
position = self.pos() + delta
self.move(max(0, min(position.x(), self.owner.width() - self.width())),
max(0, min(position.y(), self.owner.height() - self.height())))
else:
self.owner.move(self.owner.pos() + delta)
event.accept()
return
super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event: QMouseEvent) -> None:
self.drag_origin = None
super().mouseReleaseEvent(event)
class SystemKeyboardWindow(QWidget, MainWindowControlHintsMixin):
def __init__(self) -> None:
super().__init__(None, Qt.WindowType.Tool | Qt.WindowType.FramelessWindowHint
| Qt.WindowType.WindowStaysOnTopHint | Qt.WindowType.WindowDoesNotAcceptFocus)
self.setWindowTitle('PortProtonQt System Keyboard')
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
self.setAttribute(Qt.WidgetAttribute.WA_X11NetWmWindowTypeDock)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.layer_shell = compositor(os.environ) is not None
self.native_layer: Any = None
self.theme_manager = ThemeManager()
self.theme = self.theme_manager.apply_theme(ui_config.get_theme())
gtype = GamepadType.PLAYSTATION if gamepad_config.get_gamepad_type() == 'playstation' else GamepadType.XBOX
self.input_manager = SimpleNamespace(gamepad_type=gtype)
self.worker = SystemInputWorker()
self.ready = False
self.wanted_visible = False
self.warning_message = ''
self.resize(self.theme.SYSTEM_KEYBOARD['width'], self.theme.SYSTEM_KEYBOARD['height'])
self.keyboard = SystemKeyboardPanel(self, self.theme)
self.worker.ready.connect(self._ready)
self.worker.failed.connect(self._failed)
self.worker.state_changed.connect(self._state_changed)
self.worker.warning.connect(self._warning)
self._position_keyboard()
screen = self.screen()
if screen is not None:
screen.availableGeometryChanged.connect(self._position_keyboard)
screen.geometryChanged.connect(self._position_keyboard)
def _position_keyboard(self) -> None:
screen = self.screen()
if screen is None:
return
metrics = self.theme.SYSTEM_KEYBOARD
area = screen.geometry() if self.layer_shell else screen.availableGeometry()
available_width = self.width() if self.layer_shell else area.width()
width, height = min(available_width, metrics['width']), metrics['height']
if self.warning_message:
height += metrics['warning_height']
if self.layer_shell:
self.keyboard.setFixedSize(width, height)
self.keyboard.move((self.width() - width) // 2, max(0, self.height() - height))
else:
self.resize(width, height)
self.move(area.x() + (area.width() - width) // 2, area.bottom() - height + 1)
self.keyboard.setFixedSize(width, height)
self.keyboard.move(0, 0)
self.keyboard.update_keyboard()
def show_keyboard(self) -> None:
self.wanted_visible = True
if not self.ready:
return
self.worker.enabled.set()
self._position_keyboard()
self.keyboard.show()
self.show()
self.keyboard.raise_()
if self.native_layer is not None:
self.native_layer.show_layer()
def hide_keyboard(self) -> None:
self.wanted_visible = False
self.worker.cancel_pending()
self.keyboard.stop_backspace_repeat()
self.keyboard._release_modifiers()
if self.native_layer is not None:
self.native_layer.hide_layer()
self.hide()
report('hidden')
def _ready(self) -> None:
self.ready = True
if self.wanted_visible:
self.show_keyboard()
def _failed(self, message: str) -> None:
logger.error('System keyboard: %s. Requires evdev and access to /dev/uinput.', message)
app = QApplication.instance()
if app is not None:
app.exit(1)
def _warning(self, message: str) -> None:
logger.warning('System keyboard: %s', message)
if self.warning_message != message:
self.warning_message = message
self._position_keyboard()
def _state_changed(self, state: dict[str, Any]) -> None:
changed = self.keyboard.labels != state['labels'] or self.keyboard.caps_lock != state['caps']
changed |= self.keyboard.shift_pressed != state['shift']
changed |= self.keyboard.modifiers != set(state['modifiers'])
changed |= self.keyboard.layout_name != state['layout']
self.keyboard.labels = state['labels']
self.keyboard.caps_lock = state['caps']
self.keyboard.shift_pressed = state['shift']
self.keyboard.modifiers = set(state['modifiers'])
self.keyboard.layout_name = state['layout']
self.keyboard.apply_key_state()
if changed:
report('shift', state['shift'])
def command(self, action: str, value: Any = None) -> None:
if action == 'show':
self.show_keyboard()
elif action == 'hide':
self.hide_keyboard()
elif action == 'theme' and isinstance(value, str):
self.theme = self.theme_manager.apply_theme(value)
self.keyboard.refresh_theme(self.theme)
self.keyboard.current_theme_name = value
self._position_keyboard()
elif action == 'gamepad' and isinstance(value, str):
self.input_manager.gamepad_type = GamepadType(value)
self.keyboard.update_keyboard()
elif action == 'direction' and value in ('up', 'down', 'left', 'right'):
self.keyboard.focusNextKey(value)
elif action == 'button' and self.ready and self.wanted_visible:
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 value == 'shift':
self.keyboard.on_shift_click(not self.keyboard.shift_pressed)
elif value in handlers:
handlers[value]()
elif action == 'quit':
app = QApplication.instance()
if app is not None:
app.quit()
def closeEvent(self, event: QCloseEvent) -> None:
event.ignore()
self.hide_keyboard()
def shutdown(self) -> None:
self.keyboard.stop_backspace_repeat()
self.worker.stop()
if self.native_layer is not None:
self.native_layer.shutdown()
+21 -10
View File
@@ -1,4 +1,5 @@
import os
import sys
from typing import TYPE_CHECKING, Any
from PySide6.QtCore import QObject, QRect, QSize, Qt, QTimer
@@ -229,6 +230,9 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
self.egsAccountTitle.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
gogForm.addRow(self.egsAccountTitle, egs_buttons)
self._update_egs_account_state()
if sys.platform == "darwin":
self.gogLoginButton.setEnabled(False)
self.egsLoginButton.setEnabled(False)
self.timeDetailCombo = CustomComboBox(theme=self.theme)
self.timeDetailCombo.view().window().setWindowFlags(
@@ -407,6 +411,8 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
autostart_layout.addWidget(self.autostartTitle)
autostart_layout.addStretch()
uiForm.addRow(autostart_layout)
if sys.platform == "darwin":
uiForm.setRowVisible(autostart_layout, False)
self.startMinimizedCheckBox = QCheckBox()
self.startMinimizedCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
@@ -565,7 +571,7 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
uiForm.addRow(disable_alt_dependency_check_layout)
disable_runtime_download_layout = None
if not os.getenv("FLATPAK_ID"):
if sys.platform != "darwin" and not os.getenv("FLATPAK_ID"):
self.disableRuntimeDownloadCheckBox = QCheckBox()
self.disableRuntimeDownloadCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
self.disableRuntimeDownloadCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -596,6 +602,8 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
steam_compat_layout.addWidget(self.steamCompatTitle)
steam_compat_layout.addStretch()
uiForm.addRow(steam_compat_layout)
if sys.platform == "darwin":
uiForm.setRowVisible(steam_compat_layout, False)
self.disableSteamProtonScanningCheckBox = QCheckBox()
self.disableSteamProtonScanningCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
@@ -611,8 +619,10 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
disable_steam_proton_scanning_layout.addWidget(self.disableSteamProtonScanningTitle)
disable_steam_proton_scanning_layout.addStretch()
uiForm.addRow(disable_steam_proton_scanning_layout)
if sys.platform == "darwin":
uiForm.setRowVisible(disable_steam_proton_scanning_layout, False)
if get_steam_compatibilitytools_dir() is not None:
if sys.platform != "darwin" and get_steam_compatibilitytools_dir() is not None:
self.downloadWineToSteamCheckBox = QCheckBox()
self.downloadWineToSteamCheckBox.setStyleSheet(self.theme.CHECKBOX_STYLE)
self.downloadWineToSteamCheckBox.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
@@ -769,7 +779,7 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
hwForm.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
scrollLayout.addWidget(hwFrame)
filtered_gpu_list = get_selectable_gpu_list()
filtered_gpu_list = [] if sys.platform == "darwin" else get_selectable_gpu_list()
hwFrame.setVisible(len(filtered_gpu_list) > 1)
if len(filtered_gpu_list) > 1:
self.gpuCombo = CustomComboBox(theme=self.theme)
@@ -1106,7 +1116,7 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
autostart_enabled = self.autostartCheckBox.isChecked()
display_config.set_autostart_enabled(autostart_enabled)
if not apply_xdg_autostart(autostart_enabled):
if sys.platform != "darwin" and not apply_xdg_autostart(autostart_enabled):
QMessageBox.warning(self, _("Error"), _("Failed to update xdg-autostart entry."))
start_minimized = self.startMinimizedCheckBox.isChecked()
@@ -1116,12 +1126,13 @@ class MainWindowSettingsTabMixin(_MainWindowTypingBase):
tray_menu_mode = self.tray_menu_mode_keys[tray_menu_mode_idx]
display_config.set_tray_menu_mode(tray_menu_mode)
steam_compat = self.steamCompatCheckBox.isChecked()
currently_installed = is_steam_compat_tool_installed()
if steam_compat and not currently_installed:
add_steam_compat_tool()
elif not steam_compat and currently_installed:
remove_steam_compat_tool()
if sys.platform != "darwin":
steam_compat = self.steamCompatCheckBox.isChecked()
currently_installed = is_steam_compat_tool_installed()
if steam_compat and not currently_installed:
add_steam_compat_tool()
elif not steam_compat and currently_installed:
remove_steam_compat_tool()
ui_config.set_disable_steam_proton_scanning(self.disableSteamProtonScanningCheckBox.isChecked())
+8 -6
View File
@@ -1,4 +1,5 @@
import os
import sys
import shlex
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, cast
@@ -36,12 +37,13 @@ from portprotonqt.localization import _
from portprotonqt.logger import get_logger
from portprotonqt.sound_manager import SoundManager
from portprotonqt.preloader import Preloader
from portprotonqt.system_manager import (
AudioManagerWorker,
BluetoothManagerWorker,
NetworkManagerWorker,
StorageManagerWorker,
)
if sys.platform != "darwin":
from portprotonqt.system_manager import (
AudioManagerWorker,
BluetoothManagerWorker,
NetworkManagerWorker,
StorageManagerWorker,
)
logger = get_logger(__name__)
+13
View File
@@ -1,4 +1,5 @@
import os
import sys
import re
import shutil
from typing import TYPE_CHECKING, Any
@@ -152,6 +153,9 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
self.defaultVulkanTitleLabel.setStyleSheet(self.theme.PARAMS_TITLE_STYLE)
self.defaultVulkanTitleLabel.setFocusPolicy(Qt.FocusPolicy.NoFocus)
formLayout.addRow(self.defaultVulkanTitleLabel, self.defaultVulkanCombo)
if sys.platform == "darwin":
self.defaultVulkanTitleLabel.hide()
self.defaultVulkanCombo.hide()
layout.addLayout(formLayout)
@@ -195,6 +199,9 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
(_("Manage WINE versions"), self.show_proton_manager),
]
if sys.platform == "darwin":
additional_buttons = [item for item in additional_buttons
if item[1] == self.show_proton_manager]
for i, (text, callback) in enumerate(additional_buttons):
row = i // 2
col = i % 2
@@ -243,6 +250,12 @@ class MainWindowWineTabMixin(_MainWindowTypingBase):
self.wine_progress_bar.setVisible(True)
proc = QProcess(self)
if sys.platform == "darwin":
proc.setUnixProcessParameters(QProcess.UnixProcessFlag.CreateNewSession)
if not hasattr(self, "wine_tool_processes"):
self.wine_tool_processes = []
self.wine_tool_processes.append(proc)
proc.finished.connect(lambda: self.wine_tool_processes.remove(proc))
process_env = QProcessEnvironment.systemEnvironment()
if env_vars.get("DISABLE_CP_DEFPFX") == "1":
process_env.insert("DISABLE_CP_DEFPFX", "1")
+17
View File
@@ -1,3 +1,7 @@
import os
import signal
import sys
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
@@ -16,6 +20,19 @@ class MainWindowWorkersMixin:
if not process.waitForFinished():
process.kill()
process.waitForFinished()
for process in list(getattr(self, "wine_tool_processes", [])):
if sys.platform == "darwin" and process.processId():
try:
os.killpg(process.processId(), signal.SIGKILL)
except ProcessLookupError:
logger.debug("Wine tool process group already exited")
except OSError as error:
logger.warning("Failed to stop Wine tool process group: %s", error)
process.terminate()
if not process.waitForFinished():
process.kill()
process.waitForFinished()
self.wine_tool_processes = []
worker_timeouts = {
"networkWorker": 3000,
"bluetoothWorker": 12000,
+7 -2
View File
@@ -3,14 +3,13 @@ import asyncio
import hashlib
import importlib.util
import os
import sys
import re
import shutil
import stat
import xml.etree.ElementTree as ET
from typing import Any, cast
import orjson
from dbus_fast import BusType
from dbus_fast.aio import MessageBus
from portprotonqt.logger import get_logger
from portprotonqt.theme_security import (
check_theme_directory_safety,
@@ -24,6 +23,10 @@ from portprotonqt.config import CACHE_DIR, ui_config, load_theme_metainfo
from portprotonqt.config.ui import _is_system_light_theme, _unwrap_variant
from portprotonqt.qt_utils import get_device_pixel_ratio
if sys.platform != "darwin":
from dbus_fast import BusType
from dbus_fast.aio import MessageBus
# Icon caching for performance optimization
_icon_cache = {}
# Directory structure cache for performance optimization
@@ -950,6 +953,8 @@ class SystemThemeWatcher(QThread):
self._poll_system_theme()
async def _watch_portal(self) -> None:
if sys.platform == "darwin":
raise OSError("Desktop portal is Linux-only")
bus = await MessageBus(bus_type=BusType.SESSION).connect()
try:
introspection = await bus.introspect(
@@ -313,12 +313,6 @@ virtual_keyboard_fade_animation_duration = 140
virtual_keyboard_slide_fade_animation_duration = 180
virtual_keyboard_slide_bounce_animation_duration = 220
virtual_keyboard_animation_type = "slide"
SYSTEM_KEYBOARD = {
"width": 1000,
"height": 220,
"minimum_key_width": 18,
"warning_height": 36,
}
DETAIL_PAGE_LAYOUT_MODE = "full"
COMPATIBILITY_REPORT_DIALOG = {
@@ -44,16 +44,6 @@ CONTEXT_MENU_STYLE = f"""
}}
"""
SYSTEM_KEYBOARD_BACKGROUND_STYLE = f"""
QFrame#systemKeyboard {{
background: {color_bg};
border-radius: {border_radius_small};
}}
QWidget#systemKeyboardContainer {{
background: {color_transparent};
}}
"""
VIRTUAL_KEYBOARD_STYLE = f"""
QWidget {{
background: {color_overlay};
-4
View File
@@ -104,10 +104,6 @@ class TrayManager:
self.tray_menu.addAction(self.pause_game_action)
self.tray_menu.addAction(self.stop_game_action)
self.update_game_actions()
system_keyboard = getattr(getattr(self, 'main_window', None), 'system_keyboard', None)
if system_keyboard is not None:
keyboard_action = self.tray_menu.addAction('System Keyboard · Start + Y')
keyboard_action.triggered.connect(system_keyboard.toggle)
if self.minimal_mode:
return
self.tray_menu.addSeparator()
+1 -1
View File
@@ -23,7 +23,7 @@ classifiers = [
]
dependencies = [
"babel>=2.18.0",
"evdev>=2.0.0",
"evdev>=2.0.0; sys_platform == 'linux'",
"libarchive-c>=5.3",
"orjson>=3.12.0",
"pillow>=12.3.0",
+377
View File
@@ -0,0 +1,377 @@
"""Native macOS Wine integration regressions, without a macOS host or network."""
from pathlib import Path
from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import Mock
import orjson
import pytest
from portprotonqt import macos
@pytest.mark.parametrize("layout", [
"bin/wine", "bin/wine64", "Wine.app/Contents/Resources/wine/bin/wine",
"Contents/Resources/wine/bin/wine64", "wswine.bundle/bin/wine64",
"wine-devel/bin/wine", "Wine.app/Contents/SharedSupport/wine/bin/wine64",
])
def test_find_wine_bundle_layouts(tmp_path: Path, layout: str) -> None:
binary = tmp_path / layout
binary.parent.mkdir(parents=True)
binary.write_text("wine", encoding="utf-8")
assert macos.find_wine(tmp_path) is None
binary.chmod(0o755)
assert macos.find_wine(tmp_path) == binary
@pytest.mark.parametrize("name", ["", "..", "../outside", "/tmp/wine", "nested/wine"])
def test_version_paths_reject_traversal(tmp_path: Path, name: str) -> None:
with pytest.raises(ValueError):
macos.version_directory(tmp_path, name)
def test_version_paths_reject_symlink_escape(tmp_path: Path) -> None:
dist = tmp_path / "data/dist"
dist.mkdir(parents=True)
(dist / "escape").symlink_to(tmp_path)
with pytest.raises(ValueError):
macos.version_directory(tmp_path, "escape")
def test_native_command_uses_selected_version_prefix_and_arguments(tmp_path: Path) -> None:
binary = macos.version_directory(tmp_path, "Wine 1") / "wswine.bundle/bin/wine64"
binary.parent.mkdir(parents=True)
binary.write_text("wine", encoding="utf-8")
binary.chmod(0o755)
command, environment = macos.wine_command(tmp_path, ["/games/A game.exe", "a b"], {
"PW_WINE_USE": "Wine 1", "PW_PREFIX_NAME": "GAME",
})
assert command == [str(binary), "/games/A game.exe", "a b"]
assert environment["WINEPREFIX"] == str(tmp_path / "data/prefixes/GAME")
assert environment["PATH"].split(":")[0] == str(binary.parent)
def test_native_command_does_not_fallback_from_missing_selection(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(macos.shutil, "which", lambda _name: "/usr/bin/wine")
with pytest.raises(FileNotFoundError):
macos.wine_command(tmp_path, ["game.exe"], {"PW_WINE_USE": "missing"})
@pytest.mark.parametrize("prefix", ["..", "../other", "/tmp/prefix"])
def test_native_command_rejects_prefix_traversal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, prefix: str) -> None:
monkeypatch.setattr(macos.shutil, "which", lambda _name: "/usr/bin/wine")
with pytest.raises(ValueError):
macos.wine_command(tmp_path, ["game.exe"], {"PW_PREFIX_NAME": prefix})
def test_settings_roundtrip_is_data_not_shell(tmp_path: Path) -> None:
path = tmp_path / "game.exe.ppdb"
values = {"PW_WINE_USE": "Wine Crossover", "PW_PREFIX_NAME": "GAME", "VALUE": "$(touch /tmp/not-run)"}
macos.write_settings(path, values)
assert macos.read_settings(path) == values
@pytest.mark.parametrize("values", [
{"BAD;command": "value"}, {"BAD\nNAME": "value"},
{"VALUE": "first\nsecond"}, {"VALUE": "first\rsecond"},
])
def test_invalid_settings_preserve_existing_file(tmp_path: Path, values: dict[str, str]) -> None:
path = tmp_path / "game.exe.ppdb"
original = 'export PW_PREFIX_NAME=GAME\n'
path.write_text(original)
with pytest.raises(ValueError):
macos.write_settings(path, values)
assert path.read_text() == original
assert not path.with_name(path.name + ".tmp").exists()
def test_adapter_cli_edits_existing_ppdb_and_shows_dialog_format(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path))
executable = str(tmp_path / "game.exe")
assert macos.main(["cli", "--edit-db", executable, "PW_WINE_USE=Wine 1", "PW_PREFIX_NAME=GAME"]) == 0
assert macos.main(["cli", "--show-ppdb", executable]) == 0
assert 'PW_WINE_USE="Wine 1"' in capsys.readouterr().out
assert macos.main(["cli", "--set-user-conf", "PW_DEFAULT_WINE_USE", "Wine 2"]) == 0
assert macos.main(["cli", "--get-user-conf", "PW_DEFAULT_WINE_USE"]) == 0
assert capsys.readouterr().out.strip() == "Wine 2"
def test_adapter_exec_preserves_owned_pid_and_arguments(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path))
executable = tmp_path / "A game.exe"
executable.touch()
monkeypatch.setattr(macos.os, "chdir", Mock())
macos.write_settings(Path(str(executable) + ".ppdb"), {"PW_PREFIX_NAME": "GAME"})
monkeypatch.setattr(macos.shutil, "which", lambda _name: "/opt/homebrew/bin/wine")
execute = Mock()
monkeypatch.setattr(macos.os, "execvpe", execute)
assert macos.main([str(executable), "a b"]) == 0
assert execute.call_args.args[1] == ["/opt/homebrew/bin/wine", str(executable), "a b"]
assert execute.call_args.args[2]["WINEPREFIX"] == str(tmp_path / "data/prefixes/GAME")
def test_adapter_tools_use_existing_wine_and_prefix_selection(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path))
binary = macos.version_directory(tmp_path, "Wine 1") / "bin/wine"
binary.parent.mkdir(parents=True)
binary.touch(mode=0o755)
execute = Mock()
monkeypatch.setattr(macos.os, "execvpe", execute)
assert macos.main(["cli", "--winecfg", "Wine 1", "TEST"]) == 0
assert execute.call_args.args[1] == [str(binary), "winecfg"]
assert execute.call_args.args[2]["WINEPREFIX"].endswith("/TEST")
assert macos.main(["cli", "--autoinstall", "linux.sh"]) == 1
def test_catalog_loader_uses_forgejo_and_completes_once(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt.dialogs import wine_loader
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path))
monkeypatch.setattr(wine_loader.sys, "platform", "darwin")
monkeypatch.setattr("portprotonqt.portproton_api.get_user_conf_setting", lambda _key: "GITHUB")
metadata = {"wine-crossover": [{"name": "Wine 1", "url": "https://example.org/wine.tar.xz", "size_human": "1 MiB"}]}
response = SimpleNamespace(raise_for_status=lambda: None, iter_content=lambda **_kwargs: [orjson.dumps(metadata)])
get = Mock(return_value=response)
monkeypatch.setattr(wine_loader, "get_requests_session", lambda: SimpleNamespace(get=get))
worker = wine_loader.WineLoadingThread()
success, failure = Mock(), Mock()
worker.loading_complete.connect(success)
worker.loading_error.connect(failure)
worker.run()
assert get.call_args.args[0] == macos.MACOS_WINE_METADATA_URL
success.assert_called_once_with(metadata)
failure.assert_not_called()
@pytest.mark.parametrize("entry", [{"name": "../escape", "url": "https://example.org/a"}, {"name": "Wine", "url": "http://example.org/a"}])
def test_catalog_rejects_unsafe_download_paths(entry: dict[str, str]) -> None:
with pytest.raises(ValueError):
macos.validate_catalog({"wine-crossover": [entry]})
def test_manager_installs_and_detects_separate_bundle_versions(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt.dialogs import proton_manager
monkeypatch.setattr(proton_manager.sys, "platform", "darwin")
manager = SimpleNamespace(portproton_location=str(tmp_path))
for name in ("Wine 1", "Wine 2"):
destination = proton_manager.ProtonManager.get_download_extract_dir(cast(Any, manager), {"asset_name": name})
binary = Path(destination) / "wswine.bundle/bin/wine64"
binary.parent.mkdir(parents=True)
binary.touch(mode=0o755)
assert proton_manager.ProtonManager.is_asset_installed(cast(Any, manager), name, "sikarugir-engines")
assert proton_manager.ProtonManager.is_installed_version_dir(cast(Any, manager), destination)
assert proton_manager.ProtonManager.filter_entries_by_cpu_level(cast(Any, manager), [{"name": "x86_64"}], "wine-crossover") == [{"name": "x86_64"}]
def test_darwin_config_selects_native_backend(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt.config import portproton
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path / "data root"))
monkeypatch.setattr(portproton.sys, "platform", "darwin")
assert portproton.get_portproton_location() == str(tmp_path / "data root")
command = portproton.get_portproton_start_command()
assert command is not None
assert command[1:] == ["-m", "portprotonqt.macos"]
def test_shutdown_waits_for_retained_wine_tools() -> None:
from portprotonqt.tabs.workers import MainWindowWorkersMixin
process = Mock()
process.waitForFinished.side_effect = [False, True]
window = SimpleNamespace(wine_tool_processes=[process], _stopWorkerThread=Mock(), _stopWorkerThreads=Mock())
MainWindowWorkersMixin._stopBackgroundWorkers(cast(Any, window))
process.terminate.assert_called_once()
process.kill.assert_called_once()
assert process.waitForFinished.call_count == 2
assert window.wine_tool_processes == []
def test_macos_extraction_is_per_version_and_rejects_escape(tmp_path: Path) -> None:
import io
import tarfile
from portprotonqt.dialogs.wine_extractor import ExtractionThread
archive = tmp_path / "wine.tar"
with tarfile.open(archive, "w") as stream:
entry = tarfile.TarInfo("wswine.bundle/bin/wine64")
entry.mode = 0o755
entry.size = len(b"wine")
stream.addfile(entry, io.BytesIO(b"wine"))
destination = macos.version_directory(tmp_path, "Engine 1")
worker = ExtractionThread(str(archive), str(destination))
worker.run()
assert macos.find_wine(destination) == destination / "wswine.bundle/bin/wine64"
assert not macos.version_directory(tmp_path, "Engine 2").exists()
with tarfile.open(archive, "w") as stream:
entry = tarfile.TarInfo("../escape")
entry.size = len(b"bad")
stream.addfile(entry, io.BytesIO(b"bad"))
worker = ExtractionThread(str(archive), str(destination))
failure = Mock()
worker.error.connect(failure)
worker.run()
failure.assert_called_once()
assert not (destination.parent / "escape").exists()
def test_macos_shutdown_kills_only_owned_groups_and_waits(monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt import main_window
monkeypatch.setattr(main_window.sys, "platform", "darwin")
kill_group = Mock()
monkeypatch.setattr(main_window.os, "killpg", kill_group)
process = Mock(pid=1234)
process.poll.return_value = 0
window = SimpleNamespace(game_processes=[process])
main_window.MainWindow._terminate_game_processes(cast(Any, window))
kill_group.assert_called_once_with(1234, main_window.signal.SIGKILL)
process.wait.assert_called_once_with(timeout=0)
detached = Mock()
monkeypatch.setattr(main_window.QProcess, "startDetached", detached)
assert main_window.MainWindow._run_portproton_stop_command(cast(Any, window))
detached.assert_not_called()
def test_macos_tool_shutdown_kills_session_and_waits(monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt.tabs import workers
monkeypatch.setattr(workers.sys, "platform", "darwin")
kill_group = Mock()
monkeypatch.setattr(workers.os, "killpg", kill_group)
process = Mock()
process.processId.return_value = 1234
window = SimpleNamespace(wine_tool_processes=[process], _stopWorkerThread=Mock(), _stopWorkerThreads=Mock())
workers.MainWindowWorkersMixin._stopBackgroundWorkers(cast(Any, window))
kill_group.assert_called_once_with(1234, workers.signal.SIGKILL)
process.waitForFinished.assert_called_once()
def test_macos_does_not_start_linux_virtual_mouse_worker(monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt import input_manager
monkeypatch.setattr(input_manager.sys, "platform", "darwin")
worker = Mock()
monkeypatch.setattr(input_manager, "MouseEmulationThread", worker)
manager = SimpleNamespace(mouse_emulation_enabled=True)
input_manager.InputManager._async_enable_mouse_emulation(cast(Any, manager))
assert manager.mouse_emulation_enabled is False
worker.assert_not_called()
def test_macos_settings_offer_only_implemented_engine_and_prefix(monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt import settings_manager
monkeypatch.setattr(settings_manager.sys, "platform", "darwin")
assert settings_manager.get_toggle_settings() == {}
settings = settings_manager.get_advanced_settings("disabled", ["1"], [], {}, ["Wine"], ["DEFAULT"])
assert {setting["key"] for setting in settings} == {"PW_WINE_USE", "PW_PREFIX_NAME"}
def test_explicit_system_wine_selection_uses_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(macos.shutil, "which", lambda _name: "/opt/homebrew/bin/wine")
command, _environment = macos.wine_command(tmp_path, ["game.exe"], {"PW_WINE_USE": "USE_SYSTEM_WINE"})
assert command == ["/opt/homebrew/bin/wine", "game.exe"]
def test_macos_wine_options_exclude_incomplete_engines(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
from portprotonqt import settings_manager
monkeypatch.setattr(settings_manager.sys, "platform", "darwin")
monkeypatch.setattr(settings_manager.shutil, "which", lambda _name: None)
valid = macos.version_directory(tmp_path, "Wine") / "Wine.app/Contents/Resources/wine/bin/wine"
valid.parent.mkdir(parents=True)
valid.touch(mode=0o755)
macos.version_directory(tmp_path, "incomplete").mkdir()
assert settings_manager.get_available_wine_options(str(tmp_path)) == ["Wine"]
@pytest.mark.parametrize("method", ["_launch_egs_game", "_launch_gog_game"])
def test_macos_store_wrappers_fail_explicitly_before_linux_setup(monkeypatch: pytest.MonkeyPatch, method: str) -> None:
from portprotonqt import main_window
monkeypatch.setattr(main_window.sys, "platform", "darwin")
warning = Mock()
monkeypatch.setattr(main_window.QMessageBox, "warning", warning)
window = SimpleNamespace(_finish_silent_launch=Mock(), egs_api=Mock(), gog_api=Mock())
getattr(main_window.MainWindow, method)(cast(Any, window), "game")
window._finish_silent_launch.assert_called_once()
warning.assert_called_once()
assert "macOS" in warning.call_args.args[2]
assert "directly" in warning.call_args.args[2]
assert window.egs_api.mock_calls == []
assert window.gog_api.mock_calls == []
def test_settings_ignores_predictable_temporary_symlink(tmp_path: Path) -> None:
outside = tmp_path / "outside"
outside.write_text("preserved")
path = tmp_path / "user.conf"
path.with_suffix(".conf.tmp").symlink_to(outside)
macos.write_settings(path, {"KEY": "value"})
assert outside.read_text() == "preserved"
assert macos.read_settings(path) == {"KEY": "value"}
def test_settings_replace_failure_preserves_original(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
path = tmp_path / "user.conf"
path.write_text("original")
monkeypatch.setattr(macos.os, "replace", Mock(side_effect=OSError("disk failure")))
with pytest.raises(OSError, match="disk failure"):
macos.write_settings(path, {"KEY": "value"})
assert path.read_text() == "original"
assert list(tmp_path.iterdir()) == [path]
@pytest.mark.parametrize("extension,dispatch", [
(".msi", ["msiexec", "/i"]), (".bat", ["cmd", "/c"]),
(".cmd", ["cmd", "/c"]), (".reg", ["regedit"]),
])
def test_adapter_dispatch_and_working_directory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
extension: str, dispatch: list[str]) -> None:
target = tmp_path / ("game" + extension)
target.touch()
monkeypatch.setenv("PORT_DATA_PATH", str(tmp_path))
monkeypatch.setattr(macos.shutil, "which", lambda _: "/wine")
execute, change_directory = Mock(), Mock()
monkeypatch.setattr(macos.os, "execvpe", execute)
monkeypatch.setattr(macos.os, "chdir", change_directory)
assert macos.main([str(target), "extra argument"]) == 0
assert execute.call_args.args[1] == ["/wine", *dispatch, str(target), "extra argument"]
change_directory.assert_called_once_with(tmp_path)
def test_darwin_extraction_failure_and_cancel_preserve_version(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import io
import tarfile
from portprotonqt.dialogs import wine_extractor
monkeypatch.setattr(wine_extractor.sys, "platform", "darwin")
destination = macos.version_directory(tmp_path, "Engine")
destination.mkdir(parents=True)
(destination / "original").write_text("working")
archive = tmp_path / "wine.tar"
with tarfile.open(archive, "w") as stream:
for name in ("bin/wine", "../escape"):
entry = tarfile.TarInfo(name)
entry.mode, entry.size = 0o755, 4
stream.addfile(entry, io.BytesIO(b"wine"))
worker = wine_extractor.ExtractionThread(str(archive), str(destination))
failed = Mock()
worker.error.connect(failed)
worker.run()
failed.assert_called_once()
assert list(destination.iterdir()) == [destination / "original"]
worker.stop()
worker.run()
assert list(destination.parent.iterdir()) == [destination]
def test_darwin_extraction_promotes_complete_version(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
import io
import tarfile
from portprotonqt.dialogs import wine_extractor
monkeypatch.setattr(wine_extractor.sys, "platform", "darwin")
archive = tmp_path / "wine.tar"
with tarfile.open(archive, "w") as stream:
entry = tarfile.TarInfo("bin/wine")
entry.mode, entry.size = 0o755, 4
stream.addfile(entry, io.BytesIO(b"wine"))
destination = macos.version_directory(tmp_path, "Engine")
worker = wine_extractor.ExtractionThread(str(archive), str(destination))
complete = Mock()
worker.finished.connect(complete)
worker.run()
complete.assert_called_once_with(str(archive), True)
assert macos.find_wine(destination) == destination / "bin/wine"
assert list(destination.parent.iterdir()) == [destination]
+1 -131
View File
@@ -1,10 +1,9 @@
"""Tests for the bundled PortProton shell scripts."""
import os
import shutil
import subprocess
from pathlib import Path
from pytest import mark, skip
from pytest import mark
@mark.parametrize("case", [
@@ -327,132 +326,3 @@ def test_run_after_wrapper_preserves_command_with_comma(tmp_path: Path) -> None:
capture_output=True, text=True, check=True,
)
assert result.stdout.splitlines() == ["first,second", "game"]
def test_wine_gpu_name_lookup(tmp_path: Path) -> None:
compiler = shutil.which("cc")
if compiler is None:
skip("C compiler is unavailable")
source = tmp_path / "wine_names.c"
source.write_text(
'#include <stdio.h>\n#include "wine_gpu_names.h"\n'
'int main(void) {\n'
'puts(wine_device_name(0x1002, 0x163f, "AMD Custom GPU 0405 (RADV VANGOGH)"));\n'
'puts(wine_device_name(0x10de, 0x249d, "NVIDIA GeForce RTX 3070 Laptop GPU"));\n'
'puts(wine_device_name(0x8086, 0x5912, "Intel native name"));\n'
'puts(wine_device_name(0xffff, 0x163f, "Unknown vendor"));\n'
'puts(wine_device_name(0x1002, 0xffff, "Unknown device"));\n'
'puts(wine_device_name(0x11002, 0x163f, "Non-PCI vendor"));\n'
'return 0;\n}\n',
)
binary = tmp_path / "wine_names"
subprocess.run(
[compiler, "-std=c99", "-Wall", "-Wextra", "-Werror", "-I",
str(Path("build-aux/src").resolve()), str(source), "-o", str(binary)],
capture_output=True, text=True, check=True,
)
result = subprocess.run([str(binary)], capture_output=True, text=True, check=True)
assert result.stdout.splitlines() == [
"AMD VANGOGH", "NVIDIA GeForce RTX 3070 (mobile)", "Intel(R) HD Graphics 630",
"Unknown vendor", "Unknown device", "Non-PCI vendor",
]
@mark.parametrize("names", [
("AMD Custom GPU 0405 (RADV VANGOGH)", "AMD VANGOGH"),
("NVIDIA GeForce RTX 3070 Laptop GPU", "NVIDIA GeForce RTX 3070 (mobile)"),
("Unknown GPU", "Unknown GPU"),
])
@mark.parametrize("override", [
{}, {"DXVK_FILTER_DEVICE_NAME": "custom-dxvk"},
{"VKD3D_FILTER_DEVICE_NAME": "custom-vkd3d"},
{"DXVK_FILTER_DEVICE_NAME": "", "VKD3D_FILTER_DEVICE_NAME": ""},
])
def test_gpu_selection_uses_wine_name_for_both_filters(
tmp_path: Path, names: tuple[str, str], override: dict[str, str],
) -> None:
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
function = "pw_select_gpu () {" + helper.split("pw_select_gpu () {", 1)[1].split(
"\npw_check_vulkan_extensions () {", 1,
)[0]
binary = tmp_path / "vk_gpu_info"
binary.write_text('#!/bin/bash\nprintf "%s" "$GPU_OUTPUT"\n')
binary.chmod(0o755)
native, wine = names
output = (
"GPU #0\ndevice_name: Other GPU\nwine_device_name: Other Wine GPU\n\n"
f"GPU #1\ndevice_name: {native}\nwine_device_name: {wine}\n\n"
"GPU #2\ndevice_name: Last GPU\nwine_device_name: Last Wine GPU\n"
)
result = subprocess.run(
["bash", "-c", function + '\npw_select_gpu\n'
'printf "%s\\n" "$DXVK_FILTER_DEVICE_NAME" "$VKD3D_FILTER_DEVICE_NAME" '
'"$PW_GPU_USE" "$MESA_VK_DEVICE_SELECT" "$MESA_VK_DEVICE_SELECT_FORCE_DEFAULT_DEVICE"'],
cwd=tmp_path, capture_output=True, text=True, check=True,
env={"PATH": f"{tmp_path}:{os.defpath}", "GPU_OUTPUT": output, "PW_GPU_USE": native,
"PW_vendorID": "0x1002", "PW_deviceID": "0x163f", **override},
)
assert result.stdout.splitlines() == [
override.get("DXVK_FILTER_DEVICE_NAME", wine),
override.get("VKD3D_FILTER_DEVICE_NAME", wine), native, "0x1002:0x163f", "1",
]
@mark.parametrize("case", [
("GPU #0\ndevice_name: Selected GPU\n", 0),
("GPU #0\ndevice_name: Selected GPU\nwine_device_name: \n", 0),
("GPU #0\ndevice_name: Other GPU\nwine_device_name: Other Wine GPU\n", 0),
("GPU #0\ndevice_name: Selected GPU\nwine_device_name: Wine GPU\n", 1),
])
@mark.parametrize("selected", ["Selected GPU", "disabled", ""])
def test_gpu_selection_falls_back_to_native_name(
tmp_path: Path, case: tuple[str, int], selected: str,
) -> None:
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
function = "pw_select_gpu () {" + helper.split("pw_select_gpu () {", 1)[1].split(
"\npw_check_vulkan_extensions () {", 1,
)[0]
output, status = case
binary = tmp_path / "vk_gpu_info"
binary.write_text(
'#!/bin/bash\ntouch probe-ran\nprintf "%s" "$GPU_OUTPUT"\n'
f'exit {status}\n',
)
binary.chmod(0o755)
result = subprocess.run(
["bash", "-c", function + '\nprint_warning () { echo "$*" >&2; }\npw_select_gpu\n'
'printf "%s\\n" "${DXVK_FILTER_DEVICE_NAME-unset}" '
'"${VKD3D_FILTER_DEVICE_NAME-unset}"'],
cwd=tmp_path, capture_output=True, text=True, check=True,
env={"PATH": f"{tmp_path}:{os.defpath}", "GPU_OUTPUT": output,
"PW_GPU_USE": selected, "PW_vendorID": "0x1002", "PW_deviceID": "0x163f"},
)
expected = selected if selected == "Selected GPU" else "unset"
assert result.stdout.splitlines() == [expected, expected]
assert (tmp_path / "probe-ran").exists() == (selected == "Selected GPU")
assert ("vk_gpu_info failed" in result.stderr) == (status != 0 and selected == "Selected GPU")
@mark.parametrize("exit_code", [0, 37])
def test_run_after_command_placeholder_preserves_arguments_and_status(
tmp_path: Path, exit_code: int,
) -> None:
helper = Path("build-aux/share/portproton/scripts/functions_helper").read_text()
wrapper = helper.split("pw_launch_wrapper () {", 1)[1].split(
"export -f pw_launch_wrapper", 1,
)[0]
launcher = tmp_path / "Обёртка с пробелами"
launcher.write_text(
'#!/bin/bash\nexport WRAPPER_ACTIVE=yes\nexec "$@"\n',
)
launcher.chmod(0o755)
result = subprocess.run(
["bash", "-c", "pw_launch_wrapper () {" + wrapper
+ '\npw_launch_wrapper bash -c \'printf "%s\\n" "$WRAPPER_ACTIVE" "$@"; '
+ 'exit "$EXIT_CODE"\' game "аргумент с пробелами" \'$(false)\' ""'],
env={"PATH": os.defpath, "PW_RUN_AFTER_EXE": f'"{launcher}" %command%',
"EXIT_CODE": str(exit_code)},
capture_output=True, text=True, check=False,
)
assert result.returncode == exit_code, result.stderr
assert result.stdout == "yes\nаргумент с пробелами\n$(false)\n\n"
-292
View File
@@ -1,292 +0,0 @@
"""System keyboard input, focus-independent routing and native lifecycle."""
from collections.abc import Generator
from threading import Event
from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import MagicMock
import pytest
from evdev import ecodes
from PySide6.QtCore import QObject, QPoint, Qt
from PySide6.QtGui import QImage, QRegion
from PySide6.QtWidgets import QApplication, QPushButton, QWidget
from portprotonqt.input_manager import InputManager
from portprotonqt.input_manager.constants import (PAD_BUTTON_START, PAD_BUTTON_NORTH,
PAD_BUTTON_SOUTH, SDL_CONTROLLER_BUTTON_TO_PAD)
from portprotonqt.native_gamepad import SDLGamepad
from portprotonqt.system_keyboard import SystemKeyboard
from portprotonqt.system_keyboard.input import SystemInputWorker
from portprotonqt.system_keyboard.window import SystemKeyboardWindow
from portprotonqt.system_keyboard import input as system_input
from portprotonqt.system_keyboard import window as system_window
from portprotonqt.system_keyboard import wayland_detection
from portprotonqt.system_keyboard.cosmic_detection import CosmicLayout
from portprotonqt.system_keyboard.detection import X11Layout, XkbState
from portprotonqt.system_keyboard.keys import XKB_GROUP_SHIFT
from portprotonqt.theme_manager import load_theme
@pytest.fixture
def application() -> QApplication:
return cast(QApplication, QApplication.instance() or QApplication([]))
@pytest.fixture
def keyboard_window(monkeypatch: pytest.MonkeyPatch, application: QApplication) -> Generator[SystemKeyboardWindow]:
theme = load_theme('standart')
monkeypatch.setattr(system_window.ThemeManager, 'apply_theme', lambda self, name: theme)
monkeypatch.setattr(system_window, 'compositor', lambda env: None)
monkeypatch.setattr(system_window, 'report', MagicMock())
window = SystemKeyboardWindow()
yield window
window.shutdown()
window.hide()
def test_panel_matches_embedded_layout_without_extra_rows(keyboard_window: SystemKeyboardWindow) -> None:
keyboard = keyboard_window.keyboard
assert keyboard.current_layout == 'us'
assert keyboard.keyboard_layout.rowCount() == 5
item = keyboard.keyboard_layout.itemAtPosition(3, 1)
assert item is not None
extra_iso_key = item.widget()
assert isinstance(extra_iso_key, QPushButton)
assert extra_iso_key.text() == '<'
assert keyboard.keycodes['<'] == ecodes.KEY_102ND
assert keyboard.height() == keyboard_window.theme.SYSTEM_KEYBOARD['height']
assert keyboard_window.windowFlags() & Qt.WindowType.WindowDoesNotAcceptFocus
def test_panel_sends_physical_keys_without_editing_target(keyboard_window: SystemKeyboardWindow) -> None:
keyboard = keyboard_window.keyboard
keyboard.on_button_click('q')
keyboard.on_enter_click()
keyboard.on_lang_click()
commands = keyboard_window.worker.commands
assert commands.get_nowait() == ('tap', (ecodes.KEY_Q,))
assert commands.get_nowait() == ('tap', (ecodes.KEY_ENTER,))
assert commands.get_nowait() == ('language', ())
keyboard.on_shift_click(True)
assert commands.get_nowait() == ('modifiers', (ecodes.KEY_LEFTSHIFT,))
keyboard.buttons['q'].click()
assert commands.get_nowait() == ('tap', (ecodes.KEY_Q,))
def test_hide_cancels_pending_input_and_repeat(keyboard_window: SystemKeyboardWindow) -> None:
keyboard_window.ready = True
keyboard_window.show_keyboard()
keyboard_window.keyboard.on_backspace_pressed()
keyboard_window.hide_keyboard()
assert not keyboard_window.worker.enabled.is_set()
assert keyboard_window.keyboard.backspace_timer is None
assert keyboard_window.worker.commands.get_nowait() == ('release', ())
assert not keyboard_window.isVisible()
def test_refresh_preserves_selected_key(keyboard_window: SystemKeyboardWindow) -> None:
keyboard = keyboard_window.keyboard
keyboard._set_selected_button(keyboard.buttons['q'])
original_button = keyboard.buttons['q']
original_button.setDown(True)
keyboard_window._state_changed({'labels': {str(ecodes.KEY_Q): 'й'}, 'caps': False,
'shift': False, 'modifiers': (), 'layout': 'ru'})
assert keyboard.selected_button is keyboard.buttons['q']
assert keyboard.buttons['q'].text() == 'й'
assert keyboard.buttons['q'] is original_button
assert original_button.isDown()
def test_caps_highlight_and_space_follow_system_state(keyboard_window: SystemKeyboardWindow) -> None:
keyboard = keyboard_window.keyboard
button = keyboard.buttons['CAPS']
keyboard_window._state_changed({'labels': {str(ecodes.KEY_CAPSLOCK): '', str(ecodes.KEY_Q): 'Й'},
'caps': True, 'shift': False, 'modifiers': (), 'layout': 'ru'})
assert button.text() == 'CAPS'
assert button.isChecked()
assert keyboard.buttons['q'].text() == 'Й'
item = keyboard.keyboard_layout.itemAtPosition(4, 1)
assert item is not None
space = item.widget()
assert isinstance(space, QPushButton)
assert space.text() == f'Space · {system_window.LAYOUT_DISPLAY_NAMES["ru"]}'
keyboard_window._state_changed({'labels': {str(ecodes.KEY_Q): 'q'}, 'caps': False,
'shift': False, 'modifiers': (), 'layout': 'us'})
assert not button.isChecked()
assert space.text() == f'Space · {system_window.LAYOUT_DISPLAY_NAMES["us"]}'
def test_panel_has_themed_background(keyboard_window: SystemKeyboardWindow) -> None:
keyboard_window.ready = True
keyboard_window.show_keyboard()
QApplication.processEvents()
image = QImage(keyboard_window.size(), QImage.Format.Format_ARGB32_Premultiplied)
image.fill(Qt.GlobalColor.transparent)
keyboard_window.render(image, QPoint(), QRegion(), QWidget.RenderFlag.DrawChildren)
assert image.pixelColor(0, 0).alpha() == 0
assert image.pixelColor(1, keyboard_window.height() // 2).alpha() > 0
def test_caps_button_does_not_keep_unconfirmed_local_toggle(keyboard_window: SystemKeyboardWindow) -> None:
button = keyboard_window.keyboard.buttons['CAPS']
button.click()
assert not button.isChecked()
assert keyboard_window.worker.commands.get_nowait() == ('caps', ())
button.setChecked(True)
keyboard_window._state_changed({'labels': {}, 'caps': False, 'shift': False,
'modifiers': (), 'layout': 'System'})
assert not button.isChecked()
def test_x11_labels_use_xkb_group_bits(application: QApplication) -> None:
layout: Any = X11Layout.__new__(X11Layout)
state = XkbState()
state.group = 1
layout.state = lambda: state
layout.display = 123
layout.lib = MagicMock()
layout.xkb = MagicMock()
layout.lib.XkbLookupKeySym.return_value = False
layout.labels()
assert layout.lib.XkbLookupKeySym.call_args_list
for call in layout.lib.XkbLookupKeySym.call_args_list:
assert call.args[2] == 1 << XKB_GROUP_SHIFT
def test_key_failure_releases_all_pressed_keys(application: QApplication) -> None:
worker = SystemInputWorker()
device = MagicMock()
device.write.side_effect = [None, OSError('injection failed'), None, None]
with pytest.raises(OSError, match='injection failed'):
worker.send_keys(device, (ecodes.KEY_LEFTSHIFT, ecodes.KEY_Q))
assert [call.args for call in device.write.call_args_list] == [
(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1), (ecodes.EV_KEY, ecodes.KEY_Q, 1),
(ecodes.EV_KEY, ecodes.KEY_Q, 0), (ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0)]
def test_hidden_keyboard_cannot_inject(application: QApplication) -> None:
worker = SystemInputWorker()
device = MagicMock()
worker._execute(device, 'tap', (ecodes.KEY_Q,))
worker._execute(device, 'language', ())
worker._execute(device, 'caps', ())
device.write.assert_not_called()
def test_worker_shutdown_closes_device_once(monkeypatch: pytest.MonkeyPatch, application: QApplication) -> None:
worker = SystemInputWorker()
device = MagicMock()
opened = Event()
def open_device(*args: Any, **kwargs: Any) -> Any:
opened.set()
return device
monkeypatch.setattr(system_input, 'UInput', open_device)
monkeypatch.setattr(worker, '_load_layout', MagicMock())
monkeypatch.setattr(worker, '_refresh_state', MagicMock())
worker.start()
assert opened.wait(2)
worker.stop()
worker.stop()
assert not worker.isRunning()
device.close.assert_called_once()
def test_worker_failure_reports_and_finishes(monkeypatch: pytest.MonkeyPatch, application: QApplication) -> None:
worker = SystemInputWorker()
monkeypatch.setattr(system_input, 'UInput', MagicMock(side_effect=PermissionError('uinput denied')))
failures = []
worker.failed.connect(failures.append)
worker.start()
assert worker.wait(2000)
application.processEvents()
assert failures == ['uinput denied']
@pytest.mark.parametrize('session', ['wayland', 'x11'])
def test_xwayland_switch_uses_uinput_instead_of_xkb(
monkeypatch: pytest.MonkeyPatch, application: QApplication, session: str,
) -> None:
monkeypatch.setenv('XDG_SESSION_TYPE', session)
worker = SystemInputWorker()
worker.enabled.set()
layout: Any = X11Layout.__new__(X11Layout)
layout.switch = MagicMock()
worker.layout = layout
device = MagicMock()
worker._execute(device, 'language', ())
if session == 'x11':
layout.switch.assert_called_once()
device.write.assert_not_called()
else:
layout.switch.assert_not_called()
assert [call.args for call in device.write.call_args_list] == [
(ecodes.EV_KEY, ecodes.KEY_KBD_LAYOUT_NEXT, 1),
(ecodes.EV_KEY, ecodes.KEY_KBD_LAYOUT_NEXT, 0)]
def test_cosmic_switch_matches_prototype_uinput_path(application: QApplication) -> None:
worker = SystemInputWorker()
worker.enabled.set()
worker.layout = CosmicLayout.__new__(CosmicLayout)
device = MagicMock()
worker._execute(device, 'language', ())
assert [call.args for call in device.write.call_args_list] == [
(ecodes.EV_KEY, ecodes.KEY_KBD_LAYOUT_NEXT, 1),
(ecodes.EV_KEY, ecodes.KEY_KBD_LAYOUT_NEXT, 0)]
def test_niri_switch_uses_ipc(monkeypatch: pytest.MonkeyPatch) -> None:
command = MagicMock()
monkeypatch.setattr(wayland_detection, 'command', command)
layout = wayland_detection.NiriLayout.__new__(wayland_detection.NiriLayout)
layout.switch()
command.assert_called_once_with(['niri', 'msg', 'action', 'switch-layout', 'next'])
def test_start_y_is_consumed_before_internal_search(application: QApplication) -> None:
manager: Any = InputManager.__new__(InputManager)
QObject.__init__(manager)
keyboard = SimpleNamespace(toggle=MagicMock(), isVisible=lambda: False)
manager._parent = SimpleNamespace(system_keyboard=keyboard)
manager.start_held = True
assert manager._handle_system_keyboard_input(PAD_BUTTON_START, 1, False)
assert manager._handle_system_keyboard_input(PAD_BUTTON_NORTH, 1, False)
assert manager._handle_system_keyboard_input(PAD_BUTTON_START, 0, False)
keyboard.toggle.assert_called_once()
manager.start_held = False
assert not manager._handle_system_keyboard_input(PAD_BUTTON_NORTH, 1, False)
def test_system_keyboard_routes_buttons_without_application_focus(application: QApplication) -> None:
manager: Any = InputManager.__new__(InputManager)
QObject.__init__(manager)
keyboard = SimpleNamespace(send=MagicMock(), isVisible=lambda: True)
manager._parent = SimpleNamespace(system_keyboard=keyboard)
manager.start_held = False
assert manager._handle_system_keyboard_input(PAD_BUTTON_SOUTH, 1, False)
keyboard.send.assert_called_once_with('button', 'confirm')
def test_start_is_polled_before_y_in_same_snapshot(application: QApplication) -> None:
manager: Any = InputManager.__new__(InputManager)
manager._handle_button_value = MagicMock()
gamepad = cast(SDLGamepad, SimpleNamespace(get_button=lambda index: 1))
manager._poll_button_events(gamepad, 1.0)
codes = [call.args[1] for call in manager._handle_button_value.call_args_list]
assert codes.index(PAD_BUTTON_START) < codes.index(PAD_BUTTON_NORTH)
assert set(codes) == set(SDL_CONTROLLER_BUTTON_TO_PAD.values())
def test_controller_shutdown_waits_for_child(monkeypatch: pytest.MonkeyPatch, application: QApplication) -> None:
parent = QWidget()
keyboard = SystemKeyboard(parent)
process = MagicMock()
from PySide6.QtCore import QProcess
process.state.return_value = QProcess.ProcessState.Running
process.waitForFinished.side_effect = [False, False, True]
keyboard.process = process
keyboard.shutdown()
process.terminate.assert_called_once()
process.kill.assert_called_once()
assert process.waitForFinished.call_count == 3
Generated
+2 -2
View File
@@ -444,7 +444,7 @@ source = { editable = "." }
dependencies = [
{ name = "babel" },
{ name = "dbus-fast" },
{ name = "evdev" },
{ name = "evdev", marker = "sys_platform == 'linux'" },
{ name = "libarchive-c" },
{ name = "orjson" },
{ name = "pefile" },
@@ -471,7 +471,7 @@ dev = [
requires-dist = [
{ name = "babel", specifier = ">=2.18.0" },
{ name = "dbus-fast", specifier = ">=5.2.0" },
{ name = "evdev", specifier = ">=2.0.0" },
{ name = "evdev", marker = "sys_platform == 'linux'", specifier = ">=2.0.0" },
{ name = "libarchive-c", specifier = ">=5.3" },
{ name = "orjson", specifier = ">=3.12.0" },
{ name = "pefile", specifier = ">=2024.8.26" },