@replit/novnc
Version:
An HTML5 VNC client
1,580 lines (1,203 loc) • 110 kB
JavaScript
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _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 _audio = _interopRequireDefault(require("./util/audio.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 _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"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 _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, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
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 } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || 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; } 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 : 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)'; // Minimum wait (ms) between two mouse moves
var MOUSE_MOVE_DELAY = 17; // Wheel thresholds
var WHEEL_STEP = 50; // Pixels needed for one step
var WHEEL_LINE_HEIGHT = 19; // Assumed pixels for one line step
// 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, 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 || []; // 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,
audio: false
};
_this._supportsFence = false;
_this._supportsContinuousUpdates = false;
_this._enabledContinuousUpdates = false;
_this._supportsSetDesktopSize = false;
_this._screenID = 0;
_this._screenFlags = 0;
_this._qemuExtKeyEventSupported = false;
_this._replitAudioSupported = false;
_this._replitAudioServerVersion = -1;
_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,
x: 0,
y: 0,
width: 0,
height: 0,
encoding: null
}; // Mouse state
_this._mousePos = {};
_this._mouseButtonMask = 0;
_this._mouseLastMoveTime = 0;
_this._viewportDragging = false;
_this._viewportDragPos = {};
_this._viewportHasMoved = false;
_this._accumulatedWheelDeltaX = 0;
_this._accumulatedWheelDeltaY = 0; // Gesture state
_this._gestureLastTapTime = null;
_this._gestureFirstDoubleTapEv = null;
_this._gestureLastMagnitudeX = 0;
_this._gestureLastMagnitudeY = 0; // Audio state
_this._audioEnabled = false;
_this._audioMimeType = null;
_this._audioStream = null; // Bound event handlers
_this._eventHandlers = {
focusCanvas: _this._focusCanvas.bind(_assertThisInitialized(_this)),
windowResize: _this._windowResize.bind(_assertThisInitialized(_this)),
handleMouse: _this._handleMouse.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._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; // 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._decoders[_encodings.encodings.encodingTightPNG] = new _tightpng["default"](); // 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));
_this._keyboard = new _keyboard["default"](_this._canvas);
_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.
// This it not possible when a pre-existing socket is passed in and is just opened.
// If the caller creates this object in the open() callback of a socket and there's
// data pending doing it next tick causes a packet to be lost.
// This is particularly noticable for RTCDataChannel's where the other end creates
// the channel and the client, this end, gets notified it exists.
if (typeof urlOrChannel === 'string') {
setTimeout(_this._updateConnectionState.bind(_assertThisInitialized(_this), 'connecting'));
} else {
_this._updateConnectionState('connecting');
}
Log.Debug("<< RFB.constructor"); // ===== PROPERTIES =====
_this.dragViewport = false;
_this.focusOnClick = true;
_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;
return _this;
} // ===== PROPERTIES =====
_createClass(RFB, [{
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();
}
}
}, {
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: "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;
if (this._rfbConnectionState === 'connected') {
this._sendEncodings();
}
}
}, {
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();
}
} // ===== PUBLIC METHODS =====
}, {
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 (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._canvas.focus();
}
}, {
key: "blur",
value: function blur() {
this._canvas.blur();
}
}, {
key: "clipboardPasteFrom",
value: function clipboardPasteFrom(text) {
if (this._rfbConnectionState !== 'connected' || this._viewOnly) {
return;
}
if (this._clipboardServerCapabilitiesFormats[extendedClipboardFormatText] && this._clipboardServerCapabilitiesActions[extendedClipboardActionNotify]) {
this._clipboardText = text;
RFB.messages.extendedClipboardNotify(this._sock, [extendedClipboardFormatText]);
} else {
var data = new Uint8Array(text.length);
for (var i = 0; i < text.length; i++) {
// FIXME: text can have values outside of Latin1/Uint8
data[i] = text.charCodeAt(i);
}
RFB.messages.clientCutText(this._sock, data);
}
}
}, {
key: "enableAudio",
value: function enableAudio(channels, codec, kbps) {
if (this._audioEnabled) {
return;
}
this._audioEnabled = true;
if (codec == RFB.audioCodecs.OpusWebM) {
this._audioMimeType = 'audio/webm;codecs=opus';
} else if (codec == RFB.audioCodecs.MP3) {
this._audioMimeType = 'audio/mpeg';
}
RFB.messages.ReplitAudioStartEncoder(this._sock, true, channels, codec, kbps);
}
}, {
key: "disableAudio",
value: function disableAudio() {
if (!this._audioEnabled) {
return;
}
this._audioEnabled = false;
RFB.messages.ReplitAudioStartEncoder(this._sock, false, 0, 0, 0);
} // ===== PRIVATE METHODS =====
}, {
key: "_connect",
value: function _connect() {
Log.Debug(">> RFB.connect");
if (this._url) {
try {
Log.Info("connecting to ".concat(this._url));
this._sock.open(this._url, this._wsProtocols);
} catch (e) {
if (e.name === 'SyntaxError') {
this._fail("Invalid host or port (" + e + ")");
} else {
this._fail("Error when opening socket (" + e + ")");
}
}
} else {
try {
Log.Info("attaching ".concat(this._rawChannel, " to Websock"));
this._sock.attach(this._rawChannel);
} catch (e) {
this._fail("Error attaching channel (" + e + ")");
}
} // Make our elements part of the page
this._target.appendChild(this._screen);
this._gestures.attach(this._canvas);
this._cursor.attach(this._canvas);
this._refreshCursor(); // Monitor size changes of the screen
// FIXME: Use ResizeObserver, or hidden overflow
window.addEventListener('resize', this._eventHandlers.windowResize); // Always grab focus on some kind of click event
this._canvas.addEventListener("mousedown", this._eventHandlers.focusCanvas);
this._canvas.addEventListener("touchstart", this._eventHandlers.focusCanvas); // Mouse events
this._canvas.addEventListener('mousedown', this._eventHandlers.handleMouse);
this._canvas.addEventListener('mouseup', this._eventHandlers.handleMouse);
this._canvas.addEventListener('mousemove', this._eventHandlers.handleMouse); // Prevent middle-click pasting (see handler for why we bind to document)
this._canvas.addEventListener('click', this._eventHandlers.handleMouse); // preventDefault() on mousedown doesn't stop this event for some
// reason so we have to explicitly block it
this._canvas.addEventListener('contextmenu', this._eventHandlers.handleMouse); // Wheel events
this._canvas.addEventListener("wheel", this._eventHandlers.handleWheel); // Gesture events
this._canvas.addEventListener("gesturestart", this._eventHandlers.handleGesture);
this._canvas.addEventListener("gesturemove", this._eventHandlers.handleGesture);
this._canvas.addEventListener("gestureend", this._eventHandlers.handleGesture);
Log.Debug("<< RFB.connect");
}
}, {
key: "_disconnect",
value: function _disconnect() {
Log.Debug(">> RFB.disconnect");
this._cursor.detach();
this._canvas.removeEventListener("gesturestart", this._eventHandlers.handleGesture);
this._canvas.removeEventListener("gesturemove", this._eventHandlers.handleGesture);
this._canvas.removeEventListener("gestureend", this._eventHandlers.handleGesture);
this._canvas.removeEventListener("wheel", this._eventHandlers.handleWheel);
this._canvas.removeEventListener('mousedown', this._eventHandlers.handleMouse);
this._canvas.removeEventListener('mouseup', this._eventHandlers.handleMouse);
this._canvas.removeEventListener('mousemove', this._eventHandlers.handleMouse);
this._canvas.removeEventListener('click', this._eventHandlers.handleMouse);
this._canvas.removeEventListener('contextmenu', this._eventHandlers.handleMouse);
this._canvas.removeEventListener("mousedown", this._eventHandlers.focusCanvas);
this._canvas.removeEventListener("touchstart", this._eventHandlers.focusCanvas);
window.removeEventListener('resize', this._eventHandlers.windowResize);
this._keyboard.ungrab();
this._gestures.detach();
this._sock.close();
try {
this._target.removeChild(this._screen);
} catch (e) {
if (e.name === 'NotFoundError') {// Some cases where the initial connection fails
// can disconnect before the _screen is created
} else {
throw e;
}
}
clearTimeout(this._resizeTimeout);
clearTimeout(this._mouseMoveTimer);
Log.Debug("<< RFB.disconnect");
}
}, {
key: "_focusCanvas",
value: function _focusCanvas(event) {
if (!this.focusOnClick) {
return;
}
this.focus();
}
}, {
key: "_setDesktopName",
value: function _setDesktopName(name) {
this._fbName = name;
this.dispatchEvent(new CustomEvent("desktopname", {
detail: {
name: this._fbName
}
}));
}
}, {
key: "_windowResize",
value: function _windowResize(event) {
var _this2 = this;
// If the window resized then our screen element might have
// as well. Update the viewport dimensions.
window.requestAnimationFrame(function () {
_this2._updateClip();
_this2._updateScale();
});
if (this._resizeSession) {
// Request changing the resolution of the remote display to
// the size of the local browser viewport.
// In order to not send multiple requests before the browser-resize
// is finished we wait 0.5 seconds before sending the request.
clearTimeout(this._resizeTimeout);
this._resizeTimeout = setTimeout(this._requestRemoteResize.bind(this), 500);
}
} // Update state of clipping in Display object, and make sure the
// configured viewport matches the current screen size
}, {
key: "_updateClip",
value: function _updateClip() {
var curClip = this._display.clipViewport;
var newClip = this._clipViewport;
if (this._scaleViewport) {
// Disable viewport clipping if we are scaling
newClip = false;
}
if (curClip !== newClip) {
this._display.clipViewport = newClip;
}
if (newClip) {
// When clipping is enabled, the screen is limited to
// the size of the container.
var size = this._screenSize();
this._display.viewportChangeSize(size.w, size.h);
this._fixScrollbars();
}
}
}, {
key: "_updateScale",
value: function _updateScale() {
if (!this._scaleViewport) {
this._display.scale = 1.0;
} else {
var size = this._screenSize();
this._display.autoscale(size.w, size.h);
}
this._fixScrollbars();
} // Requests a change of remote desktop size. This message is an extension
// and may only be sent if we have received an ExtendedDesktopSize message
}, {
key: "_requestRemoteResize",
value: function _requestRemoteResize() {
clearTimeout(this._resizeTimeout);
this._resizeTimeout = null;
if (!this._resizeSession || this._viewOnly || !this._supportsSetDesktopSize) {
return;
}
var size = this._screenSize();
RFB.messages.setDesktopSize(this._sock, Math.floor(size.w), Math.floor(size.h), this._screenID, this._screenFlags);
Log.Debug('Requested new desktop size: ' + size.w + 'x' + size.h);
} // Gets the the size of the available screen
}, {
key: "_screenSize",
value: function _screenSize() {
var r = this._screen.getBoundingClientRect();
return {
w: r.width,
h: r.height
};
}
}, {
key: "_fixScrollbars",
value: function _fixScrollbars() {
// 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;
this._screen.style.overflow = 'hidden'; // Force Chrome to recalculate the layout by asking for
// an element's dimensions
this._screen.getBoundingClientRect();
this._screen.style.overflow = orig;
}
/*
* Connection states:
* connecting
* connected
* disconnecting
* disconnected - permanent state
*/
}, {
key: "_updateConnectionState",
value: function _updateConnectionState(state) {
var _this3 = this;
var oldstate = this._rfbConnectionState;
if (state === oldstate) {
Log.Debug("Already in state '" + state + "', ignoring");
return;
} // The 'disconnected' state is permanent for each RFB object
if (oldstate === 'disconnected') {
Log.Error("Tried changing state of a disconnected RFB object");
return;
} // Ensure proper transitions before doing anything
switch (state) {
case 'connected':
if (oldstate !== 'connecting') {
Log.Error("Bad transition to connected state, " + "previous connection state: " + oldstate);
return;
}
break;
case 'disconnected':
if (oldstate !== 'disconnecting') {
Log.Error("Bad transition to disconnected state, " + "previous connection state: " + oldstate);
return;
}
break;
case 'connecting':
if (oldstate !== '') {
Log.Error("Bad transition to connecting state, " + "previous connection state: " + oldstate);
return;
}
break;
case 'disconnecting':
if (oldstate !== 'connected' && oldstate !== 'connecting') {
Log.Error("Bad transition to disconnecting state, " + "previous connection state: " + oldstate);
return;
}
break;
default:
Log.Error("Unknown connection state: " + state);
return;
} // State change actions
this._rfbConnectionState = state;
Log.Debug("New state '" + state + "', was '" + oldstate + "'.");
if (this._disconnTimer && state !== 'disconnecting') {
Log.Debug("Clearing disconnect timer");
clearTimeout(this._disconnTimer);
this._disconnTimer = null; // make sure we don't get a double event
this._sock.off('close');
}
switch (state) {
case 'connecting':
this._connect();
break;
case 'connected':
this.dispatchEvent(new CustomEvent("connect", {
detail: {}
}));
break;
case 'disconnecting':
this._disconnect();
this._disconnTimer = setTimeout(function () {
Log.Error("Disconnection timed out.");
_this3._updateConnectionState('disconnected');
}, DISCONNECT_TIMEOUT * 1000);
break;
case 'disconnected':
this.dispatchEvent(new CustomEvent("disconnect", {
detail: {
clean: this._rfbCleanDisconnect
}
}));
break;
}
}
/* Print errors and disconnect
*
* The parameter 'details' is used for information that
* should be logged but not sent to the user interface.
*/
}, {
key: "_fail",
value: function _fail(details) {
switch (this._rfbConnectionState) {
case 'disconnecting':
Log.Error("Failed when disconnecting: " + details);
break;
case 'connected':
Log.Error("Failed while connected: " + details);
break;
case 'connecting':
Log.Error("Failed when connecting: " + details);
break;
default:
Log.Error("RFB failure: " + details);
break;
}
this._rfbCleanDisconnect = false; //This is sent to the UI
// Transition to disconnected without waiting for socket to close
this._updateConnectionState('disconnecting');
this._updateConnectionState('disconnected');
return false;
}
}, {
key: "_setCapability",
value: function _setCapability(cap, val) {
this._capabilities[cap] = val;
this.dispatchEvent(new CustomEvent("capabilities", {
detail: {
capabilities: this._capabilities
}
}));
}
}, {
key: "_handleMessage",
value: function _handleMessage() {
if (this._sock.rQlen === 0) {
Log.Warn("handleMessage called on an empty receive queue");
return;
}
switch (this._rfbConnectionState) {
case 'disconnected':
Log.Error("Got data while disconnected");
break;
case 'connected':
while (true) {
if (this._flushing) {
break;
}
if (!this._normalMsg()) {
break;
}
if (this._sock.rQlen === 0) {
break;
}
}
break;
default:
this._initMsg();
break;
}
}
}, {
key: "_handleKeyEvent",
value: function _handleKeyEvent(keysym, code, down) {
this.sendKey(keysym, code, down);
}
}, {
key: "_handleMouse",
value: function _handleMouse(ev) {
/*
* We don't check connection status or viewOnly here as the
* mouse events might be used to control the viewport
*/
if (ev.type === 'click') {
/*
* Note: This is only needed for the 'click' event as it fails
* to fire properly for the target element so we have
* to listen on the document element instead.
*/
if (ev.target !== this._canvas) {
return;
}
} // FIXME: if we're in view-only and not dragging,
// should we stop events?
ev.stopPropagation();
ev.preventDefault();
if (ev.type === 'click' || ev.type === 'contextmenu') {
return;
}
var pos = (0, _element.clientToElement)(ev.clientX, ev.clientY, this._canvas);
switch (ev.type) {
case 'mousedown':
(0, _events.setCapture)(this._canvas);
this._handleMouseButton(pos.x, pos.y, true, 1 << ev.button);
break;
case 'mouseup':
this._handleMouseButton(pos.x, pos.y, false, 1 << ev.button);
break;
case 'mousemove':
this._handleMouseMove(pos.x, pos.y);
break;
}
}
}, {
key: "_handleMouseButton",
value: function _handleMouseButton(x, y, down, bmask) {
if (this.dragViewport) {
if (down && !this._viewportDragging) {
this._viewportDragging = true;
this._viewportDragPos = {
'x': x,
'y': y
};
this._viewportHasMoved = false; // Skip sending mouse events
return;
} else {
this._viewportDragging = false; // If we actually performed a drag then we are done
// here and should not send any mouse events
if (this._viewportHasMoved) {
return;
} // Otherwise we treat this as a mouse click event.
// Send the button down event here, as the button up
// event is sent at the end of this function.
this._sendMouse(x, y, bmask);
}
} // Flush waiting move event first
if (this._mouseMoveTimer !== null) {
clearTimeout(this._mouseMoveTimer);
this._mouseMoveTimer = null;
this._sendMouse(x, y, this._mouseButtonMask);
}
if (down) {
this._mouseButtonMask |= bmask;
} else {
this._mouseButtonMask &= ~bmask;
}
this._sendMouse(x, y, this._mouseButtonMask);
}
}, {
key: "_handleMouseMove",
value: function _handleMouseMove(x, y) {
var _this4 = this;
if (this._viewportDragging) {
var deltaX = this._viewportDragPos.x - x;
var deltaY = this._viewportDragPos.y - y;
if (this._viewportHasMoved || Math.abs(deltaX) > _browser.dragThreshold || Math.abs(deltaY) > _browser.dragThreshold) {
this._viewportHasMoved = true;
this._viewportDragPos = {
'x': x,
'y': y
};
this._display.viewportChangePos(deltaX, deltaY);
} // Skip sending mouse events
return;
}
this._mousePos = {
'x': x,
'y': y
}; // Limit many mouse move events to one every MOUSE_MOVE_DELAY ms
if (this._mouseMoveTimer == null) {
var timeSinceLastMove = Date.now() - this._mouseLastMoveTime;
if (timeSinceLastMove > MOUSE_MOVE_DELAY) {
this._sendMouse(x, y, this._mouseButtonMask);
this._mouseLastMoveTime = Date.now();
} else {
// Too soon since the latest move, wait the remaining time
this._mouseMoveTimer = setTimeout(function () {
_this4._handleDelayedMouseMove();
}, MOUSE_MOVE_DELAY - timeSinceLastMove);
}
}
}
}, {
key: "_handleDelayedMouseMove",
value: function _handleDelayedMouseMove() {
this._mouseMoveTimer = null;
this._sendMouse(this._mousePos.x, this._mousePos.y, this._mouseButtonMask);
this._mouseLastMoveTime = Date.now();
}
}, {
key: "_sendMouse",
value: function _sendMouse(x, y, mask) {
if (this._rfbConnectionState !== 'connected') {
return;
}
if (this._viewOnly) {
return;
} // View only, skip mouse events
RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), mask);
}
}, {
key: "_handleWheel",
value: function _handleWheel(ev) {
if (this._rfbConnectionState !== 'connected') {
return;
}
if (this._viewOnly) {
return;
} // View only, skip mouse events
ev.stopPropagation();
ev.preventDefault();
var pos = (0, _element.clientToElement)(ev.clientX, ev.clientY, this._canvas);
var dX = ev.deltaX;
var dY = ev.deltaY; // Pixel units unless it's non-zero.
// Note that if deltamode is line or page won't matter since we aren't
// sending the mouse wheel delta to the server anyway.
// The difference between pixel and line can be important however since
// we have a threshold that can be smaller than the line height.
if (ev.deltaMode !== 0) {
dX *= WHEEL_LINE_HEIGHT;
dY *= WHEEL_LINE_HEIGHT;
} // Mouse wheel events are sent in steps over VNC. This means that the VNC
// protocol can't handle a wheel event with specific distance or speed.
// Therefor, if we get a lot of small mouse wheel events we combine them.
this._accumulatedWheelDeltaX += dX;
this._accumulatedWheelDeltaY += dY; // Generate a mouse wheel step event when the accumulated delta
// for one of the axes is large enough.
if (Math.abs(this._accumulatedWheelDeltaX) >= WHEEL_STEP) {
if (this._accumulatedWheelDeltaX < 0) {
this._handleMouseButton(pos.x, pos.y, true, 1 << 5);
this._handleMouseButton(pos.x, pos.y, false, 1 << 5);
} else if (this._accumulatedWheelDeltaX > 0) {
this._handleMouseButton(pos.x, pos.y, true, 1 << 6);
this._handleMouseButton(pos.x, pos.y, false, 1 << 6);
}
this._accumulatedWheelDeltaX = 0;
}
if (Math.abs(this._accumulatedWheelDeltaY) >= WHEEL_STEP) {
if (this._accumulatedWheelDeltaY < 0) {
this._handleMouseButton(pos.x, pos.y, true, 1 << 3);
this._handleMouseButton(pos.x, pos.y, false, 1 << 3);
} else if (this._accumulatedWheelDeltaY > 0) {
this._handleMouseButton(pos.x, pos.y, true, 1 << 4);
this._handleMouseButton(pos.x, pos.y, false, 1 << 4);
}
this._accumulatedWheelDeltaY = 0;
}
}
}, {
key: "_fakeMouseMove",
value: function _fakeMouseMove(ev, elementX, elementY) {
this._handleMouseMove(elementX, elementY);
this._cursor.move(ev.detail.clientX, ev.detail.clientY);
}
}, {
key: "_handleTapEvent",
value: function _handleTapEvent(ev, bmask) {
var pos = (0, _element.clientToElement)(ev.detail.clientX, ev.detail.clientY, this._canvas); // If the user quickly taps multiple times we assume they meant to
// hit the same spot, so slightly adjust coordinates
if (this._gestureLastTapTime !== null && Date.now() - this._gestureLastTapTime < DOUBLE_TAP_TIMEOUT && this._gestureFirstDoubleTapEv.detail.type === ev.detail.type) {
var dx = this._gestureFirstDoubleTapEv.detail.clientX - ev.detail.clientX;
var dy = this._gestureFirstDoubleTapEv.detail.clientY - ev.detail.clientY;
var distance = Math.hypot(dx, dy);
if (distance < DOUBLE_TAP_THRESHOLD) {
pos = (0, _element.clientToElement)(this._gestureFirstDoubleTapEv.detail.clientX, this._gestureFirstDoubleTapEv.detail.clientY, this._canvas);
} else {
this._gestureFirstDoubleTapEv = ev;
}
} else {
this._gestureFirstDoubleTapEv = ev;
}
this._gestureLastTapTime = Date.now();
this._fakeMouseMove(this._gestureFirstDoubleTapEv, pos.x, pos.y);
this._handleMouseButton(pos.x, pos.y, true, bmask);
this._handleMouseButton(pos.x, pos.y, false, bmask);
}
}, {
key: "_handleGesture",
value: function _handleGesture(ev) {
var magnitude;
var pos = (0, _element.clientToElement)(ev.detail.clientX, ev.detail.clientY, this._canvas);
switch (ev.type) {
case 'gesturestart':
switch (ev.detail.type) {
case 'onetap':
this._handleTapEvent(ev, 0x1);
break;
case 'twotap':
this._handleTapEvent(ev, 0x4);
break;
case 'threetap':
this._handleTapEvent(ev, 0x2);
break;
case 'drag':
this._fakeMouseMove(ev, pos.x, pos.y);
this._handleMouseButton(pos.x, pos.y, true, 0x1);
break;
case 'longpress':
this._fakeMouseMove(ev, pos.x, pos.y);
this._handleMouseButton(pos.x, pos.y, true, 0x4);
break;
case 'twodrag':
this._gestureLastMagnitudeX = ev.detail.magnitudeX;
this._gestureLastMagnitudeY = ev.detail.magnitudeY;
this._fakeMouseMove(ev, pos.x, pos.y);
break;
case 'pinch':
this._gestureLastMagnitudeX = Math.hypot(ev.detail.magnitudeX, ev.detail.magnitudeY);
this._fakeMouseMove(ev, pos.x, pos.y);
break;
}
break;
case 'gesturemove':
switch (ev.detail.type) {
case 'onetap':
case 'twotap':
case 'threetap':
break;
case 'drag':
case 'longpress':
this._fakeMouseMove(ev, pos.x, pos.y);
break;
case 'twodrag':
// Always scroll in the same position.
// We don't know if the mouse was moved so we need to move it
// every update.
this._fakeMouseMove(ev, pos.x, pos.y);
while (ev.detail.magnitudeY - this._gestureLastMagnitudeY > GESTURE_SCRLSENS) {
this._handleMouseButton(pos.x, pos.y, true, 0x8);
this._handleMouseButton(pos.x, pos.y, false, 0x8);
this._gestureLastMagnitudeY += GESTURE_SCRLSENS;
}
while (ev.detail.magnitudeY - this._gestureLastMagnitudeY < -GESTURE_SCRLSENS) {
this._handleMouseButton(pos.x, pos.y, true, 0x10);
this._handleMouseButton(pos.x, pos.y, false, 0x10);
this._gestureLastMagnitudeY -= GESTURE_SCRLSENS;
}
while (ev.detail.magnitudeX - this._gestureLastMagnitudeX > GESTURE_SCRLSENS) {
this._handleMouseButton(pos.x, pos.y, true, 0x20);
this._handleMouseButton(pos.x, pos.y, false, 0x20);
this._gestureLastMagnitudeX += GESTURE_SCRLSENS;
}
while (ev.detail.magnitudeX - this._gestureLastMagnitudeX < -GESTURE_SCRLSENS) {
this._handleMouseButton(pos.x, pos.y, true, 0x40);
this._handleMouseButton(pos.x, pos.y, false, 0x40);
this._gestureLastMagnitudeX -= GESTURE_SCRLSENS;
}
break;
case 'pinch':
// Always scroll in the same position.
// We don't know if the mouse was moved so we need to move it
// every update.
this._fakeMouseMove(ev, pos.x, pos.y);
magnitude = Math.hypot(ev.detail.magnitudeX, ev.detail.magnitudeY);
if (Math.abs(magnitude - this._gestureLastMagnitudeX) > GESTURE_ZOOMSENS) {
this._handleKeyEvent(_keysym["default"].XK_Control_L, "ControlLeft", true);
while (magnitude - this._gestureLastMagnitudeX > GESTURE_ZOOMSENS) {
this._handleMouseButton(pos.x, pos.y, true, 0x8);
this._handleMouseButton(pos.x, pos.y, false, 0x8);
this._gestureLastMagnitudeX += GESTURE_ZOOMSENS;
}
while (magnitude - this._gestureLastMagnitudeX < -GESTURE_ZOOMSENS) {
this._handleMouseButton(pos.x, pos.y, true, 0x10);
this._handleMouseButton(pos.x, pos.y, false, 0x10);
this._gestureLastMagnitudeX -= GESTURE_ZOOMSENS;
}
}
this._handleKeyEvent(_keysym["default"].XK_Control_L, "ControlLeft", false);
break;
}
break;
case 'gestureend':
switch (ev.detail.type) {
case 'onetap':
case 'twotap':
case 'threetap':
case 'pinch':
case 'twodrag':
break;
case 'drag':
this._fakeMouseMove(ev, pos.x, pos.y);
this._handleMouseButton(pos.x, pos.y, false, 0x1);
break;
case 'longpress':
this._fakeMouseMove(ev, pos.x, pos.y);
this._handleMouseButton(pos.x, pos.y, false, 0x4);
break;
}
break;
}
} // Message Handlers
}, {
key: "_negotiateProtocolVersion",
value: function _negotiateProtocolVersion() {
if (this._sock.rQwait("version", 12)) {
return false;
}
var sversion = this._sock.rQshiftStr(12).substr(4, 7);
Log.Info("Server ProtocolVersion: " + sversion);
var isRepeater = 0;
switch (sversion) {
case "000.000":
// UltraVNC repeater
isRepeater = 1;
break;
case "003.003":
case "003.006": // UltraVNC
case "003.889":
// Apple Remote Desktop
this._rfbVersion = 3.3;
break;
case "003.007":
this._rfbVersion = 3.7;
break;
case "003.008":
case "004.000": // Intel AMT KVM
case "004.001": // RealVNC 4.6
case "005.000":
// RealVNC 5.3
this._rfbVersion = 3.8;
break;
default:
return this._fail("Invalid server version " + sversion);
}
if (isRepeater) {
var repeaterID = "ID:" + this._repeaterID;
while (repeaterID.length < 250) {
repeaterID += "\0";
}
this._sock.sendString(repeaterID);
return true;
}