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