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