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