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