/
device.ts
69 lines (54 loc) · 1.91 KB
/
device.ts
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
import interception, { Context, DeviceId, Filter, KeyboardStroke, MAX_KEYBOARD, MAX_MOUSE, MouseStroke, Stroke } from './native';
export type Mouse = Device<MouseStroke>;
export type Keyboard = Device<KeyboardStroke>;
export class Device<TStroke extends Stroke = Stroke> {
constructor(
private readonly _context: Context,
public readonly id: DeviceId,
) { }
get context() {
if (interception.isContextDestroyed(this._context)) throw new Error('The context is destroyed');
return this._context;
}
/**
* Gets the precedence (priority) set for this device.
*/
getPrecedence(): number {
return interception.getPrecedence(this.context, this.id);
}
/**
* Sets the precedence (priority) wanted for this device.
*/
setPrecedence(precedence: number): void {
interception.setPrecedence(this.context, this.id, precedence);
}
getFilter(): Filter {
return interception.getFilter(this.context, this.id);
}
send(stroke: TStroke): boolean {
return interception.send(this.context, this.id, stroke);
}
receive(): TStroke | null {
return interception.receive(this.context, this.id);
}
getHardwareId(): string | null {
return interception.getHardwareId(this.context, this.id)
?.replace(/\x00\x00$/, '')?.replace(/\x00/gi, ', ')
?? null;
}
isMouse(): this is Mouse {
return this.id > MAX_KEYBOARD && this.id < MAX_KEYBOARD + MAX_MOUSE;
}
isKeyboard(): this is Keyboard {
return this.id > 0 && this.id < MAX_KEYBOARD;
}
isInvalid(): boolean {
return !this.isMouse() && !this.isKeyboard();
}
toString(): string {
let type = 'Invalid';
if (this.isMouse()) type = 'Mouse';
else if (this.isKeyboard()) type = 'Keyboard';
return `[${type} ${this.id}]: ${this.getHardwareId()}`;
}
}