feat: add system keyboard via tray and Start + #297

Merged
Boria138 merged 1 commits from system-keyboard into main 2026-11-18 19:56:37 +00:00
34 changed files with 3896 additions and 23 deletions

No files matched your search

+1 -1
View File
@@ -80,7 +80,7 @@ PortProtonQt uses code and dependencies from the following projects:
- [heroic-gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl) — GOG downloading module, [GPLv3](https://github.com/Heroic-Games-Launcher/heroic-gogdl/blob/main/LICENSE) license.
- [Legendary](https://github.com/Heroic-Games-Launcher/legendary) — Epic Games launcher alternative, [GPLv3](https://github.com/Heroic-Games-Launcher/legendary/blob/master/LICENSE) license.
- [pyte](https://github.com/selectel/pyte) — ANSI escape code parser, [LGPLv3](https://github.com/selectel/pyte?tab=LGPL-3.0-1-ov-file) license.
- [gjs-osk](https://github.com/Vishram1123/gjs-osk) — base for virtual keyboard layout data, GPLv3 license.
- [gjs-osk](https://github.com/Vishram1123/gjs-osk) — source of the original virtual keyboard layout data and reference for the system keyboard's compact layout and modifier key handling, [GPLv3](https://github.com/Vishram1123/gjs-osk/blob/main/LICENSE) license.
- [omikuji](https://github.com/omikuji-launcher/omikuji) — inspiration and source material for the procedural detail page backgrounds, [GPLv3](https://github.com/omikuji-launcher/omikuji/blob/master/LICENSE) license.
- [Bottles](https://github.com/bottlesdevs/Bottles) — source of the compatibility analysis rules, GPL-3.0-only license.
+1 -1
View File
@@ -80,7 +80,7 @@ PortProtonQt использует код и зависимости от след
- [heroic-gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl) — модуль загрузки игр GOG, лицензия [GPLv3](https://github.com/Heroic-Games-Launcher/heroic-gogdl/blob/main/LICENSE).
- [Legendary](https://github.com/Heroic-Games-Launcher/legendary) — альтернатива Epic Games Launcher, лицензия [GPLv3](https://github.com/Heroic-Games-Launcher/legendary/blob/master/LICENSE).
- [pyte](https://github.com/selectel/pyte) — разбор ANSI escape-кодов, лицензия [LGPLv3](https://github.com/selectel/pyte?tab=LGPL-3.0-1-ov-file)
- [gjs-osk](https://github.com/Vishram1123/gjs-osk) — основа данных раскладок виртуальной клавиатуры, лицензия GPLv3.
- [gjs-osk](https://github.com/Vishram1123/gjs-osk) — источник исходных данных раскладок виртуальной клавиатуры и образец compact-компоновки системной клавиатуры и обработки клавиш-модификаторов, лицензия [GPLv3](https://github.com/Vishram1123/gjs-osk/blob/main/LICENSE).
- [omikuji](https://github.com/omikuji-launcher/omikuji) — источник вдохновения и материалов для процедурных фонов детальной страницы, лицензия [GPLv3](https://github.com/omikuji-launcher/omikuji/blob/master/LICENSE).
- [Bottles](https://github.com/bottlesdevs/Bottles) — источник правил анализа совместимости, лицензия GPL-3.0-only.
+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')
'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' 'libx11' 'xkeyboard-config')
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')
'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' 'libx11' 'xkeyboard-config')
makedepends=('meson' 'ninja' 'vulkan-headers' 'gettext' 'sdl3')
conflicts=("portprotonqt-steam-compat")
provides=('portprotonqt-steam-compat')
+3
View File
@@ -23,6 +23,8 @@ BuildRequires: gettext
BuildRequires: systemd-rpm-macros
BuildRequires: vulkan-loader-devel
BuildRequires: pkgconfig(sdl3)
BuildRequires: pkgconfig(wayland-client)
BuildRequires: pkgconfig(x11)
BuildRequires: gcc
Obsoletes: python3-%{pypi_name}-git < %{version}-%{release}
@@ -66,6 +68,7 @@ Requires: psmisc
Requires: 7zip
Requires: python3-dbus-fast
Requires: desktop-file-utils
Requires: xkeyboard-config
# System Tab
Recommends: NetworkManager
+3
View File
@@ -20,6 +20,8 @@ BuildRequires: gettext
BuildRequires: systemd-rpm-macros
BuildRequires: vulkan-loader-devel
BuildRequires: pkgconfig(sdl3)
BuildRequires: pkgconfig(wayland-client)
BuildRequires: pkgconfig(x11)
BuildRequires: gcc
Obsoletes: python3-%{pypi_name} < %{version}-%{release}
@@ -63,6 +65,7 @@ Requires: psmisc
Requires: 7zip
Requires: python3-dbus-fast
Requires: desktop-file-utils
Requires: xkeyboard-config
# System Tab
Recommends: NetworkManager
Binary file not shown.
+224
View File
@@ -0,0 +1,224 @@
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/XKBlib.h>
#include <string.h>
#include <wayland-client.h>
struct wl_display *portproton_keyboard_wayland_connect(const char *name)
{
return wl_display_connect(name);
}
Display *portproton_keyboard_x11_open_display(const char *name)
{
Display *display = XOpenDisplay(name);
if (display)
XkbSelectEvents(display, XkbUseCoreKbd,
XkbMapNotifyMask | XkbNewKeyboardNotifyMask,
XkbMapNotifyMask | XkbNewKeyboardNotifyMask);
return display;
}
static int keyboard_group_name(Display *display, unsigned int group,
char *buffer, size_t size)
{
XkbDescPtr keyboard = XkbGetMap(display, 0, XkbUseCoreKbd);
int found = 0;
if (!keyboard)
return 0;
if (XkbGetNames(display, XkbGroupNamesMask, keyboard) == Success &&
keyboard->names && group < XkbNumKbdGroups && keyboard->names->groups[group]) {
char *name = XGetAtomName(display, keyboard->names->groups[group]);
if (name) {
size_t length = strlen(name);
found = length > 0 && length < size;
if (found)
memcpy(buffer, name, length + 1);
XFree(name);
}
}
XkbFreeKeyboard(keyboard, XkbAllComponentsMask, True);
return found;
}
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 (!buffer || size == 0)
return 0;
if (!property)
return keyboard_group_name(display, group, buffer, size);
if (XGetWindowProperty(display, DefaultRootWindow(display), property, 0,
property_length, False, XA_STRING, &type, &format,
&length, &remaining, &data) != Success || !data)
return keyboard_group_name(display, group, buffer, size);
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 || keyboard_group_name(display, group, buffer, size);
}
int portproton_keyboard_x11_state(Display *display, unsigned int *values)
{
XkbStateRec state;
int opcode, event_base, error_base;
int major = XkbMajorVersion, minor = XkbMinorVersion;
if (!XkbQueryExtension(display, &opcode, &event_base, &error_base, &major, &minor))
return 0;
/* Reading XKB events also invalidates Xlib's cached keyboard map. */
while (XPending(display)) {
XkbEvent event;
XNextEvent(display, &event.core);
if (event.type == MappingNotify)
XRefreshKeyboardMapping(&event.core.xmapping);
else if (event.type == event_base && event.any.xkb_type == XkbMapNotify)
XkbRefreshKeyboardMapping(&event.map);
}
if (XkbGetState(display, XkbUseCoreKbd, &state) != Success)
return 0;
values[0] = state.group;
values[1] = state.mods;
values[2] = state.locked_mods;
return 1;
}
unsigned int portproton_keyboard_x11_keysym(Display *display, unsigned int code,
unsigned int mask)
{
unsigned int consumed;
KeySym symbol;
if (!XkbLookupKeySym(display, code, mask, &consumed, &symbol))
return 0;
return (unsigned int)symbol;
}
static const struct wl_message keyboard_group_requests[] = {
{"set_group", "u", NULL}, {"destroy", "", NULL}
};
static const struct wl_message keyboard_group_events[] = {{"group", "u", NULL}};
static const struct wl_interface keyboard_group_interface = {
"zcosmic_keyboard_layout_v1", 1, 2, keyboard_group_requests, 1, keyboard_group_events
};
static const struct wl_interface *keyboard_manager_types[] = {
&keyboard_group_interface, &wl_keyboard_interface
};
static const struct wl_message keyboard_manager_requests[] = {
{"get_keyboard_layout", "no", keyboard_manager_types}, {"destroy", "", NULL}
};
static const struct wl_interface keyboard_manager_interface = {
"zcosmic_keyboard_layout_manager_v1", 1, 2, keyboard_manager_requests, 0, NULL
};
static const struct wl_message keyboard_layer_requests[] = {
{"set_size", "uu", NULL}, {"set_anchor", "u", NULL},
{"set_exclusive_zone", "i", NULL}, {"set_margin", "iiii", NULL},
{"set_keyboard_interactivity", "u", NULL}, {"get_popup", "o", NULL},
{"ack_configure", "u", NULL}, {"destroy", "", NULL}
};
static const struct wl_message keyboard_layer_events[] = {
{"configure", "uuu", NULL}, {"closed", "", NULL}
};
static const struct wl_interface keyboard_layer_interface = {
"zwlr_layer_surface_v1", 1, 8, keyboard_layer_requests, 2, keyboard_layer_events
};
static const struct wl_interface *keyboard_shell_types[] = {
&keyboard_layer_interface, &wl_surface_interface, &wl_output_interface, NULL, NULL
};
static const struct wl_message keyboard_shell_requests[] = {
{"get_layer_surface", "no?ous", keyboard_shell_types}
};
static const struct wl_interface keyboard_shell_interface = {
"zwlr_layer_shell_v1", 1, 1, keyboard_shell_requests, 0, NULL
};
const struct wl_interface *portproton_keyboard_wayland_interface(const char *name)
{
const struct wl_interface *interfaces[] = {
&wl_registry_interface, &wl_seat_interface, &wl_keyboard_interface,
&keyboard_group_interface, &keyboard_manager_interface,
&wl_callback_interface, &wl_compositor_interface, &wl_shm_interface,
&wl_surface_interface, &wl_output_interface, &wl_region_interface,
&wl_shm_pool_interface, &wl_buffer_interface, &wl_pointer_interface,
&wl_touch_interface, &keyboard_layer_interface, &keyboard_shell_interface
};
for (size_t index = 0; index < sizeof(interfaces) / sizeof(interfaces[0]); ++index) {
if (strcmp(name, interfaces[index]->name) == 0)
return interfaces[index];
}
return NULL;
}
enum keyboard_probe_global {
KEYBOARD_PROBE_COMPOSITOR,
KEYBOARD_PROBE_SHM,
KEYBOARD_PROBE_LAYER_SHELL,
KEYBOARD_PROBE_GLOBAL_COUNT
};
static void keyboard_probe_global(void *data, struct wl_registry *registry,
uint32_t name, const char *interface, uint32_t version)
{
uint32_t *globals = data;
const char *required[] = {"wl_compositor", "wl_shm", "zwlr_layer_shell_v1"};
(void)registry;
(void)version;
for (size_t index = 0; index < sizeof(required) / sizeof(required[0]); ++index) {
if (strcmp(interface, required[index]) == 0)
globals[index] = name;
}
}
static void keyboard_probe_removed(void *data, struct wl_registry *registry, uint32_t name)
{
uint32_t *globals = data;
(void)registry;
for (size_t index = 0; index < KEYBOARD_PROBE_GLOBAL_COUNT; ++index) {
if (globals[index] == name)
globals[index] = 0;
}
}
int portproton_keyboard_has_layer_shell(void)
{
struct wl_display *display = wl_display_connect(NULL);
if (!display)
return 0;
uint32_t globals[KEYBOARD_PROBE_GLOBAL_COUNT] = {0};
const struct wl_registry_listener listener = {
.global = keyboard_probe_global, .global_remove = keyboard_probe_removed
};
struct wl_registry *registry = wl_display_get_registry(display);
if (!registry) {
wl_display_disconnect(display);
return 0;
}
int ready = wl_registry_add_listener(registry, &listener, globals) == 0 &&
wl_display_roundtrip(display) >= 0;
wl_registry_destroy(registry);
wl_display_disconnect(display);
return ready && globals[KEYBOARD_PROBE_COMPOSITOR] &&
globals[KEYBOARD_PROBE_SHM] && globals[KEYBOARD_PROBE_LAYER_SHELL];
}
+3
View File
@@ -7,6 +7,8 @@ Build-Depends:
gettext,
libsdl3-dev,
libvulkan-dev,
libwayland-dev,
libx11-dev,
meson,
ninja-build,
pkgconf,
@@ -55,6 +57,7 @@ Depends:
qt6-svg-plugins,
unrar-free,
unzip,
xkb-data,
xz-utils,
zstd,
${misc:Depends},
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Regenerate bundled keyboard layers; libxkbcommon is a generation-only tool."""
import ctypes as C
import ctypes.util
from pathlib import Path
import re
import orjson
from portprotonqt.system_keyboard.input import KEY_ROWS
ROOT = Path(__file__).resolve().parents[1]
lib = C.CDLL(ctypes.util.find_library('xkbcommon'))
class Names(C.Structure):
_fields_ = [(name, C.c_char_p) for name in ('rules', 'model', 'layout', 'variant', 'options')]
for name, args, result in (
('xkb_context_new', [C.c_int], C.c_void_p),
('xkb_keymap_new_from_names', [C.c_void_p, C.POINTER(Names), C.c_int], C.c_void_p),
('xkb_state_new', [C.c_void_p], C.c_void_p),
('xkb_state_update_key', [C.c_void_p, C.c_uint, C.c_int], C.c_int),
('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),
('xkb_keysym_to_utf32', [C.c_uint], C.c_uint),
('xkb_keysym_to_upper', [C.c_uint], C.c_uint),
('xkb_keysym_from_name', [C.c_char_p, C.c_int], C.c_uint),
('xkb_state_unref', [C.c_void_p], None),
('xkb_keymap_unref', [C.c_void_p], None),
('xkb_context_unref', [C.c_void_p], None),
):
function = getattr(lib, name)
function.argtypes, function.restype = args, result
path = ROOT / 'portprotonqt/keyboard_layouts.json'
data = orjson.loads(path.read_bytes())
context = lib.xkb_context_new(0)
failures = []
for identifier, layout in data.items():
language, _, variant = identifier.partition('+')
names = Names(None, b'pc105', language.encode(), variant.encode(), b'')
keymap = lib.xkb_keymap_new_from_names(context, C.byref(names), 0)
if not keymap:
failures.append(identifier)
continue
for layer, modifiers in (
('altgr', (108,)), ('shift_altgr', (50, 108)),
('caps', (66,)), ('shift_caps', (50, 66)),
('altgr_caps', (108, 66)), ('shift_altgr_caps', (50, 108, 66)),
):
state = lib.xkb_state_new(keymap)
for code in modifiers:
lib.xkb_state_update_key(state, code, 1)
rows = []
for fallbacks, codes in zip(layout['normal'], KEY_ROWS, strict=True):
row = []
for fallback, code in zip(fallbacks, codes, strict=True):
buffer = C.create_string_buffer(128)
lib.xkb_state_key_get_utf8(state, code + 8, buffer, len(buffer))
label = buffer.value.decode()
if not label or not label.isprintable():
symbol = lib.xkb_state_key_get_one_sym(state, code + 8)
lib.xkb_keysym_get_name(symbol, buffer, len(buffer))
label = buffer.value.decode() or fallback
row.append(label.replace('&', '&&') if code not in (15, 58, 42) else fallback)
rows.append(row)
layout[layer] = rows
lib.xkb_state_unref(state)
lib.xkb_keymap_unref(keymap)
lib.xkb_context_unref(context)
if failures:
raise SystemExit(f'Cannot generate layouts: {failures}')
path.write_bytes(orjson.dumps(data) + b'\n')
symbols = {'names': {}, 'values': {}, 'keysyms': {}, 'upper': {}}
header = Path('/usr/include/xkbcommon/xkbcommon-keysyms.h').read_text()
for name in re.findall(r'^#define XKB_KEY_(\w+)\s', header, re.MULTILINE):
symbol = lib.xkb_keysym_from_name(name.encode(), 0)
value = lib.xkb_keysym_to_utf32(symbol)
buffer = C.create_string_buffer(128)
lib.xkb_keysym_get_name(symbol, buffer, len(buffer))
symbols['keysyms'][str(symbol)] = buffer.value.decode()
if value and chr(value).isprintable():
symbols['keysyms'][str(symbol)] = chr(value)
symbols['names'][name] = chr(value)
symbols['values'][str(symbol)] = chr(value)
upper = lib.xkb_keysym_to_utf32(lib.xkb_keysym_to_upper(symbol))
if upper and chr(upper).isprintable():
symbols['upper'][chr(value)] = chr(upper)
(ROOT / 'portprotonqt/keyboard_symbols.json').write_bytes(orjson.dumps(symbols) + b'\n')
+2
View File
@@ -40,6 +40,8 @@ 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('x11')]
keyboard_sources = files('build-aux/src/keyboard_backend.c')
# Install Python package
subdir('portprotonqt')
+11
View File
@@ -311,6 +311,17 @@ 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)
+56 -8
View File
@@ -57,8 +57,6 @@ 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':
@@ -80,8 +78,6 @@ class GamepadRuntimeMixin(InputMixin):
def check_gamepad(self) -> None:
try:
if self._gamepad_polling_suspended:
return
new_gamepad = self.find_gamepad()
if new_gamepad:
@@ -128,6 +124,7 @@ 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
@@ -173,6 +170,9 @@ 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 if self.gamepad is not None else None)
def find_gamepad(self) -> SDLGamepad | None:
"""Open the SDL3 handle that combines all connected gamepads."""
@@ -206,6 +206,9 @@ 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:
@@ -217,10 +220,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 Guide before Select when both change in the same SDL snapshot.
# Deliver modifier buttons before their combinations in the same snapshot.
buttons = sorted(
SDL_CONTROLLER_BUTTON_TO_PAD.items(),
key=lambda item: item[1] not in BUTTONS['guide'],
key=lambda item: (item[1] not in BUTTONS['guide'], item[1] != PAD_BUTTON_START),
)
for button_index, button_code in buttons:
value = gamepad.get_button(button_index)
@@ -242,6 +245,8 @@ 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()
@@ -265,6 +270,41 @@ 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
@@ -347,14 +387,22 @@ 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 or self._gamepad_polling_suspended:
if not self.running:
return
current_time = time.time()
active_gamepad = self.gamepad
@@ -382,7 +430,7 @@ class GamepadRuntimeMixin(InputMixin):
self._poll_axis_events(active_gamepad, current_time)
if (
current_time - self.last_update >= self.update_interval and
self.mouse_emulation_enabled and self.emulation_active and self.emulation_triggered
self._is_mouse_emulation_active()
):
self.update_mouse_position()
self.last_update = current_time
+1 -1
View File
@@ -1 +1 @@
{"af+fa-olpc":{"normal":[["‍","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ"],["⬆","<","ظ","ط","ز","ر","ذ","د","پ","و",".","/"]],"shift":[["÷","!","٬","٫","؋","٪","×","،","*",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","]","[","}","{","|"],["CAPS","ؤ","ئ","ي","إ","أ","آ","ة","»","«",":","؛"],["⬆",">","ك","ٓ","ژ","ٰ","‌","ٔ","ء",">","<","؟"]]},"af+ps-olpc":{"normal":[["‍","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","ګ"],["⬆","<","ظ","ې","ز","ر","ذ","د","ړ","و","ږ","/"]],"shift":[["ٔ","!","٬","٫","؋","٪","×","»","«",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","ځ","څ","]","[","*"],["CAPS","ښ","ۍ","ي","پ","أ","آ","ټ","ڼ","ة",":","؛"],["⬆",">","ئ","ط","ژ","ء","‌","ډ","ؤ",".",".","؟"]]},"af+ps":{"normal":[["‍","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","ګ"],["⬆","<","ۍ","ې","ز","ر","ذ","د","ړ","و","ږ","/"]],"shift":[["÷","!","٬","٫","","٪","×","»","«",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","ځ","څ","]","[","*"],["CAPS","ښ","ئ","ي","پ","أ","آ","ټ","ڼ","ة",":","؛"],["⬆",">","ظ","ط","ژ","ء","‌","ډ","ؤ","،",".","؟"]]},"af+uz-olpc":{"normal":[["‍","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ"],["⬆","<","ظ","ط","ز","ر","ذ","د","پ","و",".","/"]],"shift":[["÷","!","٬","٫","؋","٪","×","،","*",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","]","[","}","{","|"],["CAPS","ؤ","ئ","ي","ې","أ","آ","ة","»","«",":","؛"],["⬆",">","ۉ","ۇ","ژ","إ","‌","ٔ","ء",">","<","؟"]]},"af+uz":{"normal":[["‍","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ"],["⬆","<","ظ","ط","ز","ر","ذ","د","پ","و",".","/"]],"shift":[["÷","!","٬","٫","","٪","×","،","*",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","]","[","}","{","|"],["CAPS","ؤ","ئ","ي","ې","أ","آ","ة","»","«",":","؛"],["⬆",">","ۉ","ۇ","ژ","إ","‌","ٔ","ء",">","<","؟"]]},"af":{"normal":[["‍","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ"],["⬆","<","ظ","ط","ز","ر","ذ","د","پ","و",".","/"]],"shift":[["÷","!","٬","٫","","٪","×","،","*",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","]","[","}","{","|"],["CAPS","ؤ","ئ","ي","إ","أ","آ","ة","»","«",":","؛"],["⬆",">","ك","ٓ","ژ","ٰ","‌","ٔ","ء",">","<","؟"]]},"al+plisi":{"normal":[["`","1","2","3","4","5","6","7","8","9","0","-","="],["TAB","q","w","e","r","t","y","u","i","o","p","ç",">","\\"],["CAPS","a","s","d","f","g","h","j","k","l","ë","'"],["⬆","<","z","x","c","v","b","n","m",",",".","/"]],"shift":[["~","!","@","#","$","%","^","&&","*","(",")","_","+"],["TAB","Q","W","E","R","T","Y","U","I","O","P","Ç","<","|"],["CAPS","A","S","D","F","G","H","J","K","L","Ë","\""],["⬆",">","Z","X","C","V","B","N","M",";",":","?"]]},"al+veqilharxhi":{"normal":[["`","1","2","3","4","5","6","7","8","9","0","-","="],["TAB","𐖰","𐖟","𐖞","𐖱","𐖵","𐖻","𐖷","𐖥","𐖮","𐖯","[","]","\\"],["CAPS","𐖗","𐖳","𐖜","𐖠","𐖡","𐖣","𐖧","𐖨","𐖩",";","'"],["⬆","<","𐖼","𐖹","𐖚","𐖸","𐖘","𐖬","𐖫",",",".","/"]],"shift":[["~","!","@","#","$","%","^","&&","*","(",")","_","+"],["TAB","𐖉","𐕸","𐕷","𐖊","𐖎","𐖔","𐖐","𐕾","𐖇","𐖈","{","}","|"],["CAPS","𐕰","𐖌","𐕵","𐕹","𐕺","𐕼","𐖀","𐖁","𐖂",":","\""],["⬆",">","𐖕","𐖒","𐕳","𐖑","𐕱","𐖅","𐖄","<",">","?"]]},"al":{"normal":[["\\","1","2","3","4","5","6","7","8","9","0","-","="],["TAB","q","w","e","r","t","z","u","i","o","p","ç","@","]"],["CAPS","a","s","d","f","g","h","j","k","l","ë","["],["⬆","<","y","x","c","v","b","n","m",",",".","/"]],"shift":[["|","!","\"","#","$","%","^","&&","*","(",")","_","+"],["TAB","Q","W","E","R","T","Z","U","I","O","P","Ç","'","}"],["CAPS","A","S","D","F","G","H","J","K","L","Ë","{"],["⬆",">","Y","X","C","V","B","N","M",";",":","?"]]},"am+eastern-alt":{"normal":[["՝","։","ձ","յ","՛",",","-",".","«","»","օ","ռ","ժ"],["TABLine truncated
{"af+fa-olpc":{"normal":[["‍","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ"],["⬆","<","ظ","ط","ز","ر","ذ","د","پ","و",".","/"]],"shift":[["÷","!","٬","٫","؋","٪","×","،","*",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","]","[","}","{","|"],["CAPS","ؤ","ئ","ي","إ","أ","آ","ة","»","«",":","؛"],["⬆",">","ك","ٓ","ژ","ٰ","‌","ٔ","ء",">","<","؟"]],"altgr":[["U200D","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ"],["⬆","<","ظ","ط","ز","ر","ذ","د","پ","و",".","/"]],"shift_altgr":[["÷","!","٬","٫","؋","٪","×","،","*",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","]","[","}","{","|"],["CAPS","ؤ","ئ","ي","إ","أ","آ","ة","»","«",":","؛"],["⬆",">","ك","ٓ","ژ","ٰ","U200C","ٔ","ء",">","<","؟"]],"caps":[["U200D","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ"],["⬆","<","ظ","ط","ز","ر","ذ","د","پ","و",".","/"]],"shift_caps":[["÷","!","٬","٫","؋","٪","×","،","*",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","]","[","}","{","|"],["CAPS","ؤ","ئ","ي","إ","أ","آ","ة","»","«",":","؛"],["⬆",">","ك","ٓ","ژ","ٰ","U200C","ٔ","ء",">","<","؟"]],"altgr_caps":[["U200D","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ"],["⬆","<","ظ","ط","ز","ر","ذ","د","پ","و",".","/"]],"shift_altgr_caps":[["÷","!","٬","٫","؋","٪","×","،","*",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","]","[","}","{","|"],["CAPS","ؤ","ئ","ي","إ","أ","آ","ة","»","«",":","؛"],["⬆",">","ك","ٓ","ژ","ٰ","U200C","ٔ","ء",">","<","؟"]]},"af+ps-olpc":{"normal":[["‍","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","ګ"],["⬆","<","ظ","ې","ز","ر","ذ","د","ړ","و","ږ","/"]],"shift":[["ٔ","!","٬","٫","؋","٪","×","»","«",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","ځ","څ","]","[","*"],["CAPS","ښ","ۍ","ي","پ","أ","آ","ټ","ڼ","ة",":","؛"],["⬆",">","ئ","ط","ژ","ء","‌","ډ","ؤ",".",".","؟"]],"altgr":[["U200D","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","ګ"],["⬆","<","ظ","ې","ز","ر","ذ","د","ړ","و","ږ","/"]],"shift_altgr":[["ٔ","!","٬","٫","؋","٪","×","»","«",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","ځ","څ","]","[","*"],["CAPS","ښ","ۍ","ي","پ","أ","آ","ټ","ڼ","ة",":","؛"],["⬆",">","ئ","ط","ژ","ء","U200C","ډ","ؤ",".",".","؟"]],"caps":[["U200D","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","ګ"],["⬆","<","ظ","ې","ز","ر","ذ","د","ړ","و","ږ","/"]],"shift_caps":[["ٔ","!","٬","٫","؋","٪","×","»","«",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","ځ","څ","]","[","*"],["CAPS","ښ","ۍ","ي","پ","أ","آ","ټ","ڼ","ة",":","؛"],["⬆",">","ئ","ط","ژ","ء","U200C","ډ","ؤ",".",".","؟"]],"altgr_caps":[["U200D","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","ګ"],["⬆","<","ظ","ې","ز","ر","ذ","د","ړ","و","ږ","/"]],"shift_altgr_caps":[["ٔ","!","٬","٫","؋","٪","×","»","«",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","ځ","څ","]","[","*"],["CAPS","ښ","ۍ","ي","پ","أ","آ","ټ","ڼ","ة",":","؛"],["⬆",">","ئ","ط","ژ","ء","U200C","ډ","ؤ",".",".","؟"]]},"af+ps":{"normal":[["‍","۱","۲","۳","۴","۵","۶","۷","۸","۹","۰","-","="],["TAB","ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","\\"],["CAPS","ش","س","ی","ب","ل","ا","ت","ن","م","ک","ګ"],["⬆","<","ۍ","ې","ز","ر","ذ","د","ړ","و","ږ","/"]],"shift":[["÷","!","٬","٫","","٪","×","»","«",")","(","ـ","+"],["TAB","ْ","ٌ","ٍ","ً","ُ","ِ","َ","ّ","ځ","څ","]","[","*"],["CAPS","ښ","ئ","ي","پ","أ","آ","ټ","ڼ","ة",":","؛"],["⬆",">","ظ","ط","ژ","ء","‌","ډ","ؤ","،",".","؟"]],"altgr":[["dead_tilde","`Line truncated
+1
View File
@@ -0,0 +1 @@
{"names":{"KP_Space":" ","KP_Equal":"=","KP_Multiply":"*","KP_Add":"+","KP_Separator":",","KP_Subtract":"-","KP_Decimal":".","KP_Divide":"/","KP_0":"0","KP_1":"1","KP_2":"2","KP_3":"3","KP_4":"4","KP_5":"5","KP_6":"6","KP_7":"7","KP_8":"8","KP_9":"9","space":" ","exclam":"!","quotedbl":"\"","numbersign":"#","dollar":"$","percent":"%","ampersand":"&","apostrophe":"'","quoteright":"'","parenleft":"(","parenright":")","asterisk":"*","plus":"+","comma":",","minus":"-","period":".","slash":"/","0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","colon":":","semicolon":";","less":"<","equal":"=","greater":">","question":"?","at":"@","A":"A","B":"B","C":"C","D":"D","E":"E","F":"F","G":"G","H":"H","I":"I","J":"J","K":"K","L":"L","M":"M","N":"N","O":"O","P":"P","Q":"Q","R":"R","S":"S","T":"T","U":"U","V":"V","W":"W","X":"X","Y":"Y","Z":"Z","bracketleft":"[","backslash":"\\","bracketright":"]","asciicircum":"^","underscore":"_","grave":"`","quoteleft":"`","a":"a","b":"b","c":"c","d":"d","e":"e","f":"f","g":"g","h":"h","i":"i","j":"j","k":"k","l":"l","m":"m","n":"n","o":"o","p":"p","q":"q","r":"r","s":"s","t":"t","u":"u","v":"v","w":"w","x":"x","y":"y","z":"z","braceleft":"{","bar":"|","braceright":"}","asciitilde":"~","exclamdown":"¡","cent":"¢","sterling":"£","currency":"¤","yen":"¥","brokenbar":"¦","section":"§","diaeresis":"¨","copyright":"©","ordfeminine":"ª","guillemotleft":"«","guillemetleft":"«","notsign":"¬","registered":"®","macron":"¯","degree":"°","plusminus":"±","twosuperior":"²","threesuperior":"³","acute":"´","mu":"µ","paragraph":"¶","periodcentered":"·","cedilla":"¸","onesuperior":"¹","masculine":"º","ordmasculine":"º","guillemotright":"»","guillemetright":"»","onequarter":"¼","onehalf":"½","threequarters":"¾","questiondown":"¿","Agrave":"À","Aacute":"Á","Acircumflex":"Â","Atilde":"Ã","Adiaeresis":"Ä","Aring":"Å","AE":"Æ","Ccedilla":"Ç","Egrave":"È","Eacute":"É","Ecircumflex":"Ê","Ediaeresis":"Ë","Igrave":"Ì","Iacute":"Í","Icircumflex":"Î","Idiaeresis":"Ï","ETH":"Ð","Eth":"Ð","Ntilde":"Ñ","Ograve":"Ò","Oacute":"Ó","Ocircumflex":"Ô","Otilde":"Õ","Odiaeresis":"Ö","multiply":"×","Oslash":"Ø","Ooblique":"Ø","Ugrave":"Ù","Uacute":"Ú","Ucircumflex":"Û","Udiaeresis":"Ü","Yacute":"Ý","THORN":"Þ","Thorn":"Þ","ssharp":"ß","agrave":"à","aacute":"á","acircumflex":"â","atilde":"ã","adiaeresis":"ä","aring":"å","ae":"æ","ccedilla":"ç","egrave":"è","eacute":"é","ecircumflex":"ê","ediaeresis":"ë","igrave":"ì","iacute":"í","icircumflex":"î","idiaeresis":"ï","eth":"ð","ntilde":"ñ","ograve":"ò","oacute":"ó","ocircumflex":"ô","otilde":"õ","odiaeresis":"ö","division":"÷","oslash":"ø","ooblique":"ø","ugrave":"ù","uacute":"ú","ucircumflex":"û","udiaeresis":"ü","yacute":"ý","thorn":"þ","ydiaeresis":"ÿ","Aogonek":"Ą","breve":"˘","Lstroke":"Ł","Lcaron":"Ľ","Sacute":"Ś","Scaron":"Š","Scedilla":"Ş","Tcaron":"Ť","Zacute":"Ź","Zcaron":"Ž","Zabovedot":"Ż","aogonek":"ą","ogonek":"˛","lstroke":"ł","lcaron":"ľ","sacute":"ś","caron":"ˇ","scaron":"š","scedilla":"ş","tcaron":"ť","zacute":"ź","doubleacute":"˝","zcaron":"ž","zabovedot":"ż","Racute":"Ŕ","Abreve":"Ă","Lacute":"Ĺ","Cacute":"Ć","Ccaron":"Č","Eogonek":"Ę","Ecaron":"Ě","Dcaron":"Ď","Dstroke":"Đ","Nacute":"Ń","Ncaron":"Ň","Odoubleacute":"Ő","Rcaron":"Ř","Uring":"Ů","Udoubleacute":"Ű","Tcedilla":"Ţ","racute":"ŕ","abreve":"ă","lacute":"ĺ","cacute":"ć","ccaron":"č","eogonek":"ę","ecaron":"ě","dcaron":"ď","dstroke":"đ","nacute":"ń","ncaron":"ň","odoubleacute":"ő","rcaron":"ř","uring":"ů","udoubleacute":"ű","tcedilla":"ţ","abovedot":"˙","Hstroke":"Ħ","Hcircumflex":"Ĥ","Iabovedot":"İ","Gbreve":"Ğ","Jcircumflex":"Ĵ","hstroke":"ħ","hcircumflex":"ĥ","idotless":"ı","gbreve":"ğ","jcircumflex":"ĵ","Cabovedot":"Ċ","Ccircumflex":"Ĉ","Gabovedot":"Ġ","Gcircumflex":"Ĝ","Ubreve":"Ŭ","Scircumflex":"Ŝ","cabovedot":"ċ","ccircumflex":"ĉ","gabovedot":"ġ","gcircumflex":"ĝ","ubreve":"ŭ","scircumflex":"ŝ","kra":"ĸ","kappa":"ĸ","Rcedilla":"Ŗ","Itilde":"Ĩ","Lcedilla":"Ļ","Emacron":"Ē","Gcedilla":"Ģ","Tslash":"Ŧ","rcedilla":"ŗ","itilde":"ĩ","lcedilla":"ļ","emacron":"ē","gcedilla":"ģ","tslash":"ŧ","ENG":"Ŋ","eng":"ŋ","Amacron":"Ā","Iogonek":"Į","Eabovedot":"Ė","Imacron":"Ī","Ncedilla":"Ņ","Omacron":"Ō","Kcedilla":"Ķ","Uogonek":"Ų","Utilde":"Ũ","Umacron":"Ū","amacron":"ā","iogonek":"į","eabovedot":"ė","imacron":"ī","ncedilla":"ņ","omacron":"ō","kcedilla":"ķ","uogonek":"ų","utilde":"ũ","umacron":"ū","Wcircumflex":"Ŵ","wcircumflex":"ŵ","Ycircumflex":"Ŷ","ycircumflex":"ŷ","Babovedot":"Ḃ","babovedot":"ḃ","Dabovedot":"Ḋ","dabovedot":"ḋ","Fabovedot":"Ḟ","fabovedot":"ḟ","Mabovedot":"Ṁ","mabovedot":"ṁ","Pabovedot":"Ṗ","pabovedot":"ṗ","Sabovedot":"Ṡ","sabovedot":"ṡ","Tabovedot":"Ṫ","tabovedot":"ṫ","Wgrave":"Ẁ","wgrave":"ẁ","Wacute":"Ẃ","wacuteLine truncated
+5
View File
@@ -579,6 +579,8 @@ 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 = {}
@@ -3529,6 +3531,9 @@ 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:
+22
View File
@@ -77,14 +77,36 @@ 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',
'keyboard_symbols.json',
],
install_dir: pythondir / meson.project_name(),
)
# 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/native.py',
'system_keyboard/window.py',
],
install_dir: pythondir / meson.project_name() / 'system_keyboard',
)
install_data(
['animations/__init__.py',
'animations/detail_background.py',
+103
View File
@@ -0,0 +1,103 @@
"""Launch and control the system keyboard independently of application focus."""
import sys
import orjson
from PySide6.QtCore import QObject, QProcess
from PySide6.QtWidgets import QApplication, QWidget
from portprotonqt.config import ui_config
from portprotonqt.logger import get_logger
logger = get_logger(__name__)
SHUTDOWN_TIMEOUT_MS = 3000
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.setProcessChannelMode(QProcess.ProcessChannelMode.ForwardedErrorChannel)
self.process.errorOccurred.connect(self._process_error)
self.process.finished.connect(self._finished)
self.visible = False
self.shift_pressed = False
self.output = bytearray()
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.output.clear()
self.process.start(sys.executable, ['-m', 'portprotonqt.system_keyboard'])
def _started(self) -> None:
self.send('theme', ui_config.get_theme())
manager = getattr(self.owner, 'input_manager', None)
connected = getattr(manager, 'gamepad', None) is not None
self.send('gamepad', manager.gamepad_type.value if manager is not None and connected else None)
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 _process_error(self, error: QProcess.ProcessError) -> None:
if error == QProcess.ProcessError.FailedToStart:
self.visible = False
logger.error('Cannot open system keyboard: %s', self.process.errorString())
def _finished(self, code: int, status: QProcess.ExitStatus) -> None:
self.visible = False
self.shift_pressed = False
if not self.closing and (code or status == QProcess.ExitStatus.CrashExit):
logger.error('System keyboard exited with code %s (%s)', code, status.name)
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)
+78
View File
@@ -0,0 +1,78 @@
"""Isolated Qt frontend: X11/XWayland or a native Wayland layer surface."""
import ctypes
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 portprotonqt.system_keyboard.native import load_library
layer_shell = False
if os.environ.get('WAYLAND_DISPLAY'):
library = load_library()
library.portproton_keyboard_has_layer_shell.argtypes = []
library.portproton_keyboard_has_layer_shell.restype = ctypes.c_int
layer_shell = bool(library.portproton_keyboard_has_layer_shell())
os.environ['QT_QPA_PLATFORM'] = 'offscreen' if layer_shell else 'xcb'
app = QApplication([sys.argv[0]])
app.setQuitOnLastWindowClosed(False)
from portprotonqt.system_keyboard.window import SystemKeyboardWindow, WaylandWindow
window = SystemKeyboardWindow(layer_shell=layer_shell)
try:
if layer_shell:
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())
+641
View File
@@ -0,0 +1,641 @@
"""Detect active keyboard layouts through X11, compositor IPC or desktop settings."""
import ast
import asyncio
import ctypes as C
import os
import re
import select
import subprocess
import xml.etree.ElementTree as ET
from collections.abc import Mapping
from configparser import ConfigParser
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import orjson
from evdev import ecodes
from dbus_fast import BusType, Message
from dbus_fast.aio import MessageBus
from portprotonqt.logger import get_logger
from portprotonqt.scripts_utils.dbus_tools import _bus_call, dbus_call
from portprotonqt.system_keyboard.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 portprotonqt.system_keyboard.layouts import Layout, keysym_label
from portprotonqt.system_keyboard.native import load_library
logger = get_logger(__name__)
LAYOUT_NAME_BUFFER_BYTES = 256
IBUS_SCHEMA = 'org.freedesktop.ibus.general'
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 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),
'portproton_keyboard_x11_state': ([C.c_void_p, C.POINTER(C.c_uint)], 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),
'portproton_keyboard_x11_keysym': ([C.c_void_p, C.c_uint, C.c_uint], C.c_uint),
'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.display = self.lib.portproton_keyboard_x11_open_display(None)
if not self.display:
raise RuntimeError('Cannot read the X11 keyboard layout')
def state(self) -> SimpleNamespace:
values = (C.c_uint * 3)()
if not self.lib.portproton_keyboard_x11_state(self.display, values):
raise RuntimeError('Cannot read XKB state')
return SimpleNamespace(group=values[0], mods=values[1], locked_mods=values[2])
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_RIGHTSHIFT, 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
value = self.lib.portproton_keyboard_x11_keysym(
self.display, code + XKB_KEYCODE_OFFSET, mask)
character = keysym_label(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
class IBusLayout(X11Layout):
def switch(self) -> None:
text = command(['gsettings', 'get', IBUS_SCHEMA, 'preload-engines']).strip()
engines = ast.literal_eval(re.sub(r'^@as\s+', '', text))
if (not isinstance(engines, list) or not engines
or any(not isinstance(engine, str) or not engine.startswith('xkb:') for engine in engines)):
raise ValueError('IBus input sources must be XKB keyboard layouts')
current = command(['ibus', 'engine']).strip()
if current not in engines:
raise RuntimeError('Current IBus engine is not in the configured input sources')
following = engines[(engines.index(current) + 1) % len(engines)]
command(['ibus', 'engine', following])
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.group_interface = self._interface('zcosmic_keyboard_layout_v1')
self.manager_interface = self._interface('zcosmic_keyboard_layout_manager_v1')
try:
self.display = self.lib.portproton_keyboard_wayland_connect(None)
if not self.display:
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),
('portproton_keyboard_wayland_interface', [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, p,
C.c_uint32, C.c_uint32], p),
):
fn = getattr(self.lib, name)
fn.argtypes, fn.restype = args, result
def _interface(self, name: str) -> int:
interface = self.lib.portproton_keyboard_wayland_interface(name.encode())
if not interface:
raise RuntimeError(f'Unknown Wayland interface: {name}')
return 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, interface,
1, 0, *args)
if not result:
raise RuntimeError('COSMIC: failed to create Wayland object')
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: failed to subscribe to Wayland events')
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 == b'zcosmic_keyboard_layout_manager_v1' and self.manager is None:
self.manager = self._new(self.registry, (0, self.manager_interface),
C.c_uint32(name), interface, C.c_uint32(1), C.c_void_p())
self._track()
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: keyboard disconnected')
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: invalid Wayland keymap')
text = os.pread(fd, size, 0)
if len(text) != size:
raise RuntimeError('COSMIC: incomplete Wayland keymap')
replacement = Layout(keymap_text=text)
finally:
os.close(fd)
self.layout = replacement
def _check(self, result: Any) -> None:
if result < 0:
raise RuntimeError('COSMIC: Wayland connection closed')
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: keyboard layout unavailable')
return self.layout.labels(modifiers, mask=(0, 0, 0, self.group))
def close(self) -> None:
if self.layout is not None:
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
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
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 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)
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)
@staticmethod
def switch_codes() -> tuple[int, ...]:
desktop = os.environ.get('XDG_CURRENT_DESKTOP', '').lower().split(':')
cinnamon = any('cinnamon' in name for name in desktop)
schema = 'org.cinnamon.desktop.keybindings.wm' if cinnamon else BINDINGS_SCHEMA
# GNOME's forward shortcut toggles the two most recent sources; reverse MRU cycles all.
key = 'switch-input-source' if cinnamon else 'switch-input-source-backward'
text = command(['gsettings', 'get', schema, key]).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 = None
def compositor(environment: Any) -> Any:
desktop = environment.get('XDG_CURRENT_DESKTOP', '').lower().split(':')
for name, variable in [('hyprland', 'HYPRLAND_INSTANCE_SIGNATURE'),
('sway', 'SWAYSOCK'), ('niri', 'NIRI_SOCKET'),
('umbriel', 'UMBRIEL_SOCKET'), ('mango', 'MANGO_INSTANCE_SIGNATURE')]:
if environment.get(variable):
return name
name = next((name for name in ('hyprland', 'sway', 'niri', 'cosmic', 'umbriel', 'mango')
if name in desktop), None)
if name is not None:
return name
return 'wayland' if environment.get('WAYLAND_DISPLAY') else 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 error ({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:
data = orjson.loads(command(['niri', 'msg', '--json', 'keyboard-layouts']))
index = data['current_idx']
if type(index) is not int or not 0 <= index < len(data['names']):
raise ValueError('Invalid niri keyboard layout index')
return data['names'][index]
def _update(self) -> None:
name = self._query_name()
if name not in self.names:
raise ValueError(f'Layout not found in XKB registry: {name}')
choice = self.names[name]
if choice != self.current:
replacement = Layout(*choice)
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 = 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 did not report a keyboard layout')
# 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 keyboards have conflicting layouts')
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 failed to switch keyboard layout: {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 did not report the main keyboard layout')
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 failed to switch keyboard layout: {result.strip()}')
class KDELayout(GSettingsLayout):
def __init__(self) -> None:
self.layout = None
self.current = None
self.names: list[tuple[str, str, str]] = []
self.sources: list[tuple[str, str]] = []
self.runner = asyncio.Runner()
self.bus: MessageBus | None = None
try:
self._update()
except Exception:
self.close()
raise
async def _request(self, method: str) -> list[Any] | None:
bus = self.bus
if bus is None:
bus = MessageBus(bus_type=BusType.SESSION)
await dbus_call(bus.connect())
self.bus = bus
return await _bus_call(bus, Message(
destination='org.kde.keyboard', path='/Layouts',
interface='org.kde.KeyboardLayouts', member=method))
def _call(self, method: str) -> list[Any]:
try:
result = self.runner.run(self._request(method))
except Exception as error:
raise RuntimeError(f'KDE keyboard layout request failed: {error}') from error
if result is None:
raise RuntimeError(f'KDE keyboard layout request failed: {method}')
return result
def _source(self) -> tuple[str, str]:
result = self._call('getLayoutsList')
if len(result) != 1:
raise ValueError('Invalid KDE keyboard layouts response')
rows = result[0]
if not isinstance(rows, list) or any(
not isinstance(row, (list, tuple)) or len(row) != 3 for row in rows
):
raise ValueError('Invalid KDE keyboard layout entries')
entries = [(row[0], row[1], row[2]) for row in rows]
names = [entry[0] for entry in entries]
if not names or any(not isinstance(name, str) or not name for name in names):
raise ValueError('Invalid KDE keyboard layout names')
if entries != self.names:
config = ConfigParser(interpolation=None)
directory = Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config')
config.read(directory / 'kxkbrc', encoding='utf-8')
variants = config.get('Layout', 'VariantList', fallback='').split(',')
if not any(variants):
variants = [''] * len(names)
if len(variants) != len(names):
raise ValueError('KDE keyboard layout variants do not match the layout list')
self.sources = list(zip(names, variants, strict=True))
self.names = entries
current = self._call('getLayout')
if len(current) != 1 or type(current[0]) is not int or not 0 <= current[0] < len(self.sources):
raise ValueError('Invalid KDE keyboard layout index')
return self.sources[current[0]]
def switch(self) -> None:
self._call('switchToNextLayout')
def close(self) -> None:
try:
super().close()
if self.bus is not None:
self.bus.disconnect()
self.runner.run(dbus_call(self.bus.wait_for_disconnect()))
self.bus = None
finally:
self.runner.close()
class CinnamonLayout(KDELayout):
async def _request(self, method: str) -> list[Any] | None:
bus = self.bus
if bus is None:
bus = MessageBus(bus_type=BusType.SESSION)
await dbus_call(bus.connect())
self.bus = bus
return await _bus_call(bus, Message(
destination='org.Cinnamon', path='/org/Cinnamon',
interface='org.Cinnamon', member=method))
def _source(self) -> tuple[str, str]:
result = self._call('GetInputSources')
if len(result) != 1 or not isinstance(result[0], list):
raise ValueError('Invalid Cinnamon input sources response')
selected = []
for source in result[0]:
if not isinstance(source, (list, tuple)) or len(source) != 12:
raise ValueError('Invalid Cinnamon input source entry')
if source[-1] is True:
selected.append(source)
if len(selected) != 1:
raise ValueError('Cinnamon current input source is unavailable')
source = selected[0]
layout, variant = source[7], source[8]
if source[0] != 'xkb' or not isinstance(layout, str) or not layout:
raise ValueError('Cinnamon input source is not an XKB layout')
if not isinstance(variant, str):
raise ValueError('Invalid Cinnamon XKB variant')
return layout, variant
class UmbrielLayout(NiriLayout):
def _query_name(self) -> str:
data = orjson.loads(command(['umbriel', 'keyboard-layouts', '--json']))
if not isinstance(data, dict):
raise ValueError('Invalid Umbriel keyboard layout response')
names, index = data.get('names'), data.get('current_index')
if not isinstance(names, list) or type(index) is not int or not 0 <= index < len(names):
raise ValueError('Invalid Umbriel keyboard layout index')
name = names[index]
if not isinstance(name, str) or not name:
raise ValueError('Invalid Umbriel keyboard layout name')
return name
def switch(self) -> None:
command(['umbriel', 'msg', 'keyboard-layout-next'])
class MangoLayout(NiriLayout):
def _query_name(self) -> str:
data = orjson.loads(command(['mmsg', 'get', 'keyboardlayout']))
name = data.get('layout') if isinstance(data, dict) else None
if not isinstance(name, str) or not name:
raise ValueError('Invalid Mango keyboard layout response')
return name
def switch(self) -> None:
# Zero cycles layouts; positive values select a one-based layout index.
result = orjson.loads(command(['mmsg', 'dispatch', 'switch_keyboard_layout,0']))
if not isinstance(result, dict) or result.get('success') is not True:
raise RuntimeError(f'Mango failed to switch keyboard layout: {result}')
def detect_layout() -> object:
desktop = os.environ.get('XDG_CURRENT_DESKTOP', '').lower().split(':')
if any('cinnamon' in name for name in desktop):
return CinnamonLayout()
if 'gnome' in desktop:
return X11Layout() if is_x11_session(os.environ) else GSettingsLayout()
if 'kde' in desktop:
return KDELayout()
name = compositor(os.environ)
if name is None:
ibus = (os.environ.get('XMODIFIERS') == '@im=ibus'
or any(os.environ.get(key) == 'ibus' for key in ('GTK_IM_MODULE', 'QT_IM_MODULE')))
if ibus and is_x11_session(os.environ):
try:
system_map = command(['gsettings', 'get', IBUS_SCHEMA, 'use-system-keyboard-layout'])
if system_map.strip() == 'false' and command(['ibus', 'engine']).strip().startswith('xkb:'):
return IBusLayout()
except RuntimeError as error:
logger.warning('IBus layout detection unavailable: %s', error)
return X11Layout()
adapter = {'cosmic': CosmicLayout, 'niri': NiriLayout, 'sway': SwayLayout,
'hyprland': HyprlandLayout, 'umbriel': UmbrielLayout, 'mango': MangoLayout}.get(name)
if adapter is None:
raise RuntimeError('No keyboard layout adapter for this compositor')
return adapter()
+231
View File
@@ -0,0 +1,231 @@
"""System input for the themed on-screen keyboard."""
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 input backend 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:
from portprotonqt.system_keyboard.keys import SERVICE_KEYS
device = None
try:
keys = {code for row in KEY_ROWS for code in row} | set(SPECIAL_KEYS)
keys.update(code for _, code in SERVICE_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 device is not None:
self._set_modifiers(device, ())
device.close()
close_layout = getattr(self.layout, 'close', None)
if close_layout is not None:
close_layout()
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 portprotonqt.system_keyboard.detection import compositor, detect_layout
from portprotonqt.system_keyboard.layouts import ManualLayout
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 portprotonqt.system_keyboard.detection import CinnamonLayout, GSettingsLayout, KDELayout, X11Layout, is_x11_session
import os
if action in {'tap', 'caps', 'language', 'modifiers'} and not self.enabled.is_set():
return
if action == 'modifiers':
modifier_only = ((self.modifiers == {ecodes.KEY_LEFTMETA}
and not is_x11_session(os.environ))
or (len(self.modifiers) == 2 and ecodes.KEY_LEFTALT in self.modifiers
and bool(self.modifiers & {ecodes.KEY_LEFTSHIFT, ecodes.KEY_RIGHTSHIFT})))
if self.modifiers - set(codes) and modifier_only:
# Replay modifier-only chords after the mouse release, with Shift last.
chord = tuple(sorted(self.modifiers, key=lambda code: (
code in {ecodes.KEY_LEFTSHIFT, ecodes.KEY_RIGHTSHIFT}, code)))
self._set_modifiers(device, ())
self.send_keys(device, chord)
self._set_modifiers(device, codes)
elif action == 'release':
self._set_modifiers(device, ())
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':
self._set_modifiers(device, ())
if (type(self.layout) is X11Layout
and 'gnome' in os.environ.get('XDG_CURRENT_DESKTOP', '').lower().split(':')):
self.send_keys(device, GSettingsLayout.switch_codes())
elif isinstance(self.layout, X11Layout) and is_x11_session(os.environ):
self.layout.switch()
elif isinstance(self.layout, CinnamonLayout):
self.send_keys(device, self.layout.switch_codes())
elif isinstance(self.layout, KDELayout):
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,))
elif action == 'tap':
try:
self.send_keys(device, tuple(code for code in codes if code not in self.modifiers))
finally:
self._set_modifiers(device, ())
def _set_modifiers(self, device: UInput, codes: tuple[int, ...]) -> None:
requested = set(codes)
for code in sorted(self.modifiers - requested, reverse=True):
try:
device.write(ecodes.EV_KEY, code, 0)
device.syn()
except OSError:
logger.exception('Failed to release system keyboard modifier %s', code)
continue
self.modifiers.discard(code)
for code in sorted(requested - self.modifiers):
self.modifiers.add(code)
device.write(ecodes.EV_KEY, code, 1)
device.syn()
def _refresh_state(self, device: UInput) -> None:
from portprotonqt.system_keyboard.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_RIGHTSHIFT, 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': bool(self.modifiers & {ecodes.KEY_LEFTSHIFT, ecodes.KEY_RIGHTSHIFT}),
'modifiers': tuple(sorted(self.modifiers)), 'layout': name})
except Exception as error:
logger.warning("Cannot update system keyboard labels: %s", error)
self.warning.emit(str(error))
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', ()))
+29
View File
@@ -0,0 +1,29 @@
"""Physical keys shared by uinput and XKB label readers."""
from evdev import ecodes
from portprotonqt.system_keyboard.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, ecodes.KEY_RIGHTSHIFT, ecodes.KEY_RIGHTCTRL}
SERVICE_KEYS = (
('Esc', ecodes.KEY_ESC), ('PrtSc', ecodes.KEY_SYSRQ), ('Del', ecodes.KEY_DELETE),
('⌫', ecodes.KEY_BACKSPACE), ('Enter', ecodes.KEY_ENTER), ('Space', ecodes.KEY_SPACE),
('Ctrl', ecodes.KEY_LEFTCTRL), ('RCtrl', ecodes.KEY_RIGHTCTRL), ('Super', ecodes.KEY_LEFTMETA),
('Alt', ecodes.KEY_LEFTALT), ('AltGr', ecodes.KEY_RIGHTALT), ('RShift', ecodes.KEY_RIGHTSHIFT),
('◄', ecodes.KEY_LEFT), ('►', ecodes.KEY_RIGHT), ('▲', ecodes.KEY_UP), ('▼', ecodes.KEY_DOWN),
*((f'F{number}', getattr(ecodes, f'KEY_F{number}')) for number in range(1, 13)),
)
KEY_KBD_LAYOUT_NEXT = ecodes.KEY_KBD_LAYOUT_NEXT
LATCH_KEYS = frozenset(MODIFIERS | {code for key, code in SERVICE_KEYS if key.startswith('F')})
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
KEYSYM_UNICODE_FLAG = 0x01000000
KEYSYM_UNICODE_MASK = 0xFFFFFF
UNICODE_MAX = 0x10FFFF
+156
View File
@@ -0,0 +1,156 @@
"""Read bundled keyboard layers and compositor-provided symbol maps."""
from functools import lru_cache
from importlib.resources import files
import re
from typing import Any
import orjson
from evdev import ecodes
from portprotonqt.keyboard_layouts import keyboard_layouts
from portprotonqt.system_keyboard.keys import (
ROWS, MODIFIERS, XKB_SHIFT_MASK, XKB_LOCK_MASK, XKB_ALTGR_MASK, XKB_KEYCODE_OFFSET,
KEYSYM_UNICODE_FLAG, KEYSYM_UNICODE_MASK, UNICODE_MAX,
)
@lru_cache(maxsize=1)
def _symbols() -> dict[str, dict[str, str]]:
return orjson.loads(files('portprotonqt').joinpath('keyboard_symbols.json').read_bytes())
def keysym_label(symbol: int | str) -> str:
"""Translate X11 keysyms without a runtime xkbcommon library."""
if isinstance(symbol, int):
value = symbol & KEYSYM_UNICODE_MASK if symbol & ~KEYSYM_UNICODE_MASK == KEYSYM_UNICODE_FLAG else symbol
if symbol & ~KEYSYM_UNICODE_MASK == KEYSYM_UNICODE_FLAG and value <= UNICODE_MAX:
return chr(value) if chr(value).isprintable() else ''
return _symbols()['values'].get(str(symbol), '')
if re.fullmatch(r'U[0-9a-fA-F]{4,8}', symbol):
value = int(symbol[1:], 16)
return chr(value) if value <= UNICODE_MAX and chr(value).isprintable() else symbol
if symbol.startswith('0x'):
value = int(symbol, 16)
fallback = f'U{value & KEYSYM_UNICODE_MASK:04X}' if value & ~KEYSYM_UNICODE_MASK == KEYSYM_UNICODE_FLAG else symbol
return _symbols()['keysyms'].get(str(value), keysym_label(value) or fallback)
return _symbols()['names'].get(symbol, symbol)
class Layout:
def __init__(self, layout: Any='us', variant: Any='', *, keymap_text: Any=None) -> None:
layout = 'us' if layout == 'en' else layout
self.identifier = f'{layout}+{variant}' if variant else layout
self.groups: dict[int, str] = {}
self.types: dict[str, tuple[set[str], dict[frozenset[str], int], dict[frozenset[str], set[str]]]] = {}
self.keys: dict[int, tuple[dict[int, str], dict[int, list[str]]]] = {}
if keymap_text is not None:
self._read_keymap(keymap_text.decode() if isinstance(keymap_text, bytes) else keymap_text)
elif self.identifier not in keyboard_layouts:
raise ValueError(f'Unknown keyboard layout: {self.identifier}')
def _read_keymap(self, text: str) -> None:
text = re.sub(r'/\*.*?\*/|//[^\n]*', '', text, flags=re.DOTALL)
codes = {name: int(code) - XKB_KEYCODE_OFFSET
for name, code in re.findall(r'<([^>]+)>\s*=\s*(\d+)\s*;', text)}
self.groups = {int(group) - 1: name for group, name in re.findall(
r'name\[(?:Group)?(\d+)\]\s*=\s*"([^"]*)"', text)}
for name, body in re.findall(r'type\s+"([^"]+)"\s*\{(.*?)\};', text, re.DOTALL):
modifiers = re.search(r'modifiers\s*=\s*([^;]+)', body)
allowed = set(modifiers[1].split('+')) if modifiers else set()
levels = {frozenset(part.strip() for part in mask.split('+') if part.strip() != 'None'):
int(level) - 1 for mask, level in re.findall(
r'map\[([^]]+)\]\s*=\s*(?:Level)?(\d+)', body)}
preserved = {frozenset(part.strip() for part in mask.split('+')):
{part.strip() for part in value.split('+')} for mask, value in re.findall(
r'preserve\[([^]]+)\]\s*=\s*([^;]+)', body)}
self.types[name] = ({part.strip() for part in allowed}, levels, preserved)
for name, body in re.findall(r'key\s+<([^>]+)>\s*\{(.*?)\};', text, re.DOTALL):
if name not in codes:
continue
types = {int(group or 1) - 1: kind for group, kind in re.findall(
r'type(?:\[(?:Group)?(\d+)\])?\s*=\s*"([^"]+)"', body)}
groups = {int(group) - 1: [part.strip() for part in symbols.split(',')]
for group, symbols in re.findall(
r'symbols\[(?:Group)?(\d+)\]\s*=\s*\[([^]]*)\]', body)}
if not groups:
symbols = re.search(r'\[([^]]*)\]', body)
if symbols:
groups[0] = [part.strip() for part in symbols[1].split(',')]
self.keys[codes[name]] = types, groups
if not self.keys:
raise ValueError('Keyboard keymap contains no physical keys')
def _keymap_labels(self, modifiers: set[int], mask: tuple[int, ...]) -> dict[str, str]:
depressed, latched, locked, group = mask
bits = depressed | latched | locked
active = set()
_, alt_groups = self.keys.get(ecodes.KEY_RIGHTALT, ({}, {}))
alt_symbols = alt_groups.get(group, alt_groups.get(0, []))
altgr_codes = {ecodes.KEY_RIGHTALT} if any(
keysym_label(symbol) in {'ISO_Level3_Shift', 'Mode_switch'} for symbol in alt_symbols) else set()
for name, bit, codes in (
('Shift', XKB_SHIFT_MASK, {ecodes.KEY_LEFTSHIFT, ecodes.KEY_RIGHTSHIFT}),
('Lock', XKB_LOCK_MASK, {ecodes.KEY_CAPSLOCK}),
('LevelThree', XKB_ALTGR_MASK, altgr_codes),
):
if bits & bit or modifiers & codes:
active.add(name)
result = {}
for code, (types, groups) in self.keys.items():
if code in MODIFIERS:
continue
symbols = groups.get(group, groups.get(0, []))
kind = types.get(group, types.get(0, ''))
if not kind:
labels = [keysym_label(symbol) for symbol in symbols]
alphabetic = len(labels) > 1 and labels[0].islower() and labels[1].isupper()
kind = 'ALPHABETIC' if alphabetic else 'TWO_LEVEL'
if len(labels) > 2:
kind = 'FOUR_LEVEL_SEMIALPHABETIC' if alphabetic else 'FOUR_LEVEL'
if alphabetic and len(labels) > 3 and labels[2].islower() and labels[3].isupper():
kind = 'FOUR_LEVEL_ALPHABETIC'
if len(labels) == 1:
kind = 'ONE_LEVEL'
allowed, levels, preserved = self.types.get(kind, (set(), {}, {}))
selected = frozenset(active & allowed)
level = levels.get(selected, 0)
symbol = symbols[level] if level < len(symbols) else 'NoSymbol'
label = keysym_label(symbol)
if 'Lock' in active and ('Lock' not in allowed or 'Lock' in preserved.get(selected, set())):
label = _symbols()['upper'].get(label, label.upper() if len(label) == 1 else label)
result[str(code)] = label
return result
def labels(self, modifiers: Any=(), *, mask: Any=None) -> dict[str, str]:
native_mask = (0, 0, 0, 0) if mask is None else tuple(mask)
depressed, latched, locked, group = native_mask
codes = set(modifiers)
if self.keys:
return self._keymap_labels(codes, native_mask)
bits = depressed | latched | locked
shift = bool(bits & XKB_SHIFT_MASK or codes & {ecodes.KEY_LEFTSHIFT, ecodes.KEY_RIGHTSHIFT})
altgr = bool(bits & XKB_ALTGR_MASK or ecodes.KEY_RIGHTALT in codes)
caps = bool(bits & XKB_LOCK_MASK or ecodes.KEY_CAPSLOCK in codes)
layer = '_'.join(name for name, enabled in (
('shift', shift), ('altgr', altgr), ('caps', caps)) if enabled) or 'normal'
rows = keyboard_layouts[self.identifier][layer]
return {str(code): label.replace('&&', '&')
for labels, physical in zip(rows, ROWS, strict=True)
for label, (_, code) in zip(labels, physical, strict=True) if code not in MODIFIERS}
def layout_identifier(self, group: int) -> str:
return self.groups.get(group, self.identifier)
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'
self.layout = Layout(language)
self.language = language
def labels(self, modifiers: Any=()) -> Any:
return self.layout.labels(modifiers)
+14
View File
@@ -0,0 +1,14 @@
"""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))
+753
View File
@@ -0,0 +1,753 @@
"""Reuse the embedded keyboard's buttons and theme for system input."""
import ctypes as C
from functools import partial
import mmap
import select
import sys
import tempfile
from types import SimpleNamespace
from typing import Any, cast
import orjson
from evdev import ecodes
from PySide6.QtCore import QEvent, QObject, QPoint, QPointF, QSocketNotifier, Qt, QTimer
from PySide6.QtGui import QCloseEvent, QIcon, QMouseEvent, QImage, QRegion
from PySide6.QtWidgets import QApplication, QFrame, QLabel, QPushButton, QSizePolicy, QWidget
from 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
from portprotonqt.system_keyboard.input import KEY_ROWS, SystemInputWorker
from portprotonqt.system_keyboard.keys import LATCH_KEYS, SERVICE_KEYS
from portprotonqt.system_keyboard.native import load_library
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 set_gamepad_icon(self, button: QPushButton, icon_type: str, gtype: Any = '') -> None:
if self.owner.input_manager.gamepad:
super().set_gamepad_icon(button, icon_type, gtype)
else:
button.setIcon(QIcon())
def get_layouts_setxkbmap(self) -> list[str]:
return ['us']
def _space_button_text(self) -> str:
return 'Space'
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
self.num_cols = metrics['columns']
self.button_height = metrics['key_height']
self.spacing = metrics['spacing']
margin = metrics['margin']
self.keyboard_layout.setSpacing(self.spacing)
self.keyboard_layout.setContentsMargins(margin, margin, margin, margin)
width = min(self.owner.width(), metrics['width'])
height = metrics['height'] + (metrics['warning_height'] if self.owner.warning_message else 0)
if hasattr(self, 'keyboard_container'):
self.keyboard_container.setFixedSize(width, height)
for column in range(self.num_cols):
self.keyboard_layout.setColumnStretch(column, 1)
def update_keyboard(self) -> None:
self._apply_responsive_metrics()
selected = next((key for key, button in self.buttons.items() if button is self.selected_button), None)
self.selected_button = None
while self.keyboard_layout.count():
item = self.keyboard_layout.takeAt(0)
widget = item.widget() if item is not None else None
if widget is not None:
widget.setParent(None)
widget.deleteLater()
self.buttons.clear()
self.keycodes = dict(SERVICE_KEYS)
for row, codes in zip(keyboard_layouts['us']['normal'], KEY_ROWS, strict=True):
self.keycodes.update(zip(row, codes, strict=True))
units = self.theme.SYSTEM_KEYBOARD['row_units']
for row, keys in enumerate(self.theme.SYSTEM_KEYBOARD['rows']):
column = 0
for key, span in keys:
if key == '▲▼':
self._add_key('▲', (row * units, column, 1, span))
self._add_key('▼', (row * units + 1, column, 1, span))
else:
self._add_key(key, (row * units, column, units, span))
column += span
self.apply_key_state()
self._set_selected_button(self.buttons.get(selected or 'Esc', self.buttons['Esc']))
if self.owner.warning_message:
warning = QLabel(self.owner.warning_message)
warning.setStyleSheet(self.theme.SETTINGS_TITLE_STYLE)
warning.setWordWrap(True)
self.keyboard_layout.addWidget(warning, len(self.theme.SYSTEM_KEYBOARD['rows']) * units,
0, units, self.num_cols)
def _add_key(self, key: str, position: tuple[int, int, int, int]) -> None:
button = QPushButton('⬆' if key == 'RShift' else key)
button.setFocusPolicy(Qt.FocusPolicy.NoFocus)
button.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Fixed)
button.setMinimumWidth(self.theme.SYSTEM_KEYBOARD['minimum_key_width'])
units = self.theme.SYSTEM_KEYBOARD['row_units']
height = (self.button_height + self.spacing) * position[2] // units - self.spacing
button.setFixedHeight(height)
code = self.keycodes.get(key)
if code is not None and code in LATCH_KEYS:
button.setCheckable(True)
button.clicked.connect(lambda checked: self._toggle_modifier(code, checked))
elif key == 'CAPS':
button.setCheckable(True)
button.clicked.connect(self.on_caps_click)
elif key == '⌫':
button.setProperty('sound_event', False)
button.pressed.connect(self.on_backspace_pressed)
button.released.connect(self.stop_backspace_repeat)
elif key in {'🌐', 'Hide'}:
button.clicked.connect(self.on_lang_click if key == '🌐' else self.hide)
else:
button.clicked.connect(lambda checked=False: self.on_button_click(key))
self.keyboard_layout.addWidget(button, *position)
self.buttons[key] = button
icon = {'⬆': 'right', 'RShift': 'right', '⌫': 'add_game', '🌐': 'left', 'Hide': 'back'}.get(key)
if icon is not None:
self.set_gamepad_icon(button, icon, self.input_manager.gamepad_type)
def _toggle_modifier(self, code: int, checked: bool) -> None:
if checked:
self.modifiers.add(code)
else:
self.modifiers.discard(code)
self.shift_pressed = bool(self.modifiers & {ecodes.KEY_LEFTSHIFT, ecodes.KEY_RIGHTSHIFT})
self.owner.worker.commands.put(('modifiers', tuple(sorted(self.modifiers))))
self.apply_key_state()
def apply_key_state(self) -> None:
for key, button in self.buttons.items():
code = self.keycodes.get(key)
if code not in LATCH_KEYS | {None, ecodes.KEY_TAB, ecodes.KEY_CAPSLOCK} and str(code) in self.labels:
text = self.labels[str(code)].replace('&', '&&')
if button.text() != text:
button.setText(text)
for key, button in self.buttons.items():
checked = None
if key == 'CAPS':
checked = self.caps_lock
elif button.isCheckable():
checked = self.keycodes[key] in self.modifiers
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_caps_click(self) -> None:
self.apply_key_state()
self.owner.worker.commands.put(('caps', ()))
def on_shift_click(self, checked: bool) -> None:
self._toggle_modifier(ecodes.KEY_LEFTSHIFT, checked)
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, layer_shell: bool = False) -> 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 = layer_shell
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, gamepad=False)
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', 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 (value is None or isinstance(value, str)):
self.input_manager.gamepad = value is not None
if value is not None:
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()
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.layer_interface = self._interface('zwlr_layer_surface_v1')
self.shell_interface = self._interface('zwlr_layer_shell_v1')
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),
'portproton_keyboard_wayland_interface': ([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, p, 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 _interface(self, name: str) -> int:
interface = self.lib.portproton_keyboard_wayland_interface(name.encode())
if not interface:
raise RuntimeError(f'Unknown Wayland interface: {name}')
return interface
def _request(self, proxy: int | None, request: tuple[int, Any], arguments: tuple[Any, ...] = ()) -> Any:
opcode, interface = request
result = self.lib.wl_proxy_marshal_flags(proxy, opcode, interface, 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
with tempfile.TemporaryFile() as storage:
storage.truncate(size)
memory = mmap.mmap(storage.fileno(), size)
try:
pool = self._request(self.shm, (0, self._interface('wl_shm_pool')),
(C.c_void_p(), C.c_int(storage.fileno()), 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)
except Exception:
memory.close()
raise
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 isinstance(target, QPushButton) and self.window.keyboard.selected_button is not target:
self.window.keyboard._set_selected_button(target)
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()
+36 -6
View File
@@ -16,8 +16,8 @@ from portprotonqt.qt_utils import get_device_pixel_ratio
logger = get_logger(__name__)
GAMEPAD_HINT_ACTIONS = ("confirm", "back", "add_game", "search", "decrease_size", "increase_size", "context_menu", "menu", "guide_select", "mouse_emulation", "prev_section", "next_section")
COMBINATION_HINT_ACTIONS = ("guide_select", "mouse_emulation")
GAMEPAD_HINT_ACTIONS = ("confirm", "back", "add_game", "search", "decrease_size", "increase_size", "context_menu", "menu", "guide_select", "system_keyboard", "mouse_emulation", "prev_section", "next_section")
COMBINATION_HINT_ACTIONS = ("guide_select", "system_keyboard", "mouse_emulation")
VOLUME_HINT_ACTIONS = ("decrease_size", "increase_size")
def _load_control_hint_pixmap(paths: tuple[str | None, ...], width: int, height: int) -> QPixmap:
@@ -220,6 +220,7 @@ class MainWindowControlHintsMixin:
("search", _("Search")),
("guide_select", _("Refresh Grid")),
("mouse_emulation", _("Mouse Emulation")),
("system_keyboard", _("System Keyboard")),
("prev_section", _("Prev Tab")),
("next_section", _("Next Tab")),
]
@@ -294,7 +295,18 @@ class MainWindowControlHintsMixin:
layout.setSpacing(6)
guide_icon = _ControlHintIconLabel(26, 26)
if action == "mouse_emulation":
if action == "system_keyboard":
_set_control_hint_icon(
guide_icon,
(
self.theme_manager.get_icon("xbox_start", self.current_theme_name, as_path=True),
self.theme_manager.get_icon("ps_options", self.current_theme_name, as_path=True),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
),
26,
26,
)
elif action == "mouse_emulation":
_set_control_hint_icon(
guide_icon,
(
@@ -334,7 +346,18 @@ class MainWindowControlHintsMixin:
select_icon = _ControlHintIconLabel(26, 26)
if action == "mouse_emulation":
if action == "system_keyboard":
_set_control_hint_icon(
select_icon,
(
self.theme_manager.get_icon("xbox_y", self.current_theme_name, as_path=True),
self.theme_manager.get_icon("ps_triangle", self.current_theme_name, as_path=True),
self.theme_manager.get_theme_image("placeholder", self.current_theme_name),
),
26,
26,
)
elif action == "mouse_emulation":
_set_control_hint_icon(
select_icon,
(
@@ -391,6 +414,9 @@ class MainWindowControlHintsMixin:
def _triggerControlHintAction(self, action: str | None) -> None:
if action is None:
return
if action == "system_keyboard":
self.system_keyboard.toggle()
return
if action == "menu":
self._triggerControlHintFullscreen()
return
@@ -504,7 +530,9 @@ class MainWindowControlHintsMixin:
):
guide_icon, plus_icon, select_icon = icon_element
if action == "mouse_emulation":
if action == "system_keyboard":
guide_icon_name = "ps_options" if gtype == GamepadType.PLAYSTATION else "xbox_start"
elif action == "mouse_emulation":
if gtype == GamepadType.PLAYSTATION:
guide_icon_name = "ps_share"
else:
@@ -537,7 +565,9 @@ class MainWindowControlHintsMixin:
)
select_icon_name = "xbox_view"
if action == "guide_select":
if action == "system_keyboard":
select_icon_name = "ps_triangle" if gtype == GamepadType.PLAYSTATION else "xbox_y"
elif action == "guide_select":
if gtype == GamepadType.XBOX:
select_icon_name = "xbox_view"
elif gtype == GamepadType.PLAYSTATION:
+2 -2
View File
@@ -1771,12 +1771,12 @@ QPushButton:pressed {{
border: {border_none} {color_transparent};
color: {color_text};
}}
QPushButton[checked="true"] {{
QPushButton:checked {{
background-color: {color_accent};
color: {color_text_accent_hover};
border: {border_none} {color_transparent};
}}
QPushButton[checked="true"]:focus {{
QPushButton:checked:focus {{
border: {border_thin} {color_text};
}}
"""
@@ -313,6 +313,31 @@ 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": 270,
"minimum_key_width": 18,
"warning_height": 36,
"key_height": 40,
"spacing": 4,
"margin": 5,
"row_units": 2,
"columns": 30,
"rows": (
(("Esc", 2), ("F1", 2), ("F2", 2), ("F3", 2), ("F4", 2), ("F5", 2), ("F6", 2),
("F7", 2), ("F8", 2), ("F9", 2), ("F10", 2), ("F11", 2), ("F12", 2), ("PrtSc", 2), ("Del", 2)),
(("`", 2), ("1", 2), ("2", 2), ("3", 2), ("4", 2), ("5", 2), ("6", 2), ("7", 2),
("8", 2), ("9", 2), ("0", 2), ("-", 2), ("=", 2), ("⌫", 4)),
(("TAB", 3), ("q", 2), ("w", 2), ("e", 2), ("r", 2), ("t", 2), ("y", 2), ("u", 2),
("i", 2), ("o", 2), ("p", 2), ("[", 2), ("]", 2), ("\\", 3)),
(("CAPS", 4), ("a", 2), ("s", 2), ("d", 2), ("f", 2), ("g", 2), ("h", 2), ("j", 2),
("k", 2), ("l", 2), (";", 2), ("'", 2), ("Enter", 4)),
(("⬆", 4), ("<", 2), ("z", 2), ("x", 2), ("c", 2), ("v", 2), ("b", 2), ("n", 2),
("m", 2), (",", 2), (".", 2), ("/", 2), ("RShift", 4)),
(("Ctrl", 2), ("Super", 2), ("Alt", 2), ("Space", 10), ("🌐", 2), ("AltGr", 2),
("RCtrl", 2), ("◄", 2), ("▲▼", 2), ("►", 2), ("Hide", 2)),
),
}
DETAIL_PAGE_LAYOUT_MODE = "full"
COMPATIBILITY_REPORT_DIALOG = {
@@ -44,6 +44,21 @@ CONTEXT_MENU_STYLE = f"""
}}
"""
SYSTEM_KEYBOARD_BACKGROUND_STYLE = f"""
QFrame#systemKeyboard {{
background: {color_bg};
border-radius: {border_radius_small};
}}
QWidget#systemKeyboardContainer {{
background: {color_transparent};
}}
QFrame#systemKeyboard QPushButton {{
min-width: 0;
min-height: 0;
padding: 0;
}}
"""
VIRTUAL_KEYBOARD_STYLE = f"""
QWidget {{
background: {color_overlay};
@@ -77,12 +92,12 @@ QPushButton:pressed {{
background-color: {color_surface};
border: {border_none} {color_transparent};
}}
QPushButton[checked="true"] {{
QPushButton:checked {{
background-color: {color_accent};
color: {color_text_accent_hover};
border: {border_none} {color_transparent};
}}
QPushButton[checked="true"]:focus {{
QPushButton:checked:focus {{
border: {border_thin} {color_text};
}}
"""
+4
View File
@@ -104,6 +104,10 @@ 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')
keyboard_action.triggered.connect(system_keyboard.toggle)
if self.minimal_mode:
return
self.tray_menu.addSeparator()
+4
View File
@@ -136,6 +136,7 @@ def test_theme_tab_focusables_include_delete_button(monkeypatch: MonkeyPatch) ->
def test_native_gamepad_result_preserves_python_interface(monkeypatch: MonkeyPatch) -> None:
monkeypatch.setattr(native_gamepad, "_library", MagicMock())
controller = 42
monkeypatch.setattr(native_gamepad._library, "portproton_gamepad_find", lambda: controller)
monkeypatch.setattr(native_gamepad._library, "portproton_gamepad_close", lambda _handle: None)
@@ -159,6 +160,7 @@ def test_native_gamepad_result_preserves_python_interface(monkeypatch: MonkeyPat
def test_native_gamepad_update_passes_collection_handle(monkeypatch: MonkeyPatch) -> None:
monkeypatch.setattr(native_gamepad, "_library", MagicMock())
updated_handles: list[int] = []
gamepad = SDLGamepad(42, "Gamepads", "sdl3-gamepad:7", 7, 1)
monkeypatch.setattr(native_gamepad._library, "portproton_gamepad_close", lambda _handle: None)
@@ -189,6 +191,7 @@ def test_native_gamepad_update_passes_collection_handle(monkeypatch: MonkeyPatch
def test_native_gamepad_reports_sdl_discovery_error(monkeypatch: MonkeyPatch) -> None:
monkeypatch.setattr(native_gamepad, "_library", MagicMock())
monkeypatch.setattr(native_gamepad._library, "portproton_gamepad_find", lambda: None)
monkeypatch.setattr(
native_gamepad._library,
@@ -201,6 +204,7 @@ def test_native_gamepad_reports_sdl_discovery_error(monkeypatch: MonkeyPatch) ->
def test_native_gamepad_absence_is_not_an_error(monkeypatch: MonkeyPatch) -> None:
monkeypatch.setattr(native_gamepad, "_library", MagicMock())
monkeypatch.setattr(native_gamepad._library, "portproton_gamepad_find", lambda: None)
monkeypatch.setattr(native_gamepad._library, "portproton_gamepad_get_error", lambda: b"")
+8
View File
@@ -3571,3 +3571,11 @@ def test_steam_watch_keeps_stop_during_preparation_gap(monkeypatch: MonkeyPatch)
monkeypatch.setattr(main_window_module.time, "monotonic", lambda: 1004.0)
MainWindow._steam_scan_finished(cast(Any, window), "620")
assert watch["running"] is False
def test_system_keyboard_control_hint_opens_keyboard() -> None:
window = SimpleNamespace(system_keyboard=SimpleNamespace(toggle=MagicMock()))
MainWindowControlHintsMixin._triggerControlHintAction(cast(Any, window), "system_keyboard")
window.system_keyboard.toggle.assert_called_once_with()
+24
View File
@@ -0,0 +1,24 @@
import ctypes
import importlib.util
import sys
from pathlib import Path
from unittest.mock import Mock
import pytest
def test_missing_sdl_disables_gamepad(monkeypatch: pytest.MonkeyPatch) -> None:
library_loader = Mock(side_effect=OSError("libSDL3.so.0: not found"))
monkeypatch.setattr(ctypes.CDLL, "__init__", library_loader)
path = Path(__file__).parents[1] / "portprotonqt" / "native_gamepad.py"
spec = importlib.util.spec_from_file_location("gamepad_without_sdl", path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
monkeypatch.setitem(sys.modules, spec.name, module)
spec.loader.exec_module(module)
assert module.find_gamepad() is None
assert module.find_gamepad() is None
module.shutdown()
library_loader.assert_called_once()
File diff suppressed because it is too large. Load diff