-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
108 lines (89 loc) · 2.59 KB
/
script.js
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
let screen, initWidth, initHeight, host;
let socket;
function debounce(func, wait, immediate) {
let timeout;
return function() {
let context = this, args = arguments;
let later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function screenUpdate(){
let binary = reader.result;
screen.src = "data:image/jpeg;base64," + btoa(binary);
}
function getMousePos(screen, event){
let rect = screen.getBoundingClientRect(),
scaleX = initWidth / screen.width,
scaleY = initHeight / screen.height;
console.log(`scales: ${scaleX} ${scaleY}`);
return {
x: (event.clientX - rect.left) * scaleX,
y: (event.clientY - rect.top) * scaleY
}
}
let reader = new FileReader();
reader.onload = screenUpdate;
let deboundHandler = debounce(moveHandler, 200);
function moveHandler(event){
let pos = getMousePos(screen, event);
console.log(`Sent ${pos.x} ${pos.y}`);
socket.send(`move ${pos.x} ${pos.y}`);
}
function lclickHandler(event){
if (event && (event.which == 2 || event.button == 4 )) {
console.log("mouse 2");
socket.send("mouse 2");
}
else {
console.log("mouse 0");
socket.send("mouse 0");
}
}
function rclickHandler(){
console.log("mouse 1");
socket.send("mouse 1");
}
function keyHandler(event){
event.preventDefault();
let key = event.key;
if (key.length != 1){
key = key.toLowerCase();
}
key = key.replace("arrow", "");
if (key == " "){
key = "space";
}
if (event.ctrlKey)
key += " ctrl";
if(event.shiftKey)
key += " shift";
if(event.altKey)
key += " alt";
console.log("key " + key);
socket.send("key " + key)
}
function messageHandler(event){
try {
reader.readAsBinaryString(event.data);
} catch (TypeError) {
let data = event.data.split(" ");
initWidth = data[1];
initHeight = data[2];
console.log(`Host resolution: ${initWidth}x${initHeight}`);
}
}
window.onload = function(){
host = document.location.host;
document.getElementById("h").innerText = `You are now controlling server located at: ${host}`
screen = document.getElementById("screen");
socket = new WebSocket("ws://" + host + "/ws");
socket.onmessage = messageHandler;
document.addEventListener('keydown', keyHandler);
}