2 * noVNC: HTML5 VNC client
3 * Copyright (C) 2012 Joel Martin
4 * Copyright (C) 2016 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)
14 * import Util from "./util";
15 * import Display from "./display";
16 * import { Keyboard, Mouse } from "./input/devices"
17 * import Websock from "./websock"
18 * import Base64 from "./base64";
19 * import DES from "./des";
20 * import KeyTable from "./input/keysym";
21 * import XtScancode from "./input/xtscancodes";
22 * import Inflator from "./inflator.mod";
24 /*jslint white: false, browser: true */
25 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
27 /* [module] export default */ function RFB(defaults
) {
34 this._rfb_port
= 5900;
35 this._rfb_password
= '';
38 this._rfb_connection_state
= '';
39 this._rfb_init_state
= '';
40 this._rfb_version
= 0;
41 this._rfb_max_version
= 3.8;
42 this._rfb_auth_scheme
= '';
43 this._rfb_disconnect_reason
= "";
45 this._rfb_tightvnc
= false;
46 this._rfb_xvp_ver
= 0;
48 // In preference order
57 // Psuedo-encoding settings
59 //['JPEG_quality_lo', -32 ],
60 ['JPEG_quality_med', -26 ],
61 //['JPEG_quality_hi', -23 ],
62 //['compress_lo', -255 ],
63 ['compress_hi', -247 ],
65 ['DesktopSize', -223 ],
68 ['QEMUExtendedKeyEvent', -258 ],
69 ['ExtendedDesktopSize', -308 ],
72 ['ContinuousUpdates', -313 ]
75 this._encHandlers
= {};
79 this._sock
= null; // Websock object
80 this._display
= null; // Display object
81 this._flushing
= false; // Display flushing state
82 this._keyboard
= null; // Keyboard input handler object
83 this._mouse
= null; // Mouse input handler object
84 this._disconnTimer
= null; // disconnection timer
86 this._supportsFence
= false;
88 this._supportsContinuousUpdates
= false;
89 this._enabledContinuousUpdates
= false;
91 // Frame buffer update state
105 zlib
: [] // TIGHT zlib streams
114 this._destBuff
= null;
115 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
117 this._rre_chunk_sz
= 100;
132 this._supportsSetDesktopSize
= false;
134 this._screen_flags
= 0;
137 this._mouse_buttonMask
= 0;
138 this._mouse_arr
= [];
139 this._viewportDragging
= false;
140 this._viewportDragPos
= {};
141 this._viewportHasMoved
= false;
143 // QEMU Extended Key Event support - default to false
144 this._qemuExtKeyEventSupported
= false;
146 // set the default value on user-facing properties
147 Util
.set_defaults(this, defaults
, {
148 'target': 'null', // VNC display rendering Canvas object
149 'focusContainer': document
, // DOM element that captures keyboard input
150 'encrypt': false, // Use TLS/SSL/wss encryption
151 'true_color': true, // Request true color pixel data
152 'local_cursor': false, // Request locally rendered cursor
153 'shared': true, // Request shared mode
154 'view_only': false, // Disable client mouse/keyboard
155 'xvp_password_sep': '@', // Separator for XVP password fields
156 'disconnectTimeout': 3, // Time (s) to wait for disconnection
157 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
158 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
159 'viewportDrag': false, // Move the viewport on mouse drags
161 // Callback functions
162 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
163 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
164 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
165 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
166 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
167 'onBell': function () { }, // onBell(rfb): RFB Bell message received
168 'onFBUReceive': function () { }, // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
169 'onFBUComplete': function () { }, // onFBUComplete(rfb, fbu): RFB FBU received and processed
170 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
171 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
172 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
176 Util
.Debug(">> RFB.constructor");
178 // populate encHandlers with bound versions
179 Object
.keys(RFB
.encodingHandlers
).forEach(function (encName
) {
180 this._encHandlers
[encName
] = RFB
.encodingHandlers
[encName
].bind(this);
183 // Create lookup tables based on encoding number
184 for (var i
= 0; i
< this._encodings
.length
; i
++) {
185 this._encHandlers
[this._encodings
[i
][1]] = this._encHandlers
[this._encodings
[i
][0]];
186 this._encNames
[this._encodings
[i
][1]] = this._encodings
[i
][0];
187 this._encStats
[this._encodings
[i
][1]] = [0, 0];
190 // NB: nothing that needs explicit teardown should be done
191 // before this point, since this can throw an exception
193 this._display
= new Display({target
: this._target
,
194 onFlush
: this._onFlush
.bind(this)});
196 Util
.Error("Display exception: " + exc
);
200 this._keyboard
= new Keyboard({target
: this._focusContainer
,
201 onKeyPress
: this._handleKeyPress
.bind(this)});
203 this._mouse
= new Mouse({target
: this._target
,
204 onMouseButton
: this._handleMouseButton
.bind(this),
205 onMouseMove
: this._handleMouseMove
.bind(this),
206 notify
: this._keyboard
.sync
.bind(this._keyboard
)});
208 this._sock
= new Websock();
209 this._sock
.on('message', this._handle_message
.bind(this));
210 this._sock
.on('open', function () {
211 if ((this._rfb_connection_state
=== 'connecting') &&
212 (this._rfb_init_state
=== '')) {
213 this._rfb_init_state
= 'ProtocolVersion';
214 Util
.Debug("Starting VNC handshake");
216 this._fail("Got unexpected WebSocket connection");
219 this._sock
.on('close', function (e
) {
220 Util
.Warn("WebSocket on-close event");
223 msg
= " (code: " + e
.code
;
225 msg
+= ", reason: " + e
.reason
;
229 switch (this._rfb_connection_state
) {
230 case 'disconnecting':
231 this._updateConnectionState('disconnected');
234 this._fail('Failed to connect to server' + msg
);
237 Util
.Error("Received onclose while disconnected" + msg
);
240 this._fail("Server disconnected" + msg
);
243 this._sock
.off('close');
245 this._sock
.on('error', function (e
) {
246 Util
.Warn("WebSocket on-error event");
252 var rmode
= this._display
.get_render_mode();
253 Util
.Info("Using native WebSockets, render mode: " + rmode
);
255 Util
.Debug("<< RFB.constructor");
261 connect: function (host
, port
, password
, path
) {
262 this._rfb_host
= host
;
263 this._rfb_port
= port
;
264 this._rfb_password
= (password
!== undefined) ? password
: "";
265 this._rfb_path
= (path
!== undefined) ? path
: "";
267 if (!this._rfb_host
|| !this._rfb_port
) {
269 Util
.Localisation
.get("Must set host and port"));
272 this._rfb_init_state
= '';
273 this._updateConnectionState('connecting');
277 disconnect: function () {
278 this._updateConnectionState('disconnecting');
279 this._sock
.off('error');
280 this._sock
.off('message');
281 this._sock
.off('open');
284 sendPassword: function (passwd
) {
285 this._rfb_password
= passwd
;
286 setTimeout(this._init_msg
.bind(this), 0);
289 sendCtrlAltDel: function () {
290 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
291 Util
.Info("Sending Ctrl-Alt-Del");
293 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Control_L
, 1);
294 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Alt_L
, 1);
295 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Delete
, 1);
296 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Delete
, 0);
297 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Alt_L
, 0);
298 RFB
.messages
.keyEvent(this._sock
, KeyTable
.XK_Control_L
, 0);
302 xvpOp: function (ver
, op
) {
303 if (this._rfb_xvp_ver
< ver
) { return false; }
304 Util
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
305 this._sock
.send_string("\xFA\x00" + String
.fromCharCode(ver
) + String
.fromCharCode(op
));
309 xvpShutdown: function () {
310 return this.xvpOp(1, 2);
313 xvpReboot: function () {
314 return this.xvpOp(1, 3);
317 xvpReset: function () {
318 return this.xvpOp(1, 4);
321 // Send a key press. If 'down' is not specified then send a down key
322 // followed by an up key.
323 sendKey: function (code
, down
) {
324 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
325 if (typeof down
!== 'undefined') {
326 Util
.Info("Sending key code (" + (down
? "down" : "up") + "): " + code
);
327 RFB
.messages
.keyEvent(this._sock
, code
, down
? 1 : 0);
329 Util
.Info("Sending key code (down + up): " + code
);
330 RFB
.messages
.keyEvent(this._sock
, code
, 1);
331 RFB
.messages
.keyEvent(this._sock
, code
, 0);
336 clipboardPasteFrom: function (text
) {
337 if (this._rfb_connection_state
!== 'connected') { return; }
338 RFB
.messages
.clientCutText(this._sock
, text
);
341 // Requests a change of remote desktop size. This message is an extension
342 // and may only be sent if we have received an ExtendedDesktopSize message
343 requestDesktopSize: function (width
, height
) {
344 if (this._rfb_connection_state
!== 'connected' ||
349 if (this._supportsSetDesktopSize
) {
350 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
351 this._screen_id
, this._screen_flags
);
362 _connect: function () {
363 Util
.Debug(">> RFB.connect");
366 if (typeof UsingSocketIO
!== 'undefined') {
369 uri
= this._encrypt
? 'wss' : 'ws';
372 uri
+= '://' + this._rfb_host
+ ':' + this._rfb_port
+ '/' + this._rfb_path
;
373 Util
.Info("connecting to " + uri
);
375 this._sock
.open(uri
, this._wsProtocols
);
377 Util
.Debug("<< RFB.connect");
380 _init_vars: function () {
383 this._FBU
.subrects
= 0; // RRE and HEXTILE
384 this._FBU
.lines
= 0; // RAW
385 this._FBU
.tiles
= 0; // HEXTILE
386 this._FBU
.zlibs
= []; // TIGHT zlib encoders
387 this._mouse_buttonMask
= 0;
388 this._mouse_arr
= [];
389 this._rfb_tightvnc
= false;
391 // Clear the per connection encoding stats
393 for (i
= 0; i
< this._encodings
.length
; i
++) {
394 this._encStats
[this._encodings
[i
][1]][0] = 0;
397 for (i
= 0; i
< 4; i
++) {
398 this._FBU
.zlibs
[i
] = new Inflator
.Inflate();
402 _print_stats: function () {
403 Util
.Info("Encoding stats for this connection:");
405 for (i
= 0; i
< this._encodings
.length
; i
++) {
406 s
= this._encStats
[this._encodings
[i
][1]];
407 if (s
[0] + s
[1] > 0) {
408 Util
.Info(" " + this._encodings
[i
][0] + ": " + s
[0] + " rects");
412 Util
.Info("Encoding stats since page load:");
413 for (i
= 0; i
< this._encodings
.length
; i
++) {
414 s
= this._encStats
[this._encodings
[i
][1]];
415 Util
.Info(" " + this._encodings
[i
][0] + ": " + s
[1] + " rects");
419 _cleanup: function () {
420 if (this._display
&& this._display
.get_context()) {
421 if (!this._view_only
) { this._keyboard
.ungrab(); }
422 if (!this._view_only
) { this._mouse
.ungrab(); }
423 this._display
.defaultCursor();
424 if (Util
.get_logging() !== 'debug') {
425 // Show noVNC logo on load and when disconnected, unless in
427 this._display
.clear();
437 * disconnected - permanent state
439 _updateConnectionState: function (state
) {
440 var oldstate
= this._rfb_connection_state
;
442 if (state
=== oldstate
) {
443 Util
.Debug("Already in state '" + state
+ "', ignoring");
447 // The 'disconnected' state is permanent for each RFB object
448 if (oldstate
=== 'disconnected') {
449 Util
.Error("Tried changing state of a disconnected RFB object");
453 this._rfb_connection_state
= state
;
455 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
458 if (this._disconnTimer
&& state
!== 'disconnecting') {
459 Util
.Debug("Clearing disconnect timer");
460 clearTimeout(this._disconnTimer
);
461 this._disconnTimer
= null;
462 this._sock
.off('close'); // make sure we don't get a double event
465 this._onUpdateState(this, state
, oldstate
);
468 if (oldstate
!== 'connecting') {
469 Util
.Error("Bad transition to connected state, " +
470 "previous connection state: " + oldstate
);
476 if (oldstate
!== 'disconnecting') {
477 Util
.Error("Bad transition to disconnected state, " +
478 "previous connection state: " + oldstate
);
482 if (this._rfb_disconnect_reason
!== "") {
483 this._onDisconnected(this, this._rfb_disconnect_reason
);
485 // No reason means clean disconnect
486 this._onDisconnected(this);
493 // WebSocket.onopen transitions to the RFB init states
497 case 'disconnecting':
499 this._sock
.close(); // transitions to 'disconnected'
501 this._disconnTimer
= setTimeout(function () {
502 this._rfb_disconnect_reason
= "Disconnect timeout";
503 this._updateConnectionState('disconnected');
504 }.bind(this), this._disconnectTimeout
* 1000);
510 Util
.Error("Unknown connection state: " + state
);
515 _fail: function (msg
) {
516 switch (this._rfb_connection_state
) {
517 case 'disconnecting':
518 Util
.Error("Error while disconnecting: " + msg
);
521 Util
.Error("Error while connected: " + msg
);
524 Util
.Error("Error while connecting: " + msg
);
527 Util
.Error("RFB error: " + msg
);
530 this._rfb_disconnect_reason
= msg
;
531 this._updateConnectionState('disconnecting');
536 * Send a notification to the UI. Valid levels are:
537 * 'normal'|'warn'|'error'
539 * NOTE: Options could be added in the future.
540 * NOTE: If this function is called multiple times, remember that the
541 * interface could be only showing the latest notification.
543 _notification: function(msg
, level
, options
) {
548 Util
.Debug("Notification[" + level
+ "]:" + msg
);
551 Util
.Error("Invalid notification level: " + level
);
556 this._onNotification(this, msg
, level
, options
);
558 this._onNotification(this, msg
, level
);
562 _handle_message: function () {
563 if (this._sock
.rQlen() === 0) {
564 Util
.Warn("handle_message called on an empty receive queue");
568 switch (this._rfb_connection_state
) {
570 Util
.Error("Got data while disconnected");
574 if (this._flushing
) {
577 if (!this._normal_msg()) {
580 if (this._sock
.rQlen() === 0) {
591 _handleKeyPress: function (keyevent
) {
592 if (this._view_only
) { return; } // View only, skip keyboard, events
594 var down
= (keyevent
.type
== 'keydown');
595 if (this._qemuExtKeyEventSupported
) {
596 var scancode
= XtScancode
[keyevent
.code
];
598 var keysym
= keyevent
.keysym
;
599 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
601 Util
.Error('Unable to find a xt scancode for code = ' + keyevent
.code
);
604 keysym
= keyevent
.keysym
.keysym
;
605 RFB
.messages
.keyEvent(this._sock
, keysym
, down
);
609 _handleMouseButton: function (x
, y
, down
, bmask
) {
611 this._mouse_buttonMask
|= bmask
;
613 this._mouse_buttonMask
^= bmask
;
616 if (this._viewportDrag
) {
617 if (down
&& !this._viewportDragging
) {
618 this._viewportDragging
= true;
619 this._viewportDragPos
= {'x': x
, 'y': y
};
621 // Skip sending mouse events
624 this._viewportDragging
= false;
626 // If the viewport didn't actually move, then treat as a mouse click event
627 // Send the button down event here, as the button up event is sent at the end of this function
628 if (!this._viewportHasMoved
&& !this._view_only
) {
629 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
631 this._viewportHasMoved
= false;
635 if (this._view_only
) { return; } // View only, skip mouse events
637 if (this._rfb_connection_state
!== 'connected') { return; }
638 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
641 _handleMouseMove: function (x
, y
) {
642 if (this._viewportDragging
) {
643 var deltaX
= this._viewportDragPos
.x
- x
;
644 var deltaY
= this._viewportDragPos
.y
- y
;
646 // The goal is to trigger on a certain physical width, the
647 // devicePixelRatio brings us a bit closer but is not optimal.
648 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
650 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
651 Math
.abs(deltaY
) > dragThreshold
)) {
652 this._viewportHasMoved
= true;
654 this._viewportDragPos
= {'x': x
, 'y': y
};
655 this._display
.viewportChangePos(deltaX
, deltaY
);
658 // Skip sending mouse events
662 if (this._view_only
) { return; } // View only, skip mouse events
664 if (this._rfb_connection_state
!== 'connected') { return; }
665 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
670 _negotiate_protocol_version: function () {
671 if (this._sock
.rQlen() < 12) {
672 return this._fail("Incomplete protocol version");
675 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
676 Util
.Info("Server ProtocolVersion: " + sversion
);
679 case "000.000": // UltraVNC repeater
683 case "003.006": // UltraVNC
684 case "003.889": // Apple Remote Desktop
685 this._rfb_version
= 3.3;
688 this._rfb_version
= 3.7;
691 case "004.000": // Intel AMT KVM
692 case "004.001": // RealVNC 4.6
693 case "005.000": // RealVNC 5.3
694 this._rfb_version
= 3.8;
697 return this._fail("Invalid server version " + sversion
);
701 var repeaterID
= this._repeaterID
;
702 while (repeaterID
.length
< 250) {
705 this._sock
.send_string(repeaterID
);
709 if (this._rfb_version
> this._rfb_max_version
) {
710 this._rfb_version
= this._rfb_max_version
;
713 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
714 ".00" + ((this._rfb_version
* 10) % 10);
715 this._sock
.send_string("RFB " + cversion
+ "\n");
716 Util
.Debug('Sent ProtocolVersion: ' + cversion
);
718 this._rfb_init_state
= 'Security';
721 _negotiate_security: function () {
722 if (this._rfb_version
>= 3.7) {
723 // Server sends supported list, client decides
724 var num_types
= this._sock
.rQshift8();
725 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
727 if (num_types
=== 0) {
728 var strlen
= this._sock
.rQshift32();
729 var reason
= this._sock
.rQshiftStr(strlen
);
730 return this._fail("Security failure: " + reason
);
733 this._rfb_auth_scheme
= 0;
734 var types
= this._sock
.rQshiftBytes(num_types
);
735 Util
.Debug("Server security types: " + types
);
736 for (var i
= 0; i
< types
.length
; i
++) {
739 case 2: // VNC Authentication
742 if (types
[i
] > this._rfb_auth_scheme
) {
743 this._rfb_auth_scheme
= types
[i
];
751 if (this._rfb_auth_scheme
=== 0) {
752 return this._fail("Unsupported security types: " + types
);
755 this._sock
.send([this._rfb_auth_scheme
]);
758 if (this._sock
.rQwait("security scheme", 4)) { return false; }
759 this._rfb_auth_scheme
= this._sock
.rQshift32();
762 this._rfb_init_state
= 'Authentication';
763 Util
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
765 return this._init_msg(); // jump to authentication
769 _negotiate_xvp_auth: function () {
770 var xvp_sep
= this._xvp_password_sep
;
771 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
772 if (xvp_auth
.length
< 3) {
773 var msg
= 'XVP credentials required (user' + xvp_sep
+
774 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
775 this._onPasswordRequired(this, msg
);
779 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
780 String
.fromCharCode(xvp_auth
[1].length
) +
783 this._sock
.send_string(xvp_auth_str
);
784 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
785 this._rfb_auth_scheme
= 2;
786 return this._negotiate_authentication();
789 _negotiate_std_vnc_auth: function () {
790 if (this._rfb_password
.length
=== 0) {
791 this._onPasswordRequired(this);
795 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
797 // TODO(directxman12): make genDES not require an Array
798 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
799 var response
= RFB
.genDES(this._rfb_password
, challenge
);
800 this._sock
.send(response
);
801 this._rfb_init_state
= "SecurityResult";
805 _negotiate_tight_tunnels: function (numTunnels
) {
806 var clientSupportedTunnelTypes
= {
807 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
809 var serverSupportedTunnelTypes
= {};
810 // receive tunnel capabilities
811 for (var i
= 0; i
< numTunnels
; i
++) {
812 var cap_code
= this._sock
.rQshift32();
813 var cap_vendor
= this._sock
.rQshiftStr(4);
814 var cap_signature
= this._sock
.rQshiftStr(8);
815 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
818 // choose the notunnel type
819 if (serverSupportedTunnelTypes
[0]) {
820 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
821 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
822 return this._fail("Client's tunnel type had the incorrect vendor or signature");
824 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
825 return false; // wait until we receive the sub auth count to continue
827 return this._fail("Server wanted tunnels, but doesn't support the notunnel type");
831 _negotiate_tight_auth: function () {
832 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
833 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
834 var numTunnels
= this._sock
.rQshift32();
835 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
837 this._rfb_tightvnc
= true;
839 if (numTunnels
> 0) {
840 this._negotiate_tight_tunnels(numTunnels
);
841 return false; // wait until we receive the sub auth to continue
845 // second pass, do the sub-auth negotiation
846 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
847 var subAuthCount
= this._sock
.rQshift32();
848 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
849 this._updateState('SecurityResult');
853 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
855 var clientSupportedTypes
= {
860 var serverSupportedTypes
= [];
862 for (var i
= 0; i
< subAuthCount
; i
++) {
863 var capNum
= this._sock
.rQshift32();
864 var capabilities
= this._sock
.rQshiftStr(12);
865 serverSupportedTypes
.push(capabilities
);
868 for (var authType
in clientSupportedTypes
) {
869 if (serverSupportedTypes
.indexOf(authType
) != -1) {
870 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
873 case 'STDVNOAUTH__': // no auth
874 this._rfb_init_state
= 'SecurityResult';
876 case 'STDVVNCAUTH_': // VNC auth
877 this._rfb_auth_scheme
= 2;
878 return this._init_msg();
880 return this._fail("Unsupported tiny auth scheme: " + authType
);
885 return this._fail("No supported sub-auth types!");
888 _negotiate_authentication: function () {
889 switch (this._rfb_auth_scheme
) {
890 case 0: // connection failed
891 if (this._sock
.rQwait("auth reason", 4)) { return false; }
892 var strlen
= this._sock
.rQshift32();
893 var reason
= this._sock
.rQshiftStr(strlen
);
894 return this._fail("Auth failure: " + reason
);
897 if (this._rfb_version
>= 3.8) {
898 this._rfb_init_state
= 'SecurityResult';
901 this._rfb_init_state
= 'ClientInitialisation';
902 return this._init_msg();
905 return this._negotiate_xvp_auth();
907 case 2: // VNC authentication
908 return this._negotiate_std_vnc_auth();
910 case 16: // TightVNC Security Type
911 return this._negotiate_tight_auth();
914 return this._fail("Unsupported auth scheme: " + this._rfb_auth_scheme
);
918 _handle_security_result: function () {
919 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
920 switch (this._sock
.rQshift32()) {
922 this._rfb_init_state
= 'ClientInitialisation';
923 Util
.Debug('Authentication OK');
924 return this._init_msg();
926 if (this._rfb_version
>= 3.8) {
927 var length
= this._sock
.rQshift32();
928 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
929 var reason
= this._sock
.rQshiftStr(length
);
930 return this._fail(reason
);
932 return this._fail("Authentication failure");
936 return this._fail("Too many auth attempts");
938 return this._fail("Unknown SecurityResult");
942 _negotiate_server_init: function () {
943 if (this._sock
.rQwait("server initialization", 24)) { return false; }
946 this._fb_width
= this._sock
.rQshift16();
947 this._fb_height
= this._sock
.rQshift16();
948 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
951 var bpp
= this._sock
.rQshift8();
952 var depth
= this._sock
.rQshift8();
953 var big_endian
= this._sock
.rQshift8();
954 var true_color
= this._sock
.rQshift8();
956 var red_max
= this._sock
.rQshift16();
957 var green_max
= this._sock
.rQshift16();
958 var blue_max
= this._sock
.rQshift16();
959 var red_shift
= this._sock
.rQshift8();
960 var green_shift
= this._sock
.rQshift8();
961 var blue_shift
= this._sock
.rQshift8();
962 this._sock
.rQskipBytes(3); // padding
964 // NB(directxman12): we don't want to call any callbacks or print messages until
965 // *after* we're past the point where we could backtrack
967 /* Connection name/title */
968 var name_length = this._sock.rQshift32();
969 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
970 this._fb_name = Util.decodeUTF8(this._sock.rQshiftStr(name_length));
972 if (this._rfb_tightvnc) {
973 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
974 // In TightVNC mode, ServerInit message is extended
975 var numServerMessages = this._sock.rQshift16();
976 var numClientMessages = this._sock.rQshift16();
977 var numEncodings = this._sock.rQshift16();
978 this._sock.rQskipBytes(2); // padding
980 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
981 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
983 // we don't actually do anything with the capability information that TIGHT sends,
984 // so we just skip the all of this.
986 // TIGHT server message capabilities
987 this._sock.rQskipBytes(16 * numServerMessages);
989 // TIGHT client message capabilities
990 this._sock.rQskipBytes(16 * numClientMessages);
992 // TIGHT encoding capabilities
993 this._sock.rQskipBytes(16 * numEncodings);
996 // NB(directxman12): these are down here so that we don't run them multiple times
998 Util.Info("Screen: " + this._fb_width + "x" + this._fb_height +
999 ", bpp: " + bpp + ", depth: " + depth +
1000 ", big_endian: " + big_endian +
1001 ", true_color: " + true_color +
1002 ", red_max: " + red_max +
1003 ", green_max: " + green_max +
1004 ", blue_max: " + blue_max +
1005 ", red_shift: " + red_shift +
1006 ", green_shift: " + green_shift +
1007 ", blue_shift: " + blue_shift);
1009 if (big_endian !== 0) {
1010 Util.Warn("Server native endian is not little endian");
1013 if (red_shift !== 16) {
1014 Util.Warn("Server native red-shift is not 16");
1017 if (blue_shift !== 0) {
1018 Util.Warn("Server native blue-shift is not 0");
1021 // we're past the point where we could backtrack, so it's safe to call this
1022 this._onDesktopName(this, this._fb_name);
1024 if (this._true_color && this._fb_name === "Intel(r) AMT KVM") {
1025 Util.Warn("Intel AMT KVM only supports 8/16 bit depths. Disabling true color");
1026 this._true_color = false;
1029 this._display.set_true_color(this._true_color);
1030 this._display.resize(this._fb_width, this._fb_height);
1031 this._onFBResize(this, this._fb_width, this._fb_height);
1033 if (!this._view_only) { this._keyboard.grab(); }
1034 if (!this._view_only) { this._mouse.grab(); }
1036 if (this._true_color) {
1044 RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
1045 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
1046 RFB.messages.fbUpdateRequests(this._sock, false, this._display.getCleanDirtyReset(), this._fb_width, this._fb_height);
1048 this._timing.fbu_rt_start = (new Date()).getTime();
1049 this._timing.pixels = 0;
1051 this._updateConnectionState('connected');
1055 /* RFB protocol initialization states:
1060 * ClientInitialization - not triggered by server message
1061 * ServerInitialization
1063 _init_msg: function () {
1064 switch (this._rfb_init_state
) {
1065 case 'ProtocolVersion':
1066 return this._negotiate_protocol_version();
1069 return this._negotiate_security();
1071 case 'Authentication':
1072 return this._negotiate_authentication();
1074 case 'SecurityResult':
1075 return this._handle_security_result();
1077 case 'ClientInitialisation':
1078 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1079 this._rfb_init_state
= 'ServerInitialisation';
1082 case 'ServerInitialisation':
1083 return this._negotiate_server_init();
1086 return this._fail("Unknown init state: " +
1087 this._rfb_init_state
);
1091 _handle_set_colour_map_msg: function () {
1092 Util
.Debug("SetColorMapEntries");
1093 this._sock
.rQskip8(); // Padding
1095 var first_colour
= this._sock
.rQshift16();
1096 var num_colours
= this._sock
.rQshift16();
1097 if (this._sock
.rQwait('SetColorMapEntries', num_colours
* 6, 6)) { return false; }
1099 for (var c
= 0; c
< num_colours
; c
++) {
1100 var red
= parseInt(this._sock
.rQshift16() / 256, 10);
1101 var green
= parseInt(this._sock
.rQshift16() / 256, 10);
1102 var blue
= parseInt(this._sock
.rQshift16() / 256, 10);
1103 this._display
.set_colourMap([blue
, green
, red
], first_colour
+ c
);
1105 Util
.Debug("colourMap: " + this._display
.get_colourMap());
1106 Util
.Info("Registered " + num_colours
+ " colourMap entries");
1111 _handle_server_cut_text: function () {
1112 Util
.Debug("ServerCutText");
1113 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1114 this._sock
.rQskipBytes(3); // Padding
1115 var length
= this._sock
.rQshift32();
1116 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1118 var text
= this._sock
.rQshiftStr(length
);
1119 this._onClipboard(this, text
);
1124 _handle_server_fence_msg: function() {
1125 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1126 this._sock
.rQskipBytes(3); // Padding
1127 var flags
= this._sock
.rQshift32();
1128 var length
= this._sock
.rQshift8();
1130 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1133 Util
.Warn("Bad payload length (" + length
+ ") in fence response");
1137 var payload
= this._sock
.rQshiftStr(length
);
1139 this._supportsFence
= true;
1144 * (1<<0) - BlockBefore
1145 * (1<<1) - BlockAfter
1150 if (!(flags
& (1<<31))) {
1151 return this._fail("Unexpected fence response");
1154 // Filter out unsupported flags
1155 // FIXME: support syncNext
1156 flags
&= (1<<0) | (1<<1);
1158 // BlockBefore and BlockAfter are automatically handled by
1159 // the fact that we process each incoming message
1161 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1166 _handle_xvp_msg: function () {
1167 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1168 this._sock
.rQskip8(); // Padding
1169 var xvp_ver
= this._sock
.rQshift8();
1170 var xvp_msg
= this._sock
.rQshift8();
1174 Util
.Error("Operation Failed");
1175 this._notification("XVP Operation Failed", 'error');
1178 this._rfb_xvp_ver
= xvp_ver
;
1179 Util
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1180 this._onXvpInit(this._rfb_xvp_ver
);
1183 this._fail("Disconnected: illegal server XVP message " + xvp_msg
);
1190 _normal_msg: function () {
1193 if (this._FBU
.rects
> 0) {
1196 msg_type
= this._sock
.rQshift8();
1200 case 0: // FramebufferUpdate
1201 var ret
= this._framebufferUpdate();
1203 RFB
.messages
.fbUpdateRequests(this._sock
,
1204 this._enabledContinuousUpdates
,
1205 this._display
.getCleanDirtyReset(),
1206 this._fb_width
, this._fb_height
);
1210 case 1: // SetColorMapEntries
1211 return this._handle_set_colour_map_msg();
1218 case 3: // ServerCutText
1219 return this._handle_server_cut_text();
1221 case 150: // EndOfContinuousUpdates
1222 var first
= !(this._supportsContinuousUpdates
);
1223 this._supportsContinuousUpdates
= true;
1224 this._enabledContinuousUpdates
= false;
1226 this._enabledContinuousUpdates
= true;
1227 this._updateContinuousUpdates();
1228 Util
.Info("Enabling continuous updates.");
1230 // FIXME: We need to send a framebufferupdaterequest here
1231 // if we add support for turning off continuous updates
1235 case 248: // ServerFence
1236 return this._handle_server_fence_msg();
1239 return this._handle_xvp_msg();
1242 this._fail("Disconnected: illegal server message type " + msg_type
);
1243 Util
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1248 _onFlush: function() {
1249 this._flushing
= false;
1250 // Resume processing
1251 if (this._sock
.rQlen() > 0) {
1252 this._handle_message();
1256 _framebufferUpdate: function () {
1260 if (this._FBU
.rects
=== 0) {
1261 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1262 this._sock
.rQskip8(); // Padding
1263 this._FBU
.rects
= this._sock
.rQshift16();
1264 this._FBU
.bytes
= 0;
1265 this._timing
.cur_fbu
= 0;
1266 if (this._timing
.fbu_rt_start
> 0) {
1267 now
= (new Date()).getTime();
1268 Util
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1271 // Make sure the previous frame is fully rendered first
1272 // to avoid building up an excessive queue
1273 if (this._display
.pending()) {
1274 this._flushing
= true;
1275 this._display
.flush();
1280 while (this._FBU
.rects
> 0) {
1281 if (this._rfb_connection_state
!== 'connected') { return false; }
1283 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1284 if (this._FBU
.bytes
=== 0) {
1285 if (this._sock
.rQwait("rect header", 12)) { return false; }
1286 /* New FramebufferUpdate */
1288 var hdr
= this._sock
.rQshiftBytes(12);
1289 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1290 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1291 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1292 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1293 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1294 (hdr
[10] << 8) + hdr
[11], 10);
1296 this._onFBUReceive(this,
1297 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1298 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1299 'encoding': this._FBU
.encoding
,
1300 'encodingName': this._encNames
[this._FBU
.encoding
]});
1302 if (!this._encNames
[this._FBU
.encoding
]) {
1303 this._fail("Disconnected: unsupported encoding " +
1304 this._FBU
.encoding
);
1309 this._timing
.last_fbu
= (new Date()).getTime();
1311 ret
= this._encHandlers
[this._FBU
.encoding
]();
1313 now
= (new Date()).getTime();
1314 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1317 this._encStats
[this._FBU
.encoding
][0]++;
1318 this._encStats
[this._FBU
.encoding
][1]++;
1319 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1322 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1323 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1324 this._timing
.fbu_rt_start
> 0) {
1325 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1326 this._timing
.full_fbu_cnt
++;
1327 Util
.Info("Timing of full FBU, curr: " +
1328 this._timing
.cur_fbu
+ ", total: " +
1329 this._timing
.full_fbu_total
+ ", cnt: " +
1330 this._timing
.full_fbu_cnt
+ ", avg: " +
1331 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1334 if (this._timing
.fbu_rt_start
> 0) {
1335 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1336 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1337 this._timing
.fbu_rt_cnt
++;
1338 Util
.Info("full FBU round-trip, cur: " +
1339 fbu_rt_diff
+ ", total: " +
1340 this._timing
.fbu_rt_total
+ ", cnt: " +
1341 this._timing
.fbu_rt_cnt
+ ", avg: " +
1342 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1343 this._timing
.fbu_rt_start
= 0;
1347 if (!ret
) { return ret
; } // need more data
1350 this._onFBUComplete(this,
1351 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1352 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1353 'encoding': this._FBU
.encoding
,
1354 'encodingName': this._encNames
[this._FBU
.encoding
]});
1356 return true; // We finished this FBU
1359 _updateContinuousUpdates: function() {
1360 if (!this._enabledContinuousUpdates
) { return; }
1362 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1363 this._fb_width
, this._fb_height
);
1367 Util
.make_properties(RFB
, [
1368 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1369 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1370 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1371 ['true_color', 'rw', 'bool'], // Request true color pixel data
1372 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1373 ['shared', 'rw', 'bool'], // Request shared mode
1374 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1375 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1376 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1377 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1378 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1379 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1381 // Callback functions
1382 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1383 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1384 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1385 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1386 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1387 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1388 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1389 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1390 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1391 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1392 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1395 RFB
.prototype.set_local_cursor = function (cursor
) {
1396 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1397 this._local_cursor
= false;
1398 this._display
.disableLocalCursor(); //Only show server-side cursor
1400 if (this._display
.get_cursor_uri()) {
1401 this._local_cursor
= true;
1403 Util
.Warn("Browser does not support local cursor");
1404 this._display
.disableLocalCursor();
1409 RFB
.prototype.get_display = function () { return this._display
; };
1410 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1411 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1415 keyEvent: function (sock
, keysym
, down
) {
1416 var buff
= sock
._sQ
;
1417 var offset
= sock
._sQlen
;
1419 buff
[offset
] = 4; // msg-type
1420 buff
[offset
+ 1] = down
;
1422 buff
[offset
+ 2] = 0;
1423 buff
[offset
+ 3] = 0;
1425 buff
[offset
+ 4] = (keysym
>> 24);
1426 buff
[offset
+ 5] = (keysym
>> 16);
1427 buff
[offset
+ 6] = (keysym
>> 8);
1428 buff
[offset
+ 7] = keysym
;
1434 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1435 function getRFBkeycode(xt_scancode
) {
1436 var upperByte
= (keycode
>> 8);
1437 var lowerByte
= (keycode
& 0x00ff);
1438 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1439 lowerByte
= lowerByte
| 0x80;
1445 var buff
= sock
._sQ
;
1446 var offset
= sock
._sQlen
;
1448 buff
[offset
] = 255; // msg-type
1449 buff
[offset
+ 1] = 0; // sub msg-type
1451 buff
[offset
+ 2] = (down
>> 8);
1452 buff
[offset
+ 3] = down
;
1454 buff
[offset
+ 4] = (keysym
>> 24);
1455 buff
[offset
+ 5] = (keysym
>> 16);
1456 buff
[offset
+ 6] = (keysym
>> 8);
1457 buff
[offset
+ 7] = keysym
;
1459 var RFBkeycode
= getRFBkeycode(keycode
);
1461 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1462 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1463 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1464 buff
[offset
+ 11] = RFBkeycode
;
1470 pointerEvent: function (sock
, x
, y
, mask
) {
1471 var buff
= sock
._sQ
;
1472 var offset
= sock
._sQlen
;
1474 buff
[offset
] = 5; // msg-type
1476 buff
[offset
+ 1] = mask
;
1478 buff
[offset
+ 2] = x
>> 8;
1479 buff
[offset
+ 3] = x
;
1481 buff
[offset
+ 4] = y
>> 8;
1482 buff
[offset
+ 5] = y
;
1488 // TODO(directxman12): make this unicode compatible?
1489 clientCutText: function (sock
, text
) {
1490 var buff
= sock
._sQ
;
1491 var offset
= sock
._sQlen
;
1493 buff
[offset
] = 6; // msg-type
1495 buff
[offset
+ 1] = 0; // padding
1496 buff
[offset
+ 2] = 0; // padding
1497 buff
[offset
+ 3] = 0; // padding
1499 var n
= text
.length
;
1501 buff
[offset
+ 4] = n
>> 24;
1502 buff
[offset
+ 5] = n
>> 16;
1503 buff
[offset
+ 6] = n
>> 8;
1504 buff
[offset
+ 7] = n
;
1506 for (var i
= 0; i
< n
; i
++) {
1507 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1510 sock
._sQlen
+= 8 + n
;
1514 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1515 var buff
= sock
._sQ
;
1516 var offset
= sock
._sQlen
;
1518 buff
[offset
] = 251; // msg-type
1519 buff
[offset
+ 1] = 0; // padding
1520 buff
[offset
+ 2] = width
>> 8; // width
1521 buff
[offset
+ 3] = width
;
1522 buff
[offset
+ 4] = height
>> 8; // height
1523 buff
[offset
+ 5] = height
;
1525 buff
[offset
+ 6] = 1; // number-of-screens
1526 buff
[offset
+ 7] = 0; // padding
1529 buff
[offset
+ 8] = id
>> 24; // id
1530 buff
[offset
+ 9] = id
>> 16;
1531 buff
[offset
+ 10] = id
>> 8;
1532 buff
[offset
+ 11] = id
;
1533 buff
[offset
+ 12] = 0; // x-position
1534 buff
[offset
+ 13] = 0;
1535 buff
[offset
+ 14] = 0; // y-position
1536 buff
[offset
+ 15] = 0;
1537 buff
[offset
+ 16] = width
>> 8; // width
1538 buff
[offset
+ 17] = width
;
1539 buff
[offset
+ 18] = height
>> 8; // height
1540 buff
[offset
+ 19] = height
;
1541 buff
[offset
+ 20] = flags
>> 24; // flags
1542 buff
[offset
+ 21] = flags
>> 16;
1543 buff
[offset
+ 22] = flags
>> 8;
1544 buff
[offset
+ 23] = flags
;
1550 clientFence: function (sock
, flags
, payload
) {
1551 var buff
= sock
._sQ
;
1552 var offset
= sock
._sQlen
;
1554 buff
[offset
] = 248; // msg-type
1556 buff
[offset
+ 1] = 0; // padding
1557 buff
[offset
+ 2] = 0; // padding
1558 buff
[offset
+ 3] = 0; // padding
1560 buff
[offset
+ 4] = flags
>> 24; // flags
1561 buff
[offset
+ 5] = flags
>> 16;
1562 buff
[offset
+ 6] = flags
>> 8;
1563 buff
[offset
+ 7] = flags
;
1565 var n
= payload
.length
;
1567 buff
[offset
+ 8] = n
; // length
1569 for (var i
= 0; i
< n
; i
++) {
1570 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1573 sock
._sQlen
+= 9 + n
;
1577 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1578 var buff
= sock
._sQ
;
1579 var offset
= sock
._sQlen
;
1581 buff
[offset
] = 150; // msg-type
1582 buff
[offset
+ 1] = enable
; // enable-flag
1584 buff
[offset
+ 2] = x
>> 8; // x
1585 buff
[offset
+ 3] = x
;
1586 buff
[offset
+ 4] = y
>> 8; // y
1587 buff
[offset
+ 5] = y
;
1588 buff
[offset
+ 6] = width
>> 8; // width
1589 buff
[offset
+ 7] = width
;
1590 buff
[offset
+ 8] = height
>> 8; // height
1591 buff
[offset
+ 9] = height
;
1597 pixelFormat: function (sock
, bpp
, depth
, true_color
) {
1598 var buff
= sock
._sQ
;
1599 var offset
= sock
._sQlen
;
1601 buff
[offset
] = 0; // msg-type
1603 buff
[offset
+ 1] = 0; // padding
1604 buff
[offset
+ 2] = 0; // padding
1605 buff
[offset
+ 3] = 0; // padding
1607 buff
[offset
+ 4] = bpp
* 8; // bits-per-pixel
1608 buff
[offset
+ 5] = depth
* 8; // depth
1609 buff
[offset
+ 6] = 0; // little-endian
1610 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1612 buff
[offset
+ 8] = 0; // red-max
1613 buff
[offset
+ 9] = 255; // red-max
1615 buff
[offset
+ 10] = 0; // green-max
1616 buff
[offset
+ 11] = 255; // green-max
1618 buff
[offset
+ 12] = 0; // blue-max
1619 buff
[offset
+ 13] = 255; // blue-max
1621 buff
[offset
+ 14] = 16; // red-shift
1622 buff
[offset
+ 15] = 8; // green-shift
1623 buff
[offset
+ 16] = 0; // blue-shift
1625 buff
[offset
+ 17] = 0; // padding
1626 buff
[offset
+ 18] = 0; // padding
1627 buff
[offset
+ 19] = 0; // padding
1633 clientEncodings: function (sock
, encodings
, local_cursor
, true_color
) {
1634 var buff
= sock
._sQ
;
1635 var offset
= sock
._sQlen
;
1637 buff
[offset
] = 2; // msg-type
1638 buff
[offset
+ 1] = 0; // padding
1640 // offset + 2 and offset + 3 are encoding count
1642 var i
, j
= offset
+ 4, cnt
= 0;
1643 for (i
= 0; i
< encodings
.length
; i
++) {
1644 if (encodings
[i
][0] === "Cursor" && !local_cursor
) {
1645 Util
.Debug("Skipping Cursor pseudo-encoding");
1646 } else if (encodings
[i
][0] === "TIGHT" && !true_color
) {
1647 // TODO: remove this when we have tight+non-true-color
1648 Util
.Warn("Skipping tight as it is only supported with true color");
1650 var enc
= encodings
[i
][1];
1651 buff
[j
] = enc
>> 24;
1652 buff
[j
+ 1] = enc
>> 16;
1653 buff
[j
+ 2] = enc
>> 8;
1661 buff
[offset
+ 2] = cnt
>> 8;
1662 buff
[offset
+ 3] = cnt
;
1664 sock
._sQlen
+= j
- offset
;
1668 fbUpdateRequests: function (sock
, onlyNonInc
, cleanDirty
, fb_width
, fb_height
) {
1669 var offsetIncrement
= 0;
1671 var cb
= cleanDirty
.cleanBox
;
1673 if (!onlyNonInc
&& (cb
.w
> 0 && cb
.h
> 0)) {
1674 w
= typeof cb
.w
=== "undefined" ? fb_width
: cb
.w
;
1675 h
= typeof cb
.h
=== "undefined" ? fb_height
: cb
.h
;
1676 // Request incremental for clean box
1677 RFB
.messages
.fbUpdateRequest(sock
, 1, cb
.x
, cb
.y
, w
, h
);
1680 for (var i
= 0; i
< cleanDirty
.dirtyBoxes
.length
; i
++) {
1681 var db
= cleanDirty
.dirtyBoxes
[i
];
1682 // Force all (non-incremental) for dirty box
1683 w
= typeof db
.w
=== "undefined" ? fb_width
: db
.w
;
1684 h
= typeof db
.h
=== "undefined" ? fb_height
: db
.h
;
1685 RFB
.messages
.fbUpdateRequest(sock
, 0, db
.x
, db
.y
, w
, h
);
1689 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1690 var buff
= sock
._sQ
;
1691 var offset
= sock
._sQlen
;
1693 if (typeof(x
) === "undefined") { x
= 0; }
1694 if (typeof(y
) === "undefined") { y
= 0; }
1696 buff
[offset
] = 3; // msg-type
1697 buff
[offset
+ 1] = incremental
;
1699 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1700 buff
[offset
+ 3] = x
& 0xFF;
1702 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1703 buff
[offset
+ 5] = y
& 0xFF;
1705 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1706 buff
[offset
+ 7] = w
& 0xFF;
1708 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1709 buff
[offset
+ 9] = h
& 0xFF;
1716 RFB
.genDES = function (password
, challenge
) {
1718 for (var i
= 0; i
< password
.length
; i
++) {
1719 passwd
.push(password
.charCodeAt(i
));
1721 return (new DES(passwd
)).encrypt(challenge
);
1724 RFB
.encodingHandlers
= {
1726 if (this._FBU
.lines
=== 0) {
1727 this._FBU
.lines
= this._FBU
.height
;
1730 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // at least a line
1731 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1732 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1733 var curr_height
= Math
.min(this._FBU
.lines
,
1734 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* this._fb_Bpp
)));
1735 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1736 curr_height
, this._sock
.get_rQ(),
1737 this._sock
.get_rQi());
1738 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* this._fb_Bpp
);
1739 this._FBU
.lines
-= curr_height
;
1741 if (this._FBU
.lines
> 0) {
1742 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // At least another line
1745 this._FBU
.bytes
= 0;
1751 COPYRECT: function () {
1752 this._FBU
.bytes
= 4;
1753 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1754 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1755 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1759 this._FBU
.bytes
= 0;
1765 if (this._FBU
.subrects
=== 0) {
1766 this._FBU
.bytes
= 4 + this._fb_Bpp
;
1767 if (this._sock
.rQwait("RRE", 4 + this._fb_Bpp
)) { return false; }
1768 this._FBU
.subrects
= this._sock
.rQshift32();
1769 color
= this._sock
.rQshiftBytes(this._fb_Bpp
); // Background
1770 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1773 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (this._fb_Bpp
+ 8)) {
1774 color
= this._sock
.rQshiftBytes(this._fb_Bpp
);
1775 var x
= this._sock
.rQshift16();
1776 var y
= this._sock
.rQshift16();
1777 var width
= this._sock
.rQshift16();
1778 var height
= this._sock
.rQshift16();
1779 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1780 this._FBU
.subrects
--;
1783 if (this._FBU
.subrects
> 0) {
1784 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1785 this._FBU
.bytes
= (this._fb_Bpp
+ 8) * chunk
;
1788 this._FBU
.bytes
= 0;
1794 HEXTILE: function () {
1795 var rQ
= this._sock
.get_rQ();
1796 var rQi
= this._sock
.get_rQi();
1798 if (this._FBU
.tiles
=== 0) {
1799 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1800 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1801 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1802 this._FBU
.tiles
= this._FBU
.total_tiles
;
1805 while (this._FBU
.tiles
> 0) {
1806 this._FBU
.bytes
= 1;
1807 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1808 var subencoding
= rQ
[rQi
]; // Peek
1809 if (subencoding
> 30) { // Raw
1810 this._fail("Disconnected: illegal hextile subencoding " + subencoding
);
1815 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1816 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1817 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1818 var x
= this._FBU
.x
+ tile_x
* 16;
1819 var y
= this._FBU
.y
+ tile_y
* 16;
1820 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1821 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1823 // Figure out how much we are expecting
1824 if (subencoding
& 0x01) { // Raw
1825 this._FBU
.bytes
+= w
* h
* this._fb_Bpp
;
1827 if (subencoding
& 0x02) { // Background
1828 this._FBU
.bytes
+= this._fb_Bpp
;
1830 if (subencoding
& 0x04) { // Foreground
1831 this._FBU
.bytes
+= this._fb_Bpp
;
1833 if (subencoding
& 0x08) { // AnySubrects
1834 this._FBU
.bytes
++; // Since we aren't shifting it off
1835 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1836 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1837 if (subencoding
& 0x10) { // SubrectsColoured
1838 this._FBU
.bytes
+= subrects
* (this._fb_Bpp
+ 2);
1840 this._FBU
.bytes
+= subrects
* 2;
1845 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1847 // We know the encoding and have a whole tile
1848 this._FBU
.subencoding
= rQ
[rQi
];
1850 if (this._FBU
.subencoding
=== 0) {
1851 if (this._FBU
.lastsubencoding
& 0x01) {
1852 // Weird: ignore blanks are RAW
1853 Util
.Debug(" Ignoring blank after RAW");
1855 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1857 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1858 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1859 rQi
+= this._FBU
.bytes
- 1;
1861 if (this._FBU
.subencoding
& 0x02) { // Background
1862 if (this._fb_Bpp
== 1) {
1863 this._FBU
.background
= rQ
[rQi
];
1866 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1868 rQi
+= this._fb_Bpp
;
1870 if (this._FBU
.subencoding
& 0x04) { // Foreground
1871 if (this._fb_Bpp
== 1) {
1872 this._FBU
.foreground
= rQ
[rQi
];
1874 // this._fb_Bpp is 4
1875 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1877 rQi
+= this._fb_Bpp
;
1880 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1881 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1885 for (var s
= 0; s
< subrects
; s
++) {
1887 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1888 if (this._fb_Bpp
=== 1) {
1892 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1894 rQi
+= this._fb_Bpp
;
1896 color
= this._FBU
.foreground
;
1901 var sy
= (xy
& 0x0f);
1905 var sw
= (wh
>> 4) + 1;
1906 var sh
= (wh
& 0x0f) + 1;
1908 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1911 this._display
.finishTile();
1913 this._sock
.set_rQi(rQi
);
1914 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
1915 this._FBU
.bytes
= 0;
1919 if (this._FBU
.tiles
=== 0) {
1926 getTightCLength: function (arr
) {
1927 var header
= 1, data
= 0;
1928 data
+= arr
[0] & 0x7f;
1929 if (arr
[0] & 0x80) {
1931 data
+= (arr
[1] & 0x7f) << 7;
1932 if (arr
[1] & 0x80) {
1934 data
+= arr
[2] << 14;
1937 return [header
, data
];
1940 display_tight: function (isTightPNG
) {
1941 if (this._fb_depth
=== 1) {
1942 this._fail("Tight protocol handler only implements true color mode");
1945 this._FBU
.bytes
= 1; // compression-control byte
1946 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
1948 var checksum = function (data
) {
1950 for (var i
= 0; i
< data
.length
; i
++) {
1952 if (sum
> 65536) sum
-= 65536;
1957 var resetStreams
= 0;
1959 var decompress = function (data
, expected
) {
1960 for (var i
= 0; i
< 4; i
++) {
1961 if ((resetStreams
>> i
) & 1) {
1962 this._FBU
.zlibs
[i
].reset();
1963 Util
.Info("Reset zlib stream " + i
);
1967 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
1968 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
1969 /*if (uncompressed.status !== 0) {
1970 Util.Error("Invalid data in zlib stream");
1973 //return uncompressed.data;
1974 return uncompressed
;
1977 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
1978 // Convert indexed (palette based) image data to RGB
1979 // TODO: reduce number of calculations inside loop
1980 var dest
= this._destBuff
;
1981 var w
= Math
.floor((width
+ 7) / 8);
1982 var w1
= Math
.floor(width
/ 8);
1984 /*for (var y = 0; y < height; y++) {
1986 var yoffset = y * width;
1987 var ybitoffset = y * w;
1988 var xoffset, targetbyte;
1989 for (x = 0; x < w1; x++) {
1990 xoffset = yoffset + x * 8;
1991 targetbyte = data[ybitoffset + x];
1992 for (b = 7; b >= 0; b--) {
1993 dp = (xoffset + 7 - b) * 3;
1994 sp = (targetbyte >> b & 1) * 3;
1995 dest[dp] = palette[sp];
1996 dest[dp + 1] = palette[sp + 1];
1997 dest[dp + 2] = palette[sp + 2];
2001 xoffset = yoffset + x * 8;
2002 targetbyte = data[ybitoffset + x];
2003 for (b = 7; b >= 8 - width % 8; b--) {
2004 dp = (xoffset + 7 - b) * 3;
2005 sp = (targetbyte >> b & 1) * 3;
2006 dest[dp] = palette[sp];
2007 dest[dp + 1] = palette[sp + 1];
2008 dest[dp + 2] = palette[sp + 2];
2012 for (var y
= 0; y
< height
; y
++) {
2014 for (x
= 0; x
< w1
; x
++) {
2015 for (b
= 7; b
>= 0; b
--) {
2016 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2017 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2018 dest
[dp
] = palette
[sp
];
2019 dest
[dp
+ 1] = palette
[sp
+ 1];
2020 dest
[dp
+ 2] = palette
[sp
+ 2];
2025 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2026 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2027 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2028 dest
[dp
] = palette
[sp
];
2029 dest
[dp
+ 1] = palette
[sp
+ 1];
2030 dest
[dp
+ 2] = palette
[sp
+ 2];
2038 var indexedToRGBX = function (data
, palette
, width
, height
) {
2039 // Convert indexed (palette based) image data to RGB
2040 var dest
= this._destBuff
;
2041 var total
= width
* height
* 4;
2042 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2043 var sp
= data
[j
] * 3;
2044 dest
[i
] = palette
[sp
];
2045 dest
[i
+ 1] = palette
[sp
+ 1];
2046 dest
[i
+ 2] = palette
[sp
+ 2];
2053 var rQi
= this._sock
.get_rQi();
2054 var rQ
= this._sock
.rQwhole();
2056 var cl_header
, cl_data
;
2058 var handlePalette = function () {
2059 var numColors
= rQ
[rQi
+ 2] + 1;
2060 var paletteSize
= numColors
* this._fb_depth
;
2061 this._FBU
.bytes
+= paletteSize
;
2062 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2064 var bpp
= (numColors
<= 2) ? 1 : 8;
2065 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2067 if (rowSize
* this._FBU
.height
< 12) {
2070 cl_data
= rowSize
* this._FBU
.height
;
2071 //clength = [0, rowSize * this._FBU.height];
2073 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2074 var cl_offset
= rQi
+ 3 + paletteSize
;
2077 cl_data
+= rQ
[cl_offset
] & 0x7f;
2078 if (rQ
[cl_offset
] & 0x80) {
2080 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2081 if (rQ
[cl_offset
+ 1] & 0x80) {
2083 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2086 // end inline getTightCLength
2089 this._FBU
.bytes
+= cl_header
+ cl_data
;
2090 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2092 // Shift ctl, filter id, num colors, palette entries, and clength off
2093 this._sock
.rQskipBytes(3);
2094 //var palette = this._sock.rQshiftBytes(paletteSize);
2095 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2096 this._sock
.rQskipBytes(cl_header
);
2099 data
= this._sock
.rQshiftBytes(cl_data
);
2101 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2104 // Convert indexed (palette based) image data to RGB
2106 if (numColors
== 2) {
2107 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2108 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2110 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2111 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2118 var handleCopy = function () {
2120 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* this._fb_depth
;
2121 if (uncompressedSize
< 12) {
2124 cl_data
= uncompressedSize
;
2126 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2127 var cl_offset
= rQi
+ 1;
2130 cl_data
+= rQ
[cl_offset
] & 0x7f;
2131 if (rQ
[cl_offset
] & 0x80) {
2133 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2134 if (rQ
[cl_offset
+ 1] & 0x80) {
2136 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2139 // end inline getTightCLength
2141 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2142 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2144 // Shift ctl, clength off
2145 this._sock
.rQshiftBytes(1 + cl_header
);
2148 data
= this._sock
.rQshiftBytes(cl_data
);
2150 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2153 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2158 var ctl
= this._sock
.rQpeek8();
2160 // Keep tight reset bits
2161 resetStreams
= ctl
& 0xF;
2163 // Figure out filter
2165 streamId
= ctl
& 0x3;
2167 if (ctl
=== 0x08) cmode
= "fill";
2168 else if (ctl
=== 0x09) cmode
= "jpeg";
2169 else if (ctl
=== 0x0A) cmode
= "png";
2170 else if (ctl
& 0x04) cmode
= "filter";
2171 else if (ctl
< 0x04) cmode
= "copy";
2172 else return this._fail("Illegal tight compression received, ctl: " + ctl
);
2174 if (isTightPNG
&& (cmode
=== "filter" || cmode
=== "copy")) {
2175 return this._fail("filter/copy received in tightPNG mode");
2179 // fill use fb_depth because TPIXELs drop the padding byte
2180 case "fill": // TPIXEL
2181 this._FBU
.bytes
+= this._fb_depth
;
2183 case "jpeg": // max clength
2184 this._FBU
.bytes
+= 3;
2186 case "png": // max clength
2187 this._FBU
.bytes
+= 3;
2189 case "filter": // filter id + num colors if palette
2190 this._FBU
.bytes
+= 2;
2196 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2198 // Determine FBU.bytes
2202 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);
2203 this._sock
.rQskipBytes(4);
2207 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2208 var cl_offset
= rQi
+ 1;
2211 cl_data
+= rQ
[cl_offset
] & 0x7f;
2212 if (rQ
[cl_offset
] & 0x80) {
2214 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2215 if (rQ
[cl_offset
+ 1] & 0x80) {
2217 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2220 // end inline getTightCLength
2221 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2222 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2224 // We have everything, render it
2225 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2226 data
= this._sock
.rQshiftBytes(cl_data
);
2227 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2230 var filterId
= rQ
[rQi
+ 1];
2231 if (filterId
=== 1) {
2232 if (!handlePalette()) { return false; }
2234 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2235 // Filter 2, Gradient is valid but not use if jpeg is enabled
2236 this._fail("Unsupported tight subencoding received, filter: " + filterId
);
2240 if (!handleCopy()) { return false; }
2245 this._FBU
.bytes
= 0;
2251 TIGHT: function () { return this._encHandlers
.display_tight(false); },
2252 TIGHT_PNG: function () { return this._encHandlers
.display_tight(true); },
2254 last_rect: function () {
2255 this._FBU
.rects
= 0;
2259 handle_FB_resize: function () {
2260 this._fb_width
= this._FBU
.width
;
2261 this._fb_height
= this._FBU
.height
;
2262 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
2263 this._display
.resize(this._fb_width
, this._fb_height
);
2264 this._onFBResize(this, this._fb_width
, this._fb_height
);
2265 this._timing
.fbu_rt_start
= (new Date()).getTime();
2266 this._updateContinuousUpdates();
2268 this._FBU
.bytes
= 0;
2269 this._FBU
.rects
-= 1;
2273 ExtendedDesktopSize: function () {
2274 this._FBU
.bytes
= 1;
2275 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2277 this._supportsSetDesktopSize
= true;
2278 var number_of_screens
= this._sock
.rQpeek8();
2280 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2281 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2283 this._sock
.rQskipBytes(1); // number-of-screens
2284 this._sock
.rQskipBytes(3); // padding
2286 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2287 // Save the id and flags of the first screen
2289 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2290 this._sock
.rQskipBytes(2); // x-position
2291 this._sock
.rQskipBytes(2); // y-position
2292 this._sock
.rQskipBytes(2); // width
2293 this._sock
.rQskipBytes(2); // height
2294 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2296 this._sock
.rQskipBytes(16);
2301 * The x-position indicates the reason for the change:
2303 * 0 - server resized on its own
2304 * 1 - this client requested the resize
2305 * 2 - another client requested the resize
2308 // We need to handle errors when we requested the resize.
2309 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2311 // The y-position indicates the status code from the server
2312 switch (this._FBU
.y
) {
2314 msg
= "Resize is administratively prohibited";
2317 msg
= "Out of resources";
2320 msg
= "Invalid screen layout";
2323 msg
= "Unknown reason";
2326 this._notification("Server did not accept the resize request: "
2331 this._encHandlers
.handle_FB_resize();
2335 DesktopSize: function () {
2336 this._encHandlers
.handle_FB_resize();
2340 Cursor: function () {
2341 Util
.Debug(">> set_cursor");
2342 var x
= this._FBU
.x
; // hotspot-x
2343 var y
= this._FBU
.y
; // hotspot-y
2344 var w
= this._FBU
.width
;
2345 var h
= this._FBU
.height
;
2347 var pixelslength
= w
* h
* this._fb_Bpp
;
2348 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2350 this._FBU
.bytes
= pixelslength
+ masklength
;
2351 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2353 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2354 this._sock
.rQshiftBytes(masklength
),
2357 this._FBU
.bytes
= 0;
2360 Util
.Debug("<< set_cursor");
2364 QEMUExtendedKeyEvent: function () {
2367 var keyboardEvent
= document
.createEvent("keyboardEvent");
2368 if (keyboardEvent
.code
!== undefined) {
2369 this._qemuExtKeyEventSupported
= true;
2370 this._keyboard
.setQEMUVNCKeyboardHandler();
2374 JPEG_quality_lo: function () {
2375 Util
.Error("Server sent jpeg_quality pseudo-encoding");
2378 compress_lo: function () {
2379 Util
.Error("Server sent compress level pseudo-encoding");