summaryrefslogtreecommitdiff
path: root/kvmd/plugins/hid/otg/keyboard.py
blob: fb964d8a30ee495407354554289e9b84330d0a89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# ========================================================================== #
#                                                                            #
#    KVMD - The main Pi-KVM daemon.                                          #
#                                                                            #
#    Copyright (C) 2018  Maxim Devaev <[email protected]>                    #
#                                                                            #
#    This program is free software: you can redistribute it and/or modify    #
#    it under the terms of the GNU General Public License as published by    #
#    the Free Software Foundation, either version 3 of the License, or       #
#    (at your option) any later version.                                     #
#                                                                            #
#    This program is distributed in the hope that it will be useful,         #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of          #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           #
#    GNU General Public License for more details.                            #
#                                                                            #
#    You should have received a copy of the GNU General Public License       #
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.  #
#                                                                            #
# ========================================================================== #


import dataclasses

from typing import List
from typing import Set
from typing import Optional
from typing import Any

from ....logging import get_logger

from .... import keymap

from .device import BaseEvent
from .device import BaseDeviceProcess


# =====
class _ClearEvent(BaseEvent):
    pass


class _ResetEvent(BaseEvent):
    pass


@dataclasses.dataclass(frozen=True)
class _ModifierEvent(BaseEvent):
    modifier: keymap.OtgKey
    state: bool

    def __post_init__(self) -> None:
        assert self.modifier.is_modifier


@dataclasses.dataclass(frozen=True)
class _KeyEvent(BaseEvent):
    key: keymap.OtgKey
    state: bool

    def __post_init__(self) -> None:
        assert not self.key.is_modifier


# =====
class KeyboardProcess(BaseDeviceProcess):
    def __init__(self, **kwargs: Any) -> None:
        super().__init__(
            name="keyboard",
            read_size=1,
            initial_state={"caps": False, "scroll": False, "num": False},
            **kwargs,
        )

        self.__pressed_modifiers: Set[keymap.OtgKey] = set()
        self.__pressed_keys: List[Optional[keymap.OtgKey]] = [None] * 6

    def cleanup(self) -> None:
        self._stop()
        get_logger().info("Clearing HID-keyboard events ...")
        self._ensure_write(b"\x00" * 8, close=True)  # Release all keys and modifiers

    def send_clear_event(self) -> None:
        self._queue_event(_ClearEvent())

    def send_reset_event(self) -> None:
        self._queue_event(_ResetEvent())

    def send_key_event(self, key: str, state: bool) -> None:
        otg_key = keymap.KEYMAP[key].otg
        if otg_key.is_modifier:
            self._queue_event(_ModifierEvent(otg_key, state))
        else:
            self._queue_event(_KeyEvent(otg_key, state))

    # =====

    def _process_read_report(self, report: bytes) -> None:
        # https://wiki.osdev.org/USB_Human_Interface_Devices#LED_lamps
        assert len(report) == 1, report
        self._update_state(
            caps=bool(report[0] & 2),
            scroll=bool(report[0] & 4),
            num=bool(report[0] & 1),
        )

    # =====

    def _process_event(self, event: BaseEvent) -> None:
        if isinstance(event, _ClearEvent):
            self.__process_clear_event()
        elif isinstance(event, _ResetEvent):
            self.__process_clear_event(reopen=True)
        elif isinstance(event, _ModifierEvent):
            self.__process_modifier_event(event)
        elif isinstance(event, _KeyEvent):
            self.__process_key_event(event)

    def __process_clear_event(self, reopen: bool=False) -> None:
        self.__clear_modifiers()
        self.__clear_keys()
        self.__send_current_state(reopen=reopen)

    def __process_modifier_event(self, event: _ModifierEvent) -> None:
        if event.modifier in self.__pressed_modifiers:
            # Ранее нажатый модификатор отжимаем
            self.__pressed_modifiers.remove(event.modifier)
            if not self.__send_current_state():
                return
        if event.state:
            # Нажимаем если нужно
            self.__pressed_modifiers.add(event.modifier)
            self.__send_current_state()

    def __process_key_event(self, event: _KeyEvent) -> None:
        if event.key in self.__pressed_keys:
            # Ранее нажатую клавишу отжимаем
            self.__pressed_keys[self.__pressed_keys.index(event.key)] = None
            if not self.__send_current_state():
                return
        elif event.state and None not in self.__pressed_keys:
            # Если нужно нажать что-то новое, но свободных слотов нет - отжимаем всё
            self.__clear_keys()
            if not self.__send_current_state():
                return
        if event.state:
            # Нажимаем если нужно
            self.__pressed_keys[self.__pressed_keys.index(None)] = event.key
            self.__send_current_state()

    # =====

    def __send_current_state(self, reopen: bool=False) -> bool:
        if not self._ensure_write(self.__make_report(), reopen=reopen):
            self.__clear_modifiers()
            self.__clear_keys()
            return False
        return True

    def __clear_modifiers(self) -> None:
        self.__pressed_modifiers.clear()

    def __clear_keys(self) -> None:
        self.__pressed_keys = [None] * 6

    def __make_report(self) -> bytes:
        modifiers = 0
        for modifier in self.__pressed_modifiers:
            modifiers |= modifier.code

        assert len(self.__pressed_keys) == 6
        keys = [
            (0 if key is None else key.code)
            for key in self.__pressed_keys
        ]

        return bytes([modifiers, 0] + keys)