summaryrefslogtreecommitdiff
path: root/web/share/js/kvm/mouse.js
blob: 3310d17ec79686319ce37a3b5324d63da6adeca0 (plain)
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
/*****************************************************************************
#                                                                            #
#    KVMD - The main PiKVM daemon.                                           #
#                                                                            #
#    Copyright (C) 2018-2024  Maxim Devaev <[email protected]>               #
#                                                                            #
#    This program is free software: you can redistribute it and/or modify    #
#    it under the terms of the GNU General Public License as published by    #
#    the Free Software Foundation, either version 3 of the License, or       #
#    (at your option) any later version.                                     #
#                                                                            #
#    This program is distributed in the hope that it will be useful,         #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of          #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           #
#    GNU General Public License for more details.                            #
#                                                                            #
#    You should have received a copy of the GNU General Public License       #
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.  #
#                                                                            #
*****************************************************************************/


"use strict";


import {tools, $} from "../tools.js";
import {Keypad} from "../keypad.js";


export function Mouse(__getGeometry, __recordWsEvent) {
	var self = this;

	/************************************************************************/

	var __ws = null;
	var __online = true;
	var __absolute = true;

	var __keypad = null;

	var __timer = null;
	var __planned_pos = {"x": 0, "y": 0};
	var __sent_pos = {"x": 0, "y": 0};
	var __relative_deltas = [];
	var __relative_touch_pos = null;
	var __relative_sens = 1.0;
	var __scroll_rate = 5;
	var __scroll_delta = {"x": 0, "y": 0};

	var __stream_hovered = false;

	var __init__ = function() {
		__keypad = new Keypad("div#stream-mouse-buttons", __sendButton, false);

		$("hid-mouse-led").title = "Mouse free";

		document.onpointerlockchange = __relativeCapturedHandler; // Only for relative
		document.onpointerlockerror = __relativeCapturedHandler;
		$("stream-box").onmouseenter = () => __streamHoveredHandler(true);
		$("stream-box").onmouseleave = () => __streamHoveredHandler(false);
		$("stream-box").onmousedown = (event) => __streamButtonHandler(event, true);
		$("stream-box").onmouseup = (event) => __streamButtonHandler(event, false);
		$("stream-box").oncontextmenu = (event) => event.preventDefault();
		$("stream-box").onmousemove = __streamMoveHandler;
		$("stream-box").onwheel = __streamScrollHandler;
		$("stream-box").ontouchstart = (event) => __streamTouchStartHandler(event);
		$("stream-box").ontouchmove = (event) => __streamTouchMoveHandler(event);
		$("stream-box").ontouchend = (event) => __streamTouchEndHandler(event);

		tools.storage.bindSimpleSwitch($("hid-mouse-squash-switch"), "hid.mouse.squash", true);
		tools.slider.setParams($("hid-mouse-sens-slider"), 0.1, 1.9, 0.1, tools.storage.get("hid.mouse.sens", 1.0), __updateRelativeSens);
		tools.slider.setParams($("hid-mouse-rate-slider"), 10, 100, 10, tools.storage.get("hid.mouse.rate", 10), __updateRate); // set __timer

		tools.storage.bindSimpleSwitch($("hid-mouse-reverse-scrolling-switch"), "hid.mouse.reverse_scrolling", false);
		tools.storage.bindSimpleSwitch($("hid-mouse-reverse-panning-switch"), "hid.mouse.reverse_panning", false);
		let cumulative_scrolling = !(tools.browser.is_firefox && !tools.browser.is_mac);
		tools.storage.bindSimpleSwitch($("hid-mouse-cumulative-scrolling-switch"), "hid.mouse.cumulative_scrolling", cumulative_scrolling);
		tools.slider.setParams($("hid-mouse-scroll-slider"), 1, 25, 1, tools.storage.get("hid.mouse.scroll_rate", 5), __updateScrollRate);

		tools.storage.bindSimpleSwitch($("hid-mouse-dot-switch"), "hid.mouse.dot", true, __updateOnlineLeds);
	};

	/************************************************************************/

	self.setSocket = function(ws) {
		__ws = ws;
		if (!__absolute && __isRelativeCaptured()) {
			document.exitPointerLock();
		}
		__updateOnlineLeds();
	};

	self.setState = function(online, absolute, hid_online, hid_busy) {
		if (!hid_online) {
			__online = null;
		} else {
			__online = (online && !hid_busy);
		}
		if (!__absolute && absolute && __isRelativeCaptured()) {
			document.exitPointerLock();
		}
		if (__absolute && !absolute) {
			__relative_deltas = [];
			__relative_touch_pos = null;
		}
		__absolute = absolute;
		__updateOnlineLeds();
	};

	self.releaseAll = function() {
		__keypad.releaseAll();
	};

	var __updateRate = function(value) {
		$("hid-mouse-rate-value").innerHTML = value + " ms";
		tools.storage.set("hid.mouse.rate", value);
		if (__timer) {
			clearInterval(__timer);
		}
		__timer = setInterval(__sendPlannedMove, value);
	};

	var __updateScrollRate = function(value) {
		$("hid-mouse-scroll-value").innerHTML = value;
		tools.storage.set("hid.mouse.scroll_rate", value);
		__scroll_rate = value;
	};

	var __updateRelativeSens = function(value) {
		$("hid-mouse-sens-value").innerHTML = value.toFixed(1);
		tools.storage.set("hid.mouse.sens", value);
		__relative_sens = value;
	};

	var __streamHoveredHandler = function(hovered) {
		if (__absolute) {
			__stream_hovered = hovered;
			__updateOnlineLeds();
		}
	};

	var __updateOnlineLeds = function() {
		let is_captured;
		if (__absolute) {
			is_captured = (__stream_hovered || tools.browser.is_mobile);
		} else {
			is_captured = __isRelativeCaptured();
		}
		let led = "led-gray";
		let title = "Mouse free";

		if (__ws) {
			if (__online === null) {
				led = "led-red";
				title = (is_captured ? "Mouse captured, HID offline" : "Mouse free, HID offline");
			} else if (__online) {
				if (is_captured) {
					led = "led-green";
					title = "Mouse captured";
				}
			} else {
				led = "led-yellow";
				title = (is_captured ? "Mouse captured, inactive/busy" : "Mouse free, inactive/busy");
			}
		} else {
			if (is_captured) {
				title = "Mouse captured, PiKVM offline";
			}
		}
		$("hid-mouse-led").className = led;
		$("hid-mouse-led").title = title;

		if (__absolute && is_captured) {
			let dot = $("hid-mouse-dot-switch").checked;
			$("stream-box").classList.toggle("stream-box-mouse-dot", (dot && __ws));
			$("stream-box").classList.toggle("stream-box-mouse-none", (!dot && __ws));
		} else {
			$("stream-box").classList.toggle("stream-box-mouse-dot", false);
			$("stream-box").classList.toggle("stream-box-mouse-none", false);
		}
	};

	var __isRelativeCaptured = function() {
		return (document.pointerLockElement === $("stream-box"));
	};

	var __relativeCapturedHandler = function() {
		tools.info("Relative mouse", (__isRelativeCaptured() ? "captured" : "released"), "by pointer lock");
		__updateOnlineLeds();
	};

	var __streamButtonHandler = function(event, state) {
		// https://www.w3schools.com/jsref/event_button.asp
		event.preventDefault();
		if (__absolute || __isRelativeCaptured()) {
			switch (event.button) {
				case 0: __keypad.emitByCode("left", state); break;
				case 2: __keypad.emitByCode("right", state); break;
				case 1: __keypad.emitByCode("middle", state); break;
				case 3: __keypad.emitByCode("up", state); break;
				case 4: __keypad.emitByCode("down", state); break;
			}
		} else if (!__absolute && !__isRelativeCaptured() && !state) {
			$("stream-box").requestPointerLock();
		}
	};

	var __streamTouchStartHandler = function(event) {
		event.preventDefault();
		if (event.touches.length === 1) {
			if (__absolute) {
				__planned_pos = __getTouchPosition(event, 0);
				__sendPlannedMove();
			} else {
				__relative_touch_pos = __getTouchPosition(event, 0);
			}
		}
	};

	var __streamTouchMoveHandler = function(event) {
		event.preventDefault();
		if (event.touches.length === 1) {
			if (__absolute) {
				__planned_pos = __getTouchPosition(event, 0);
			} else if (__relative_touch_pos === null) {
				__relative_touch_pos = __getTouchPosition(event, 0);
			} else {
				let pos = __getTouchPosition(event, 0);
				__sendOrPlanRelativeMove({
					"x": (pos.x - __relative_touch_pos.x),
					"y": (pos.y - __relative_touch_pos.y),
				});
				__relative_touch_pos = pos;
			}
		}
	};

	var __streamTouchEndHandler = function(event) {
		event.preventDefault();
		__sendPlannedMove();
	};

	var __getTouchPosition = function(event, index) {
		if (event.touches[index].target && event.touches[index].target.getBoundingClientRect) {
			let rect = event.touches[index].target.getBoundingClientRect();
			return {
				"x": Math.round(event.touches[index].clientX - rect.left),
				"y": Math.round(event.touches[index].clientY - rect.top),
			};
		}
		return null;
	};

	var __streamMoveHandler = function(event) {
		if (__absolute) {
			let rect = event.target.getBoundingClientRect();
			__planned_pos = {
				"x": Math.max(Math.round(event.clientX - rect.left), 0),
				"y": Math.max(Math.round(event.clientY - rect.top), 0),
			};
		} else if (__isRelativeCaptured()) {
			__sendOrPlanRelativeMove({
				"x": event.movementX,
				"y": event.movementY,
			});
		}
	};

	var __streamScrollHandler = function(event) {
		// https://learn.javascript.ru/mousewheel
		// https://stackoverflow.com/a/24595588

		event.preventDefault();

		if (!__absolute && !__isRelativeCaptured()) {
			return;
		}

		let delta = {"x": 0, "y": 0};
		if ($("hid-mouse-cumulative-scrolling-switch").checked) {
			let factor = (tools.browser.is_mac ? 5 : 1);

			__scroll_delta.x += event.deltaX * factor; // Horizontal scrolling
			if (Math.abs(__scroll_delta.x) >= 100) {
				delta.x = __scroll_delta.x / Math.abs(__scroll_delta.x) * (-__scroll_rate);
				__scroll_delta.x = 0;
			}

			__scroll_delta.y += event.deltaY * factor; // Vertical scrolling
			if (Math.abs(__scroll_delta.y) >= 100) {
				delta.y = __scroll_delta.y / Math.abs(__scroll_delta.y) * (-__scroll_rate);
				__scroll_delta.y = 0;
			}
		} else {
			if (event.deltaX !== 0) {
				delta.x = event.deltaX / Math.abs(event.deltaX) * (-__scroll_rate);
			}
			if (event.deltaY !== 0) {
				delta.y = event.deltaY / Math.abs(event.deltaY) * (-__scroll_rate);
			}
		}

		__sendScroll(delta);
	};

	var __sendOrPlanRelativeMove = function(delta) {
		delta = {
			"x": Math.min(Math.max(-127, Math.floor(delta.x * __relative_sens)), 127),
			"y": Math.min(Math.max(-127, Math.floor(delta.y * __relative_sens)), 127),
		};
		if (delta.x || delta.y) {
			if ($("hid-mouse-squash-switch").checked) {
				__relative_deltas.push(delta);
			} else {
				tools.debug("Mouse: relative:", delta);
				__sendEvent("mouse_relative", {"delta": delta});
			}
		}
	};

	var __sendScroll = function(delta) {
		if (delta.x || delta.y) {
			if ($("hid-mouse-reverse-scrolling-switch").checked) {
				delta.y *= -1;
			}
			if ($("hid-mouse-reverse-panning-switch").checked) {
				delta.x *= -1;
			}
			tools.debug("Mouse: scrolled:", delta);
			__sendEvent("mouse_wheel", {"delta": delta});
		}
	};

	var __sendPlannedMove = function() {
		if (__absolute) {
			let pos = __planned_pos;
			if (pos.x !== __sent_pos.x || pos.y !== __sent_pos.y) {
				let geo = __getGeometry();
				let to = {
					"x": tools.remap(pos.x, geo.x, geo.width, -32768, 32767),
					"y": tools.remap(pos.y, geo.y, geo.height, -32768, 32767),
				};
				tools.debug("Mouse: moved:", to);
				__sendEvent("mouse_move", {"to": to});
				__sent_pos = pos;
			}
		} else if (__relative_deltas.length) {
			tools.debug("Mouse: relative:", __relative_deltas);
			__sendEvent("mouse_relative", {"delta": __relative_deltas, "squash": true});
			__relative_deltas = [];
		}
	};

	var __sendButton = function(button, state) {
		tools.debug("Mouse: button", (state ? "pressed:" : "released:"), button);
		__sendPlannedMove();
		__sendEvent("mouse_button", {"button": button, "state": state});
	};

	var __sendEvent = function(event_type, event) {
		event = {"event_type": event_type, "event": event};
		if (__ws && !$("hid-mute-switch").checked) {
			__ws.sendHidEvent(event);
		}
		__recordWsEvent(event);
	};

	__init__();
}