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