-
-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathInputHandler.ts
More file actions
398 lines (359 loc) · 9.84 KB
/
InputHandler.ts
File metadata and controls
398 lines (359 loc) · 9.84 KB
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import { Button, Key, Point, keyboard, mouse } from "@nut-tree-fork/nut-js"
import { KEY_MAP } from "./KeyMap"
import { moveRelative } from "./ydotool"
import os from "node:os"
type ServerToClientMessage = {
type: "clipboard-text"
text: string
}
export interface InputMessage {
type:
| "move"
| "paste"
| "copy"
| "clipboard-push"
| "clipboard-pull"
| "click"
| "scroll"
| "key"
| "text"
| "zoom"
| "combo"
dx?: number
dy?: number
button?: "left" | "right" | "middle"
press?: boolean
key?: string
keys?: string[]
text?: string
delta?: number
}
export class InputHandler {
private lastMoveTime = 0
private lastScrollTime = 0
private pendingMove: InputMessage | null = null
private pendingScroll: InputMessage | null = null
private moveTimer: ReturnType<typeof setTimeout> | null = null
private scrollTimer: ReturnType<typeof setTimeout> | null = null
private throttleMs: number
private modifier: Key
constructor(
private sendToClient: (msg: ServerToClientMessage) => void,
throttleMs = 8,
) {
mouse.config.mouseSpeed = 1000
this.modifier = os.platform() === "darwin" ? Key.LeftSuper : Key.LeftControl
this.throttleMs = throttleMs
}
setThrottleMs(ms: number) {
this.throttleMs = ms
}
private isFiniteNumber(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value)
}
private clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value))
}
async handleMessage(msg: InputMessage) {
if (msg.text && typeof msg.text === "string" && msg.text.length > 500) {
msg.text = msg.text.substring(0, 500)
}
const MAX_COORD = 2000
if (this.isFiniteNumber(msg.dx)) {
msg.dx = this.clamp(msg.dx, -MAX_COORD, MAX_COORD)
} else {
msg.dx = 0
}
if (this.isFiniteNumber(msg.dy)) {
msg.dy = this.clamp(msg.dy, -MAX_COORD, MAX_COORD)
} else {
msg.dy = 0
}
if (this.isFiniteNumber(msg.delta)) {
msg.delta = this.clamp(msg.delta, -MAX_COORD, MAX_COORD)
} else {
msg.delta = 0
}
// Throttling: Limit high-frequency events (configurable via inputThrottleMs)
if (msg.type === "move") {
const now = Date.now()
if (now - this.lastMoveTime < this.throttleMs) {
this.pendingMove = msg
if (!this.moveTimer) {
this.moveTimer = setTimeout(() => {
this.moveTimer = null
if (this.pendingMove) {
const pending = this.pendingMove
this.pendingMove = null
this.handleMessage(pending).catch((err) => {
console.error("Error processing pending move event:", err)
})
}
}, this.throttleMs)
}
return
}
this.lastMoveTime = now
} else if (msg.type === "scroll") {
const now = Date.now()
if (now - this.lastScrollTime < this.throttleMs) {
this.pendingScroll = msg
if (!this.scrollTimer) {
this.scrollTimer = setTimeout(() => {
this.scrollTimer = null
if (this.pendingScroll) {
const pending = this.pendingScroll
this.pendingScroll = null
this.handleMessage(pending).catch((err) => {
console.error("Error processing pending move event:", err)
})
}
}, this.throttleMs)
}
return
}
this.lastScrollTime = now
}
switch (msg.type) {
case "move":
if (
typeof msg.dx === "number" &&
typeof msg.dy === "number" &&
Number.isFinite(msg.dx) &&
Number.isFinite(msg.dy)
) {
try {
// Attempt ydotool relative movement first
const success = await moveRelative(msg.dx, msg.dy)
// Fallback to absolute positioning if ydotool is unavailable or fails
if (!success) {
const currentPos = await mouse.getPosition()
await mouse.setPosition(
new Point(
Math.round(currentPos.x + msg.dx),
Math.round(currentPos.y + msg.dy),
),
)
}
} catch (err) {
console.error("Move event failed:", err)
}
}
break
case "click": {
const VALID_BUTTONS = ["left", "right", "middle"]
if (msg.button && VALID_BUTTONS.includes(msg.button)) {
const btn =
msg.button === "left"
? Button.LEFT
: msg.button === "right"
? Button.RIGHT
: Button.MIDDLE
try {
if (msg.press) {
await mouse.pressButton(btn)
} else {
await mouse.releaseButton(btn)
}
} catch (err) {
console.error("Click event failed:", err)
// ensure release just in case
await mouse.releaseButton(btn).catch(() => {})
}
}
break
}
case "copy": {
try {
await keyboard.pressKey(this.modifier, Key.C)
} catch (err) {
console.warn("Error while copying:", err)
} finally {
await Promise.allSettled([
keyboard.releaseKey(Key.C),
keyboard.releaseKey(this.modifier),
])
}
break
}
case "paste": {
try {
await keyboard.pressKey(this.modifier, Key.V)
} catch (err) {
console.warn("Error while pasting:", err)
} finally {
await Promise.allSettled([
keyboard.releaseKey(Key.V),
keyboard.releaseKey(this.modifier),
])
}
break
}
case "clipboard-push": {
if (msg.text) {
// TEMP: fallback using typing instead of real clipboard
try {
await keyboard.type(msg.text)
} catch (err) {
console.error("Clipboard push failed:", err)
}
}
break
}
case "clipboard-pull": {
// simulate Ctrl+C to get current clipboard
try {
await keyboard.pressKey(this.modifier, Key.C)
} finally {
await Promise.allSettled([
keyboard.releaseKey(Key.C),
keyboard.releaseKey(this.modifier),
])
}
// small delay to allow clipboard update
await new Promise((r) => setTimeout(r, 100))
// ❗ send back to client (IMPORTANT)
this.sendToClient({
type: "clipboard-text",
text: "CLIPBOARD_DATA_UNAVAILABLE",
})
break
}
case "scroll": {
const MAX_SCROLL = 100
const promises: Promise<unknown>[] = []
// Vertical scroll
if (this.isFiniteNumber(msg.dy) && Math.round(msg.dy) !== 0) {
const amount = this.clamp(Math.round(msg.dy), -MAX_SCROLL, MAX_SCROLL)
if (amount > 0) {
promises.push(mouse.scrollDown(amount))
} else if (amount < 0) {
promises.push(mouse.scrollUp(-amount))
}
}
// Horizontal scroll
if (this.isFiniteNumber(msg.dx) && Math.round(msg.dx) !== 0) {
const amount = this.clamp(Math.round(msg.dx), -MAX_SCROLL, MAX_SCROLL)
if (amount > 0) {
promises.push(mouse.scrollRight(amount))
} else if (amount < 0) {
promises.push(mouse.scrollLeft(-amount))
}
}
if (promises.length) {
const results = await Promise.allSettled(promises)
for (const result of results) {
if (result.status === "rejected") {
console.error("Scroll event failed:", result.reason)
}
}
}
break
}
case "zoom":
if (this.isFiniteNumber(msg.delta) && msg.delta !== 0) {
const sensitivityFactor = 0.5
const MAX_ZOOM_STEP = 5
const scaledDelta =
Math.sign(msg.delta) *
Math.min(Math.abs(msg.delta) * sensitivityFactor, MAX_ZOOM_STEP)
const amount = Math.round(-scaledDelta)
if (amount !== 0) {
await keyboard.pressKey(Key.LeftControl)
try {
if (amount > 0) {
await mouse.scrollDown(amount)
} else {
await mouse.scrollUp(-amount)
}
} finally {
await keyboard.releaseKey(Key.LeftControl)
}
}
}
break
case "key":
if (msg.key && typeof msg.key === "string" && msg.key.length <= 50) {
console.log(`Processing key: ${msg.key}`)
const nutKey = KEY_MAP[msg.key.toLowerCase()]
try {
if (nutKey !== undefined) {
await keyboard.pressKey(nutKey)
await keyboard.releaseKey(nutKey)
} else if (msg.key === " " || msg.key?.toLowerCase() === "space") {
const spaceKey = KEY_MAP.space
await keyboard.pressKey(spaceKey)
await keyboard.releaseKey(spaceKey)
} else if (msg.key.length === 1) {
await keyboard.type(msg.key)
} else {
console.log(`Unmapped key: ${msg.key}`)
}
} catch (err) {
console.warn("Key press failed:", err)
// ensure release just in case
if (nutKey !== undefined)
await keyboard.releaseKey(nutKey).catch(() => {})
if (msg.key === " " || msg.key?.toLowerCase() === "space")
await keyboard.releaseKey(KEY_MAP.space).catch(() => {})
}
}
break
case "combo":
if (
msg.keys &&
Array.isArray(msg.keys) &&
msg.keys.length > 0 &&
msg.keys.length <= 10
) {
const nutKeys: (Key | string)[] = []
for (const k of msg.keys) {
const lowerKey = k.toLowerCase()
const nutKey = KEY_MAP[lowerKey]
if (nutKey !== undefined) {
nutKeys.push(nutKey)
} else if (lowerKey.length === 1) {
nutKeys.push(lowerKey)
} else {
console.warn(`Unknown key in combo: ${k}`)
}
}
if (nutKeys.length === 0) {
console.error("No valid keys in combo")
return
}
console.log("Pressing keys:", nutKeys)
const pressedKeys: Key[] = []
try {
for (const k of nutKeys) {
if (typeof k === "string") {
await keyboard.type(k)
} else {
await keyboard.pressKey(k)
pressedKeys.push(k)
}
}
await new Promise((resolve) => setTimeout(resolve, 10))
} catch (err) {
console.error("Combo execution failed:", err)
} finally {
const releasePromises = pressedKeys
.reverse()
.map((k) => keyboard.releaseKey(k))
await Promise.allSettled(releasePromises)
}
console.log(`Combo complete: ${msg.keys.join("+")}`)
}
break
case "text":
if (msg.text && typeof msg.text === "string") {
try {
await keyboard.type(msg.text)
} catch (err) {
console.error("Failed to type text:", err)
}
}
break
}
}
}