Skip to content

Commit 0dd7098

Browse files
committed
Use the KeysDownState for the infobar
Strong typed in the typescript realm.
1 parent b3d8c3b commit 0dd7098

File tree

8 files changed

+177
-185
lines changed

8 files changed

+177
-185
lines changed

internal/usbgadget/hid_keyboard.go

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ func getKeyboardState(b byte) KeyboardState {
100100
}
101101
}
102102

103-
func (u *UsbGadget) updateKeyboardState(state byte) {
103+
func (u *UsbGadget) updateKeyboardState(state uint8) {
104104
u.keyboardStateLock.Lock()
105105
defer u.keyboardStateLock.Unlock()
106106

@@ -185,7 +185,7 @@ func (u *UsbGadget) listenKeyboardEvents() {
185185
l.Trace().Msg("starting")
186186

187187
go func() {
188-
buf := make([]byte, hidReadBufferSize)
188+
buf := make([]uint8, hidReadBufferSize)
189189
for {
190190
select {
191191
case <-u.keyboardStateCtx.Done():
@@ -209,7 +209,7 @@ func (u *UsbGadget) listenKeyboardEvents() {
209209
}
210210
u.resetLogSuppressionCounter("keyboardHidFileRead")
211211

212-
l.Trace().Int("n", n).Bytes("buf", buf).Msg("got data from keyboard")
212+
l.Trace().Int("n", n).Uints8("buf", buf).Msg("got data from keyboard")
213213
if n != 1 {
214214
l.Trace().Int("n", n).Msg("expected 1 byte, got")
215215
continue
@@ -245,12 +245,12 @@ func (u *UsbGadget) OpenKeyboardHidFile() error {
245245
return u.openKeyboardHidFile()
246246
}
247247

248-
func (u *UsbGadget) keyboardWriteHidFile(modifier byte, keys []byte) error {
248+
func (u *UsbGadget) keyboardWriteHidFile(modifier uint8, keys []uint8) error {
249249
if err := u.openKeyboardHidFile(); err != nil {
250250
return err
251251
}
252252

253-
_, err := u.keyboardHidFile.Write(append([]byte{modifier, 0x00}, keys[:]...))
253+
_, err := u.keyboardHidFile.Write(append([]uint8{modifier, 0x00}, keys[:hidKeyBufferSize]...))
254254
if err != nil {
255255
u.logWithSuppression("keyboardWriteHidFile", 100, u.log, err, "failed to write to hidg0")
256256
u.keyboardHidFile.Close()
@@ -261,7 +261,7 @@ func (u *UsbGadget) keyboardWriteHidFile(modifier byte, keys []byte) error {
261261
return nil
262262
}
263263

264-
func (u *UsbGadget) KeyboardReport(modifier byte, keys []byte) error {
264+
func (u *UsbGadget) KeyboardReport(modifier uint8, keys []uint8) error {
265265
u.keyboardLock.Lock()
266266
defer u.keyboardLock.Unlock()
267267
defer u.resetUserInputTime()
@@ -270,7 +270,7 @@ func (u *UsbGadget) KeyboardReport(modifier byte, keys []byte) error {
270270
keys = keys[:hidKeyBufferSize]
271271
}
272272
if len(keys) < hidKeyBufferSize {
273-
keys = append(keys, make([]byte, hidKeyBufferSize-len(keys))...)
273+
keys = append(keys, make([]uint8, hidKeyBufferSize-len(keys))...)
274274
}
275275

276276
return u.keyboardWriteHidFile(modifier, keys)
@@ -289,12 +289,6 @@ const (
289289
RightSuper = 0xE7 // Right GUI (e.g. Windows key, Apple Command key)
290290
)
291291

292-
// KeyCodeMask maps a key code to its corresponding bit mask
293-
type KeyCodeMask struct {
294-
KeyCode byte
295-
Mask byte
296-
}
297-
298292
// KeyCodeToMaskMap is a slice of KeyCodeMask for quick lookup
299293
var KeyCodeToMaskMap = map[uint8]uint8{
300294
LeftControl: ModifierMaskLeftControl,
@@ -307,7 +301,7 @@ var KeyCodeToMaskMap = map[uint8]uint8{
307301
RightSuper: ModifierMaskRightSuper,
308302
}
309303

310-
func (u *UsbGadget) KeypressReport(key byte, press bool) (KeysDownState, error) {
304+
func (u *UsbGadget) KeypressReport(key uint8, press bool) (KeysDownState, error) {
311305
u.keyboardLock.Lock()
312306
defer u.keyboardLock.Unlock()
313307
defer u.resetUserInputTime()
@@ -364,7 +358,7 @@ func (u *UsbGadget) KeypressReport(key byte, press bool) (KeysDownState, error)
364358
}
365359

366360
if err := u.keyboardWriteHidFile(modifier, keys); err != nil {
367-
u.log.Warn().Uint8("modifier", modifier).Bytes("keys", keys).Msg("Could not write keypress report to hidg0")
361+
u.log.Warn().Uint8("modifier", modifier).Uints8("keys", keys).Msg("Could not write keypress report to hidg0")
368362
}
369363

370364
state.Modifier = modifier

internal/usbgadget/usbgadget.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ var defaultUsbGadgetDevices = Devices{
4242
}
4343

4444
type KeysDownState struct {
45-
Modifier byte `json:"modifier"`
46-
Keys []byte `json:"keys"`
45+
Modifier uint8 `json:"modifier"`
46+
Keys []uint8 `json:"keys"`
4747
}
4848

4949
// UsbGadget is a struct that represents a USB gadget.
@@ -65,7 +65,7 @@ type UsbGadget struct {
6565
relMouseHidFile *os.File
6666
relMouseLock sync.Mutex
6767

68-
keyboardState byte // keyboard latched state (NumLock, CapsLock, ScrollLock, Compose, Kana)
68+
keyboardState uint8 // keyboard latched state (NumLock, CapsLock, ScrollLock, Compose, Kana)
6969
keysDownState KeysDownState // keyboard dynamic state (modifier keys and pressed keys)
7070

7171
keyboardStateLock sync.Mutex
@@ -131,7 +131,7 @@ func newUsbGadget(name string, configMap map[string]gadgetConfigItem, enabledDev
131131
keyboardStateCtx: keyboardCtx,
132132
keyboardStateCancel: keyboardCancel,
133133
keyboardState: 0,
134-
keysDownState: KeysDownState{Modifier: 0, Keys: []byte{0, 0, 0, 0, 0, 0}}, // must be initialized to hidKeyBufferSize (6) zero bytes
134+
keysDownState: KeysDownState{Modifier: 0, Keys: []uint8{0, 0, 0, 0, 0, 0}}, // must be initialized to hidKeyBufferSize (6) zero bytes
135135
enabledDevices: *enabledDevices,
136136
lastUserInput: time.Now(),
137137
log: logger,

ui/src/components/InfoBar.tsx

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,65 @@
1-
import { useEffect } from "react";
1+
import { useEffect, useMemo } from "react";
22

33
import { cx } from "@/cva.config";
44
import {
5+
HidState,
6+
KeysDownState,
7+
MouseState,
8+
RTCState,
9+
SettingsState,
510
useHidStore,
611
useMouseStore,
712
useRTCStore,
813
useSettingsStore,
914
useVideoStore,
15+
VideoState,
1016
} from "@/hooks/stores";
1117
import { keys, modifiers } from "@/keyboardMappings";
1218

1319
export default function InfoBar() {
14-
const activeKeys = useHidStore(state => state.activeKeys);
15-
const activeModifiers = useHidStore(state => state.activeModifiers);
16-
const mouseX = useMouseStore(state => state.mouseX);
17-
const mouseY = useMouseStore(state => state.mouseY);
18-
const mouseMove = useMouseStore(state => state.mouseMove);
20+
const keysDownState = useHidStore((state: HidState) => state.keysDownState);
21+
const mouseX = useMouseStore((state: MouseState) => state.mouseX);
22+
const mouseY = useMouseStore((state: MouseState) => state.mouseY);
23+
const mouseMove = useMouseStore((state: MouseState) => state.mouseMove);
1924

2025
const videoClientSize = useVideoStore(
21-
state => `${Math.round(state.clientWidth)}x${Math.round(state.clientHeight)}`,
26+
(state: VideoState) => `${Math.round(state.clientWidth)}x${Math.round(state.clientHeight)}`,
2227
);
2328

2429
const videoSize = useVideoStore(
25-
state => `${Math.round(state.width)}x${Math.round(state.height)}`,
30+
(state: VideoState) => `${Math.round(state.width)}x${Math.round(state.height)}`,
2631
);
2732

28-
const rpcDataChannel = useRTCStore(state => state.rpcDataChannel);
33+
const rpcDataChannel = useRTCStore((state: RTCState) => state.rpcDataChannel);
2934

3035
const settings = useSettingsStore();
31-
const showPressedKeys = useSettingsStore(state => state.showPressedKeys);
36+
const showPressedKeys = useSettingsStore((state: SettingsState) => state.showPressedKeys);
3237

3338
useEffect(() => {
3439
if (!rpcDataChannel) return;
3540
rpcDataChannel.onclose = () => console.log("rpcDataChannel has closed");
36-
rpcDataChannel.onerror = e =>
41+
rpcDataChannel.onerror = (e: Event) =>
3742
console.log(`Error on DataChannel '${rpcDataChannel.label}': ${e}`);
3843
}, [rpcDataChannel]);
3944

40-
const keyboardLedState = useHidStore(state => state.keyboardLedState);
41-
const isTurnServerInUse = useRTCStore(state => state.isTurnServerInUse);
45+
const keyboardLedState = useHidStore((state: HidState) => state.keyboardLedState);
46+
const isTurnServerInUse = useRTCStore((state: RTCState) => state.isTurnServerInUse);
4247

43-
const usbState = useHidStore(state => state.usbState);
44-
const hdmiState = useVideoStore(state => state.hdmiState);
48+
const usbState = useHidStore((state: HidState) => state.usbState);
49+
const hdmiState = useVideoStore((state: VideoState) => state.hdmiState);
50+
51+
const displayKeys = useMemo(() => {
52+
if (!showPressedKeys || !keysDownState)
53+
return "";
54+
55+
const state = keysDownState as KeysDownState;
56+
const activeModifierMask = state.modifier || 0;
57+
const keysDown = state.keys || [];
58+
const modifierNames = Object.entries(modifiers).filter(([_, mask]) => (activeModifierMask & mask) !== 0).map(([name, _]) => name);
59+
const keyNames = Object.entries(keys).filter(([_, value]) => keysDown.includes(value)).map(([name, _]) => name);
60+
61+
return [...modifierNames,...keyNames].join(", ");
62+
}, [keysDownState, showPressedKeys]);
4563

4664
return (
4765
<div className="bg-white border-t border-t-slate-800/30 text-slate-800 dark:border-t-slate-300/20 dark:bg-slate-900 dark:text-slate-300">
@@ -99,14 +117,7 @@ export default function InfoBar() {
99117
<div className="flex items-center gap-x-1">
100118
<span className="text-xs font-semibold">Keys:</span>
101119
<h2 className="text-xs">
102-
{[
103-
...activeKeys.map(
104-
x => Object.entries(keys).filter(y => y[1] === x)[0][0],
105-
),
106-
activeModifiers.map(
107-
x => Object.entries(modifiers).filter(y => y[1] === x)[0][0],
108-
),
109-
].join(", ")}
120+
{displayKeys}
110121
</h2>
111122
</div>
112123
)}

0 commit comments

Comments
 (0)