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