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