2 * noVNC: HTML5 VNC client
3 * Copyright (C) 2012 Joel Martin
4 * Copyright (C) 2017 Samuel Mannehed for Cendio AB
5 * Licensed under MPL 2.0 (see LICENSE.txt)
7 * See README.md for usage and integration instructions.
9 * TIGHT decoder portion:
10 * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca)
13 import * as Log
from './util/logging.js';
14 import _
from './util/localization.js';
15 import { decodeUTF8
} from './util/strings.js';
16 import { browserSupportsCursorURIs
, isTouchDevice
} from './util/browsers.js';
17 import EventTargetMixin
from './util/eventtarget.js';
18 import Display
from "./display.js";
19 import Keyboard
from "./input/keyboard.js";
20 import Mouse
from "./input/mouse.js";
21 import Websock
from "./websock.js";
22 import Base64
from "./base64.js";
23 import DES
from "./des.js";
24 import KeyTable
from "./input/keysym.js";
25 import XtScancode
from "./input/xtscancodes.js";
26 import Inflator
from "./inflator.js";
27 import { encodings
, encodingName
} from "./encodings.js";
28 import "./util/polyfill.js";
30 /*jslint white: false, browser: true */
31 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
33 // How many seconds to wait for a disconnect to finish
34 var DISCONNECT_TIMEOUT
= 3;
36 export default function RFB(target
, url
, options
) {
38 throw Error("Must specify target");
41 throw Error("Must specify URL");
44 this._target
= target
;
48 options
= options
|| {};
49 this._rfb_credentials
= options
.credentials
|| {};
50 this._shared
= 'shared' in options
? !!options
.shared
: true;
51 this._repeaterID
= options
.repeaterID
|| '';
54 this._rfb_connection_state
= '';
55 this._rfb_init_state
= '';
56 this._rfb_auth_scheme
= '';
57 this._rfb_disconnect_reason
= "";
59 // Server capabilities
60 this._rfb_version
= 0;
61 this._rfb_max_version
= 3.8;
62 this._rfb_tightvnc
= false;
63 this._rfb_xvp_ver
= 0;
70 this._capabilities
= { power
: false, resize
: false };
72 this._supportsFence
= false;
74 this._supportsContinuousUpdates
= false;
75 this._enabledContinuousUpdates
= false;
77 this._supportsSetDesktopSize
= false;
79 this._screen_flags
= 0;
81 this._qemuExtKeyEventSupported
= false;
84 this._sock
= null; // Websock object
85 this._display
= null; // Display object
86 this._flushing
= false; // Display flushing state
87 this._keyboard
= null; // Keyboard input handler object
88 this._mouse
= null; // Mouse input handler object
91 this._disconnTimer
= null; // disconnection timer
93 // Decoder states and stats
94 this._encHandlers
= {};
99 subrects
: 0, // RRE and HEXTILE
110 zlibs
: [] // TIGHT zlib streams
112 for (var i
= 0; i
< 4; i
++) {
113 this._FBU
.zlibs
[i
] = new Inflator();
116 this._destBuff
= null;
117 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
119 this._rre_chunk_sz
= 100;
135 this._mouse_buttonMask
= 0;
136 this._mouse_arr
= [];
137 this._viewportDragging
= false;
138 this._viewportDragPos
= {};
139 this._viewportHasMoved
= false;
141 // Bound event handlers
142 this._eventHandlers
= {
143 focusCanvas
: this._focusCanvas
.bind(this),
147 Log
.Debug(">> RFB.constructor");
149 // Target canvas must be able to have focus
150 if (!this._target
.hasAttribute('tabindex')) {
151 this._target
.tabIndex
= -1;
154 // populate encHandlers with bound versions
155 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this);
156 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this);
157 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this);
158 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this);
159 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this);
161 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this);
162 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this);
163 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this);
164 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this);
165 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this);
167 // NB: nothing that needs explicit teardown should be done
168 // before this point, since this can throw an exception
170 this._display
= new Display(this._target
);
172 Log
.Error("Display exception: " + exc
);
175 this._display
.onflush
= this._onFlush
.bind(this);
176 this._display
.clear();
178 this._keyboard
= new Keyboard(this._target
);
179 this._keyboard
.onkeyevent
= this._handleKeyEvent
.bind(this);
181 this._mouse
= new Mouse(this._target
);
182 this._mouse
.onmousebutton
= this._handleMouseButton
.bind(this);
183 this._mouse
.onmousemove
= this._handleMouseMove
.bind(this);
185 this._sock
= new Websock();
186 this._sock
.on('message', this._handle_message
.bind(this));
187 this._sock
.on('open', function () {
188 if ((this._rfb_connection_state
=== 'connecting') &&
189 (this._rfb_init_state
=== '')) {
190 this._rfb_init_state
= 'ProtocolVersion';
191 Log
.Debug("Starting VNC handshake");
193 this._fail("Unexpected server connection");
196 this._sock
.on('close', function (e
) {
197 Log
.Warn("WebSocket on-close event");
200 msg
= " (code: " + e
.code
;
202 msg
+= ", reason: " + e
.reason
;
206 switch (this._rfb_connection_state
) {
207 case 'disconnecting':
208 this._updateConnectionState('disconnected');
211 this._fail('Failed to connect to server', msg
);
214 // Handle disconnects that were initiated server-side
215 this._updateConnectionState('disconnecting');
216 this._updateConnectionState('disconnected');
219 this._fail("Unexpected server disconnect",
220 "Already disconnected: " + msg
);
223 this._fail("Unexpected server disconnect",
224 "Not in any state yet: " + msg
);
227 this._sock
.off('close');
229 this._sock
.on('error', function (e
) {
230 Log
.Warn("WebSocket on-error event");
233 // Slight delay of the actual connection so that the caller has
234 // time to set up callbacks
235 setTimeout(this._updateConnectionState
.bind(this, 'connecting'));
237 Log
.Debug("<< RFB.constructor");
241 // ===== PROPERTIES =====
247 get viewOnly() { return this._viewOnly
; },
248 set viewOnly(viewOnly
) {
249 this._viewOnly
= viewOnly
;
251 if (this._rfb_connection_state
=== "connecting" ||
252 this._rfb_connection_state
=== "connected") {
254 this._keyboard
.ungrab();
255 this._mouse
.ungrab();
257 this._keyboard
.grab();
263 get capabilities() { return this._capabilities
; },
265 get touchButton() { return this._mouse
.touchButton
; },
266 set touchButton(button
) { this._mouse
.touchButton
= button
; },
268 get viewportScale() { return this._display
.scale
; },
269 set viewportScale(scale
) { this._display
.scale
= scale
; },
271 get clipViewport() { return this._display
.clipViewport
; },
272 set clipViewport(viewport
) { this._display
.clipViewport
= viewport
; },
274 get isClipped() { return this._display
.isClipped
; },
276 // ===== PUBLIC METHODS =====
278 disconnect: function () {
279 this._updateConnectionState('disconnecting');
280 this._sock
.off('error');
281 this._sock
.off('message');
282 this._sock
.off('open');
285 sendCredentials: function (creds
) {
286 this._rfb_credentials
= creds
;
287 setTimeout(this._init_msg
.bind(this), 0);
290 sendCtrlAltDel: function () {
291 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
292 Log
.Info("Sending Ctrl-Alt-Del");
294 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
295 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
296 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
297 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
298 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
299 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
302 machineShutdown: function () {
306 machineReboot: function () {
310 machineReset: function () {
314 // Send a key press. If 'down' is not specified then send a down key
315 // followed by an up key.
316 sendKey: function (keysym
, code
, down
) {
317 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
319 if (down
=== undefined) {
320 this.sendKey(keysym
, code
, true);
321 this.sendKey(keysym
, code
, false);
325 var scancode
= XtScancode
[code
];
327 if (this._qemuExtKeyEventSupported
&& scancode
) {
329 keysym
= keysym
|| 0;
331 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
333 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
338 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
339 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
343 clipboardPasteFrom: function (text
) {
344 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
345 RFB
.messages
.clientCutText(this._sock
, text
);
348 autoscale: function (width
, height
) {
349 if (this._rfb_connection_state
!== 'connected') { return; }
350 this._display
.autoscale(width
, height
);
353 viewportChangeSize: function(width
, height
) {
354 if (this._rfb_connection_state
!== 'connected') { return; }
355 this._display
.viewportChangeSize(width
, height
);
358 // Requests a change of remote desktop size. This message is an extension
359 // and may only be sent if we have received an ExtendedDesktopSize message
360 requestDesktopSize: function (width
, height
) {
361 if (this._rfb_connection_state
!== 'connected' ||
366 if (!this._supportsSetDesktopSize
) {
370 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
371 this._screen_id
, this._screen_flags
);
375 // ===== PRIVATE METHODS =====
377 _connect: function () {
378 Log
.Debug(">> RFB.connect");
380 Log
.Info("connecting to " + this._url
);
383 // WebSocket.onopen transitions to the RFB init states
384 this._sock
.open(this._url
, ['binary']);
386 if (e
.name
=== 'SyntaxError') {
387 this._fail("Invalid host or port value given", e
);
389 this._fail("Error while connecting", e
);
393 // Always grab focus on some kind of click event
394 this._target
.addEventListener("mousedown", this._eventHandlers
.focusCanvas
);
395 this._target
.addEventListener("touchstart", this._eventHandlers
.focusCanvas
);
397 Log
.Debug("<< RFB.connect");
400 _disconnect: function () {
401 Log
.Debug(">> RFB.disconnect");
402 this._target
.removeEventListener("mousedown", this._eventHandlers
.focusCanvas
);
403 this._target
.removeEventListener("touchstart", this._eventHandlers
.focusCanvas
);
407 Log
.Debug("<< RFB.disconnect");
410 _print_stats: function () {
411 var stats
= this._encStats
;
413 Log
.Info("Encoding stats for this connection:");
414 Object
.keys(stats
).forEach(function (key
) {
416 if (s
[0] + s
[1] > 0) {
417 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
421 Log
.Info("Encoding stats since page load:");
422 Object
.keys(stats
).forEach(function (key
) {
424 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
428 _cleanup: function () {
429 if (!this._viewOnly
) { this._keyboard
.ungrab(); }
430 if (!this._viewOnly
) { this._mouse
.ungrab(); }
431 this._display
.defaultCursor();
432 if (Log
.get_logging() !== 'debug') {
433 // Show noVNC logo when disconnected, unless in
435 this._display
.clear();
439 _focusCanvas: function(event
) {
440 // Respect earlier handlers' request to not do side-effects
441 if (event
.defaultPrevented
) {
445 if (!this._focus_on_click
) {
449 this._target
.focus();
457 * disconnected - permanent state
459 _updateConnectionState: function (state
) {
460 var oldstate
= this._rfb_connection_state
;
462 if (state
=== oldstate
) {
463 Log
.Debug("Already in state '" + state
+ "', ignoring");
467 // The 'disconnected' state is permanent for each RFB object
468 if (oldstate
=== 'disconnected') {
469 Log
.Error("Tried changing state of a disconnected RFB object");
473 // Ensure proper transitions before doing anything
476 if (oldstate
!== 'connecting') {
477 Log
.Error("Bad transition to connected state, " +
478 "previous connection state: " + oldstate
);
484 if (oldstate
!== 'disconnecting') {
485 Log
.Error("Bad transition to disconnected state, " +
486 "previous connection state: " + oldstate
);
492 if (oldstate
!== '') {
493 Log
.Error("Bad transition to connecting state, " +
494 "previous connection state: " + oldstate
);
499 case 'disconnecting':
500 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
501 Log
.Error("Bad transition to disconnecting state, " +
502 "previous connection state: " + oldstate
);
508 Log
.Error("Unknown connection state: " + state
);
512 // State change actions
514 this._rfb_connection_state
= state
;
516 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
519 if (this._disconnTimer
&& state
!== 'disconnecting') {
520 Log
.Debug("Clearing disconnect timer");
521 clearTimeout(this._disconnTimer
);
522 this._disconnTimer
= null;
524 // make sure we don't get a double event
525 this._sock
.off('close');
534 var event
= new CustomEvent("connect", { detail
: {} });
535 this.dispatchEvent(event
);
538 case 'disconnecting':
541 this._disconnTimer
= setTimeout(function () {
542 this._rfb_disconnect_reason
= _("Disconnect timeout");
543 this._updateConnectionState('disconnected');
544 }.bind(this), DISCONNECT_TIMEOUT
* 1000);
548 if (this._rfb_disconnect_reason
!== "") {
549 event
= new CustomEvent("disconnect",
550 { detail
: { reason
: this._rfb_disconnect_reason
} });
552 // No reason means clean disconnect
553 event
= new CustomEvent("disconnect", { detail
: {} });
555 this.dispatchEvent(event
);
560 /* Print errors and disconnect
562 * The optional parameter 'details' is used for information that
563 * should be logged but not sent to the user interface.
565 _fail: function (msg
, details
) {
567 if (typeof details
!== 'undefined') {
568 fullmsg
= msg
+ " (" + details
+ ")";
570 switch (this._rfb_connection_state
) {
571 case 'disconnecting':
572 Log
.Error("Failed when disconnecting: " + fullmsg
);
575 Log
.Error("Failed while connected: " + fullmsg
);
578 Log
.Error("Failed when connecting: " + fullmsg
);
581 Log
.Error("RFB failure: " + fullmsg
);
584 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
586 // Transition to disconnected without waiting for socket to close
587 this._updateConnectionState('disconnecting');
588 this._updateConnectionState('disconnected');
593 _setCapability: function (cap
, val
) {
594 this._capabilities
[cap
] = val
;
595 var event
= new CustomEvent("capabilities",
596 { detail
: { capabilities
: this._capabilities
} });
597 this.dispatchEvent(event
);
600 _handle_message: function () {
601 if (this._sock
.rQlen() === 0) {
602 Log
.Warn("handle_message called on an empty receive queue");
606 switch (this._rfb_connection_state
) {
608 Log
.Error("Got data while disconnected");
612 if (this._flushing
) {
615 if (!this._normal_msg()) {
618 if (this._sock
.rQlen() === 0) {
629 _handleKeyEvent: function (keysym
, code
, down
) {
630 this.sendKey(keysym
, code
, down
);
633 _handleMouseButton: function (x
, y
, down
, bmask
) {
635 this._mouse_buttonMask
|= bmask
;
637 this._mouse_buttonMask
&= ~bmask
;
640 if (this.dragViewport
) {
641 if (down
&& !this._viewportDragging
) {
642 this._viewportDragging
= true;
643 this._viewportDragPos
= {'x': x
, 'y': y
};
645 // Skip sending mouse events
648 this._viewportDragging
= false;
650 // If the viewport didn't actually move, then treat as a mouse click event
651 // Send the button down event here, as the button up event is sent at the end of this function
652 if (!this._viewportHasMoved
&& !this._viewOnly
) {
653 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
655 this._viewportHasMoved
= false;
659 if (this._viewOnly
) { return; } // View only, skip mouse events
661 if (this._rfb_connection_state
!== 'connected') { return; }
662 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
665 _handleMouseMove: function (x
, y
) {
666 if (this._viewportDragging
) {
667 var deltaX
= this._viewportDragPos
.x
- x
;
668 var deltaY
= this._viewportDragPos
.y
- y
;
670 // The goal is to trigger on a certain physical width, the
671 // devicePixelRatio brings us a bit closer but is not optimal.
672 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
674 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
675 Math
.abs(deltaY
) > dragThreshold
)) {
676 this._viewportHasMoved
= true;
678 this._viewportDragPos
= {'x': x
, 'y': y
};
679 this._display
.viewportChangePos(deltaX
, deltaY
);
682 // Skip sending mouse events
686 if (this._viewOnly
) { return; } // View only, skip mouse events
688 if (this._rfb_connection_state
!== 'connected') { return; }
689 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
694 _negotiate_protocol_version: function () {
695 if (this._sock
.rQlen() < 12) {
696 return this._fail("Error while negotiating with server",
697 "Incomplete protocol version");
700 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
701 Log
.Info("Server ProtocolVersion: " + sversion
);
704 case "000.000": // UltraVNC repeater
708 case "003.006": // UltraVNC
709 case "003.889": // Apple Remote Desktop
710 this._rfb_version
= 3.3;
713 this._rfb_version
= 3.7;
716 case "004.000": // Intel AMT KVM
717 case "004.001": // RealVNC 4.6
718 case "005.000": // RealVNC 5.3
719 this._rfb_version
= 3.8;
722 return this._fail("Unsupported server",
723 "Invalid server version: " + sversion
);
727 var repeaterID
= "ID:" + this._repeaterID
;
728 while (repeaterID
.length
< 250) {
731 this._sock
.send_string(repeaterID
);
735 if (this._rfb_version
> this._rfb_max_version
) {
736 this._rfb_version
= this._rfb_max_version
;
739 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
740 ".00" + ((this._rfb_version
* 10) % 10);
741 this._sock
.send_string("RFB " + cversion
+ "\n");
742 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
744 this._rfb_init_state
= 'Security';
747 _negotiate_security: function () {
748 // Polyfill since IE and PhantomJS doesn't have
749 // TypedArray.includes()
750 function includes(item
, array
) {
751 for (var i
= 0; i
< array
.length
; i
++) {
752 if (array
[i
] === item
) {
759 if (this._rfb_version
>= 3.7) {
760 // Server sends supported list, client decides
761 var num_types
= this._sock
.rQshift8();
762 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
764 if (num_types
=== 0) {
765 var strlen
= this._sock
.rQshift32();
766 var reason
= this._sock
.rQshiftStr(strlen
);
767 return this._fail("Error while negotiating with server",
768 "Security failure: " + reason
);
771 var types
= this._sock
.rQshiftBytes(num_types
);
772 Log
.Debug("Server security types: " + types
);
774 // Look for each auth in preferred order
775 this._rfb_auth_scheme
= 0;
776 if (includes(1, types
)) {
777 this._rfb_auth_scheme
= 1; // None
778 } else if (includes(22, types
)) {
779 this._rfb_auth_scheme
= 22; // XVP
780 } else if (includes(16, types
)) {
781 this._rfb_auth_scheme
= 16; // Tight
782 } else if (includes(2, types
)) {
783 this._rfb_auth_scheme
= 2; // VNC Auth
785 return this._fail("Unsupported server",
786 "Unsupported security types: " + types
);
789 this._sock
.send([this._rfb_auth_scheme
]);
792 if (this._sock
.rQwait("security scheme", 4)) { return false; }
793 this._rfb_auth_scheme
= this._sock
.rQshift32();
796 this._rfb_init_state
= 'Authentication';
797 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
799 return this._init_msg(); // jump to authentication
803 _negotiate_xvp_auth: function () {
804 if (!this._rfb_credentials
.username
||
805 !this._rfb_credentials
.password
||
806 !this._rfb_credentials
.target
) {
807 var event
= new CustomEvent("credentialsrequired",
808 { detail
: { types
: ["username", "password", "target"] } });
809 this.dispatchEvent(event
);
813 var xvp_auth_str
= String
.fromCharCode(this._rfb_credentials
.username
.length
) +
814 String
.fromCharCode(this._rfb_credentials
.target
.length
) +
815 this._rfb_credentials
.username
+
816 this._rfb_credentials
.target
;
817 this._sock
.send_string(xvp_auth_str
);
818 this._rfb_auth_scheme
= 2;
819 return this._negotiate_authentication();
822 _negotiate_std_vnc_auth: function () {
823 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
825 if (!this._rfb_credentials
.password
) {
826 var event
= new CustomEvent("credentialsrequired",
827 { detail
: { types
: ["password"] } });
828 this.dispatchEvent(event
);
832 // TODO(directxman12): make genDES not require an Array
833 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
834 var response
= RFB
.genDES(this._rfb_credentials
.password
, challenge
);
835 this._sock
.send(response
);
836 this._rfb_init_state
= "SecurityResult";
840 _negotiate_tight_tunnels: function (numTunnels
) {
841 var clientSupportedTunnelTypes
= {
842 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
844 var serverSupportedTunnelTypes
= {};
845 // receive tunnel capabilities
846 for (var i
= 0; i
< numTunnels
; i
++) {
847 var cap_code
= this._sock
.rQshift32();
848 var cap_vendor
= this._sock
.rQshiftStr(4);
849 var cap_signature
= this._sock
.rQshiftStr(8);
850 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
853 // choose the notunnel type
854 if (serverSupportedTunnelTypes
[0]) {
855 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
856 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
857 return this._fail("Unsupported server",
858 "Client's tunnel type had the incorrect " +
859 "vendor or signature");
861 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
862 return false; // wait until we receive the sub auth count to continue
864 return this._fail("Unsupported server",
865 "Server wanted tunnels, but doesn't support " +
866 "the notunnel type");
870 _negotiate_tight_auth: function () {
871 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
872 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
873 var numTunnels
= this._sock
.rQshift32();
874 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
876 this._rfb_tightvnc
= true;
878 if (numTunnels
> 0) {
879 this._negotiate_tight_tunnels(numTunnels
);
880 return false; // wait until we receive the sub auth to continue
884 // second pass, do the sub-auth negotiation
885 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
886 var subAuthCount
= this._sock
.rQshift32();
887 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
888 this._rfb_init_state
= 'SecurityResult';
892 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
894 var clientSupportedTypes
= {
899 var serverSupportedTypes
= [];
901 for (var i
= 0; i
< subAuthCount
; i
++) {
902 var capNum
= this._sock
.rQshift32();
903 var capabilities
= this._sock
.rQshiftStr(12);
904 serverSupportedTypes
.push(capabilities
);
907 for (var authType
in clientSupportedTypes
) {
908 if (serverSupportedTypes
.indexOf(authType
) != -1) {
909 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
912 case 'STDVNOAUTH__': // no auth
913 this._rfb_init_state
= 'SecurityResult';
915 case 'STDVVNCAUTH_': // VNC auth
916 this._rfb_auth_scheme
= 2;
917 return this._init_msg();
919 return this._fail("Unsupported server",
920 "Unsupported tiny auth scheme: " +
926 return this._fail("Unsupported server",
927 "No supported sub-auth types!");
930 _negotiate_authentication: function () {
931 switch (this._rfb_auth_scheme
) {
932 case 0: // connection failed
933 if (this._sock
.rQwait("auth reason", 4)) { return false; }
934 var strlen
= this._sock
.rQshift32();
935 var reason
= this._sock
.rQshiftStr(strlen
);
936 return this._fail("Authentication failure", reason
);
939 if (this._rfb_version
>= 3.8) {
940 this._rfb_init_state
= 'SecurityResult';
943 this._rfb_init_state
= 'ClientInitialisation';
944 return this._init_msg();
947 return this._negotiate_xvp_auth();
949 case 2: // VNC authentication
950 return this._negotiate_std_vnc_auth();
952 case 16: // TightVNC Security Type
953 return this._negotiate_tight_auth();
956 return this._fail("Unsupported server",
957 "Unsupported auth scheme: " +
958 this._rfb_auth_scheme
);
962 _handle_security_result: function () {
963 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
964 switch (this._sock
.rQshift32()) {
966 this._rfb_init_state
= 'ClientInitialisation';
967 Log
.Debug('Authentication OK');
968 return this._init_msg();
970 if (this._rfb_version
>= 3.8) {
971 var length
= this._sock
.rQshift32();
972 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
973 var reason
= this._sock
.rQshiftStr(length
);
974 return this._fail("Authentication failure", reason
);
976 return this._fail("Authentication failure");
979 return this._fail("Too many authentication attempts");
981 return this._fail("Unsupported server",
982 "Unknown SecurityResult");
986 _negotiate_server_init: function () {
987 if (this._sock
.rQwait("server initialization", 24)) { return false; }
990 var width
= this._sock
.rQshift16();
991 var height
= this._sock
.rQshift16();
994 var bpp
= this._sock
.rQshift8();
995 var depth
= this._sock
.rQshift8();
996 var big_endian
= this._sock
.rQshift8();
997 var true_color
= this._sock
.rQshift8();
999 var red_max
= this._sock
.rQshift16();
1000 var green_max
= this._sock
.rQshift16();
1001 var blue_max
= this._sock
.rQshift16();
1002 var red_shift
= this._sock
.rQshift8();
1003 var green_shift
= this._sock
.rQshift8();
1004 var blue_shift
= this._sock
.rQshift8();
1005 this._sock
.rQskipBytes(3); // padding
1007 // NB(directxman12): we don't want to call any callbacks or print messages until
1008 // *after* we're past the point where we could backtrack
1010 /* Connection name/title */
1011 var name_length = this._sock.rQshift32();
1012 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1013 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1015 if (this._rfb_tightvnc) {
1016 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1017 // In TightVNC mode, ServerInit message is extended
1018 var numServerMessages = this._sock.rQshift16();
1019 var numClientMessages = this._sock.rQshift16();
1020 var numEncodings = this._sock.rQshift16();
1021 this._sock.rQskipBytes(2); // padding
1023 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1024 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1026 // we don't actually do anything with the capability information that TIGHT sends,
1027 // so we just skip the all of this.
1029 // TIGHT server message capabilities
1030 this._sock.rQskipBytes(16 * numServerMessages);
1032 // TIGHT client message capabilities
1033 this._sock.rQskipBytes(16 * numClientMessages);
1035 // TIGHT encoding capabilities
1036 this._sock.rQskipBytes(16 * numEncodings);
1039 // NB(directxman12): these are down here so that we don't run them multiple times
1041 Log.Info("Screen: " + width + "x" + height +
1042 ", bpp: " + bpp + ", depth: " + depth +
1043 ", big_endian: " + big_endian +
1044 ", true_color: " + true_color +
1045 ", red_max: " + red_max +
1046 ", green_max: " + green_max +
1047 ", blue_max: " + blue_max +
1048 ", red_shift: " + red_shift +
1049 ", green_shift: " + green_shift +
1050 ", blue_shift: " + blue_shift);
1052 if (big_endian !== 0) {
1053 Log.Warn("Server native endian is not little endian");
1056 if (red_shift !== 16) {
1057 Log.Warn("Server native red-shift is not 16");
1060 if (blue_shift !== 0) {
1061 Log.Warn("Server native blue-shift is not 0");
1064 // we're past the point where we could backtrack, so it's safe to call this
1065 var event = new CustomEvent("desktopname",
1066 { detail: { name: this._fb_name } });
1067 this.dispatchEvent(event);
1069 this._resize(width, height);
1071 if (!this._viewOnly) { this._keyboard.grab(); }
1072 if (!this._viewOnly) { this._mouse.grab(); }
1074 this._fb_depth = 24;
1076 if (this._fb_name === "Intel(r) AMT KVM") {
1077 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1081 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1082 this._sendEncodings();
1083 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1085 this._timing.fbu_rt_start = (new Date()).getTime();
1086 this._timing.pixels = 0;
1088 // Cursor will be server side until the server decides to honor
1089 // our request and send over the cursor image
1090 this._display.disableLocalCursor();
1092 this._updateConnectionState('connected');
1096 _sendEncodings: function () {
1099 // In preference order
1100 encs.push(encodings.encodingCopyRect);
1101 // Only supported with full depth support
1102 if (this._fb_depth == 24) {
1103 encs.push(encodings.encodingTight);
1104 encs.push(encodings.encodingHextile);
1105 encs.push(encodings.encodingRRE);
1107 encs.push(encodings.encodingRaw);
1109 // Psuedo-encoding settings
1110 encs.push(encodings.pseudoEncodingTightPNG);
1111 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1112 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1114 encs.push(encodings.pseudoEncodingDesktopSize);
1115 encs.push(encodings.pseudoEncodingLastRect);
1116 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1117 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1118 encs.push(encodings.pseudoEncodingXvp);
1119 encs.push(encodings.pseudoEncodingFence);
1120 encs.push(encodings.pseudoEncodingContinuousUpdates);
1122 if (browserSupportsCursorURIs() &&
1123 !isTouchDevice && this._fb_depth == 24) {
1124 encs.push(encodings.pseudoEncodingCursor);
1127 RFB.messages.clientEncodings(this._sock, encs);
1130 /* RFB protocol initialization states:
1135 * ClientInitialization - not triggered by server message
1136 * ServerInitialization
1138 _init_msg: function () {
1139 switch (this._rfb_init_state
) {
1140 case 'ProtocolVersion':
1141 return this._negotiate_protocol_version();
1144 return this._negotiate_security();
1146 case 'Authentication':
1147 return this._negotiate_authentication();
1149 case 'SecurityResult':
1150 return this._handle_security_result();
1152 case 'ClientInitialisation':
1153 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1154 this._rfb_init_state
= 'ServerInitialisation';
1157 case 'ServerInitialisation':
1158 return this._negotiate_server_init();
1161 return this._fail("Internal error", "Unknown init state: " +
1162 this._rfb_init_state
);
1166 _handle_set_colour_map_msg: function () {
1167 Log
.Debug("SetColorMapEntries");
1169 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1172 _handle_server_cut_text: function () {
1173 Log
.Debug("ServerCutText");
1175 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1176 this._sock
.rQskipBytes(3); // Padding
1177 var length
= this._sock
.rQshift32();
1178 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1180 var text
= this._sock
.rQshiftStr(length
);
1182 if (this._viewOnly
) { return true; }
1184 var event
= new CustomEvent("clipboard",
1185 { detail
: { text
: text
} });
1186 this.dispatchEvent(event
);
1191 _handle_server_fence_msg: function() {
1192 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1193 this._sock
.rQskipBytes(3); // Padding
1194 var flags
= this._sock
.rQshift32();
1195 var length
= this._sock
.rQshift8();
1197 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1200 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1204 var payload
= this._sock
.rQshiftStr(length
);
1206 this._supportsFence
= true;
1211 * (1<<0) - BlockBefore
1212 * (1<<1) - BlockAfter
1217 if (!(flags
& (1<<31))) {
1218 return this._fail("Internal error",
1219 "Unexpected fence response");
1222 // Filter out unsupported flags
1223 // FIXME: support syncNext
1224 flags
&= (1<<0) | (1<<1);
1226 // BlockBefore and BlockAfter are automatically handled by
1227 // the fact that we process each incoming message
1229 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1234 _handle_xvp_msg: function () {
1235 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1236 this._sock
.rQskip8(); // Padding
1237 var xvp_ver
= this._sock
.rQshift8();
1238 var xvp_msg
= this._sock
.rQshift8();
1242 Log
.Error("XVP Operation Failed");
1245 this._rfb_xvp_ver
= xvp_ver
;
1246 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1247 this._setCapability("power", true);
1250 this._fail("Unexpected server message",
1251 "Illegal server XVP message " + xvp_msg
);
1258 _normal_msg: function () {
1261 if (this._FBU
.rects
> 0) {
1264 msg_type
= this._sock
.rQshift8();
1268 case 0: // FramebufferUpdate
1269 var ret
= this._framebufferUpdate();
1270 if (ret
&& !this._enabledContinuousUpdates
) {
1271 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1272 this._fb_width
, this._fb_height
);
1276 case 1: // SetColorMapEntries
1277 return this._handle_set_colour_map_msg();
1281 var event
= new CustomEvent("bell", { detail
: {} });
1282 this.dispatchEvent(event
);
1285 case 3: // ServerCutText
1286 return this._handle_server_cut_text();
1288 case 150: // EndOfContinuousUpdates
1289 var first
= !(this._supportsContinuousUpdates
);
1290 this._supportsContinuousUpdates
= true;
1291 this._enabledContinuousUpdates
= false;
1293 this._enabledContinuousUpdates
= true;
1294 this._updateContinuousUpdates();
1295 Log
.Info("Enabling continuous updates.");
1297 // FIXME: We need to send a framebufferupdaterequest here
1298 // if we add support for turning off continuous updates
1302 case 248: // ServerFence
1303 return this._handle_server_fence_msg();
1306 return this._handle_xvp_msg();
1309 this._fail("Unexpected server message", "Type:" + msg_type
);
1310 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1315 _onFlush: function() {
1316 this._flushing
= false;
1317 // Resume processing
1318 if (this._sock
.rQlen() > 0) {
1319 this._handle_message();
1323 _framebufferUpdate: function () {
1327 if (this._FBU
.rects
=== 0) {
1328 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1329 this._sock
.rQskip8(); // Padding
1330 this._FBU
.rects
= this._sock
.rQshift16();
1331 this._FBU
.bytes
= 0;
1332 this._timing
.cur_fbu
= 0;
1333 if (this._timing
.fbu_rt_start
> 0) {
1334 now
= (new Date()).getTime();
1335 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1338 // Make sure the previous frame is fully rendered first
1339 // to avoid building up an excessive queue
1340 if (this._display
.pending()) {
1341 this._flushing
= true;
1342 this._display
.flush();
1347 while (this._FBU
.rects
> 0) {
1348 if (this._rfb_connection_state
!== 'connected') { return false; }
1350 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1351 if (this._FBU
.bytes
=== 0) {
1352 if (this._sock
.rQwait("rect header", 12)) { return false; }
1353 /* New FramebufferUpdate */
1355 var hdr
= this._sock
.rQshiftBytes(12);
1356 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1357 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1358 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1359 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1360 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1361 (hdr
[10] << 8) + hdr
[11], 10);
1363 if (!this._encHandlers
[this._FBU
.encoding
]) {
1364 this._fail("Unexpected server message",
1365 "Unsupported encoding " +
1366 this._FBU
.encoding
);
1371 this._timing
.last_fbu
= (new Date()).getTime();
1373 ret
= this._encHandlers
[this._FBU
.encoding
]();
1375 now
= (new Date()).getTime();
1376 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1379 if (!(this._FBU
.encoding
in this._encStats
)) {
1380 this._encStats
[this._FBU
.encoding
] = [0, 0];
1382 this._encStats
[this._FBU
.encoding
][0]++;
1383 this._encStats
[this._FBU
.encoding
][1]++;
1384 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1387 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1388 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1389 this._timing
.fbu_rt_start
> 0) {
1390 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1391 this._timing
.full_fbu_cnt
++;
1392 Log
.Info("Timing of full FBU, curr: " +
1393 this._timing
.cur_fbu
+ ", total: " +
1394 this._timing
.full_fbu_total
+ ", cnt: " +
1395 this._timing
.full_fbu_cnt
+ ", avg: " +
1396 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1399 if (this._timing
.fbu_rt_start
> 0) {
1400 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1401 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1402 this._timing
.fbu_rt_cnt
++;
1403 Log
.Info("full FBU round-trip, cur: " +
1404 fbu_rt_diff
+ ", total: " +
1405 this._timing
.fbu_rt_total
+ ", cnt: " +
1406 this._timing
.fbu_rt_cnt
+ ", avg: " +
1407 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1408 this._timing
.fbu_rt_start
= 0;
1412 if (!ret
) { return ret
; } // need more data
1415 this._display
.flip();
1417 return true; // We finished this FBU
1420 _updateContinuousUpdates: function() {
1421 if (!this._enabledContinuousUpdates
) { return; }
1423 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1424 this._fb_width
, this._fb_height
);
1427 _resize: function(width
, height
) {
1428 this._fb_width
= width
;
1429 this._fb_height
= height
;
1431 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1433 this._display
.resize(this._fb_width
, this._fb_height
);
1435 var event
= new CustomEvent("fbresize",
1436 { detail
: { width
: this._fb_width
,
1437 height
: this._fb_height
} });
1438 this.dispatchEvent(event
);
1440 this._timing
.fbu_rt_start
= (new Date()).getTime();
1441 this._updateContinuousUpdates();
1444 _xvpOp: function (ver
, op
) {
1445 if (this._rfb_xvp_ver
< ver
) { return; }
1446 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
1447 RFB
.messages
.xvpOp(this._sock
, ver
, op
);
1451 Object
.assign(RFB
.prototype, EventTargetMixin
);
1455 keyEvent: function (sock
, keysym
, down
) {
1456 var buff
= sock
._sQ
;
1457 var offset
= sock
._sQlen
;
1459 buff
[offset
] = 4; // msg-type
1460 buff
[offset
+ 1] = down
;
1462 buff
[offset
+ 2] = 0;
1463 buff
[offset
+ 3] = 0;
1465 buff
[offset
+ 4] = (keysym
>> 24);
1466 buff
[offset
+ 5] = (keysym
>> 16);
1467 buff
[offset
+ 6] = (keysym
>> 8);
1468 buff
[offset
+ 7] = keysym
;
1474 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1475 function getRFBkeycode(xt_scancode
) {
1476 var upperByte
= (keycode
>> 8);
1477 var lowerByte
= (keycode
& 0x00ff);
1478 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1479 lowerByte
= lowerByte
| 0x80;
1485 var buff
= sock
._sQ
;
1486 var offset
= sock
._sQlen
;
1488 buff
[offset
] = 255; // msg-type
1489 buff
[offset
+ 1] = 0; // sub msg-type
1491 buff
[offset
+ 2] = (down
>> 8);
1492 buff
[offset
+ 3] = down
;
1494 buff
[offset
+ 4] = (keysym
>> 24);
1495 buff
[offset
+ 5] = (keysym
>> 16);
1496 buff
[offset
+ 6] = (keysym
>> 8);
1497 buff
[offset
+ 7] = keysym
;
1499 var RFBkeycode
= getRFBkeycode(keycode
);
1501 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1502 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1503 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1504 buff
[offset
+ 11] = RFBkeycode
;
1510 pointerEvent: function (sock
, x
, y
, mask
) {
1511 var buff
= sock
._sQ
;
1512 var offset
= sock
._sQlen
;
1514 buff
[offset
] = 5; // msg-type
1516 buff
[offset
+ 1] = mask
;
1518 buff
[offset
+ 2] = x
>> 8;
1519 buff
[offset
+ 3] = x
;
1521 buff
[offset
+ 4] = y
>> 8;
1522 buff
[offset
+ 5] = y
;
1528 // TODO(directxman12): make this unicode compatible?
1529 clientCutText: function (sock
, text
) {
1530 var buff
= sock
._sQ
;
1531 var offset
= sock
._sQlen
;
1533 buff
[offset
] = 6; // msg-type
1535 buff
[offset
+ 1] = 0; // padding
1536 buff
[offset
+ 2] = 0; // padding
1537 buff
[offset
+ 3] = 0; // padding
1539 var n
= text
.length
;
1541 buff
[offset
+ 4] = n
>> 24;
1542 buff
[offset
+ 5] = n
>> 16;
1543 buff
[offset
+ 6] = n
>> 8;
1544 buff
[offset
+ 7] = n
;
1546 for (var i
= 0; i
< n
; i
++) {
1547 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1550 sock
._sQlen
+= 8 + n
;
1554 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1555 var buff
= sock
._sQ
;
1556 var offset
= sock
._sQlen
;
1558 buff
[offset
] = 251; // msg-type
1559 buff
[offset
+ 1] = 0; // padding
1560 buff
[offset
+ 2] = width
>> 8; // width
1561 buff
[offset
+ 3] = width
;
1562 buff
[offset
+ 4] = height
>> 8; // height
1563 buff
[offset
+ 5] = height
;
1565 buff
[offset
+ 6] = 1; // number-of-screens
1566 buff
[offset
+ 7] = 0; // padding
1569 buff
[offset
+ 8] = id
>> 24; // id
1570 buff
[offset
+ 9] = id
>> 16;
1571 buff
[offset
+ 10] = id
>> 8;
1572 buff
[offset
+ 11] = id
;
1573 buff
[offset
+ 12] = 0; // x-position
1574 buff
[offset
+ 13] = 0;
1575 buff
[offset
+ 14] = 0; // y-position
1576 buff
[offset
+ 15] = 0;
1577 buff
[offset
+ 16] = width
>> 8; // width
1578 buff
[offset
+ 17] = width
;
1579 buff
[offset
+ 18] = height
>> 8; // height
1580 buff
[offset
+ 19] = height
;
1581 buff
[offset
+ 20] = flags
>> 24; // flags
1582 buff
[offset
+ 21] = flags
>> 16;
1583 buff
[offset
+ 22] = flags
>> 8;
1584 buff
[offset
+ 23] = flags
;
1590 clientFence: function (sock
, flags
, payload
) {
1591 var buff
= sock
._sQ
;
1592 var offset
= sock
._sQlen
;
1594 buff
[offset
] = 248; // msg-type
1596 buff
[offset
+ 1] = 0; // padding
1597 buff
[offset
+ 2] = 0; // padding
1598 buff
[offset
+ 3] = 0; // padding
1600 buff
[offset
+ 4] = flags
>> 24; // flags
1601 buff
[offset
+ 5] = flags
>> 16;
1602 buff
[offset
+ 6] = flags
>> 8;
1603 buff
[offset
+ 7] = flags
;
1605 var n
= payload
.length
;
1607 buff
[offset
+ 8] = n
; // length
1609 for (var i
= 0; i
< n
; i
++) {
1610 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1613 sock
._sQlen
+= 9 + n
;
1617 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1618 var buff
= sock
._sQ
;
1619 var offset
= sock
._sQlen
;
1621 buff
[offset
] = 150; // msg-type
1622 buff
[offset
+ 1] = enable
; // enable-flag
1624 buff
[offset
+ 2] = x
>> 8; // x
1625 buff
[offset
+ 3] = x
;
1626 buff
[offset
+ 4] = y
>> 8; // y
1627 buff
[offset
+ 5] = y
;
1628 buff
[offset
+ 6] = width
>> 8; // width
1629 buff
[offset
+ 7] = width
;
1630 buff
[offset
+ 8] = height
>> 8; // height
1631 buff
[offset
+ 9] = height
;
1637 pixelFormat: function (sock
, depth
, true_color
) {
1638 var buff
= sock
._sQ
;
1639 var offset
= sock
._sQlen
;
1645 } else if (depth
> 8) {
1651 bits
= Math
.floor(depth
/3);
1653 buff
[offset
] = 0; // msg-type
1655 buff
[offset
+ 1] = 0; // padding
1656 buff
[offset
+ 2] = 0; // padding
1657 buff
[offset
+ 3] = 0; // padding
1659 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1660 buff
[offset
+ 5] = depth
; // depth
1661 buff
[offset
+ 6] = 0; // little-endian
1662 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1664 buff
[offset
+ 8] = 0; // red-max
1665 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1667 buff
[offset
+ 10] = 0; // green-max
1668 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1670 buff
[offset
+ 12] = 0; // blue-max
1671 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1673 buff
[offset
+ 14] = bits
* 2; // red-shift
1674 buff
[offset
+ 15] = bits
* 1; // green-shift
1675 buff
[offset
+ 16] = bits
* 0; // blue-shift
1677 buff
[offset
+ 17] = 0; // padding
1678 buff
[offset
+ 18] = 0; // padding
1679 buff
[offset
+ 19] = 0; // padding
1685 clientEncodings: function (sock
, encodings
) {
1686 var buff
= sock
._sQ
;
1687 var offset
= sock
._sQlen
;
1689 buff
[offset
] = 2; // msg-type
1690 buff
[offset
+ 1] = 0; // padding
1692 buff
[offset
+ 2] = encodings
.length
>> 8;
1693 buff
[offset
+ 3] = encodings
.length
;
1695 var i
, j
= offset
+ 4;
1696 for (i
= 0; i
< encodings
.length
; i
++) {
1697 var enc
= encodings
[i
];
1698 buff
[j
] = enc
>> 24;
1699 buff
[j
+ 1] = enc
>> 16;
1700 buff
[j
+ 2] = enc
>> 8;
1706 sock
._sQlen
+= j
- offset
;
1710 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1711 var buff
= sock
._sQ
;
1712 var offset
= sock
._sQlen
;
1714 if (typeof(x
) === "undefined") { x
= 0; }
1715 if (typeof(y
) === "undefined") { y
= 0; }
1717 buff
[offset
] = 3; // msg-type
1718 buff
[offset
+ 1] = incremental
? 1 : 0;
1720 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1721 buff
[offset
+ 3] = x
& 0xFF;
1723 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1724 buff
[offset
+ 5] = y
& 0xFF;
1726 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1727 buff
[offset
+ 7] = w
& 0xFF;
1729 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1730 buff
[offset
+ 9] = h
& 0xFF;
1736 xvpOp: function (sock
, ver
, op
) {
1737 var buff
= sock
._sQ
;
1738 var offset
= sock
._sQlen
;
1740 buff
[offset
] = 250; // msg-type
1741 buff
[offset
+ 1] = 0; // padding
1743 buff
[offset
+ 2] = ver
;
1744 buff
[offset
+ 3] = op
;
1751 RFB
.genDES = function (password
, challenge
) {
1753 for (var i
= 0; i
< password
.length
; i
++) {
1754 passwd
.push(password
.charCodeAt(i
));
1756 return (new DES(passwd
)).encrypt(challenge
);
1759 RFB
.encodingHandlers
= {
1761 if (this._FBU
.lines
=== 0) {
1762 this._FBU
.lines
= this._FBU
.height
;
1765 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1766 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1767 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1768 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1769 var curr_height
= Math
.min(this._FBU
.lines
,
1770 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1771 var data
= this._sock
.get_rQ();
1772 var index
= this._sock
.get_rQi();
1773 if (this._fb_depth
== 8) {
1774 var pixels
= this._FBU
.width
* curr_height
1775 var newdata
= new Uint8Array(pixels
* 4);
1777 for (i
= 0;i
< pixels
;i
++) {
1778 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1779 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1780 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1781 newdata
[i
* 4 + 4] = 0;
1786 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1787 curr_height
, data
, index
);
1788 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1789 this._FBU
.lines
-= curr_height
;
1791 if (this._FBU
.lines
> 0) {
1792 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1795 this._FBU
.bytes
= 0;
1801 COPYRECT: function () {
1802 this._FBU
.bytes
= 4;
1803 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1804 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1805 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1809 this._FBU
.bytes
= 0;
1815 if (this._FBU
.subrects
=== 0) {
1816 this._FBU
.bytes
= 4 + 4;
1817 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1818 this._FBU
.subrects
= this._sock
.rQshift32();
1819 color
= this._sock
.rQshiftBytes(4); // Background
1820 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1823 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1824 color
= this._sock
.rQshiftBytes(4);
1825 var x
= this._sock
.rQshift16();
1826 var y
= this._sock
.rQshift16();
1827 var width
= this._sock
.rQshift16();
1828 var height
= this._sock
.rQshift16();
1829 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1830 this._FBU
.subrects
--;
1833 if (this._FBU
.subrects
> 0) {
1834 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1835 this._FBU
.bytes
= (4 + 8) * chunk
;
1838 this._FBU
.bytes
= 0;
1844 HEXTILE: function () {
1845 var rQ
= this._sock
.get_rQ();
1846 var rQi
= this._sock
.get_rQi();
1848 if (this._FBU
.tiles
=== 0) {
1849 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1850 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1851 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1852 this._FBU
.tiles
= this._FBU
.total_tiles
;
1855 while (this._FBU
.tiles
> 0) {
1856 this._FBU
.bytes
= 1;
1857 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1858 var subencoding
= rQ
[rQi
]; // Peek
1859 if (subencoding
> 30) { // Raw
1860 this._fail("Unexpected server message",
1861 "Illegal hextile subencoding: " + subencoding
);
1866 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1867 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1868 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1869 var x
= this._FBU
.x
+ tile_x
* 16;
1870 var y
= this._FBU
.y
+ tile_y
* 16;
1871 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1872 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1874 // Figure out how much we are expecting
1875 if (subencoding
& 0x01) { // Raw
1876 this._FBU
.bytes
+= w
* h
* 4;
1878 if (subencoding
& 0x02) { // Background
1879 this._FBU
.bytes
+= 4;
1881 if (subencoding
& 0x04) { // Foreground
1882 this._FBU
.bytes
+= 4;
1884 if (subencoding
& 0x08) { // AnySubrects
1885 this._FBU
.bytes
++; // Since we aren't shifting it off
1886 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1887 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1888 if (subencoding
& 0x10) { // SubrectsColoured
1889 this._FBU
.bytes
+= subrects
* (4 + 2);
1891 this._FBU
.bytes
+= subrects
* 2;
1896 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1898 // We know the encoding and have a whole tile
1899 this._FBU
.subencoding
= rQ
[rQi
];
1901 if (this._FBU
.subencoding
=== 0) {
1902 if (this._FBU
.lastsubencoding
& 0x01) {
1903 // Weird: ignore blanks are RAW
1904 Log
.Debug(" Ignoring blank after RAW");
1906 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1908 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1909 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1910 rQi
+= this._FBU
.bytes
- 1;
1912 if (this._FBU
.subencoding
& 0x02) { // Background
1913 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1916 if (this._FBU
.subencoding
& 0x04) { // Foreground
1917 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1921 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1922 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1926 for (var s
= 0; s
< subrects
; s
++) {
1928 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1929 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1932 color
= this._FBU
.foreground
;
1937 var sy
= (xy
& 0x0f);
1941 var sw
= (wh
>> 4) + 1;
1942 var sh
= (wh
& 0x0f) + 1;
1944 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1947 this._display
.finishTile();
1949 this._sock
.set_rQi(rQi
);
1950 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
1951 this._FBU
.bytes
= 0;
1955 if (this._FBU
.tiles
=== 0) {
1962 TIGHT: function () {
1963 this._FBU
.bytes
= 1; // compression-control byte
1964 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
1966 var checksum = function (data
) {
1968 for (var i
= 0; i
< data
.length
; i
++) {
1970 if (sum
> 65536) sum
-= 65536;
1975 var resetStreams
= 0;
1977 var decompress = function (data
, expected
) {
1978 for (var i
= 0; i
< 4; i
++) {
1979 if ((resetStreams
>> i
) & 1) {
1980 this._FBU
.zlibs
[i
].reset();
1981 Log
.Info("Reset zlib stream " + i
);
1985 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
1986 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
1987 /*if (uncompressed.status !== 0) {
1988 Log.Error("Invalid data in zlib stream");
1991 //return uncompressed.data;
1992 return uncompressed
;
1995 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
1996 // Convert indexed (palette based) image data to RGB
1997 // TODO: reduce number of calculations inside loop
1998 var dest
= this._destBuff
;
1999 var w
= Math
.floor((width
+ 7) / 8);
2000 var w1
= Math
.floor(width
/ 8);
2002 /*for (var y = 0; y < height; y++) {
2004 var yoffset = y * width;
2005 var ybitoffset = y * w;
2006 var xoffset, targetbyte;
2007 for (x = 0; x < w1; x++) {
2008 xoffset = yoffset + x * 8;
2009 targetbyte = data[ybitoffset + x];
2010 for (b = 7; b >= 0; b--) {
2011 dp = (xoffset + 7 - b) * 3;
2012 sp = (targetbyte >> b & 1) * 3;
2013 dest[dp] = palette[sp];
2014 dest[dp + 1] = palette[sp + 1];
2015 dest[dp + 2] = palette[sp + 2];
2019 xoffset = yoffset + x * 8;
2020 targetbyte = data[ybitoffset + x];
2021 for (b = 7; b >= 8 - width % 8; b--) {
2022 dp = (xoffset + 7 - b) * 3;
2023 sp = (targetbyte >> b & 1) * 3;
2024 dest[dp] = palette[sp];
2025 dest[dp + 1] = palette[sp + 1];
2026 dest[dp + 2] = palette[sp + 2];
2030 for (var y
= 0; y
< height
; y
++) {
2032 for (x
= 0; x
< w1
; x
++) {
2033 for (b
= 7; b
>= 0; b
--) {
2034 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2035 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2036 dest
[dp
] = palette
[sp
];
2037 dest
[dp
+ 1] = palette
[sp
+ 1];
2038 dest
[dp
+ 2] = palette
[sp
+ 2];
2043 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2044 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2045 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2046 dest
[dp
] = palette
[sp
];
2047 dest
[dp
+ 1] = palette
[sp
+ 1];
2048 dest
[dp
+ 2] = palette
[sp
+ 2];
2056 var indexedToRGBX = function (data
, palette
, width
, height
) {
2057 // Convert indexed (palette based) image data to RGB
2058 var dest
= this._destBuff
;
2059 var total
= width
* height
* 4;
2060 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2061 var sp
= data
[j
] * 3;
2062 dest
[i
] = palette
[sp
];
2063 dest
[i
+ 1] = palette
[sp
+ 1];
2064 dest
[i
+ 2] = palette
[sp
+ 2];
2071 var rQi
= this._sock
.get_rQi();
2072 var rQ
= this._sock
.rQwhole();
2074 var cl_header
, cl_data
;
2076 var handlePalette = function () {
2077 var numColors
= rQ
[rQi
+ 2] + 1;
2078 var paletteSize
= numColors
* 3;
2079 this._FBU
.bytes
+= paletteSize
;
2080 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2082 var bpp
= (numColors
<= 2) ? 1 : 8;
2083 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2085 if (rowSize
* this._FBU
.height
< 12) {
2088 cl_data
= rowSize
* this._FBU
.height
;
2089 //clength = [0, rowSize * this._FBU.height];
2091 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2092 var cl_offset
= rQi
+ 3 + paletteSize
;
2095 cl_data
+= rQ
[cl_offset
] & 0x7f;
2096 if (rQ
[cl_offset
] & 0x80) {
2098 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2099 if (rQ
[cl_offset
+ 1] & 0x80) {
2101 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2104 // end inline getTightCLength
2107 this._FBU
.bytes
+= cl_header
+ cl_data
;
2108 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2110 // Shift ctl, filter id, num colors, palette entries, and clength off
2111 this._sock
.rQskipBytes(3);
2112 //var palette = this._sock.rQshiftBytes(paletteSize);
2113 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2114 this._sock
.rQskipBytes(cl_header
);
2117 data
= this._sock
.rQshiftBytes(cl_data
);
2119 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2122 // Convert indexed (palette based) image data to RGB
2124 if (numColors
== 2) {
2125 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2126 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2128 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2129 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2136 var handleCopy = function () {
2138 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2139 if (uncompressedSize
< 12) {
2142 cl_data
= uncompressedSize
;
2144 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2145 var cl_offset
= rQi
+ 1;
2148 cl_data
+= rQ
[cl_offset
] & 0x7f;
2149 if (rQ
[cl_offset
] & 0x80) {
2151 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2152 if (rQ
[cl_offset
+ 1] & 0x80) {
2154 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2157 // end inline getTightCLength
2159 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2160 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2162 // Shift ctl, clength off
2163 this._sock
.rQshiftBytes(1 + cl_header
);
2166 data
= this._sock
.rQshiftBytes(cl_data
);
2168 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2171 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2176 var ctl
= this._sock
.rQpeek8();
2178 // Keep tight reset bits
2179 resetStreams
= ctl
& 0xF;
2181 // Figure out filter
2183 streamId
= ctl
& 0x3;
2185 if (ctl
=== 0x08) cmode
= "fill";
2186 else if (ctl
=== 0x09) cmode
= "jpeg";
2187 else if (ctl
=== 0x0A) cmode
= "png";
2188 else if (ctl
& 0x04) cmode
= "filter";
2189 else if (ctl
< 0x04) cmode
= "copy";
2190 else return this._fail("Unexpected server message",
2191 "Illegal tight compression received, " +
2195 // fill use depth because TPIXELs drop the padding byte
2196 case "fill": // TPIXEL
2197 this._FBU
.bytes
+= 3;
2199 case "jpeg": // max clength
2200 this._FBU
.bytes
+= 3;
2202 case "png": // max clength
2203 this._FBU
.bytes
+= 3;
2205 case "filter": // filter id + num colors if palette
2206 this._FBU
.bytes
+= 2;
2212 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2214 // Determine FBU.bytes
2218 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, [rQ
[rQi
+ 3], rQ
[rQi
+ 2], rQ
[rQi
+ 1]], false);
2219 this._sock
.rQskipBytes(4);
2223 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2224 var cl_offset
= rQi
+ 1;
2227 cl_data
+= rQ
[cl_offset
] & 0x7f;
2228 if (rQ
[cl_offset
] & 0x80) {
2230 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2231 if (rQ
[cl_offset
+ 1] & 0x80) {
2233 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2236 // end inline getTightCLength
2237 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2238 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2240 // We have everything, render it
2241 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2242 data
= this._sock
.rQshiftBytes(cl_data
);
2243 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2246 var filterId
= rQ
[rQi
+ 1];
2247 if (filterId
=== 1) {
2248 if (!handlePalette()) { return false; }
2250 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2251 // Filter 2, Gradient is valid but not use if jpeg is enabled
2252 this._fail("Unexpected server message",
2253 "Unsupported tight subencoding received, " +
2254 "filter: " + filterId
);
2258 if (!handleCopy()) { return false; }
2263 this._FBU
.bytes
= 0;
2269 last_rect: function () {
2270 this._FBU
.rects
= 0;
2274 ExtendedDesktopSize: function () {
2275 this._FBU
.bytes
= 1;
2276 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2278 this._supportsSetDesktopSize
= true;
2279 this._setCapability("resize", true);
2281 var number_of_screens
= this._sock
.rQpeek8();
2283 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2284 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2286 this._sock
.rQskipBytes(1); // number-of-screens
2287 this._sock
.rQskipBytes(3); // padding
2289 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2290 // Save the id and flags of the first screen
2292 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2293 this._sock
.rQskipBytes(2); // x-position
2294 this._sock
.rQskipBytes(2); // y-position
2295 this._sock
.rQskipBytes(2); // width
2296 this._sock
.rQskipBytes(2); // height
2297 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2299 this._sock
.rQskipBytes(16);
2304 * The x-position indicates the reason for the change:
2306 * 0 - server resized on its own
2307 * 1 - this client requested the resize
2308 * 2 - another client requested the resize
2311 // We need to handle errors when we requested the resize.
2312 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2314 // The y-position indicates the status code from the server
2315 switch (this._FBU
.y
) {
2317 msg
= "Resize is administratively prohibited";
2320 msg
= "Out of resources";
2323 msg
= "Invalid screen layout";
2326 msg
= "Unknown reason";
2329 Log
.Warn("Server did not accept the resize request: "
2332 this._resize(this._FBU
.width
, this._FBU
.height
);
2335 this._FBU
.bytes
= 0;
2336 this._FBU
.rects
-= 1;
2340 DesktopSize: function () {
2341 this._resize(this._FBU
.width
, this._FBU
.height
);
2342 this._FBU
.bytes
= 0;
2343 this._FBU
.rects
-= 1;
2347 Cursor: function () {
2348 Log
.Debug(">> set_cursor");
2349 var x
= this._FBU
.x
; // hotspot-x
2350 var y
= this._FBU
.y
; // hotspot-y
2351 var w
= this._FBU
.width
;
2352 var h
= this._FBU
.height
;
2354 var pixelslength
= w
* h
* 4;
2355 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2357 this._FBU
.bytes
= pixelslength
+ masklength
;
2358 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2360 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2361 this._sock
.rQshiftBytes(masklength
),
2364 this._FBU
.bytes
= 0;
2367 Log
.Debug("<< set_cursor");
2371 QEMUExtendedKeyEvent: function () {
2374 // Old Safari doesn't support creating keyboard events
2376 var keyboardEvent
= document
.createEvent("keyboardEvent");
2377 if (keyboardEvent
.code
!== undefined) {
2378 this._qemuExtKeyEventSupported
= true;