From 2b5f94fa6abbdfab4213f91ef04207298f35d2b7 Mon Sep 17 00:00:00 2001 From: Juanjo Diaz Date: Thu, 24 May 2018 00:27:09 +0300 Subject: [PATCH] Prefer const/let over var --- .eslintrc | 3 +- app/error-handler.js | 7 +- app/localization.js | 48 ++-- app/ui.js | 175 ++++++------- app/webutil.js | 70 ++--- core/base64.js | 59 ++--- core/des.js | 114 ++++----- core/display.js | 127 +++++---- core/encodings.js | 2 +- core/input/domkeytable.js | 2 +- core/input/keyboard.js | 50 ++-- core/input/keysymdef.js | 4 +- core/input/mouse.js | 31 +-- core/input/util.js | 12 +- core/rfb.js | 482 +++++++++++++++++------------------ core/util/browser.js | 6 +- core/util/events.js | 17 +- core/util/eventtarget.js | 2 +- core/util/logging.js | 10 +- core/util/polyfill.js | 10 +- core/websock.js | 18 +- docs/API.md | 2 +- po/po2js | 16 +- po/xgettext-html | 33 ++- tests/assertions.js | 33 ++- tests/fake.websocket.js | 8 +- tests/karma-test-main.js | 6 +- tests/playback-ui.js | 16 +- tests/playback.js | 36 +-- tests/test.base64.js | 12 +- tests/test.display.js | 73 +++--- tests/test.helper.js | 6 +- tests/test.keyboard.js | 100 ++++---- tests/test.localization.js | 5 +- tests/test.mouse.js | 48 ++-- tests/test.rfb.js | 377 ++++++++++++++------------- tests/test.util.js | 2 +- tests/test.websock.js | 64 ++--- tests/test.webutil.js | 12 +- utils/genkeysymdef.js | 43 ++-- utils/use_require.js | 65 ++--- utils/use_require_helpers.js | 22 +- 42 files changed, 1094 insertions(+), 1134 deletions(-) diff --git a/.eslintrc b/.eslintrc index b65b16c..aef4c0d 100644 --- a/.eslintrc +++ b/.eslintrc @@ -9,6 +9,7 @@ "extends": "eslint:recommended", "rules": { "no-unused-vars": ["error", { "vars": "all", "args": "none", "ignoreRestSiblings": true }], - "no-constant-condition": ["error", { "checkLoops": false }] + "no-constant-condition": ["error", { "checkLoops": false }], + "no-var": "error" } } diff --git a/app/error-handler.js b/app/error-handler.js index 5a2650f..d813349 100644 --- a/app/error-handler.js +++ b/app/error-handler.js @@ -2,21 +2,20 @@ // native support in the browsers, so that our error handler // can catch script-loading errors. - (function(){ "use strict"; // Fallback for all uncought errors function handleError (event, err) { try { - var msg = document.getElementById('noVNC_fallback_errormsg'); + const msg = document.getElementById('noVNC_fallback_errormsg'); // Only show the initial error if (msg.hasChildNodes()) { return false; } - var div = document.createElement("div"); + let div = document.createElement("div"); div.classList.add('noVNC_message'); div.appendChild(document.createTextNode(event.message)); msg.appendChild(div); @@ -24,7 +23,7 @@ if (event.filename) { div = document.createElement("div"); div.className = 'noVNC_location'; - var text = event.filename; + let text = event.filename; if (event.lineno !== undefined) { text += ":" + event.lineno; if (event.colno !== undefined) { diff --git a/app/localization.js b/app/localization.js index 43c1294..11144f7 100644 --- a/app/localization.js +++ b/app/localization.js @@ -21,25 +21,24 @@ export function Localizer() { Localizer.prototype = { // Configure suitable language based on user preferences setup: function (supportedLanguages) { - var userLanguages; - this.language = 'en'; // Default: US English /* * Navigator.languages only available in Chrome (32+) and FireFox (32+) * Fall back to navigator.language for other browsers */ + let userLanguages; if (typeof window.navigator.languages == 'object') { userLanguages = window.navigator.languages; } else { userLanguages = [navigator.language || navigator.userLanguage]; } - for (var i = 0;i < userLanguages.length;i++) { - var userLang = userLanguages[i]; - userLang = userLang.toLowerCase(); - userLang = userLang.replace("_", "-"); - userLang = userLang.split("-"); + for (let i = 0;i < userLanguages.length;i++) { + const userLang = userLanguages[i] + .toLowerCase() + .replace("_", "-") + .split("-"); // Built-in default? if ((userLang[0] === 'en') && @@ -48,12 +47,11 @@ Localizer.prototype = { } // First pass: perfect match - var j; - for (j = 0; j < supportedLanguages.length; j++) { - var supLang = supportedLanguages[j]; - supLang = supLang.toLowerCase(); - supLang = supLang.replace("_", "-"); - supLang = supLang.split("-"); + for (let j = 0; j < supportedLanguages.length; j++) { + const supLang = supportedLanguages[j] + .toLowerCase() + .replace("_", "-") + .split("-"); if (userLang[0] !== supLang[0]) continue; @@ -65,11 +63,11 @@ Localizer.prototype = { } // Second pass: fallback - for (j = 0;j < supportedLanguages.length;j++) { - supLang = supportedLanguages[j]; - supLang = supLang.toLowerCase(); - supLang = supLang.replace("_", "-"); - supLang = supLang.split("-"); + for (let j = 0;j < supportedLanguages.length;j++) { + const supLang = supportedLanguages[j] + .toLowerCase() + .replace("_", "-") + .split("-"); if (userLang[0] !== supLang[0]) continue; @@ -94,21 +92,19 @@ Localizer.prototype = { // Traverses the DOM and translates relevant fields // See https://html.spec.whatwg.org/multipage/dom.html#attr-translate translateDOM: function () { - var self = this; + const self = this; function process(elem, enabled) { function isAnyOf(searchElement, items) { return items.indexOf(searchElement) !== -1; } function translateAttribute(elem, attr) { - var str = elem.getAttribute(attr); - str = self.get(str); + const str = self.get(elem.getAttribute(attr)); elem.setAttribute(attr, str); } function translateTextNode(node) { - var str = node.data.trim(); - str = self.get(str); + const str = self.get(node.data.trim()); node.data = str; } @@ -153,8 +149,8 @@ Localizer.prototype = { } } - for (var i = 0;i < elem.childNodes.length;i++) { - var node = elem.childNodes[i]; + for (let i = 0; i < elem.childNodes.length; i++) { + const node = elem.childNodes[i]; if (node.nodeType === node.ELEMENT_NODE) { process(node, enabled); } else if (node.nodeType === node.TEXT_NODE && enabled) { @@ -167,5 +163,5 @@ Localizer.prototype = { }, }; -export var l10n = new Localizer(); +export const l10n = new Localizer(); export default l10n.get.bind(l10n); diff --git a/app/ui.js b/app/ui.js index 8515387..d587cfc 100644 --- a/app/ui.js +++ b/app/ui.js @@ -18,7 +18,7 @@ import Keyboard from "../core/input/keyboard.js"; import RFB from "../core/rfb.js"; import * as WebUtil from "./webutil.js"; -var UI = { +const UI = { connected: false, desktopName: "", @@ -101,7 +101,7 @@ var UI = { document.documentElement.classList.remove("noVNC_loading"); - var autoconnect = WebUtil.getConfigVar('autoconnect', false); + let autoconnect = WebUtil.getConfigVar('autoconnect', false); if (autoconnect === 'true' || autoconnect == '1') { autoconnect = true; UI.connect(); @@ -131,12 +131,10 @@ var UI = { }, initSettings: function() { - var i; - // Logging selection dropdown - var llevels = ['error', 'warn', 'info', 'debug']; - for (i = 0; i < llevels.length; i += 1) { - UI.addOption(document.getElementById('noVNC_setting_logging'),llevels[i], llevels[i]); + const llevels = ['error', 'warn', 'info', 'debug']; + for (let i = 0; i < llevels.length; i += 1) { + UI.addOption(document.getElementById('noVNC_setting_logging'), llevels[i], llevels[i]); } // Settings with immediate effects @@ -145,7 +143,7 @@ var UI = { // if port == 80 (or 443) then it won't be present and should be // set manually - var port = window.location.port; + let port = window.location.port; if (!port) { if (window.location.protocol.substring(0,5) == 'https') { port = 443; @@ -172,16 +170,16 @@ var UI = { }, // Adds a link to the label elements on the corresponding input elements setupSettingLabels: function() { - var labels = document.getElementsByTagName('LABEL'); - for (var i = 0; i < labels.length; i++) { - var htmlFor = labels[i].htmlFor; + const labels = document.getElementsByTagName('LABEL'); + for (let i = 0; i < labels.length; i++) { + const htmlFor = labels[i].htmlFor; if (htmlFor != '') { - var elem = document.getElementById(htmlFor); + const elem = document.getElementById(htmlFor); if (elem) elem.label = labels[i]; } else { // If 'for' isn't set, use the first input element child - var children = labels[i].children; - for (var j = 0; j < children.length; j++) { + const children = labels[i].children; + for (let j = 0; j < children.length; j++) { if (children[j].form !== undefined) { children[j].label = labels[i]; break; @@ -224,8 +222,8 @@ var UI = { // resize events aren't available for elements window.addEventListener('resize', UI.updateControlbarHandle); - var exps = document.getElementsByClassName("noVNC_expander"); - for (var i = 0;i < exps.length;i++) { + const exps = document.getElementsByClassName("noVNC_expander"); + for (let i = 0;i < exps.length;i++) { exps[i].addEventListener('click', UI.toggleExpander); } }, @@ -329,7 +327,7 @@ var UI = { // Add a call to save settings when the element changes, // unless the optional parameter changeFunc is used instead. addSettingChangeHandler: function(name, changeFunc) { - var settingElem = document.getElementById("noVNC_setting_" + name); + const settingElem = document.getElementById("noVNC_setting_" + name); if (changeFunc === undefined) { changeFunc = function () { UI.saveSetting(name); }; } @@ -383,7 +381,7 @@ var UI = { document.documentElement.classList.remove("noVNC_disconnecting"); document.documentElement.classList.remove("noVNC_reconnecting"); - let transition_elem = document.getElementById("noVNC_transition_text"); + const transition_elem = document.getElementById("noVNC_transition_text"); switch (state) { case 'init': break; @@ -444,7 +442,7 @@ var UI = { }, showStatus: function(text, status_type, time) { - var statusElem = document.getElementById('noVNC_status'); + const statusElem = document.getElementById('noVNC_status'); clearTimeout(UI.statusTimeout); @@ -550,15 +548,15 @@ var UI = { toggleControlbarSide: function () { // Temporarily disable animation, if bar is displayed, to avoid weird // movement. The transitionend-event will not fire when display=none. - var bar = document.getElementById('noVNC_control_bar'); - var barDisplayStyle = window.getComputedStyle(bar).display; + const bar = document.getElementById('noVNC_control_bar'); + const barDisplayStyle = window.getComputedStyle(bar).display; if (barDisplayStyle !== 'none') { bar.style.transitionDuration = '0s'; bar.addEventListener('transitionend', function () { this.style.transitionDuration = ""; }); } - var anchor = document.getElementById('noVNC_control_bar_anchor'); + const anchor = document.getElementById('noVNC_control_bar_anchor'); if (anchor.classList.contains("noVNC_right")) { WebUtil.writeSetting('controlbar_pos', 'left'); anchor.classList.remove("noVNC_right"); @@ -572,7 +570,7 @@ var UI = { }, showControlbarHint: function (show) { - var hint = document.getElementById('noVNC_control_bar_hint'); + const hint = document.getElementById('noVNC_control_bar_hint'); if (show) { hint.classList.add("noVNC_active"); } else { @@ -583,9 +581,9 @@ var UI = { dragControlbarHandle: function (e) { if (!UI.controlbarGrabbed) return; - var ptr = getPointerEvent(e); + const ptr = getPointerEvent(e); - var anchor = document.getElementById('noVNC_control_bar_anchor'); + const anchor = document.getElementById('noVNC_control_bar_anchor'); if (ptr.clientX < (window.innerWidth * 0.1)) { if (anchor.classList.contains("noVNC_right")) { UI.toggleControlbarSide(); @@ -599,15 +597,15 @@ var UI = { if (!UI.controlbarDrag) { // The goal is to trigger on a certain physical width, the // devicePixelRatio brings us a bit closer but is not optimal. - var dragThreshold = 10 * (window.devicePixelRatio || 1); - var dragDistance = Math.abs(ptr.clientY - UI.controlbarMouseDownClientY); + const dragThreshold = 10 * (window.devicePixelRatio || 1); + const dragDistance = Math.abs(ptr.clientY - UI.controlbarMouseDownClientY); if (dragDistance < dragThreshold) return; UI.controlbarDrag = true; } - var eventY = ptr.clientY - UI.controlbarMouseDownOffsetY; + const eventY = ptr.clientY - UI.controlbarMouseDownOffsetY; UI.moveControlbarHandle(eventY); @@ -619,18 +617,18 @@ var UI = { // Move the handle but don't allow any position outside the bounds moveControlbarHandle: function (viewportRelativeY) { - var handle = document.getElementById("noVNC_control_bar_handle"); - var handleHeight = handle.getBoundingClientRect().height; - var controlbarBounds = document.getElementById("noVNC_control_bar") + const handle = document.getElementById("noVNC_control_bar_handle"); + const handleHeight = handle.getBoundingClientRect().height; + const controlbarBounds = document.getElementById("noVNC_control_bar") .getBoundingClientRect(); - var margin = 10; + const margin = 10; // These heights need to be non-zero for the below logic to work if (handleHeight === 0 || controlbarBounds.height === 0) { return; } - var newY = viewportRelativeY; + let newY = viewportRelativeY; // Check if the coordinates are outside the control bar if (newY < controlbarBounds.top + margin) { @@ -651,15 +649,15 @@ var UI = { } // The transform needs coordinates that are relative to the parent - var parentRelativeY = newY - controlbarBounds.top; + const parentRelativeY = newY - controlbarBounds.top; handle.style.transform = "translateY(" + parentRelativeY + "px)"; }, updateControlbarHandle: function () { // Since the control bar is fixed on the viewport and not the page, // the move function expects coordinates relative the the viewport. - var handle = document.getElementById("noVNC_control_bar_handle"); - var handleBounds = handle.getBoundingClientRect(); + const handle = document.getElementById("noVNC_control_bar_handle"); + const handleBounds = handle.getBoundingClientRect(); UI.moveControlbarHandle(handleBounds.top); }, @@ -681,10 +679,10 @@ var UI = { controlbarHandleMouseDown: function(e) { if ((e.type == "mousedown") && (e.button != 0)) return; - var ptr = getPointerEvent(e); + const ptr = getPointerEvent(e); - var handle = document.getElementById("noVNC_control_bar_handle"); - var bounds = handle.getBoundingClientRect(); + const handle = document.getElementById("noVNC_control_bar_handle"); + const bounds = handle.getBoundingClientRect(); // Touch events have implicit capture if (e.type === "mousedown") { @@ -721,7 +719,7 @@ var UI = { // Initial page load read/initialization of settings initSetting: function(name, defVal) { // Check Query string followed by cookie - var val = WebUtil.getConfigVar(name); + let val = WebUtil.getConfigVar(name); if (val === null) { val = WebUtil.readSetting(name, defVal); } @@ -735,14 +733,14 @@ var UI = { updateSetting: function(name) { // Update the settings control - var value = UI.getSetting(name); + let value = UI.getSetting(name); - var ctrl = document.getElementById('noVNC_setting_' + name); + const ctrl = document.getElementById('noVNC_setting_' + name); if (ctrl.type === 'checkbox') { ctrl.checked = value; } else if (typeof ctrl.options !== 'undefined') { - for (var i = 0; i < ctrl.options.length; i += 1) { + for (let i = 0; i < ctrl.options.length; i += 1) { if (ctrl.options[i].value === value) { ctrl.selectedIndex = i; break; @@ -760,7 +758,8 @@ var UI = { // Save control setting to cookie saveSetting: function(name) { - var val, ctrl = document.getElementById('noVNC_setting_' + name); + const ctrl = document.getElementById('noVNC_setting_' + name); + let val; if (ctrl.type === 'checkbox') { val = ctrl.checked; } else if (typeof ctrl.options !== 'undefined') { @@ -775,8 +774,8 @@ var UI = { // Read form control compatible setting from cookie getSetting: function(name) { - var ctrl = document.getElementById('noVNC_setting_' + name); - var val = WebUtil.readSetting(name); + const ctrl = document.getElementById('noVNC_setting_' + name); + let val = WebUtil.readSetting(name); if (typeof val !== 'undefined' && val !== null && ctrl.type === 'checkbox') { if (val.toString().toLowerCase() in {'0':1, 'no':1, 'false':1}) { val = false; @@ -791,13 +790,13 @@ var UI = { // previous-sibling-selectors in CSS which are needed when we want to // disable the labels that belong to disabled input elements. disableSetting: function(name) { - var ctrl = document.getElementById('noVNC_setting_' + name); + const ctrl = document.getElementById('noVNC_setting_' + name); ctrl.disabled = true; ctrl.label.classList.add('noVNC_disabled'); }, enableSetting: function(name) { - var ctrl = document.getElementById('noVNC_setting_' + name); + const ctrl = document.getElementById('noVNC_setting_' + name); ctrl.disabled = false; ctrl.label.classList.remove('noVNC_disabled'); }, @@ -950,7 +949,7 @@ var UI = { }, clipboardSend: function() { - var text = document.getElementById('noVNC_clipboard_text').value; + const text = document.getElementById('noVNC_clipboard_text').value; Log.Debug(">> UI.clipboardSend: " + text.substr(0,40) + "..."); UI.rfb.clipboardPasteFrom(text); Log.Debug("<< UI.clipboardSend"); @@ -979,9 +978,9 @@ var UI = { return; } - var host = UI.getSetting('host'); - var port = UI.getSetting('port'); - var path = UI.getSetting('path'); + const host = UI.getSetting('host'); + const port = UI.getSetting('port'); + const path = UI.getSetting('path'); if (typeof password === 'undefined') { password = WebUtil.getConfigVar('password'); @@ -1005,7 +1004,7 @@ var UI = { UI.updateVisualState('connecting'); - var url; + let url; url = UI.getSetting('encrypt') ? 'wss' : 'ws'; @@ -1089,7 +1088,7 @@ var UI = { }, disconnectFinished: function (e) { - let wasConnected = UI.connected; + const wasConnected = UI.connected; // This variable is ideally set when disconnection starts, but // when the disconnection isn't clean or if it is initiated by @@ -1110,7 +1109,7 @@ var UI = { } else if (UI.getSetting('reconnect', false) === true && !UI.inhibit_reconnect) { UI.updateVisualState('reconnecting'); - var delay = parseInt(UI.getSetting('reconnect_delay')); + const delay = parseInt(UI.getSetting('reconnect_delay')); UI.reconnect_callback = setTimeout(UI.reconnect, delay); return; } else { @@ -1159,8 +1158,8 @@ var UI = { // Prevent actually submitting the form e.preventDefault(); - var inputElem = document.getElementById('noVNC_password_input'); - var password = inputElem.value; + const inputElem = document.getElementById('noVNC_password_input'); + const password = inputElem.value; // Clear the input after reading the password inputElem.value = ""; UI.rfb.sendCredentials({ password: password }); @@ -1241,8 +1240,8 @@ var UI = { updateViewClip: function() { if (!UI.rfb) return; - var cur_clip = UI.rfb.clipViewport; - var new_clip = UI.getSetting('view_clip'); + const cur_clip = UI.rfb.clipViewport; + let new_clip = UI.getSetting('view_clip'); if (isTouchDevice) { // Touch devices usually have shit scrollbars @@ -1260,7 +1259,7 @@ var UI = { // Handle special cases where viewport clipping is forced on/off or locked enableDisableViewClip: function() { - var resizeSetting = UI.getSetting('resize'); + const resizeSetting = UI.getSetting('resize'); // Disable clipping if we are scaling, connected or on touch if (resizeSetting === 'scale' || isTouchDevice) { @@ -1279,7 +1278,7 @@ var UI = { toggleViewDrag: function() { if (!UI.rfb) return; - var drag = UI.rfb.dragViewport; + const drag = UI.rfb.dragViewport; UI.setViewDrag(!drag); }, @@ -1295,7 +1294,7 @@ var UI = { updateViewDrag: function() { if (!UI.connected) return; - var viewDragButton = document.getElementById('noVNC_view_drag_button'); + const viewDragButton = document.getElementById('noVNC_view_drag_button'); if (!UI.rfb.clipViewport && UI.rfb.dragViewport) { // We are no longer clipping the viewport. Make sure @@ -1339,14 +1338,14 @@ var UI = { showVirtualKeyboard: function() { if (!isTouchDevice) return; - var input = document.getElementById('noVNC_keyboardinput'); + const input = document.getElementById('noVNC_keyboardinput'); if (document.activeElement == input) return; input.focus(); try { - var l = input.value.length; + const l = input.value.length; // Move the caret to the end input.setSelectionRange(l, l); } catch (err) { @@ -1357,7 +1356,7 @@ var UI = { hideVirtualKeyboard: function() { if (!isTouchDevice) return; - var input = document.getElementById('noVNC_keyboardinput'); + const input = document.getElementById('noVNC_keyboardinput'); if (document.activeElement != input) return; @@ -1390,7 +1389,7 @@ var UI = { }, keepVirtualKeyboard: function(event) { - var input = document.getElementById('noVNC_keyboardinput'); + const input = document.getElementById('noVNC_keyboardinput'); // Only prevent focus change if the virtual keyboard is active if (document.activeElement != input) { @@ -1418,7 +1417,7 @@ var UI = { }, keyboardinputReset: function() { - var kbi = document.getElementById('noVNC_keyboardinput'); + const kbi = document.getElementById('noVNC_keyboardinput'); kbi.value = new Array(UI.defaultKeyboardinputLen).join("_"); UI.lastKeyboardinput = kbi.value; }, @@ -1437,14 +1436,14 @@ var UI = { if (!UI.rfb) return; - var newValue = event.target.value; + const newValue = event.target.value; if (!UI.lastKeyboardinput) { UI.keyboardinputReset(); } - var oldValue = UI.lastKeyboardinput; + const oldValue = UI.lastKeyboardinput; - var newLen; + let newLen; try { // Try to check caret position since whitespace at the end // will not be considered by value.length in some browsers @@ -1453,20 +1452,14 @@ var UI = { // selectionStart is undefined in Google Chrome newLen = newValue.length; } - var oldLen = oldValue.length; + const oldLen = oldValue.length; - var backspaces; - var inputs = newLen - oldLen; - if (inputs < 0) { - backspaces = -inputs; - } else { - backspaces = 0; - } + let inputs = newLen - oldLen; + let backspaces = inputs < 0 ? -inputs : 0; // Compare the old string with the new to account for // text-corrections or other input that modify existing text - var i; - for (i = 0; i < Math.min(oldLen, newLen); i++) { + for (let i = 0; i < Math.min(oldLen, newLen); i++) { if (newValue.charAt(i) != oldValue.charAt(i)) { inputs = newLen - i; backspaces = oldLen - i; @@ -1475,10 +1468,10 @@ var UI = { } // Send the key events - for (i = 0; i < backspaces; i++) { + for (let i = 0; i < backspaces; i++) { UI.rfb.sendKey(KeyTable.XK_BackSpace, "Backspace"); } - for (i = newLen - inputs; i < newLen; i++) { + for (let i = newLen - inputs; i < newLen; i++) { UI.rfb.sendKey(keysyms.lookup(newValue.charCodeAt(i))); } @@ -1541,7 +1534,7 @@ var UI = { }, toggleCtrl: function() { - var btn = document.getElementById('noVNC_toggle_ctrl_button'); + const btn = document.getElementById('noVNC_toggle_ctrl_button'); if (btn.classList.contains("noVNC_selected")) { UI.rfb.sendKey(KeyTable.XK_Control_L, "ControlLeft", false); btn.classList.remove("noVNC_selected"); @@ -1552,7 +1545,7 @@ var UI = { }, toggleAlt: function() { - var btn = document.getElementById('noVNC_toggle_alt_button'); + const btn = document.getElementById('noVNC_toggle_alt_button'); if (btn.classList.contains("noVNC_selected")) { UI.rfb.sendKey(KeyTable.XK_Alt_L, "AltLeft", false); btn.classList.remove("noVNC_selected"); @@ -1573,14 +1566,14 @@ var UI = { * ------v------*/ setMouseButton: function(num) { - var view_only = UI.rfb.viewOnly; + const view_only = UI.rfb.viewOnly; if (UI.rfb && !view_only) { UI.rfb.touchButton = num; } - var blist = [0, 1,2,4]; - for (var b = 0; b < blist.length; b++) { - var button = document.getElementById('noVNC_mouse_button' + + const blist = [0, 1,2,4]; + for (let b = 0; b < blist.length; b++) { + const button = document.getElementById('noVNC_mouse_button' + blist[b]); if (blist[b] === num && !view_only) { button.classList.remove("noVNC_hidden"); @@ -1621,7 +1614,7 @@ var UI = { bell: function(e) { if (WebUtil.getConfigVar('bell', 'on') === 'on') { - var promise = document.getElementById('noVNC_bell').play(); + const promise = document.getElementById('noVNC_bell').play(); // The standards disagree on the return value here if (promise) { promise.catch(function(e) { @@ -1639,7 +1632,7 @@ var UI = { //Helper to add options to dropdown. addOption: function(selectbox, text, value) { - var optn = document.createElement("OPTION"); + const optn = document.createElement("OPTION"); optn.text = text; optn.value = value; selectbox.options.add(optn); @@ -1652,7 +1645,7 @@ var UI = { }; // Set up translations -var LINGUAS = ["de", "el", "es", "nl", "pl", "sv", "tr", "zh_CN", "zh_TW"]; +const LINGUAS = ["de", "el", "es", "nl", "pl", "sv", "tr", "zh_CN", "zh_TW"]; l10n.setup(LINGUAS); if (l10n.language !== "en" && l10n.dictionary === undefined) { WebUtil.fetchJSON('app/locale/' + l10n.language + '.json', function (translations) { diff --git a/app/webutil.js b/app/webutil.js index 73d24af..18816d1 100644 --- a/app/webutil.js +++ b/app/webutil.js @@ -15,7 +15,7 @@ export function init_logging (level) { if (typeof level !== "undefined") { main_init_logging(level); } else { - var param = document.location.href.match(/logging=([A-Za-z0-9._-]*)/); + const param = document.location.href.match(/logging=([A-Za-z0-9._-]*)/); main_init_logging(param || undefined); } } @@ -23,37 +23,41 @@ export function init_logging (level) { // Read a query string variable export function getQueryVar (name, defVal) { "use strict"; - var re = new RegExp('.*[?&]' + name + '=([^&#]*)'), + const re = new RegExp('.*[?&]' + name + '=([^&#]*)'), match = document.location.href.match(re); if (typeof defVal === 'undefined') { defVal = null; } + if (match) { return decodeURIComponent(match[1]); - } else { - return defVal; } + + return defVal; } // Read a hash fragment variable export function getHashVar (name, defVal) { "use strict"; - var re = new RegExp('.*[&#]' + name + '=([^&]*)'), + const re = new RegExp('.*[&#]' + name + '=([^&]*)'), match = document.location.hash.match(re); if (typeof defVal === 'undefined') { defVal = null; } + if (match) { return decodeURIComponent(match[1]); - } else { - return defVal; } + + return defVal; } // Read a variable from the fragment or the query string // Fragment takes precedence export function getConfigVar (name, defVal) { "use strict"; - var val = getHashVar(name); + const val = getHashVar(name); + if (val === null) { - val = getQueryVar(name, defVal); + return getQueryVar(name, defVal); } + return val; } @@ -64,7 +68,7 @@ export function getConfigVar (name, defVal) { // No days means only for this browser session export function createCookie (name, value, days) { "use strict"; - var date, expires; + let date, expires; if (days) { date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); @@ -73,7 +77,7 @@ export function createCookie (name, value, days) { expires = ""; } - var secure; + let secure; if (document.location.protocol === "https:") { secure = "; secure"; } else { @@ -84,14 +88,19 @@ export function createCookie (name, value, days) { export function readCookie (name, defaultValue) { "use strict"; - var nameEQ = name + "=", - ca = document.cookie.split(';'); + const nameEQ = name + "="; + const ca = document.cookie.split(';'); - for (var i = 0; i < ca.length; i += 1) { - var c = ca[i]; - while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } - if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } + for (let i = 0; i < ca.length; i += 1) { + let c = ca[i]; + while (c.charAt(0) === ' ') { + c = c.substring(1, c.length); + } + if (c.indexOf(nameEQ) === 0) { + return c.substring(nameEQ.length, c.length); + } } + return (typeof defaultValue !== 'undefined') ? defaultValue : null; } @@ -104,11 +113,11 @@ export function eraseCookie (name) { * Setting handling. */ -var settings = {}; +let settings = {}; export function initSettings (callback /*, ...callbackArgs */) { "use strict"; - var callbackArgs = Array.prototype.slice.call(arguments, 1); + const callbackArgs = Array.prototype.slice.call(arguments, 1); if (window.chrome && window.chrome.storage) { window.chrome.storage.sync.get(function (cfg) { settings = cfg; @@ -143,7 +152,7 @@ export function writeSetting (name, value) { export function readSetting (name, defaultValue) { "use strict"; - var value; + let value; if ((name in settings) || (window.chrome && window.chrome.storage)) { value = settings[name]; } else { @@ -153,11 +162,12 @@ export function readSetting (name, defaultValue) { if (typeof value === "undefined") { value = null; } + if (value === null && typeof defaultValue !== "undefined") { return defaultValue; - } else { - return value; } + + return value; } export function eraseSetting (name) { @@ -180,11 +190,11 @@ export function injectParamIfMissing (path, param, value) { // (assume that we wanted an extra if we pass one in) path = "/" + path; - var elem = document.createElement('a'); + const elem = document.createElement('a'); elem.href = path; - var param_eq = encodeURIComponent(param) + "="; - var query; + const param_eq = encodeURIComponent(param) + "="; + let query; if (elem.search) { query = elem.search.slice(1).split('&'); } else { @@ -200,9 +210,9 @@ export function injectParamIfMissing (path, param, value) { // in the elem.pathname string. Handle that case gracefully. if (elem.pathname.charAt(0) == "/") { return elem.pathname.slice(1) + elem.search + elem.hash; - } else { - return elem.pathname + elem.search + elem.hash; } + + return elem.pathname + elem.search + elem.hash; } // sadly, we can't use the Fetch API until we decide to drop @@ -211,16 +221,16 @@ export function injectParamIfMissing (path, param, value) { // will receive either an event or an error on failure. export function fetchJSON(path, resolve, reject) { // NB: IE11 doesn't support JSON as a responseType - var req = new XMLHttpRequest(); + const req = new XMLHttpRequest(); req.open('GET', path); req.onload = function () { if (req.status === 200) { + let resObj; try { - var resObj = JSON.parse(req.responseText); + resObj = JSON.parse(req.responseText); } catch (err) { reject(err); - return; } resolve(resObj); } else { diff --git a/core/base64.js b/core/base64.js index 48e28c3..d57d986 100644 --- a/core/base64.js +++ b/core/base64.js @@ -13,33 +13,30 @@ export default { encode: function (data) { "use strict"; - var result = ''; - var toBase64Table = this.toBase64Table; - var length = data.length; - var lengthpad = (length % 3); + let result = ''; + const length = data.length; + const lengthpad = (length % 3); // Convert every three bytes to 4 ascii characters. - for (var i = 0; i < (length - 2); i += 3) { - result += toBase64Table[data[i] >> 2]; - result += toBase64Table[((data[i] & 0x03) << 4) + (data[i + 1] >> 4)]; - result += toBase64Table[((data[i + 1] & 0x0f) << 2) + (data[i + 2] >> 6)]; - result += toBase64Table[data[i + 2] & 0x3f]; + for (let i = 0; i < (length - 2); i += 3) { + result += this.toBase64Table[data[i] >> 2]; + result += this.toBase64Table[((data[i] & 0x03) << 4) + (data[i + 1] >> 4)]; + result += this.toBase64Table[((data[i + 1] & 0x0f) << 2) + (data[i + 2] >> 6)]; + result += this.toBase64Table[data[i + 2] & 0x3f]; } // Convert the remaining 1 or 2 bytes, pad out to 4 characters. - var j = 0; + const j = length - lengthpad; if (lengthpad === 2) { - j = length - lengthpad; - result += toBase64Table[data[j] >> 2]; - result += toBase64Table[((data[j] & 0x03) << 4) + (data[j + 1] >> 4)]; - result += toBase64Table[(data[j + 1] & 0x0f) << 2]; - result += toBase64Table[64]; + result += this.toBase64Table[data[j] >> 2]; + result += this.toBase64Table[((data[j] & 0x03) << 4) + (data[j + 1] >> 4)]; + result += this.toBase64Table[(data[j + 1] & 0x0f) << 2]; + result += this.toBase64Table[64]; } else if (lengthpad === 1) { - j = length - lengthpad; - result += toBase64Table[data[j] >> 2]; - result += toBase64Table[(data[j] & 0x03) << 4]; - result += toBase64Table[64]; - result += toBase64Table[64]; + result += this.toBase64Table[data[j] >> 2]; + result += this.toBase64Table[(data[j] & 0x03) << 4]; + result += this.toBase64Table[64]; + result += this.toBase64Table[64]; } return result; @@ -60,23 +57,21 @@ export default { decode: function (data, offset) { "use strict"; offset = typeof(offset) !== 'undefined' ? offset : 0; - var toBinaryTable = this.toBinaryTable; - var base64Pad = this.base64Pad; - var result, result_length; - var leftbits = 0; // number of bits decoded, but yet to be appended - var leftdata = 0; // bits decoded, but yet to be appended - var data_length = data.indexOf('=') - offset; + let data_length = data.indexOf('=') - offset; if (data_length < 0) { data_length = data.length - offset; } /* Every four characters is 3 resulting numbers */ - result_length = (data_length >> 2) * 3 + Math.floor((data_length % 4) / 1.5); - result = new Array(result_length); + const result_length = (data_length >> 2) * 3 + Math.floor((data_length % 4) / 1.5); + const result = new Array(result_length); // Convert one by one. - for (var idx = 0, i = offset; i < data.length; i++) { - var c = toBinaryTable[data.charCodeAt(i) & 0x7f]; - var padding = (data.charAt(i) === base64Pad); + + let leftbits = 0; // number of bits decoded, but yet to be appended + let leftdata = 0; // bits decoded, but yet to be appended + for (let idx = 0, i = offset; i < data.length; i++) { + const c = this.toBinaryTable[data.charCodeAt(i) & 0x7f]; + const padding = (data.charAt(i) === this.base64Pad); // Skip illegal characters and whitespace if (c === -1) { Log.Error("Illegal character code " + data.charCodeAt(i) + " at position " + i); @@ -100,7 +95,7 @@ export default { // If there are any bits left, the base64 string was corrupted if (leftbits) { - var err = new Error('Corrupted base64 string'); + const err = new Error('Corrupted base64 string'); err.name = 'Base64-Error'; throw err; } diff --git a/core/des.js b/core/des.js index 821929b..5adc7ae 100644 --- a/core/des.js +++ b/core/des.js @@ -79,80 +79,76 @@ export default function DES(passwd) { "use strict"; // Tables, permutations, S-boxes, etc. - var PC2 = [13,16,10,23, 0, 4, 2,27,14, 5,20, 9,22,18,11, 3, - 25, 7,15, 6,26,19,12, 1,40,51,30,36,46,54,29,39, - 50,44,32,47,43,48,38,55,33,52,45,41,49,35,28,31 ], + const PC2 = [13,16,10,23, 0, 4, 2,27,14, 5,20, 9,22,18,11, 3, + 25, 7,15, 6,26,19,12, 1,40,51,30,36,46,54,29,39, + 50,44,32,47,43,48,38,55,33,52,45,41,49,35,28,31 ], totrot = [ 1, 2, 4, 6, 8,10,12,14,15,17,19,21,23,25,27,28], - z = 0x0, a,b,c,d,e,f, SP1,SP2,SP3,SP4,SP5,SP6,SP7,SP8, + z = 0x0, keys = []; + let a,b,c,d,e,f; a=1<<16; b=1<<24; c=a|b; d=1<<2; e=1<<10; f=d|e; - SP1 = [c|e,z|z,a|z,c|f,c|d,a|f,z|d,a|z,z|e,c|e,c|f,z|e,b|f,c|d,b|z,z|d, - z|f,b|e,b|e,a|e,a|e,c|z,c|z,b|f,a|d,b|d,b|d,a|d,z|z,z|f,a|f,b|z, - a|z,c|f,z|d,c|z,c|e,b|z,b|z,z|e,c|d,a|z,a|e,b|d,z|e,z|d,b|f,a|f, - c|f,a|d,c|z,b|f,b|d,z|f,a|f,c|e,z|f,b|e,b|e,z|z,a|d,a|e,z|z,c|d]; + const SP1 = [c|e,z|z,a|z,c|f,c|d,a|f,z|d,a|z,z|e,c|e,c|f,z|e,b|f,c|d,b|z,z|d, + z|f,b|e,b|e,a|e,a|e,c|z,c|z,b|f,a|d,b|d,b|d,a|d,z|z,z|f,a|f,b|z, + a|z,c|f,z|d,c|z,c|e,b|z,b|z,z|e,c|d,a|z,a|e,b|d,z|e,z|d,b|f,a|f, + c|f,a|d,c|z,b|f,b|d,z|f,a|f,c|e,z|f,b|e,b|e,z|z,a|d,a|e,z|z,c|d]; a=1<<20; b=1<<31; c=a|b; d=1<<5; e=1<<15; f=d|e; - SP2 = [c|f,b|e,z|e,a|f,a|z,z|d,c|d,b|f,b|d,c|f,c|e,b|z,b|e,a|z,z|d,c|d, - a|e,a|d,b|f,z|z,b|z,z|e,a|f,c|z,a|d,b|d,z|z,a|e,z|f,c|e,c|z,z|f, - z|z,a|f,c|d,a|z,b|f,c|z,c|e,z|e,c|z,b|e,z|d,c|f,a|f,z|d,z|e,b|z, - z|f,c|e,a|z,b|d,a|d,b|f,b|d,a|d,a|e,z|z,b|e,z|f,b|z,c|d,c|f,a|e]; + const SP2 = [c|f,b|e,z|e,a|f,a|z,z|d,c|d,b|f,b|d,c|f,c|e,b|z,b|e,a|z,z|d,c|d, + a|e,a|d,b|f,z|z,b|z,z|e,a|f,c|z,a|d,b|d,z|z,a|e,z|f,c|e,c|z,z|f, + z|z,a|f,c|d,a|z,b|f,c|z,c|e,z|e,c|z,b|e,z|d,c|f,a|f,z|d,z|e,b|z, + z|f,c|e,a|z,b|d,a|d,b|f,b|d,a|d,a|e,z|z,b|e,z|f,b|z,c|d,c|f,a|e]; a=1<<17; b=1<<27; c=a|b; d=1<<3; e=1<<9; f=d|e; - SP3 = [z|f,c|e,z|z,c|d,b|e,z|z,a|f,b|e,a|d,b|d,b|d,a|z,c|f,a|d,c|z,z|f, - b|z,z|d,c|e,z|e,a|e,c|z,c|d,a|f,b|f,a|e,a|z,b|f,z|d,c|f,z|e,b|z, - c|e,b|z,a|d,z|f,a|z,c|e,b|e,z|z,z|e,a|d,c|f,b|e,b|d,z|e,z|z,c|d, - b|f,a|z,b|z,c|f,z|d,a|f,a|e,b|d,c|z,b|f,z|f,c|z,a|f,z|d,c|d,a|e]; + const SP3 = [z|f,c|e,z|z,c|d,b|e,z|z,a|f,b|e,a|d,b|d,b|d,a|z,c|f,a|d,c|z,z|f, + b|z,z|d,c|e,z|e,a|e,c|z,c|d,a|f,b|f,a|e,a|z,b|f,z|d,c|f,z|e,b|z, + c|e,b|z,a|d,z|f,a|z,c|e,b|e,z|z,z|e,a|d,c|f,b|e,b|d,z|e,z|z,c|d, + b|f,a|z,b|z,c|f,z|d,a|f,a|e,b|d,c|z,b|f,z|f,c|z,a|f,z|d,c|d,a|e]; a=1<<13; b=1<<23; c=a|b; d=1<<0; e=1<<7; f=d|e; - SP4 = [c|d,a|f,a|f,z|e,c|e,b|f,b|d,a|d,z|z,c|z,c|z,c|f,z|f,z|z,b|e,b|d, - z|d,a|z,b|z,c|d,z|e,b|z,a|d,a|e,b|f,z|d,a|e,b|e,a|z,c|e,c|f,z|f, - b|e,b|d,c|z,c|f,z|f,z|z,z|z,c|z,a|e,b|e,b|f,z|d,c|d,a|f,a|f,z|e, - c|f,z|f,z|d,a|z,b|d,a|d,c|e,b|f,a|d,a|e,b|z,c|d,z|e,b|z,a|z,c|e]; + const SP4 = [c|d,a|f,a|f,z|e,c|e,b|f,b|d,a|d,z|z,c|z,c|z,c|f,z|f,z|z,b|e,b|d, + z|d,a|z,b|z,c|d,z|e,b|z,a|d,a|e,b|f,z|d,a|e,b|e,a|z,c|e,c|f,z|f, + b|e,b|d,c|z,c|f,z|f,z|z,z|z,c|z,a|e,b|e,b|f,z|d,c|d,a|f,a|f,z|e, + c|f,z|f,z|d,a|z,b|d,a|d,c|e,b|f,a|d,a|e,b|z,c|d,z|e,b|z,a|z,c|e]; a=1<<25; b=1<<30; c=a|b; d=1<<8; e=1<<19; f=d|e; - SP5 = [z|d,a|f,a|e,c|d,z|e,z|d,b|z,a|e,b|f,z|e,a|d,b|f,c|d,c|e,z|f,b|z, - a|z,b|e,b|e,z|z,b|d,c|f,c|f,a|d,c|e,b|d,z|z,c|z,a|f,a|z,c|z,z|f, - z|e,c|d,z|d,a|z,b|z,a|e,c|d,b|f,a|d,b|z,c|e,a|f,b|f,z|d,a|z,c|e, - c|f,z|f,c|z,c|f,a|e,z|z,b|e,c|z,z|f,a|d,b|d,z|e,z|z,b|e,a|f,b|d]; + const SP5 = [z|d,a|f,a|e,c|d,z|e,z|d,b|z,a|e,b|f,z|e,a|d,b|f,c|d,c|e,z|f,b|z, + a|z,b|e,b|e,z|z,b|d,c|f,c|f,a|d,c|e,b|d,z|z,c|z,a|f,a|z,c|z,z|f, + z|e,c|d,z|d,a|z,b|z,a|e,c|d,b|f,a|d,b|z,c|e,a|f,b|f,z|d,a|z,c|e, + c|f,z|f,c|z,c|f,a|e,z|z,b|e,c|z,z|f,a|d,b|d,z|e,z|z,b|e,a|f,b|d]; a=1<<22; b=1<<29; c=a|b; d=1<<4; e=1<<14; f=d|e; - SP6 = [b|d,c|z,z|e,c|f,c|z,z|d,c|f,a|z,b|e,a|f,a|z,b|d,a|d,b|e,b|z,z|f, - z|z,a|d,b|f,z|e,a|e,b|f,z|d,c|d,c|d,z|z,a|f,c|e,z|f,a|e,c|e,b|z, - b|e,z|d,c|d,a|e,c|f,a|z,z|f,b|d,a|z,b|e,b|z,z|f,b|d,c|f,a|e,c|z, - a|f,c|e,z|z,c|d,z|d,z|e,c|z,a|f,z|e,a|d,b|f,z|z,c|e,b|z,a|d,b|f]; + const SP6 = [b|d,c|z,z|e,c|f,c|z,z|d,c|f,a|z,b|e,a|f,a|z,b|d,a|d,b|e,b|z,z|f, + z|z,a|d,b|f,z|e,a|e,b|f,z|d,c|d,c|d,z|z,a|f,c|e,z|f,a|e,c|e,b|z, + b|e,z|d,c|d,a|e,c|f,a|z,z|f,b|d,a|z,b|e,b|z,z|f,b|d,c|f,a|e,c|z, + a|f,c|e,z|z,c|d,z|d,z|e,c|z,a|f,z|e,a|d,b|f,z|z,c|e,b|z,a|d,b|f]; a=1<<21; b=1<<26; c=a|b; d=1<<1; e=1<<11; f=d|e; - SP7 = [a|z,c|d,b|f,z|z,z|e,b|f,a|f,c|e,c|f,a|z,z|z,b|d,z|d,b|z,c|d,z|f, - b|e,a|f,a|d,b|e,b|d,c|z,c|e,a|d,c|z,z|e,z|f,c|f,a|e,z|d,b|z,a|e, - b|z,a|e,a|z,b|f,b|f,c|d,c|d,z|d,a|d,b|z,b|e,a|z,c|e,z|f,a|f,c|e, - z|f,b|d,c|f,c|z,a|e,z|z,z|d,c|f,z|z,a|f,c|z,z|e,b|d,b|e,z|e,a|d]; + const SP7 = [a|z,c|d,b|f,z|z,z|e,b|f,a|f,c|e,c|f,a|z,z|z,b|d,z|d,b|z,c|d,z|f, + b|e,a|f,a|d,b|e,b|d,c|z,c|e,a|d,c|z,z|e,z|f,c|f,a|e,z|d,b|z,a|e, + b|z,a|e,a|z,b|f,b|f,c|d,c|d,z|d,a|d,b|z,b|e,a|z,c|e,z|f,a|f,c|e, + z|f,b|d,c|f,c|z,a|e,z|z,z|d,c|f,z|z,a|f,c|z,z|e,b|d,b|e,z|e,a|d]; a=1<<18; b=1<<28; c=a|b; d=1<<6; e=1<<12; f=d|e; - SP8 = [b|f,z|e,a|z,c|f,b|z,b|f,z|d,b|z,a|d,c|z,c|f,a|e,c|e,a|f,z|e,z|d, - c|z,b|d,b|e,z|f,a|e,a|d,c|d,c|e,z|f,z|z,z|z,c|d,b|d,b|e,a|f,a|z, - a|f,a|z,c|e,z|e,z|d,c|d,z|e,a|f,b|e,z|d,b|d,c|z,c|d,b|z,a|z,b|f, - z|z,c|f,a|d,b|d,c|z,b|e,b|f,z|z,c|f,a|e,a|e,z|f,z|f,a|d,b|z,c|e]; + const SP8 = [b|f,z|e,a|z,c|f,b|z,b|f,z|d,b|z,a|d,c|z,c|f,a|e,c|e,a|f,z|e,z|d, + c|z,b|d,b|e,z|f,a|e,a|d,c|d,c|e,z|f,z|z,z|z,c|d,b|d,b|e,a|f,a|z, + a|f,a|z,c|e,z|e,z|d,c|d,z|e,a|f,b|e,z|d,b|d,c|z,c|d,b|z,a|z,b|f, + z|z,c|f,a|d,b|d,c|z,b|e,b|f,z|z,c|f,a|e,a|e,z|f,z|f,a|d,b|z,c|e]; // Set the key. function setKeys(keyBlock) { - var i, j, l, m, n, o, pc1m = [], pcr = [], kn = [], - raw0, raw1, rawi, KnLi; + const pc1m = [], pcr = [], kn = []; - for (j = 0, l = 56; j < 56; ++j, l -= 8) { + for (let j = 0, l = 56; j < 56; ++j, l -= 8) { l += l < -5 ? 65 : l < -3 ? 31 : l < -1 ? 63 : l === 27 ? 35 : 0; // PC1 - m = l & 0x7; + const m = l & 0x7; pc1m[j] = ((keyBlock[l >>> 3] & (1<>> 10; @@ -181,8 +177,8 @@ export default function DES(passwd) { // Encrypt 8 bytes of text function enc8(text) { - var i = 0, b = text.slice(), fval, keysi = 0, - l, r, x; // left, right, accumulator + const b = text.slice(); + let i = 0, l, r, x; // left, right, accumulator // Squash 8 bytes to 2 ints l = b[i++]<<24 | b[i++]<<16 | b[i++]<<8 | b[i++]; @@ -206,10 +202,10 @@ export default function DES(passwd) { r ^= x; l = (l << 1) | ((l >>> 31) & 1); - for (i = 0; i < 8; ++i) { + for (let i = 0, keysi = 0; i < 8; ++i) { x = (r << 28) | (r >>> 4); x ^= keys[keysi++]; - fval = SP7[x & 0x3f]; + let fval = SP7[x & 0x3f]; fval |= SP5[(x >>> 8) & 0x3f]; fval |= SP3[(x >>> 16) & 0x3f]; fval |= SP1[(x >>> 24) & 0x3f]; diff --git a/core/display.js b/core/display.js index 7fed184..eb7eec2 100644 --- a/core/display.js +++ b/core/display.js @@ -70,7 +70,7 @@ export default function Display(target) { Log.Debug("<< Display.constructor"); } -var SUPPORTS_IMAGEDATA_CONSTRUCTOR = false; +let SUPPORTS_IMAGEDATA_CONSTRUCTOR = false; try { new ImageData(new Uint8ClampedArray(4), 1, 1); SUPPORTS_IMAGEDATA_CONSTRUCTOR = true; @@ -92,7 +92,7 @@ Display.prototype = { set clipViewport(viewport) { this._clipViewport = viewport; // May need to readjust the viewport dimensions - var vp = this._viewportLoc; + const vp = this._viewportLoc; this.viewportChangeSize(vp.w, vp.h); this.viewportChangePos(0, 0); }, @@ -113,7 +113,7 @@ Display.prototype = { // ===== PUBLIC METHODS ===== viewportChangePos: function (deltaX, deltaY) { - var vp = this._viewportLoc; + const vp = this._viewportLoc; deltaX = Math.floor(deltaX); deltaY = Math.floor(deltaY); @@ -122,8 +122,8 @@ Display.prototype = { deltaY = -vp.h; } - var vx2 = vp.x + vp.w - 1; - var vy2 = vp.y + vp.h - 1; + const vx2 = vp.x + vp.w - 1; + const vy2 = vp.y + vp.h - 1; // Position change @@ -172,12 +172,12 @@ Display.prototype = { height = this._fb_height; } - var vp = this._viewportLoc; + const vp = this._viewportLoc; if (vp.w !== width || vp.h !== height) { vp.w = width; vp.h = height; - var canvas = this._target; + const canvas = this._target; canvas.width = width; canvas.height = height; @@ -206,11 +206,11 @@ Display.prototype = { this._fb_width = width; this._fb_height = height; - var canvas = this._backbuffer; + const canvas = this._backbuffer; if (canvas.width !== width || canvas.height !== height) { // We have to save the canvas data since changing the size will clear it - var saveImg = null; + let saveImg = null; if (canvas.width > 0 && canvas.height > 0) { saveImg = this._drawCtx.getImageData(0, 0, canvas.width, canvas.height); } @@ -229,7 +229,7 @@ Display.prototype = { // Readjust the viewport as it may be incorrectly sized // and positioned - var vp = this._viewportLoc; + const vp = this._viewportLoc; this.viewportChangeSize(vp.w, vp.h); this.viewportChangePos(0, 0); }, @@ -258,15 +258,13 @@ Display.prototype = { 'type': 'flip' }); } else { - var x, y, vx, vy, w, h; + let x = this._damageBounds.left; + let y = this._damageBounds.top; + let w = this._damageBounds.right - x; + let h = this._damageBounds.bottom - y; - x = this._damageBounds.left; - y = this._damageBounds.top; - w = this._damageBounds.right - x; - h = this._damageBounds.bottom - y; - - vx = x - this._viewportLoc.x; - vy = y - this._viewportLoc.y; + let vx = x - this._viewportLoc.x; + let vy = y - this._viewportLoc.y; if (vx < 0) { w += vx; @@ -372,7 +370,7 @@ Display.prototype = { }, imageRect: function(x, y, mime, arr) { - var img = new Image(); + const img = new Image(); img.src = "data: " + mime + ";base64," + Base64.encode(arr); this._renderQ_push({ 'type': 'img', @@ -392,12 +390,12 @@ Display.prototype = { this._tile = this._drawCtx.createImageData(width, height); } - var red = color[2]; - var green = color[1]; - var blue = color[0]; + const red = color[2]; + const green = color[1]; + const blue = color[0]; - var data = this._tile.data; - for (var i = 0; i < width * height * 4; i += 4) { + const data = this._tile.data; + for (let i = 0; i < width * height * 4; i += 4) { data[i] = red; data[i + 1] = green; data[i + 2] = blue; @@ -407,17 +405,17 @@ Display.prototype = { // update sub-rectangle of the current tile subTile: function (x, y, w, h, color) { - var red = color[2]; - var green = color[1]; - var blue = color[0]; - var xend = x + w; - var yend = y + h; - - var data = this._tile.data; - var width = this._tile.width; - for (var j = y; j < yend; j++) { - for (var i = x; i < xend; i++) { - var p = (i + (j * width)) * 4; + const red = color[2]; + const green = color[1]; + const blue = color[0]; + const xend = x + w; + const yend = y + h; + + const data = this._tile.data; + const width = this._tile.width; + for (let j = y; j < yend; j++) { + for (let i = x; i < xend; i++) { + const p = (i + (j * width)) * 4; data[p] = red; data[p + 1] = green; data[p + 2] = blue; @@ -438,7 +436,7 @@ Display.prototype = { // NB(directxman12): it's technically more performant here to use preallocated arrays, // but it's a lot of extra work for not a lot of payoff -- if we're using the render queue, // this probably isn't getting called *nearly* as much - var new_arr = new Uint8Array(width * height * 4); + const new_arr = new Uint8Array(width * height * 4); new_arr.set(new Uint8Array(arr.buffer, 0, new_arr.length)); this._renderQ_push({ 'type': 'blit', @@ -458,7 +456,7 @@ Display.prototype = { // NB(directxman12): it's technically more performant here to use preallocated arrays, // but it's a lot of extra work for not a lot of payoff -- if we're using the render queue, // this probably isn't getting called *nearly* as much - var new_arr = new Uint8Array(width * height * 3); + const new_arr = new Uint8Array(width * height * 3); new_arr.set(new Uint8Array(arr.buffer, 0, new_arr.length)); this._renderQ_push({ 'type': 'blitRgb', @@ -478,7 +476,7 @@ Display.prototype = { // NB(directxman12): it's technically more performant here to use preallocated arrays, // but it's a lot of extra work for not a lot of payoff -- if we're using the render queue, // this probably isn't getting called *nearly* as much - var new_arr = new Uint8Array(width * height * 4); + const new_arr = new Uint8Array(width * height * 4); new_arr.set(new Uint8Array(arr.buffer, 0, new_arr.length)); this._renderQ_push({ 'type': 'blitRgbx', @@ -511,11 +509,11 @@ Display.prototype = { }, autoscale: function (containerWidth, containerHeight) { - var vp = this._viewportLoc; - var targetAspectRatio = containerWidth / containerHeight; - var fbAspectRatio = vp.w / vp.h; + const vp = this._viewportLoc; + const targetAspectRatio = containerWidth / containerHeight; + const fbAspectRatio = vp.w / vp.h; - var scaleRatio; + let scaleRatio; if (fbAspectRatio >= targetAspectRatio) { scaleRatio = containerWidth / vp.w; } else { @@ -529,14 +527,14 @@ Display.prototype = { _rescale: function (factor) { this._scale = factor; - var vp = this._viewportLoc; + const vp = this._viewportLoc; // NB(directxman12): If you set the width directly, or set the // style width to a number, the canvas is cleared. // However, if you set the style width to a string // ('NNNpx'), the canvas is scaled without clearing. - var width = Math.round(factor * vp.w) + 'px'; - var height = Math.round(factor * vp.h) + 'px'; + const width = Math.round(factor * vp.w) + 'px'; + const height = Math.round(factor * vp.h) + 'px'; if ((this._target.style.width !== width) || (this._target.style.height !== height)) { @@ -546,7 +544,7 @@ Display.prototype = { }, _setFillColor: function (color) { - var newStyle = 'rgb(' + color[2] + ',' + color[1] + ',' + color[0] + ')'; + const newStyle = 'rgb(' + color[2] + ',' + color[1] + ',' + color[0] + ')'; if (newStyle !== this._prevDrawStyle) { this._drawCtx.fillStyle = newStyle; this._prevDrawStyle = newStyle; @@ -554,9 +552,9 @@ Display.prototype = { }, _rgbImageData: function (x, y, width, height, arr, offset) { - var img = this._drawCtx.createImageData(width, height); - var data = img.data; - for (var i = 0, j = offset; i < width * height * 4; i += 4, j += 3) { + const img = this._drawCtx.createImageData(width, height); + const data = img.data; + for (let i = 0, j = offset; i < width * height * 4; i += 4, j += 3) { data[i] = arr[j]; data[i + 1] = arr[j + 1]; data[i + 2] = arr[j + 2]; @@ -567,9 +565,9 @@ Display.prototype = { }, _bgrxImageData: function (x, y, width, height, arr, offset) { - var img = this._drawCtx.createImageData(width, height); - var data = img.data; - for (var i = 0, j = offset; i < width * height * 4; i += 4, j += 4) { + const img = this._drawCtx.createImageData(width, height); + const data = img.data; + for (let i = 0, j = offset; i < width * height * 4; i += 4, j += 4) { data[i] = arr[j + 2]; data[i + 1] = arr[j + 1]; data[i + 2] = arr[j]; @@ -581,7 +579,7 @@ Display.prototype = { _rgbxImageData: function (x, y, width, height, arr, offset) { // NB(directxman12): arr must be an Type Array view - var img; + let img; if (SUPPORTS_IMAGEDATA_CONSTRUCTOR) { img = new ImageData(new Uint8ClampedArray(arr.buffer, arr.byteOffset, width * height * 4), width, height); } else { @@ -609,9 +607,9 @@ Display.prototype = { }, _scan_renderQ: function () { - var ready = true; + let ready = true; while (ready && this._renderQ.length > 0) { - var a = this._renderQ[0]; + const a = this._renderQ[0]; switch (a.type) { case 'flip': this.flip(true); @@ -663,12 +661,11 @@ Display.changeCursor = function (target, pixels, mask, hotx, hoty, w, h) { return; } - var cur = [] - var y, x; - for (y = 0; y < h; y++) { - for (x = 0; x < w; x++) { - var idx = y * Math.ceil(w / 8) + Math.floor(x / 8); - var alpha = (mask[idx] << (x % 8)) & 0x80 ? 255 : 0; + const cur = [] + for (let y = 0; y < h; y++) { + for (let x = 0; x < w; x++) { + let idx = y * Math.ceil(w / 8) + Math.floor(x / 8); + const alpha = (mask[idx] << (x % 8)) & 0x80 ? 255 : 0; idx = ((w * y) + x) * 4; cur.push(pixels[idx + 2]); // red cur.push(pixels[idx + 1]); // green @@ -677,13 +674,13 @@ Display.changeCursor = function (target, pixels, mask, hotx, hoty, w, h) { } } - var canvas = document.createElement('canvas'); - var ctx = canvas.getContext('2d'); + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); canvas.width = w; canvas.height = h; - var img; + let img; if (SUPPORTS_IMAGEDATA_CONSTRUCTOR) { img = new ImageData(new Uint8ClampedArray(cur), w, h); } else { @@ -693,6 +690,6 @@ Display.changeCursor = function (target, pixels, mask, hotx, hoty, w, h) { ctx.clearRect(0, 0, w, h); ctx.putImageData(img, 0, 0); - var url = canvas.toDataURL(); + const url = canvas.toDataURL(); target.style.cursor = 'url(' + url + ')' + hotx + ' ' + hoty + ', default'; }; diff --git a/core/encodings.js b/core/encodings.js index c383063..5a70e66 100644 --- a/core/encodings.js +++ b/core/encodings.js @@ -6,7 +6,7 @@ * See README.md for usage and integration instructions. */ -export var encodings = { +export const encodings = { encodingRaw: 0, encodingCopyRect: 1, encodingRRE: 2, diff --git a/core/input/domkeytable.js b/core/input/domkeytable.js index 7103bba..a0cc1f5 100644 --- a/core/input/domkeytable.js +++ b/core/input/domkeytable.js @@ -13,7 +13,7 @@ import KeyTable from "./keysym.js"; * See https://www.w3.org/TR/uievents-key/ for possible values. */ -var DOMKeyTable = {}; +const DOMKeyTable = {}; function addStandard(key, standard) { diff --git a/core/input/keyboard.js b/core/input/keyboard.js index 4ba36e3..d64298a 100644 --- a/core/input/keyboard.js +++ b/core/input/keyboard.js @@ -57,7 +57,7 @@ Keyboard.prototype = { }, _getKeyCode: function (e) { - var code = KeyboardUtil.getKeycode(e); + const code = KeyboardUtil.getKeycode(e); if (code !== 'Unidentified') { return code; } @@ -80,10 +80,8 @@ Keyboard.prototype = { return e.keyIdentifier; } - var codepoint = parseInt(e.keyIdentifier.substr(2), 16); - var char = String.fromCharCode(codepoint); - // Some implementations fail to uppercase the symbols - char = char.toUpperCase(); + const codepoint = parseInt(e.keyIdentifier.substr(2), 16); + const char = String.fromCharCode(codepoint).toUpperCase(); return 'Platform' + char.charCodeAt(); } @@ -92,8 +90,8 @@ Keyboard.prototype = { }, _handleKeyDown: function (e) { - var code = this._getKeyCode(e); - var keysym = KeyboardUtil.getKeysym(e); + const code = this._getKeyCode(e); + let keysym = KeyboardUtil.getKeysym(e); // Windows doesn't have a proper AltGr, but handles it using // fake Ctrl+Alt. However the remote end might not be Windows, @@ -211,8 +209,8 @@ Keyboard.prototype = { return; } - var code = this._getKeyCode(e); - var keysym = KeyboardUtil.getKeysym(e); + let code = this._getKeyCode(e); + const keysym = KeyboardUtil.getKeysym(e); // The key we were waiting for? if ((code !== 'Unidentified') && (code != this._pendingKey)) { @@ -235,9 +233,9 @@ Keyboard.prototype = { return; } - var code, keysym; + let keysym; - code = this._pendingKey; + const code = this._pendingKey; this._pendingKey = null; // We have no way of knowing the proper keysym with the @@ -248,7 +246,7 @@ Keyboard.prototype = { keysym = e.keyCode; } else if ((e.keyCode >= 0x41) && (e.keyCode <= 0x5a)) { // Character (A-Z) - var char = String.fromCharCode(e.keyCode); + let char = String.fromCharCode(e.keyCode); // A feeble attempt at the correct case if (e.shiftKey) char = char.toUpperCase(); @@ -266,7 +264,7 @@ Keyboard.prototype = { _handleKeyUp: function (e) { stopEvent(e); - var code = this._getKeyCode(e); + const code = this._getKeyCode(e); // We can't get a release in the middle of an AltGr sequence, so // abort that detection @@ -294,7 +292,7 @@ Keyboard.prototype = { _allKeysUp: function () { Log.Debug(">> Keyboard.allKeysUp"); - for (var code in this._keyDownList) { + for (let code in this._keyDownList) { this._sendKeyEvent(this._keyDownList[code], code, false); } Log.Debug("<< Keyboard.allKeysUp"); @@ -306,14 +304,14 @@ Keyboard.prototype = { return; } - let target = this._target; - let downList = this._keyDownList; + const target = this._target; + const downList = this._keyDownList; ['AltLeft', 'AltRight'].forEach(function (code) { if (!(code in downList)) { return; } - let event = new KeyboardEvent('keyup', + const event = new KeyboardEvent('keyup', { key: downList[code], code: code }); target.dispatchEvent(event); @@ -324,11 +322,10 @@ Keyboard.prototype = { grab: function () { //Log.Debug(">> Keyboard.grab"); - var c = this._target; - c.addEventListener('keydown', this._eventHandlers.keydown); - c.addEventListener('keyup', this._eventHandlers.keyup); - c.addEventListener('keypress', this._eventHandlers.keypress); + this._target.addEventListener('keydown', this._eventHandlers.keydown); + this._target.addEventListener('keyup', this._eventHandlers.keyup); + this._target.addEventListener('keypress', this._eventHandlers.keypress); // Release (key up) if window loses focus window.addEventListener('blur', this._eventHandlers.blur); @@ -337,7 +334,7 @@ Keyboard.prototype = { // best we can for releases (still doesn't prevent the menu // from popping up though as we can't call preventDefault()) if (browser.isWindows() && browser.isFirefox()) { - let handler = this._eventHandlers.checkalt; + const handler = this._eventHandlers.checkalt; ['mousedown', 'mouseup', 'mousemove', 'wheel', 'touchstart', 'touchend', 'touchmove', 'keydown', 'keyup'].forEach(function (type) { @@ -352,10 +349,9 @@ Keyboard.prototype = { ungrab: function () { //Log.Debug(">> Keyboard.ungrab"); - var c = this._target; if (browser.isWindows() && browser.isFirefox()) { - let handler = this._eventHandlers.checkalt; + const handler = this._eventHandlers.checkalt; ['mousedown', 'mouseup', 'mousemove', 'wheel', 'touchstart', 'touchend', 'touchmove', 'keydown', 'keyup'].forEach(function (type) { @@ -363,9 +359,9 @@ Keyboard.prototype = { }); } - c.removeEventListener('keydown', this._eventHandlers.keydown); - c.removeEventListener('keyup', this._eventHandlers.keyup); - c.removeEventListener('keypress', this._eventHandlers.keypress); + this._target.removeEventListener('keydown', this._eventHandlers.keydown); + this._target.removeEventListener('keyup', this._eventHandlers.keyup); + this._target.removeEventListener('keypress', this._eventHandlers.keypress); window.removeEventListener('blur', this._eventHandlers.blur); // Release (key up) all keys that are in a down state diff --git a/core/input/keysymdef.js b/core/input/keysymdef.js index 95922b3..5969b5d 100644 --- a/core/input/keysymdef.js +++ b/core/input/keysymdef.js @@ -7,7 +7,7 @@ /* Functions at the bottom */ -var codepoints = { +const codepoints = { 0x0100: 0x03c0, // XK_Amacron 0x0101: 0x03e0, // XK_amacron 0x0102: 0x01c3, // XK_Abreve @@ -677,7 +677,7 @@ export default { } // Lookup table (fairly random) - var keysym = codepoints[u]; + const keysym = codepoints[u]; if (keysym !== undefined) { return keysym; } diff --git a/core/input/mouse.js b/core/input/mouse.js index df9b7e1..17c8cd5 100644 --- a/core/input/mouse.js +++ b/core/input/mouse.js @@ -9,9 +9,9 @@ import * as Log from '../util/logging.js'; import { isTouchDevice } from '../util/browser.js'; import { setCapture, stopEvent, getPointerEvent } from '../util/events.js'; -var WHEEL_STEP = 10; // Delta threshold for a mouse wheel step -var WHEEL_STEP_TIMEOUT = 50; // ms -var WHEEL_LINE_HEIGHT = 19; +const WHEEL_STEP = 10; // Delta threshold for a mouse wheel step +const WHEEL_STEP_TIMEOUT = 50; // ms +const WHEEL_LINE_HEIGHT = 19; export default function Mouse(target) { this._target = target || document; @@ -52,9 +52,9 @@ Mouse.prototype = { _handleMouseButton: function (e, down) { this._updateMousePosition(e); - var pos = this._pos; + let pos = this._pos; - var bmask; + let bmask; if (e.touches || e.changedTouches) { // Touch device @@ -70,13 +70,13 @@ Mouse.prototype = { // force the position of the latter touch to the position of // the first. - var xs = this._lastTouchPos.x - pos.x; - var ys = this._lastTouchPos.y - pos.y; - var d = Math.sqrt((xs * xs) + (ys * ys)); + const xs = this._lastTouchPos.x - pos.x; + const ys = this._lastTouchPos.y - pos.y; + const d = Math.sqrt((xs * xs) + (ys * ys)); // The goal is to trigger on a certain physical width, the // devicePixelRatio brings us a bit closer but is not optimal. - var threshold = 20 * (window.devicePixelRatio || 1); + const threshold = 20 * (window.devicePixelRatio || 1); if (d < threshold) { pos = this._lastTouchPos; } @@ -156,8 +156,8 @@ Mouse.prototype = { this._updateMousePosition(e); - var dX = e.deltaX; - var dY = e.deltaY; + let dX = e.deltaX; + let dY = e.deltaY; // Pixel units unless it's non-zero. // Note that if deltamode is line or page won't matter since we aren't @@ -215,8 +215,9 @@ Mouse.prototype = { // Update coordinates relative to target _updateMousePosition: function(e) { e = getPointerEvent(e); - var bounds = this._target.getBoundingClientRect(); - var x, y; + const bounds = this._target.getBoundingClientRect(); + let x; + let y; // Clip to target bounds if (e.clientX < bounds.left) { x = 0; @@ -238,7 +239,7 @@ Mouse.prototype = { // ===== PUBLIC METHODS ===== grab: function () { - var c = this._target; + const c = this._target; if (isTouchDevice) { c.addEventListener('touchstart', this._eventHandlers.mousedown); @@ -259,7 +260,7 @@ Mouse.prototype = { }, ungrab: function () { - var c = this._target; + const c = this._target; this._resetWheelStepTimers(); diff --git a/core/input/util.js b/core/input/util.js index 1201e1d..57e9ce4 100644 --- a/core/input/util.js +++ b/core/input/util.js @@ -24,7 +24,7 @@ export function getKeycode(evt){ // in the 'keyCode' field for non-printable characters. However // Webkit sets it to the same as charCode in 'keypress' events. if ((evt.type !== 'keypress') && (evt.keyCode in vkeys)) { - var code = vkeys[evt.keyCode]; + let code = vkeys[evt.keyCode]; // macOS has messed up this code for some reason if (browser.isMac() && (code === 'ContextMenu')) { @@ -110,7 +110,7 @@ export function getKey(evt) { } // Try to deduce it based on the physical key - var code = getKeycode(evt); + const code = getKeycode(evt); if (code in fixedkeys) { return fixedkeys[code]; } @@ -126,7 +126,7 @@ export function getKey(evt) { // Get the most reliable keysym value we can get from a key event export function getKeysym(evt){ - var key = getKey(evt); + const key = getKey(evt); if (key === 'Unidentified') { return null; @@ -134,7 +134,7 @@ export function getKeysym(evt){ // First look up special keys if (key in DOMKeyTable) { - var location = evt.location; + let location = evt.location; // Safari screws up location for the right cmd key if ((key === 'Meta') && (location === 0)) { @@ -150,14 +150,12 @@ export function getKeysym(evt){ // Now we need to look at the Unicode symbol instead - var codepoint; - // Special key? (FIXME: Should have been caught earlier) if (key.length !== 1) { return null; } - codepoint = key.charCodeAt(); + const codepoint = key.charCodeAt(); if (codepoint) { return keysyms.lookup(codepoint); } diff --git a/core/rfb.js b/core/rfb.js index 652fbeb..d336d6c 100644 --- a/core/rfb.js +++ b/core/rfb.js @@ -26,7 +26,7 @@ import { encodings, encodingName } from "./encodings.js"; import "./util/polyfill.js"; // How many seconds to wait for a disconnect to finish -var DISCONNECT_TIMEOUT = 3; +const DISCONNECT_TIMEOUT = 3; export default function RFB(target, url, options) { if (!target) { @@ -105,7 +105,7 @@ export default function RFB(target, url, options) { background: null, zlibs: [] // TIGHT zlib streams }; - for (var i = 0; i < 4; i++) { + for (let i = 0; i < 4; i++) { this._FBU.zlibs[i] = new Inflator(); } @@ -207,7 +207,7 @@ export default function RFB(target, url, options) { }.bind(this)); this._sock.on('close', function (e) { Log.Debug("WebSocket on-close event"); - var msg = ""; + let msg = ""; if (e.code) { msg = "(code: " + e.code; if (e.reason) { @@ -358,7 +358,7 @@ RFB.prototype = { return; } - var scancode = XtScancode[code]; + const scancode = XtScancode[code]; if (this._qemuExtKeyEventSupported && scancode) { // 0 is NoSymbol @@ -445,11 +445,11 @@ RFB.prototype = { }, _print_stats: function () { - var stats = this._encStats; + const stats = this._encStats; Log.Info("Encoding stats for this connection:"); Object.keys(stats).forEach(function (key) { - var s = stats[key]; + const s = stats[key]; if (s[0] + s[1] > 0) { Log.Info(" " + encodingName(key) + ": " + s[0] + " rects"); } @@ -457,7 +457,7 @@ RFB.prototype = { Log.Info("Encoding stats since page load:"); Object.keys(stats).forEach(function (key) { - var s = stats[key]; + const s = stats[key]; Log.Info(" " + encodingName(key) + ": " + s[1] + " rects"); }); }, @@ -497,8 +497,8 @@ RFB.prototype = { // Update state of clipping in Display object, and make sure the // configured viewport matches the current screen size _updateClip: function () { - var cur_clip = this._display.clipViewport; - var new_clip = this._clipViewport; + const cur_clip = this._display.clipViewport; + let new_clip = this._clipViewport; if (this._scaleViewport) { // Disable viewport clipping if we are scaling @@ -512,7 +512,7 @@ RFB.prototype = { if (new_clip) { // When clipping is enabled, the screen is limited to // the size of the container. - let size = this._screenSize(); + const size = this._screenSize(); this._display.viewportChangeSize(size.w, size.h); this._fixScrollbars(); } @@ -522,7 +522,7 @@ RFB.prototype = { if (!this._scaleViewport) { this._display.scale = 1.0; } else { - let size = this._screenSize(); + const size = this._screenSize(); this._display.autoscale(size.w, size.h); } this._fixScrollbars(); @@ -539,7 +539,7 @@ RFB.prototype = { return; } - let size = this._screenSize(); + const size = this._screenSize(); RFB.messages.setDesktopSize(this._sock, size.w, size.h, this._screen_id, this._screen_flags); @@ -557,7 +557,7 @@ RFB.prototype = { // This is a hack because Chrome screws up the calculation // for when scrollbars are needed. So to fix it we temporarily // toggle them off and on. - var orig = this._screen.style.overflow; + const orig = this._screen.style.overflow; this._screen.style.overflow = 'hidden'; // Force Chrome to recalculate the layout by asking for // an element's dimensions @@ -573,7 +573,7 @@ RFB.prototype = { * disconnected - permanent state */ _updateConnectionState: function (state) { - var oldstate = this._rfb_connection_state; + const oldstate = this._rfb_connection_state; if (state === oldstate) { Log.Debug("Already in state '" + state + "', ignoring"); @@ -629,7 +629,7 @@ RFB.prototype = { this._rfb_connection_state = state; - var smsg = "New state '" + state + "', was '" + oldstate + "'."; + const smsg = "New state '" + state + "', was '" + oldstate + "'."; Log.Debug(smsg); if (this._disconnTimer && state !== 'disconnecting') { @@ -647,8 +647,7 @@ RFB.prototype = { break; case 'connected': - var event = new CustomEvent("connect", { detail: {} }); - this.dispatchEvent(event); + this.dispatchEvent(new CustomEvent("connect", { detail: {} })); break; case 'disconnecting': @@ -661,10 +660,9 @@ RFB.prototype = { break; case 'disconnected': - event = new CustomEvent( + this.dispatchEvent(new CustomEvent( "disconnect", { detail: - { clean: this._rfb_clean_disconnect } }); - this.dispatchEvent(event); + { clean: this._rfb_clean_disconnect } })); break; } }, @@ -700,9 +698,8 @@ RFB.prototype = { _setCapability: function (cap, val) { this._capabilities[cap] = val; - var event = new CustomEvent("capabilities", - { detail: { capabilities: this._capabilities } }); - this.dispatchEvent(event); + this.dispatchEvent(new CustomEvent("capabilities", + { detail: { capabilities: this._capabilities } })); }, _handle_message: function () { @@ -780,12 +777,12 @@ RFB.prototype = { _handleMouseMove: function (x, y) { if (this._viewportDragging) { - var deltaX = this._viewportDragPos.x - x; - var deltaY = this._viewportDragPos.y - y; + const deltaX = this._viewportDragPos.x - x; + const deltaY = this._viewportDragPos.y - y; // The goal is to trigger on a certain physical width, the // devicePixelRatio brings us a bit closer but is not optimal. - var dragThreshold = 10 * (window.devicePixelRatio || 1); + const dragThreshold = 10 * (window.devicePixelRatio || 1); if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold || Math.abs(deltaY) > dragThreshold)) { @@ -812,9 +809,9 @@ RFB.prototype = { return this._fail("Received incomplete protocol version."); } - var sversion = this._sock.rQshiftStr(12).substr(4, 7); + const sversion = this._sock.rQshiftStr(12).substr(4, 7); Log.Info("Server ProtocolVersion: " + sversion); - var is_repeater = 0; + let is_repeater = 0; switch (sversion) { case "000.000": // UltraVNC repeater is_repeater = 1; @@ -838,7 +835,7 @@ RFB.prototype = { } if (is_repeater) { - var repeaterID = "ID:" + this._repeaterID; + let repeaterID = "ID:" + this._repeaterID; while (repeaterID.length < 250) { repeaterID += "\0"; } @@ -850,7 +847,7 @@ RFB.prototype = { this._rfb_version = this._rfb_max_version; } - var cversion = "00" + parseInt(this._rfb_version, 10) + + const cversion = "00" + parseInt(this._rfb_version, 10) + ".00" + ((this._rfb_version * 10) % 10); this._sock.send_string("RFB " + cversion + "\n"); Log.Debug('Sent ProtocolVersion: ' + cversion); @@ -862,7 +859,7 @@ RFB.prototype = { // Polyfill since IE and PhantomJS doesn't have // TypedArray.includes() function includes(item, array) { - for (var i = 0; i < array.length; i++) { + for (let i = 0; i < array.length; i++) { if (array[i] === item) { return true; } @@ -872,14 +869,14 @@ RFB.prototype = { if (this._rfb_version >= 3.7) { // Server sends supported list, client decides - var num_types = this._sock.rQshift8(); + const num_types = this._sock.rQshift8(); if (this._sock.rQwait("security type", num_types, 1)) { return false; } if (num_types === 0) { return this._handle_security_failure("no security types"); } - var types = this._sock.rQshiftBytes(num_types); + const types = this._sock.rQshiftBytes(num_types); Log.Debug("Server security types: " + types); // Look for each auth in preferred order @@ -934,7 +931,7 @@ RFB.prototype = { if (this._sock.rQwait("reason length", 4)) { return false; } - let strlen = this._sock.rQshift32(); + const strlen = this._sock.rQshift32(); let reason = ""; if (strlen > 0) { @@ -943,20 +940,16 @@ RFB.prototype = { } if (reason !== "") { - - let event = new CustomEvent( + this.dispatchEvent(new CustomEvent( "securityfailure", - { detail: { status: security_result_status, reason: reason } }); - this.dispatchEvent(event); + { detail: { status: security_result_status, reason: reason } })); return this._fail("Security negotiation failed" + context + " (reason: " + reason + ")"); } else { - - let event = new CustomEvent( + this.dispatchEvent(new CustomEvent( "securityfailure", - { detail: { status: security_result_status } }); - this.dispatchEvent(event); + { detail: { status: security_result_status } })); return this._fail("Security negotiation failed" + context); } @@ -967,13 +960,13 @@ RFB.prototype = { if (!this._rfb_credentials.username || !this._rfb_credentials.password || !this._rfb_credentials.target) { - var event = new CustomEvent("credentialsrequired", - { detail: { types: ["username", "password", "target"] } }); - this.dispatchEvent(event); + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["username", "password", "target"] } })); return false; } - var xvp_auth_str = String.fromCharCode(this._rfb_credentials.username.length) + + const xvp_auth_str = String.fromCharCode(this._rfb_credentials.username.length) + String.fromCharCode(this._rfb_credentials.target.length) + this._rfb_credentials.username + this._rfb_credentials.target; @@ -986,30 +979,30 @@ RFB.prototype = { if (this._sock.rQwait("auth challenge", 16)) { return false; } if (!this._rfb_credentials.password) { - var event = new CustomEvent("credentialsrequired", - { detail: { types: ["password"] } }); - this.dispatchEvent(event); + this.dispatchEvent(new CustomEvent( + "credentialsrequired", + { detail: { types: ["password"] } })); return false; } // TODO(directxman12): make genDES not require an Array - var challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16)); - var response = RFB.genDES(this._rfb_credentials.password, challenge); + const challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16)); + const response = RFB.genDES(this._rfb_credentials.password, challenge); this._sock.send(response); this._rfb_init_state = "SecurityResult"; return true; }, _negotiate_tight_tunnels: function (numTunnels) { - var clientSupportedTunnelTypes = { + const clientSupportedTunnelTypes = { 0: { vendor: 'TGHT', signature: 'NOTUNNEL' } }; - var serverSupportedTunnelTypes = {}; + const serverSupportedTunnelTypes = {}; // receive tunnel capabilities - for (var i = 0; i < numTunnels; i++) { - var cap_code = this._sock.rQshift32(); - var cap_vendor = this._sock.rQshiftStr(4); - var cap_signature = this._sock.rQshiftStr(8); + for (let i = 0; i < numTunnels; i++) { + const cap_code = this._sock.rQshift32(); + const cap_vendor = this._sock.rQshiftStr(4); + const cap_signature = this._sock.rQshiftStr(8); serverSupportedTunnelTypes[cap_code] = { vendor: cap_vendor, signature: cap_signature }; } @@ -1031,7 +1024,7 @@ RFB.prototype = { _negotiate_tight_auth: function () { if (!this._rfb_tightvnc) { // first pass, do the tunnel negotiation if (this._sock.rQwait("num tunnels", 4)) { return false; } - var numTunnels = this._sock.rQshift32(); + const numTunnels = this._sock.rQshift32(); if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; } this._rfb_tightvnc = true; @@ -1044,7 +1037,7 @@ RFB.prototype = { // second pass, do the sub-auth negotiation if (this._sock.rQwait("sub auth count", 4)) { return false; } - var subAuthCount = this._sock.rQshift32(); + const subAuthCount = this._sock.rQshift32(); if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected this._rfb_init_state = 'SecurityResult'; return true; @@ -1052,20 +1045,20 @@ RFB.prototype = { if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; } - var clientSupportedTypes = { + const clientSupportedTypes = { 'STDVNOAUTH__': 1, 'STDVVNCAUTH_': 2 }; - var serverSupportedTypes = []; + const serverSupportedTypes = []; - for (var i = 0; i < subAuthCount; i++) { + for (let i = 0; i < subAuthCount; i++) { this._sock.rQshift32(); // capNum - var capabilities = this._sock.rQshiftStr(12); + const capabilities = this._sock.rQshiftStr(12); serverSupportedTypes.push(capabilities); } - for (var authType in clientSupportedTypes) { + for (let authType in clientSupportedTypes) { if (serverSupportedTypes.indexOf(authType) != -1) { this._sock.send([0, 0, 0, clientSupportedTypes[authType]]); @@ -1117,7 +1110,7 @@ RFB.prototype = { _handle_security_result: function () { if (this._sock.rQwait('VNC auth response ', 4)) { return false; } - let status = this._sock.rQshift32(); + const status = this._sock.rQshift32(); if (status === 0) { // OK this._rfb_init_state = 'ClientInitialisation'; @@ -1127,9 +1120,9 @@ RFB.prototype = { if (this._rfb_version >= 3.8) { return this._handle_security_failure("security result", status); } else { - let event = new CustomEvent("securityfailure", - { detail: { status: status } }); - this.dispatchEvent(event); + this.dispatchEvent(new CustomEvent( + "securityfailure", + { detail: { status: status } })); return this._fail("Security handshake failed"); } @@ -1140,40 +1133,40 @@ RFB.prototype = { if (this._sock.rQwait("server initialization", 24)) { return false; } /* Screen size */ - var width = this._sock.rQshift16(); - var height = this._sock.rQshift16(); + const width = this._sock.rQshift16(); + const height = this._sock.rQshift16(); /* PIXEL_FORMAT */ - var bpp = this._sock.rQshift8(); - var depth = this._sock.rQshift8(); - var big_endian = this._sock.rQshift8(); - var true_color = this._sock.rQshift8(); - - var red_max = this._sock.rQshift16(); - var green_max = this._sock.rQshift16(); - var blue_max = this._sock.rQshift16(); - var red_shift = this._sock.rQshift8(); - var green_shift = this._sock.rQshift8(); - var blue_shift = this._sock.rQshift8(); + const bpp = this._sock.rQshift8(); + const depth = this._sock.rQshift8(); + const big_endian = this._sock.rQshift8(); + const true_color = this._sock.rQshift8(); + + const red_max = this._sock.rQshift16(); + const green_max = this._sock.rQshift16(); + const blue_max = this._sock.rQshift16(); + const red_shift = this._sock.rQshift8(); + const green_shift = this._sock.rQshift8(); + const blue_shift = this._sock.rQshift8(); this._sock.rQskipBytes(3); // padding // NB(directxman12): we don't want to call any callbacks or print messages until // *after* we're past the point where we could backtrack /* Connection name/title */ - var name_length = this._sock.rQshift32(); + const name_length = this._sock.rQshift32(); if (this._sock.rQwait('server init name', name_length, 24)) { return false; } this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length)); if (this._rfb_tightvnc) { if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; } // In TightVNC mode, ServerInit message is extended - var numServerMessages = this._sock.rQshift16(); - var numClientMessages = this._sock.rQshift16(); - var numEncodings = this._sock.rQshift16(); + const numServerMessages = this._sock.rQshift16(); + const numClientMessages = this._sock.rQshift16(); + const numEncodings = this._sock.rQshift16(); this._sock.rQskipBytes(2); // padding - var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16; + const totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16; if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; } // we don't actually do anything with the capability information that TIGHT sends, @@ -1215,9 +1208,9 @@ RFB.prototype = { } // we're past the point where we could backtrack, so it's safe to call this - var event = new CustomEvent("desktopname", - { detail: { name: this._fb_name } }); - this.dispatchEvent(event); + this.dispatchEvent(new CustomEvent( + "desktopname", + { detail: { name: this._fb_name } })); this._resize(width, height); @@ -1247,7 +1240,7 @@ RFB.prototype = { }, _sendEncodings: function () { - var encs = []; + const encs = []; // In preference order encs.push(encodings.encodingCopyRect); @@ -1327,16 +1320,16 @@ RFB.prototype = { if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; } this._sock.rQskipBytes(3); // Padding - var length = this._sock.rQshift32(); + const length = this._sock.rQshift32(); if (this._sock.rQwait("ServerCutText", length, 8)) { return false; } - var text = this._sock.rQshiftStr(length); + const text = this._sock.rQshiftStr(length); if (this._viewOnly) { return true; } - var event = new CustomEvent("clipboard", - { detail: { text: text } }); - this.dispatchEvent(event); + this.dispatchEvent(new CustomEvent( + "clipboard", + { detail: { text: text } })); return true; }, @@ -1344,8 +1337,8 @@ RFB.prototype = { _handle_server_fence_msg: function() { if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; } this._sock.rQskipBytes(3); // Padding - var flags = this._sock.rQshift32(); - var length = this._sock.rQshift8(); + let flags = this._sock.rQshift32(); + let length = this._sock.rQshift8(); if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; } @@ -1354,7 +1347,7 @@ RFB.prototype = { length = 64; } - var payload = this._sock.rQshiftStr(length); + const payload = this._sock.rQshiftStr(length); this._supportsFence = true; @@ -1386,8 +1379,8 @@ RFB.prototype = { _handle_xvp_msg: function () { if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; } this._sock.rQskip8(); // Padding - var xvp_ver = this._sock.rQshift8(); - var xvp_msg = this._sock.rQshift8(); + const xvp_ver = this._sock.rQshift8(); + const xvp_msg = this._sock.rQshift8(); switch (xvp_msg) { case 0: // XVP_FAIL @@ -1407,17 +1400,17 @@ RFB.prototype = { }, _normal_msg: function () { - var msg_type; - + let msg_type; if (this._FBU.rects > 0) { msg_type = 0; } else { msg_type = this._sock.rQshift8(); } + let first, ret; switch (msg_type) { case 0: // FramebufferUpdate - var ret = this._framebufferUpdate(); + ret = this._framebufferUpdate(); if (ret && !this._enabledContinuousUpdates) { RFB.messages.fbUpdateRequest(this._sock, true, 0, 0, this._fb_width, this._fb_height); @@ -1429,15 +1422,16 @@ RFB.prototype = { case 2: // Bell Log.Debug("Bell"); - var event = new CustomEvent("bell", { detail: {} }); - this.dispatchEvent(event); + this.dispatchEvent(new CustomEvent( + "bell", + { detail: {} })); return true; case 3: // ServerCutText return this._handle_server_cut_text(); case 150: // EndOfContinuousUpdates - var first = !(this._supportsContinuousUpdates); + first = !this._supportsContinuousUpdates; this._supportsContinuousUpdates = true; this._enabledContinuousUpdates = false; if (first) { @@ -1472,9 +1466,6 @@ RFB.prototype = { }, _framebufferUpdate: function () { - var ret = true; - var now; - if (this._FBU.rects === 0) { if (this._sock.rQwait("FBU header", 3, 1)) { return false; } this._sock.rQskip8(); // Padding @@ -1482,7 +1473,7 @@ RFB.prototype = { this._FBU.bytes = 0; this._timing.cur_fbu = 0; if (this._timing.fbu_rt_start > 0) { - now = (new Date()).getTime(); + const now = (new Date()).getTime(); Log.Info("First FBU latency: " + (now - this._timing.fbu_rt_start)); } @@ -1503,7 +1494,7 @@ RFB.prototype = { if (this._sock.rQwait("rect header", 12)) { return false; } /* New FramebufferUpdate */ - var hdr = this._sock.rQshiftBytes(12); + const hdr = this._sock.rQshiftBytes(12); this._FBU.x = (hdr[0] << 8) + hdr[1]; this._FBU.y = (hdr[2] << 8) + hdr[3]; this._FBU.width = (hdr[4] << 8) + hdr[5]; @@ -1520,9 +1511,9 @@ RFB.prototype = { this._timing.last_fbu = (new Date()).getTime(); - ret = this._encHandlers[this._FBU.encoding](); + const ret = this._encHandlers[this._FBU.encoding](); - now = (new Date()).getTime(); + const now = (new Date()).getTime(); this._timing.cur_fbu += (now - this._timing.last_fbu); if (ret) { @@ -1547,7 +1538,7 @@ RFB.prototype = { } if (this._timing.fbu_rt_start > 0) { - var fbu_rt_diff = now - this._timing.fbu_rt_start; + const fbu_rt_diff = now - this._timing.fbu_rt_start; this._timing.fbu_rt_total += fbu_rt_diff; this._timing.fbu_rt_cnt++; Log.Info("full FBU round-trip, cur: " + @@ -1602,8 +1593,8 @@ Object.assign(RFB.prototype, EventTargetMixin); // Class Methods RFB.messages = { keyEvent: function (sock, keysym, down) { - var buff = sock._sQ; - var offset = sock._sQlen; + const buff = sock._sQ; + const offset = sock._sQlen; buff[offset] = 4; // msg-type buff[offset + 1] = down; @@ -1622,17 +1613,16 @@ RFB.messages = { QEMUExtendedKeyEvent: function (sock, keysym, down, keycode) { function getRFBkeycode(xt_scancode) { - var upperByte = (keycode >> 8); - var lowerByte = (keycode & 0x00ff); + const upperByte = (keycode >> 8); + const lowerByte = (keycode & 0x00ff); if (upperByte === 0xe0 && lowerByte < 0x7f) { - lowerByte = lowerByte | 0x80; - return lowerByte; + return lowerByte | 0x80; } return xt_scancode; } - var buff = sock._sQ; - var offset = sock._sQlen; + const buff = sock._sQ; + const offset = sock._sQlen; buff[offset] = 255; // msg-type buff[offset + 1] = 0; // sub msg-type @@ -1645,7 +1635,7 @@ RFB.messages = { buff[offset + 6] = (keysym >> 8); buff[offset + 7] = keysym; - var RFBkeycode = getRFBkeycode(keycode); + const RFBkeycode = getRFBkeycode(keycode); buff[offset + 8] = (RFBkeycode >> 24); buff[offset + 9] = (RFBkeycode >> 16); @@ -1657,8 +1647,8 @@ RFB.messages = { }, pointerEvent: function (sock, x, y, mask) { - var buff = sock._sQ; - var offset = sock._sQlen; + const buff = sock._sQ; + const offset = sock._sQlen; buff[offset] = 5; // msg-type @@ -1676,8 +1666,8 @@ RFB.messages = { // TODO(directxman12): make this unicode compatible? clientCutText: function (sock, text) { - var buff = sock._sQ; - var offset = sock._sQlen; + const buff = sock._sQ; + const offset = sock._sQlen; buff[offset] = 6; // msg-type @@ -1685,7 +1675,7 @@ RFB.messages = { buff[offset + 2] = 0; // padding buff[offset + 3] = 0; // padding - let length = text.length; + const length = text.length; buff[offset + 4] = length >> 24; buff[offset + 5] = length >> 16; @@ -1701,16 +1691,14 @@ RFB.messages = { let remaining = length; while (remaining > 0) { - let flushSize = Math.min(remaining, (sock._sQbufferSize - sock._sQlen)); + const flushSize = Math.min(remaining, (sock._sQbufferSize - sock._sQlen)); if (flushSize <= 0) { this._fail("Clipboard contents could not be sent"); break; } - offset = sock._sQlen; - for (let i = 0; i < flushSize; i++) { - buff[offset + i] = text.charCodeAt(textOffset + i); + buff[sock._sQlen + i] = text.charCodeAt(textOffset + i); } sock._sQlen += flushSize; @@ -1722,8 +1710,8 @@ RFB.messages = { }, setDesktopSize: function (sock, width, height, id, flags) { - var buff = sock._sQ; - var offset = sock._sQlen; + const buff = sock._sQ; + const offset = sock._sQlen; buff[offset] = 251; // msg-type buff[offset + 1] = 0; // padding @@ -1758,8 +1746,8 @@ RFB.messages = { }, clientFence: function (sock, flags, payload) { - var buff = sock._sQ; - var offset = sock._sQlen; + const buff = sock._sQ; + const offset = sock._sQlen; buff[offset] = 248; // msg-type @@ -1772,11 +1760,11 @@ RFB.messages = { buff[offset + 6] = flags >> 8; buff[offset + 7] = flags; - var n = payload.length; + const n = payload.length; buff[offset + 8] = n; // length - for (var i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { buff[offset + 9 + i] = payload.charCodeAt(i); } @@ -1785,8 +1773,8 @@ RFB.messages = { }, enableContinuousUpdates: function (sock, enable, x, y, width, height) { - var buff = sock._sQ; - var offset = sock._sQlen; + const buff = sock._sQ; + const offset = sock._sQlen; buff[offset] = 150; // msg-type buff[offset + 1] = enable; // enable-flag @@ -1805,10 +1793,10 @@ RFB.messages = { }, pixelFormat: function (sock, depth, true_color) { - var buff = sock._sQ; - var offset = sock._sQlen; + const buff = sock._sQ; + const offset = sock._sQlen; - var bpp, bits; + let bpp; if (depth > 16) { bpp = 32; @@ -1818,7 +1806,7 @@ RFB.messages = { bpp = 8; } - bits = Math.floor(depth/3); + const bits = Math.floor(depth/3); buff[offset] = 0; // msg-type @@ -1853,8 +1841,8 @@ RFB.messages = { }, clientEncodings: function (sock, encodings) { - var buff = sock._sQ; - var offset = sock._sQlen; + const buff = sock._sQ; + const offset = sock._sQlen; buff[offset] = 2; // msg-type buff[offset + 1] = 0; // padding @@ -1862,9 +1850,9 @@ RFB.messages = { buff[offset + 2] = encodings.length >> 8; buff[offset + 3] = encodings.length; - var i, j = offset + 4; - for (i = 0; i < encodings.length; i++) { - var enc = encodings[i]; + let j = offset + 4; + for (let i = 0; i < encodings.length; i++) { + const enc = encodings[i]; buff[j] = enc >> 24; buff[j + 1] = enc >> 16; buff[j + 2] = enc >> 8; @@ -1878,8 +1866,8 @@ RFB.messages = { }, fbUpdateRequest: function (sock, incremental, x, y, w, h) { - var buff = sock._sQ; - var offset = sock._sQlen; + const buff = sock._sQ; + const offset = sock._sQlen; if (typeof(x) === "undefined") { x = 0; } if (typeof(y) === "undefined") { y = 0; } @@ -1904,8 +1892,8 @@ RFB.messages = { }, xvpOp: function (sock, ver, op) { - var buff = sock._sQ; - var offset = sock._sQlen; + const buff = sock._sQ; + const offset = sock._sQlen; buff[offset] = 250; // msg-type buff[offset + 1] = 0; // padding @@ -1919,8 +1907,8 @@ RFB.messages = { }; RFB.genDES = function (password, challenge) { - var passwd = []; - for (var i = 0; i < password.length; i++) { + const passwd = []; + for (let i = 0; i < password.length; i++) { passwd.push(password.charCodeAt(i)); } return (new DES(passwd)).encrypt(challenge); @@ -1932,19 +1920,18 @@ RFB.encodingHandlers = { this._FBU.lines = this._FBU.height; } - var pixelSize = this._fb_depth == 8 ? 1 : 4; + const pixelSize = this._fb_depth == 8 ? 1 : 4; this._FBU.bytes = this._FBU.width * pixelSize; // at least a line if (this._sock.rQwait("RAW", this._FBU.bytes)) { return false; } - var cur_y = this._FBU.y + (this._FBU.height - this._FBU.lines); - var curr_height = Math.min(this._FBU.lines, + const cur_y = this._FBU.y + (this._FBU.height - this._FBU.lines); + const curr_height = Math.min(this._FBU.lines, Math.floor(this._sock.rQlen() / (this._FBU.width * pixelSize))); - var data = this._sock.get_rQ(); - var index = this._sock.get_rQi(); + let data = this._sock.get_rQ(); + let index = this._sock.get_rQi(); if (this._fb_depth == 8) { - var pixels = this._FBU.width * curr_height - var newdata = new Uint8Array(pixels * 4); - var i; - for (i = 0;i < pixels;i++) { + const pixels = this._FBU.width * curr_height + const newdata = new Uint8Array(pixels * 4); + for (let i = 0; i < pixels; i++) { newdata[i * 4 + 0] = ((data[index + i] >> 0) & 0x3) * 255 / 3; newdata[i * 4 + 1] = ((data[index + i] >> 2) & 0x3) * 255 / 3; newdata[i * 4 + 2] = ((data[index + i] >> 4) & 0x3) * 255 / 3; @@ -1981,7 +1968,7 @@ RFB.encodingHandlers = { }, RRE: function () { - var color; + let color; if (this._FBU.subrects === 0) { this._FBU.bytes = 4 + 4; if (this._sock.rQwait("RRE", 4 + 4)) { return false; } @@ -1992,16 +1979,16 @@ RFB.encodingHandlers = { while (this._FBU.subrects > 0 && this._sock.rQlen() >= (4 + 8)) { color = this._sock.rQshiftBytes(4); - var x = this._sock.rQshift16(); - var y = this._sock.rQshift16(); - var width = this._sock.rQshift16(); - var height = this._sock.rQshift16(); + const x = this._sock.rQshift16(); + const y = this._sock.rQshift16(); + const width = this._sock.rQshift16(); + const height = this._sock.rQshift16(); this._display.fillRect(this._FBU.x + x, this._FBU.y + y, width, height, color); this._FBU.subrects--; } if (this._FBU.subrects > 0) { - var chunk = Math.min(this._rre_chunk_sz, this._FBU.subrects); + const chunk = Math.min(this._rre_chunk_sz, this._FBU.subrects); this._FBU.bytes = (4 + 8) * chunk; } else { this._FBU.rects--; @@ -2012,8 +1999,8 @@ RFB.encodingHandlers = { }, HEXTILE: function () { - var rQ = this._sock.get_rQ(); - var rQi = this._sock.get_rQi(); + const rQ = this._sock.get_rQ(); + let rQi = this._sock.get_rQi(); if (this._FBU.tiles === 0) { this._FBU.tiles_x = Math.ceil(this._FBU.width / 16); @@ -2025,21 +2012,21 @@ RFB.encodingHandlers = { while (this._FBU.tiles > 0) { this._FBU.bytes = 1; if (this._sock.rQwait("HEXTILE subencoding", this._FBU.bytes)) { return false; } - var subencoding = rQ[rQi]; // Peek + const subencoding = rQ[rQi]; // Peek if (subencoding > 30) { // Raw this._fail("Illegal hextile subencoding (subencoding: " + subencoding + ")"); return false; } - var subrects = 0; - var curr_tile = this._FBU.total_tiles - this._FBU.tiles; - var tile_x = curr_tile % this._FBU.tiles_x; - var tile_y = Math.floor(curr_tile / this._FBU.tiles_x); - var x = this._FBU.x + tile_x * 16; - var y = this._FBU.y + tile_y * 16; - var w = Math.min(16, (this._FBU.x + this._FBU.width) - x); - var h = Math.min(16, (this._FBU.y + this._FBU.height) - y); + let subrects = 0; + const curr_tile = this._FBU.total_tiles - this._FBU.tiles; + const tile_x = curr_tile % this._FBU.tiles_x; + const tile_y = Math.floor(curr_tile / this._FBU.tiles_x); + const x = this._FBU.x + tile_x * 16; + const y = this._FBU.y + tile_y * 16; + const w = Math.min(16, (this._FBU.x + this._FBU.width) - x); + const h = Math.min(16, (this._FBU.y + this._FBU.height) - y); // Figure out how much we are expecting if (subencoding & 0x01) { // Raw @@ -2093,23 +2080,23 @@ RFB.encodingHandlers = { subrects = rQ[rQi]; rQi++; - for (var s = 0; s < subrects; s++) { - var color; + for (let s = 0; s < subrects; s++) { + let color; if (this._FBU.subencoding & 0x10) { // SubrectsColoured color = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]]; rQi += 4; } else { color = this._FBU.foreground; } - var xy = rQ[rQi]; + const xy = rQ[rQi]; rQi++; - var sx = (xy >> 4); - var sy = (xy & 0x0f); + const sx = (xy >> 4); + const sy = (xy & 0x0f); - var wh = rQ[rQi]; + const wh = rQ[rQi]; rQi++; - var sw = (wh >> 4) + 1; - var sh = (wh & 0x0f) + 1; + const sw = (wh >> 4) + 1; + const sh = (wh & 0x0f) + 1; this._display.subTile(sx, sy, sw, sh, color); } @@ -2133,18 +2120,18 @@ RFB.encodingHandlers = { this._FBU.bytes = 1; // compression-control byte if (this._sock.rQwait("TIGHT compression-control", this._FBU.bytes)) { return false; } - var resetStreams = 0; - var streamId = -1; - var decompress = function (data, expected) { - for (var i = 0; i < 4; i++) { + let resetStreams = 0; + let streamId = -1; + const decompress = function (data, expected) { + for (let i = 0; i < 4; i++) { if ((resetStreams >> i) & 1) { this._FBU.zlibs[i].reset(); Log.Info("Reset zlib stream " + i); } } - //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0); - var uncompressed = this._FBU.zlibs[streamId].inflate(data, true, expected); + //const uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0); + const uncompressed = this._FBU.zlibs[streamId].inflate(data, true, expected); /*if (uncompressed.status !== 0) { Log.Error("Invalid data in zlib stream"); }*/ @@ -2153,18 +2140,18 @@ RFB.encodingHandlers = { return uncompressed; }.bind(this); - var indexedToRGBX2Color = function (data, palette, width, height) { + const indexedToRGBX2Color = function (data, palette, width, height) { // Convert indexed (palette based) image data to RGB // TODO: reduce number of calculations inside loop - var dest = this._destBuff; - var w = Math.floor((width + 7) / 8); - var w1 = Math.floor(width / 8); - - /*for (var y = 0; y < height; y++) { - var b, x, dp, sp; - var yoffset = y * width; - var ybitoffset = y * w; - var xoffset, targetbyte; + const dest = this._destBuff; + const w = Math.floor((width + 7) / 8); + const w1 = Math.floor(width / 8); + + /*for (let y = 0; y < height; y++) { + let b, x, dp, sp; + const yoffset = y * width; + const ybitoffset = y * w; + let xoffset, targetbyte; for (x = 0; x < w1; x++) { xoffset = yoffset + x * 8; targetbyte = data[ybitoffset + x]; @@ -2188,10 +2175,10 @@ RFB.encodingHandlers = { } }*/ - for (var y = 0; y < height; y++) { - var b, x, dp, sp; + for (let y = 0; y < height; y++) { + let dp, sp, x; for (x = 0; x < w1; x++) { - for (b = 7; b >= 0; b--) { + for (let b = 7; b >= 0; b--) { dp = (y * width + x * 8 + 7 - b) * 4; sp = (data[y * w + x] >> b & 1) * 3; dest[dp] = palette[sp]; @@ -2201,7 +2188,7 @@ RFB.encodingHandlers = { } } - for (b = 7; b >= 8 - width % 8; b--) { + for (let b = 7; b >= 8 - width % 8; b--) { dp = (y * width + x * 8 + 7 - b) * 4; sp = (data[y * w + x] >> b & 1) * 3; dest[dp] = palette[sp]; @@ -2214,12 +2201,12 @@ RFB.encodingHandlers = { return dest; }.bind(this); - var indexedToRGBX = function (data, palette, width, height) { + const indexedToRGBX = function (data, palette, width, height) { // Convert indexed (palette based) image data to RGB - var dest = this._destBuff; - var total = width * height * 4; - for (var i = 0, j = 0; i < total; i += 4, j++) { - var sp = data[j] * 3; + const dest = this._destBuff; + const total = width * height * 4; + for (let i = 0, j = 0; i < total; i += 4, j++) { + const sp = data[j] * 3; dest[i] = palette[sp]; dest[i + 1] = palette[sp + 1]; dest[i + 2] = palette[sp + 2]; @@ -2229,20 +2216,20 @@ RFB.encodingHandlers = { return dest; }.bind(this); - var rQi = this._sock.get_rQi(); - var rQ = this._sock.rQwhole(); - var cmode, data; - var cl_header, cl_data; + const rQi = this._sock.get_rQi(); + const rQ = this._sock.rQwhole(); + let cmode, data; + let cl_header, cl_data; - var handlePalette = function () { - var numColors = rQ[rQi + 2] + 1; - var paletteSize = numColors * 3; + const handlePalette = function () { + const numColors = rQ[rQi + 2] + 1; + const paletteSize = numColors * 3; this._FBU.bytes += paletteSize; if (this._sock.rQwait("TIGHT palette " + cmode, this._FBU.bytes)) { return false; } - var bpp = (numColors <= 2) ? 1 : 8; - var rowSize = Math.floor((this._FBU.width * bpp + 7) / 8); - var raw = false; + const bpp = (numColors <= 2) ? 1 : 8; + const rowSize = Math.floor((this._FBU.width * bpp + 7) / 8); + let raw = false; if (rowSize * this._FBU.height < 12) { raw = true; cl_header = 0; @@ -2250,7 +2237,7 @@ RFB.encodingHandlers = { //clength = [0, rowSize * this._FBU.height]; } else { // begin inline getTightCLength (returning two-item arrays is bad for performance with GC) - var cl_offset = rQi + 3 + paletteSize; + const cl_offset = rQi + 3 + paletteSize; cl_header = 1; cl_data = 0; cl_data += rQ[cl_offset] & 0x7f; @@ -2270,7 +2257,7 @@ RFB.encodingHandlers = { // Shift ctl, filter id, num colors, palette entries, and clength off this._sock.rQskipBytes(3); - //var palette = this._sock.rQshiftBytes(paletteSize); + //const palette = this._sock.rQshiftBytes(paletteSize); this._sock.rQshiftTo(this._paletteBuff, paletteSize); this._sock.rQskipBytes(cl_header); @@ -2281,29 +2268,29 @@ RFB.encodingHandlers = { } // Convert indexed (palette based) image data to RGB - var rgbx; + let rgbx; if (numColors == 2) { rgbx = indexedToRGBX2Color(data, this._paletteBuff, this._FBU.width, this._FBU.height); - this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false); } else { rgbx = indexedToRGBX(data, this._paletteBuff, this._FBU.width, this._FBU.height); - this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false); } + this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false); + return true; }.bind(this); - var handleCopy = function () { - var raw = false; - var uncompressedSize = this._FBU.width * this._FBU.height * 3; + const handleCopy = function () { + let raw = false; + const uncompressedSize = this._FBU.width * this._FBU.height * 3; if (uncompressedSize < 12) { raw = true; cl_header = 0; cl_data = uncompressedSize; } else { // begin inline getTightCLength (returning two-item arrays is for peformance with GC) - var cl_offset = rQi + 1; + const cl_offset = rQi + 1; cl_header = 1; cl_data = 0; cl_data += rQ[cl_offset] & 0x7f; @@ -2334,7 +2321,7 @@ RFB.encodingHandlers = { return true; }.bind(this); - var ctl = this._sock.rQpeek8(); + let ctl = this._sock.rQpeek8(); // Keep tight reset bits resetStreams = ctl & 0xF; @@ -2379,6 +2366,7 @@ RFB.encodingHandlers = { if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; } // Determine FBU.bytes + let cl_offset, filterId; switch (cmode) { case "fill": // skip ctl byte @@ -2388,7 +2376,7 @@ RFB.encodingHandlers = { case "png": case "jpeg": // begin inline getTightCLength (returning two-item arrays is for peformance with GC) - var cl_offset = rQi + 1; + cl_offset = rQi + 1; cl_header = 1; cl_data = 0; cl_data += rQ[cl_offset] & 0x7f; @@ -2410,7 +2398,7 @@ RFB.encodingHandlers = { this._display.imageRect(this._FBU.x, this._FBU.y, "image/" + cmode, data); break; case "filter": - var filterId = rQ[rQi + 1]; + filterId = rQ[rQi + 1]; if (filterId === 1) { if (!handlePalette()) { return false; } } else { @@ -2441,7 +2429,7 @@ RFB.encodingHandlers = { this._FBU.bytes = 1; if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; } - var firstUpdate = !this._supportsSetDesktopSize; + const firstUpdate = !this._supportsSetDesktopSize; this._supportsSetDesktopSize = true; // Normally we only apply the current resize mode after a @@ -2452,7 +2440,7 @@ RFB.encodingHandlers = { this._requestRemoteResize(); } - var number_of_screens = this._sock.rQpeek8(); + const number_of_screens = this._sock.rQpeek8(); this._FBU.bytes = 4 + (number_of_screens * 16); if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; } @@ -2460,7 +2448,7 @@ RFB.encodingHandlers = { this._sock.rQskipBytes(1); // number-of-screens this._sock.rQskipBytes(3); // padding - for (var i = 0; i < number_of_screens; i += 1) { + for (let i = 0; i < number_of_screens; i += 1) { // Save the id and flags of the first screen if (i === 0) { this._screen_id = this._sock.rQshiftBytes(4); // id @@ -2484,7 +2472,7 @@ RFB.encodingHandlers = { // We need to handle errors when we requested the resize. if (this._FBU.x === 1 && this._FBU.y !== 0) { - var msg = ""; + let msg = ""; // The y-position indicates the status code from the server switch (this._FBU.y) { case 1: @@ -2520,13 +2508,13 @@ RFB.encodingHandlers = { Cursor: function () { Log.Debug(">> set_cursor"); - var x = this._FBU.x; // hotspot-x - var y = this._FBU.y; // hotspot-y - var w = this._FBU.width; - var h = this._FBU.height; + const x = this._FBU.x; // hotspot-x + const y = this._FBU.y; // hotspot-y + const w = this._FBU.width; + const h = this._FBU.height; - var pixelslength = w * h * 4; - var masklength = Math.floor((w + 7) / 8) * h; + const pixelslength = w * h * 4; + const masklength = Math.floor((w + 7) / 8) * h; this._FBU.bytes = pixelslength + masklength; if (this._sock.rQwait("cursor encoding", this._FBU.bytes)) { return false; } @@ -2547,7 +2535,7 @@ RFB.encodingHandlers = { // Old Safari doesn't support creating keyboard events try { - var keyboardEvent = document.createEvent("keyboardEvent"); + const keyboardEvent = document.createEvent("keyboardEvent"); if (keyboardEvent.code !== undefined) { this._qemuExtKeyEventSupported = true; } diff --git a/core/util/browser.js b/core/util/browser.js index 2b44fb2..80551d4 100644 --- a/core/util/browser.js +++ b/core/util/browser.js @@ -9,7 +9,7 @@ import * as Log from './logging.js'; // Touch detection -export var isTouchDevice = ('ontouchstart' in document.documentElement) || +export let isTouchDevice = ('ontouchstart' in document.documentElement) || // requried for Chrome debugger (document.ontouchstart !== undefined) || // required for MS Surface @@ -20,12 +20,12 @@ window.addEventListener('touchstart', function onFirstTouch() { window.removeEventListener('touchstart', onFirstTouch, false); }, false); -var _cursor_uris_supported = null; +let _cursor_uris_supported = null; export function supportsCursorURIs () { if (_cursor_uris_supported === null) { try { - var target = document.createElement('canvas'); + const target = document.createElement('canvas'); target.style.cursor = 'url("data:image/x-icon;base64,AAACAAEACAgAAAIAAgA4AQAAFgAAACgAAAAIAAAAEAAAAAEAIAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAD/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////AAAAAAAAAAAAAAAAAAAAAA==") 2 2, default'; if (target.style.cursor) { diff --git a/core/util/events.js b/core/util/events.js index 270a558..66527fa 100644 --- a/core/util/events.js +++ b/core/util/events.js @@ -20,14 +20,14 @@ export function stopEvent (e) { } // Emulate Element.setCapture() when not supported -var _captureRecursion = false; -var _captureElem = null; +let _captureRecursion = false; +let _captureElem = null; function _captureProxy(e) { // Recursion protection as we'll see our own event if (_captureRecursion) return; // Clone the event as we cannot dispatch an already dispatched event - var newEv = new e.constructor(e.type, e); + const newEv = new e.constructor(e.type, e); _captureRecursion = true; _captureElem.dispatchEvent(newEv); @@ -49,12 +49,13 @@ function _captureProxy(e) { // Follow cursor style of target element function _captureElemChanged() { - var captureElem = document.getElementById("noVNC_mouse_capture_elem"); + const captureElem = document.getElementById("noVNC_mouse_capture_elem"); captureElem.style.cursor = window.getComputedStyle(_captureElem).cursor; } -var _captureObserver = new MutationObserver(_captureElemChanged); -var _captureIndex = 0; +const _captureObserver = new MutationObserver(_captureElemChanged); + +let _captureIndex = 0; export function setCapture (elem) { if (elem.setCapture) { @@ -69,7 +70,7 @@ export function setCapture (elem) { // called multiple times without coordination releaseCapture(); - var captureElem = document.getElementById("noVNC_mouse_capture_elem"); + let captureElem = document.getElementById("noVNC_mouse_capture_elem"); if (captureElem === null) { captureElem = document.createElement("div"); @@ -129,7 +130,7 @@ export function releaseCapture () { _captureObserver.disconnect(); - var captureElem = document.getElementById("noVNC_mouse_capture_elem"); + const captureElem = document.getElementById("noVNC_mouse_capture_elem"); captureElem.style.display = "none"; window.removeEventListener('mousemove', _captureProxy); diff --git a/core/util/eventtarget.js b/core/util/eventtarget.js index 61bc7a1..2472319 100644 --- a/core/util/eventtarget.js +++ b/core/util/eventtarget.js @@ -6,7 +6,7 @@ * See README.md for usage and integration instructions. */ -var EventTargetMixin = { +const EventTargetMixin = { _listeners: null, addEventListener: function(type, callback) { diff --git a/core/util/logging.js b/core/util/logging.js index 3b60f69..5669ad2 100644 --- a/core/util/logging.js +++ b/core/util/logging.js @@ -10,12 +10,12 @@ * Logging/debug routines */ -var _log_level = 'warn'; +let _log_level = 'warn'; -var Debug = function (msg) {}; -var Info = function (msg) {}; -var Warn = function (msg) {}; -var Error = function (msg) {}; +let Debug = function (msg) {}; +let Info = function (msg) {}; +let Warn = function (msg) {}; +let Error = function (msg) {}; export function init_logging (level) { if (typeof level === 'undefined') { diff --git a/core/util/polyfill.js b/core/util/polyfill.js index 8c600e6..c991aa2 100644 --- a/core/util/polyfill.js +++ b/core/util/polyfill.js @@ -16,13 +16,13 @@ if (typeof Object.assign != 'function') { throw new TypeError('Cannot convert undefined or null to object'); } - var to = Object(target); + const to = Object(target); - for (var index = 1; index < arguments.length; index++) { - var nextSource = arguments[index]; + for (let index = 1; index < arguments.length; index++) { + const nextSource = arguments[index]; if (nextSource != null) { // Skip over if undefined or null - for (var nextKey in nextSource) { + for (let nextKey in nextSource) { // Avoid bugs when hasOwnProperty is shadowed if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) { to[nextKey] = nextSource[nextKey]; @@ -41,7 +41,7 @@ if (typeof Object.assign != 'function') { (function () { function CustomEvent ( event, params ) { params = params || { bubbles: false, cancelable: false, detail: undefined }; - var evt = document.createEvent( 'CustomEvent' ); + const evt = document.createEvent( 'CustomEvent' ); evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail ); return evt; } diff --git a/core/websock.js b/core/websock.js index a5643dd..f07a7be 100644 --- a/core/websock.js +++ b/core/websock.js @@ -42,15 +42,15 @@ export default function Websock() { // this has performance issues in some versions Chromium, and // doesn't gain a tremendous amount of performance increase in Firefox // at the moment. It may be valuable to turn it on in the future. -var ENABLE_COPYWITHIN = false; +const ENABLE_COPYWITHIN = false; -var MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB +const MAX_RQ_GROW_SIZE = 40 * 1024 * 1024; // 40 MiB -var typedArrayToString = (function () { +const typedArrayToString = (function () { // This is only for PhantomJS, which doesn't like apply-ing // with Typed Arrays try { - var arr = new Uint8Array([1, 2, 3]); + const arr = new Uint8Array([1, 2, 3]); String.fromCharCode.apply(null, arr); return function (a) { return String.fromCharCode.apply(null, a); }; } catch (ex) { @@ -115,7 +115,7 @@ Websock.prototype = { rQshiftStr: function (len) { if (typeof(len) === 'undefined') { len = this.rQlen(); } - var arr = new Uint8Array(this._rQ.buffer, this._rQi, len); + const arr = new Uint8Array(this._rQ.buffer, this._rQi, len); this._rQi += len; return typedArrayToString(arr); }, @@ -149,7 +149,7 @@ Websock.prototype = { // to be available in the receive queue. Return true if we need to // wait (and possibly print a debug message), otherwise false. rQwait: function (msg, num, goback) { - var rQlen = this._rQlen - this._rQi; // Skip rQlen() function call + const rQlen = this._rQlen - this._rQi; // Skip rQlen() function call if (rQlen < num) { if (goback) { if (this._rQi < goback) { @@ -251,7 +251,7 @@ Websock.prototype = { }, _expand_compact_rQ: function (min_fit) { - var resizeNeeded = min_fit || this._rQlen - this._rQi > this._rQbufferSize / 2; + const resizeNeeded = min_fit || this._rQlen - this._rQi > this._rQbufferSize / 2; if (resizeNeeded) { if (!min_fit) { // just double the size if we need to do compaction @@ -271,7 +271,7 @@ Websock.prototype = { } if (resizeNeeded) { - var old_rQbuffer = this._rQ.buffer; + const old_rQbuffer = this._rQ.buffer; this._rQmax = this._rQbufferSize / 8; this._rQ = new Uint8Array(this._rQbufferSize); this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi)); @@ -289,7 +289,7 @@ Websock.prototype = { _decode_message: function (data) { // push arraybuffer values onto the end - var u8 = new Uint8Array(data); + const u8 = new Uint8Array(data); if (u8.length > this._rQbufferSize - this._rQlen) { this._expand_compact_rQ(u8.length); } diff --git a/docs/API.md b/docs/API.md index c5923e3..a81da5c 100644 --- a/docs/API.md +++ b/docs/API.md @@ -137,7 +137,7 @@ connection to a specified VNC server. ##### Syntax - var rfb = new RFB( target, url [, options] ); + let rfb = new RFB( target, url [, options] ); ###### Parameters diff --git a/po/po2js b/po/po2js index 15304c9..6531716 100755 --- a/po/po2js +++ b/po/po2js @@ -17,11 +17,11 @@ * along with this program. If not, see . */ -var getopt = require('node-getopt'); -var fs = require('fs'); -var po2json = require("po2json"); +const getopt = require('node-getopt'); +const fs = require('fs'); +const po2json = require("po2json"); -opt = getopt.create([ +const opt = getopt.create([ ['h' , 'help' , 'display this help'], ]).bindHelp().parseSystem(); @@ -30,14 +30,14 @@ if (opt.argv.length != 2) { process.exit(1); } -var data = po2json.parseFileSync(opt.argv[0]); +const data = po2json.parseFileSync(opt.argv[0]); -var bodyPart = Object.keys(data).filter((msgid) => msgid !== "").map((msgid) => { +const bodyPart = Object.keys(data).filter((msgid) => msgid !== "").map((msgid) => { if (msgid === "") return; - var msgstr = data[msgid][1]; + const msgstr = data[msgid][1]; return " " + JSON.stringify(msgid) + ": " + JSON.stringify(msgstr); }).join(",\n"); -var output = "{\n" + bodyPart + "\n}"; +const output = "{\n" + bodyPart + "\n}"; fs.writeFileSync(opt.argv[1], output); diff --git a/po/xgettext-html b/po/xgettext-html index 231de44..87638cb 100755 --- a/po/xgettext-html +++ b/po/xgettext-html @@ -5,17 +5,16 @@ * Licensed under MPL 2.0 (see LICENSE.txt) */ -var getopt = require('node-getopt'); +const getopt = require('node-getopt'); +const jsdom = require("jsdom"); +const fs = require("fs"); -var jsdom = require("jsdom"); -var fs = require("fs"); - -opt = getopt.create([ +const opt = getopt.create([ ['o' , 'output=FILE' , 'write output to specified file'], ['h' , 'help' , 'display this help'], ]).bindHelp().parseSystem(); -var strings = {}; +const strings = {}; function addString(str, location) { if (str.length == 0) { @@ -74,7 +73,7 @@ function process(elem, locator, enabled) { } } - for (var i = 0;i < elem.childNodes.length;i++) { + for (let i = 0; i < elem.childNodes.length; i++) { node = elem.childNodes[i]; if (node.nodeType === node.ELEMENT_NODE) { process(node, locator, enabled); @@ -84,24 +83,22 @@ function process(elem, locator, enabled) { } } -for (var i = 0;i < opt.argv.length;i++) { - var file; - - fn = opt.argv[i]; - file = fs.readFileSync(fn, "utf8"); - dom = new jsdom.JSDOM(file, { includeNodeLocations: true }); - body = dom.window.document.body; +for (let i = 0; i < opt.argv.length; i++) { + const fn = opt.argv[i]; + const file = fs.readFileSync(fn, "utf8"); + const dom = new jsdom.JSDOM(file, { includeNodeLocations: true }); + const body = dom.window.document.body; - locator = function (elem) { - offset = dom.nodeLocation(elem).startOffset; - line = file.slice(0, offset).split("\n").length; + const locator = function (elem) { + const offset = dom.nodeLocation(elem).startOffset; + const line = file.slice(0, offset).split("\n").length; return fn + ":" + line; }; process(body, locator, true); } -var output = ""; +let output = ""; for (str in strings) { output += "#:"; diff --git a/tests/assertions.js b/tests/assertions.js index 4f1cdc1..a336a7a 100644 --- a/tests/assertions.js +++ b/tests/assertions.js @@ -5,15 +5,15 @@ chai.use(sinonChai); // noVNC specific assertions chai.use(function (_chai, utils) { _chai.Assertion.addMethod('displayed', function (target_data) { - var obj = this._obj; - var ctx = obj._target.getContext('2d'); - var data_cl = ctx.getImageData(0, 0, obj._target.width, obj._target.height).data; + const obj = this._obj; + const ctx = obj._target.getContext('2d'); + const data_cl = ctx.getImageData(0, 0, obj._target.width, obj._target.height).data; // NB(directxman12): PhantomJS 1.x doesn't implement Uint8ClampedArray, so work around that - var data = new Uint8Array(data_cl); - var len = data_cl.length; + const data = new Uint8Array(data_cl); + const len = data_cl.length; new chai.Assertion(len).to.be.equal(target_data.length, "unexpected display size"); - var same = true; - for (var i = 0; i < len; i++) { + let same = true; + for (let i = 0; i < len; i++) { if (data[i] != target_data[i]) { same = false; break; @@ -31,19 +31,19 @@ chai.use(function (_chai, utils) { }); _chai.Assertion.addMethod('sent', function (target_data) { - var obj = this._obj; + const obj = this._obj; obj.inspect = function () { - var res = { _websocket: obj._websocket, rQi: obj._rQi, _rQ: new Uint8Array(obj._rQ.buffer, 0, obj._rQlen), + const res = { _websocket: obj._websocket, rQi: obj._rQi, _rQ: new Uint8Array(obj._rQ.buffer, 0, obj._rQlen), _sQ: new Uint8Array(obj._sQ.buffer, 0, obj._sQlen) }; res.prototype = obj; return res; }; - var data = obj._websocket._get_sent_data(); - var same = true; + const data = obj._websocket._get_sent_data(); + let same = true; if (data.length != target_data.length) { same = false; } else { - for (var i = 0; i < data.length; i++) { + for (let i = 0; i < data.length; i++) { if (data[i] != target_data[i]) { same = false; break; @@ -68,13 +68,12 @@ chai.use(function (_chai, utils) { _chai.Assertion.overwriteMethod('equal', function (_super) { return function assertArrayEqual(target) { if (utils.flag(this, 'array')) { - var obj = this._obj; + const obj = this._obj; - var i; - var same = true; + let same = true; if (utils.flag(this, 'deep')) { - for (i = 0; i < obj.length; i++) { + for (let i = 0; i < obj.length; i++) { if (!utils.eql(obj[i], target[i])) { same = false; break; @@ -86,7 +85,7 @@ chai.use(function (_chai, utils) { "expected #{this} not to have elements deeply equal to #{exp}", Array.prototype.slice.call(target)); } else { - for (i = 0; i < obj.length; i++) { + for (let i = 0; i < obj.length; i++) { if (obj[i] != target[i]) { same = false; break; diff --git a/tests/fake.websocket.js b/tests/fake.websocket.js index de3fb30..2e28494 100644 --- a/tests/fake.websocket.js +++ b/tests/fake.websocket.js @@ -2,10 +2,10 @@ import Base64 from '../core/base64.js'; // PhantomJS can't create Event objects directly, so we need to use this function make_event(name, props) { - var evt = document.createEvent('Event'); + const evt = document.createEvent('Event'); evt.initEvent(name, true, true); if (props) { - for (var prop in props) { + for (let prop in props) { evt[prop] = props[prop]; } } @@ -50,7 +50,7 @@ FakeWebSocket.prototype = { }, _get_sent_data: function () { - var res = new Uint8Array(this._send_queue.buffer, 0, this.bufferedAmount); + const res = new Uint8Array(this._send_queue.buffer, 0, this.bufferedAmount); this.bufferedAmount = 0; return res; }, @@ -76,7 +76,7 @@ FakeWebSocket.__is_fake = true; FakeWebSocket.replace = function () { if (!WebSocket.__is_fake) { - var real_version = WebSocket; + const real_version = WebSocket; // eslint-disable-next-line no-global-assign WebSocket = FakeWebSocket; FakeWebSocket.__real_version = real_version; diff --git a/tests/karma-test-main.js b/tests/karma-test-main.js index 657e312..334b771 100644 --- a/tests/karma-test-main.js +++ b/tests/karma-test-main.js @@ -1,6 +1,6 @@ -var TEST_REGEXP = /test\..*\.js/; -var allTestFiles = []; -var extraFiles = ['/base/tests/assertions.js']; +const TEST_REGEXP = /test\..*\.js/; +const allTestFiles = []; +const extraFiles = ['/base/tests/assertions.js']; Object.keys(window.__karma__.files).forEach(function (file) { if (TEST_REGEXP.test(file)) { diff --git a/tests/playback-ui.js b/tests/playback-ui.js index 84683cf..1565b8f 100644 --- a/tests/playback-ui.js +++ b/tests/playback-ui.js @@ -3,11 +3,11 @@ import * as WebUtil from '../app/webutil.js'; import RecordingPlayer from './playback.js'; -var frames = null; -var encoding = null; +let frames = null; +let encoding = null; function message(str) { - var cell = document.getElementById('messages'); + const cell = document.getElementById('messages'); cell.textContent += str + "\n"; cell.scrollTop = cell.scrollHeight; } @@ -22,7 +22,7 @@ function loadFile() { message("Loading " + fname); return new Promise(function (resolve, reject) { - var script = document.createElement("script"); + const script = document.createElement("script"); script.onload = resolve; script.onerror = reject; document.body.appendChild(script); @@ -31,10 +31,10 @@ function loadFile() { } function enableUI() { - var iterations = WebUtil.getQueryVar('iterations', 3); + const iterations = WebUtil.getQueryVar('iterations', 3); document.getElementById('iterations').value = iterations; - var mode = WebUtil.getQueryVar('mode', 3); + const mode = WebUtil.getQueryVar('mode', 3); if (mode === 'realtime') { document.getElementById('mode2').checked = true; } else { @@ -121,7 +121,7 @@ IterationPlayer.prototype = { this._state = 'failed'; } - var evt = new Event('rfbdisconnected'); + const evt = new Event('rfbdisconnected'); evt.clean = clean; evt.frame = frame; evt.iteration = this._iteration; @@ -136,7 +136,7 @@ function start() { const iterations = document.getElementById('iterations').value; - var mode; + let mode; if (document.getElementById('mode1').checked) { message(`Starting performance playback (fullspeed) [${iterations} iteration(s)]`); diff --git a/tests/playback.js b/tests/playback.js index 7c9d7ff..cbeb20f 100644 --- a/tests/playback.js +++ b/tests/playback.js @@ -9,12 +9,12 @@ import * as Log from '../core/util/logging.js'; import Base64 from '../core/base64.js'; // Immediate polyfill -if (setImmediate === undefined) { - var _immediateIdCounter = 1; - var _immediateFuncs = {}; +if (window.setImmediate === undefined) { + let _immediateIdCounter = 1; + const _immediateFuncs = {}; - var setImmediate = function (func) { - var index = _immediateIdCounter++; + window.setImmediate = function (func) { + const index = _immediateIdCounter++; _immediateFuncs[index] = func; window.postMessage("noVNC immediate trigger:" + index, "*"); return index; @@ -24,15 +24,15 @@ if (setImmediate === undefined) { _immediateFuncs[id]; }; - var _onMessage = function (event) { + const _onMessage = function (event) { if ((typeof event.data !== "string") || (event.data.indexOf("noVNC immediate trigger:") !== 0)) { return; } - var index = event.data.slice("noVNC immediate trigger:".length); + const index = event.data.slice("noVNC immediate trigger:".length); - var callback = _immediateFuncs[index]; + const callback = _immediateFuncs[index]; if (callback === undefined) { return; } @@ -51,8 +51,8 @@ export default function RecordingPlayer (frames, encoding, disconnected) { this._disconnected = disconnected; if (this._encoding === undefined) { - let frame = this._frames[0]; - let start = frame.indexOf('{', 1) + 1; + const frame = this._frames[0]; + const start = frame.indexOf('{', 1) + 1; if (frame.slice(start).startsWith('UkZC')) { this._encoding = 'base64'; } else { @@ -108,7 +108,7 @@ RecordingPlayer.prototype = { _queueNextPacket: function () { if (!this._running) { return; } - var frame = this._frames[this._frame_index]; + let frame = this._frames[this._frame_index]; // skip send frames while (this._frame_index < this._frame_length && frame.charAt(0) === "}") { @@ -129,8 +129,8 @@ RecordingPlayer.prototype = { } if (this._realtime) { - let foffset = frame.slice(1, frame.indexOf('{', 1)); - let toffset = (new Date()).getTime() - this._start_time; + const foffset = frame.slice(1, frame.indexOf('{', 1)); + const toffset = (new Date()).getTime() - this._start_time; let delay = foffset - toffset; if (delay < 1) delay = 1; @@ -143,8 +143,8 @@ RecordingPlayer.prototype = { _doPacket: function () { // Avoid having excessive queue buildup in non-realtime mode if (this._trafficManagement && this._rfb._flushing) { - let player = this; - let orig = this._rfb._display.onflush; + const player = this; + const orig = this._rfb._display.onflush; this._rfb._display.onflush = function () { player._rfb._display.onflush = orig; player._rfb._onFlush(); @@ -154,8 +154,8 @@ RecordingPlayer.prototype = { } const frame = this._frames[this._frame_index]; - var start = frame.indexOf('{', 1) + 1; - var u8; + let start = frame.indexOf('{', 1) + 1; + let u8; if (this._encoding === 'base64') { u8 = Base64.decode(frame.slice(start)); start = 0; @@ -174,7 +174,7 @@ RecordingPlayer.prototype = { _finish() { if (this._rfb._display.pending()) { - var player = this; + const player = this; this._rfb._display.onflush = function () { if (player._rfb._flushing) { player._rfb._onFlush(); diff --git a/tests/test.base64.js b/tests/test.base64.js index b87fdd2..0ff4bfe 100644 --- a/tests/test.base64.js +++ b/tests/test.base64.js @@ -1,28 +1,28 @@ -var expect = chai.expect; +const expect = chai.expect; import Base64 from '../core/base64.js'; describe('Base64 Tools', function() { "use strict"; - var BIN_ARR = new Array(256); - for (var i = 0; i < 256; i++) { + const BIN_ARR = new Array(256); + for (let i = 0; i < 256; i++) { BIN_ARR[i] = i; } - var B64_STR = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w=="; + const B64_STR = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w=="; describe('encode', function() { it('should encode a binary string into Base64', function() { - var encoded = Base64.encode(BIN_ARR); + const encoded = Base64.encode(BIN_ARR); expect(encoded).to.equal(B64_STR); }); }); describe('decode', function() { it('should decode a Base64 string into a normal string', function() { - var decoded = Base64.decode(B64_STR); + const decoded = Base64.decode(B64_STR); expect(decoded).to.deep.equal(BIN_ARR); }); diff --git a/tests/test.display.js b/tests/test.display.js index 5a46f18..a7afd06 100644 --- a/tests/test.display.js +++ b/tests/test.display.js @@ -1,4 +1,4 @@ -var expect = chai.expect; +const expect = chai.expect; import Base64 from '../core/base64.js'; import Display from '../core/display.js'; @@ -6,37 +6,35 @@ import Display from '../core/display.js'; import sinon from '../vendor/sinon.js'; describe('Display/Canvas Helper', function () { - var checked_data = [ + const checked_data = new Uint8Array([ 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 - ]; - checked_data = new Uint8Array(checked_data); + ]); - var basic_data = [0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0xff, 0xff, 0xff, 255]; - basic_data = new Uint8Array(basic_data); + const basic_data = new Uint8Array([0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0xff, 0xff, 0xff, 255]); function make_image_canvas (input_data) { - var canvas = document.createElement('canvas'); + const canvas = document.createElement('canvas'); canvas.width = 4; canvas.height = 4; - var ctx = canvas.getContext('2d'); - var data = ctx.createImageData(4, 4); - for (var i = 0; i < checked_data.length; i++) { data.data[i] = input_data[i]; } + const ctx = canvas.getContext('2d'); + const data = ctx.createImageData(4, 4); + for (let i = 0; i < checked_data.length; i++) { data.data[i] = input_data[i]; } ctx.putImageData(data, 0, 0); return canvas; } function make_image_png (input_data) { - var canvas = make_image_canvas(input_data); - var url = canvas.toDataURL(); - var data = url.split(",")[1]; + const canvas = make_image_canvas(input_data); + const url = canvas.toDataURL(); + const data = url.split(",")[1]; return Base64.decode(data); } describe('viewport handling', function () { - var display; + let display; beforeEach(function () { display = new Display(document.createElement('canvas')); display.clipViewport = true; @@ -51,10 +49,9 @@ describe('Display/Canvas Helper', function () { display.drawImage(make_image_canvas(basic_data), 1, 1); display.flip(); - var expected = new Uint8Array(16); - var i; - for (i = 0; i < 8; i++) { expected[i] = basic_data[i]; } - for (i = 8; i < 16; i++) { expected[i] = 0; } + const expected = new Uint8Array(16); + for (let i = 0; i < 8; i++) { expected[i] = basic_data[i]; } + for (let i = 8; i < 16; i++) { expected[i] = 0; } expect(display).to.have.displayed(expected); }); @@ -119,7 +116,7 @@ describe('Display/Canvas Helper', function () { }); describe('resizing', function () { - var display; + let display; beforeEach(function () { display = new Display(document.createElement('canvas')); display.clipViewport = false; @@ -136,8 +133,8 @@ describe('Display/Canvas Helper', function () { display.fillRect(0, 0, 4, 4, [0, 0, 0xff]); display.resize(2, 2); display.flip(); - var expected = []; - for (var i = 0; i < 4 * 2*2; i += 4) { + const expected = []; + for (let i = 0; i < 4 * 2*2; i += 4) { expected[i] = 0xff; expected[i+1] = expected[i+2] = 0; expected[i+3] = 0xff; @@ -179,8 +176,8 @@ describe('Display/Canvas Helper', function () { }); describe('rescaling', function () { - var display; - var canvas; + let display; + let canvas; beforeEach(function () { canvas = document.createElement('canvas'); @@ -220,8 +217,8 @@ describe('Display/Canvas Helper', function () { }); describe('autoscaling', function () { - var display; - var canvas; + let display; + let canvas; beforeEach(function () { canvas = document.createElement('canvas'); @@ -268,7 +265,7 @@ describe('Display/Canvas Helper', function () { // TODO(directxman12): improve the tests for each of the drawing functions to cover more than just the // basic cases - var display; + let display; beforeEach(function () { display = new Display(document.createElement('canvas')); display.resize(4, 4); @@ -279,8 +276,8 @@ describe('Display/Canvas Helper', function () { display._logo = null; display.clear(); display.resize(4, 4); - var empty = []; - for (var i = 0; i < 4 * display._fb_width * display._fb_height; i++) { empty[i] = 0; } + const empty = []; + for (let i = 0; i < 4 * display._fb_width * display._fb_height; i++) { empty[i] = 0; } expect(display).to.have.displayed(new Uint8Array(empty)); }); @@ -300,8 +297,8 @@ describe('Display/Canvas Helper', function () { display.fillRect(0, 0, 4, 4, [0, 0, 0xff]); display.flip(); display.fillRect(0, 0, 4, 4, [0, 0xff, 0]); - var expected = []; - for (var i = 0; i < 4 * display._fb_width * display._fb_height; i += 4) { + const expected = []; + for (let i = 0; i < 4 * display._fb_width * display._fb_height; i += 4) { expected[i] = 0xff; expected[i+1] = expected[i+2] = 0; expected[i+3] = 0xff; @@ -346,7 +343,7 @@ describe('Display/Canvas Helper', function () { // We have a special cache for 16x16 tiles that we need to test it('should support drawing a 16x16 tile', function () { - let large_checked_data = new Uint8Array(16*16*4); + const large_checked_data = new Uint8Array(16*16*4); display.resize(16, 16); for (let y = 0;y < 16;y++) { @@ -371,8 +368,8 @@ describe('Display/Canvas Helper', function () { }); it('should support drawing BGRX blit images with true color via #blitImage', function () { - var data = []; - for (var i = 0; i < 16; i++) { + const data = []; + for (let i = 0; i < 16; i++) { data[i * 4] = checked_data[i * 4 + 2]; data[i * 4 + 1] = checked_data[i * 4 + 1]; data[i * 4 + 2] = checked_data[i * 4]; @@ -384,8 +381,8 @@ describe('Display/Canvas Helper', function () { }); it('should support drawing RGB blit images with true color via #blitRgbImage', function () { - var data = []; - for (var i = 0; i < 16; i++) { + const data = []; + for (let i = 0; i < 16; i++) { data[i * 3] = checked_data[i * 4]; data[i * 3 + 1] = checked_data[i * 4 + 1]; data[i * 3 + 2] = checked_data[i * 4 + 2]; @@ -396,7 +393,7 @@ describe('Display/Canvas Helper', function () { }); it('should support drawing an image object via #drawImage', function () { - var img = make_image_canvas(checked_data); + const img = make_image_canvas(checked_data); display.drawImage(img, 0, 0); display.flip(); expect(display).to.have.displayed(checked_data); @@ -404,7 +401,7 @@ describe('Display/Canvas Helper', function () { }); describe('the render queue processor', function () { - var display; + let display; beforeEach(function () { display = new Display(document.createElement('canvas')); display.resize(4, 4); @@ -427,7 +424,7 @@ describe('Display/Canvas Helper', function () { }); it('should wait until an image is loaded to attempt to draw it and the rest of the queue', function () { - var img = { complete: false, addEventListener: sinon.spy() } + const img = { complete: false, addEventListener: sinon.spy() } display._renderQ = [{ type: 'img', x: 3, y: 4, img: img }, { type: 'fill', x: 1, y: 2, width: 3, height: 4, color: 5 }]; display.drawImage = sinon.spy(); diff --git a/tests/test.helper.js b/tests/test.helper.js index 1ab02fb..b04005d 100644 --- a/tests/test.helper.js +++ b/tests/test.helper.js @@ -1,4 +1,4 @@ -var expect = chai.expect; +const expect = chai.expect; import keysyms from '../core/input/keysymdef.js'; import * as KeyboardUtil from "../core/input/util.js"; @@ -64,7 +64,7 @@ describe('Helpers', function() { }); describe('Fix Meta on macOS', function() { - var origNavigator; + let origNavigator; beforeEach(function () { // window.navigator is a protected read-only property in many // environments, so we need to redefine it whilst running these @@ -127,7 +127,7 @@ describe('Helpers', function() { }); describe('Broken key AltGraph on IE/Edge', function() { - var origNavigator; + let origNavigator; beforeEach(function () { // window.navigator is a protected read-only property in many // environments, so we need to redefine it whilst running these diff --git a/tests/test.keyboard.js b/tests/test.keyboard.js index 574f88e..3d409fb 100644 --- a/tests/test.keyboard.js +++ b/tests/test.keyboard.js @@ -1,4 +1,4 @@ -var expect = chai.expect; +const expect = chai.expect; import sinon from '../vendor/sinon.js'; @@ -11,8 +11,8 @@ describe('Key Event Handling', function() { // The real KeyboardEvent constructor might not work everywhere we // want to run these tests function keyevent(typeArg, KeyboardEventInit) { - var e = { type: typeArg }; - for (var key in KeyboardEventInit) { + const e = { type: typeArg }; + for (let key in KeyboardEventInit) { e[key] = KeyboardEventInit[key]; } e.stopPropagation = sinon.spy(); @@ -23,7 +23,7 @@ describe('Key Event Handling', function() { describe('Decode Keyboard Events', function() { it('should decode keydown events', function(done) { if (browser.isIE() || browser.isEdge()) this.skip(); - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('KeyA'); @@ -34,8 +34,8 @@ describe('Key Event Handling', function() { }); it('should decode keyup events', function(done) { if (browser.isIE() || browser.isEdge()) this.skip(); - var calls = 0; - var kbd = new Keyboard(document); + let calls = 0; + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('KeyA'); @@ -50,13 +50,13 @@ describe('Key Event Handling', function() { describe('Legacy keypress Events', function() { it('should wait for keypress when needed', function() { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41})); expect(kbd.onkeyevent).to.not.have.been.called; }); it('should decode keypress events', function(done) { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('KeyA'); @@ -67,14 +67,14 @@ describe('Key Event Handling', function() { kbd._handleKeyPress(keyevent('keypress', {code: 'KeyA', charCode: 0x61})); }); it('should ignore keypress with different code', function() { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41})); kbd._handleKeyPress(keyevent('keypress', {code: 'KeyB', charCode: 0x61})); expect(kbd.onkeyevent).to.not.have.been.called; }); it('should handle keypress with missing code', function(done) { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('KeyA'); @@ -85,7 +85,7 @@ describe('Key Event Handling', function() { kbd._handleKeyPress(keyevent('keypress', {charCode: 0x61})); }); it('should guess key if no keypress and numeric key', function(done) { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x32); expect(code).to.be.equal('Digit2'); @@ -95,7 +95,7 @@ describe('Key Event Handling', function() { kbd._handleKeyDown(keyevent('keydown', {code: 'Digit2', keyCode: 0x32})); }); it('should guess key if no keypress and alpha key', function(done) { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('KeyA'); @@ -105,7 +105,7 @@ describe('Key Event Handling', function() { kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41, shiftKey: false})); }); it('should guess key if no keypress and alpha key (with shift)', function(done) { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x41); expect(code).to.be.equal('KeyA'); @@ -115,7 +115,7 @@ describe('Key Event Handling', function() { kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', keyCode: 0x41, shiftKey: true})); }); it('should not guess key if no keypress and unknown key', function(done) { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0); expect(code).to.be.equal('KeyA'); @@ -131,25 +131,25 @@ describe('Key Event Handling', function() { if (browser.isIE() || browser.isEdge()) this.skip(); }); it('should suppress anything with a valid key', function() { - var kbd = new Keyboard(document, {}); - var evt1 = keyevent('keydown', {code: 'KeyA', key: 'a'}); + const kbd = new Keyboard(document, {}); + const evt1 = keyevent('keydown', {code: 'KeyA', key: 'a'}); kbd._handleKeyDown(evt1); expect(evt1.preventDefault).to.have.been.called; - var evt2 = keyevent('keyup', {code: 'KeyA', key: 'a'}); + const evt2 = keyevent('keyup', {code: 'KeyA', key: 'a'}); kbd._handleKeyUp(evt2); expect(evt2.preventDefault).to.have.been.called; }); it('should not suppress keys without key', function() { - var kbd = new Keyboard(document, {}); - var evt = keyevent('keydown', {code: 'KeyA', keyCode: 0x41}); + const kbd = new Keyboard(document, {}); + const evt = keyevent('keydown', {code: 'KeyA', keyCode: 0x41}); kbd._handleKeyDown(evt); expect(evt.preventDefault).to.not.have.been.called; }); it('should suppress the following keypress event', function() { - var kbd = new Keyboard(document, {}); - var evt1 = keyevent('keydown', {code: 'KeyA', keyCode: 0x41}); + const kbd = new Keyboard(document, {}); + const evt1 = keyevent('keydown', {code: 'KeyA', keyCode: 0x41}); kbd._handleKeyDown(evt1); - var evt2 = keyevent('keypress', {code: 'KeyA', charCode: 0x41}); + const evt2 = keyevent('keypress', {code: 'KeyA', charCode: 0x41}); kbd._handleKeyPress(evt2); expect(evt2.preventDefault).to.have.been.called; }); @@ -159,8 +159,8 @@ describe('Key Event Handling', function() { describe('Fake keyup', function() { it('should fake keyup events for virtual keyboards', function(done) { if (browser.isIE() || browser.isEdge()) this.skip(); - var count = 0; - var kbd = new Keyboard(document); + let count = 0; + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { switch (count++) { case 0: @@ -179,7 +179,7 @@ describe('Key Event Handling', function() { }); describe('iOS', function() { - var origNavigator; + let origNavigator; beforeEach(function () { // window.navigator is a protected read-only property in many // environments, so we need to redefine it whilst running these @@ -206,8 +206,8 @@ describe('Key Event Handling', function() { it('should fake keyup events on iOS', function(done) { if (browser.isIE() || browser.isEdge()) this.skip(); - var count = 0; - var kbd = new Keyboard(document); + let count = 0; + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { switch (count++) { case 0: @@ -232,7 +232,7 @@ describe('Key Event Handling', function() { if (browser.isIE() || browser.isEdge()) this.skip(); }); it('should send release using the same keysym as the press', function(done) { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('KeyA'); @@ -244,8 +244,8 @@ describe('Key Event Handling', function() { kbd._handleKeyUp(keyevent('keyup', {code: 'KeyA', key: 'b'})); }); it('should send the same keysym for multiple presses', function() { - var count = 0; - var kbd = new Keyboard(document); + let count = 0; + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('KeyA'); @@ -257,7 +257,7 @@ describe('Key Event Handling', function() { expect(count).to.be.equal(2); }); it('should do nothing on keyup events if no keys are down', function() { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyUp(keyevent('keyup', {code: 'KeyA', key: 'a'})); expect(kbd.onkeyevent).to.not.have.been.called; @@ -265,7 +265,7 @@ describe('Key Event Handling', function() { describe('Legacy Events', function() { it('should track keys using keyCode if no code', function(done) { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('Platform65'); @@ -277,7 +277,7 @@ describe('Key Event Handling', function() { kbd._handleKeyUp(keyevent('keyup', {keyCode: 65, key: 'b'})); }); it('should ignore compositing code', function() { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('Unidentified'); @@ -285,7 +285,7 @@ describe('Key Event Handling', function() { kbd._handleKeyDown(keyevent('keydown', {keyCode: 229, key: 'a'})); }); it('should track keys using keyIdentifier if no code', function(done) { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0x61); expect(code).to.be.equal('Platform65'); @@ -300,7 +300,7 @@ describe('Key Event Handling', function() { }); describe('Shuffle modifiers on macOS', function() { - var origNavigator; + let origNavigator; beforeEach(function () { // window.navigator is a protected read-only property in many // environments, so we need to redefine it whilst running these @@ -326,8 +326,8 @@ describe('Key Event Handling', function() { }); it('should change Alt to AltGraph', function() { - var count = 0; - var kbd = new Keyboard(document); + let count = 0; + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { switch (count++) { case 0: @@ -345,7 +345,7 @@ describe('Key Event Handling', function() { expect(count).to.be.equal(2); }); it('should change left Super to Alt', function(done) { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0xFFE9); expect(code).to.be.equal('MetaLeft'); @@ -354,7 +354,7 @@ describe('Key Event Handling', function() { kbd._handleKeyDown(keyevent('keydown', {code: 'MetaLeft', key: 'Meta', location: 1})); }); it('should change right Super to left Super', function(done) { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = function(keysym, code, down) { expect(keysym).to.be.equal(0xFFEB); expect(code).to.be.equal('MetaRight'); @@ -365,7 +365,7 @@ describe('Key Event Handling', function() { }); describe('Escape AltGraph on Windows', function() { - var origNavigator; + let origNavigator; beforeEach(function () { // window.navigator is a protected read-only property in many // environments, so we need to redefine it whilst running these @@ -394,14 +394,14 @@ describe('Key Event Handling', function() { }); it('should supress ControlLeft until it knows if it is AltGr', function () { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); expect(kbd.onkeyevent).to.not.have.been.called; }); it('should not trigger on repeating ControlLeft', function () { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); @@ -411,7 +411,7 @@ describe('Key Event Handling', function() { }); it('should not supress ControlRight', function () { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlRight', key: 'Control', location: 2})); expect(kbd.onkeyevent).to.have.been.calledOnce; @@ -419,7 +419,7 @@ describe('Key Event Handling', function() { }); it('should release ControlLeft after 100 ms', function () { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); expect(kbd.onkeyevent).to.not.have.been.called; @@ -429,7 +429,7 @@ describe('Key Event Handling', function() { }); it('should release ControlLeft on other key press', function () { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); expect(kbd.onkeyevent).to.not.have.been.called; @@ -445,7 +445,7 @@ describe('Key Event Handling', function() { }); it('should release ControlLeft on other key release', function () { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'KeyA', key: 'a'})); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1})); @@ -463,7 +463,7 @@ describe('Key Event Handling', function() { }); it('should generate AltGraph for quick Ctrl+Alt sequence', function () { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1, timeStamp: Date.now()})); this.clock.tick(20); @@ -478,7 +478,7 @@ describe('Key Event Handling', function() { }); it('should generate Ctrl, Alt for slow Ctrl+Alt sequence', function () { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'ControlLeft', key: 'Control', location: 1, timeStamp: Date.now()})); this.clock.tick(60); @@ -494,7 +494,7 @@ describe('Key Event Handling', function() { }); it('should pass through single Alt', function () { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'Alt', location: 2})); expect(kbd.onkeyevent).to.have.been.calledOnce; @@ -502,7 +502,7 @@ describe('Key Event Handling', function() { }); it('should pass through single AltGr', function () { - var kbd = new Keyboard(document); + const kbd = new Keyboard(document); kbd.onkeyevent = sinon.spy(); kbd._handleKeyDown(keyevent('keydown', {code: 'AltRight', key: 'AltGraph', location: 2})); expect(kbd.onkeyevent).to.have.been.calledOnce; diff --git a/tests/test.localization.js b/tests/test.localization.js index adb29db..7ea11d6 100644 --- a/tests/test.localization.js +++ b/tests/test.localization.js @@ -1,12 +1,11 @@ -var expect = chai.expect; - +const expect = chai.expect; import { l10n } from '../app/localization.js'; describe('Localization', function() { "use strict"; describe('language selection', function () { - var origNavigator; + let origNavigator; beforeEach(function () { // window.navigator is a protected read-only property in many // environments, so we need to redefine it whilst running these diff --git a/tests/test.mouse.js b/tests/test.mouse.js index d25913c..58200a4 100644 --- a/tests/test.mouse.js +++ b/tests/test.mouse.js @@ -1,4 +1,4 @@ -var expect = chai.expect; +const expect = chai.expect; import sinon from '../vendor/sinon.js'; @@ -14,24 +14,24 @@ describe('Mouse Event Handling', function() { // located at coordinates 10x10 sinon.stub(Element.prototype, 'getBoundingClientRect').returns( {left: 10, right: 110, top: 10, bottom: 110, width: 100, height: 100}); - var target = document.createElement('canvas'); + const target = document.createElement('canvas'); // The real constructors might not work everywhere we // want to run these tests - var mouseevent, touchevent; - mouseevent = touchevent = function(typeArg, MouseEventInit) { - var e = { type: typeArg }; - for (var key in MouseEventInit) { + const mouseevent = function(typeArg, MouseEventInit) { + const e = { type: typeArg }; + for (let key in MouseEventInit) { e[key] = MouseEventInit[key]; } e.stopPropagation = sinon.spy(); e.preventDefault = sinon.spy(); return e; }; + const touchevent = mouseevent; describe('Decode Mouse Events', function() { it('should decode mousedown events', function(done) { - var mouse = new Mouse(target); + const mouse = new Mouse(target); mouse.onmousebutton = function(x, y, down, bmask) { expect(bmask).to.be.equal(0x01); expect(down).to.be.equal(1); @@ -40,8 +40,8 @@ describe('Mouse Event Handling', function() { mouse._handleMouseDown(mouseevent('mousedown', { button: '0x01' })); }); it('should decode mouseup events', function(done) { - var calls = 0; - var mouse = new Mouse(target); + let calls = 0; + const mouse = new Mouse(target); mouse.onmousebutton = function(x, y, down, bmask) { expect(bmask).to.be.equal(0x01); if (calls++ === 1) { @@ -53,7 +53,7 @@ describe('Mouse Event Handling', function() { mouse._handleMouseUp(mouseevent('mouseup', { button: '0x01' })); }); it('should decode mousemove events', function(done) { - var mouse = new Mouse(target); + const mouse = new Mouse(target); mouse.onmousemove = function(x, y) { // Note that target relative coordinates are sent expect(x).to.be.equal(40); @@ -64,8 +64,8 @@ describe('Mouse Event Handling', function() { { clientX: 50, clientY: 20 })); }); it('should decode mousewheel events', function(done) { - var calls = 0; - var mouse = new Mouse(target); + let calls = 0; + const mouse = new Mouse(target); mouse.onmousebutton = function(x, y, down, bmask) { calls++; expect(bmask).to.be.equal(1<<6); @@ -88,8 +88,8 @@ describe('Mouse Event Handling', function() { afterEach(function () { this.clock.restore(); }); it('should use same pos for 2nd tap if close enough', function(done) { - var calls = 0; - var mouse = new Mouse(target); + let calls = 0; + const mouse = new Mouse(target); mouse.onmousebutton = function(x, y, down, bmask) { calls++; if (calls === 1) { @@ -119,8 +119,8 @@ describe('Mouse Event Handling', function() { }); it('should not modify 2nd tap pos if far apart', function(done) { - var calls = 0; - var mouse = new Mouse(target); + let calls = 0; + const mouse = new Mouse(target); mouse.onmousebutton = function(x, y, down, bmask) { calls++; if (calls === 1) { @@ -148,8 +148,8 @@ describe('Mouse Event Handling', function() { }); it('should not modify 2nd tap pos if not soon enough', function(done) { - var calls = 0; - var mouse = new Mouse(target); + let calls = 0; + const mouse = new Mouse(target); mouse.onmousebutton = function(x, y, down, bmask) { calls++; if (calls === 1) { @@ -177,8 +177,8 @@ describe('Mouse Event Handling', function() { }); it('should not modify 2nd tap pos if not touch', function(done) { - var calls = 0; - var mouse = new Mouse(target); + let calls = 0; + const mouse = new Mouse(target); mouse.onmousebutton = function(x, y, down, bmask) { calls++; if (calls === 1) { @@ -213,7 +213,7 @@ describe('Mouse Event Handling', function() { afterEach(function () { this.clock.restore(); }); it('should accumulate wheel events if small enough', function () { - var mouse = new Mouse(target); + const mouse = new Mouse(target); mouse.onmousebutton = sinon.spy(); mouse._handleMouseWheel(mouseevent( @@ -246,7 +246,7 @@ describe('Mouse Event Handling', function() { }); it('should not accumulate large wheel events', function () { - var mouse = new Mouse(target); + const mouse = new Mouse(target); mouse.onmousebutton = sinon.spy(); mouse._handleMouseWheel(mouseevent( @@ -265,7 +265,7 @@ describe('Mouse Event Handling', function() { }); it('should send even small wheel events after a timeout', function () { - var mouse = new Mouse(target); + const mouse = new Mouse(target); mouse.onmousebutton = sinon.spy(); mouse._handleMouseWheel(mouseevent( @@ -277,7 +277,7 @@ describe('Mouse Event Handling', function() { }); it('should account for non-zero deltaMode', function () { - var mouse = new Mouse(target); + const mouse = new Mouse(target); mouse.onmousebutton = sinon.spy(); mouse._handleMouseWheel(mouseevent( diff --git a/tests/test.rfb.js b/tests/test.rfb.js index eaf1366..21cfc35 100644 --- a/tests/test.rfb.js +++ b/tests/test.rfb.js @@ -1,4 +1,4 @@ -var expect = chai.expect; +const expect = chai.expect; import RFB from '../core/rfb.js'; import Websock from '../core/websock.js'; @@ -13,7 +13,7 @@ import sinon from '../vendor/sinon.js'; function UIEvent ( event, params ) { params = params || { bubbles: false, cancelable: false, view: window, detail: undefined }; - var evt = document.createEvent( 'UIEvent' ); + const evt = document.createEvent( 'UIEvent' ); evt.initUIEvent( event, params.bubbles, params.cancelable, params.view, params.detail ); return evt; } @@ -23,18 +23,18 @@ import sinon from '../vendor/sinon.js'; window.UIEvent = UIEvent; })(); -var push8 = function (arr, num) { +const push8 = function (arr, num) { "use strict"; arr.push(num & 0xFF); }; -var push16 = function (arr, num) { +const push16 = function (arr, num) { "use strict"; arr.push((num >> 8) & 0xFF, num & 0xFF); }; -var push32 = function (arr, num) { +const push32 = function (arr, num) { "use strict"; arr.push((num >> 24) & 0xFF, (num >> 16) & 0xFF, @@ -43,8 +43,8 @@ var push32 = function (arr, num) { }; describe('Remote Frame Buffer Protocol Client', function() { - var clock; - var raf; + let clock; + let raf; before(FakeWebSocket.replace); after(FakeWebSocket.restore); @@ -56,9 +56,9 @@ describe('Remote Frame Buffer Protocol Client', function() { window.requestAnimationFrame = setTimeout; // Use a single set of buffers instead of reallocating to // speed up tests - var sock = new Websock(); - var _sQ = new Uint8Array(sock._sQbufferSize); - var rQ = new Uint8Array(sock._rQbufferSize); + const sock = new Websock(); + const _sQ = new Uint8Array(sock._sQbufferSize); + const rQ = new Uint8Array(sock._rQbufferSize); Websock.prototype._old_allocate_buffers = Websock.prototype._allocate_buffers; Websock.prototype._allocate_buffers = function () { @@ -74,8 +74,8 @@ describe('Remote Frame Buffer Protocol Client', function() { window.requestAnimationFrame = raf; }); - var container; - var rfbs; + let container; + let rfbs; beforeEach(function () { // Create a container element for all RFB objects to attach to @@ -102,7 +102,7 @@ describe('Remote Frame Buffer Protocol Client', function() { function make_rfb (url, options) { url = url || 'wss://host:8675'; - var rfb = new RFB(container, url, options); + const rfb = new RFB(container, url, options); clock.tick(); rfb._sock._websocket._open(); rfb._rfb_connection_state = 'connected'; @@ -114,14 +114,14 @@ describe('Remote Frame Buffer Protocol Client', function() { describe('Connecting/Disconnecting', function () { describe('#RFB', function () { it('should set the current state to "connecting"', function () { - var client = new RFB(document.createElement('div'), 'wss://host:8675'); + const client = new RFB(document.createElement('div'), 'wss://host:8675'); client._rfb_connection_state = ''; this.clock.tick(); expect(client._rfb_connection_state).to.equal('connecting'); }); it('should actually connect to the websocket', function () { - var client = new RFB(document.createElement('div'), 'ws://HOST:8675/PATH'); + const client = new RFB(document.createElement('div'), 'ws://HOST:8675/PATH'); sinon.spy(client._sock, 'open'); this.clock.tick(); expect(client._sock.open).to.have.been.calledOnce; @@ -130,7 +130,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('#disconnect', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); }); @@ -166,7 +166,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('#sendCredentials', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); client._rfb_connection_state = 'connecting'; @@ -187,14 +187,14 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('Public API Basic Behavior', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); }); describe('#sendCtrlAlDel', function () { it('should sent ctrl[down]-alt[down]-del[down] then del[up]-alt[up]-ctrl[up]', function () { - var expected = {_sQ: new Uint8Array(48), _sQlen: 0, flush: function () {}}; + const expected = {_sQ: new Uint8Array(48), _sQlen: 0, flush: function () {}}; RFB.messages.keyEvent(expected, 0xFFE3, 1); RFB.messages.keyEvent(expected, 0xFFE9, 1); RFB.messages.keyEvent(expected, 0xFFFF, 1); @@ -223,14 +223,14 @@ describe('Remote Frame Buffer Protocol Client', function() { describe('#sendKey', function () { it('should send a single key with the given code and state (down = true)', function () { - var expected = {_sQ: new Uint8Array(8), _sQlen: 0, flush: function () {}}; + const expected = {_sQ: new Uint8Array(8), _sQlen: 0, flush: function () {}}; RFB.messages.keyEvent(expected, 123, 1); client.sendKey(123, 'Key123', true); expect(client._sock).to.have.sent(expected._sQ); }); it('should send both a down and up event if the state is not specified', function () { - var expected = {_sQ: new Uint8Array(16), _sQlen: 0, flush: function () {}}; + const expected = {_sQ: new Uint8Array(16), _sQlen: 0, flush: function () {}}; RFB.messages.keyEvent(expected, 123, 1); RFB.messages.keyEvent(expected, 123, 0); client.sendKey(123, 'Key123'); @@ -253,7 +253,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should send QEMU extended events if supported', function () { client._qemuExtKeyEventSupported = true; - var expected = {_sQ: new Uint8Array(12), _sQlen: 0, flush: function () {}}; + const expected = {_sQ: new Uint8Array(12), _sQlen: 0, flush: function () {}}; RFB.messages.QEMUExtendedKeyEvent(expected, 0x20, true, 0x0039); client.sendKey(0x20, 'Space', true); expect(client._sock).to.have.sent(expected._sQ); @@ -261,7 +261,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should not send QEMU extended events if unknown key code', function () { client._qemuExtKeyEventSupported = true; - var expected = {_sQ: new Uint8Array(8), _sQlen: 0, flush: function () {}}; + const expected = {_sQ: new Uint8Array(8), _sQlen: 0, flush: function () {}}; RFB.messages.keyEvent(expected, 123, 1); client.sendKey(123, 'FooBar', true); expect(client._sock).to.have.sent(expected._sQ); @@ -286,7 +286,7 @@ describe('Remote Frame Buffer Protocol Client', function() { describe('#clipboardPasteFrom', function () { it('should send the given text in a paste event', function () { - var expected = {_sQ: new Uint8Array(11), _sQlen: 0, + const expected = {_sQ: new Uint8Array(11), _sQlen: 0, _sQbufferSize: 11, flush: function () {}}; RFB.messages.clientCutText(expected, 'abc'); client.clipboardPasteFrom('abc'); @@ -340,7 +340,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('Clipping', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); container.style.width = '70px'; @@ -349,7 +349,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should update display clip state when changing the property', function () { - var spy = sinon.spy(client._display, "clipViewport", ["set"]); + const spy = sinon.spy(client._display, "clipViewport", ["set"]); client.clipViewport = false; expect(spy.set).to.have.been.calledOnce; @@ -366,7 +366,7 @@ describe('Remote Frame Buffer Protocol Client', function() { container.style.width = '40px'; container.style.height = '50px'; - var event = new UIEvent('resize'); + const event = new UIEvent('resize'); window.dispatchEvent(event); clock.tick(); @@ -376,7 +376,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should update the viewport when the remote session resizes', function () { // Simple ExtendedDesktopSize FBU message - var incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xcc, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, @@ -398,7 +398,7 @@ describe('Remote Frame Buffer Protocol Client', function() { container.style.width = '40px'; container.style.height = '50px'; - var event = new UIEvent('resize'); + const event = new UIEvent('resize'); window.dispatchEvent(event); clock.tick(); @@ -411,7 +411,7 @@ describe('Remote Frame Buffer Protocol Client', function() { container.style.width = '40px'; container.style.height = '50px'; - var event = new UIEvent('resize'); + const event = new UIEvent('resize'); window.dispatchEvent(event); clock.tick(); @@ -513,7 +513,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('Scaling', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); container.style.width = '70px'; @@ -522,7 +522,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should update display scale factor when changing the property', function () { - var spy = sinon.spy(client._display, "scale", ["set"]); + const spy = sinon.spy(client._display, "scale", ["set"]); sinon.spy(client._display, "autoscale"); client.scaleViewport = false; @@ -538,7 +538,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should update the clipping setting when changing the property', function () { client.clipViewport = true; - var spy = sinon.spy(client._display, "clipViewport", ["set"]); + const spy = sinon.spy(client._display, "clipViewport", ["set"]); client.scaleViewport = false; expect(spy.set).to.have.been.calledOnce; @@ -556,7 +556,7 @@ describe('Remote Frame Buffer Protocol Client', function() { container.style.width = '40px'; container.style.height = '50px'; - var event = new UIEvent('resize'); + const event = new UIEvent('resize'); window.dispatchEvent(event); clock.tick(); @@ -566,7 +566,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should update the scaling when the remote session resizes', function () { // Simple ExtendedDesktopSize FBU message - var incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0xfe, 0xcc, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, @@ -587,7 +587,7 @@ describe('Remote Frame Buffer Protocol Client', function() { container.style.width = '40px'; container.style.height = '50px'; - var event = new UIEvent('resize'); + const event = new UIEvent('resize'); window.dispatchEvent(event); clock.tick(); @@ -596,7 +596,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('Remote resize', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); client._supportsSetDesktopSize = true; @@ -619,7 +619,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should request a resize when initially connecting', function () { // Simple ExtendedDesktopSize FBU message - var incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, 0xff, 0xff, 0xfe, 0xcc, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, @@ -646,7 +646,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should request a resize when the container resizes', function () { container.style.width = '40px'; container.style.height = '50px'; - var event = new UIEvent('resize'); + const event = new UIEvent('resize'); window.dispatchEvent(event); clock.tick(1000); @@ -657,7 +657,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should not resize until the container size is stable', function () { container.style.width = '20px'; container.style.height = '30px'; - var event1 = new UIEvent('resize'); + const event1 = new UIEvent('resize'); window.dispatchEvent(event1); clock.tick(400); @@ -665,7 +665,7 @@ describe('Remote Frame Buffer Protocol Client', function() { container.style.width = '40px'; container.style.height = '50px'; - var event2 = new UIEvent('resize'); + const event2 = new UIEvent('resize'); window.dispatchEvent(event2); clock.tick(400); @@ -682,7 +682,7 @@ describe('Remote Frame Buffer Protocol Client', function() { container.style.width = '40px'; container.style.height = '50px'; - var event = new UIEvent('resize'); + const event = new UIEvent('resize'); window.dispatchEvent(event); clock.tick(1000); @@ -694,7 +694,7 @@ describe('Remote Frame Buffer Protocol Client', function() { container.style.width = '40px'; container.style.height = '50px'; - var event = new UIEvent('resize'); + const event = new UIEvent('resize'); window.dispatchEvent(event); clock.tick(1000); @@ -706,7 +706,7 @@ describe('Remote Frame Buffer Protocol Client', function() { container.style.width = '40px'; container.style.height = '50px'; - var event = new UIEvent('resize'); + const event = new UIEvent('resize'); window.dispatchEvent(event); clock.tick(1000); @@ -715,7 +715,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should not try to override a server resize', function () { // Simple ExtendedDesktopSize FBU message - var incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + const incoming = [ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, 0xff, 0xff, 0xfe, 0xcc, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, @@ -729,13 +729,13 @@ describe('Remote Frame Buffer Protocol Client', function() { describe('Misc Internals', function () { describe('#_updateConnectionState', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); }); it('should clear the disconnect timer if the state is not "disconnecting"', function () { - var spy = sinon.spy(); + const spy = sinon.spy(); client._disconnTimer = setTimeout(spy, 50); client._rfb_connection_state = 'connecting'; client._updateConnectionState('connected'); @@ -758,7 +758,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should ignore state changes to the same state', function () { - var connectSpy = sinon.spy(); + const connectSpy = sinon.spy(); client.addEventListener("connect", connectSpy); expect(client._rfb_connection_state).to.equal('connected'); @@ -767,7 +767,7 @@ describe('Remote Frame Buffer Protocol Client', function() { client.disconnect(); - var disconnectSpy = sinon.spy(); + const disconnectSpy = sinon.spy(); client.addEventListener("disconnect", disconnectSpy); expect(client._rfb_connection_state).to.equal('disconnected'); @@ -776,7 +776,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should ignore illegal state changes', function () { - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("disconnect", spy); client._updateConnectionState('disconnected'); expect(client._rfb_connection_state).to.not.equal('disconnected'); @@ -785,7 +785,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('#_fail', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); }); @@ -813,7 +813,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should result in disconnect event with clean set to false', function () { client._rfb_connection_state = 'connected'; - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("disconnect", spy); client._fail(); this.clock.tick(2000); @@ -827,7 +827,7 @@ describe('Remote Frame Buffer Protocol Client', function() { describe('Connection States', function () { describe('connecting', function () { it('should open the websocket connection', function () { - var client = new RFB(document.createElement('div'), + const client = new RFB(document.createElement('div'), 'ws://HOST:8675/PATH'); sinon.spy(client._sock, 'open'); this.clock.tick(); @@ -836,13 +836,13 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('connected', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); }); it('should result in a connect event if state becomes connected', function () { - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("connect", spy); client._rfb_connection_state = 'connecting'; client._updateConnectionState('connected'); @@ -850,7 +850,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should not result in a connect event if the state is not "connected"', function () { - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("connect", spy); client._sock._websocket.open = function () {}; // explicitly don't call onopen client._updateConnectionState('connecting'); @@ -859,7 +859,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('disconnecting', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); }); @@ -889,7 +889,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should not result in a disconnect event', function () { - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("disconnect", spy); client._sock._websocket.close = function () {}; // explicitly don't call onclose client._updateConnectionState('disconnecting'); @@ -898,13 +898,13 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('disconnected', function () { - var client; + let client; beforeEach(function () { client = new RFB(document.createElement('div'), 'ws://HOST:8675/PATH'); }); it('should result in a disconnect event if state becomes "disconnected"', function () { - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("disconnect", spy); client._rfb_connection_state = 'disconnecting'; client._updateConnectionState('disconnected'); @@ -913,7 +913,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should result in a disconnect event without msg when no reason given', function () { - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("disconnect", spy); client._rfb_connection_state = 'disconnecting'; client._rfb_disconnect_reason = ""; @@ -925,7 +925,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('Protocol Initialization States', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); client._rfb_connection_state = 'connecting'; @@ -933,8 +933,8 @@ describe('Remote Frame Buffer Protocol Client', function() { describe('ProtocolVersion', function () { function send_ver (ver, client) { - var arr = new Uint8Array(12); - for (var i = 0; i < ver.length; i++) { + const arr = new Uint8Array(12); + for (let i = 0; i < ver.length; i++) { arr[i+4] = ver.charCodeAt(i); } arr[0] = 'R'; arr[1] = 'F'; arr[2] = 'B'; arr[3] = ' '; @@ -993,9 +993,9 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should send back the interpreted version', function () { send_ver('004.000', client); - var expected_str = 'RFB 003.008\n'; - var expected = []; - for (var i = 0; i < expected_str.length; i++) { + const expected_str = 'RFB 003.008\n'; + const expected = []; + for (let i = 0; i < expected_str.length; i++) { expected[i] = expected_str.charCodeAt(i); } @@ -1017,7 +1017,7 @@ describe('Remote Frame Buffer Protocol Client', function() { send_ver('000.000', client); expect(client._rfb_version).to.equal(0); - var sent_data = client._sock._websocket._get_sent_data(); + const sent_data = client._sock._websocket._get_sent_data(); expect(new Uint8Array(sent_data.buffer, 0, 9)).to.array.equal(new Uint8Array([73, 68, 58, 49, 50, 51, 52, 53, 0])); expect(sent_data).to.have.length(250); }); @@ -1037,8 +1037,8 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should simply receive the auth scheme when for versions < 3.7', function () { client._rfb_version = 3.6; - var auth_scheme_raw = [1, 2, 3, 4]; - var auth_scheme = (auth_scheme_raw[0] << 24) + (auth_scheme_raw[1] << 16) + + const auth_scheme_raw = [1, 2, 3, 4]; + const auth_scheme = (auth_scheme_raw[0] << 24) + (auth_scheme_raw[1] << 16) + (auth_scheme_raw[2] << 8) + auth_scheme_raw[3]; client._sock._websocket._receive_data(auth_scheme_raw); expect(client._rfb_auth_scheme).to.equal(auth_scheme); @@ -1046,7 +1046,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should prefer no authentication is possible', function () { client._rfb_version = 3.7; - var auth_schemes = [2, 1, 3]; + const auth_schemes = [2, 1, 3]; client._sock._websocket._receive_data(auth_schemes); expect(client._rfb_auth_scheme).to.equal(1); expect(client._sock).to.have.sent(new Uint8Array([1, 1])); @@ -1054,7 +1054,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should choose for the most prefered scheme possible for versions >= 3.7', function () { client._rfb_version = 3.7; - var auth_schemes = [2, 22, 16]; + const auth_schemes = [2, 22, 16]; client._sock._websocket._receive_data(auth_schemes); expect(client._rfb_auth_scheme).to.equal(22); expect(client._sock).to.have.sent(new Uint8Array([22])); @@ -1063,14 +1063,14 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should fail if there are no supported schemes for versions >= 3.7', function () { sinon.spy(client, "_fail"); client._rfb_version = 3.7; - var auth_schemes = [1, 32]; + const auth_schemes = [1, 32]; client._sock._websocket._receive_data(auth_schemes); expect(client._fail).to.have.been.calledOnce; }); it('should fail with the appropriate message if no types are sent for versions >= 3.7', function () { client._rfb_version = 3.7; - var failure_data = [0, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; + const failure_data = [0, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; sinon.spy(client, '_fail'); client._sock._websocket._receive_data(failure_data); @@ -1081,7 +1081,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should transition to the Authentication state and continue on successful negotiation', function () { client._rfb_version = 3.7; - var auth_schemes = [1, 1]; + const auth_schemes = [1, 1]; client._negotiate_authentication = sinon.spy(); client._sock._websocket._receive_data(auth_schemes); expect(client._rfb_init_state).to.equal('Authentication'); @@ -1100,11 +1100,11 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should fail on auth scheme 0 (pre 3.7) with the given message', function () { client._rfb_version = 3.6; - var err_msg = "Whoopsies"; - var data = [0, 0, 0, 0]; - var err_len = err_msg.length; + const err_msg = "Whoopsies"; + const data = [0, 0, 0, 0]; + const err_len = err_msg.length; push32(data, err_len); - for (var i = 0; i < err_len; i++) { + for (let i = 0; i < err_len; i++) { data.push(err_msg.charCodeAt(i)); } @@ -1140,12 +1140,12 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should fire the credentialsrequired event if missing a password', function () { - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("credentialsrequired", spy); send_security(2, client); - var challenge = []; - for (var i = 0; i < 16; i++) { challenge[i] = i; } + const challenge = []; + for (let i = 0; i < 16; i++) { challenge[i] = i; } client._sock._websocket._receive_data(new Uint8Array(challenge)); expect(client._rfb_credentials).to.be.empty; @@ -1158,11 +1158,11 @@ describe('Remote Frame Buffer Protocol Client', function() { send_security(2, client); client._sock._websocket._get_sent_data(); // skip the choice of auth reply - var challenge = []; - for (var i = 0; i < 16; i++) { challenge[i] = i; } + const challenge = []; + for (let i = 0; i < 16; i++) { challenge[i] = i; } client._sock._websocket._receive_data(new Uint8Array(challenge)); - var des_pass = RFB.genDES('passwd', challenge); + const des_pass = RFB.genDES('passwd', challenge); expect(client._sock).to.have.sent(new Uint8Array(des_pass)); }); @@ -1170,8 +1170,8 @@ describe('Remote Frame Buffer Protocol Client', function() { client._rfb_credentials = { password: 'passwd' }; send_security(2, client); - var challenge = []; - for (var i = 0; i < 16; i++) { challenge[i] = i; } + const challenge = []; + for (let i = 0; i < 16; i++) { challenge[i] = i; } client._sock._websocket._receive_data(new Uint8Array(challenge)); expect(client._rfb_init_state).to.equal('SecurityResult'); @@ -1194,7 +1194,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should fire the credentialsrequired event if all credentials are missing', function() { - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("credentialsrequired", spy); client._rfb_credentials = {}; send_security(22, client); @@ -1205,7 +1205,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should fire the credentialsrequired event if some credentials are missing', function() { - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("credentialsrequired", spy); client._rfb_credentials = { username: 'user', target: 'target' }; @@ -1223,8 +1223,8 @@ describe('Remote Frame Buffer Protocol Client', function() { send_security(22, client); - var expected = [22, 4, 6]; // auth selection, len user, len target - for (var i = 0; i < 10; i++) { expected[i+3] = 'usertarget'.charCodeAt(i); } + const expected = [22, 4, 6]; // auth selection, len user, len target + for (let i = 0; i < 10; i++) { expected[i+3] = 'usertarget'.charCodeAt(i); } expect(client._sock).to.have.sent(new Uint8Array(expected)); }); @@ -1239,17 +1239,16 @@ describe('Remote Frame Buffer Protocol Client', function() { }); function send_num_str_pairs(pairs, client) { - var pairs_len = pairs.length; - var data = []; + const pairs_len = pairs.length; + const data = []; push32(data, pairs_len); - for (var i = 0; i < pairs_len; i++) { + for (let i = 0; i < pairs_len; i++) { push32(data, pairs[i][0]); - var j; - for (j = 0; j < 4; j++) { + for (let j = 0; j < 4; j++) { data.push(pairs[i][1].charCodeAt(j)); } - for (j = 0; j < 8; j++) { + for (let j = 0; j < 8; j++) { data.push(pairs[i][2].charCodeAt(j)); } } @@ -1328,7 +1327,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should fail on an error code of 1 with the given message for versions >= 3.8', function () { client._rfb_version = 3.8; sinon.spy(client, '_fail'); - var failure_data = [0, 0, 0, 1, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; + const failure_data = [0, 0, 0, 1, 0, 0, 0, 6, 119, 104, 111, 111, 112, 115]; client._sock._websocket._receive_data(new Uint8Array(failure_data)); expect(client._fail).to.have.been.calledWith( 'Security negotiation failed on security result (reason: whoops)'); @@ -1343,7 +1342,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should result in securityfailure event when receiving a non zero status', function () { - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("securityfailure", spy); client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 2])); expect(spy).to.have.been.calledOnce; @@ -1352,9 +1351,9 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should include reason when provided in securityfailure event', function () { client._rfb_version = 3.8; - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("securityfailure", spy); - var failure_data = [0, 0, 0, 1, 0, 0, 0, 12, 115, 117, 99, 104, + const failure_data = [0, 0, 0, 1, 0, 0, 0, 12, 115, 117, 99, 104, 32, 102, 97, 105, 108, 117, 114, 101]; client._sock._websocket._receive_data(new Uint8Array(failure_data)); expect(spy.args[0][0].detail.status).to.equal(1); @@ -1363,9 +1362,9 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should not include reason when length is zero in securityfailure event', function () { client._rfb_version = 3.9; - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("securityfailure", spy); - var failure_data = [0, 0, 0, 1, 0, 0, 0, 0]; + const failure_data = [0, 0, 0, 1, 0, 0, 0, 0]; client._sock._websocket._receive_data(new Uint8Array(failure_data)); expect(spy.args[0][0].detail.status).to.equal(1); expect('reason' in spy.args[0][0].detail).to.be.false; @@ -1373,7 +1372,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should not include reason in securityfailure event for version < 3.8', function () { client._rfb_version = 3.6; - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("securityfailure", spy); client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 2])); expect(spy.args[0][0].detail.status).to.equal(2); @@ -1383,7 +1382,7 @@ describe('Remote Frame Buffer Protocol Client', function() { describe('ClientInitialisation', function () { it('should transition to the ServerInitialisation state', function () { - var client = make_rfb(); + const client = make_rfb(); client._rfb_connection_state = 'connecting'; client._rfb_init_state = 'SecurityResult'; client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); @@ -1391,7 +1390,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should send 1 if we are in shared mode', function () { - var client = make_rfb('wss://host:8675', { shared: true }); + const client = make_rfb('wss://host:8675', { shared: true }); client._rfb_connection_state = 'connecting'; client._rfb_init_state = 'SecurityResult'; client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); @@ -1399,7 +1398,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should send 0 if we are not in shared mode', function () { - var client = make_rfb('wss://host:8675', { shared: false }); + const client = make_rfb('wss://host:8675', { shared: false }); client._rfb_connection_state = 'connecting'; client._rfb_init_state = 'SecurityResult'; client._sock._websocket._receive_data(new Uint8Array([0, 0, 0, 0])); @@ -1413,13 +1412,13 @@ describe('Remote Frame Buffer Protocol Client', function() { }); function send_server_init(opts, client) { - var full_opts = { width: 10, height: 12, bpp: 24, depth: 24, big_endian: 0, + const full_opts = { width: 10, height: 12, bpp: 24, depth: 24, big_endian: 0, true_color: 1, red_max: 255, green_max: 255, blue_max: 255, red_shift: 16, green_shift: 8, blue_shift: 0, name: 'a name' }; - for (var opt in opts) { + for (let opt in opts) { full_opts[opt] = opts[opt]; } - var data = []; + const data = []; push16(data, full_opts.width); push16(data, full_opts.height); @@ -1443,9 +1442,9 @@ describe('Remote Frame Buffer Protocol Client', function() { client._sock._websocket._receive_data(new Uint8Array(data)); - var name_data = []; + const name_data = []; push32(name_data, full_opts.name.length); - for (var i = 0; i < full_opts.name.length; i++) { + for (let i = 0; i < full_opts.name.length; i++) { name_data.push(full_opts.name.charCodeAt(i)); } client._sock._websocket._receive_data(new Uint8Array(name_data)); @@ -1460,7 +1459,7 @@ describe('Remote Frame Buffer Protocol Client', function() { // NB(sross): we just warn, not fail, for endian-ness and shifts, so we don't test them it('should set the framebuffer name and call the callback', function () { - var spy = sinon.spy(); + const spy = sinon.spy(); client.addEventListener("desktopname", spy); send_server_init({ name: 'some name' }, client); @@ -1475,12 +1474,12 @@ describe('Remote Frame Buffer Protocol Client', function() { client._rfb_tightvnc = true; send_server_init({}, client); - var tight_data = []; + const tight_data = []; push16(tight_data, 1); push16(tight_data, 2); push16(tight_data, 3); push16(tight_data, 0); - for (var i = 0; i < 16 + 32 + 48; i++) { + for (let i = 0; i < 16 + 32 + 48; i++) { tight_data.push(i); } client._sock._websocket._receive_data(tight_data); @@ -1554,7 +1553,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('Protocol Message Processing After Completing Initialization', function () { - var client; + let client; beforeEach(function () { client = make_rfb(); @@ -1564,21 +1563,21 @@ describe('Remote Frame Buffer Protocol Client', function() { }); describe('Framebuffer Update Handling', function () { - var target_data_arr = [ + const target_data_arr = [ 0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0xff, 0x00, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0xee, 0x00, 0xff, 255, 0x00, 0xee, 0xff, 255, 0xaa, 0xee, 0xff, 255, 0xab, 0xee, 0xff, 255, 0xee, 0x00, 0xff, 255, 0x00, 0xee, 0xff, 255, 0xaa, 0xee, 0xff, 255, 0xab, 0xee, 0xff, 255 ]; - var target_data; + let target_data; - var target_data_check_arr = [ + const target_data_check_arr = [ 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255 ]; - var target_data_check; + let target_data_check; before(function () { // NB(directxman12): PhantomJS 1.x doesn't implement Uint8ClampedArray @@ -1587,7 +1586,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); function send_fbu_msg (rect_info, rect_data, client, rect_cnt) { - var data = []; + let data = []; if (!rect_cnt || rect_cnt > -1) { // header @@ -1596,7 +1595,7 @@ describe('Remote Frame Buffer Protocol Client', function() { push16(data, rect_cnt || rect_data.length); } - for (var i = 0; i < rect_data.length; i++) { + for (let i = 0; i < rect_data.length; i++) { if (rect_info[i]) { push16(data, rect_info[i].x); push16(data, rect_info[i].y); @@ -1611,7 +1610,7 @@ describe('Remote Frame Buffer Protocol Client', function() { } it('should send an update request if there is sufficient data', function () { - var expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: function() {}}; + const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: function() {}}; RFB.messages.fbUpdateRequest(expected_msg, true, 0, 0, 640, 20); client._framebufferUpdate = function () { return true; }; @@ -1626,7 +1625,7 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should resume receiving an update if we previously did not have enough data', function () { - var expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: function() {}}; + const expected_msg = {_sQ: new Uint8Array(10), _sQlen: 0, flush: function() {}}; RFB.messages.fbUpdateRequest(expected_msg, true, 0, 0, 640, 20); // just enough to set FBU.rects @@ -1649,7 +1648,7 @@ describe('Remote Frame Buffer Protocol Client', function() { it('should fail on an unsupported encoding', function () { sinon.spy(client, "_fail"); - var rect_info = { x: 8, y: 11, width: 27, height: 32, encoding: 234 }; + const rect_info = { x: 8, y: 11, width: 27, height: 32, encoding: 234 }; send_fbu_msg([rect_info], [[]], client); expect(client._fail).to.have.been.calledOnce; }); @@ -1661,10 +1660,10 @@ describe('Remote Frame Buffer Protocol Client', function() { client._display.resize(4, 4); client._display.blitRgbxImage(0, 0, 4, 2, new Uint8Array(target_data_check_arr.slice(0, 32)), 0); - var info = [{ x: 0, y: 2, width: 2, height: 2, encoding: 0x01}, + const info = [{ x: 0, y: 2, width: 2, height: 2, encoding: 0x01}, { x: 2, y: 2, width: 2, height: 2, encoding: 0x01}]; // data says [{ old_x: 2, old_y: 0 }, { old_x: 0, old_y: 0 }] - var rects = [[0, 2, 0, 0], [0, 0, 0, 0]]; + const rects = [[0, 2, 0, 0], [0, 0, 0, 0]]; send_fbu_msg([info[0]], [rects[0]], client, 2); send_fbu_msg([info[1]], [rects[1]], client, -1); expect(client._display).to.have.displayed(target_data_check); @@ -1680,12 +1679,12 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should handle the RAW encoding', function () { - var info = [{ x: 0, y: 0, width: 2, height: 2, encoding: 0x00 }, + const info = [{ x: 0, y: 0, width: 2, height: 2, encoding: 0x00 }, { x: 2, y: 0, width: 2, height: 2, encoding: 0x00 }, { x: 0, y: 2, width: 4, height: 1, encoding: 0x00 }, { x: 0, y: 3, width: 4, height: 1, encoding: 0x00 }]; // data is in bgrx - var rects = [ + const rects = [ [0x00, 0x00, 0xff, 0, 0x00, 0xff, 0x00, 0, 0x00, 0xff, 0x00, 0, 0x00, 0x00, 0xff, 0], [0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0, 0xff, 0x00, 0x00, 0], [0xff, 0x00, 0xee, 0, 0xff, 0xee, 0x00, 0, 0xff, 0xee, 0xaa, 0, 0xff, 0xee, 0xab, 0], @@ -1695,11 +1694,11 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should handle the RAW encoding in low colour mode', function () { - var info = [{ x: 0, y: 0, width: 2, height: 2, encoding: 0x00 }, + const info = [{ x: 0, y: 0, width: 2, height: 2, encoding: 0x00 }, { x: 2, y: 0, width: 2, height: 2, encoding: 0x00 }, { x: 0, y: 2, width: 4, height: 1, encoding: 0x00 }, { x: 0, y: 3, width: 4, height: 1, encoding: 0x00 }]; - var rects = [ + const rects = [ [0x03, 0x03, 0x03, 0x03], [0x0c, 0x0c, 0x0c, 0x0c], [0x0c, 0x0c, 0x03, 0x03], @@ -1713,10 +1712,10 @@ describe('Remote Frame Buffer Protocol Client', function() { // seed some initial data to copy client._display.blitRgbxImage(0, 0, 4, 2, new Uint8Array(target_data_check_arr.slice(0, 32)), 0); - var info = [{ x: 0, y: 2, width: 2, height: 2, encoding: 0x01}, + const info = [{ x: 0, y: 2, width: 2, height: 2, encoding: 0x01}, { x: 2, y: 2, width: 2, height: 2, encoding: 0x01}]; // data says [{ old_x: 0, old_y: 0 }, { old_x: 0, old_y: 0 }] - var rects = [[0, 2, 0, 0], [0, 0, 0, 0]]; + const rects = [[0, 2, 0, 0], [0, 0, 0, 0]]; send_fbu_msg(info, rects, client); expect(client._display).to.have.displayed(target_data_check); }); @@ -1725,8 +1724,8 @@ describe('Remote Frame Buffer Protocol Client', function() { // TODO(directxman12): test rre_chunk_sz (related to above about subrects)? it('should handle the RRE encoding', function () { - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x02 }]; - var rect = []; + const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x02 }]; + const rect = []; push32(rect, 2); // 2 subrects push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color rect.push(0xff); // becomes ff0000ff --> #0000FF color @@ -1752,8 +1751,8 @@ describe('Remote Frame Buffer Protocol Client', function() { describe('the HEXTILE encoding handler', function () { it('should handle a tile with fg, bg specified, normal subrects', function () { - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - var rect = []; + const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; + const rect = []; rect.push(0x02 | 0x04 | 0x08); // bg spec, fg spec, anysubrects push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color rect.push(0xff); // becomes ff0000ff --> #0000FF fg color @@ -1770,10 +1769,10 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should handle a raw tile', function () { - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - var rect = []; + const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; + const rect = []; rect.push(0x01); // raw - for (var i = 0; i < target_data.length; i += 4) { + for (let i = 0; i < target_data.length; i += 4) { rect.push(target_data[i + 2]); rect.push(target_data[i + 1]); rect.push(target_data[i]); @@ -1784,14 +1783,14 @@ describe('Remote Frame Buffer Protocol Client', function() { }); it('should handle a tile with only bg specified (solid bg)', function () { - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - var rect = []; + const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; + const rect = []; rect.push(0x02); push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color send_fbu_msg(info, [rect], client); - var expected = []; - for (var i = 0; i < 16; i++) { push32(expected, 0xff00ff); } + const expected = []; + for (let i = 0; i < 16; i++) { push32(expected, 0xff00ff); } expect(client._display).to.have.displayed(new Uint8Array(expected)); }); @@ -1800,9 +1799,9 @@ describe('Remote Frame Buffer Protocol Client', function() { client._fb_width = 8; client._display.resize(8, 4); - var info = [{ x: 0, y: 0, width: 32, height: 4, encoding: 0x05 }]; + const info = [{ x: 0, y: 0, width: 32, height: 4, encoding: 0x05 }]; - var rect = []; + const rect = []; // send a bg frame rect.push(0x02); @@ -1813,16 +1812,15 @@ describe('Remote Frame Buffer Protocol Client', function() { send_fbu_msg(info, [rect], client); - var expected = []; - var i; - for (i = 0; i < 16; i++) { push32(expected, 0xff00ff); } // rect 1: solid - for (i = 0; i < 16; i++) { push32(expected, 0xff00ff); } // rect 2: same bkground color + const expected = []; + for (let i = 0; i < 16; i++) { push32(expected, 0xff00ff); } // rect 1: solid + for (let i = 0; i < 16; i++) { push32(expected, 0xff00ff); } // rect 2: same bkground color expect(client._display).to.have.displayed(new Uint8Array(expected)); }); it('should handle a tile with bg and coloured subrects', function () { - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - var rect = []; + const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; + const rect = []; rect.push(0x02 | 0x08 | 0x10); // bg spec, anysubrects, colouredsubrects push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color rect.push(2); // 2 subrects @@ -1847,8 +1845,8 @@ describe('Remote Frame Buffer Protocol Client', function() { client._fb_height = 17; client._display.resize(4, 17); - var info = [{ x: 0, y: 0, width: 4, height: 17, encoding: 0x05}]; - var rect = []; + const info = [{ x: 0, y: 0, width: 4, height: 17, encoding: 0x05}]; + const rect = []; rect.push(0x02 | 0x04 | 0x08); // bg spec, fg spec, anysubrects push32(rect, 0xff00ff); // becomes 00ff00ff --> #00FF00 bg color rect.push(0xff); // becomes ff0000ff --> #0000FF fg color @@ -1856,8 +1854,7 @@ describe('Remote Frame Buffer Protocol Client', function() { rect.push(0x00); rect.push(0xff); rect.push(8); // 8 subrects - var i; - for (i = 0; i < 4; i++) { + for (let i = 0; i < 4; i++) { rect.push((0 << 4) | (i * 4)); // x: 0, y: i*4 rect.push(1 | (1 << 4)); // width: 2, height: 2 rect.push((2 << 4) | (i * 4 + 2)); // x: 2, y: i * 4 + 2 @@ -1869,16 +1866,16 @@ describe('Remote Frame Buffer Protocol Client', function() { rect.push(1 | (1 << 4)); // width: 2, height: 2 send_fbu_msg(info, [rect], client); - var expected = []; - for (i = 0; i < 4; i++) { expected = expected.concat(target_data_check_arr); } + let expected = []; + for (let i = 0; i < 4; i++) { expected = expected.concat(target_data_check_arr); } expected = expected.concat(target_data_check_arr.slice(0, 16)); expect(client._display).to.have.displayed(new Uint8Array(expected)); }); it('should fail on an invalid subencoding', function () { sinon.spy(client,"_fail"); - var info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; - var rects = [[45]]; // an invalid subencoding + const info = [{ x: 0, y: 0, width: 4, height: 4, encoding: 0x05 }]; + const rects = [[45]]; // an invalid subencoding send_fbu_msg(info, rects, client); expect(client._fail).to.have.been.calledOnce; }); @@ -1913,11 +1910,11 @@ describe('Remote Frame Buffer Protocol Client', function() { }); function make_screen_data (nr_of_screens) { - var data = []; + const data = []; push8(data, nr_of_screens); // number-of-screens push8(data, 0); // padding push16(data, 0); // padding - for (var i=0; i no_transform_files.add(file)); // util.promisify requires Node.js 8.x, so we have our own function promisify(original) { return function () { - let obj = this; - let args = Array.prototype.slice.call(arguments); + const obj = this; + const args = Array.prototype.slice.call(arguments); return new Promise((resolve, reject) => { original.apply(obj, args.concat((err, value) => { if (err) return reject(err); @@ -70,10 +70,10 @@ const babelTransformFile = promisify(babel.transformFile); // walkDir *recursively* walks directories trees, // calling the callback for all normal files found. -var walkDir = function (base_path, cb, filter) { +const walkDir = function (base_path, cb, filter) { return readdir(base_path) .then(files => { - let paths = files.map(filename => path.join(base_path, filename)); + const paths = files.map(filename => path.join(base_path, filename)); return Promise.all(paths.map((filepath) => { return lstat(filepath) .then(stats => { @@ -87,20 +87,20 @@ var walkDir = function (base_path, cb, filter) { }); }; -var transform_html = function (legacy_scripts, only_legacy) { +const transform_html = function (legacy_scripts, only_legacy) { // write out the modified vnc.html file that works with the bundle - var src_html_path = path.resolve(__dirname, '..', 'vnc.html'); - var out_html_path = path.resolve(paths.out_dir_base, 'vnc.html'); + const src_html_path = path.resolve(__dirname, '..', 'vnc.html'); + const out_html_path = path.resolve(paths.out_dir_base, 'vnc.html'); return readFile(src_html_path) .then(contents_raw => { - var contents = contents_raw.toString(); + let contents = contents_raw.toString(); - var start_marker = '\n'; - var end_marker = ''; - var start_ind = contents.indexOf(start_marker) + start_marker.length; - var end_ind = contents.indexOf(end_marker, start_ind); + const start_marker = '\n'; + const end_marker = ''; + const start_ind = contents.indexOf(start_marker) + start_marker.length; + const end_ind = contents.indexOf(end_marker, start_ind); - var new_script = ''; + let new_script = ''; if (only_legacy) { // Only legacy version, so include things directly @@ -141,7 +141,7 @@ var transform_html = function (legacy_scripts, only_legacy) { }); } -var make_lib_files = function (import_format, source_maps, with_app_dir, only_legacy) { +const make_lib_files = function (import_format, source_maps, with_app_dir, only_legacy) { if (!import_format) { throw new Error("you must specify an import format to generate compiled noVNC libraries"); } else if (!SUPPORTED_FORMATS.has(import_format)) { @@ -161,8 +161,8 @@ var make_lib_files = function (import_format, source_maps, with_app_dir, only_le only_legacy = true; } - var in_path; - var out_path_base; + let in_path; + let out_path_base; if (with_app_dir) { out_path_base = paths.out_dir_base; in_path = paths.main; @@ -178,7 +178,7 @@ var make_lib_files = function (import_format, source_maps, with_app_dir, only_le const outFiles = []; - var handleDir = (js_only, vendor_rewrite, in_path_base, filename) => Promise.resolve() + const handleDir = (js_only, vendor_rewrite, in_path_base, filename) => Promise.resolve() .then(() => { if (no_copy_files.has(filename)) return; @@ -225,7 +225,8 @@ var make_lib_files = function (import_format, source_maps, with_app_dir, only_le return babelTransformFile(filename, opts) .then(res => { console.log(`Writing ${legacy_path}`); - var {code, map} = res; + const {map} = res; + let {code} = res; if (source_maps === true) { // append URL for external source map code += `\n//# sourceMappingURL=${path.basename(legacy_path)}.map\n`; @@ -249,19 +250,19 @@ var make_lib_files = function (import_format, source_maps, with_app_dir, only_le Promise.resolve() .then(() => { - let handler = handleDir.bind(null, true, false, in_path || paths.main); - let filter = (filename, stats) => !no_copy_files.has(filename); + const handler = handleDir.bind(null, true, false, in_path || paths.main); + const filter = (filename, stats) => !no_copy_files.has(filename); return walkDir(paths.vendor, handler, filter); }) .then(() => { - let handler = handleDir.bind(null, true, !in_path, in_path || paths.core); - let filter = (filename, stats) => !no_copy_files.has(filename); + const handler = handleDir.bind(null, true, !in_path, in_path || paths.core); + const filter = (filename, stats) => !no_copy_files.has(filename); return walkDir(paths.core, handler, filter); }) .then(() => { if (!with_app_dir) return; - let handler = handleDir.bind(null, false, false, in_path); - let filter = (filename, stats) => !no_copy_files.has(filename); + const handler = handleDir.bind(null, false, false, in_path); + const filter = (filename, stats) => !no_copy_files.has(filename); return walkDir(paths.app, handler, filter); }) .then(() => { @@ -275,8 +276,8 @@ var make_lib_files = function (import_format, source_maps, with_app_dir, only_le console.log(`Writing ${out_app_path}`); return helper.appWriter(out_path_base, legacy_path_base, out_app_path) .then(extra_scripts => { - let rel_app_path = path.relative(out_path_base, out_app_path); - let legacy_scripts = extra_scripts.concat([rel_app_path]); + const rel_app_path = path.relative(out_path_base, out_app_path); + const legacy_scripts = extra_scripts.concat([rel_app_path]); transform_html(legacy_scripts, only_legacy); }) .then(() => { @@ -287,7 +288,7 @@ var make_lib_files = function (import_format, source_maps, with_app_dir, only_le .then(() => { // Try to clean up any empty directories if this // was the last file in there - let rmdir_r = dir => { + const rmdir_r = dir => { return rmdir(dir) .then(() => rmdir_r(path.dirname(dir))) .catch(() => { diff --git a/utils/use_require_helpers.js b/utils/use_require_helpers.js index 9bba453..532e8f1 100644 --- a/utils/use_require_helpers.js +++ b/utils/use_require_helpers.js @@ -1,12 +1,12 @@ // writes helpers require for vnc.html (they should output app.js) -var fs = require('fs'); -var path = require('path'); +const fs = require('fs'); +const path = require('path'); // util.promisify requires Node.js 8.x, so we have our own function promisify(original) { return function () { - let obj = this; - let args = Array.prototype.slice.call(arguments); + const obj = this; + const args = Array.prototype.slice.call(arguments); return new Promise((resolve, reject) => { original.apply(obj, args.concat((err, value) => { if (err) return reject(err); @@ -22,12 +22,12 @@ module.exports = { 'amd': { appWriter: (base_out_path, script_base_path, out_path) => { // setup for requirejs - let ui_path = path.relative(base_out_path, + const ui_path = path.relative(base_out_path, path.join(script_base_path, 'app', 'ui')); return writeFile(out_path, `requirejs(["${ui_path}"], function (ui) {});`) .then(() => { console.log(`Please place RequireJS in ${path.join(script_base_path, 'require.js')}`); - let require_path = path.relative(base_out_path, + const require_path = path.relative(base_out_path, path.join(script_base_path, 'require.js')) return [ require_path ]; }); @@ -40,8 +40,8 @@ module.exports = { opts.plugins.unshift("add-module-exports"); }, appWriter: (base_out_path, script_base_path, out_path) => { - var browserify = require('browserify'); - var b = browserify(path.join(script_base_path, 'app/ui.js'), {}); + const browserify = require('browserify'); + const b = browserify(path.join(script_base_path, 'app/ui.js'), {}); return promisify(b.bundle).call(b) .then((buf) => writeFile(out_path, buf)) .then(() => []); @@ -51,15 +51,15 @@ module.exports = { }, 'systemjs': { appWriter: (base_out_path, script_base_path, out_path) => { - let ui_path = path.relative(base_out_path, + const ui_path = path.relative(base_out_path, path.join(script_base_path, 'app', 'ui.js')); return writeFile(out_path, `SystemJS.import("${ui_path}");`) .then(() => { console.log(`Please place SystemJS in ${path.join(script_base_path, 'system-production.js')}`); // FIXME: Should probably be in the legacy directory - let promise_path = path.relative(base_out_path, + const promise_path = path.relative(base_out_path, path.join(base_out_path, 'vendor', 'promise.js')) - let systemjs_path = path.relative(base_out_path, + const systemjs_path = path.relative(base_out_path, path.join(script_base_path, 'system-production.js')) return [ promise_path, systemjs_path ]; }); -- 2.39.2