]> git.proxmox.com Git - mirror_novnc.git/blob - app/ui.js
Fix focus problem after closing the toolbar
[mirror_novnc.git] / app / ui.js
1 /*
2 * noVNC: HTML5 VNC client
3 * Copyright (C) 2019 The noVNC Authors
4 * Licensed under MPL 2.0 (see LICENSE.txt)
5 *
6 * See README.md for usage and integration instructions.
7 */
8
9 import * as Log from '../core/util/logging.js';
10 import _, { l10n } from './localization.js';
11 import { isTouchDevice, isSafari, hasScrollbarGutter, dragThreshold }
12 from '../core/util/browser.js';
13 import { setCapture, getPointerEvent } from '../core/util/events.js';
14 import KeyTable from "../core/input/keysym.js";
15 import keysyms from "../core/input/keysymdef.js";
16 import Keyboard from "../core/input/keyboard.js";
17 import RFB from "../core/rfb.js";
18 import * as WebUtil from "./webutil.js";
19
20 const PAGE_TITLE = "noVNC";
21
22 const UI = {
23
24 connected: false,
25 desktopName: "",
26
27 statusTimeout: null,
28 hideKeyboardTimeout: null,
29 idleControlbarTimeout: null,
30 closeControlbarTimeout: null,
31
32 controlbarGrabbed: false,
33 controlbarDrag: false,
34 controlbarMouseDownClientY: 0,
35 controlbarMouseDownOffsetY: 0,
36
37 lastKeyboardinput: null,
38 defaultKeyboardinputLen: 100,
39
40 inhibit_reconnect: true,
41 reconnect_callback: null,
42 reconnect_password: null,
43
44 prime() {
45 return WebUtil.initSettings().then(() => {
46 if (document.readyState === "interactive" || document.readyState === "complete") {
47 return UI.start();
48 }
49
50 return new Promise((resolve, reject) => {
51 document.addEventListener('DOMContentLoaded', () => UI.start().then(resolve).catch(reject));
52 });
53 });
54 },
55
56 // Render default UI and initialize settings menu
57 start() {
58
59 UI.initSettings();
60
61 // Translate the DOM
62 l10n.translateDOM();
63
64 WebUtil.fetchJSON('./package.json')
65 .then((packageInfo) => {
66 Array.from(document.getElementsByClassName('noVNC_version')).forEach(el => el.innerText = packageInfo.version);
67 })
68 .catch((err) => {
69 Log.Error("Couldn't fetch package.json: " + err);
70 Array.from(document.getElementsByClassName('noVNC_version_wrapper'))
71 .concat(Array.from(document.getElementsByClassName('noVNC_version_separator')))
72 .forEach(el => el.style.display = 'none');
73 });
74
75 // Adapt the interface for touch screen devices
76 if (isTouchDevice) {
77 document.documentElement.classList.add("noVNC_touch");
78 // Remove the address bar
79 setTimeout(() => window.scrollTo(0, 1), 100);
80 }
81
82 // Restore control bar position
83 if (WebUtil.readSetting('controlbar_pos') === 'right') {
84 UI.toggleControlbarSide();
85 }
86
87 UI.initFullscreen();
88
89 // Setup event handlers
90 UI.addControlbarHandlers();
91 UI.addTouchSpecificHandlers();
92 UI.addExtraKeysHandlers();
93 UI.addMachineHandlers();
94 UI.addConnectionControlHandlers();
95 UI.addClipboardHandlers();
96 UI.addSettingsHandlers();
97 document.getElementById("noVNC_status")
98 .addEventListener('click', UI.hideStatus);
99
100 // Bootstrap fallback input handler
101 UI.keyboardinputReset();
102
103 UI.openControlbar();
104
105 UI.updateVisualState('init');
106
107 document.documentElement.classList.remove("noVNC_loading");
108
109 let autoconnect = WebUtil.getConfigVar('autoconnect', false);
110 if (autoconnect === 'true' || autoconnect == '1') {
111 autoconnect = true;
112 UI.connect();
113 } else {
114 autoconnect = false;
115 // Show the connect panel on first load unless autoconnecting
116 UI.openConnectPanel();
117 }
118
119 return Promise.resolve(UI.rfb);
120 },
121
122 initFullscreen() {
123 // Only show the button if fullscreen is properly supported
124 // * Safari doesn't support alphanumerical input while in fullscreen
125 if (!isSafari() &&
126 (document.documentElement.requestFullscreen ||
127 document.documentElement.mozRequestFullScreen ||
128 document.documentElement.webkitRequestFullscreen ||
129 document.body.msRequestFullscreen)) {
130 document.getElementById('noVNC_fullscreen_button')
131 .classList.remove("noVNC_hidden");
132 UI.addFullscreenHandlers();
133 }
134 },
135
136 initSettings() {
137 // Logging selection dropdown
138 const llevels = ['error', 'warn', 'info', 'debug'];
139 for (let i = 0; i < llevels.length; i += 1) {
140 UI.addOption(document.getElementById('noVNC_setting_logging'), llevels[i], llevels[i]);
141 }
142
143 // Settings with immediate effects
144 UI.initSetting('logging', 'warn');
145 UI.updateLogging();
146
147 // if port == 80 (or 443) then it won't be present and should be
148 // set manually
149 let port = window.location.port;
150 if (!port) {
151 if (window.location.protocol.substring(0, 5) == 'https') {
152 port = 443;
153 } else if (window.location.protocol.substring(0, 4) == 'http') {
154 port = 80;
155 }
156 }
157
158 /* Populate the controls if defaults are provided in the URL */
159 UI.initSetting('host', window.location.hostname);
160 UI.initSetting('port', port);
161 UI.initSetting('encrypt', (window.location.protocol === "https:"));
162 UI.initSetting('view_clip', false);
163 UI.initSetting('resize', 'off');
164 UI.initSetting('quality', 6);
165 UI.initSetting('shared', true);
166 UI.initSetting('view_only', false);
167 UI.initSetting('show_dot', false);
168 UI.initSetting('path', 'websockify');
169 UI.initSetting('repeaterID', '');
170 UI.initSetting('reconnect', false);
171 UI.initSetting('reconnect_delay', 5000);
172
173 UI.setupSettingLabels();
174 },
175 // Adds a link to the label elements on the corresponding input elements
176 setupSettingLabels() {
177 const labels = document.getElementsByTagName('LABEL');
178 for (let i = 0; i < labels.length; i++) {
179 const htmlFor = labels[i].htmlFor;
180 if (htmlFor != '') {
181 const elem = document.getElementById(htmlFor);
182 if (elem) elem.label = labels[i];
183 } else {
184 // If 'for' isn't set, use the first input element child
185 const children = labels[i].children;
186 for (let j = 0; j < children.length; j++) {
187 if (children[j].form !== undefined) {
188 children[j].label = labels[i];
189 break;
190 }
191 }
192 }
193 }
194 },
195
196 /* ------^-------
197 * /INIT
198 * ==============
199 * EVENT HANDLERS
200 * ------v------*/
201
202 addControlbarHandlers() {
203 document.getElementById("noVNC_control_bar")
204 .addEventListener('mousemove', UI.activateControlbar);
205 document.getElementById("noVNC_control_bar")
206 .addEventListener('mouseup', UI.activateControlbar);
207 document.getElementById("noVNC_control_bar")
208 .addEventListener('mousedown', UI.activateControlbar);
209 document.getElementById("noVNC_control_bar")
210 .addEventListener('keydown', UI.activateControlbar);
211
212 document.getElementById("noVNC_control_bar")
213 .addEventListener('mousedown', UI.keepControlbar);
214 document.getElementById("noVNC_control_bar")
215 .addEventListener('keydown', UI.keepControlbar);
216
217 document.getElementById("noVNC_view_drag_button")
218 .addEventListener('click', UI.toggleViewDrag);
219
220 document.getElementById("noVNC_control_bar_handle")
221 .addEventListener('mousedown', UI.controlbarHandleMouseDown);
222 document.getElementById("noVNC_control_bar_handle")
223 .addEventListener('mouseup', UI.controlbarHandleMouseUp);
224 document.getElementById("noVNC_control_bar_handle")
225 .addEventListener('mousemove', UI.dragControlbarHandle);
226 // resize events aren't available for elements
227 window.addEventListener('resize', UI.updateControlbarHandle);
228
229 const exps = document.getElementsByClassName("noVNC_expander");
230 for (let i = 0;i < exps.length;i++) {
231 exps[i].addEventListener('click', UI.toggleExpander);
232 }
233 },
234
235 addTouchSpecificHandlers() {
236 document.getElementById("noVNC_mouse_button0")
237 .addEventListener('click', () => UI.setMouseButton(1));
238 document.getElementById("noVNC_mouse_button1")
239 .addEventListener('click', () => UI.setMouseButton(2));
240 document.getElementById("noVNC_mouse_button2")
241 .addEventListener('click', () => UI.setMouseButton(4));
242 document.getElementById("noVNC_mouse_button4")
243 .addEventListener('click', () => UI.setMouseButton(0));
244 document.getElementById("noVNC_keyboard_button")
245 .addEventListener('click', UI.toggleVirtualKeyboard);
246
247 UI.touchKeyboard = new Keyboard(document.getElementById('noVNC_keyboardinput'));
248 UI.touchKeyboard.onkeyevent = UI.keyEvent;
249 UI.touchKeyboard.grab();
250 document.getElementById("noVNC_keyboardinput")
251 .addEventListener('input', UI.keyInput);
252 document.getElementById("noVNC_keyboardinput")
253 .addEventListener('focus', UI.onfocusVirtualKeyboard);
254 document.getElementById("noVNC_keyboardinput")
255 .addEventListener('blur', UI.onblurVirtualKeyboard);
256 document.getElementById("noVNC_keyboardinput")
257 .addEventListener('submit', () => false);
258
259 document.documentElement
260 .addEventListener('mousedown', UI.keepVirtualKeyboard, true);
261
262 document.getElementById("noVNC_control_bar")
263 .addEventListener('touchstart', UI.activateControlbar);
264 document.getElementById("noVNC_control_bar")
265 .addEventListener('touchmove', UI.activateControlbar);
266 document.getElementById("noVNC_control_bar")
267 .addEventListener('touchend', UI.activateControlbar);
268 document.getElementById("noVNC_control_bar")
269 .addEventListener('input', UI.activateControlbar);
270
271 document.getElementById("noVNC_control_bar")
272 .addEventListener('touchstart', UI.keepControlbar);
273 document.getElementById("noVNC_control_bar")
274 .addEventListener('input', UI.keepControlbar);
275
276 document.getElementById("noVNC_control_bar_handle")
277 .addEventListener('touchstart', UI.controlbarHandleMouseDown);
278 document.getElementById("noVNC_control_bar_handle")
279 .addEventListener('touchend', UI.controlbarHandleMouseUp);
280 document.getElementById("noVNC_control_bar_handle")
281 .addEventListener('touchmove', UI.dragControlbarHandle);
282 },
283
284 addExtraKeysHandlers() {
285 document.getElementById("noVNC_toggle_extra_keys_button")
286 .addEventListener('click', UI.toggleExtraKeys);
287 document.getElementById("noVNC_toggle_ctrl_button")
288 .addEventListener('click', UI.toggleCtrl);
289 document.getElementById("noVNC_toggle_windows_button")
290 .addEventListener('click', UI.toggleWindows);
291 document.getElementById("noVNC_toggle_alt_button")
292 .addEventListener('click', UI.toggleAlt);
293 document.getElementById("noVNC_send_tab_button")
294 .addEventListener('click', UI.sendTab);
295 document.getElementById("noVNC_send_esc_button")
296 .addEventListener('click', UI.sendEsc);
297 document.getElementById("noVNC_send_ctrl_alt_del_button")
298 .addEventListener('click', UI.sendCtrlAltDel);
299 },
300
301 addMachineHandlers() {
302 document.getElementById("noVNC_shutdown_button")
303 .addEventListener('click', () => UI.rfb.machineShutdown());
304 document.getElementById("noVNC_reboot_button")
305 .addEventListener('click', () => UI.rfb.machineReboot());
306 document.getElementById("noVNC_reset_button")
307 .addEventListener('click', () => UI.rfb.machineReset());
308 document.getElementById("noVNC_power_button")
309 .addEventListener('click', UI.togglePowerPanel);
310 },
311
312 addConnectionControlHandlers() {
313 document.getElementById("noVNC_disconnect_button")
314 .addEventListener('click', UI.disconnect);
315 document.getElementById("noVNC_connect_button")
316 .addEventListener('click', UI.connect);
317 document.getElementById("noVNC_cancel_reconnect_button")
318 .addEventListener('click', UI.cancelReconnect);
319
320 document.getElementById("noVNC_credentials_button")
321 .addEventListener('click', UI.setCredentials);
322 },
323
324 addClipboardHandlers() {
325 document.getElementById("noVNC_clipboard_button")
326 .addEventListener('click', UI.toggleClipboardPanel);
327 document.getElementById("noVNC_clipboard_text")
328 .addEventListener('change', UI.clipboardSend);
329 document.getElementById("noVNC_clipboard_clear_button")
330 .addEventListener('click', UI.clipboardClear);
331 },
332
333 // Add a call to save settings when the element changes,
334 // unless the optional parameter changeFunc is used instead.
335 addSettingChangeHandler(name, changeFunc) {
336 const settingElem = document.getElementById("noVNC_setting_" + name);
337 if (changeFunc === undefined) {
338 changeFunc = () => UI.saveSetting(name);
339 }
340 settingElem.addEventListener('change', changeFunc);
341 },
342
343 addSettingsHandlers() {
344 document.getElementById("noVNC_settings_button")
345 .addEventListener('click', UI.toggleSettingsPanel);
346
347 UI.addSettingChangeHandler('encrypt');
348 UI.addSettingChangeHandler('resize');
349 UI.addSettingChangeHandler('resize', UI.applyResizeMode);
350 UI.addSettingChangeHandler('resize', UI.updateViewClip);
351 UI.addSettingChangeHandler('quality');
352 UI.addSettingChangeHandler('quality', UI.updateQuality);
353 UI.addSettingChangeHandler('view_clip');
354 UI.addSettingChangeHandler('view_clip', UI.updateViewClip);
355 UI.addSettingChangeHandler('shared');
356 UI.addSettingChangeHandler('view_only');
357 UI.addSettingChangeHandler('view_only', UI.updateViewOnly);
358 UI.addSettingChangeHandler('show_dot');
359 UI.addSettingChangeHandler('show_dot', UI.updateShowDotCursor);
360 UI.addSettingChangeHandler('host');
361 UI.addSettingChangeHandler('port');
362 UI.addSettingChangeHandler('path');
363 UI.addSettingChangeHandler('repeaterID');
364 UI.addSettingChangeHandler('logging');
365 UI.addSettingChangeHandler('logging', UI.updateLogging);
366 UI.addSettingChangeHandler('reconnect');
367 UI.addSettingChangeHandler('reconnect_delay');
368 },
369
370 addFullscreenHandlers() {
371 document.getElementById("noVNC_fullscreen_button")
372 .addEventListener('click', UI.toggleFullscreen);
373
374 window.addEventListener('fullscreenchange', UI.updateFullscreenButton);
375 window.addEventListener('mozfullscreenchange', UI.updateFullscreenButton);
376 window.addEventListener('webkitfullscreenchange', UI.updateFullscreenButton);
377 window.addEventListener('msfullscreenchange', UI.updateFullscreenButton);
378 },
379
380 /* ------^-------
381 * /EVENT HANDLERS
382 * ==============
383 * VISUAL
384 * ------v------*/
385
386 // Disable/enable controls depending on connection state
387 updateVisualState(state) {
388
389 document.documentElement.classList.remove("noVNC_connecting");
390 document.documentElement.classList.remove("noVNC_connected");
391 document.documentElement.classList.remove("noVNC_disconnecting");
392 document.documentElement.classList.remove("noVNC_reconnecting");
393
394 const transition_elem = document.getElementById("noVNC_transition_text");
395 switch (state) {
396 case 'init':
397 break;
398 case 'connecting':
399 transition_elem.textContent = _("Connecting...");
400 document.documentElement.classList.add("noVNC_connecting");
401 break;
402 case 'connected':
403 document.documentElement.classList.add("noVNC_connected");
404 break;
405 case 'disconnecting':
406 transition_elem.textContent = _("Disconnecting...");
407 document.documentElement.classList.add("noVNC_disconnecting");
408 break;
409 case 'disconnected':
410 break;
411 case 'reconnecting':
412 transition_elem.textContent = _("Reconnecting...");
413 document.documentElement.classList.add("noVNC_reconnecting");
414 break;
415 default:
416 Log.Error("Invalid visual state: " + state);
417 UI.showStatus(_("Internal error"), 'error');
418 return;
419 }
420
421 if (UI.connected) {
422 UI.updateViewClip();
423
424 UI.disableSetting('encrypt');
425 UI.disableSetting('shared');
426 UI.disableSetting('host');
427 UI.disableSetting('port');
428 UI.disableSetting('path');
429 UI.disableSetting('repeaterID');
430 UI.setMouseButton(1);
431
432 // Hide the controlbar after 2 seconds
433 UI.closeControlbarTimeout = setTimeout(UI.closeControlbar, 2000);
434 } else {
435 UI.enableSetting('encrypt');
436 UI.enableSetting('shared');
437 UI.enableSetting('host');
438 UI.enableSetting('port');
439 UI.enableSetting('path');
440 UI.enableSetting('repeaterID');
441 UI.updatePowerButton();
442 UI.keepControlbar();
443 }
444
445 // State change closes the password dialog
446 document.getElementById('noVNC_credentials_dlg')
447 .classList.remove('noVNC_open');
448 },
449
450 showStatus(text, status_type, time) {
451 const statusElem = document.getElementById('noVNC_status');
452
453 if (typeof status_type === 'undefined') {
454 status_type = 'normal';
455 }
456
457 // Don't overwrite more severe visible statuses and never
458 // errors. Only shows the first error.
459 if (statusElem.classList.contains("noVNC_open")) {
460 if (statusElem.classList.contains("noVNC_status_error")) {
461 return;
462 }
463 if (statusElem.classList.contains("noVNC_status_warn") &&
464 status_type === 'normal') {
465 return;
466 }
467 }
468
469 clearTimeout(UI.statusTimeout);
470
471 switch (status_type) {
472 case 'error':
473 statusElem.classList.remove("noVNC_status_warn");
474 statusElem.classList.remove("noVNC_status_normal");
475 statusElem.classList.add("noVNC_status_error");
476 break;
477 case 'warning':
478 case 'warn':
479 statusElem.classList.remove("noVNC_status_error");
480 statusElem.classList.remove("noVNC_status_normal");
481 statusElem.classList.add("noVNC_status_warn");
482 break;
483 case 'normal':
484 case 'info':
485 default:
486 statusElem.classList.remove("noVNC_status_error");
487 statusElem.classList.remove("noVNC_status_warn");
488 statusElem.classList.add("noVNC_status_normal");
489 break;
490 }
491
492 statusElem.textContent = text;
493 statusElem.classList.add("noVNC_open");
494
495 // If no time was specified, show the status for 1.5 seconds
496 if (typeof time === 'undefined') {
497 time = 1500;
498 }
499
500 // Error messages do not timeout
501 if (status_type !== 'error') {
502 UI.statusTimeout = window.setTimeout(UI.hideStatus, time);
503 }
504 },
505
506 hideStatus() {
507 clearTimeout(UI.statusTimeout);
508 document.getElementById('noVNC_status').classList.remove("noVNC_open");
509 },
510
511 activateControlbar(event) {
512 clearTimeout(UI.idleControlbarTimeout);
513 // We manipulate the anchor instead of the actual control
514 // bar in order to avoid creating new a stacking group
515 document.getElementById('noVNC_control_bar_anchor')
516 .classList.remove("noVNC_idle");
517 UI.idleControlbarTimeout = window.setTimeout(UI.idleControlbar, 2000);
518 },
519
520 idleControlbar() {
521 document.getElementById('noVNC_control_bar_anchor')
522 .classList.add("noVNC_idle");
523 },
524
525 keepControlbar() {
526 clearTimeout(UI.closeControlbarTimeout);
527 },
528
529 openControlbar() {
530 document.getElementById('noVNC_control_bar')
531 .classList.add("noVNC_open");
532 },
533
534 closeControlbar() {
535 UI.closeAllPanels();
536 document.getElementById('noVNC_control_bar')
537 .classList.remove("noVNC_open");
538 UI.rfb.focus();
539 },
540
541 toggleControlbar() {
542 if (document.getElementById('noVNC_control_bar')
543 .classList.contains("noVNC_open")) {
544 UI.closeControlbar();
545 } else {
546 UI.openControlbar();
547 }
548 },
549
550 toggleControlbarSide() {
551 // Temporarily disable animation, if bar is displayed, to avoid weird
552 // movement. The transitionend-event will not fire when display=none.
553 const bar = document.getElementById('noVNC_control_bar');
554 const barDisplayStyle = window.getComputedStyle(bar).display;
555 if (barDisplayStyle !== 'none') {
556 bar.style.transitionDuration = '0s';
557 bar.addEventListener('transitionend', () => bar.style.transitionDuration = '');
558 }
559
560 const anchor = document.getElementById('noVNC_control_bar_anchor');
561 if (anchor.classList.contains("noVNC_right")) {
562 WebUtil.writeSetting('controlbar_pos', 'left');
563 anchor.classList.remove("noVNC_right");
564 } else {
565 WebUtil.writeSetting('controlbar_pos', 'right');
566 anchor.classList.add("noVNC_right");
567 }
568
569 // Consider this a movement of the handle
570 UI.controlbarDrag = true;
571 },
572
573 showControlbarHint(show) {
574 const hint = document.getElementById('noVNC_control_bar_hint');
575 if (show) {
576 hint.classList.add("noVNC_active");
577 } else {
578 hint.classList.remove("noVNC_active");
579 }
580 },
581
582 dragControlbarHandle(e) {
583 if (!UI.controlbarGrabbed) return;
584
585 const ptr = getPointerEvent(e);
586
587 const anchor = document.getElementById('noVNC_control_bar_anchor');
588 if (ptr.clientX < (window.innerWidth * 0.1)) {
589 if (anchor.classList.contains("noVNC_right")) {
590 UI.toggleControlbarSide();
591 }
592 } else if (ptr.clientX > (window.innerWidth * 0.9)) {
593 if (!anchor.classList.contains("noVNC_right")) {
594 UI.toggleControlbarSide();
595 }
596 }
597
598 if (!UI.controlbarDrag) {
599 const dragDistance = Math.abs(ptr.clientY - UI.controlbarMouseDownClientY);
600
601 if (dragDistance < dragThreshold) return;
602
603 UI.controlbarDrag = true;
604 }
605
606 const eventY = ptr.clientY - UI.controlbarMouseDownOffsetY;
607
608 UI.moveControlbarHandle(eventY);
609
610 e.preventDefault();
611 e.stopPropagation();
612 UI.keepControlbar();
613 UI.activateControlbar();
614 },
615
616 // Move the handle but don't allow any position outside the bounds
617 moveControlbarHandle(viewportRelativeY) {
618 const handle = document.getElementById("noVNC_control_bar_handle");
619 const handleHeight = handle.getBoundingClientRect().height;
620 const controlbarBounds = document.getElementById("noVNC_control_bar")
621 .getBoundingClientRect();
622 const margin = 10;
623
624 // These heights need to be non-zero for the below logic to work
625 if (handleHeight === 0 || controlbarBounds.height === 0) {
626 return;
627 }
628
629 let newY = viewportRelativeY;
630
631 // Check if the coordinates are outside the control bar
632 if (newY < controlbarBounds.top + margin) {
633 // Force coordinates to be below the top of the control bar
634 newY = controlbarBounds.top + margin;
635
636 } else if (newY > controlbarBounds.top +
637 controlbarBounds.height - handleHeight - margin) {
638 // Force coordinates to be above the bottom of the control bar
639 newY = controlbarBounds.top +
640 controlbarBounds.height - handleHeight - margin;
641 }
642
643 // Corner case: control bar too small for stable position
644 if (controlbarBounds.height < (handleHeight + margin * 2)) {
645 newY = controlbarBounds.top +
646 (controlbarBounds.height - handleHeight) / 2;
647 }
648
649 // The transform needs coordinates that are relative to the parent
650 const parentRelativeY = newY - controlbarBounds.top;
651 handle.style.transform = "translateY(" + parentRelativeY + "px)";
652 },
653
654 updateControlbarHandle() {
655 // Since the control bar is fixed on the viewport and not the page,
656 // the move function expects coordinates relative the the viewport.
657 const handle = document.getElementById("noVNC_control_bar_handle");
658 const handleBounds = handle.getBoundingClientRect();
659 UI.moveControlbarHandle(handleBounds.top);
660 },
661
662 controlbarHandleMouseUp(e) {
663 if ((e.type == "mouseup") && (e.button != 0)) return;
664
665 // mouseup and mousedown on the same place toggles the controlbar
666 if (UI.controlbarGrabbed && !UI.controlbarDrag) {
667 UI.toggleControlbar();
668 e.preventDefault();
669 e.stopPropagation();
670 UI.keepControlbar();
671 UI.activateControlbar();
672 }
673 UI.controlbarGrabbed = false;
674 UI.showControlbarHint(false);
675 },
676
677 controlbarHandleMouseDown(e) {
678 if ((e.type == "mousedown") && (e.button != 0)) return;
679
680 const ptr = getPointerEvent(e);
681
682 const handle = document.getElementById("noVNC_control_bar_handle");
683 const bounds = handle.getBoundingClientRect();
684
685 // Touch events have implicit capture
686 if (e.type === "mousedown") {
687 setCapture(handle);
688 }
689
690 UI.controlbarGrabbed = true;
691 UI.controlbarDrag = false;
692
693 UI.showControlbarHint(true);
694
695 UI.controlbarMouseDownClientY = ptr.clientY;
696 UI.controlbarMouseDownOffsetY = ptr.clientY - bounds.top;
697 e.preventDefault();
698 e.stopPropagation();
699 UI.keepControlbar();
700 UI.activateControlbar();
701 },
702
703 toggleExpander(e) {
704 if (this.classList.contains("noVNC_open")) {
705 this.classList.remove("noVNC_open");
706 } else {
707 this.classList.add("noVNC_open");
708 }
709 },
710
711 /* ------^-------
712 * /VISUAL
713 * ==============
714 * SETTINGS
715 * ------v------*/
716
717 // Initial page load read/initialization of settings
718 initSetting(name, defVal) {
719 // Check Query string followed by cookie
720 let val = WebUtil.getConfigVar(name);
721 if (val === null) {
722 val = WebUtil.readSetting(name, defVal);
723 }
724 WebUtil.setSetting(name, val);
725 UI.updateSetting(name);
726 return val;
727 },
728
729 // Set the new value, update and disable form control setting
730 forceSetting(name, val) {
731 WebUtil.setSetting(name, val);
732 UI.updateSetting(name);
733 UI.disableSetting(name);
734 },
735
736 // Update cookie and form control setting. If value is not set, then
737 // updates from control to current cookie setting.
738 updateSetting(name) {
739
740 // Update the settings control
741 let value = UI.getSetting(name);
742
743 const ctrl = document.getElementById('noVNC_setting_' + name);
744 if (ctrl.type === 'checkbox') {
745 ctrl.checked = value;
746
747 } else if (typeof ctrl.options !== 'undefined') {
748 for (let i = 0; i < ctrl.options.length; i += 1) {
749 if (ctrl.options[i].value === value) {
750 ctrl.selectedIndex = i;
751 break;
752 }
753 }
754 } else {
755 /*Weird IE9 error leads to 'null' appearring
756 in textboxes instead of ''.*/
757 if (value === null) {
758 value = "";
759 }
760 ctrl.value = value;
761 }
762 },
763
764 // Save control setting to cookie
765 saveSetting(name) {
766 const ctrl = document.getElementById('noVNC_setting_' + name);
767 let val;
768 if (ctrl.type === 'checkbox') {
769 val = ctrl.checked;
770 } else if (typeof ctrl.options !== 'undefined') {
771 val = ctrl.options[ctrl.selectedIndex].value;
772 } else {
773 val = ctrl.value;
774 }
775 WebUtil.writeSetting(name, val);
776 //Log.Debug("Setting saved '" + name + "=" + val + "'");
777 return val;
778 },
779
780 // Read form control compatible setting from cookie
781 getSetting(name) {
782 const ctrl = document.getElementById('noVNC_setting_' + name);
783 let val = WebUtil.readSetting(name);
784 if (typeof val !== 'undefined' && val !== null && ctrl.type === 'checkbox') {
785 if (val.toString().toLowerCase() in {'0': 1, 'no': 1, 'false': 1}) {
786 val = false;
787 } else {
788 val = true;
789 }
790 }
791 return val;
792 },
793
794 // These helpers compensate for the lack of parent-selectors and
795 // previous-sibling-selectors in CSS which are needed when we want to
796 // disable the labels that belong to disabled input elements.
797 disableSetting(name) {
798 const ctrl = document.getElementById('noVNC_setting_' + name);
799 ctrl.disabled = true;
800 ctrl.label.classList.add('noVNC_disabled');
801 },
802
803 enableSetting(name) {
804 const ctrl = document.getElementById('noVNC_setting_' + name);
805 ctrl.disabled = false;
806 ctrl.label.classList.remove('noVNC_disabled');
807 },
808
809 /* ------^-------
810 * /SETTINGS
811 * ==============
812 * PANELS
813 * ------v------*/
814
815 closeAllPanels() {
816 UI.closeSettingsPanel();
817 UI.closePowerPanel();
818 UI.closeClipboardPanel();
819 UI.closeExtraKeys();
820 },
821
822 /* ------^-------
823 * /PANELS
824 * ==============
825 * SETTINGS (panel)
826 * ------v------*/
827
828 openSettingsPanel() {
829 UI.closeAllPanels();
830 UI.openControlbar();
831
832 // Refresh UI elements from saved cookies
833 UI.updateSetting('encrypt');
834 UI.updateSetting('view_clip');
835 UI.updateSetting('resize');
836 UI.updateSetting('quality');
837 UI.updateSetting('shared');
838 UI.updateSetting('view_only');
839 UI.updateSetting('path');
840 UI.updateSetting('repeaterID');
841 UI.updateSetting('logging');
842 UI.updateSetting('reconnect');
843 UI.updateSetting('reconnect_delay');
844
845 document.getElementById('noVNC_settings')
846 .classList.add("noVNC_open");
847 document.getElementById('noVNC_settings_button')
848 .classList.add("noVNC_selected");
849 },
850
851 closeSettingsPanel() {
852 document.getElementById('noVNC_settings')
853 .classList.remove("noVNC_open");
854 document.getElementById('noVNC_settings_button')
855 .classList.remove("noVNC_selected");
856 },
857
858 toggleSettingsPanel() {
859 if (document.getElementById('noVNC_settings')
860 .classList.contains("noVNC_open")) {
861 UI.closeSettingsPanel();
862 } else {
863 UI.openSettingsPanel();
864 }
865 },
866
867 /* ------^-------
868 * /SETTINGS
869 * ==============
870 * POWER
871 * ------v------*/
872
873 openPowerPanel() {
874 UI.closeAllPanels();
875 UI.openControlbar();
876
877 document.getElementById('noVNC_power')
878 .classList.add("noVNC_open");
879 document.getElementById('noVNC_power_button')
880 .classList.add("noVNC_selected");
881 },
882
883 closePowerPanel() {
884 document.getElementById('noVNC_power')
885 .classList.remove("noVNC_open");
886 document.getElementById('noVNC_power_button')
887 .classList.remove("noVNC_selected");
888 },
889
890 togglePowerPanel() {
891 if (document.getElementById('noVNC_power')
892 .classList.contains("noVNC_open")) {
893 UI.closePowerPanel();
894 } else {
895 UI.openPowerPanel();
896 }
897 },
898
899 // Disable/enable power button
900 updatePowerButton() {
901 if (UI.connected &&
902 UI.rfb.capabilities.power &&
903 !UI.rfb.viewOnly) {
904 document.getElementById('noVNC_power_button')
905 .classList.remove("noVNC_hidden");
906 } else {
907 document.getElementById('noVNC_power_button')
908 .classList.add("noVNC_hidden");
909 // Close power panel if open
910 UI.closePowerPanel();
911 }
912 },
913
914 /* ------^-------
915 * /POWER
916 * ==============
917 * CLIPBOARD
918 * ------v------*/
919
920 openClipboardPanel() {
921 UI.closeAllPanels();
922 UI.openControlbar();
923
924 document.getElementById('noVNC_clipboard')
925 .classList.add("noVNC_open");
926 document.getElementById('noVNC_clipboard_button')
927 .classList.add("noVNC_selected");
928 },
929
930 closeClipboardPanel() {
931 document.getElementById('noVNC_clipboard')
932 .classList.remove("noVNC_open");
933 document.getElementById('noVNC_clipboard_button')
934 .classList.remove("noVNC_selected");
935 },
936
937 toggleClipboardPanel() {
938 if (document.getElementById('noVNC_clipboard')
939 .classList.contains("noVNC_open")) {
940 UI.closeClipboardPanel();
941 } else {
942 UI.openClipboardPanel();
943 }
944 },
945
946 clipboardReceive(e) {
947 Log.Debug(">> UI.clipboardReceive: " + e.detail.text.substr(0, 40) + "...");
948 document.getElementById('noVNC_clipboard_text').value = e.detail.text;
949 Log.Debug("<< UI.clipboardReceive");
950 },
951
952 clipboardClear() {
953 document.getElementById('noVNC_clipboard_text').value = "";
954 UI.rfb.clipboardPasteFrom("");
955 },
956
957 clipboardSend() {
958 const text = document.getElementById('noVNC_clipboard_text').value;
959 Log.Debug(">> UI.clipboardSend: " + text.substr(0, 40) + "...");
960 UI.rfb.clipboardPasteFrom(text);
961 Log.Debug("<< UI.clipboardSend");
962 },
963
964 /* ------^-------
965 * /CLIPBOARD
966 * ==============
967 * CONNECTION
968 * ------v------*/
969
970 openConnectPanel() {
971 document.getElementById('noVNC_connect_dlg')
972 .classList.add("noVNC_open");
973 },
974
975 closeConnectPanel() {
976 document.getElementById('noVNC_connect_dlg')
977 .classList.remove("noVNC_open");
978 },
979
980 connect(event, password) {
981
982 // Ignore when rfb already exists
983 if (typeof UI.rfb !== 'undefined') {
984 return;
985 }
986
987 const host = UI.getSetting('host');
988 const port = UI.getSetting('port');
989 const path = UI.getSetting('path');
990
991 if (typeof password === 'undefined') {
992 password = WebUtil.getConfigVar('password');
993 UI.reconnect_password = password;
994 }
995
996 if (password === null) {
997 password = undefined;
998 }
999
1000 UI.hideStatus();
1001
1002 if (!host) {
1003 Log.Error("Can't connect when host is: " + host);
1004 UI.showStatus(_("Must set host"), 'error');
1005 return;
1006 }
1007
1008 UI.closeAllPanels();
1009 UI.closeConnectPanel();
1010
1011 UI.updateVisualState('connecting');
1012
1013 let url;
1014
1015 url = UI.getSetting('encrypt') ? 'wss' : 'ws';
1016
1017 url += '://' + host;
1018 if (port) {
1019 url += ':' + port;
1020 }
1021 url += '/' + path;
1022
1023 UI.rfb = new RFB(document.getElementById('noVNC_container'), url,
1024 { shared: UI.getSetting('shared'),
1025 repeaterID: UI.getSetting('repeaterID'),
1026 credentials: { password: password } });
1027 UI.rfb.addEventListener("connect", UI.connectFinished);
1028 UI.rfb.addEventListener("disconnect", UI.disconnectFinished);
1029 UI.rfb.addEventListener("credentialsrequired", UI.credentials);
1030 UI.rfb.addEventListener("securityfailure", UI.securityFailed);
1031 UI.rfb.addEventListener("capabilities", UI.updatePowerButton);
1032 UI.rfb.addEventListener("clipboard", UI.clipboardReceive);
1033 UI.rfb.addEventListener("bell", UI.bell);
1034 UI.rfb.addEventListener("desktopname", UI.updateDesktopName);
1035 UI.rfb.clipViewport = UI.getSetting('view_clip');
1036 UI.rfb.scaleViewport = UI.getSetting('resize') === 'scale';
1037 UI.rfb.resizeSession = UI.getSetting('resize') === 'remote';
1038 UI.rfb.qualityLevel = parseInt(UI.getSetting('quality'));
1039 UI.rfb.showDotCursor = UI.getSetting('show_dot');
1040
1041 UI.updateViewOnly(); // requires UI.rfb
1042 },
1043
1044 disconnect() {
1045 UI.closeAllPanels();
1046 UI.rfb.disconnect();
1047
1048 UI.connected = false;
1049
1050 // Disable automatic reconnecting
1051 UI.inhibit_reconnect = true;
1052
1053 UI.updateVisualState('disconnecting');
1054
1055 // Don't display the connection settings until we're actually disconnected
1056 },
1057
1058 reconnect() {
1059 UI.reconnect_callback = null;
1060
1061 // if reconnect has been disabled in the meantime, do nothing.
1062 if (UI.inhibit_reconnect) {
1063 return;
1064 }
1065
1066 UI.connect(null, UI.reconnect_password);
1067 },
1068
1069 cancelReconnect() {
1070 if (UI.reconnect_callback !== null) {
1071 clearTimeout(UI.reconnect_callback);
1072 UI.reconnect_callback = null;
1073 }
1074
1075 UI.updateVisualState('disconnected');
1076
1077 UI.openControlbar();
1078 UI.openConnectPanel();
1079 },
1080
1081 connectFinished(e) {
1082 UI.connected = true;
1083 UI.inhibit_reconnect = false;
1084
1085 let msg;
1086 if (UI.getSetting('encrypt')) {
1087 msg = _("Connected (encrypted) to ") + UI.desktopName;
1088 } else {
1089 msg = _("Connected (unencrypted) to ") + UI.desktopName;
1090 }
1091 UI.showStatus(msg);
1092 UI.updateVisualState('connected');
1093
1094 // Do this last because it can only be used on rendered elements
1095 UI.rfb.focus();
1096 },
1097
1098 disconnectFinished(e) {
1099 const wasConnected = UI.connected;
1100
1101 // This variable is ideally set when disconnection starts, but
1102 // when the disconnection isn't clean or if it is initiated by
1103 // the server, we need to do it here as well since
1104 // UI.disconnect() won't be used in those cases.
1105 UI.connected = false;
1106
1107 UI.rfb = undefined;
1108
1109 if (!e.detail.clean) {
1110 UI.updateVisualState('disconnected');
1111 if (wasConnected) {
1112 UI.showStatus(_("Something went wrong, connection is closed"),
1113 'error');
1114 } else {
1115 UI.showStatus(_("Failed to connect to server"), 'error');
1116 }
1117 } else if (UI.getSetting('reconnect', false) === true && !UI.inhibit_reconnect) {
1118 UI.updateVisualState('reconnecting');
1119
1120 const delay = parseInt(UI.getSetting('reconnect_delay'));
1121 UI.reconnect_callback = setTimeout(UI.reconnect, delay);
1122 return;
1123 } else {
1124 UI.updateVisualState('disconnected');
1125 UI.showStatus(_("Disconnected"), 'normal');
1126 }
1127
1128 document.title = PAGE_TITLE;
1129
1130 UI.openControlbar();
1131 UI.openConnectPanel();
1132 },
1133
1134 securityFailed(e) {
1135 let msg = "";
1136 // On security failures we might get a string with a reason
1137 // directly from the server. Note that we can't control if
1138 // this string is translated or not.
1139 if ('reason' in e.detail) {
1140 msg = _("New connection has been rejected with reason: ") +
1141 e.detail.reason;
1142 } else {
1143 msg = _("New connection has been rejected");
1144 }
1145 UI.showStatus(msg, 'error');
1146 },
1147
1148 /* ------^-------
1149 * /CONNECTION
1150 * ==============
1151 * PASSWORD
1152 * ------v------*/
1153
1154 credentials(e) {
1155 // FIXME: handle more types
1156
1157 document.getElementById("noVNC_username_block").classList.remove("noVNC_hidden");
1158 document.getElementById("noVNC_password_block").classList.remove("noVNC_hidden");
1159
1160 let inputFocus = "none";
1161 if (e.detail.types.indexOf("username") === -1) {
1162 document.getElementById("noVNC_username_block").classList.add("noVNC_hidden");
1163 } else {
1164 inputFocus = inputFocus === "none" ? "noVNC_username_input" : inputFocus;
1165 }
1166 if (e.detail.types.indexOf("password") === -1) {
1167 document.getElementById("noVNC_password_block").classList.add("noVNC_hidden");
1168 } else {
1169 inputFocus = inputFocus === "none" ? "noVNC_password_input" : inputFocus;
1170 }
1171 document.getElementById('noVNC_credentials_dlg')
1172 .classList.add('noVNC_open');
1173
1174 setTimeout(() => document
1175 .getElementById(inputFocus).focus(), 100);
1176
1177 Log.Warn("Server asked for credentials");
1178 UI.showStatus(_("Credentials are required"), "warning");
1179 },
1180
1181 setCredentials(e) {
1182 // Prevent actually submitting the form
1183 e.preventDefault();
1184
1185 let inputElemUsername = document.getElementById('noVNC_username_input');
1186 const username = inputElemUsername.value;
1187
1188 let inputElemPassword = document.getElementById('noVNC_password_input');
1189 const password = inputElemPassword.value;
1190 // Clear the input after reading the password
1191 inputElemPassword.value = "";
1192
1193 UI.rfb.sendCredentials({ username: username, password: password });
1194 UI.reconnect_password = password;
1195 document.getElementById('noVNC_credentials_dlg')
1196 .classList.remove('noVNC_open');
1197 },
1198
1199 /* ------^-------
1200 * /PASSWORD
1201 * ==============
1202 * FULLSCREEN
1203 * ------v------*/
1204
1205 toggleFullscreen() {
1206 if (document.fullscreenElement || // alternative standard method
1207 document.mozFullScreenElement || // currently working methods
1208 document.webkitFullscreenElement ||
1209 document.msFullscreenElement) {
1210 if (document.exitFullscreen) {
1211 document.exitFullscreen();
1212 } else if (document.mozCancelFullScreen) {
1213 document.mozCancelFullScreen();
1214 } else if (document.webkitExitFullscreen) {
1215 document.webkitExitFullscreen();
1216 } else if (document.msExitFullscreen) {
1217 document.msExitFullscreen();
1218 }
1219 } else {
1220 if (document.documentElement.requestFullscreen) {
1221 document.documentElement.requestFullscreen();
1222 } else if (document.documentElement.mozRequestFullScreen) {
1223 document.documentElement.mozRequestFullScreen();
1224 } else if (document.documentElement.webkitRequestFullscreen) {
1225 document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
1226 } else if (document.body.msRequestFullscreen) {
1227 document.body.msRequestFullscreen();
1228 }
1229 }
1230 UI.updateFullscreenButton();
1231 },
1232
1233 updateFullscreenButton() {
1234 if (document.fullscreenElement || // alternative standard method
1235 document.mozFullScreenElement || // currently working methods
1236 document.webkitFullscreenElement ||
1237 document.msFullscreenElement ) {
1238 document.getElementById('noVNC_fullscreen_button')
1239 .classList.add("noVNC_selected");
1240 } else {
1241 document.getElementById('noVNC_fullscreen_button')
1242 .classList.remove("noVNC_selected");
1243 }
1244 },
1245
1246 /* ------^-------
1247 * /FULLSCREEN
1248 * ==============
1249 * RESIZE
1250 * ------v------*/
1251
1252 // Apply remote resizing or local scaling
1253 applyResizeMode() {
1254 if (!UI.rfb) return;
1255
1256 UI.rfb.scaleViewport = UI.getSetting('resize') === 'scale';
1257 UI.rfb.resizeSession = UI.getSetting('resize') === 'remote';
1258 },
1259
1260 /* ------^-------
1261 * /RESIZE
1262 * ==============
1263 * VIEW CLIPPING
1264 * ------v------*/
1265
1266 // Update viewport clipping property for the connection. The normal
1267 // case is to get the value from the setting. There are special cases
1268 // for when the viewport is scaled or when a touch device is used.
1269 updateViewClip() {
1270 if (!UI.rfb) return;
1271
1272 const scaling = UI.getSetting('resize') === 'scale';
1273
1274 if (scaling) {
1275 // Can't be clipping if viewport is scaled to fit
1276 UI.forceSetting('view_clip', false);
1277 UI.rfb.clipViewport = false;
1278 } else if (!hasScrollbarGutter) {
1279 // Some platforms have scrollbars that are difficult
1280 // to use in our case, so we always use our own panning
1281 UI.forceSetting('view_clip', true);
1282 UI.rfb.clipViewport = true;
1283 } else {
1284 UI.enableSetting('view_clip');
1285 UI.rfb.clipViewport = UI.getSetting('view_clip');
1286 }
1287
1288 // Changing the viewport may change the state of
1289 // the dragging button
1290 UI.updateViewDrag();
1291 },
1292
1293 /* ------^-------
1294 * /VIEW CLIPPING
1295 * ==============
1296 * VIEWDRAG
1297 * ------v------*/
1298
1299 toggleViewDrag() {
1300 if (!UI.rfb) return;
1301
1302 UI.rfb.dragViewport = !UI.rfb.dragViewport;
1303 UI.updateViewDrag();
1304 },
1305
1306 updateViewDrag() {
1307 if (!UI.connected) return;
1308
1309 const viewDragButton = document.getElementById('noVNC_view_drag_button');
1310
1311 if (!UI.rfb.clipViewport && UI.rfb.dragViewport) {
1312 // We are no longer clipping the viewport. Make sure
1313 // viewport drag isn't active when it can't be used.
1314 UI.rfb.dragViewport = false;
1315 }
1316
1317 if (UI.rfb.dragViewport) {
1318 viewDragButton.classList.add("noVNC_selected");
1319 } else {
1320 viewDragButton.classList.remove("noVNC_selected");
1321 }
1322
1323 if (UI.rfb.clipViewport) {
1324 viewDragButton.classList.remove("noVNC_hidden");
1325 } else {
1326 viewDragButton.classList.add("noVNC_hidden");
1327 }
1328 },
1329
1330 /* ------^-------
1331 * /VIEWDRAG
1332 * ==============
1333 * QUALITY
1334 * ------v------*/
1335
1336 updateQuality() {
1337 if (!UI.rfb) return;
1338
1339 UI.rfb.qualityLevel = parseInt(UI.getSetting('quality'));
1340 },
1341
1342 /* ------^-------
1343 * /QUALITY
1344 * ==============
1345 * KEYBOARD
1346 * ------v------*/
1347
1348 showVirtualKeyboard() {
1349 if (!isTouchDevice) return;
1350
1351 const input = document.getElementById('noVNC_keyboardinput');
1352
1353 if (document.activeElement == input) return;
1354
1355 input.focus();
1356
1357 try {
1358 const l = input.value.length;
1359 // Move the caret to the end
1360 input.setSelectionRange(l, l);
1361 } catch (err) {
1362 // setSelectionRange is undefined in Google Chrome
1363 }
1364 },
1365
1366 hideVirtualKeyboard() {
1367 if (!isTouchDevice) return;
1368
1369 const input = document.getElementById('noVNC_keyboardinput');
1370
1371 if (document.activeElement != input) return;
1372
1373 input.blur();
1374 },
1375
1376 toggleVirtualKeyboard() {
1377 if (document.getElementById('noVNC_keyboard_button')
1378 .classList.contains("noVNC_selected")) {
1379 UI.hideVirtualKeyboard();
1380 } else {
1381 UI.showVirtualKeyboard();
1382 }
1383 },
1384
1385 onfocusVirtualKeyboard(event) {
1386 document.getElementById('noVNC_keyboard_button')
1387 .classList.add("noVNC_selected");
1388 if (UI.rfb) {
1389 UI.rfb.focusOnClick = false;
1390 }
1391 },
1392
1393 onblurVirtualKeyboard(event) {
1394 document.getElementById('noVNC_keyboard_button')
1395 .classList.remove("noVNC_selected");
1396 if (UI.rfb) {
1397 UI.rfb.focusOnClick = true;
1398 }
1399 },
1400
1401 keepVirtualKeyboard(event) {
1402 const input = document.getElementById('noVNC_keyboardinput');
1403
1404 // Only prevent focus change if the virtual keyboard is active
1405 if (document.activeElement != input) {
1406 return;
1407 }
1408
1409 // Only allow focus to move to other elements that need
1410 // focus to function properly
1411 if (event.target.form !== undefined) {
1412 switch (event.target.type) {
1413 case 'text':
1414 case 'email':
1415 case 'search':
1416 case 'password':
1417 case 'tel':
1418 case 'url':
1419 case 'textarea':
1420 case 'select-one':
1421 case 'select-multiple':
1422 return;
1423 }
1424 }
1425
1426 event.preventDefault();
1427 },
1428
1429 keyboardinputReset() {
1430 const kbi = document.getElementById('noVNC_keyboardinput');
1431 kbi.value = new Array(UI.defaultKeyboardinputLen).join("_");
1432 UI.lastKeyboardinput = kbi.value;
1433 },
1434
1435 keyEvent(keysym, code, down) {
1436 if (!UI.rfb) return;
1437
1438 UI.rfb.sendKey(keysym, code, down);
1439 },
1440
1441 // When normal keyboard events are left uncought, use the input events from
1442 // the keyboardinput element instead and generate the corresponding key events.
1443 // This code is required since some browsers on Android are inconsistent in
1444 // sending keyCodes in the normal keyboard events when using on screen keyboards.
1445 keyInput(event) {
1446
1447 if (!UI.rfb) return;
1448
1449 const newValue = event.target.value;
1450
1451 if (!UI.lastKeyboardinput) {
1452 UI.keyboardinputReset();
1453 }
1454 const oldValue = UI.lastKeyboardinput;
1455
1456 let newLen;
1457 try {
1458 // Try to check caret position since whitespace at the end
1459 // will not be considered by value.length in some browsers
1460 newLen = Math.max(event.target.selectionStart, newValue.length);
1461 } catch (err) {
1462 // selectionStart is undefined in Google Chrome
1463 newLen = newValue.length;
1464 }
1465 const oldLen = oldValue.length;
1466
1467 let inputs = newLen - oldLen;
1468 let backspaces = inputs < 0 ? -inputs : 0;
1469
1470 // Compare the old string with the new to account for
1471 // text-corrections or other input that modify existing text
1472 for (let i = 0; i < Math.min(oldLen, newLen); i++) {
1473 if (newValue.charAt(i) != oldValue.charAt(i)) {
1474 inputs = newLen - i;
1475 backspaces = oldLen - i;
1476 break;
1477 }
1478 }
1479
1480 // Send the key events
1481 for (let i = 0; i < backspaces; i++) {
1482 UI.rfb.sendKey(KeyTable.XK_BackSpace, "Backspace");
1483 }
1484 for (let i = newLen - inputs; i < newLen; i++) {
1485 UI.rfb.sendKey(keysyms.lookup(newValue.charCodeAt(i)));
1486 }
1487
1488 // Control the text content length in the keyboardinput element
1489 if (newLen > 2 * UI.defaultKeyboardinputLen) {
1490 UI.keyboardinputReset();
1491 } else if (newLen < 1) {
1492 // There always have to be some text in the keyboardinput
1493 // element with which backspace can interact.
1494 UI.keyboardinputReset();
1495 // This sometimes causes the keyboard to disappear for a second
1496 // but it is required for the android keyboard to recognize that
1497 // text has been added to the field
1498 event.target.blur();
1499 // This has to be ran outside of the input handler in order to work
1500 setTimeout(event.target.focus.bind(event.target), 0);
1501 } else {
1502 UI.lastKeyboardinput = newValue;
1503 }
1504 },
1505
1506 /* ------^-------
1507 * /KEYBOARD
1508 * ==============
1509 * EXTRA KEYS
1510 * ------v------*/
1511
1512 openExtraKeys() {
1513 UI.closeAllPanels();
1514 UI.openControlbar();
1515
1516 document.getElementById('noVNC_modifiers')
1517 .classList.add("noVNC_open");
1518 document.getElementById('noVNC_toggle_extra_keys_button')
1519 .classList.add("noVNC_selected");
1520 },
1521
1522 closeExtraKeys() {
1523 document.getElementById('noVNC_modifiers')
1524 .classList.remove("noVNC_open");
1525 document.getElementById('noVNC_toggle_extra_keys_button')
1526 .classList.remove("noVNC_selected");
1527 },
1528
1529 toggleExtraKeys() {
1530 if (document.getElementById('noVNC_modifiers')
1531 .classList.contains("noVNC_open")) {
1532 UI.closeExtraKeys();
1533 } else {
1534 UI.openExtraKeys();
1535 }
1536 },
1537
1538 sendEsc() {
1539 UI.sendKey(KeyTable.XK_Escape, "Escape");
1540 },
1541
1542 sendTab() {
1543 UI.sendKey(KeyTable.XK_Tab, "Tab");
1544 },
1545
1546 toggleCtrl() {
1547 const btn = document.getElementById('noVNC_toggle_ctrl_button');
1548 if (btn.classList.contains("noVNC_selected")) {
1549 UI.sendKey(KeyTable.XK_Control_L, "ControlLeft", false);
1550 btn.classList.remove("noVNC_selected");
1551 } else {
1552 UI.sendKey(KeyTable.XK_Control_L, "ControlLeft", true);
1553 btn.classList.add("noVNC_selected");
1554 }
1555 },
1556
1557 toggleWindows() {
1558 const btn = document.getElementById('noVNC_toggle_windows_button');
1559 if (btn.classList.contains("noVNC_selected")) {
1560 UI.sendKey(KeyTable.XK_Super_L, "MetaLeft", false);
1561 btn.classList.remove("noVNC_selected");
1562 } else {
1563 UI.sendKey(KeyTable.XK_Super_L, "MetaLeft", true);
1564 btn.classList.add("noVNC_selected");
1565 }
1566 },
1567
1568 toggleAlt() {
1569 const btn = document.getElementById('noVNC_toggle_alt_button');
1570 if (btn.classList.contains("noVNC_selected")) {
1571 UI.sendKey(KeyTable.XK_Alt_L, "AltLeft", false);
1572 btn.classList.remove("noVNC_selected");
1573 } else {
1574 UI.sendKey(KeyTable.XK_Alt_L, "AltLeft", true);
1575 btn.classList.add("noVNC_selected");
1576 }
1577 },
1578
1579 sendCtrlAltDel() {
1580 UI.rfb.sendCtrlAltDel();
1581 // See below
1582 UI.rfb.focus();
1583 UI.idleControlbar();
1584 },
1585
1586 sendKey(keysym, code, down) {
1587 UI.rfb.sendKey(keysym, code, down);
1588
1589 // Move focus to the screen in order to be able to use the
1590 // keyboard right after these extra keys.
1591 // The exception is when a virtual keyboard is used, because
1592 // if we focus the screen the virtual keyboard would be closed.
1593 // In this case we focus our special virtual keyboard input
1594 // element instead.
1595 if (document.getElementById('noVNC_keyboard_button')
1596 .classList.contains("noVNC_selected")) {
1597 document.getElementById('noVNC_keyboardinput').focus();
1598 } else {
1599 UI.rfb.focus();
1600 }
1601 // fade out the controlbar to highlight that
1602 // the focus has been moved to the screen
1603 UI.idleControlbar();
1604 },
1605
1606 /* ------^-------
1607 * /EXTRA KEYS
1608 * ==============
1609 * MISC
1610 * ------v------*/
1611
1612 setMouseButton(num) {
1613 const view_only = UI.rfb.viewOnly;
1614 if (UI.rfb && !view_only) {
1615 UI.rfb.touchButton = num;
1616 }
1617
1618 const blist = [0, 1, 2, 4];
1619 for (let b = 0; b < blist.length; b++) {
1620 const button = document.getElementById('noVNC_mouse_button' +
1621 blist[b]);
1622 if (blist[b] === num && !view_only) {
1623 button.classList.remove("noVNC_hidden");
1624 } else {
1625 button.classList.add("noVNC_hidden");
1626 }
1627 }
1628 },
1629
1630 updateViewOnly() {
1631 if (!UI.rfb) return;
1632 UI.rfb.viewOnly = UI.getSetting('view_only');
1633
1634 // Hide input related buttons in view only mode
1635 if (UI.rfb.viewOnly) {
1636 document.getElementById('noVNC_keyboard_button')
1637 .classList.add('noVNC_hidden');
1638 document.getElementById('noVNC_toggle_extra_keys_button')
1639 .classList.add('noVNC_hidden');
1640 document.getElementById('noVNC_mouse_button' + UI.rfb.touchButton)
1641 .classList.add('noVNC_hidden');
1642 document.getElementById('noVNC_clipboard_button')
1643 .classList.add('noVNC_hidden');
1644 } else {
1645 document.getElementById('noVNC_keyboard_button')
1646 .classList.remove('noVNC_hidden');
1647 document.getElementById('noVNC_toggle_extra_keys_button')
1648 .classList.remove('noVNC_hidden');
1649 document.getElementById('noVNC_mouse_button' + UI.rfb.touchButton)
1650 .classList.remove('noVNC_hidden');
1651 document.getElementById('noVNC_clipboard_button')
1652 .classList.remove('noVNC_hidden');
1653 }
1654 },
1655
1656 updateShowDotCursor() {
1657 if (!UI.rfb) return;
1658 UI.rfb.showDotCursor = UI.getSetting('show_dot');
1659 },
1660
1661 updateLogging() {
1662 WebUtil.init_logging(UI.getSetting('logging'));
1663 },
1664
1665 updateDesktopName(e) {
1666 UI.desktopName = e.detail.name;
1667 // Display the desktop name in the document title
1668 document.title = e.detail.name + " - " + PAGE_TITLE;
1669 },
1670
1671 bell(e) {
1672 if (WebUtil.getConfigVar('bell', 'on') === 'on') {
1673 const promise = document.getElementById('noVNC_bell').play();
1674 // The standards disagree on the return value here
1675 if (promise) {
1676 promise.catch((e) => {
1677 if (e.name === "NotAllowedError") {
1678 // Ignore when the browser doesn't let us play audio.
1679 // It is common that the browsers require audio to be
1680 // initiated from a user action.
1681 } else {
1682 Log.Error("Unable to play bell: " + e);
1683 }
1684 });
1685 }
1686 }
1687 },
1688
1689 //Helper to add options to dropdown.
1690 addOption(selectbox, text, value) {
1691 const optn = document.createElement("OPTION");
1692 optn.text = text;
1693 optn.value = value;
1694 selectbox.options.add(optn);
1695 },
1696
1697 /* ------^-------
1698 * /MISC
1699 * ==============
1700 */
1701 };
1702
1703 // Set up translations
1704 const LINGUAS = ["cs", "de", "el", "es", "ja", "ko", "nl", "pl", "ru", "sv", "tr", "zh_CN", "zh_TW"];
1705 l10n.setup(LINGUAS);
1706 if (l10n.language === "en" || l10n.dictionary !== undefined) {
1707 UI.prime();
1708 } else {
1709 WebUtil.fetchJSON('app/locale/' + l10n.language + '.json')
1710 .then((translations) => { l10n.dictionary = translations; })
1711 .catch(err => Log.Error("Failed to load translations: " + err))
1712 .then(UI.prime);
1713 }
1714
1715 export default UI;