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
|
var keyboard = new function() {
var __ws = null;
var __keys = [];
var __modifiers = [];
this.init = function() {
document.onkeydown = (event) => __keyboardHandler(event, true);
document.onkeyup = (event) => __keyboardHandler(event, false);
Array.prototype.forEach.call(document.getElementsByClassName("key"), function(el_key) {
el_key.onmousedown = () => __clickHandler(el_key, true);
el_key.onmouseup = () => __clickHandler(el_key, false);
el_key.onmouseout = function() {
if (__isPressed(el_key)) {
__clickHandler(el_key, false);
}
};
__keys.push(el_key);
});
Array.prototype.forEach.call(document.getElementsByClassName("modifier"), function(el_key) {
el_key.onmousedown = () => __toggleModifierHandler(el_key);
__modifiers.push(el_key);
});
};
this.setSocket = function(ws) {
keyboard.releaseAll();
__ws = ws;
$("hid-keyboard-led").className = (ws ? "led-on" : "led-off");
};
this.releaseAll = function(ws) {
__keys.concat(__modifiers).forEach(function(el_key) {
if (__isActive(el_key)) {
keyboard.fireEvent(el_key.id, false);
}
});
};
this.fireEvent = function(code, state) {
document.dispatchEvent(new KeyboardEvent(
(state ? "keydown" : "keyup"),
{code: code},
));
};
var __keyboardHandler = function(event, state) {
event.preventDefault();
el_key = $(event.code);
if (el_key && !event.repeat) {
__commonHandler(el_key, state, "pressed");
__unholdModifiers();
}
};
var __clickHandler = function(el_key, state) {
__commonHandler(el_key, state, "pressed");
__unholdModifiers();
};
var __toggleModifierHandler = function(el_key) {
__commonHandler(el_key, !__isActive(el_key), "holded");
};
var __unholdModifiers = function() {
__modifiers.forEach(function(el_key) {
if (__isHolded(el_key)) {
__deactivate(el_key);
__sendKey(el_key.id, false);
}
});
};
var __commonHandler = function(el_key, state, cls) {
if (state && !__isActive(el_key)) {
__deactivate(el_key);
el_key.classList.add(cls);
__sendKey(el_key.id, true);
} else {
__deactivate(el_key);
__sendKey(el_key.id, false);
}
};
var __isPressed = function(el_key) {
return el_key.classList.contains("pressed");
};
var __isHolded = function(el_key) {
return el_key.classList.contains("holded");
};
var __isActive = function(el_key) {
return (__isPressed(el_key) || __isHolded(el_key));
};
var __deactivate = function(el_key) {
el_key.classList.remove("pressed");
el_key.classList.remove("holded");
};
var __sendKey = function(code, state) {
tools.debug("Key", (state ? "pressed:" : "released:"), code);
if (__ws) {
__ws.send(JSON.stringify({
event_type: "key",
key: code,
state: state,
}));
}
};
};
|