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