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