K65 Studio: Linux control app for the Corsair K65 PLUS Wireless
Bragi protocol over hidraw, device service with heartbeat and notifications, PySide6 UI with animated preview, profiles, tray, autostart, udev rule and installer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
7e276912da
23 files changed
+2631
No files matched your search
@@ -0,0 +1 @@
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,17 @@
|
||||
import argparse
|
||||
import logging
|
||||
|
||||
|
||||
def run() -> int:
|
||||
parser = argparse.ArgumentParser(prog="k65studio", description="Corsair K65 PLUS Wireless für Linux")
|
||||
parser.add_argument("--minimized", action="store_true", help="nur im Tray starten")
|
||||
parser.add_argument("--debug", action="store_true", help="ausführliches Logging")
|
||||
args = parser.parse_args()
|
||||
logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
from .app import main
|
||||
return main(minimized=args.minimized)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(run())
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Application wiring: Qt app, tray icon, single instance and the device service."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QObject, QTimer, Signal
|
||||
from PySide6.QtGui import QAction, QActionGroup, QIcon
|
||||
from PySide6.QtNetwork import QLocalServer, QLocalSocket
|
||||
from PySide6.QtWidgets import QApplication, QMenu, QSystemTrayIcon
|
||||
|
||||
from .device import DeviceService, DeviceState
|
||||
from .profiles import Config
|
||||
from .ui.main_window import MainWindow
|
||||
from .ui.style import STYLESHEET
|
||||
|
||||
ICON = Path(__file__).parent / "assets" / "k65studio.svg"
|
||||
INSTANCE_NAME = f"k65studio-{os.getuid()}"
|
||||
LOW_BATTERY = 15
|
||||
|
||||
|
||||
class _Bridge(QObject):
|
||||
state = Signal(object)
|
||||
|
||||
|
||||
class App:
|
||||
def __init__(self, argv: list[str], minimized: bool):
|
||||
self.qapp = QApplication(argv)
|
||||
self.qapp.setApplicationName("K65 Studio")
|
||||
self.qapp.setDesktopFileName("k65studio")
|
||||
self.qapp.setQuitOnLastWindowClosed(False)
|
||||
self.qapp.setStyleSheet(STYLESHEET)
|
||||
self.icon = QIcon(str(ICON))
|
||||
self.qapp.setWindowIcon(self.icon)
|
||||
|
||||
self.config = Config.load()
|
||||
self.window = MainWindow(self.config)
|
||||
self.window.closeEvent = self._close_window
|
||||
|
||||
self.bridge = _Bridge()
|
||||
self.bridge.state.connect(self._on_state)
|
||||
self.device = DeviceService(self.bridge.state.emit)
|
||||
self.window.profile_changed.connect(lambda profile: self.device.apply(profile))
|
||||
self.window.reinit_requested.connect(self._reinit)
|
||||
self._warned_battery = False
|
||||
self._hint_shown = False
|
||||
|
||||
self.tray = self._build_tray() if QSystemTrayIcon.isSystemTrayAvailable() else None
|
||||
self.server = QLocalServer()
|
||||
QLocalServer.removeServer(INSTANCE_NAME)
|
||||
self.server.listen(INSTANCE_NAME)
|
||||
self.server.newConnection.connect(self._show_window)
|
||||
|
||||
self.qapp.aboutToQuit.connect(self._shutdown)
|
||||
signal.signal(signal.SIGTERM, lambda *_: self.qapp.quit())
|
||||
signal.signal(signal.SIGINT, lambda *_: self.qapp.quit())
|
||||
|
||||
self.device.start(self.config.profile)
|
||||
if not ((minimized or self.config.start_minimized) and self.tray):
|
||||
self._show_window()
|
||||
|
||||
def _build_tray(self) -> QSystemTrayIcon:
|
||||
tray = QSystemTrayIcon(self.icon)
|
||||
tray.setToolTip("K65 Studio")
|
||||
menu = QMenu()
|
||||
menu.addAction("Öffnen", self._show_window)
|
||||
self.profile_menu = menu.addMenu("Profil")
|
||||
self.profile_menu.aboutToShow.connect(self._fill_profile_menu)
|
||||
menu.addSeparator()
|
||||
menu.addAction("Beenden", self.qapp.quit)
|
||||
tray.setContextMenu(menu)
|
||||
tray.activated.connect(lambda reason: reason == QSystemTrayIcon.Trigger and self._toggle_window())
|
||||
tray.show()
|
||||
self._tray_menu = menu
|
||||
return tray
|
||||
|
||||
def _fill_profile_menu(self) -> None:
|
||||
self.profile_menu.clear()
|
||||
group = QActionGroup(self.profile_menu)
|
||||
for name in self.config.profiles:
|
||||
act = QAction(name, self.profile_menu, checkable=True, checked=name == self.config.active)
|
||||
act.triggered.connect(lambda _=False, n=name: self.window.activate_profile(n))
|
||||
group.addAction(act)
|
||||
self.profile_menu.addAction(act)
|
||||
|
||||
def _show_window(self) -> None:
|
||||
while self.server.hasPendingConnections():
|
||||
self.server.nextPendingConnection().close()
|
||||
self.window.showNormal()
|
||||
self.window.raise_()
|
||||
self.window.activateWindow()
|
||||
|
||||
def _toggle_window(self) -> None:
|
||||
if self.window.isVisible():
|
||||
self.window.hide()
|
||||
else:
|
||||
self._show_window()
|
||||
|
||||
def _close_window(self, event) -> None:
|
||||
if self.tray is None:
|
||||
event.accept()
|
||||
self.qapp.quit()
|
||||
return
|
||||
event.ignore()
|
||||
self.window.hide()
|
||||
if not self._hint_shown:
|
||||
self._hint_shown = True
|
||||
self.tray.showMessage("K65 Studio", "Läuft im Hintergrund weiter, damit die Beleuchtung erhalten bleibt.",
|
||||
self.icon, 4000)
|
||||
|
||||
def _on_state(self, state: DeviceState) -> None:
|
||||
self.window.set_state(state)
|
||||
if self.tray is None:
|
||||
return
|
||||
if state.keyboard and state.battery is not None:
|
||||
self.tray.setToolTip(f"K65 Studio · K65 PLUS · Akku {state.battery} %")
|
||||
if state.battery <= LOW_BATTERY and not self._warned_battery:
|
||||
self._warned_battery = True
|
||||
self.tray.showMessage("Akku schwach", f"K65 PLUS: noch {state.battery} %. Bitte bald laden.",
|
||||
QSystemTrayIcon.Warning, 8000)
|
||||
elif state.battery > LOW_BATTERY + 5:
|
||||
self._warned_battery = False
|
||||
else:
|
||||
self.tray.setToolTip("K65 Studio · Tastatur nicht verbunden")
|
||||
|
||||
def _reinit(self) -> None:
|
||||
self.device.stop(restore_hardware=False)
|
||||
self.device = DeviceService(self.bridge.state.emit)
|
||||
self.device.start(self.config.profile)
|
||||
|
||||
def _shutdown(self) -> None:
|
||||
self.config.save()
|
||||
self.device.stop(restore_hardware=self.config.restore_hardware_on_exit)
|
||||
if self.tray:
|
||||
self.tray.hide()
|
||||
|
||||
def run(self) -> int:
|
||||
# Wake the interpreter regularly so Python signal handlers (SIGTERM/SIGINT) run.
|
||||
self._sig_timer = QTimer(interval=300, timeout=lambda: None)
|
||||
self._sig_timer.start()
|
||||
return self.qapp.exec()
|
||||
|
||||
|
||||
def notify_running_instance() -> bool:
|
||||
sock = QLocalSocket()
|
||||
sock.connectToServer(INSTANCE_NAME)
|
||||
ok = sock.waitForConnected(300)
|
||||
sock.close()
|
||||
return ok
|
||||
|
||||
|
||||
def main(minimized: bool = False) -> int:
|
||||
if notify_running_instance():
|
||||
return 0
|
||||
return App(sys.argv, minimized).run()
|
||||
@@ -0,0 +1,20 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<defs>
|
||||
<linearGradient id="g" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0" stop-color="#19d3c5"/>
|
||||
<stop offset="0.5" stop-color="#7a2cff"/>
|
||||
<stop offset="1" stop-color="#ff2d95"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="3" y="15" width="58" height="34" rx="7" fill="#15171b" stroke="url(#g)" stroke-width="3"/>
|
||||
<g fill="url(#g)">
|
||||
<rect x="9" y="21" width="6" height="5" rx="1.2"/><rect x="17" y="21" width="6" height="5" rx="1.2"/>
|
||||
<rect x="25" y="21" width="6" height="5" rx="1.2"/><rect x="33" y="21" width="6" height="5" rx="1.2"/>
|
||||
<rect x="41" y="21" width="6" height="5" rx="1.2"/><rect x="49" y="21" width="6" height="5" rx="1.2"/>
|
||||
<rect x="9" y="29" width="9" height="5" rx="1.2"/><rect x="20" y="29" width="6" height="5" rx="1.2"/>
|
||||
<rect x="28" y="29" width="6" height="5" rx="1.2"/><rect x="36" y="29" width="6" height="5" rx="1.2"/>
|
||||
<rect x="44" y="29" width="11" height="5" rx="1.2"/>
|
||||
<rect x="9" y="37" width="7" height="6" rx="1.2"/><rect x="18" y="37" width="26" height="6" rx="1.2"/>
|
||||
<rect x="46" y="37" width="9" height="6" rx="1.2"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.2 KiB |
@@ -0,0 +1,39 @@
|
||||
"""XDG autostart entry for starting minimized at login."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
AUTOSTART_FILE = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "autostart" / "k65studio.desktop"
|
||||
|
||||
|
||||
def _exec_line() -> str:
|
||||
launcher = shutil.which("k65studio")
|
||||
if launcher:
|
||||
return f"{launcher} --minimized"
|
||||
project = Path(__file__).resolve().parent.parent
|
||||
return f"sh -c 'cd \"{project}\" && exec \"{sys.executable}\" -m k65studio --minimized'"
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
return AUTOSTART_FILE.exists()
|
||||
|
||||
|
||||
def set_enabled(enabled: bool) -> None:
|
||||
if not enabled:
|
||||
AUTOSTART_FILE.unlink(missing_ok=True)
|
||||
return
|
||||
AUTOSTART_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
AUTOSTART_FILE.write_text(
|
||||
"[Desktop Entry]\n"
|
||||
"Type=Application\n"
|
||||
"Name=K65 Studio\n"
|
||||
"Comment=Corsair K65 PLUS Wireless Beleuchtung und Einstellungen\n"
|
||||
f"Exec={_exec_line()}\n"
|
||||
"Icon=k65studio\n"
|
||||
"X-GNOME-Autostart-enabled=true\n"
|
||||
"X-KDE-autostart-after=panel\n"
|
||||
)
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Corsair "Bragi" protocol as spoken by the K65 PLUS Wireless and its Slipstream receiver.
|
||||
|
||||
Every packet is 64 bytes: [target, command, args...].
|
||||
target 0x08 = the device behind this USB interface (receiver, or keyboard when wired)
|
||||
target 0x09 = the keyboard paired to the receiver (wireless)
|
||||
Responses echo [target, command, status, data...]; status 0 means success.
|
||||
|
||||
Protocol knowledge from the OpenLinkHub (GPL-3.0) and OpenRGB (GPL-2.0+) projects.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
|
||||
VENDOR_CORSAIR = 0x1B1C
|
||||
PID_SLIPSTREAM_K65 = 0x2B07
|
||||
PIDS_K65_PLUS_WIRED = (0x2B10, 0x2B11, 0x2B23)
|
||||
|
||||
TARGET_LOCAL = 0x08
|
||||
TARGET_PAIRED = 0x09
|
||||
|
||||
# Commands
|
||||
CMD_SET = 0x01
|
||||
CMD_GET = 0x02
|
||||
CMD_CLOSE = 0x05
|
||||
CMD_WRITE_FIRST = 0x06
|
||||
CMD_WRITE_NEXT = 0x07
|
||||
CMD_READ = 0x08
|
||||
CMD_PREPARE = 0x09
|
||||
CMD_OPEN = 0x0D
|
||||
CMD_HEARTBEAT = 0x12
|
||||
CMD_DEVICE_LIST = 0x24
|
||||
|
||||
# Properties (CMD_SET / CMD_GET)
|
||||
PROP_BRIGHTNESS = 0x02 # u16, 0..1000
|
||||
PROP_MODE = 0x03 # 1 = hardware, 2 = software
|
||||
PROP_SLEEP = 0x0E # u32, milliseconds
|
||||
PROP_BATTERY = 0x0F # u16, per mille
|
||||
PROP_FIRMWARE = 0x13
|
||||
PROP_GAME_MODE = 0x45 # 0/1
|
||||
PROP_LOCKS = 0x4A # bitmask, see LOCK_*
|
||||
|
||||
MODE_HARDWARE = 0x01
|
||||
MODE_SOFTWARE = 0x02
|
||||
|
||||
LOCK_WIN = 0x01
|
||||
LOCK_ALT_TAB = 0x02
|
||||
LOCK_ALT_F4 = 0x04
|
||||
LOCK_SHIFT_TAB = 0x08
|
||||
|
||||
# Writable resources
|
||||
RESOURCE_LIGHTING = 0x6D60
|
||||
RESOURCE_KEYMAP = 0x02
|
||||
|
||||
HANDLE = 0x01
|
||||
CHUNK_FIRST = 61 # 64 - [target, cmd, handle]
|
||||
KEYMAP_SIZE = 123
|
||||
|
||||
# Notifications (second vendor interface)
|
||||
NOTIFY_CONNECTION = 0x36
|
||||
|
||||
# Lighting effect ids
|
||||
FX_STATIC = 0x207E
|
||||
FX_COLOR_PULSE = 0xAD4F
|
||||
FX_COLOR_SHIFT = 0xA5FA
|
||||
FX_COLOR_WAVE = 0x7BFF
|
||||
FX_RAINBOW_WAVE = 0xB94C
|
||||
FX_RAIN = 0xA07E
|
||||
FX_SPIRAL_RAINBOW = 0xAB87
|
||||
FX_WATERCOLOR = 0x0022
|
||||
FX_TYPE_KEY = 0xB1F9
|
||||
FX_TYPE_RIPPLE = 0x09A2
|
||||
FX_VISOR = 0x90C0
|
||||
|
||||
COLORS_NONE = 0x00
|
||||
COLORS_SPECIFIC = 0x01
|
||||
COLORS_RANDOM = 0x02
|
||||
COLORS_ALT = 0x03
|
||||
|
||||
SPEED_SLOW = 0x03
|
||||
SPEED_MEDIUM = 0x04
|
||||
SPEED_FAST = 0x05
|
||||
|
||||
# Default keymap: HID usage -> function code. 57 = regular key, 59 = key with an Fn layer,
|
||||
# 63 = modifier. Everything else stays 0x01 (no key at that position).
|
||||
_FN_LAYER = {18, 19, 47, 48, 55, 56, 58, 59, 60, 61, *range(64, 70)}
|
||||
_MODIFIERS = {105, 106, 107, 109, 110, 111, 122}
|
||||
_REGULAR = {*range(4, 18), *range(20, 47), *range(49, 50), *range(51, 55), 57,
|
||||
62, 63, 74, 75, 76, *range(78, 83), 108}
|
||||
_REGULAR -= _FN_LAYER
|
||||
|
||||
|
||||
def default_keymap() -> bytes:
|
||||
table = bytearray([0x01] * KEYMAP_SIZE)
|
||||
for usage in _REGULAR:
|
||||
table[usage] = 57
|
||||
for usage in _FN_LAYER:
|
||||
table[usage] = 59
|
||||
for usage in _MODIFIERS:
|
||||
table[usage] = 63
|
||||
return bytes(table)
|
||||
|
||||
|
||||
def packet(target: int, *parts: bytes | int) -> bytes:
|
||||
out = bytearray([target])
|
||||
for p in parts:
|
||||
out += bytes([p]) if isinstance(p, int) else p
|
||||
if len(out) > 64:
|
||||
raise ValueError("packet exceeds 64 bytes")
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def set_property(target: int, prop: int, value: bytes) -> bytes:
|
||||
return packet(target, CMD_SET, prop, 0x00, value)
|
||||
|
||||
|
||||
def get_property(target: int, prop: int) -> bytes:
|
||||
return packet(target, CMD_GET, prop)
|
||||
|
||||
|
||||
def block_packets(target: int, payload: bytes, declared: int | None = None) -> list[bytes]:
|
||||
"""Split a length-prefixed block write to HANDLE into first/next packets."""
|
||||
framed = struct.pack("<HH", len(payload) if declared is None else declared, 0) + payload
|
||||
chunks = [framed[i:i + CHUNK_FIRST] for i in range(0, len(framed), CHUNK_FIRST)]
|
||||
return [packet(target, CMD_WRITE_FIRST if i == 0 else CMD_WRITE_NEXT, HANDLE, c)
|
||||
for i, c in enumerate(chunks)]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Rgb:
|
||||
r: int
|
||||
g: int
|
||||
b: int
|
||||
|
||||
@classmethod
|
||||
def from_hex(cls, value: str) -> "Rgb":
|
||||
value = value.lstrip("#")
|
||||
return cls(int(value[0:2], 16), int(value[2:4], 16), int(value[4:6], 16))
|
||||
|
||||
def hex(self) -> str:
|
||||
return f"#{self.r:02x}{self.g:02x}{self.b:02x}"
|
||||
|
||||
|
||||
LIGHTING_BLOCK_SIZE = 96
|
||||
|
||||
|
||||
def lighting_packets(target: int, effect: int, color_mode: int = COLORS_NONE, speed: int = 0,
|
||||
direction: int = 0, colors: list[Rgb] | tuple[Rgb, ...] = ()) -> list[bytes]:
|
||||
"""Hardware lighting effect: id, color mode, speed, direction, then colors as (A, B, G, R)."""
|
||||
body = bytearray(struct.pack("<H", effect))
|
||||
body += bytes([color_mode, speed, direction, 0x00])
|
||||
if colors:
|
||||
body.append(len(colors))
|
||||
for c in colors:
|
||||
body += bytes([0xFF, c.b, c.g, c.r])
|
||||
# Same declared lengths OpenLinkHub uses; everything past the colors is zero padding.
|
||||
declared = 93 if effect == FX_STATIC else 89
|
||||
return block_packets(target, bytes(body.ljust(LIGHTING_BLOCK_SIZE, b"\x00")), declared)
|
||||
|
||||
|
||||
def parse_u16(resp: bytes, offset: int = 3) -> int:
|
||||
return struct.unpack_from("<H", resp, offset)[0]
|
||||
|
||||
|
||||
def parse_firmware(resp: bytes) -> str:
|
||||
return f"{resp[3]}.{resp[4]}.{struct.unpack_from('<H', resp, 5)[0]}"
|
||||
@@ -0,0 +1,381 @@
|
||||
"""K65 PLUS Wireless device service.
|
||||
|
||||
A background thread owns the hidraw handles. It finds the Slipstream receiver (or a wired
|
||||
keyboard), keeps the keyboard in software mode with heartbeats, applies profiles and reports
|
||||
state changes through a callback.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import queue
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field, replace
|
||||
from typing import Callable
|
||||
|
||||
from . import bragi, effects
|
||||
from .hidraw import Hidraw, enumerate_hidraw
|
||||
from .profiles import Profile
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
HEARTBEAT_INTERVAL = 10.0
|
||||
DISCOVERY_INTERVAL = 2.0
|
||||
RECONNECT_DELAY = 3.0
|
||||
TIMEOUT = 0.5
|
||||
|
||||
|
||||
class DeviceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PermissionProblem(DeviceError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeviceState:
|
||||
receiver: bool = False # receiver (or wired keyboard) present and opened
|
||||
keyboard: bool = False # keyboard reachable
|
||||
wireless: bool = True
|
||||
battery: int | None = None # percent
|
||||
keyboard_firmware: str = ""
|
||||
receiver_firmware: str = ""
|
||||
serial: str = ""
|
||||
error: str = ""
|
||||
|
||||
|
||||
class Transport:
|
||||
def __init__(self, path: str):
|
||||
self.dev = Hidraw(path)
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def close(self) -> None:
|
||||
self.dev.close()
|
||||
|
||||
def transfer(self, pkt: bytes, timeout: float = TIMEOUT) -> bytes:
|
||||
with self.lock:
|
||||
self.dev.drain()
|
||||
self.dev.write(pkt)
|
||||
deadline = time.monotonic() + timeout
|
||||
while (left := deadline - time.monotonic()) > 0:
|
||||
resp = self.dev.read(left)
|
||||
if resp and resp[0] == pkt[0] and resp[1] == pkt[1]:
|
||||
return resp
|
||||
raise DeviceError(f"no response to {pkt[:4].hex(' ')}")
|
||||
|
||||
def command(self, pkt: bytes, timeout: float = TIMEOUT) -> bytes:
|
||||
resp = self.transfer(pkt, timeout)
|
||||
if resp[2] != 0:
|
||||
raise DeviceError(f"status {resp[2]:#04x} for {pkt[:4].hex(' ')}")
|
||||
return resp
|
||||
|
||||
|
||||
class Keyboard:
|
||||
"""Commands for the keyboard, addressed through `target` on `transport`."""
|
||||
|
||||
def __init__(self, transport: Transport, target: int):
|
||||
self.t = transport
|
||||
self.target = target
|
||||
|
||||
def heartbeat(self) -> None:
|
||||
self.t.command(bragi.packet(self.target, bragi.CMD_HEARTBEAT))
|
||||
|
||||
def set_mode(self, mode: int) -> None:
|
||||
self.t.command(bragi.set_property(self.target, bragi.PROP_MODE, bytes([mode])))
|
||||
|
||||
def battery(self) -> int:
|
||||
resp = self.t.command(bragi.get_property(self.target, bragi.PROP_BATTERY))
|
||||
return round(bragi.parse_u16(resp) / 10)
|
||||
|
||||
def firmware(self) -> str:
|
||||
return bragi.parse_firmware(self.t.command(bragi.get_property(self.target, bragi.PROP_FIRMWARE)))
|
||||
|
||||
def brightness(self, percent: int) -> None:
|
||||
value = struct.pack("<H", max(0, min(100, percent)) * 10)
|
||||
self.t.command(bragi.set_property(self.target, bragi.PROP_BRIGHTNESS, value))
|
||||
|
||||
def sleep_timer(self, minutes: int) -> None:
|
||||
value = struct.pack("<I", max(1, minutes) * 60_000)
|
||||
self.t.command(bragi.set_property(self.target, bragi.PROP_SLEEP, value))
|
||||
|
||||
def locks(self, game_mode: bool, flags: int) -> None:
|
||||
self.t.command(bragi.set_property(self.target, bragi.PROP_LOCKS, bytes([flags if game_mode else 0])))
|
||||
self.t.command(bragi.set_property(self.target, bragi.PROP_GAME_MODE, bytes([int(game_mode)])))
|
||||
|
||||
def _close_handle(self) -> None:
|
||||
self.t.transfer(bragi.packet(self.target, bragi.CMD_CLOSE, bragi.HANDLE, bragi.HANDLE))
|
||||
|
||||
def _write_block(self, open_args: bytes, packets: list[bytes], settle: float = 0.0) -> None:
|
||||
self._close_handle()
|
||||
self.t.command(bragi.packet(self.target, bragi.CMD_OPEN, bragi.HANDLE, open_args))
|
||||
if settle:
|
||||
time.sleep(settle)
|
||||
self.t.transfer(bragi.packet(self.target, bragi.CMD_PREPARE, bragi.HANDLE))
|
||||
try:
|
||||
for p in packets:
|
||||
self.t.command(p)
|
||||
finally:
|
||||
self._close_handle()
|
||||
|
||||
def lighting(self, packets: list[bytes]) -> None:
|
||||
self._write_block(struct.pack("<H", bragi.RESOURCE_LIGHTING), packets, settle=0.5)
|
||||
|
||||
def keymap(self) -> None:
|
||||
self._write_block(bytes([bragi.RESOURCE_KEYMAP]),
|
||||
bragi.block_packets(self.target, bragi.default_keymap()))
|
||||
|
||||
def apply(self, p: Profile, prev: Profile | None = None) -> None:
|
||||
"""Send `p`; with `prev` given, only the settings that differ from it."""
|
||||
def changed(*names: str) -> bool:
|
||||
return prev is None or any(getattr(p, n) != getattr(prev, n) for n in names)
|
||||
|
||||
if prev is None:
|
||||
self.set_mode(bragi.MODE_SOFTWARE)
|
||||
if changed("effect", "colors", "random_colors", "speed"):
|
||||
self.lighting(effects.encode(self.target, p.effect, p.colors, p.random_colors, p.speed))
|
||||
if changed("brightness"):
|
||||
self.brightness(p.brightness)
|
||||
if changed("sleep_minutes"):
|
||||
self.sleep_timer(p.sleep_minutes)
|
||||
if changed("game_mode", "lock_win", "lock_alt_tab", "lock_alt_f4", "lock_shift_tab"):
|
||||
flags = ((bragi.LOCK_WIN if p.lock_win else 0) | (bragi.LOCK_ALT_TAB if p.lock_alt_tab else 0)
|
||||
| (bragi.LOCK_ALT_F4 if p.lock_alt_f4 else 0)
|
||||
| (bragi.LOCK_SHIFT_TAB if p.lock_shift_tab else 0))
|
||||
self.locks(p.game_mode, flags)
|
||||
if prev is None:
|
||||
self.keymap()
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Handles:
|
||||
transport: Transport
|
||||
notify: Hidraw | None
|
||||
keyboard: Keyboard
|
||||
receiver: Keyboard | None # the receiver itself, wireless only
|
||||
paths: tuple[str, ...] = field(default_factory=tuple)
|
||||
|
||||
def close(self) -> None:
|
||||
self.transport.close()
|
||||
if self.notify:
|
||||
self.notify.close()
|
||||
|
||||
|
||||
def find_interfaces() -> tuple[str, str | None, bool] | None:
|
||||
"""Return (command hidraw, notification hidraw, wireless) for the first K65 PLUS found."""
|
||||
devs = [d for d in enumerate_hidraw(bragi.VENDOR_CORSAIR) if d.bus == 3]
|
||||
for pids, wireless in (((bragi.PID_SLIPSTREAM_K65,), True), (bragi.PIDS_K65_PLUS_WIRED, False)):
|
||||
cmd = next((d for d in devs if d.product_id in pids and d.interface == 1), None)
|
||||
if cmd:
|
||||
notify = next((d for d in devs if d.product_id == cmd.product_id and d.interface == 2), None)
|
||||
return cmd.path, notify.path if notify else None, wireless
|
||||
return None
|
||||
|
||||
|
||||
class DeviceService:
|
||||
"""Runs the device loop in a thread. `on_state` is called from that thread."""
|
||||
|
||||
def __init__(self, on_state: Callable[[DeviceState], None]):
|
||||
self.on_state = on_state
|
||||
self.state = DeviceState()
|
||||
self._profile: Profile | None = None
|
||||
self._applied: Profile | None = None # what the keyboard currently has
|
||||
self._jobs: queue.Queue[tuple[str, object]] = queue.Queue()
|
||||
self._stop = threading.Event()
|
||||
self._restore_hardware = True
|
||||
self._thread = threading.Thread(target=self._run, name="k65-device", daemon=True)
|
||||
self._h: _Handles | None = None
|
||||
self._reconnect_at: float | None = None
|
||||
|
||||
# --- public API (any thread) ---
|
||||
|
||||
def start(self, profile: Profile) -> None:
|
||||
self._profile = replace(profile, colors=list(profile.colors))
|
||||
self._thread.start()
|
||||
|
||||
def apply(self, profile: Profile) -> None:
|
||||
self._jobs.put(("apply", replace(profile, colors=list(profile.colors))))
|
||||
|
||||
def stop(self, restore_hardware: bool = True, timeout: float = 3.0) -> None:
|
||||
self._restore_hardware = restore_hardware
|
||||
self._stop.set()
|
||||
self._thread.join(timeout)
|
||||
|
||||
# --- device thread ---
|
||||
|
||||
def _set(self, **changes) -> None:
|
||||
new = replace(self.state, **changes)
|
||||
if new != self.state:
|
||||
self.state = new
|
||||
self.on_state(new)
|
||||
|
||||
def _run(self) -> None:
|
||||
next_heartbeat = 0.0
|
||||
while not self._stop.is_set():
|
||||
if self._h is None:
|
||||
if not self._open():
|
||||
self._stop.wait(DISCOVERY_INTERVAL)
|
||||
continue
|
||||
next_heartbeat = time.monotonic() + HEARTBEAT_INTERVAL
|
||||
try:
|
||||
self._process_jobs()
|
||||
self._read_notifications(0.2)
|
||||
now = time.monotonic()
|
||||
if self._reconnect_at is not None and now >= self._reconnect_at:
|
||||
self._reconnect_at = None
|
||||
self._init_keyboard()
|
||||
if now >= next_heartbeat:
|
||||
next_heartbeat = now + HEARTBEAT_INTERVAL
|
||||
self._heartbeat()
|
||||
except OSError as e:
|
||||
log.warning("device lost: %s", e)
|
||||
self._close()
|
||||
self._set(receiver=False, keyboard=False, battery=None, error="Gerät getrennt")
|
||||
self._shutdown()
|
||||
|
||||
def _open(self) -> bool:
|
||||
found = find_interfaces()
|
||||
if not found:
|
||||
self._set(receiver=False, keyboard=False, error="Kein K65 PLUS gefunden")
|
||||
return False
|
||||
cmd_path, notify_path, wireless = found
|
||||
try:
|
||||
transport = Transport(cmd_path)
|
||||
notify = Hidraw(notify_path) if notify_path else None
|
||||
except PermissionError:
|
||||
self._set(receiver=False, keyboard=False,
|
||||
error=f"Keine Berechtigung für {cmd_path}. udev-Regel installieren (siehe README).")
|
||||
return False
|
||||
except OSError as e:
|
||||
self._set(receiver=False, keyboard=False, error=str(e))
|
||||
return False
|
||||
target = bragi.TARGET_PAIRED if wireless else bragi.TARGET_LOCAL
|
||||
receiver = Keyboard(transport, bragi.TARGET_LOCAL) if wireless else None
|
||||
self._h = _Handles(transport, notify, Keyboard(transport, target), receiver)
|
||||
self._set(receiver=True, wireless=wireless, error="")
|
||||
if receiver:
|
||||
try:
|
||||
self._set(receiver_firmware=receiver.firmware(), serial=self._paired_serial())
|
||||
receiver.set_mode(bragi.MODE_SOFTWARE)
|
||||
except DeviceError as e:
|
||||
log.warning("receiver init: %s", e)
|
||||
self._init_keyboard()
|
||||
return True
|
||||
|
||||
def _paired_serial(self) -> str:
|
||||
"""Read the receiver's pairing list and return the keyboard serial."""
|
||||
t = self._h.transport
|
||||
res = struct.pack("<B", bragi.CMD_DEVICE_LIST)
|
||||
t.transfer(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_CLOSE, bragi.HANDLE, res))
|
||||
t.command(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_OPEN, 0x00, res))
|
||||
t.transfer(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_PREPARE, 0x00, res))
|
||||
buf = t.command(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_READ, 0x00, res))
|
||||
t.transfer(bragi.packet(bragi.TARGET_LOCAL, bragi.CMD_CLOSE, bragi.HANDLE))
|
||||
if buf[5] == 0:
|
||||
return ""
|
||||
return buf[11:11 + buf[10]].decode("ascii", "replace")
|
||||
|
||||
def _init_keyboard(self) -> None:
|
||||
kb = self._h.keyboard
|
||||
try:
|
||||
kb.heartbeat()
|
||||
except DeviceError:
|
||||
self._set(keyboard=False, battery=None)
|
||||
return
|
||||
try:
|
||||
kb.set_mode(bragi.MODE_SOFTWARE)
|
||||
self._set(keyboard=True, keyboard_firmware=kb.firmware(), battery=self._battery(kb))
|
||||
self._applied = None
|
||||
if self._profile:
|
||||
kb.apply(self._profile)
|
||||
self._applied = self._profile
|
||||
self._set(error="")
|
||||
except DeviceError as e:
|
||||
log.warning("keyboard init: %s", e)
|
||||
self._set(error=f"Initialisierung fehlgeschlagen: {e}")
|
||||
|
||||
def _battery(self, kb: Keyboard) -> int | None:
|
||||
if not self.state.wireless:
|
||||
return None
|
||||
try:
|
||||
return kb.battery()
|
||||
except DeviceError:
|
||||
return self.state.battery
|
||||
|
||||
def _heartbeat(self) -> None:
|
||||
if self._h.receiver:
|
||||
try:
|
||||
self._h.receiver.heartbeat()
|
||||
except DeviceError as e:
|
||||
log.debug("receiver heartbeat: %s", e)
|
||||
try:
|
||||
self._h.keyboard.heartbeat()
|
||||
except DeviceError:
|
||||
self._set(keyboard=False, battery=None)
|
||||
return
|
||||
if not self.state.keyboard:
|
||||
self._init_keyboard()
|
||||
else:
|
||||
self._set(battery=self._battery(self._h.keyboard))
|
||||
|
||||
def _process_jobs(self) -> None:
|
||||
latest = None
|
||||
while True:
|
||||
try:
|
||||
job, arg = self._jobs.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
if job == "apply":
|
||||
latest = arg
|
||||
if latest is None:
|
||||
return
|
||||
self._profile = latest
|
||||
if self.state.keyboard:
|
||||
try:
|
||||
self._h.keyboard.apply(latest, self._applied)
|
||||
self._applied = latest
|
||||
self._set(error="")
|
||||
except DeviceError as e:
|
||||
self._applied = None
|
||||
self._set(error=f"Profil konnte nicht angewendet werden: {e}")
|
||||
|
||||
def _read_notifications(self, timeout: float) -> None:
|
||||
notify = self._h.notify
|
||||
if notify is None:
|
||||
time.sleep(timeout)
|
||||
return
|
||||
data = notify.read(timeout)
|
||||
while data:
|
||||
self._handle_notification(data)
|
||||
data = notify.read(0)
|
||||
|
||||
def _handle_notification(self, data: bytes) -> None:
|
||||
if len(data) < 6:
|
||||
return
|
||||
if data[1] == 0x01 and data[2] == bragi.NOTIFY_CONNECTION:
|
||||
if data[4] == 0x02:
|
||||
self._reconnect_at = time.monotonic() + RECONNECT_DELAY
|
||||
elif data[4] == 0x00:
|
||||
self._set(keyboard=False, battery=None)
|
||||
elif data[2] == bragi.PROP_BATTERY:
|
||||
level = round(bragi.parse_u16(data, 4) / 10)
|
||||
if level > 0:
|
||||
self._set(battery=level)
|
||||
|
||||
def _close(self) -> None:
|
||||
if self._h:
|
||||
self._h.close()
|
||||
self._h = None
|
||||
|
||||
def _shutdown(self) -> None:
|
||||
if self._h and self._restore_hardware:
|
||||
for dev in (self._h.keyboard, self._h.receiver):
|
||||
if dev is None:
|
||||
continue
|
||||
try:
|
||||
dev.set_mode(bragi.MODE_HARDWARE)
|
||||
except (DeviceError, OSError) as e:
|
||||
log.debug("hardware mode: %s", e)
|
||||
self._close()
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Catalog of the hardware lighting effects the K65 PLUS renders on its own."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from . import bragi
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Effect:
|
||||
key: str
|
||||
label: str
|
||||
fx: int
|
||||
max_colors: int = 0 # how many user colors the effect takes
|
||||
random_colors: bool = False # supports "random colors" instead of user colors
|
||||
speed: bool = True
|
||||
direction: int = 0
|
||||
fixed_color_mode: int | None = None
|
||||
fixed_colors: tuple[bragi.Rgb, ...] = ()
|
||||
|
||||
|
||||
SPEEDS = {"slow": bragi.SPEED_SLOW, "medium": bragi.SPEED_MEDIUM, "fast": bragi.SPEED_FAST}
|
||||
SPEED_LABELS = {"slow": "Langsam", "medium": "Mittel", "fast": "Schnell"}
|
||||
|
||||
_WHITE = bragi.Rgb(255, 255, 255)
|
||||
_BLACK = bragi.Rgb(0, 0, 0)
|
||||
|
||||
EFFECTS: dict[str, Effect] = {e.key: e for e in (
|
||||
Effect("static", "Statische Farbe", bragi.FX_STATIC, max_colors=1, speed=False),
|
||||
Effect("rainbow_wave", "Regenbogenwelle", bragi.FX_RAINBOW_WAVE, direction=0x04),
|
||||
Effect("spiral_rainbow", "Spiralregenbogen", bragi.FX_SPIRAL_RAINBOW, direction=0x06),
|
||||
Effect("color_wave", "Farbwelle", bragi.FX_COLOR_WAVE, max_colors=2, random_colors=True, direction=0x04),
|
||||
Effect("color_shift", "Farbwechsel", bragi.FX_COLOR_SHIFT, max_colors=2, random_colors=True),
|
||||
Effect("color_pulse", "Farbpuls", bragi.FX_COLOR_PULSE, max_colors=2, random_colors=True),
|
||||
Effect("rain", "Regen", bragi.FX_RAIN, max_colors=2, random_colors=True, direction=0x01),
|
||||
Effect("watercolor", "Aquarell", bragi.FX_WATERCOLOR,
|
||||
fixed_color_mode=bragi.COLORS_ALT, fixed_colors=(_WHITE,)),
|
||||
Effect("type_key", "Tippen: Taste", bragi.FX_TYPE_KEY, max_colors=2, random_colors=True),
|
||||
Effect("type_ripple", "Tippen: Welle", bragi.FX_TYPE_RIPPLE, max_colors=2, random_colors=True),
|
||||
Effect("visor", "Visier", bragi.FX_VISOR, max_colors=2, random_colors=True),
|
||||
Effect("off", "Aus", bragi.FX_STATIC, speed=False,
|
||||
fixed_color_mode=bragi.COLORS_SPECIFIC, fixed_colors=(_BLACK,)),
|
||||
)}
|
||||
|
||||
|
||||
def encode(target: int, effect_key: str, colors: list[str], random: bool, speed: str) -> list[bytes]:
|
||||
effect = EFFECTS.get(effect_key, EFFECTS["static"])
|
||||
if effect.fixed_color_mode is not None:
|
||||
mode, rgb = effect.fixed_color_mode, list(effect.fixed_colors)
|
||||
elif effect.max_colors and not (random and effect.random_colors):
|
||||
mode = bragi.COLORS_SPECIFIC
|
||||
rgb = [bragi.Rgb.from_hex(c) for c in colors[:effect.max_colors]] or [_WHITE]
|
||||
elif effect.random_colors:
|
||||
mode, rgb = bragi.COLORS_RANDOM, []
|
||||
else:
|
||||
mode, rgb = bragi.COLORS_NONE, []
|
||||
return bragi.lighting_packets(
|
||||
target, effect.fx, mode,
|
||||
SPEEDS.get(speed, bragi.SPEED_MEDIUM) if effect.speed else 0,
|
||||
effect.direction, rgb,
|
||||
)
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Minimal hidraw transport and device discovery (Linux only, no external deps)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import select
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
REPORT_SIZE = 64
|
||||
SYSFS_HIDRAW = Path("/sys/class/hidraw")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HidrawInfo:
|
||||
path: str # /dev/hidrawN
|
||||
vendor_id: int
|
||||
product_id: int
|
||||
interface: int # USB bInterfaceNumber, -1 if unknown (e.g. Bluetooth)
|
||||
name: str
|
||||
bus: int # 3 = USB, 5 = Bluetooth
|
||||
|
||||
|
||||
def enumerate_hidraw(vendor_id: int | None = None) -> list[HidrawInfo]:
|
||||
devices: list[HidrawInfo] = []
|
||||
if not SYSFS_HIDRAW.exists():
|
||||
return devices
|
||||
for entry in sorted(SYSFS_HIDRAW.iterdir()):
|
||||
try:
|
||||
uevent = (entry / "device" / "uevent").read_text()
|
||||
except OSError:
|
||||
continue
|
||||
fields = dict(line.split("=", 1) for line in uevent.splitlines() if "=" in line)
|
||||
hid_id = fields.get("HID_ID", "")
|
||||
m = re.fullmatch(r"([0-9A-Fa-f]+):([0-9A-Fa-f]+):([0-9A-Fa-f]+)", hid_id)
|
||||
if not m:
|
||||
continue
|
||||
bus, vid, pid = (int(x, 16) for x in m.groups())
|
||||
if vendor_id is not None and vid != vendor_id:
|
||||
continue
|
||||
# .../1-2:1.1/0003:1B1C:2B07.0002 -> interface 1
|
||||
real = os.path.realpath(entry / "device")
|
||||
im = re.search(r":\d+\.(\d+)/[^/]+$", real)
|
||||
devices.append(HidrawInfo(
|
||||
path=f"/dev/{entry.name}",
|
||||
vendor_id=vid,
|
||||
product_id=pid,
|
||||
interface=int(im.group(1)) if im else -1,
|
||||
name=fields.get("HID_NAME", ""),
|
||||
bus=bus,
|
||||
))
|
||||
return devices
|
||||
|
||||
|
||||
class Hidraw:
|
||||
"""A raw HID device without numbered reports (report id byte 0 is stripped by the kernel)."""
|
||||
|
||||
def __init__(self, path: str):
|
||||
self.path = path
|
||||
self.fd = os.open(path, os.O_RDWR | os.O_NONBLOCK)
|
||||
|
||||
def close(self) -> None:
|
||||
if self.fd >= 0:
|
||||
os.close(self.fd)
|
||||
self.fd = -1
|
||||
|
||||
def write(self, data: bytes) -> None:
|
||||
if len(data) > REPORT_SIZE:
|
||||
raise ValueError(f"report too long: {len(data)} > {REPORT_SIZE}")
|
||||
os.write(self.fd, b"\x00" + data.ljust(REPORT_SIZE, b"\x00"))
|
||||
|
||||
def read(self, timeout: float) -> bytes | None:
|
||||
ready, _, _ = select.select([self.fd], [], [], timeout)
|
||||
if not ready:
|
||||
return None
|
||||
try:
|
||||
return os.read(self.fd, REPORT_SIZE)
|
||||
except BlockingIOError:
|
||||
return None
|
||||
|
||||
def drain(self) -> None:
|
||||
while self.read(0) is not None:
|
||||
pass
|
||||
|
||||
def __enter__(self) -> "Hidraw":
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc) -> None:
|
||||
self.close()
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Key geometry of the K65 PLUS (75 %, ISO-DE) in key units."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Key:
|
||||
label: str
|
||||
x: float
|
||||
y: float
|
||||
w: float = 1.0
|
||||
h: float = 1.0
|
||||
iso_enter: bool = False
|
||||
|
||||
@property
|
||||
def cx(self) -> float:
|
||||
return self.x + self.w / 2
|
||||
|
||||
@property
|
||||
def cy(self) -> float:
|
||||
return self.y + self.h / 2
|
||||
|
||||
|
||||
def _row(y: float, x: float, keys: list[tuple[str, float] | str]) -> list[Key]:
|
||||
out = []
|
||||
for k in keys:
|
||||
label, w = (k, 1.0) if isinstance(k, str) else k
|
||||
out.append(Key(label, x, y, w))
|
||||
x += w
|
||||
return out
|
||||
|
||||
|
||||
def _build() -> list[Key]:
|
||||
keys = [Key("Esc", 0, 0)]
|
||||
for group, start in ((("F1", "F2", "F3", "F4"), 1.25), (("F5", "F6", "F7", "F8"), 5.5),
|
||||
(("F9", "F10", "F11", "F12"), 9.75)):
|
||||
keys += _row(0, start, list(group))
|
||||
keys.append(Key("Entf", 15, 0))
|
||||
keys += _row(1.25, 0, ["^", *"1234567890", "ß", "´", ("⌫", 2.0), "Pos1"])
|
||||
keys += _row(2.25, 0, [("Tab", 1.5), *"QWERTZUIOP", "Ü", "+"])
|
||||
keys.append(Key("↵", 13.5, 2.25, 1.5, 2.0, iso_enter=True))
|
||||
keys.append(Key("Bild↑", 15, 2.25))
|
||||
keys += _row(3.25, 0, [("Caps", 1.75), *"ASDFGHJKL", "Ö", "Ä", "#"])
|
||||
keys.append(Key("Bild↓", 15, 3.25))
|
||||
keys += _row(4.25, 0, [("⇧", 1.25), "<", *"YXCVBNM", ",", ".", "-", ("⇧", 1.75), "↑"])
|
||||
keys += _row(5.25, 0, [("Strg", 1.25), ("Win", 1.25), ("Alt", 1.25), ("", 6.25),
|
||||
"AltGr", "Fn", "Strg", "←", "↓", "→"])
|
||||
return keys
|
||||
|
||||
|
||||
KEYS: list[Key] = _build()
|
||||
WIDTH = 16.0
|
||||
HEIGHT = 6.25
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Profiles and app settings, stored as JSON in ~/.config/k65studio/config.json."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "k65studio"
|
||||
CONFIG_FILE = CONFIG_DIR / "config.json"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Profile:
|
||||
effect: str = "static"
|
||||
colors: list[str] = field(default_factory=lambda: ["#00e5ff", "#ff2d95"])
|
||||
random_colors: bool = False
|
||||
speed: str = "medium"
|
||||
brightness: int = 100 # percent
|
||||
sleep_minutes: int = 15
|
||||
game_mode: bool = False
|
||||
lock_win: bool = True
|
||||
lock_alt_tab: bool = False
|
||||
lock_alt_f4: bool = False
|
||||
lock_shift_tab: bool = False
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict) -> "Profile":
|
||||
known = {k: v for k, v in data.items() if k in cls.__dataclass_fields__}
|
||||
return cls(**known)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Config:
|
||||
active: str = "Standard"
|
||||
profiles: dict[str, Profile] = field(default_factory=lambda: {"Standard": Profile()})
|
||||
start_minimized: bool = False
|
||||
restore_hardware_on_exit: bool = True
|
||||
|
||||
@property
|
||||
def profile(self) -> Profile:
|
||||
if self.active not in self.profiles:
|
||||
self.active = next(iter(self.profiles))
|
||||
return self.profiles[self.active]
|
||||
|
||||
@classmethod
|
||||
def load(cls) -> "Config":
|
||||
try:
|
||||
data = json.loads(CONFIG_FILE.read_text())
|
||||
except (OSError, ValueError):
|
||||
return cls()
|
||||
profiles = {name: Profile.from_dict(p) for name, p in data.get("profiles", {}).items()}
|
||||
return cls(
|
||||
active=data.get("active", "Standard"),
|
||||
profiles=profiles or {"Standard": Profile()},
|
||||
start_minimized=data.get("start_minimized", False),
|
||||
restore_hardware_on_exit=data.get("restore_hardware_on_exit", True),
|
||||
)
|
||||
|
||||
def save(self) -> None:
|
||||
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
tmp = CONFIG_FILE.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(asdict(self), indent=2, ensure_ascii=False))
|
||||
tmp.replace(CONFIG_FILE)
|
||||
Whitespace-only changes.
@@ -0,0 +1,450 @@
|
||||
"""Main window: device view on top, settings pages below (iCUE-style)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
|
||||
from PySide6.QtCore import Qt, QTimer, Signal
|
||||
from PySide6.QtGui import QColor
|
||||
from PySide6.QtWidgets import (
|
||||
QButtonGroup, QCheckBox, QColorDialog, QComboBox, QFrame, QGridLayout, QHBoxLayout,
|
||||
QInputDialog, QLabel, QListWidget, QListWidgetItem, QMainWindow, QMessageBox,
|
||||
QProgressBar, QPushButton, QSlider, QSpinBox, QStackedWidget, QVBoxLayout, QWidget,
|
||||
)
|
||||
|
||||
from .. import autostart
|
||||
from ..device import DeviceState
|
||||
from ..effects import EFFECTS, SPEED_LABELS
|
||||
from ..profiles import Config, Profile
|
||||
from .preview import KeyboardPreview
|
||||
|
||||
PRESETS = ["#ff0000", "#ff7a00", "#ffd400", "#3bff3b", "#19d3c5", "#0077ff", "#7a2cff", "#ff2d95", "#ffffff"]
|
||||
|
||||
|
||||
def _card() -> tuple[QFrame, QVBoxLayout]:
|
||||
frame = QFrame(objectName="card")
|
||||
lay = QVBoxLayout(frame)
|
||||
lay.setContentsMargins(18, 16, 18, 16)
|
||||
lay.setSpacing(10)
|
||||
return frame, lay
|
||||
|
||||
|
||||
def _label(text: str, name: str = "") -> QLabel:
|
||||
lbl = QLabel(text)
|
||||
if name:
|
||||
lbl.setObjectName(name)
|
||||
lbl.setWordWrap(True)
|
||||
return lbl
|
||||
|
||||
|
||||
class MainWindow(QMainWindow):
|
||||
profile_changed = Signal(object) # Profile to send to the keyboard
|
||||
reinit_requested = Signal()
|
||||
|
||||
def __init__(self, config: Config):
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.state = DeviceState()
|
||||
self._loading = False
|
||||
self._save_timer = QTimer(self, singleShot=True, interval=600, timeout=self.config.save)
|
||||
|
||||
self.setWindowTitle("K65 Studio")
|
||||
self.resize(1240, 900)
|
||||
|
||||
root = QWidget()
|
||||
outer = QVBoxLayout(root)
|
||||
outer.setContentsMargins(0, 0, 0, 0)
|
||||
outer.setSpacing(0)
|
||||
outer.addWidget(self._build_header())
|
||||
|
||||
body = QHBoxLayout()
|
||||
body.setContentsMargins(16, 16, 16, 16)
|
||||
body.setSpacing(16)
|
||||
self.nav = QListWidget(objectName="nav")
|
||||
self.nav.setFixedWidth(200)
|
||||
for name in ("Beleuchtung", "Leistung", "Einstellungen", "Geräteinfo"):
|
||||
self.nav.addItem(name)
|
||||
body.addWidget(self.nav)
|
||||
|
||||
right = QVBoxLayout()
|
||||
right.setSpacing(16)
|
||||
preview_card, preview_lay = _card()
|
||||
self.preview = KeyboardPreview()
|
||||
preview_lay.addWidget(self.preview, 1)
|
||||
preview_lay.addWidget(_label("Vorschau (simuliert). Die Tastatur berechnet den Effekt selbst.", "hint"))
|
||||
right.addWidget(preview_card, 4)
|
||||
|
||||
self.pages = QStackedWidget()
|
||||
self.pages.addWidget(self._build_lighting())
|
||||
self.pages.addWidget(self._build_performance())
|
||||
self.pages.addWidget(self._build_settings())
|
||||
self.pages.addWidget(self._build_info())
|
||||
right.addWidget(self.pages, 5)
|
||||
body.addLayout(right, 1)
|
||||
outer.addLayout(body, 1)
|
||||
self.setCentralWidget(root)
|
||||
|
||||
self.nav.currentRowChanged.connect(self.pages.setCurrentIndex)
|
||||
self.nav.setCurrentRow(0)
|
||||
self._reload_profiles()
|
||||
self.set_state(self.state)
|
||||
|
||||
# ---------- header ----------
|
||||
|
||||
def _build_header(self) -> QFrame:
|
||||
header = QFrame(objectName="header")
|
||||
lay = QHBoxLayout(header)
|
||||
lay.setContentsMargins(20, 12, 20, 12)
|
||||
lay.setSpacing(10)
|
||||
lay.addWidget(_label("K65 STUDIO", "title"))
|
||||
lay.addSpacing(24)
|
||||
lay.addWidget(_label("Profil", "muted"))
|
||||
self.profile_box = QComboBox()
|
||||
self.profile_box.setMinimumWidth(180)
|
||||
self.profile_box.currentTextChanged.connect(self._select_profile)
|
||||
lay.addWidget(self.profile_box)
|
||||
for text, slot in (("Neu", self._new_profile), ("Umbenennen", self._rename_profile),
|
||||
("Löschen", self._delete_profile)):
|
||||
b = QPushButton(text)
|
||||
b.clicked.connect(slot)
|
||||
lay.addWidget(b)
|
||||
lay.addStretch(1)
|
||||
self.conn_chip = QLabel(objectName="chip")
|
||||
self.battery_chip = QLabel(objectName="chip")
|
||||
lay.addWidget(self.conn_chip)
|
||||
lay.addWidget(self.battery_chip)
|
||||
return header
|
||||
|
||||
# ---------- pages ----------
|
||||
|
||||
def _build_lighting(self) -> QWidget:
|
||||
page = QWidget()
|
||||
lay = QHBoxLayout(page)
|
||||
lay.setContentsMargins(0, 0, 0, 0)
|
||||
lay.setSpacing(16)
|
||||
|
||||
fx_card, fx_lay = _card()
|
||||
fx_lay.addWidget(_label("Effekt", "section"))
|
||||
self.effect_list = QListWidget()
|
||||
for key, effect in EFFECTS.items():
|
||||
item = QListWidgetItem(effect.label)
|
||||
item.setData(Qt.UserRole, key)
|
||||
self.effect_list.addItem(item)
|
||||
self.effect_list.currentItemChanged.connect(self._effect_selected)
|
||||
fx_lay.addWidget(self.effect_list)
|
||||
fx_card.setFixedWidth(260)
|
||||
lay.addWidget(fx_card)
|
||||
|
||||
opt_card, opt = _card()
|
||||
opt.addWidget(_label("Farben", "section"))
|
||||
colors = QHBoxLayout()
|
||||
self.color_buttons = []
|
||||
for i in range(2):
|
||||
b = QPushButton(objectName="color")
|
||||
b.clicked.connect(lambda _=False, i=i: self._pick_color(i))
|
||||
colors.addWidget(b)
|
||||
self.color_buttons.append(b)
|
||||
self.random_box = QCheckBox("Zufällige Farben")
|
||||
self.random_box.toggled.connect(lambda v: self._update(random_colors=v))
|
||||
colors.addSpacing(12)
|
||||
colors.addWidget(self.random_box)
|
||||
colors.addStretch(1)
|
||||
opt.addLayout(colors)
|
||||
|
||||
swatches = QHBoxLayout()
|
||||
swatches.setSpacing(6)
|
||||
swatches.addWidget(_label("Schnellwahl:", "muted"))
|
||||
for c in PRESETS:
|
||||
s = QPushButton(objectName="swatch")
|
||||
s.setStyleSheet(f"background: {c}; border: 2px solid #2c313a;")
|
||||
s.setToolTip(c)
|
||||
s.clicked.connect(lambda _=False, c=c: self._set_color(0, c))
|
||||
swatches.addWidget(s)
|
||||
swatches.addStretch(1)
|
||||
opt.addLayout(swatches)
|
||||
self.colors_hint = _label("", "hint")
|
||||
opt.addWidget(self.colors_hint)
|
||||
|
||||
opt.addWidget(_label("Geschwindigkeit", "section"))
|
||||
speeds = QHBoxLayout()
|
||||
self.speed_group = QButtonGroup(self)
|
||||
for key, text in SPEED_LABELS.items():
|
||||
b = QPushButton(text, checkable=True)
|
||||
b.setProperty("speed", key)
|
||||
self.speed_group.addButton(b)
|
||||
speeds.addWidget(b)
|
||||
speeds.addStretch(1)
|
||||
self.speed_group.buttonClicked.connect(lambda b: self._update(speed=b.property("speed")))
|
||||
opt.addLayout(speeds)
|
||||
|
||||
opt.addWidget(_label("Helligkeit", "section"))
|
||||
bright = QHBoxLayout()
|
||||
self.brightness = QSlider(Qt.Horizontal, minimum=0, maximum=100, singleStep=5, pageStep=10)
|
||||
self.brightness_value = _label("", "muted")
|
||||
self.brightness_value.setFixedWidth(48)
|
||||
self.brightness.valueChanged.connect(self._brightness_changed)
|
||||
bright.addWidget(self.brightness, 1)
|
||||
bright.addWidget(self.brightness_value)
|
||||
opt.addLayout(bright)
|
||||
opt.addStretch(1)
|
||||
lay.addWidget(opt_card, 1)
|
||||
return page
|
||||
|
||||
def _build_performance(self) -> QWidget:
|
||||
card, lay = _card()
|
||||
lay.addWidget(_label("Spielmodus", "section"))
|
||||
lay.addWidget(_label("Wenn der Spielmodus aktiv ist, sperrt die Tastatur die ausgewählten "
|
||||
"Tasten und Kombinationen, damit sie im Spiel nicht versehentlich auslösen.", "muted"))
|
||||
self.game_mode = QCheckBox("Spielmodus aktivieren")
|
||||
self.game_mode.toggled.connect(self._game_mode_changed)
|
||||
lay.addWidget(self.game_mode)
|
||||
self.locks = {
|
||||
"lock_win": QCheckBox("Windows-/Super-Taste sperren"),
|
||||
"lock_alt_tab": QCheckBox("Alt + Tab sperren"),
|
||||
"lock_alt_f4": QCheckBox("Alt + F4 sperren"),
|
||||
"lock_shift_tab": QCheckBox("Shift + Tab sperren"),
|
||||
}
|
||||
for name, box in self.locks.items():
|
||||
box.toggled.connect(lambda v, name=name: self._update(**{name: v}))
|
||||
box.setContentsMargins(24, 0, 0, 0)
|
||||
lay.addWidget(box)
|
||||
lay.addStretch(1)
|
||||
return card
|
||||
|
||||
def _build_settings(self) -> QWidget:
|
||||
card, lay = _card()
|
||||
lay.addWidget(_label("Energie", "section"))
|
||||
row = QHBoxLayout()
|
||||
row.addWidget(QLabel("Ruhezustand nach"))
|
||||
self.sleep = QSpinBox(minimum=1, maximum=120, suffix=" min")
|
||||
self.sleep.valueChanged.connect(lambda v: self._update(sleep_minutes=v))
|
||||
row.addWidget(self.sleep)
|
||||
row.addWidget(QLabel("ohne Eingabe (gilt im Funkbetrieb)", objectName="muted"))
|
||||
row.addStretch(1)
|
||||
lay.addLayout(row)
|
||||
|
||||
lay.addWidget(_label("Programm", "section"))
|
||||
self.autostart = QCheckBox("Beim Anmelden automatisch starten (im Tray)")
|
||||
self.autostart.setChecked(autostart.is_enabled())
|
||||
self.autostart.toggled.connect(autostart.set_enabled)
|
||||
lay.addWidget(self.autostart)
|
||||
self.start_min = QCheckBox("Minimiert starten")
|
||||
self.start_min.setChecked(self.config.start_minimized)
|
||||
self.start_min.toggled.connect(lambda v: self._set_config(start_minimized=v))
|
||||
lay.addWidget(self.start_min)
|
||||
self.restore_hw = QCheckBox("Beim Beenden an die Tastatur zurückgeben (Hardware-Beleuchtung)")
|
||||
self.restore_hw.setChecked(self.config.restore_hardware_on_exit)
|
||||
self.restore_hw.toggled.connect(lambda v: self._set_config(restore_hardware_on_exit=v))
|
||||
lay.addWidget(self.restore_hw)
|
||||
|
||||
reinit = QPushButton("Tastatur neu initialisieren")
|
||||
reinit.clicked.connect(self.reinit_requested)
|
||||
row = QHBoxLayout()
|
||||
row.addWidget(reinit)
|
||||
row.addStretch(1)
|
||||
lay.addSpacing(8)
|
||||
lay.addLayout(row)
|
||||
lay.addStretch(1)
|
||||
return card
|
||||
|
||||
def _build_info(self) -> QWidget:
|
||||
card, lay = _card()
|
||||
lay.addWidget(_label("CORSAIR K65 PLUS WIRELESS", "section"))
|
||||
grid = QGridLayout()
|
||||
grid.setHorizontalSpacing(24)
|
||||
grid.setVerticalSpacing(8)
|
||||
self.info = {}
|
||||
for i, (key, text) in enumerate((("conn", "Verbindung"), ("serial", "Seriennummer"),
|
||||
("kb_fw", "Firmware Tastatur"), ("rx_fw", "Firmware Empfänger"),
|
||||
("battery", "Akku"))):
|
||||
grid.addWidget(_label(text, "muted"), i, 0)
|
||||
value = QLabel("–")
|
||||
value.setTextInteractionFlags(Qt.TextSelectableByMouse)
|
||||
grid.addWidget(value, i, 1)
|
||||
self.info[key] = value
|
||||
self.battery_bar = QProgressBar(maximum=100, textVisible=False)
|
||||
self.battery_bar.setFixedWidth(220)
|
||||
grid.addWidget(self.battery_bar, 5, 1)
|
||||
grid.setColumnStretch(2, 1)
|
||||
lay.addLayout(grid)
|
||||
self.error_label = _label("", "hint")
|
||||
lay.addWidget(self.error_label)
|
||||
lay.addStretch(1)
|
||||
return card
|
||||
|
||||
# ---------- profile handling ----------
|
||||
|
||||
@property
|
||||
def profile(self) -> Profile:
|
||||
return self.config.profile
|
||||
|
||||
def _reload_profiles(self) -> None:
|
||||
self._loading = True
|
||||
self.profile_box.clear()
|
||||
self.profile_box.addItems(list(self.config.profiles))
|
||||
self.profile_box.setCurrentText(self.config.active)
|
||||
self._loading = False
|
||||
self._load_profile_into_ui()
|
||||
|
||||
def _load_profile_into_ui(self) -> None:
|
||||
p = self.profile
|
||||
self._loading = True
|
||||
for i in range(self.effect_list.count()):
|
||||
if self.effect_list.item(i).data(Qt.UserRole) == p.effect:
|
||||
self.effect_list.setCurrentRow(i)
|
||||
self.random_box.setChecked(p.random_colors)
|
||||
for b in self.speed_group.buttons():
|
||||
b.setChecked(b.property("speed") == p.speed)
|
||||
self.brightness.setValue(p.brightness)
|
||||
self.brightness_value.setText(f"{p.brightness} %")
|
||||
self.game_mode.setChecked(p.game_mode)
|
||||
for name, box in self.locks.items():
|
||||
box.setChecked(getattr(p, name))
|
||||
self.sleep.setValue(p.sleep_minutes)
|
||||
self._loading = False
|
||||
self._refresh_controls()
|
||||
self.preview.set_profile(p)
|
||||
|
||||
def _refresh_controls(self) -> None:
|
||||
p = self.profile
|
||||
effect = EFFECTS.get(p.effect, EFFECTS["static"])
|
||||
for i, b in enumerate(self.color_buttons):
|
||||
c = p.colors[i] if i < len(p.colors) else "#ffffff"
|
||||
fg = "#000" if QColor(c).lightness() > 140 else "#fff"
|
||||
b.setStyleSheet(f"background: {c}; color: {fg}; border: 1px solid #3a404a;")
|
||||
b.setText(c.upper())
|
||||
b.setVisible(i < effect.max_colors)
|
||||
b.setEnabled(not (p.random_colors and effect.random_colors))
|
||||
self.random_box.setVisible(effect.random_colors)
|
||||
if effect.max_colors == 0:
|
||||
hints = {"off": "Beleuchtung ist ausgeschaltet.",
|
||||
"watercolor": "Dieser Effekt verwendet feste Farben."}
|
||||
self.colors_hint.setText(hints.get(p.effect, "Dieser Effekt verwendet den Regenbogen."))
|
||||
elif effect.max_colors == 2:
|
||||
self.colors_hint.setText("Zwei Farben, zwischen denen der Effekt wechselt.")
|
||||
else:
|
||||
self.colors_hint.setText("")
|
||||
for b in self.speed_group.buttons():
|
||||
b.setEnabled(effect.speed)
|
||||
for box in self.locks.values():
|
||||
box.setEnabled(p.game_mode)
|
||||
|
||||
def _update(self, **changes) -> None:
|
||||
if self._loading:
|
||||
return
|
||||
self.config.profiles[self.config.active] = replace(self.profile, **changes)
|
||||
self._refresh_controls()
|
||||
self.preview.set_profile(self.profile)
|
||||
self.profile_changed.emit(self.profile)
|
||||
self._save_timer.start()
|
||||
|
||||
def _set_config(self, **changes) -> None:
|
||||
for k, v in changes.items():
|
||||
setattr(self.config, k, v)
|
||||
self._save_timer.start()
|
||||
|
||||
def _select_profile(self, name: str) -> None:
|
||||
if self._loading or not name or name == self.config.active:
|
||||
return
|
||||
self.activate_profile(name)
|
||||
|
||||
def activate_profile(self, name: str) -> None:
|
||||
if name not in self.config.profiles:
|
||||
return
|
||||
self.config.active = name
|
||||
self.config.save()
|
||||
self._reload_profiles()
|
||||
self.profile_changed.emit(self.profile)
|
||||
|
||||
def _ask_name(self, title: str, default: str) -> str | None:
|
||||
name, ok = QInputDialog.getText(self, title, "Name:", text=default)
|
||||
name = name.strip()
|
||||
if not ok or not name:
|
||||
return None
|
||||
if name in self.config.profiles:
|
||||
QMessageBox.warning(self, title, f"Ein Profil „{name}“ gibt es schon.")
|
||||
return None
|
||||
return name
|
||||
|
||||
def _new_profile(self) -> None:
|
||||
name = self._ask_name("Neues Profil", f"Profil {len(self.config.profiles) + 1}")
|
||||
if name:
|
||||
self.config.profiles[name] = replace(self.profile, colors=list(self.profile.colors))
|
||||
self.activate_profile(name)
|
||||
|
||||
def _rename_profile(self) -> None:
|
||||
old = self.config.active
|
||||
name = self._ask_name("Profil umbenennen", old)
|
||||
if name:
|
||||
self.config.profiles = {(name if k == old else k): v for k, v in self.config.profiles.items()}
|
||||
self.config.active = name
|
||||
self.config.save()
|
||||
self._reload_profiles()
|
||||
|
||||
def _delete_profile(self) -> None:
|
||||
if len(self.config.profiles) <= 1:
|
||||
QMessageBox.information(self, "Profil löschen", "Das letzte Profil kann nicht gelöscht werden.")
|
||||
return
|
||||
name = self.config.active
|
||||
if QMessageBox.question(self, "Profil löschen", f"Profil „{name}“ löschen?") != QMessageBox.Yes:
|
||||
return
|
||||
del self.config.profiles[name]
|
||||
self.activate_profile(next(iter(self.config.profiles)))
|
||||
|
||||
# ---------- control callbacks ----------
|
||||
|
||||
def _effect_selected(self, item: QListWidgetItem | None, _prev=None) -> None:
|
||||
if item is not None:
|
||||
self._update(effect=item.data(Qt.UserRole))
|
||||
|
||||
def _set_color(self, index: int, color: str) -> None:
|
||||
colors = list(self.profile.colors) + ["#ffffff"] * (2 - len(self.profile.colors))
|
||||
colors[index] = color
|
||||
self._update(colors=colors, random_colors=False)
|
||||
self.random_box.blockSignals(True)
|
||||
self.random_box.setChecked(False)
|
||||
self.random_box.blockSignals(False)
|
||||
|
||||
def _pick_color(self, index: int) -> None:
|
||||
current = QColor(self.profile.colors[index] if index < len(self.profile.colors) else "#ffffff")
|
||||
color = QColorDialog.getColor(current, self, "Farbe wählen")
|
||||
if color.isValid():
|
||||
self._set_color(index, color.name())
|
||||
|
||||
def _brightness_changed(self, value: int) -> None:
|
||||
self.brightness_value.setText(f"{value} %")
|
||||
self._update(brightness=value)
|
||||
|
||||
def _game_mode_changed(self, value: bool) -> None:
|
||||
self._update(game_mode=value)
|
||||
|
||||
# ---------- device state ----------
|
||||
|
||||
def set_state(self, s: DeviceState) -> None:
|
||||
self.state = s
|
||||
self.preview.set_connected(s.keyboard)
|
||||
if s.keyboard:
|
||||
mode = "Funk (Slipstream)" if s.wireless else "USB-Kabel"
|
||||
self.conn_chip.setText(f"● Verbunden · {mode}")
|
||||
self.conn_chip.setStyleSheet("color: #3ddc84;")
|
||||
elif s.receiver:
|
||||
self.conn_chip.setText("● Empfänger bereit · Tastatur schläft/aus")
|
||||
self.conn_chip.setStyleSheet("color: #f5b942;")
|
||||
else:
|
||||
self.conn_chip.setText("● Nicht verbunden")
|
||||
self.conn_chip.setStyleSheet("color: #ef5350;")
|
||||
if s.battery is not None:
|
||||
self.battery_chip.setText(f"Akku {s.battery} %")
|
||||
self.battery_chip.setStyleSheet("color: #ef5350;" if s.battery <= 15 else "")
|
||||
self.battery_chip.show()
|
||||
else:
|
||||
self.battery_chip.hide()
|
||||
|
||||
self.info["conn"].setText(self.conn_chip.text().lstrip("● ").strip())
|
||||
self.info["serial"].setText(s.serial or "–")
|
||||
self.info["kb_fw"].setText(s.keyboard_firmware or "–")
|
||||
self.info["rx_fw"].setText(s.receiver_firmware or ("–" if s.wireless else "nicht vorhanden (Kabel)"))
|
||||
self.info["battery"].setText(f"{s.battery} %" if s.battery is not None else "–")
|
||||
self.battery_bar.setValue(s.battery or 0)
|
||||
self.error_label.setText(s.error)
|
||||
self.error_label.setStyleSheet("color: #ef5350;" if s.error else "")
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Animated keyboard preview that approximates the hardware effects."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import colorsys
|
||||
import math
|
||||
import random
|
||||
import time
|
||||
|
||||
from PySide6.QtCore import QRectF, Qt, QTimer
|
||||
from PySide6.QtGui import QColor, QFont, QPainter, QPainterPath, QPen
|
||||
from PySide6.QtWidgets import QWidget
|
||||
|
||||
from .. import layout
|
||||
from ..profiles import Profile
|
||||
|
||||
SPEED_FACTOR = {"slow": 0.5, "medium": 1.0, "fast": 1.8}
|
||||
RGB = tuple[float, float, float]
|
||||
|
||||
|
||||
def _hex(c: str) -> RGB:
|
||||
q = QColor(c)
|
||||
return q.redF(), q.greenF(), q.blueF()
|
||||
|
||||
|
||||
def _hue(h: float) -> RGB:
|
||||
return colorsys.hsv_to_rgb(h % 1.0, 1.0, 1.0)
|
||||
|
||||
|
||||
def _mix(a: RGB, b: RGB, t: float) -> RGB:
|
||||
return tuple(x + (y - x) * t for x, y in zip(a, b))
|
||||
|
||||
|
||||
def _scale(a: RGB, f: float) -> RGB:
|
||||
return tuple(x * f for x in a)
|
||||
|
||||
|
||||
class KeyboardPreview(QWidget):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setMinimumHeight(220)
|
||||
self.profile = Profile()
|
||||
self.connected = True
|
||||
self._t0 = time.monotonic()
|
||||
self._presses: list[tuple[float, layout.Key, RGB]] = []
|
||||
self._next_press = 0.0
|
||||
self._rand = random.Random(7)
|
||||
self._palette_seed = [self._rand.random() for _ in range(64)]
|
||||
self._timer = QTimer(self, interval=33, timeout=self.update)
|
||||
self._timer.start()
|
||||
|
||||
def set_profile(self, profile: Profile) -> None:
|
||||
self.profile = profile
|
||||
self.update()
|
||||
|
||||
def set_connected(self, connected: bool) -> None:
|
||||
self.connected = connected
|
||||
self.update()
|
||||
|
||||
def showEvent(self, e):
|
||||
self._timer.start()
|
||||
super().showEvent(e)
|
||||
|
||||
def hideEvent(self, e):
|
||||
self._timer.stop()
|
||||
super().hideEvent(e)
|
||||
|
||||
# --- effect simulation ---
|
||||
|
||||
def _colors(self) -> tuple[RGB, RGB]:
|
||||
cs = self.profile.colors + ["#ffffff", "#ffffff"]
|
||||
return _hex(cs[0]), _hex(cs[1])
|
||||
|
||||
def _random(self, n: int) -> RGB:
|
||||
return _hue(self._palette_seed[n % len(self._palette_seed)])
|
||||
|
||||
def _key_color(self, k: layout.Key, t: float) -> RGB:
|
||||
p = self.profile
|
||||
s = SPEED_FACTOR.get(p.speed, 1.0)
|
||||
c0, c1 = self._colors()
|
||||
rnd = p.random_colors
|
||||
x, y = k.cx / layout.WIDTH, k.cy / layout.HEIGHT
|
||||
|
||||
match p.effect:
|
||||
case "off":
|
||||
return (0, 0, 0)
|
||||
case "static":
|
||||
return c0
|
||||
case "rainbow_wave":
|
||||
return _hue(x - t * 0.25 * s)
|
||||
case "spiral_rainbow":
|
||||
a = math.atan2(y - 0.5, (x - 0.5) * 2.5) / (2 * math.pi)
|
||||
return _hue(a + t * 0.2 * s)
|
||||
case "color_wave":
|
||||
phase = x - t * 0.3 * s
|
||||
n = math.floor(phase)
|
||||
band = 0.5 + 0.5 * math.cos((phase - n) * 2 * math.pi)
|
||||
col = self._random(-n) if rnd else (c0 if n % 2 == 0 else c1)
|
||||
return _scale(col, band ** 2)
|
||||
case "color_shift":
|
||||
phase = t * 0.25 * s
|
||||
n = math.floor(phase)
|
||||
a = self._random(n) if rnd else (c0 if n % 2 == 0 else c1)
|
||||
b = self._random(n + 1) if rnd else (c1 if n % 2 == 0 else c0)
|
||||
return _mix(a, b, 0.5 - 0.5 * math.cos((phase - n) * math.pi))
|
||||
case "color_pulse":
|
||||
phase = t * 0.5 * s
|
||||
n = math.floor(phase)
|
||||
col = self._random(n) if rnd else (c0 if n % 2 == 0 else c1)
|
||||
return _scale(col, math.sin((phase - n) * math.pi) ** 2)
|
||||
case "rain":
|
||||
col_i = int(k.cx * 2)
|
||||
seed = self._palette_seed[col_i % 64]
|
||||
head = ((t * 0.5 * s + seed * 3) % 1.6) * layout.HEIGHT - 1
|
||||
d = head - k.cy
|
||||
lvl = max(0.0, 1 - d / 2.0) if d >= 0 else 0.0
|
||||
col = self._random(col_i) if rnd else (c0 if col_i % 2 else c1)
|
||||
return _scale(col, lvl)
|
||||
case "watercolor":
|
||||
h = 0.5 + 0.25 * math.sin(x * 4 + t * 0.6 * s) + 0.25 * math.sin(y * 5 - t * 0.4 * s)
|
||||
return colorsys.hsv_to_rgb(h % 1.0, 0.55, 1.0)
|
||||
case "type_key" | "type_ripple":
|
||||
return self._typing(k, t, c0, c1)
|
||||
case "visor":
|
||||
pos = (math.sin(t * 1.2 * s) * 0.5 + 0.5) * layout.WIDTH
|
||||
lvl = max(0.0, 1 - abs(k.cx - pos) / 2.5)
|
||||
col = self._random(int(t * 1.2 * s / math.pi)) if rnd else c0
|
||||
return _scale(col, lvl)
|
||||
return c0
|
||||
|
||||
def _typing(self, k: layout.Key, t: float, c0: RGB, c1: RGB) -> RGB:
|
||||
level = 0.0
|
||||
best: RGB = (0, 0, 0)
|
||||
for start, key, col in self._presses:
|
||||
age = t - start
|
||||
if self.profile.effect == "type_key":
|
||||
if key is k:
|
||||
lvl = max(0.0, 1 - age / 1.2)
|
||||
else:
|
||||
continue
|
||||
else:
|
||||
d = math.hypot(k.cx - key.cx, k.cy - key.cy)
|
||||
front = age * 9 * SPEED_FACTOR.get(self.profile.speed, 1.0)
|
||||
lvl = max(0.0, 1 - abs(d - front) / 1.2) * max(0.0, 1 - age / 1.6)
|
||||
if lvl > level:
|
||||
level, best = lvl, col
|
||||
return _scale(best, level)
|
||||
|
||||
def _update_presses(self, t: float) -> None:
|
||||
if self.profile.effect not in ("type_key", "type_ripple"):
|
||||
self._presses.clear()
|
||||
return
|
||||
if t >= self._next_press:
|
||||
key = self._rand.choice(layout.KEYS)
|
||||
c0, c1 = self._colors()
|
||||
col = _hue(self._rand.random()) if self.profile.random_colors else c0
|
||||
self._presses.append((t, key, col))
|
||||
self._next_press = t + self._rand.uniform(0.15, 0.6)
|
||||
self._presses = [p for p in self._presses if t - p[0] < 2.0]
|
||||
|
||||
# --- painting ---
|
||||
|
||||
def paintEvent(self, _):
|
||||
t = time.monotonic() - self._t0
|
||||
self._update_presses(t)
|
||||
p = QPainter(self)
|
||||
p.setRenderHint(QPainter.Antialiasing)
|
||||
|
||||
margin = 18
|
||||
unit = min((self.width() - 2 * margin) / (layout.WIDTH + 0.5),
|
||||
(self.height() - 2 * margin) / (layout.HEIGHT + 0.5))
|
||||
bw, bh = unit * (layout.WIDTH + 0.5), unit * (layout.HEIGHT + 0.5)
|
||||
ox, oy = (self.width() - bw) / 2, (self.height() - bh) / 2
|
||||
|
||||
body = QRectF(ox, oy, bw, bh)
|
||||
p.setPen(QPen(QColor("#2c2f36"), 1.5))
|
||||
p.setBrush(QColor("#15171b"))
|
||||
p.drawRoundedRect(body, unit * 0.35, unit * 0.35)
|
||||
|
||||
bright = self.profile.brightness / 100 if self.connected else 0.0
|
||||
font = QFont(self.font())
|
||||
font.setPixelSize(max(7, int(unit * 0.24)))
|
||||
p.setFont(font)
|
||||
pad = unit * 0.07
|
||||
kx, ky = ox + unit * 0.25, oy + unit * 0.25
|
||||
|
||||
for k in layout.KEYS:
|
||||
r, g, b = _scale(self._key_color(k, t), bright)
|
||||
glow = QColor.fromRgbF(min(r, 1), min(g, 1), min(b, 1))
|
||||
rect = QRectF(kx + k.x * unit + pad, ky + k.y * unit + pad, k.w * unit - 2 * pad, k.h * unit - 2 * pad)
|
||||
if k.iso_enter:
|
||||
top, stem = QPainterPath(), QPainterPath()
|
||||
top.addRoundedRect(QRectF(rect.x(), rect.y(), rect.width(), unit - 2 * pad), 4, 4)
|
||||
stem.addRoundedRect(QRectF(rect.x() + unit * 0.25, rect.y(), rect.width() - unit * 0.25,
|
||||
rect.height()), 4, 4)
|
||||
path = top.united(stem)
|
||||
else:
|
||||
path = QPainterPath()
|
||||
path.addRoundedRect(rect, 4, 4)
|
||||
# Keycap: dark top, the light leaks around the edge like on the real board.
|
||||
p.setPen(QPen(glow, max(1.5, unit * 0.05)))
|
||||
cap = QColor.fromRgbF(0.09 + r * 0.22, 0.10 + g * 0.22, 0.11 + b * 0.22)
|
||||
p.setBrush(cap)
|
||||
p.drawPath(path)
|
||||
if k.label:
|
||||
p.setPen(QColor.fromRgbF(0.35 + min(r, 1) * 0.65, 0.35 + min(g, 1) * 0.65,
|
||||
0.35 + min(b, 1) * 0.65))
|
||||
label_rect = QRectF(rect.x(), rect.y(), rect.width(), unit - 2 * pad)
|
||||
p.drawText(label_rect, Qt.AlignCenter, k.label)
|
||||
|
||||
if not self.connected:
|
||||
p.setPen(QColor("#9aa0aa"))
|
||||
f = QFont(self.font())
|
||||
f.setPixelSize(15)
|
||||
p.setFont(f)
|
||||
p.drawText(body, Qt.AlignCenter, "Tastatur nicht verbunden")
|
||||
p.end()
|
||||
@@ -0,0 +1,56 @@
|
||||
ACCENT = "#19d3c5"
|
||||
|
||||
STYLESHEET = f"""
|
||||
QWidget {{
|
||||
background: #101216;
|
||||
color: #e6e8eb;
|
||||
font-size: 13px;
|
||||
}}
|
||||
QLabel, QCheckBox {{ background: transparent; }}
|
||||
QLabel#title {{ font-size: 18px; font-weight: 600; letter-spacing: 1px; }}
|
||||
QLabel#section {{ font-size: 15px; font-weight: 600; margin-top: 4px; }}
|
||||
QLabel#muted, QLabel#hint {{ color: #8b919c; }}
|
||||
QLabel#chip {{
|
||||
background: #1b1e24; border: 1px solid #2a2e36; border-radius: 11px;
|
||||
padding: 3px 10px;
|
||||
}}
|
||||
QFrame#header {{ background: #0b0d10; border-bottom: 1px solid #22262d; }}
|
||||
QFrame#card {{ background: #161920; border: 1px solid #23272f; border-radius: 10px; }}
|
||||
QListWidget {{
|
||||
background: transparent; border: none; outline: none;
|
||||
}}
|
||||
QListWidget::item {{
|
||||
padding: 9px 12px; border-radius: 6px; margin: 1px 0;
|
||||
}}
|
||||
QListWidget::item:hover {{ background: #1b1f26; }}
|
||||
QListWidget::item:selected {{ background: #1f2a2e; color: {ACCENT}; }}
|
||||
QListWidget#nav::item {{ padding: 12px 14px; font-size: 14px; }}
|
||||
QPushButton {{
|
||||
background: #1d2128; border: 1px solid #2c313a; border-radius: 6px; padding: 7px 14px;
|
||||
}}
|
||||
QPushButton:hover {{ border-color: {ACCENT}; }}
|
||||
QPushButton:checked {{ background: #17393a; border-color: {ACCENT}; color: {ACCENT}; }}
|
||||
QPushButton:disabled {{ color: #5a606a; border-color: #23272e; }}
|
||||
QPushButton#swatch {{ border-radius: 14px; padding: 0; min-width: 28px; min-height: 28px; max-width: 28px; max-height: 28px; }}
|
||||
QPushButton#color {{ min-width: 110px; min-height: 34px; font-weight: 600; }}
|
||||
QComboBox, QSpinBox {{
|
||||
background: #1d2128; border: 1px solid #2c313a; border-radius: 6px; padding: 5px 10px; min-height: 22px;
|
||||
}}
|
||||
QComboBox:hover, QSpinBox:hover {{ border-color: {ACCENT}; }}
|
||||
QComboBox QAbstractItemView {{ background: #1d2128; selection-background-color: #1f2a2e; }}
|
||||
QCheckBox {{ spacing: 10px; padding: 4px 0; }}
|
||||
QCheckBox::indicator {{ width: 18px; height: 18px; border-radius: 4px; border: 1px solid #3a404a; background: #1d2128; }}
|
||||
QCheckBox::indicator:checked {{ background: {ACCENT}; border-color: {ACCENT}; }}
|
||||
QCheckBox:disabled {{ color: #5a606a; }}
|
||||
QSlider::groove:horizontal {{ height: 6px; background: #262a32; border-radius: 3px; }}
|
||||
QSlider::sub-page:horizontal {{ background: {ACCENT}; border-radius: 3px; }}
|
||||
QSlider::handle:horizontal {{ width: 16px; margin: -6px 0; border-radius: 8px; background: #e6e8eb; }}
|
||||
QProgressBar {{ background: #262a32; border: none; border-radius: 4px; height: 8px; text-align: center; }}
|
||||
QProgressBar::chunk {{ background: {ACCENT}; border-radius: 4px; }}
|
||||
QScrollArea {{ border: none; }}
|
||||
QScrollBar:vertical {{ background: transparent; width: 8px; margin: 2px; }}
|
||||
QScrollBar::handle:vertical {{ background: #2c313a; border-radius: 3px; min-height: 30px; }}
|
||||
QScrollBar::handle:vertical:hover {{ background: #3a404a; }}
|
||||
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{ height: 0; }}
|
||||
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {{ background: transparent; }}
|
||||
"""
|
||||
Reference in new issue
Block a user