]> git.proxmox.com Git - mirror_novnc.git/blob - app/ui.js
Separate init functions from event handling setup
[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('clip');
425 UI.addSettingChangeHandler('shared');
426 UI.addSettingChangeHandler('view_only');
427 UI.addSettingChangeHandler('host');
428 UI.addSettingChangeHandler('port');
429 UI.addSettingChangeHandler('path');
430 UI.addSettingChangeHandler('repeaterID');
431 UI.addSettingChangeHandler('logging');
432 UI.addSettingChangeHandler('logging', UI.updateLogging);
433 UI.addSettingChangeHandler('reconnect');
434 UI.addSettingChangeHandler('reconnect_delay');
435 },
436
437 addFullscreenHandlers: function() {
438 document.getElementById("noVNC_fullscreen_button")
439 .addEventListener('click', UI.toggleFullscreen);
440
441 window.addEventListener('fullscreenchange', UI.updateFullscreenButton);
442 window.addEventListener('mozfullscreenchange', UI.updateFullscreenButton);
443 window.addEventListener('webkitfullscreenchange', UI.updateFullscreenButton);
444 window.addEventListener('msfullscreenchange', UI.updateFullscreenButton);
445 },
446
447 /* ------^-------
448 * /EVENT HANDLERS
449 * ==============
450 * VISUAL
451 * ------v------*/
452
453 updateState: function(rfb, state, oldstate) {
454 var msg;
455
456 document.documentElement.classList.remove("noVNC_connecting");
457 document.documentElement.classList.remove("noVNC_connected");
458 document.documentElement.classList.remove("noVNC_disconnecting");
459 document.documentElement.classList.remove("noVNC_reconnecting");
460
461 switch (state) {
462 case 'connecting':
463 document.getElementById("noVNC_transition_text").textContent = _("Connecting...");
464 document.documentElement.classList.add("noVNC_connecting");
465 break;
466 case 'connected':
467 UI.connected = true;
468 UI.inhibit_reconnect = false;
469 document.documentElement.classList.add("noVNC_connected");
470 if (rfb && rfb.get_encrypt()) {
471 msg = _("Connected (encrypted) to ") + UI.desktopName;
472 } else {
473 msg = _("Connected (unencrypted) to ") + UI.desktopName;
474 }
475 UI.showStatus(msg);
476 break;
477 case 'disconnecting':
478 UI.connected = false;
479 document.getElementById("noVNC_transition_text").textContent = _("Disconnecting...");
480 document.documentElement.classList.add("noVNC_disconnecting");
481 break;
482 case 'disconnected':
483 UI.showStatus(_("Disconnected"));
484 break;
485 default:
486 msg = "Invalid UI state";
487 Util.Error(msg);
488 UI.showStatus(msg, 'error');
489 break;
490 }
491
492 UI.updateVisualState();
493 },
494
495 // Disable/enable controls depending on connection state
496 updateVisualState: function() {
497 //Util.Debug(">> updateVisualState");
498 document.getElementById('noVNC_setting_encrypt').disabled = UI.connected;
499 document.getElementById('noVNC_setting_true_color').disabled = UI.connected;
500 if (Util.browserSupportsCursorURIs()) {
501 document.getElementById('noVNC_setting_cursor').disabled = UI.connected;
502 } else {
503 UI.updateSetting('cursor', !Util.isTouchDevice);
504 document.getElementById('noVNC_setting_cursor').disabled = true;
505 }
506
507 UI.enableDisableViewClip();
508 document.getElementById('noVNC_setting_resize').disabled = UI.connected;
509 document.getElementById('noVNC_setting_shared').disabled = UI.connected;
510 document.getElementById('noVNC_setting_view_only').disabled = UI.connected;
511 document.getElementById('noVNC_setting_host').disabled = UI.connected;
512 document.getElementById('noVNC_setting_port').disabled = UI.connected;
513 document.getElementById('noVNC_setting_path').disabled = UI.connected;
514 document.getElementById('noVNC_setting_repeaterID').disabled = UI.connected;
515 document.getElementById('noVNC_setting_reconnect').disabled = UI.connected;
516 document.getElementById('noVNC_setting_reconnect_delay').disabled = UI.connected;
517
518 if (UI.connected) {
519 UI.updateViewClip();
520 UI.setMouseButton(1);
521
522 // Hide the controlbar after 2 seconds
523 UI.closeControlbarTimeout = setTimeout(UI.closeControlbar, 2000);
524 } else {
525 UI.updateXvpButton(0);
526 UI.keepControlbar();
527 }
528
529 // Hide input related buttons in view only mode
530 if (UI.rfb && UI.rfb.get_view_only()) {
531 document.getElementById('noVNC_keyboard_button')
532 .classList.add('noVNC_hidden');
533 document.getElementById('noVNC_toggle_extra_keys_button')
534 .classList.add('noVNC_hidden');
535 } else {
536 document.getElementById('noVNC_keyboard_button')
537 .classList.remove('noVNC_hidden');
538 document.getElementById('noVNC_toggle_extra_keys_button')
539 .classList.remove('noVNC_hidden');
540 }
541
542 // State change disables viewport dragging.
543 // It is enabled (toggled) by direct click on the button
544 UI.setViewDrag(false);
545
546 // State change also closes the password dialog
547 document.getElementById('noVNC_password_dlg')
548 .classList.remove('noVNC_open');
549
550 //Util.Debug("<< updateVisualState");
551 },
552
553 showStatus: function(text, status_type, time) {
554 var statusElem = document.getElementById('noVNC_status');
555
556 clearTimeout(UI.statusTimeout);
557
558 if (typeof status_type === 'undefined') {
559 status_type = 'normal';
560 }
561
562 statusElem.classList.remove("noVNC_status_normal",
563 "noVNC_status_warn",
564 "noVNC_status_error");
565
566 switch (status_type) {
567 case 'warning':
568 case 'warn':
569 statusElem.classList.add("noVNC_status_warn");
570 break;
571 case 'error':
572 statusElem.classList.add("noVNC_status_error");
573 break;
574 case 'normal':
575 case 'info':
576 default:
577 statusElem.classList.add("noVNC_status_normal");
578 break;
579 }
580
581 statusElem.textContent = text;
582 statusElem.classList.add("noVNC_open");
583
584 // If no time was specified, show the status for 1.5 seconds
585 if (typeof time === 'undefined') {
586 time = 1500;
587 }
588
589 // Error messages do not timeout
590 if (status_type !== 'error') {
591 UI.statusTimeout = window.setTimeout(UI.hideStatus, time);
592 }
593 },
594
595 hideStatus: function() {
596 clearTimeout(UI.statusTimeout);
597 document.getElementById('noVNC_status').classList.remove("noVNC_open");
598 },
599
600 notification: function (rfb, msg, level, options) {
601 UI.showStatus(msg, level);
602 },
603
604 activateControlbar: function(event) {
605 clearTimeout(UI.idleControlbarTimeout);
606 // We manipulate the anchor instead of the actual control
607 // bar in order to avoid creating new a stacking group
608 document.getElementById('noVNC_control_bar_anchor')
609 .classList.remove("noVNC_idle");
610 UI.idleControlbarTimeout = window.setTimeout(UI.idleControlbar, 2000);
611 },
612
613 idleControlbar: function() {
614 document.getElementById('noVNC_control_bar_anchor')
615 .classList.add("noVNC_idle");
616 },
617
618 keepControlbar: function() {
619 clearTimeout(UI.closeControlbarTimeout);
620 },
621
622 openControlbar: function() {
623 document.getElementById('noVNC_control_bar')
624 .classList.add("noVNC_open");
625 },
626
627 closeControlbar: function() {
628 UI.closeAllPanels();
629 document.getElementById('noVNC_control_bar')
630 .classList.remove("noVNC_open");
631 },
632
633 toggleControlbar: function() {
634 if (document.getElementById('noVNC_control_bar')
635 .classList.contains("noVNC_open")) {
636 UI.closeControlbar();
637 } else {
638 UI.openControlbar();
639 }
640 },
641
642 toggleControlbarSide: function () {
643 // Temporarily disable animation to avoid weird movement
644 var bar = document.getElementById('noVNC_control_bar');
645 bar.style.transitionDuration = '0s';
646 bar.addEventListener('transitionend', function () { this.style.transitionDuration = ""; });
647
648 var anchor = document.getElementById('noVNC_control_bar_anchor');
649 if (anchor.classList.contains("noVNC_right")) {
650 WebUtil.writeSetting('controlbar_pos', 'left');
651 anchor.classList.remove("noVNC_right");
652 } else {
653 WebUtil.writeSetting('controlbar_pos', 'right');
654 anchor.classList.add("noVNC_right");
655 }
656
657 // Consider this a movement of the handle
658 UI.controlbarDrag = true;
659 },
660
661 dragControlbarHandle: function (e) {
662 if (!UI.controlbarGrabbed) return;
663
664 var ptr = Util.getPointerEvent(e);
665
666 var anchor = document.getElementById('noVNC_control_bar_anchor');
667 if (ptr.clientX < (window.innerWidth * 0.1)) {
668 if (anchor.classList.contains("noVNC_right")) {
669 UI.toggleControlbarSide();
670 }
671 } else if (ptr.clientX > (window.innerWidth * 0.9)) {
672 if (!anchor.classList.contains("noVNC_right")) {
673 UI.toggleControlbarSide();
674 }
675 }
676
677 if (!UI.controlbarDrag) {
678 // The goal is to trigger on a certain physical width, the
679 // devicePixelRatio brings us a bit closer but is not optimal.
680 var dragThreshold = 10 * (window.devicePixelRatio || 1);
681 var dragDistance = Math.abs(ptr.clientY - UI.controlbarMouseDownClientY);
682
683 if (dragDistance < dragThreshold) return;
684
685 UI.controlbarDrag = true;
686 }
687
688 var eventY = ptr.clientY - UI.controlbarMouseDownOffsetY;
689
690 UI.moveControlbarHandle(eventY);
691
692 e.preventDefault();
693 e.stopPropagation();
694 UI.keepControlbar();
695 UI.activateControlbar();
696 },
697
698 // Move the handle but don't allow any position outside the bounds
699 moveControlbarHandle: function (viewportRelativeY) {
700 var handle = document.getElementById("noVNC_control_bar_handle");
701 var handleHeight = handle.getBoundingClientRect().height;
702 var controlbarBounds = document.getElementById("noVNC_control_bar")
703 .getBoundingClientRect();
704 var margin = 10;
705
706 // These heights need to be non-zero for the below logic to work
707 if (handleHeight === 0 || controlbarBounds.height === 0) {
708 return;
709 }
710
711 var newY = viewportRelativeY;
712
713 // Check if the coordinates are outside the control bar
714 if (newY < controlbarBounds.top + margin) {
715 // Force coordinates to be below the top of the control bar
716 newY = controlbarBounds.top + margin;
717
718 } else if (newY > controlbarBounds.top +
719 controlbarBounds.height - handleHeight - margin) {
720 // Force coordinates to be above the bottom of the control bar
721 newY = controlbarBounds.top +
722 controlbarBounds.height - handleHeight - margin;
723 }
724
725 // Corner case: control bar too small for stable position
726 if (controlbarBounds.height < (handleHeight + margin * 2)) {
727 newY = controlbarBounds.top +
728 (controlbarBounds.height - handleHeight) / 2;
729 }
730
731 // The transform needs coordinates that are relative to the parent
732 var parentRelativeY = newY - controlbarBounds.top;
733 handle.style.transform = "translateY(" + parentRelativeY + "px)";
734 },
735
736 updateControlbarHandle: function () {
737 // Since the control bar is fixed on the viewport and not the page,
738 // the move function expects coordinates relative the the viewport.
739 var handle = document.getElementById("noVNC_control_bar_handle");
740 var handleBounds = handle.getBoundingClientRect();
741 UI.moveControlbarHandle(handleBounds.top);
742 },
743
744 controlbarHandleMouseUp: function(e) {
745 if ((e.type == "mouseup") && (e.button != 0)) return;
746
747 // mouseup and mousedown on the same place toggles the controlbar
748 if (UI.controlbarGrabbed && !UI.controlbarDrag) {
749 UI.toggleControlbar();
750 e.preventDefault();
751 e.stopPropagation();
752 UI.keepControlbar();
753 UI.activateControlbar();
754 }
755 UI.controlbarGrabbed = false;
756 },
757
758 controlbarHandleMouseDown: function(e) {
759 if ((e.type == "mousedown") && (e.button != 0)) return;
760
761 var ptr = Util.getPointerEvent(e);
762
763 var handle = document.getElementById("noVNC_control_bar_handle");
764 var bounds = handle.getBoundingClientRect();
765
766 WebUtil.setCapture(handle);
767 UI.controlbarGrabbed = true;
768 UI.controlbarDrag = false;
769
770 UI.controlbarMouseDownClientY = ptr.clientY;
771 UI.controlbarMouseDownOffsetY = ptr.clientY - bounds.top;
772 e.preventDefault();
773 e.stopPropagation();
774 UI.keepControlbar();
775 UI.activateControlbar();
776 },
777
778 toggleExpander: function(e) {
779 if (this.classList.contains("noVNC_open")) {
780 this.classList.remove("noVNC_open");
781 } else {
782 this.classList.add("noVNC_open");
783 }
784 },
785
786 /* ------^-------
787 * /VISUAL
788 * ==============
789 * SETTINGS
790 * ------v------*/
791
792 // Initial page load read/initialization of settings
793 initSetting: function(name, defVal) {
794 // Check Query string followed by cookie
795 var val = WebUtil.getConfigVar(name);
796 if (val === null) {
797 val = WebUtil.readSetting(name, defVal);
798 }
799 UI.updateSetting(name, val);
800 return val;
801 },
802
803 // Update cookie and form control setting. If value is not set, then
804 // updates from control to current cookie setting.
805 updateSetting: function(name, value) {
806
807 // Save the cookie for this session
808 if (typeof value !== 'undefined') {
809 WebUtil.writeSetting(name, value);
810 }
811
812 // Update the settings control
813 value = UI.getSetting(name);
814
815 var ctrl = document.getElementById('noVNC_setting_' + name);
816 if (ctrl.type === 'checkbox') {
817 ctrl.checked = value;
818
819 } else if (typeof ctrl.options !== 'undefined') {
820 for (var i = 0; i < ctrl.options.length; i += 1) {
821 if (ctrl.options[i].value === value) {
822 ctrl.selectedIndex = i;
823 break;
824 }
825 }
826 } else {
827 /*Weird IE9 error leads to 'null' appearring
828 in textboxes instead of ''.*/
829 if (value === null) {
830 value = "";
831 }
832 ctrl.value = value;
833 }
834 },
835
836 // Save control setting to cookie
837 saveSetting: function(name) {
838 var val, ctrl = document.getElementById('noVNC_setting_' + name);
839 if (ctrl.type === 'checkbox') {
840 val = ctrl.checked;
841 } else if (typeof ctrl.options !== 'undefined') {
842 val = ctrl.options[ctrl.selectedIndex].value;
843 } else {
844 val = ctrl.value;
845 }
846 WebUtil.writeSetting(name, val);
847 //Util.Debug("Setting saved '" + name + "=" + val + "'");
848 return val;
849 },
850
851 // Force a setting to be a certain value
852 forceSetting: function(name, val) {
853 UI.updateSetting(name, val);
854 return val;
855 },
856
857 // Read form control compatible setting from cookie
858 getSetting: function(name) {
859 var ctrl = document.getElementById('noVNC_setting_' + name);
860 var val = WebUtil.readSetting(name);
861 if (typeof val !== 'undefined' && val !== null && ctrl.type === 'checkbox') {
862 if (val.toString().toLowerCase() in {'0':1, 'no':1, 'false':1}) {
863 val = false;
864 } else {
865 val = true;
866 }
867 }
868 return val;
869 },
870
871 /* ------^-------
872 * /SETTINGS
873 * ==============
874 * PANELS
875 * ------v------*/
876
877 closeAllPanels: function() {
878 UI.closeSettingsPanel();
879 UI.closeXvpPanel();
880 UI.closeClipboardPanel();
881 UI.closeExtraKeys();
882 },
883
884 /* ------^-------
885 * /PANELS
886 * ==============
887 * SETTINGS (panel)
888 * ------v------*/
889
890 openSettingsPanel: function() {
891 UI.closeAllPanels();
892 UI.openControlbar();
893
894 // Refresh UI elements from saved cookies
895 UI.updateSetting('encrypt');
896 UI.updateSetting('true_color');
897 if (Util.browserSupportsCursorURIs()) {
898 UI.updateSetting('cursor');
899 } else {
900 UI.updateSetting('cursor', !Util.isTouchDevice);
901 document.getElementById('noVNC_setting_cursor').disabled = true;
902 }
903 UI.updateSetting('clip');
904 UI.updateSetting('resize');
905 UI.updateSetting('shared');
906 UI.updateSetting('view_only');
907 UI.updateSetting('path');
908 UI.updateSetting('repeaterID');
909 UI.updateSetting('logging');
910 UI.updateSetting('reconnect');
911 UI.updateSetting('reconnect_delay');
912
913 document.getElementById('noVNC_settings')
914 .classList.add("noVNC_open");
915 document.getElementById('noVNC_settings_button')
916 .classList.add("noVNC_selected");
917 },
918
919 closeSettingsPanel: function() {
920 document.getElementById('noVNC_settings')
921 .classList.remove("noVNC_open");
922 document.getElementById('noVNC_settings_button')
923 .classList.remove("noVNC_selected");
924 },
925
926 toggleSettingsPanel: function() {
927 if (document.getElementById('noVNC_settings')
928 .classList.contains("noVNC_open")) {
929 UI.closeSettingsPanel();
930 } else {
931 UI.openSettingsPanel();
932 }
933 },
934
935 /* ------^-------
936 * /SETTINGS
937 * ==============
938 * XVP
939 * ------v------*/
940
941 openXvpPanel: function() {
942 UI.closeAllPanels();
943 UI.openControlbar();
944
945 document.getElementById('noVNC_xvp')
946 .classList.add("noVNC_open");
947 document.getElementById('noVNC_xvp_button')
948 .classList.add("noVNC_selected");
949 },
950
951 closeXvpPanel: function() {
952 document.getElementById('noVNC_xvp')
953 .classList.remove("noVNC_open");
954 document.getElementById('noVNC_xvp_button')
955 .classList.remove("noVNC_selected");
956 },
957
958 toggleXvpPanel: function() {
959 if (document.getElementById('noVNC_xvp')
960 .classList.contains("noVNC_open")) {
961 UI.closeXvpPanel();
962 } else {
963 UI.openXvpPanel();
964 }
965 },
966
967 // Disable/enable XVP button
968 updateXvpButton: function(ver) {
969 if (ver >= 1 && !UI.rfb.get_view_only()) {
970 document.getElementById('noVNC_xvp_button')
971 .classList.remove("noVNC_hidden");
972 } else {
973 document.getElementById('noVNC_xvp_button')
974 .classList.add("noVNC_hidden");
975 // Close XVP panel if open
976 UI.closeXvpPanel();
977 }
978 },
979
980 /* ------^-------
981 * /XVP
982 * ==============
983 * CLIPBOARD
984 * ------v------*/
985
986 openClipboardPanel: function() {
987 UI.closeAllPanels();
988 UI.openControlbar();
989
990 document.getElementById('noVNC_clipboard')
991 .classList.add("noVNC_open");
992 document.getElementById('noVNC_clipboard_button')
993 .classList.add("noVNC_selected");
994 },
995
996 closeClipboardPanel: function() {
997 document.getElementById('noVNC_clipboard')
998 .classList.remove("noVNC_open");
999 document.getElementById('noVNC_clipboard_button')
1000 .classList.remove("noVNC_selected");
1001 },
1002
1003 toggleClipboardPanel: function() {
1004 if (document.getElementById('noVNC_clipboard')
1005 .classList.contains("noVNC_open")) {
1006 UI.closeClipboardPanel();
1007 } else {
1008 UI.openClipboardPanel();
1009 }
1010 },
1011
1012 clipboardReceive: function(rfb, text) {
1013 Util.Debug(">> UI.clipboardReceive: " + text.substr(0,40) + "...");
1014 document.getElementById('noVNC_clipboard_text').value = text;
1015 Util.Debug("<< UI.clipboardReceive");
1016 },
1017
1018 clipboardClear: function() {
1019 document.getElementById('noVNC_clipboard_text').value = "";
1020 UI.rfb.clipboardPasteFrom("");
1021 },
1022
1023 clipboardSend: function() {
1024 var text = document.getElementById('noVNC_clipboard_text').value;
1025 Util.Debug(">> UI.clipboardSend: " + text.substr(0,40) + "...");
1026 UI.rfb.clipboardPasteFrom(text);
1027 Util.Debug("<< UI.clipboardSend");
1028 },
1029
1030 /* ------^-------
1031 * /CLIPBOARD
1032 * ==============
1033 * CONNECTION
1034 * ------v------*/
1035
1036 openConnectPanel: function() {
1037 document.getElementById('noVNC_connect_dlg')
1038 .classList.add("noVNC_open");
1039 },
1040
1041 closeConnectPanel: function() {
1042 document.getElementById('noVNC_connect_dlg')
1043 .classList.remove("noVNC_open");
1044 },
1045
1046 connect: function(event, password) {
1047 var host = UI.getSetting('host');
1048 var port = UI.getSetting('port');
1049 var path = UI.getSetting('path');
1050
1051 if (typeof password === 'undefined') {
1052 password = WebUtil.getConfigVar('password');
1053 }
1054
1055 if (password === null) {
1056 password = undefined;
1057 }
1058
1059 if ((!host) || (!port)) {
1060 var msg = _("Must set host and port");
1061 Util.Error(msg);
1062 UI.showStatus(msg, 'error');
1063 return;
1064 }
1065
1066 if (!UI.initRFB()) return;
1067
1068 UI.closeAllPanels();
1069 UI.closeConnectPanel();
1070
1071 UI.rfb.set_encrypt(UI.getSetting('encrypt'));
1072 UI.rfb.set_true_color(UI.getSetting('true_color'));
1073 UI.rfb.set_local_cursor(UI.getSetting('cursor'));
1074 UI.rfb.set_shared(UI.getSetting('shared'));
1075 UI.rfb.set_view_only(UI.getSetting('view_only'));
1076 UI.rfb.set_repeaterID(UI.getSetting('repeaterID'));
1077
1078 UI.rfb.connect(host, port, password, path);
1079 },
1080
1081 disconnect: function() {
1082 UI.closeAllPanels();
1083 UI.rfb.disconnect();
1084
1085 // Disable automatic reconnecting
1086 UI.inhibit_reconnect = true;
1087
1088 // Restore the callback used for initial resize
1089 UI.rfb.set_onFBUComplete(UI.initialResize);
1090
1091 // Don't display the connection settings until we're actually disconnected
1092 },
1093
1094 reconnect: function() {
1095 UI.reconnect_callback = null;
1096
1097 // if reconnect has been disabled in the meantime, do nothing.
1098 if (UI.inhibit_reconnect) {
1099 return;
1100 }
1101
1102 UI.connect(null, UI.reconnect_password);
1103 },
1104
1105 disconnectFinished: function (rfb, reason) {
1106 if (typeof reason !== 'undefined') {
1107 UI.showStatus(reason, 'error');
1108 } else if (UI.getSetting('reconnect', false) === true && !UI.inhibit_reconnect) {
1109 document.getElementById("noVNC_transition_text").textContent = _("Reconnecting...");
1110 document.documentElement.classList.add("noVNC_reconnecting");
1111
1112 var delay = parseInt(UI.getSetting('reconnect_delay'));
1113 UI.reconnect_callback = setTimeout(UI.reconnect, delay);
1114 return;
1115 }
1116
1117 UI.openControlbar();
1118 UI.openConnectPanel();
1119 },
1120
1121 cancelReconnect: function() {
1122 if (UI.reconnect_callback !== null) {
1123 clearTimeout(UI.reconnect_callback);
1124 UI.reconnect_callback = null;
1125 }
1126
1127 document.documentElement.classList.remove("noVNC_reconnecting");
1128 UI.openControlbar();
1129 UI.openConnectPanel();
1130 },
1131
1132 /* ------^-------
1133 * /CONNECTION
1134 * ==============
1135 * PASSWORD
1136 * ------v------*/
1137
1138 passwordRequired: function(rfb, msg) {
1139
1140 document.getElementById('noVNC_password_dlg')
1141 .classList.add('noVNC_open');
1142
1143 setTimeout(function () {
1144 document.getElementById('noVNC_password_input').focus();
1145 }, 100);
1146
1147 if (typeof msg === 'undefined') {
1148 msg = _("Password is required");
1149 }
1150 Util.Warn(msg);
1151 UI.showStatus(msg, "warning");
1152 },
1153
1154 setPassword: function() {
1155 var password = document.getElementById('noVNC_password_input').value;
1156 UI.rfb.sendPassword(password);
1157 UI.reconnect_password = password;
1158 document.getElementById('noVNC_password_dlg')
1159 .classList.remove('noVNC_open');
1160 return false;
1161 },
1162
1163 /* ------^-------
1164 * /PASSWORD
1165 * ==============
1166 * FULLSCREEN
1167 * ------v------*/
1168
1169 toggleFullscreen: function() {
1170 if (document.fullscreenElement || // alternative standard method
1171 document.mozFullScreenElement || // currently working methods
1172 document.webkitFullscreenElement ||
1173 document.msFullscreenElement) {
1174 if (document.exitFullscreen) {
1175 document.exitFullscreen();
1176 } else if (document.mozCancelFullScreen) {
1177 document.mozCancelFullScreen();
1178 } else if (document.webkitExitFullscreen) {
1179 document.webkitExitFullscreen();
1180 } else if (document.msExitFullscreen) {
1181 document.msExitFullscreen();
1182 }
1183 } else {
1184 if (document.documentElement.requestFullscreen) {
1185 document.documentElement.requestFullscreen();
1186 } else if (document.documentElement.mozRequestFullScreen) {
1187 document.documentElement.mozRequestFullScreen();
1188 } else if (document.documentElement.webkitRequestFullscreen) {
1189 document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
1190 } else if (document.body.msRequestFullscreen) {
1191 document.body.msRequestFullscreen();
1192 }
1193 }
1194 UI.enableDisableViewClip();
1195 UI.updateFullscreenButton();
1196 },
1197
1198 updateFullscreenButton: function() {
1199 if (document.fullscreenElement || // alternative standard method
1200 document.mozFullScreenElement || // currently working methods
1201 document.webkitFullscreenElement ||
1202 document.msFullscreenElement ) {
1203 document.getElementById('noVNC_fullscreen_button')
1204 .classList.add("noVNC_selected");
1205 } else {
1206 document.getElementById('noVNC_fullscreen_button')
1207 .classList.remove("noVNC_selected");
1208 }
1209 },
1210
1211 /* ------^-------
1212 * /FULLSCREEN
1213 * ==============
1214 * RESIZE
1215 * ------v------*/
1216
1217 // Apply remote resizing or local scaling
1218 applyResizeMode: function() {
1219 if (!UI.rfb) return;
1220
1221 var screen = UI.screenSize();
1222
1223 if (screen && UI.connected && UI.rfb.get_display()) {
1224
1225 var display = UI.rfb.get_display();
1226 var resizeMode = UI.getSetting('resize');
1227
1228 if (resizeMode === 'remote') {
1229
1230 // Request changing the resolution of the remote display to
1231 // the size of the local browser viewport.
1232
1233 // In order to not send multiple requests before the browser-resize
1234 // is finished we wait 0.5 seconds before sending the request.
1235 clearTimeout(UI.resizeTimeout);
1236 UI.resizeTimeout = setTimeout(function(){
1237 // Request a remote size covering the viewport
1238 if (UI.rfb.requestDesktopSize(screen.w, screen.h)) {
1239 Util.Debug('Requested new desktop size: ' +
1240 screen.w + 'x' + screen.h);
1241 }
1242 }, 500);
1243
1244 } else if (resizeMode === 'scale' || resizeMode === 'downscale') {
1245 var downscaleOnly = resizeMode === 'downscale';
1246 var scaleRatio = display.autoscale(screen.w, screen.h, downscaleOnly);
1247
1248 if (!UI.rfb.get_view_only()) {
1249 UI.rfb.get_mouse().set_scale(scaleRatio);
1250 Util.Debug('Scaling by ' + UI.rfb.get_mouse().get_scale());
1251 }
1252 }
1253 }
1254 },
1255
1256 // Gets the the size of the available viewport in the browser window
1257 screenSize: function() {
1258 var screen = document.getElementById('noVNC_screen');
1259
1260 // Hide the scrollbars until the size is calculated
1261 screen.style.overflow = "hidden";
1262
1263 var pos = Util.getPosition(screen);
1264 var w = pos.width;
1265 var h = pos.height;
1266
1267 screen.style.overflow = "visible";
1268
1269 if (isNaN(w) || isNaN(h)) {
1270 return false;
1271 } else {
1272 return {w: w, h: h};
1273 }
1274 },
1275
1276 // Normally we only apply the current resize mode after a window resize
1277 // event. This means that when a new connection is opened, there is no
1278 // resize mode active.
1279 // We have to wait until the first FBU because this is where the client
1280 // will find the supported encodings of the server. Some calls later in
1281 // the chain is dependant on knowing the server-capabilities.
1282 initialResize: function(rfb, fbu) {
1283 UI.applyResizeMode();
1284 // After doing this once, we remove the callback.
1285 UI.rfb.set_onFBUComplete(function() { });
1286 },
1287
1288 /* ------^-------
1289 * /RESIZE
1290 * ==============
1291 * CLIPPING
1292 * ------v------*/
1293
1294 // Set and configure viewport clipping
1295 setViewClip: function(clip) {
1296 UI.updateSetting('clip', clip);
1297 UI.updateViewClip();
1298 },
1299
1300 // Update parameters that depend on the clip setting
1301 updateViewClip: function() {
1302 if (!UI.rfb) return;
1303
1304 var display = UI.rfb.get_display();
1305 var cur_clip = display.get_viewport();
1306 var new_clip = UI.getSetting('clip');
1307
1308 if (cur_clip !== new_clip) {
1309 display.set_viewport(new_clip);
1310 }
1311
1312 var size = UI.screenSize();
1313
1314 if (new_clip && size) {
1315 // When clipping is enabled, the screen is limited to
1316 // the size of the browser window.
1317 display.viewportChangeSize(size.w, size.h);
1318 }
1319 },
1320
1321 // Handle special cases where clipping is forced on/off or locked
1322 enableDisableViewClip: function() {
1323 var resizeSetting = UI.getSetting('resize');
1324
1325 if (UI.isSafari) {
1326 // Safari auto-hides the scrollbars which makes them
1327 // impossible to use in most cases
1328 UI.setViewClip(true);
1329 document.getElementById('noVNC_setting_clip').disabled = true;
1330 } else if (resizeSetting === 'downscale' || resizeSetting === 'scale') {
1331 // Disable clipping if we are scaling
1332 UI.forceSetting('clip', false);
1333 UI.setViewClip(false);
1334 document.getElementById('noVNC_setting_clip').disabled = true;
1335 } else if (document.msFullscreenElement) {
1336 // The browser is IE and we are in fullscreen mode.
1337 // - We need to force clipping while in fullscreen since
1338 // scrollbars doesn't work.
1339 var msg = _("Forcing clipping mode since " +
1340 "scrollbars aren't supported " +
1341 "by IE in fullscreen");
1342 Util.Debug(msg);
1343 UI.showStatus(msg);
1344 UI.rememberedClipSetting = UI.getSetting('clip');
1345 UI.setViewClip(true);
1346 document.getElementById('noVNC_setting_clip').disabled = true;
1347 } else if (document.body.msRequestFullscreen &&
1348 UI.rememberedClipSetting !== null) {
1349 // Restore view clip to what it was before fullscreen on IE
1350 UI.setViewClip(UI.rememberedClipSetting);
1351 document.getElementById('noVNC_setting_clip').disabled =
1352 UI.connected || Util.isTouchDevice;
1353 } else {
1354 document.getElementById('noVNC_setting_clip').disabled =
1355 UI.connected || Util.isTouchDevice;
1356 if (Util.isTouchDevice) {
1357 UI.setViewClip(true);
1358 }
1359 }
1360 },
1361
1362 /* ------^-------
1363 * /CLIPPING
1364 * ==============
1365 * VIEWDRAG
1366 * ------v------*/
1367
1368 toggleViewDrag: function() {
1369 if (!UI.rfb) return;
1370
1371 var drag = UI.rfb.get_viewportDrag();
1372 UI.setViewDrag(!drag);
1373 },
1374
1375 // Set the view drag mode which moves the viewport on mouse drags
1376 setViewDrag: function(drag) {
1377 if (!UI.rfb) return;
1378
1379 UI.rfb.set_viewportDrag(drag);
1380
1381 UI.updateViewDrag();
1382 },
1383
1384 updateViewDrag: function() {
1385 var clipping = false;
1386
1387 if (!UI.connected) return;
1388
1389 // Check if viewport drag is possible. It is only possible
1390 // if the remote display is clipping the client display.
1391 if (UI.rfb.get_display().get_viewport() &&
1392 UI.rfb.get_display().clippingDisplay()) {
1393 clipping = true;
1394 }
1395
1396 var viewDragButton = document.getElementById('noVNC_view_drag_button');
1397
1398 if (!clipping &&
1399 UI.rfb.get_viewportDrag()) {
1400 // The size of the remote display is the same or smaller
1401 // than the client display. Make sure viewport drag isn't
1402 // active when it can't be used.
1403 UI.rfb.set_viewportDrag(false);
1404 }
1405
1406 if (UI.rfb.get_viewportDrag()) {
1407 viewDragButton.classList.add("noVNC_selected");
1408 } else {
1409 viewDragButton.classList.remove("noVNC_selected");
1410 }
1411
1412 // Different behaviour for touch vs non-touch
1413 // The button is disabled instead of hidden on touch devices
1414 if (Util.isTouchDevice) {
1415 viewDragButton.classList.remove("noVNC_hidden");
1416
1417 if (clipping) {
1418 viewDragButton.disabled = false;
1419 } else {
1420 viewDragButton.disabled = true;
1421 }
1422 } else {
1423 viewDragButton.disabled = false;
1424
1425 if (clipping) {
1426 viewDragButton.classList.remove("noVNC_hidden");
1427 } else {
1428 viewDragButton.classList.add("noVNC_hidden");
1429 }
1430 }
1431 },
1432
1433 /* ------^-------
1434 * /VIEWDRAG
1435 * ==============
1436 * KEYBOARD
1437 * ------v------*/
1438
1439 showVirtualKeyboard: function() {
1440 if (!Util.isTouchDevice) return;
1441
1442 var input = document.getElementById('noVNC_keyboardinput');
1443
1444 if (document.activeElement == input) return;
1445
1446 input.focus();
1447
1448 try {
1449 var l = input.value.length;
1450 // Move the caret to the end
1451 input.setSelectionRange(l, l);
1452 } catch (err) {} // setSelectionRange is undefined in Google Chrome
1453 },
1454
1455 hideVirtualKeyboard: function() {
1456 if (!Util.isTouchDevice) return;
1457
1458 var input = document.getElementById('noVNC_keyboardinput');
1459
1460 if (document.activeElement != input) return;
1461
1462 input.blur();
1463 },
1464
1465 toggleVirtualKeyboard: function () {
1466 if (document.getElementById('noVNC_keyboard_button')
1467 .classList.contains("noVNC_selected")) {
1468 UI.hideVirtualKeyboard();
1469 } else {
1470 UI.showVirtualKeyboard();
1471 }
1472 },
1473
1474 onfocusVirtualKeyboard: function(event) {
1475 document.getElementById('noVNC_keyboard_button')
1476 .classList.add("noVNC_selected");
1477 },
1478
1479 onblurVirtualKeyboard: function(event) {
1480 document.getElementById('noVNC_keyboard_button')
1481 .classList.remove("noVNC_selected");
1482 },
1483
1484 keepVirtualKeyboard: function(event) {
1485 var input = document.getElementById('noVNC_keyboardinput');
1486
1487 // Only prevent focus change if the virtual keyboard is active
1488 if (document.activeElement != input) {
1489 return;
1490 }
1491
1492 // Allow clicking on links
1493 if (event.target.tagName === "A") {
1494 return;
1495 }
1496
1497 // And form elements, except standard noVNC buttons
1498 if ((event.target.form !== undefined) &&
1499 !event.target.classList.contains("noVNC_button")) {
1500 return;
1501 }
1502
1503 event.preventDefault();
1504 },
1505
1506 keyboardinputReset: function() {
1507 var kbi = document.getElementById('noVNC_keyboardinput');
1508 kbi.value = new Array(UI.defaultKeyboardinputLen).join("_");
1509 UI.lastKeyboardinput = kbi.value;
1510 },
1511
1512 // When normal keyboard events are left uncought, use the input events from
1513 // the keyboardinput element instead and generate the corresponding key events.
1514 // This code is required since some browsers on Android are inconsistent in
1515 // sending keyCodes in the normal keyboard events when using on screen keyboards.
1516 keyInput: function(event) {
1517
1518 if (!UI.rfb) return;
1519
1520 var newValue = event.target.value;
1521
1522 if (!UI.lastKeyboardinput) {
1523 UI.keyboardinputReset();
1524 }
1525 var oldValue = UI.lastKeyboardinput;
1526
1527 var newLen;
1528 try {
1529 // Try to check caret position since whitespace at the end
1530 // will not be considered by value.length in some browsers
1531 newLen = Math.max(event.target.selectionStart, newValue.length);
1532 } catch (err) {
1533 // selectionStart is undefined in Google Chrome
1534 newLen = newValue.length;
1535 }
1536 var oldLen = oldValue.length;
1537
1538 var backspaces;
1539 var inputs = newLen - oldLen;
1540 if (inputs < 0) {
1541 backspaces = -inputs;
1542 } else {
1543 backspaces = 0;
1544 }
1545
1546 // Compare the old string with the new to account for
1547 // text-corrections or other input that modify existing text
1548 var i;
1549 for (i = 0; i < Math.min(oldLen, newLen); i++) {
1550 if (newValue.charAt(i) != oldValue.charAt(i)) {
1551 inputs = newLen - i;
1552 backspaces = oldLen - i;
1553 break;
1554 }
1555 }
1556
1557 // Send the key events
1558 for (i = 0; i < backspaces; i++) {
1559 UI.rfb.sendKey(KeyTable.XK_BackSpace);
1560 }
1561 for (i = newLen - inputs; i < newLen; i++) {
1562 UI.rfb.sendKey(keysyms.fromUnicode(newValue.charCodeAt(i)).keysym);
1563 }
1564
1565 // Control the text content length in the keyboardinput element
1566 if (newLen > 2 * UI.defaultKeyboardinputLen) {
1567 UI.keyboardinputReset();
1568 } else if (newLen < 1) {
1569 // There always have to be some text in the keyboardinput
1570 // element with which backspace can interact.
1571 UI.keyboardinputReset();
1572 // This sometimes causes the keyboard to disappear for a second
1573 // but it is required for the android keyboard to recognize that
1574 // text has been added to the field
1575 event.target.blur();
1576 // This has to be ran outside of the input handler in order to work
1577 setTimeout(event.target.focus.bind(event.target), 0);
1578 } else {
1579 UI.lastKeyboardinput = newValue;
1580 }
1581 },
1582
1583 /* ------^-------
1584 * /KEYBOARD
1585 * ==============
1586 * EXTRA KEYS
1587 * ------v------*/
1588
1589 openExtraKeys: function() {
1590 UI.closeAllPanels();
1591 UI.openControlbar();
1592
1593 document.getElementById('noVNC_modifiers')
1594 .classList.add("noVNC_open");
1595 document.getElementById('noVNC_toggle_extra_keys_button')
1596 .classList.add("noVNC_selected");
1597 },
1598
1599 closeExtraKeys: function() {
1600 document.getElementById('noVNC_modifiers')
1601 .classList.remove("noVNC_open");
1602 document.getElementById('noVNC_toggle_extra_keys_button')
1603 .classList.remove("noVNC_selected");
1604 },
1605
1606 toggleExtraKeys: function() {
1607 if(document.getElementById('noVNC_modifiers')
1608 .classList.contains("noVNC_open")) {
1609 UI.closeExtraKeys();
1610 } else {
1611 UI.openExtraKeys();
1612 }
1613 },
1614
1615 sendEsc: function() {
1616 UI.rfb.sendKey(KeyTable.XK_Escape);
1617 },
1618
1619 sendTab: function() {
1620 UI.rfb.sendKey(KeyTable.XK_Tab);
1621 },
1622
1623 toggleCtrl: function() {
1624 var btn = document.getElementById('noVNC_toggle_ctrl_button');
1625 if (btn.classList.contains("noVNC_selected")) {
1626 UI.rfb.sendKey(KeyTable.XK_Control_L, false);
1627 btn.classList.remove("noVNC_selected");
1628 } else {
1629 UI.rfb.sendKey(KeyTable.XK_Control_L, true);
1630 btn.classList.add("noVNC_selected");
1631 }
1632 },
1633
1634 toggleAlt: function() {
1635 var btn = document.getElementById('noVNC_toggle_alt_button');
1636 if (btn.classList.contains("noVNC_selected")) {
1637 UI.rfb.sendKey(KeyTable.XK_Alt_L, false);
1638 btn.classList.remove("noVNC_selected");
1639 } else {
1640 UI.rfb.sendKey(KeyTable.XK_Alt_L, true);
1641 btn.classList.add("noVNC_selected");
1642 }
1643 },
1644
1645 sendCtrlAltDel: function() {
1646 UI.rfb.sendCtrlAltDel();
1647 },
1648
1649 /* ------^-------
1650 * /EXTRA KEYS
1651 * ==============
1652 * MISC
1653 * ------v------*/
1654
1655 setMouseButton: function(num) {
1656 var view_only = UI.rfb.get_view_only();
1657 if (UI.rfb && !view_only) {
1658 UI.rfb.get_mouse().set_touchButton(num);
1659 }
1660
1661 var blist = [0, 1,2,4];
1662 for (var b = 0; b < blist.length; b++) {
1663 var button = document.getElementById('noVNC_mouse_button' +
1664 blist[b]);
1665 if (blist[b] === num && !view_only) {
1666 button.classList.remove("noVNC_hidden");
1667 } else {
1668 button.classList.add("noVNC_hidden");
1669 }
1670 }
1671 },
1672
1673 displayBlur: function() {
1674 if (UI.rfb && !UI.rfb.get_view_only()) {
1675 UI.rfb.get_keyboard().set_focused(false);
1676 UI.rfb.get_mouse().set_focused(false);
1677 }
1678 },
1679
1680 displayFocus: function() {
1681 if (UI.rfb && !UI.rfb.get_view_only()) {
1682 UI.rfb.get_keyboard().set_focused(true);
1683 UI.rfb.get_mouse().set_focused(true);
1684 }
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.updateViewDrag();
1694 },
1695
1696 updateDesktopName: function(rfb, name) {
1697 UI.desktopName = name;
1698 // Display the desktop name in the document title
1699 document.title = name + " - noVNC";
1700 },
1701
1702 bell: function(rfb) {
1703 if (WebUtil.getConfigVar('bell', 'on') === 'on') {
1704 document.getElementById('noVNC_bell').play();
1705 }
1706 },
1707
1708 //Helper to add options to dropdown.
1709 addOption: function(selectbox, text, value) {
1710 var optn = document.createElement("OPTION");
1711 optn.text = text;
1712 optn.value = value;
1713 selectbox.options.add(optn);
1714 },
1715
1716 /* ------^-------
1717 * /MISC
1718 * ==============
1719 */
1720 };
1721
1722 /* [module] UI.load(); */
1723 })();
1724
1725 /* [module] export default UI; */