UNPKG

novnc

Version:
1,019 lines (987 loc) 163 kB
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _int = require("./util/int.js"); var Log = _interopRequireWildcard(require("./util/logging.js")); var _strings = require("./util/strings.js"); var _browser = require("./util/browser.js"); var _element = require("./util/element.js"); var _events = require("./util/events.js"); var _eventtarget = _interopRequireDefault(require("./util/eventtarget.js")); var _display = _interopRequireDefault(require("./display.js")); var _inflator = _interopRequireDefault(require("./inflator.js")); var _deflator = _interopRequireDefault(require("./deflator.js")); var _keyboard = _interopRequireDefault(require("./input/keyboard.js")); var _gesturehandler = _interopRequireDefault(require("./input/gesturehandler.js")); var _cursor = _interopRequireDefault(require("./util/cursor.js")); var _websock = _interopRequireDefault(require("./websock.js")); var _des = _interopRequireDefault(require("./des.js")); var _keysym = _interopRequireDefault(require("./input/keysym.js")); var _xtscancodes = _interopRequireDefault(require("./input/xtscancodes.js")); var _encodings = require("./encodings.js"); var _mousebuttonmapper = require("./mousebuttonmapper.js"); var _raw = _interopRequireDefault(require("./decoders/raw.js")); var _copyrect = _interopRequireDefault(require("./decoders/copyrect.js")); var _rre = _interopRequireDefault(require("./decoders/rre.js")); var _hextile = _interopRequireDefault(require("./decoders/hextile.js")); var _tight = _interopRequireDefault(require("./decoders/tight.js")); var _tightpng = _interopRequireDefault(require("./decoders/tightpng.js")); var _udp = _interopRequireDefault(require("./decoders/udp.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } // How many seconds to wait for a disconnect to finish var DISCONNECT_TIMEOUT = 3; var DEFAULT_BACKGROUND = 'rgb(40, 40, 40)'; var _videoQuality = 2; var _enableWebP = false; var _enableQOI = false; // Minimum wait (ms) between two mouse moves var MOUSE_MOVE_DELAY = 17; // Wheel thresholds var WHEEL_LINE_HEIGHT = 19; // Pixels for one line step (on Windows) // Gesture thresholds var GESTURE_ZOOMSENS = 75; var GESTURE_SCRLSENS = 50; var DOUBLE_TAP_TIMEOUT = 1000; var DOUBLE_TAP_THRESHOLD = 50; // Extended clipboard pseudo-encoding formats var extendedClipboardFormatText = 1; /*eslint-disable no-unused-vars */ var extendedClipboardFormatRtf = 1 << 1; var extendedClipboardFormatHtml = 1 << 2; var extendedClipboardFormatDib = 1 << 3; var extendedClipboardFormatFiles = 1 << 4; /*eslint-enable */ // Extended clipboard pseudo-encoding actions var extendedClipboardActionCaps = 1 << 24; var extendedClipboardActionRequest = 1 << 25; var extendedClipboardActionPeek = 1 << 26; var extendedClipboardActionNotify = 1 << 27; var extendedClipboardActionProvide = 1 << 28; var RFB = /*#__PURE__*/function (_EventTargetMixin) { _inherits(RFB, _EventTargetMixin); var _super = _createSuper(RFB); function RFB(target, touchInput, urlOrChannel, options) { var _this; _classCallCheck(this, RFB); if (!target) { throw new Error("Must specify target"); } if (!urlOrChannel) { throw new Error("Must specify URL, WebSocket or RTCDataChannel"); } _this = _super.call(this); _this._target = target; if (typeof urlOrChannel === "string") { _this._url = urlOrChannel; } else { _this._url = null; _this._rawChannel = urlOrChannel; } // Connection details options = options || {}; _this._rfbCredentials = options.credentials || {}; _this._shared = 'shared' in options ? !!options.shared : true; _this._repeaterID = options.repeaterID || ''; _this._wsProtocols = options.wsProtocols || ['binary']; // Internal state _this._rfbConnectionState = ''; _this._rfbInitState = ''; _this._rfbAuthScheme = -1; _this._rfbCleanDisconnect = true; // Server capabilities _this._rfbVersion = 0; _this._rfbMaxVersion = 3.8; _this._rfbTightVNC = false; _this._rfbVeNCryptState = 0; _this._rfbXvpVer = 0; _this._fbWidth = 0; _this._fbHeight = 0; _this._fbName = ""; _this._capabilities = { power: false }; _this._supportsFence = false; _this._supportsContinuousUpdates = false; _this._enabledContinuousUpdates = false; _this._supportsSetDesktopSize = false; _this._screenID = 0; _this._screenFlags = 0; _this._qemuExtKeyEventSupported = false; // kasm defaults _this._jpegVideoQuality = 5; _this._webpVideoQuality = 5; _this._treatLossless = 7; _this._preferBandwidth = true; _this._dynamicQualityMin = 3; _this._dynamicQualityMax = 9; _this._videoArea = 65; _this._videoTime = 5; _this._videoOutTime = 3; _this._videoScaling = 2; _this._frameRate = 30; _this._maxVideoResolutionX = 960; _this._maxVideoResolutionY = 540; _this._clipboardBinary = true; _this._useUdp = true; _this._enableQOI = false; _this.TransitConnectionStates = { Tcp: Symbol("tcp"), Udp: Symbol("udp"), Upgrading: Symbol("upgrading"), Downgrading: Symbol("downgrading"), Failure: Symbol("failure") }; _this._transitConnectionState = _this.TransitConnectionStates.Tcp; _this._lastTransition = null; _this._udpConnectFailures = 0; //Failures in upgrading connection to udp _this._udpTransitFailures = 0; //Failures in transit after successful upgrade _this._trackFrameStats = false; _this._clipboardText = null; _this._clipboardServerCapabilitiesActions = {}; _this._clipboardServerCapabilitiesFormats = {}; // Internal objects _this._sock = null; // Websock object _this._display = null; // Display object _this._flushing = false; // Display flushing state _this._keyboard = null; // Keyboard input handler object _this._gestures = null; // Gesture input handler object // Timers _this._disconnTimer = null; // disconnection timer _this._resizeTimeout = null; // resize rate limiting _this._mouseMoveTimer = null; // Decoder states _this._decoders = {}; _this._FBU = { rects: 0, // current rect number x: 0, y: 0, width: 0, height: 0, encoding: null, frame_id: 0, rect_total: 0 //Total rects in frame }; // Mouse state _this._mousePos = {}; _this._mouseButtonMask = 0; _this._mouseLastMoveTime = 0; _this._pointerLock = false; _this._pointerLockPos = { x: 0, y: 0 }; _this._pointerRelativeEnabled = false; _this._mouseLastPinchAndZoomTime = 0; _this._viewportDragging = false; _this._viewportDragPos = {}; _this._viewportHasMoved = false; _this._accumulatedWheelDeltaX = 0; _this._accumulatedWheelDeltaY = 0; _this.mouseButtonMapper = null; // Gesture state _this._gestureLastTapTime = null; _this._gestureFirstDoubleTapEv = null; _this._gestureLastMagnitudeX = 0; _this._gestureLastMagnitudeY = 0; // Bound event handlers _this._eventHandlers = { updateHiddenKeyboard: _this._updateHiddenKeyboard.bind(_assertThisInitialized(_this)), focusCanvas: _this._focusCanvas.bind(_assertThisInitialized(_this)), windowResize: _this._windowResize.bind(_assertThisInitialized(_this)), handleMouse: _this._handleMouse.bind(_assertThisInitialized(_this)), handlePointerLockChange: _this._handlePointerLockChange.bind(_assertThisInitialized(_this)), handlePointerLockError: _this._handlePointerLockError.bind(_assertThisInitialized(_this)), handleWheel: _this._handleWheel.bind(_assertThisInitialized(_this)), handleGesture: _this._handleGesture.bind(_assertThisInitialized(_this)) }; // main setup Log.Debug(">> RFB.constructor"); // Create DOM elements _this._screen = document.createElement('div'); _this._screen.style.display = 'flex'; _this._screen.style.width = '100%'; _this._screen.style.height = '100%'; _this._screen.style.overflow = 'auto'; _this._screen.style.background = DEFAULT_BACKGROUND; _this._canvas = document.createElement('canvas'); _this._canvas.style.margin = 'auto'; // Some browsers add an outline on focus _this._canvas.style.outline = 'none'; _this._canvas.width = 0; _this._canvas.height = 0; _this._canvas.tabIndex = -1; _this._canvas.overflow = 'hidden'; _this._screen.appendChild(_this._canvas); // Cursor _this._cursor = new _cursor["default"](); // XXX: TightVNC 2.8.11 sends no cursor at all until Windows changes // it. Result: no cursor at all until a window border or an edit field // is hit blindly. But there are also VNC servers that draw the cursor // in the framebuffer and don't send the empty local cursor. There is // no way to satisfy both sides. // // The spec is unclear on this "initial cursor" issue. Many other // viewers (TigerVNC, RealVNC, Remmina) display an arrow as the // initial cursor instead. _this._cursorImage = RFB.cursors.none; // NB: nothing that needs explicit teardown should be done // before this point, since this can throw an exception try { _this._display = new _display["default"](_this._canvas); } catch (exc) { Log.Error("Display exception: " + exc); throw exc; } _this._display.onflush = _this._onFlush.bind(_assertThisInitialized(_this)); // populate decoder array with objects _this._decoders[_encodings.encodings.encodingRaw] = new _raw["default"](); _this._decoders[_encodings.encodings.encodingCopyRect] = new _copyrect["default"](); _this._decoders[_encodings.encodings.encodingRRE] = new _rre["default"](); _this._decoders[_encodings.encodings.encodingHextile] = new _hextile["default"](); _this._decoders[_encodings.encodings.encodingTight] = new _tight["default"](_this._display); _this._decoders[_encodings.encodings.encodingTightPNG] = new _tightpng["default"](); _this._decoders[_encodings.encodings.encodingUDP] = new _udp["default"](); _this._keyboard = new _keyboard["default"](_this._canvas, touchInput); _this._keyboard.onkeyevent = _this._handleKeyEvent.bind(_assertThisInitialized(_this)); _this._gestures = new _gesturehandler["default"](); _this._sock = new _websock["default"](); _this._sock.on('message', function () { _this._handleMessage(); }); _this._sock.on('open', function () { if (_this._rfbConnectionState === 'connecting' && _this._rfbInitState === '') { _this._rfbInitState = 'ProtocolVersion'; Log.Debug("Starting VNC handshake"); } else { _this._fail("Unexpected server connection while " + _this._rfbConnectionState); } }); _this._sock.on('close', function (e) { Log.Debug("WebSocket on-close event"); var msg = ""; if (e.code) { msg = "(code: " + e.code; if (e.reason) { msg += ", reason: " + e.reason; } msg += ")"; } switch (_this._rfbConnectionState) { case 'connecting': _this._fail("Connection closed " + msg); break; case 'connected': // Handle disconnects that were initiated server-side _this._updateConnectionState('disconnecting'); _this._updateConnectionState('disconnected'); break; case 'disconnecting': // Normal disconnection path _this._updateConnectionState('disconnected'); break; case 'disconnected': _this._fail("Unexpected server disconnect " + "when already disconnected " + msg); break; default: _this._fail("Unexpected server disconnect before connecting " + msg); break; } _this._sock.off('close'); // Delete reference to raw channel to allow cleanup. _this._rawChannel = null; }); _this._sock.on('error', function (e) { return Log.Warn("WebSocket on-error event"); }); // Slight delay of the actual connection so that the caller has // time to set up callbacks setTimeout(_this._updateConnectionState.bind(_assertThisInitialized(_this), 'connecting')); Log.Debug("<< RFB.constructor"); // ===== PROPERTIES ===== _this.dragViewport = false; _this.focusOnClick = true; _this.lastActiveAt = Date.now(); _this._viewOnly = false; _this._clipViewport = false; _this._scaleViewport = false; _this._resizeSession = false; _this._showDotCursor = false; if (options.showDotCursor !== undefined) { Log.Warn("Specifying showDotCursor as a RFB constructor argument is deprecated"); _this._showDotCursor = options.showDotCursor; } _this._qualityLevel = 6; _this._compressionLevel = 2; _this._clipHash = 0; return _this; } // ===== PROPERTIES ===== _createClass(RFB, [{ key: "pointerLock", get: function get() { return this._pointerLock; }, set: function set(value) { if (!this._pointerLock) { if (this._canvas.requestPointerLock) { this._canvas.requestPointerLock(); this._pointerLockChanging = true; } else if (this._canvas.mozRequestPointerLock) { this._canvas.mozRequestPointerLock(); this._pointerLockChanging = true; } } else { if (window.document.exitPointerLock) { window.document.exitPointerLock(); this._pointerLockChanging = true; } else if (window.document.mozExitPointerLock) { window.document.mozExitPointerLock(); this._pointerLockChanging = true; } } } }, { key: "pointerRelative", get: function get() { return this._pointerRelativeEnabled; }, set: function set(value) { this._pointerRelativeEnabled = value; if (value) { var max_w = this._display.scale === 1 ? this._fbWidth : this._fbWidth * this._display.scale; var max_h = this._display.scale === 1 ? this._fbHeight : this._fbHeight * this._display.scale; this._pointerLockPos.x = Math.floor(max_w / 2); this._pointerLockPos.y = Math.floor(max_h / 2); // reset the cursor position to center this._mousePos = { x: this._pointerLockPos.x, y: this._pointerLockPos.y }; this._cursor.move(this._pointerLockPos.x, this._pointerLockPos.y); } } }, { key: "keyboard", get: function get() { return this._keyboard; } }, { key: "clipboardBinary", get: function get() { return this._clipboardMode; }, set: function set(val) { this._clipboardMode = val; } }, { key: "videoQuality", get: function get() { return this._videoQuality; }, set: function set(quality) { //if changing to or from a video quality mode that uses a fixed resolution server side if (this._videoQuality <= 1 || quality <= 1) { this._pendingApplyResolutionChange = true; } this._videoQuality = quality; this._pendingApplyEncodingChanges = true; } }, { key: "preferBandwidth", get: function get() { return this._preferBandwidth; }, set: function set(val) { this._preferBandwidth = val; this._pendingApplyEncodingChanges = true; } }, { key: "viewOnly", get: function get() { return this._viewOnly; }, set: function set(viewOnly) { this._viewOnly = viewOnly; if (this._rfbConnectionState === "connecting" || this._rfbConnectionState === "connected") { if (viewOnly) { this._keyboard.ungrab(); } else { this._keyboard.grab(); } } } }, { key: "capabilities", get: function get() { return this._capabilities; } }, { key: "touchButton", get: function get() { return 0; }, set: function set(button) { Log.Warn("Using old API!"); } }, { key: "clipViewport", get: function get() { return this._clipViewport; }, set: function set(viewport) { this._clipViewport = viewport; this._updateClip(); } }, { key: "scaleViewport", get: function get() { return this._scaleViewport; }, set: function set(scale) { this._scaleViewport = scale; // Scaling trumps clipping, so we may need to adjust // clipping when enabling or disabling scaling if (scale && this._clipViewport) { this._updateClip(); } this._updateScale(); if (!scale && this._clipViewport) { this._updateClip(); } } }, { key: "resizeSession", get: function get() { return this._resizeSession; }, set: function set(resize) { this._resizeSession = resize; if (resize) { this._requestRemoteResize(); this.scaleViewport = true; } } }, { key: "showDotCursor", get: function get() { return this._showDotCursor; }, set: function set(show) { this._showDotCursor = show; this._refreshCursor(); } }, { key: "background", get: function get() { return this._screen.style.background; }, set: function set(cssValue) { this._screen.style.background = cssValue; } }, { key: "enableWebP", get: function get() { return this._enableWebP; }, set: function set(enabled) { if (this._enableWebP === enabled) { return; } this._enableWebP = enabled; this._pendingApplyEncodingChanges = true; } }, { key: "enableQOI", get: function get() { return this._enableQOI; }, set: function set(enabled) { if (this._enableQOI === enabled) { return; } if (enabled) { if (!this._decoders[_encodings.encodings.encodingTight].enableQOI()) { //enabling qoi failed return; } } this._enableQOI = enabled; this._pendingApplyEncodingChanges = true; } }, { key: "antiAliasing", get: function get() { return this._display.antiAliasing; }, set: function set(value) { this._display.antiAliasing = value; } }, { key: "jpegVideoQuality", get: function get() { return this._jpegVideoQuality; }, set: function set(qualityLevel) { if (!Number.isInteger(qualityLevel) || qualityLevel < 0 || qualityLevel > 9) { Log.Error("qualityLevel must be an integer between 0 and 9"); return; } if (this._jpegVideoQuality === qualityLevel) { return; } this._jpegVideoQuality = qualityLevel; this._pendingApplyEncodingChanges = true; } }, { key: "webpVideoQuality", get: function get() { return this._webpVideoQuality; }, set: function set(qualityLevel) { if (!Number.isInteger(qualityLevel) || qualityLevel < 0 || qualityLevel > 9) { Log.Error("qualityLevel must be an integer between 0 and 9"); return; } if (this._webpVideoQuality === qualityLevel) { return; } this._webpVideoQuality = qualityLevel; this._pendingApplyEncodingChanges = true; } }, { key: "treatLossless", get: function get() { return this._treatLossless; }, set: function set(qualityLevel) { if (!Number.isInteger(qualityLevel) || qualityLevel < 0 || qualityLevel > 9) { Log.Error("qualityLevel must be an integer between 0 and 9"); return; } if (this._treatLossless === qualityLevel) { return; } this._treatLossless = qualityLevel; } }, { key: "dynamicQualityMin", get: function get() { return this._dynamicQualityMin; }, set: function set(qualityLevel) { if (!Number.isInteger(qualityLevel) || qualityLevel < 0 || qualityLevel > 9) { Log.Error("qualityLevel must be an integer between 0 and 9"); return; } if (this._dynamicQualityMin === qualityLevel) { return; } this._dynamicQualityMin = qualityLevel; this._pendingApplyEncodingChanges = true; } }, { key: "dynamicQualityMax", get: function get() { return this._dynamicQualityMax; }, set: function set(qualityLevel) { if (!Number.isInteger(qualityLevel) || qualityLevel < 0 || qualityLevel > 9) { Log.Error("qualityLevel must be an integer between 0 and 9"); return; } if (this._dynamicQualityMax === qualityLevel) { return; } this._dynamicQualityMax = qualityLevel; this._pendingApplyEncodingChanges = true; } }, { key: "videoArea", get: function get() { return this._videoArea; }, set: function set(area) { if (!Number.isInteger(area) || area < 0 || area > 100) { Log.Error("video area must be an integer between 0 and 100"); return; } if (this._videoArea === area) { return; } this._videoArea = area; this._pendingApplyEncodingChanges = true; } }, { key: "videoTime", get: function get() { return this._videoTime; }, set: function set(value) { if (!Number.isInteger(value) || value < 0 || value > 100) { Log.Error("video time must be an integer between 0 and 100"); return; } if (this._videoTime === value) { return; } this._videoTime = value; this._pendingApplyEncodingChanges = true; } }, { key: "videoOutTime", get: function get() { return this._videoOutTime; }, set: function set(value) { if (!Number.isInteger(value) || value < 0 || value > 100) { Log.Error("video out time must be an integer between 0 and 100"); return; } if (this._videoOutTime === value) { return; } this._videoOutTime = value; this._pendingApplyEncodingChanges = true; } }, { key: "videoScaling", get: function get() { return this._videoScaling; }, set: function set(value) { if (!Number.isInteger(value) || value < 0 || value > 2) { Log.Error("video scaling must be an integer between 0 and 2"); return; } if (this._videoScaling === value) { return; } this._videoScaling = value; this._pendingApplyEncodingChanges = true; } }, { key: "frameRate", get: function get() { return this._frameRate; }, set: function set(value) { if (!Number.isInteger(value) || value < 1 || value > 120) { Log.Error("frame rate must be an integer between 1 and 120"); return; } if (this._frameRate === value) { return; } this._frameRate = value; this._pendingApplyEncodingChanges = true; } }, { key: "maxVideoResolutionX", get: function get() { return this._maxVideoResolutionX; }, set: function set(value) { if (!Number.isInteger(value) || value < 100) { Log.Error("max video resolution must be an integer greater than 100"); return; } if (this._maxVideoResolutionX === value) { return; } this._maxVideoResolutionX = value; this._pendingApplyVideoRes = true; } }, { key: "maxVideoResolutionY", get: function get() { return this._maxVideoResolutionY; }, set: function set(value) { if (!Number.isInteger(value) || value < 100) { Log.Error("max video resolution must be an integer greater than 100"); return; } if (this._maxVideoResolutionY === value) { return; } this._maxVideoResolutionY = value; this._pendingApplyVideoRes = true; } }, { key: "qualityLevel", get: function get() { return this._qualityLevel; }, set: function set(qualityLevel) { if (!Number.isInteger(qualityLevel) || qualityLevel < 0 || qualityLevel > 9) { Log.Error("qualityLevel must be an integer between 0 and 9"); return; } if (this._qualityLevel === qualityLevel) { return; } this._qualityLevel = qualityLevel; this._pendingApplyEncodingChanges = true; } }, { key: "compressionLevel", get: function get() { return this._compressionLevel; }, set: function set(compressionLevel) { if (!Number.isInteger(compressionLevel) || compressionLevel < 0 || compressionLevel > 9) { Log.Error("compressionLevel must be an integer between 0 and 9"); return; } if (this._compressionLevel === compressionLevel) { return; } this._compressionLevel = compressionLevel; if (this._rfbConnectionState === 'connected') { this._sendEncodings(); } } }, { key: "statsFps", get: function get() { return this._display.fps; } }, { key: "enableWebRTC", get: function get() { return this._useUdp; }, set: function set(value) { this._useUdp = value; if (!value) { if (this._rfbConnectionState === 'connected' && this._transitConnectionState !== this.TransitConnectionStates.Tcp) { this._sendUdpDowngrade(); } } else { if (this._rfbConnectionState === 'connected' && this._transitConnectionState !== this.TransitConnectionStates.Udp) { this._sendUdpUpgrade(); } } } // ===== PUBLIC METHODS ===== /* This function must be called after changing any properties that effect rendering quality */ }, { key: "updateConnectionSettings", value: function updateConnectionSettings() { if (this._rfbConnectionState === 'connected') { if (this._pendingApplyVideoRes) { RFB.messages.setMaxVideoResolution(this._sock, this._maxVideoResolutionX, this._maxVideoResolutionY); } if (this._pendingApplyResolutionChange) { this._requestRemoteResize(); } if (this._pendingApplyEncodingChanges) { this._sendEncodings(); } this._pendingApplyVideoRes = false; this._pendingApplyEncodingChanges = false; this._pendingApplyResolutionChange = false; } } }, { key: "disconnect", value: function disconnect() { this._updateConnectionState('disconnecting'); this._sock.off('error'); this._sock.off('message'); this._sock.off('open'); } }, { key: "sendCredentials", value: function sendCredentials(creds) { this._rfbCredentials = creds; setTimeout(this._initMsg.bind(this), 0); } }, { key: "sendCtrlAltDel", value: function sendCtrlAltDel() { if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } Log.Info("Sending Ctrl-Alt-Del"); this.sendKey(_keysym["default"].XK_Control_L, "ControlLeft", true); this.sendKey(_keysym["default"].XK_Alt_L, "AltLeft", true); this.sendKey(_keysym["default"].XK_Delete, "Delete", true); this.sendKey(_keysym["default"].XK_Delete, "Delete", false); this.sendKey(_keysym["default"].XK_Alt_L, "AltLeft", false); this.sendKey(_keysym["default"].XK_Control_L, "ControlLeft", false); } }, { key: "machineShutdown", value: function machineShutdown() { this._xvpOp(1, 2); } }, { key: "machineReboot", value: function machineReboot() { this._xvpOp(1, 3); } }, { key: "machineReset", value: function machineReset() { this._xvpOp(1, 4); } // Send a key press. If 'down' is not specified then send a down key // followed by an up key. }, { key: "sendKey", value: function sendKey(keysym, code, down) { if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } if (code !== null) { this._setLastActive(); } if (down === undefined) { this.sendKey(keysym, code, true); this.sendKey(keysym, code, false); return; } var scancode = _xtscancodes["default"][code]; if (this._qemuExtKeyEventSupported && scancode) { // 0 is NoSymbol keysym = keysym || 0; Log.Info("Sending key (" + (down ? "down" : "up") + "): keysym " + keysym + ", scancode " + scancode); RFB.messages.QEMUExtendedKeyEvent(this._sock, keysym, down, scancode); } else { if (!keysym) { return; } Log.Info("Sending keysym (" + (down ? "down" : "up") + "): " + keysym); RFB.messages.keyEvent(this._sock, keysym, down ? 1 : 0); } } }, { key: "focus", value: function focus() { this._keyboard.focus(); } }, { key: "blur", value: function blur() { this._keyboard.blur(); } }, { key: "checkLocalClipboard", value: function checkLocalClipboard() { var _this2 = this; if (this.clipboardUp && this.clipboardSeamless) { if (this.clipboardBinary) { navigator.clipboard.read().then(function (data) { _this2.clipboardPasteDataFrom(data); }, function (err) { Log.Debug("No data in clipboard: " + err); }); } else { if (navigator.clipboard && navigator.clipboard.readText) { navigator.clipboard.readText().then(function (text) { this.clipboardPasteFrom(text); }.bind(this))["catch"](function () { return Log.Debug("Failed to read system clipboard"); }); } } } } }, { key: "clipboardPasteFrom", value: function clipboardPasteFrom(text) { if (this._rfbConnectionState !== 'connected' || this._viewOnly) { return; } if (!(typeof text === 'string' && text.length > 0)) { return; } var data = new TextEncoder().encode(text); var h = (0, _int.hashUInt8Array)(data); // avoid resending the same data if larger than 64k if (h === this._clipHash) { Log.Debug('No clipboard changes'); return; } else { this._clipHash = h; } var dataset = []; var mimes = ['text/plain']; dataset.push(data); RFB.messages.sendBinaryClipboard(this._sock, dataset, mimes); } }, { key: "clipboardPasteDataFrom", value: function () { var _clipboardPasteDataFrom = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(clipdata) { var dataset, mimes, h, i, ti, mime, blob, buff, data, _i, _i2; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!(this._rfbConnectionState !== 'connected' || this._viewOnly)) { _context.next = 2; break; } return _context.abrupt("return"); case 2: dataset = []; mimes = []; h = 0; i = 0; case 6: if (!(i < clipdata.length)) { _context.next = 43; break; } ti = 0; case 8: if (!(ti < clipdata[i].types.length)) { _context.next = 40; break; } mime = clipdata[i].types[ti]; _context.t0 = mime; _context.next = _context.t0 === 'image/png' ? 13 : _context.t0 === 'text/plain' ? 13 : _context.t0 === 'text/html' ? 13 : 36; break; case 13: _context.next = 15; return clipdata[i].getType(mime); case 15: blob = _context.sent; if (blob) { _context.next = 18; break; } return _context.abrupt("continue", 37); case 18: _context.next = 20; return blob.arrayBuffer(); case 20: buff = _context.sent; data = new Uint8Array(buff); if (h) {