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