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