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