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