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