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 (keysym
, down
) {
324 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
325 if (typeof down
!== 'undefined') {
326 Util
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
327 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
329 Util
.Info("Sending keysym (down + up): " + keysym
);
330 RFB
.messages
.keyEvent(this._sock
, keysym
, 1);
331 RFB
.messages
.keyEvent(this._sock
, keysym
, 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");
367 if (typeof UsingSocketIO
!== 'undefined') {
370 uri
= this._encrypt
? 'wss' : 'ws';
373 uri
+= '://' + this._rfb_host
+ ':' + this._rfb_port
+ '/' + this._rfb_path
;
374 Util
.Info("connecting to " + uri
);
377 // WebSocket.onopen transitions to the RFB init states
378 this._sock
.open(uri
, this._wsProtocols
);
380 if (e
.name
=== 'SyntaxError') {
381 this._fail("Invalid host or port value given");
383 this._fail("Error while opening websocket (" + e
+ ")");
387 Util
.Debug("<< RFB.connect");
390 _disconnect: function () {
391 Util
.Debug(">> RFB.disconnect");
395 Util
.Debug("<< RFB.disconnect");
398 _init_vars: function () {
401 this._FBU
.subrects
= 0; // RRE and HEXTILE
402 this._FBU
.lines
= 0; // RAW
403 this._FBU
.tiles
= 0; // HEXTILE
404 this._FBU
.zlibs
= []; // TIGHT zlib encoders
405 this._mouse_buttonMask
= 0;
406 this._mouse_arr
= [];
407 this._rfb_tightvnc
= false;
409 // Clear the per connection encoding stats
411 for (i
= 0; i
< this._encodings
.length
; i
++) {
412 this._encStats
[this._encodings
[i
][1]][0] = 0;
415 for (i
= 0; i
< 4; i
++) {
416 this._FBU
.zlibs
[i
] = new Inflator
.Inflate();
420 _print_stats: function () {
421 Util
.Info("Encoding stats for this connection:");
423 for (i
= 0; i
< this._encodings
.length
; i
++) {
424 s
= this._encStats
[this._encodings
[i
][1]];
425 if (s
[0] + s
[1] > 0) {
426 Util
.Info(" " + this._encodings
[i
][0] + ": " + s
[0] + " rects");
430 Util
.Info("Encoding stats since page load:");
431 for (i
= 0; i
< this._encodings
.length
; i
++) {
432 s
= this._encStats
[this._encodings
[i
][1]];
433 Util
.Info(" " + this._encodings
[i
][0] + ": " + s
[1] + " rects");
437 _cleanup: function () {
438 if (this._display
&& this._display
.get_context()) {
439 if (!this._view_only
) { this._keyboard
.ungrab(); }
440 if (!this._view_only
) { this._mouse
.ungrab(); }
441 this._display
.defaultCursor();
442 if (Util
.get_logging() !== 'debug') {
443 // Show noVNC logo on load and when disconnected, unless in
445 this._display
.clear();
455 * disconnected - permanent state
457 _updateConnectionState: function (state
) {
458 var oldstate
= this._rfb_connection_state
;
460 if (state
=== oldstate
) {
461 Util
.Debug("Already in state '" + state
+ "', ignoring");
465 // The 'disconnected' state is permanent for each RFB object
466 if (oldstate
=== 'disconnected') {
467 Util
.Error("Tried changing state of a disconnected RFB object");
471 this._rfb_connection_state
= state
;
473 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
476 if (this._disconnTimer
&& state
!== 'disconnecting') {
477 Util
.Debug("Clearing disconnect timer");
478 clearTimeout(this._disconnTimer
);
479 this._disconnTimer
= null;
480 this._sock
.off('close'); // make sure we don't get a double event
483 this._onUpdateState(this, state
, oldstate
);
486 if (oldstate
!== 'connecting') {
487 Util
.Error("Bad transition to connected state, " +
488 "previous connection state: " + oldstate
);
494 if (oldstate
!== 'disconnecting') {
495 Util
.Error("Bad transition to disconnected state, " +
496 "previous connection state: " + oldstate
);
500 if (this._rfb_disconnect_reason
!== "") {
501 this._onDisconnected(this, this._rfb_disconnect_reason
);
503 // No reason means clean disconnect
504 this._onDisconnected(this);
512 case 'disconnecting':
515 this._disconnTimer
= setTimeout(function () {
516 this._rfb_disconnect_reason
= "Disconnect timeout";
517 this._updateConnectionState('disconnected');
518 }.bind(this), this._disconnectTimeout
* 1000);
522 Util
.Error("Unknown connection state: " + state
);
527 _fail: function (msg
) {
528 switch (this._rfb_connection_state
) {
529 case 'disconnecting':
530 Util
.Error("Error while disconnecting: " + msg
);
533 Util
.Error("Error while connected: " + msg
);
536 Util
.Error("Error while connecting: " + msg
);
539 Util
.Error("RFB error: " + msg
);
542 this._rfb_disconnect_reason
= msg
;
543 this._updateConnectionState('disconnecting');
548 * Send a notification to the UI. Valid levels are:
549 * 'normal'|'warn'|'error'
551 * NOTE: Options could be added in the future.
552 * NOTE: If this function is called multiple times, remember that the
553 * interface could be only showing the latest notification.
555 _notification: function(msg
, level
, options
) {
560 Util
.Debug("Notification[" + level
+ "]:" + msg
);
563 Util
.Error("Invalid notification level: " + level
);
568 this._onNotification(this, msg
, level
, options
);
570 this._onNotification(this, msg
, level
);
574 _handle_message: function () {
575 if (this._sock
.rQlen() === 0) {
576 Util
.Warn("handle_message called on an empty receive queue");
580 switch (this._rfb_connection_state
) {
582 Util
.Error("Got data while disconnected");
586 if (this._flushing
) {
589 if (!this._normal_msg()) {
592 if (this._sock
.rQlen() === 0) {
603 _handleKeyPress: function (keyevent
) {
604 if (this._view_only
) { return; } // View only, skip keyboard, events
606 var down
= (keyevent
.type
== 'keydown');
607 if (this._qemuExtKeyEventSupported
) {
608 var scancode
= XtScancode
[keyevent
.code
];
610 var keysym
= keyevent
.keysym
;
611 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
613 Util
.Error('Unable to find a xt scancode for code = ' + keyevent
.code
);
616 keysym
= keyevent
.keysym
.keysym
;
617 RFB
.messages
.keyEvent(this._sock
, keysym
, down
);
621 _handleMouseButton: function (x
, y
, down
, bmask
) {
623 this._mouse_buttonMask
|= bmask
;
625 this._mouse_buttonMask
^= bmask
;
628 if (this._viewportDrag
) {
629 if (down
&& !this._viewportDragging
) {
630 this._viewportDragging
= true;
631 this._viewportDragPos
= {'x': x
, 'y': y
};
633 // Skip sending mouse events
636 this._viewportDragging
= false;
638 // If the viewport didn't actually move, then treat as a mouse click event
639 // Send the button down event here, as the button up event is sent at the end of this function
640 if (!this._viewportHasMoved
&& !this._view_only
) {
641 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
643 this._viewportHasMoved
= false;
647 if (this._view_only
) { return; } // View only, skip mouse events
649 if (this._rfb_connection_state
!== 'connected') { return; }
650 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
653 _handleMouseMove: function (x
, y
) {
654 if (this._viewportDragging
) {
655 var deltaX
= this._viewportDragPos
.x
- x
;
656 var deltaY
= this._viewportDragPos
.y
- y
;
658 // The goal is to trigger on a certain physical width, the
659 // devicePixelRatio brings us a bit closer but is not optimal.
660 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
662 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
663 Math
.abs(deltaY
) > dragThreshold
)) {
664 this._viewportHasMoved
= true;
666 this._viewportDragPos
= {'x': x
, 'y': y
};
667 this._display
.viewportChangePos(deltaX
, deltaY
);
670 // Skip sending mouse events
674 if (this._view_only
) { return; } // View only, skip mouse events
676 if (this._rfb_connection_state
!== 'connected') { return; }
677 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
682 _negotiate_protocol_version: function () {
683 if (this._sock
.rQlen() < 12) {
684 return this._fail("Incomplete protocol version");
687 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
688 Util
.Info("Server ProtocolVersion: " + sversion
);
691 case "000.000": // UltraVNC repeater
695 case "003.006": // UltraVNC
696 case "003.889": // Apple Remote Desktop
697 this._rfb_version
= 3.3;
700 this._rfb_version
= 3.7;
703 case "004.000": // Intel AMT KVM
704 case "004.001": // RealVNC 4.6
705 case "005.000": // RealVNC 5.3
706 this._rfb_version
= 3.8;
709 return this._fail("Invalid server version " + sversion
);
713 var repeaterID
= this._repeaterID
;
714 while (repeaterID
.length
< 250) {
717 this._sock
.send_string(repeaterID
);
721 if (this._rfb_version
> this._rfb_max_version
) {
722 this._rfb_version
= this._rfb_max_version
;
725 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
726 ".00" + ((this._rfb_version
* 10) % 10);
727 this._sock
.send_string("RFB " + cversion
+ "\n");
728 Util
.Debug('Sent ProtocolVersion: ' + cversion
);
730 this._rfb_init_state
= 'Security';
733 _negotiate_security: function () {
734 if (this._rfb_version
>= 3.7) {
735 // Server sends supported list, client decides
736 var num_types
= this._sock
.rQshift8();
737 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
739 if (num_types
=== 0) {
740 var strlen
= this._sock
.rQshift32();
741 var reason
= this._sock
.rQshiftStr(strlen
);
742 return this._fail("Security failure: " + reason
);
745 this._rfb_auth_scheme
= 0;
746 var types
= this._sock
.rQshiftBytes(num_types
);
747 Util
.Debug("Server security types: " + types
);
748 for (var i
= 0; i
< types
.length
; i
++) {
751 case 2: // VNC Authentication
754 if (types
[i
] > this._rfb_auth_scheme
) {
755 this._rfb_auth_scheme
= types
[i
];
763 if (this._rfb_auth_scheme
=== 0) {
764 return this._fail("Unsupported security types: " + types
);
767 this._sock
.send([this._rfb_auth_scheme
]);
770 if (this._sock
.rQwait("security scheme", 4)) { return false; }
771 this._rfb_auth_scheme
= this._sock
.rQshift32();
774 this._rfb_init_state
= 'Authentication';
775 Util
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
777 return this._init_msg(); // jump to authentication
781 _negotiate_xvp_auth: function () {
782 var xvp_sep
= this._xvp_password_sep
;
783 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
784 if (xvp_auth
.length
< 3) {
785 var msg
= 'XVP credentials required (user' + xvp_sep
+
786 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
787 this._onPasswordRequired(this, msg
);
791 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
792 String
.fromCharCode(xvp_auth
[1].length
) +
795 this._sock
.send_string(xvp_auth_str
);
796 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
797 this._rfb_auth_scheme
= 2;
798 return this._negotiate_authentication();
801 _negotiate_std_vnc_auth: function () {
802 if (this._rfb_password
.length
=== 0) {
803 this._onPasswordRequired(this);
807 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
809 // TODO(directxman12): make genDES not require an Array
810 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
811 var response
= RFB
.genDES(this._rfb_password
, challenge
);
812 this._sock
.send(response
);
813 this._rfb_init_state
= "SecurityResult";
817 _negotiate_tight_tunnels: function (numTunnels
) {
818 var clientSupportedTunnelTypes
= {
819 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
821 var serverSupportedTunnelTypes
= {};
822 // receive tunnel capabilities
823 for (var i
= 0; i
< numTunnels
; i
++) {
824 var cap_code
= this._sock
.rQshift32();
825 var cap_vendor
= this._sock
.rQshiftStr(4);
826 var cap_signature
= this._sock
.rQshiftStr(8);
827 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
830 // choose the notunnel type
831 if (serverSupportedTunnelTypes
[0]) {
832 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
833 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
834 return this._fail("Client's tunnel type had the incorrect vendor or signature");
836 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
837 return false; // wait until we receive the sub auth count to continue
839 return this._fail("Server wanted tunnels, but doesn't support the notunnel type");
843 _negotiate_tight_auth: function () {
844 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
845 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
846 var numTunnels
= this._sock
.rQshift32();
847 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
849 this._rfb_tightvnc
= true;
851 if (numTunnels
> 0) {
852 this._negotiate_tight_tunnels(numTunnels
);
853 return false; // wait until we receive the sub auth to continue
857 // second pass, do the sub-auth negotiation
858 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
859 var subAuthCount
= this._sock
.rQshift32();
860 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
861 this._updateState('SecurityResult');
865 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
867 var clientSupportedTypes
= {
872 var serverSupportedTypes
= [];
874 for (var i
= 0; i
< subAuthCount
; i
++) {
875 var capNum
= this._sock
.rQshift32();
876 var capabilities
= this._sock
.rQshiftStr(12);
877 serverSupportedTypes
.push(capabilities
);
880 for (var authType
in clientSupportedTypes
) {
881 if (serverSupportedTypes
.indexOf(authType
) != -1) {
882 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
885 case 'STDVNOAUTH__': // no auth
886 this._rfb_init_state
= 'SecurityResult';
888 case 'STDVVNCAUTH_': // VNC auth
889 this._rfb_auth_scheme
= 2;
890 return this._init_msg();
892 return this._fail("Unsupported tiny auth scheme: " + authType
);
897 return this._fail("No supported sub-auth types!");
900 _negotiate_authentication: function () {
901 switch (this._rfb_auth_scheme
) {
902 case 0: // connection failed
903 if (this._sock
.rQwait("auth reason", 4)) { return false; }
904 var strlen
= this._sock
.rQshift32();
905 var reason
= this._sock
.rQshiftStr(strlen
);
906 return this._fail("Auth failure: " + reason
);
909 if (this._rfb_version
>= 3.8) {
910 this._rfb_init_state
= 'SecurityResult';
913 this._rfb_init_state
= 'ClientInitialisation';
914 return this._init_msg();
917 return this._negotiate_xvp_auth();
919 case 2: // VNC authentication
920 return this._negotiate_std_vnc_auth();
922 case 16: // TightVNC Security Type
923 return this._negotiate_tight_auth();
926 return this._fail("Unsupported auth scheme: " + this._rfb_auth_scheme
);
930 _handle_security_result: function () {
931 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
932 switch (this._sock
.rQshift32()) {
934 this._rfb_init_state
= 'ClientInitialisation';
935 Util
.Debug('Authentication OK');
936 return this._init_msg();
938 if (this._rfb_version
>= 3.8) {
939 var length
= this._sock
.rQshift32();
940 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
941 var reason
= this._sock
.rQshiftStr(length
);
942 return this._fail(reason
);
944 return this._fail("Authentication failure");
948 return this._fail("Too many auth attempts");
950 return this._fail("Unknown SecurityResult");
954 _negotiate_server_init: function () {
955 if (this._sock
.rQwait("server initialization", 24)) { return false; }
958 this._fb_width
= this._sock
.rQshift16();
959 this._fb_height
= this._sock
.rQshift16();
960 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
963 var bpp
= this._sock
.rQshift8();
964 var depth
= this._sock
.rQshift8();
965 var big_endian
= this._sock
.rQshift8();
966 var true_color
= this._sock
.rQshift8();
968 var red_max
= this._sock
.rQshift16();
969 var green_max
= this._sock
.rQshift16();
970 var blue_max
= this._sock
.rQshift16();
971 var red_shift
= this._sock
.rQshift8();
972 var green_shift
= this._sock
.rQshift8();
973 var blue_shift
= this._sock
.rQshift8();
974 this._sock
.rQskipBytes(3); // padding
976 // NB(directxman12): we don't want to call any callbacks or print messages until
977 // *after* we're past the point where we could backtrack
979 /* Connection name/title */
980 var name_length = this._sock.rQshift32();
981 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
982 this._fb_name = Util.decodeUTF8(this._sock.rQshiftStr(name_length));
984 if (this._rfb_tightvnc) {
985 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
986 // In TightVNC mode, ServerInit message is extended
987 var numServerMessages = this._sock.rQshift16();
988 var numClientMessages = this._sock.rQshift16();
989 var numEncodings = this._sock.rQshift16();
990 this._sock.rQskipBytes(2); // padding
992 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
993 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
995 // we don't actually do anything with the capability information that TIGHT sends,
996 // so we just skip the all of this.
998 // TIGHT server message capabilities
999 this._sock.rQskipBytes(16 * numServerMessages);
1001 // TIGHT client message capabilities
1002 this._sock.rQskipBytes(16 * numClientMessages);
1004 // TIGHT encoding capabilities
1005 this._sock.rQskipBytes(16 * numEncodings);
1008 // NB(directxman12): these are down here so that we don't run them multiple times
1010 Util.Info("Screen: " + this._fb_width + "x" + this._fb_height +
1011 ", bpp: " + bpp + ", depth: " + depth +
1012 ", big_endian: " + big_endian +
1013 ", true_color: " + true_color +
1014 ", red_max: " + red_max +
1015 ", green_max: " + green_max +
1016 ", blue_max: " + blue_max +
1017 ", red_shift: " + red_shift +
1018 ", green_shift: " + green_shift +
1019 ", blue_shift: " + blue_shift);
1021 if (big_endian !== 0) {
1022 Util.Warn("Server native endian is not little endian");
1025 if (red_shift !== 16) {
1026 Util.Warn("Server native red-shift is not 16");
1029 if (blue_shift !== 0) {
1030 Util.Warn("Server native blue-shift is not 0");
1033 // we're past the point where we could backtrack, so it's safe to call this
1034 this._onDesktopName(this, this._fb_name);
1036 if (this._true_color && this._fb_name === "Intel(r) AMT KVM") {
1037 Util.Warn("Intel AMT KVM only supports 8/16 bit depths. Disabling true color");
1038 this._true_color = false;
1041 this._display.set_true_color(this._true_color);
1042 this._display.resize(this._fb_width, this._fb_height);
1043 this._onFBResize(this, this._fb_width, this._fb_height);
1045 if (!this._view_only) { this._keyboard.grab(); }
1046 if (!this._view_only) { this._mouse.grab(); }
1048 if (this._true_color) {
1056 RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
1057 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
1058 RFB.messages.fbUpdateRequests(this._sock, false, this._display.getCleanDirtyReset(), this._fb_width, this._fb_height);
1060 this._timing.fbu_rt_start = (new Date()).getTime();
1061 this._timing.pixels = 0;
1063 this._updateConnectionState('connected');
1067 /* RFB protocol initialization states:
1072 * ClientInitialization - not triggered by server message
1073 * ServerInitialization
1075 _init_msg: function () {
1076 switch (this._rfb_init_state
) {
1077 case 'ProtocolVersion':
1078 return this._negotiate_protocol_version();
1081 return this._negotiate_security();
1083 case 'Authentication':
1084 return this._negotiate_authentication();
1086 case 'SecurityResult':
1087 return this._handle_security_result();
1089 case 'ClientInitialisation':
1090 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1091 this._rfb_init_state
= 'ServerInitialisation';
1094 case 'ServerInitialisation':
1095 return this._negotiate_server_init();
1098 return this._fail("Unknown init state: " +
1099 this._rfb_init_state
);
1103 _handle_set_colour_map_msg: function () {
1104 Util
.Debug("SetColorMapEntries");
1105 this._sock
.rQskip8(); // Padding
1107 var first_colour
= this._sock
.rQshift16();
1108 var num_colours
= this._sock
.rQshift16();
1109 if (this._sock
.rQwait('SetColorMapEntries', num_colours
* 6, 6)) { return false; }
1111 for (var c
= 0; c
< num_colours
; c
++) {
1112 var red
= parseInt(this._sock
.rQshift16() / 256, 10);
1113 var green
= parseInt(this._sock
.rQshift16() / 256, 10);
1114 var blue
= parseInt(this._sock
.rQshift16() / 256, 10);
1115 this._display
.set_colourMap([blue
, green
, red
], first_colour
+ c
);
1117 Util
.Debug("colourMap: " + this._display
.get_colourMap());
1118 Util
.Info("Registered " + num_colours
+ " colourMap entries");
1123 _handle_server_cut_text: function () {
1124 Util
.Debug("ServerCutText");
1125 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1126 this._sock
.rQskipBytes(3); // Padding
1127 var length
= this._sock
.rQshift32();
1128 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1130 var text
= this._sock
.rQshiftStr(length
);
1131 this._onClipboard(this, text
);
1136 _handle_server_fence_msg: function() {
1137 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1138 this._sock
.rQskipBytes(3); // Padding
1139 var flags
= this._sock
.rQshift32();
1140 var length
= this._sock
.rQshift8();
1142 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1145 Util
.Warn("Bad payload length (" + length
+ ") in fence response");
1149 var payload
= this._sock
.rQshiftStr(length
);
1151 this._supportsFence
= true;
1156 * (1<<0) - BlockBefore
1157 * (1<<1) - BlockAfter
1162 if (!(flags
& (1<<31))) {
1163 return this._fail("Unexpected fence response");
1166 // Filter out unsupported flags
1167 // FIXME: support syncNext
1168 flags
&= (1<<0) | (1<<1);
1170 // BlockBefore and BlockAfter are automatically handled by
1171 // the fact that we process each incoming message
1173 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1178 _handle_xvp_msg: function () {
1179 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1180 this._sock
.rQskip8(); // Padding
1181 var xvp_ver
= this._sock
.rQshift8();
1182 var xvp_msg
= this._sock
.rQshift8();
1186 Util
.Error("Operation Failed");
1187 this._notification("XVP Operation Failed", 'error');
1190 this._rfb_xvp_ver
= xvp_ver
;
1191 Util
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1192 this._onXvpInit(this._rfb_xvp_ver
);
1195 this._fail("Disconnected: illegal server XVP message " + xvp_msg
);
1202 _normal_msg: function () {
1205 if (this._FBU
.rects
> 0) {
1208 msg_type
= this._sock
.rQshift8();
1212 case 0: // FramebufferUpdate
1213 var ret
= this._framebufferUpdate();
1215 RFB
.messages
.fbUpdateRequests(this._sock
,
1216 this._enabledContinuousUpdates
,
1217 this._display
.getCleanDirtyReset(),
1218 this._fb_width
, this._fb_height
);
1222 case 1: // SetColorMapEntries
1223 return this._handle_set_colour_map_msg();
1230 case 3: // ServerCutText
1231 return this._handle_server_cut_text();
1233 case 150: // EndOfContinuousUpdates
1234 var first
= !(this._supportsContinuousUpdates
);
1235 this._supportsContinuousUpdates
= true;
1236 this._enabledContinuousUpdates
= false;
1238 this._enabledContinuousUpdates
= true;
1239 this._updateContinuousUpdates();
1240 Util
.Info("Enabling continuous updates.");
1242 // FIXME: We need to send a framebufferupdaterequest here
1243 // if we add support for turning off continuous updates
1247 case 248: // ServerFence
1248 return this._handle_server_fence_msg();
1251 return this._handle_xvp_msg();
1254 this._fail("Disconnected: illegal server message type " + msg_type
);
1255 Util
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1260 _onFlush: function() {
1261 this._flushing
= false;
1262 // Resume processing
1263 if (this._sock
.rQlen() > 0) {
1264 this._handle_message();
1268 _framebufferUpdate: function () {
1272 if (this._FBU
.rects
=== 0) {
1273 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1274 this._sock
.rQskip8(); // Padding
1275 this._FBU
.rects
= this._sock
.rQshift16();
1276 this._FBU
.bytes
= 0;
1277 this._timing
.cur_fbu
= 0;
1278 if (this._timing
.fbu_rt_start
> 0) {
1279 now
= (new Date()).getTime();
1280 Util
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1283 // Make sure the previous frame is fully rendered first
1284 // to avoid building up an excessive queue
1285 if (this._display
.pending()) {
1286 this._flushing
= true;
1287 this._display
.flush();
1292 while (this._FBU
.rects
> 0) {
1293 if (this._rfb_connection_state
!== 'connected') { return false; }
1295 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1296 if (this._FBU
.bytes
=== 0) {
1297 if (this._sock
.rQwait("rect header", 12)) { return false; }
1298 /* New FramebufferUpdate */
1300 var hdr
= this._sock
.rQshiftBytes(12);
1301 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1302 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1303 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1304 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1305 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1306 (hdr
[10] << 8) + hdr
[11], 10);
1308 this._onFBUReceive(this,
1309 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1310 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1311 'encoding': this._FBU
.encoding
,
1312 'encodingName': this._encNames
[this._FBU
.encoding
]});
1314 if (!this._encNames
[this._FBU
.encoding
]) {
1315 this._fail("Disconnected: unsupported encoding " +
1316 this._FBU
.encoding
);
1321 this._timing
.last_fbu
= (new Date()).getTime();
1323 ret
= this._encHandlers
[this._FBU
.encoding
]();
1325 now
= (new Date()).getTime();
1326 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1329 this._encStats
[this._FBU
.encoding
][0]++;
1330 this._encStats
[this._FBU
.encoding
][1]++;
1331 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1334 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1335 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1336 this._timing
.fbu_rt_start
> 0) {
1337 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1338 this._timing
.full_fbu_cnt
++;
1339 Util
.Info("Timing of full FBU, curr: " +
1340 this._timing
.cur_fbu
+ ", total: " +
1341 this._timing
.full_fbu_total
+ ", cnt: " +
1342 this._timing
.full_fbu_cnt
+ ", avg: " +
1343 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1346 if (this._timing
.fbu_rt_start
> 0) {
1347 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1348 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1349 this._timing
.fbu_rt_cnt
++;
1350 Util
.Info("full FBU round-trip, cur: " +
1351 fbu_rt_diff
+ ", total: " +
1352 this._timing
.fbu_rt_total
+ ", cnt: " +
1353 this._timing
.fbu_rt_cnt
+ ", avg: " +
1354 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1355 this._timing
.fbu_rt_start
= 0;
1359 if (!ret
) { return ret
; } // need more data
1362 this._onFBUComplete(this,
1363 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1364 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1365 'encoding': this._FBU
.encoding
,
1366 'encodingName': this._encNames
[this._FBU
.encoding
]});
1368 return true; // We finished this FBU
1371 _updateContinuousUpdates: function() {
1372 if (!this._enabledContinuousUpdates
) { return; }
1374 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1375 this._fb_width
, this._fb_height
);
1379 Util
.make_properties(RFB
, [
1380 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1381 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1382 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1383 ['true_color', 'rw', 'bool'], // Request true color pixel data
1384 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1385 ['shared', 'rw', 'bool'], // Request shared mode
1386 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1387 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1388 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1389 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1390 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1391 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1393 // Callback functions
1394 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1395 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1396 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1397 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1398 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1399 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1400 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1401 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1402 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1403 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1404 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1407 RFB
.prototype.set_local_cursor = function (cursor
) {
1408 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1409 this._local_cursor
= false;
1410 this._display
.disableLocalCursor(); //Only show server-side cursor
1412 if (this._display
.get_cursor_uri()) {
1413 this._local_cursor
= true;
1415 Util
.Warn("Browser does not support local cursor");
1416 this._display
.disableLocalCursor();
1421 RFB
.prototype.get_display = function () { return this._display
; };
1422 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1423 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1427 keyEvent: function (sock
, keysym
, down
) {
1428 var buff
= sock
._sQ
;
1429 var offset
= sock
._sQlen
;
1431 buff
[offset
] = 4; // msg-type
1432 buff
[offset
+ 1] = down
;
1434 buff
[offset
+ 2] = 0;
1435 buff
[offset
+ 3] = 0;
1437 buff
[offset
+ 4] = (keysym
>> 24);
1438 buff
[offset
+ 5] = (keysym
>> 16);
1439 buff
[offset
+ 6] = (keysym
>> 8);
1440 buff
[offset
+ 7] = keysym
;
1446 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1447 function getRFBkeycode(xt_scancode
) {
1448 var upperByte
= (keycode
>> 8);
1449 var lowerByte
= (keycode
& 0x00ff);
1450 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1451 lowerByte
= lowerByte
| 0x80;
1457 var buff
= sock
._sQ
;
1458 var offset
= sock
._sQlen
;
1460 buff
[offset
] = 255; // msg-type
1461 buff
[offset
+ 1] = 0; // sub msg-type
1463 buff
[offset
+ 2] = (down
>> 8);
1464 buff
[offset
+ 3] = down
;
1466 buff
[offset
+ 4] = (keysym
>> 24);
1467 buff
[offset
+ 5] = (keysym
>> 16);
1468 buff
[offset
+ 6] = (keysym
>> 8);
1469 buff
[offset
+ 7] = keysym
;
1471 var RFBkeycode
= getRFBkeycode(keycode
);
1473 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1474 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1475 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1476 buff
[offset
+ 11] = RFBkeycode
;
1482 pointerEvent: function (sock
, x
, y
, mask
) {
1483 var buff
= sock
._sQ
;
1484 var offset
= sock
._sQlen
;
1486 buff
[offset
] = 5; // msg-type
1488 buff
[offset
+ 1] = mask
;
1490 buff
[offset
+ 2] = x
>> 8;
1491 buff
[offset
+ 3] = x
;
1493 buff
[offset
+ 4] = y
>> 8;
1494 buff
[offset
+ 5] = y
;
1500 // TODO(directxman12): make this unicode compatible?
1501 clientCutText: function (sock
, text
) {
1502 var buff
= sock
._sQ
;
1503 var offset
= sock
._sQlen
;
1505 buff
[offset
] = 6; // msg-type
1507 buff
[offset
+ 1] = 0; // padding
1508 buff
[offset
+ 2] = 0; // padding
1509 buff
[offset
+ 3] = 0; // padding
1511 var n
= text
.length
;
1513 buff
[offset
+ 4] = n
>> 24;
1514 buff
[offset
+ 5] = n
>> 16;
1515 buff
[offset
+ 6] = n
>> 8;
1516 buff
[offset
+ 7] = n
;
1518 for (var i
= 0; i
< n
; i
++) {
1519 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1522 sock
._sQlen
+= 8 + n
;
1526 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1527 var buff
= sock
._sQ
;
1528 var offset
= sock
._sQlen
;
1530 buff
[offset
] = 251; // msg-type
1531 buff
[offset
+ 1] = 0; // padding
1532 buff
[offset
+ 2] = width
>> 8; // width
1533 buff
[offset
+ 3] = width
;
1534 buff
[offset
+ 4] = height
>> 8; // height
1535 buff
[offset
+ 5] = height
;
1537 buff
[offset
+ 6] = 1; // number-of-screens
1538 buff
[offset
+ 7] = 0; // padding
1541 buff
[offset
+ 8] = id
>> 24; // id
1542 buff
[offset
+ 9] = id
>> 16;
1543 buff
[offset
+ 10] = id
>> 8;
1544 buff
[offset
+ 11] = id
;
1545 buff
[offset
+ 12] = 0; // x-position
1546 buff
[offset
+ 13] = 0;
1547 buff
[offset
+ 14] = 0; // y-position
1548 buff
[offset
+ 15] = 0;
1549 buff
[offset
+ 16] = width
>> 8; // width
1550 buff
[offset
+ 17] = width
;
1551 buff
[offset
+ 18] = height
>> 8; // height
1552 buff
[offset
+ 19] = height
;
1553 buff
[offset
+ 20] = flags
>> 24; // flags
1554 buff
[offset
+ 21] = flags
>> 16;
1555 buff
[offset
+ 22] = flags
>> 8;
1556 buff
[offset
+ 23] = flags
;
1562 clientFence: function (sock
, flags
, payload
) {
1563 var buff
= sock
._sQ
;
1564 var offset
= sock
._sQlen
;
1566 buff
[offset
] = 248; // msg-type
1568 buff
[offset
+ 1] = 0; // padding
1569 buff
[offset
+ 2] = 0; // padding
1570 buff
[offset
+ 3] = 0; // padding
1572 buff
[offset
+ 4] = flags
>> 24; // flags
1573 buff
[offset
+ 5] = flags
>> 16;
1574 buff
[offset
+ 6] = flags
>> 8;
1575 buff
[offset
+ 7] = flags
;
1577 var n
= payload
.length
;
1579 buff
[offset
+ 8] = n
; // length
1581 for (var i
= 0; i
< n
; i
++) {
1582 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1585 sock
._sQlen
+= 9 + n
;
1589 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1590 var buff
= sock
._sQ
;
1591 var offset
= sock
._sQlen
;
1593 buff
[offset
] = 150; // msg-type
1594 buff
[offset
+ 1] = enable
; // enable-flag
1596 buff
[offset
+ 2] = x
>> 8; // x
1597 buff
[offset
+ 3] = x
;
1598 buff
[offset
+ 4] = y
>> 8; // y
1599 buff
[offset
+ 5] = y
;
1600 buff
[offset
+ 6] = width
>> 8; // width
1601 buff
[offset
+ 7] = width
;
1602 buff
[offset
+ 8] = height
>> 8; // height
1603 buff
[offset
+ 9] = height
;
1609 pixelFormat: function (sock
, bpp
, depth
, true_color
) {
1610 var buff
= sock
._sQ
;
1611 var offset
= sock
._sQlen
;
1613 buff
[offset
] = 0; // msg-type
1615 buff
[offset
+ 1] = 0; // padding
1616 buff
[offset
+ 2] = 0; // padding
1617 buff
[offset
+ 3] = 0; // padding
1619 buff
[offset
+ 4] = bpp
* 8; // bits-per-pixel
1620 buff
[offset
+ 5] = depth
* 8; // depth
1621 buff
[offset
+ 6] = 0; // little-endian
1622 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1624 buff
[offset
+ 8] = 0; // red-max
1625 buff
[offset
+ 9] = 255; // red-max
1627 buff
[offset
+ 10] = 0; // green-max
1628 buff
[offset
+ 11] = 255; // green-max
1630 buff
[offset
+ 12] = 0; // blue-max
1631 buff
[offset
+ 13] = 255; // blue-max
1633 buff
[offset
+ 14] = 16; // red-shift
1634 buff
[offset
+ 15] = 8; // green-shift
1635 buff
[offset
+ 16] = 0; // blue-shift
1637 buff
[offset
+ 17] = 0; // padding
1638 buff
[offset
+ 18] = 0; // padding
1639 buff
[offset
+ 19] = 0; // padding
1645 clientEncodings: function (sock
, encodings
, local_cursor
, true_color
) {
1646 var buff
= sock
._sQ
;
1647 var offset
= sock
._sQlen
;
1649 buff
[offset
] = 2; // msg-type
1650 buff
[offset
+ 1] = 0; // padding
1652 // offset + 2 and offset + 3 are encoding count
1654 var i
, j
= offset
+ 4, cnt
= 0;
1655 for (i
= 0; i
< encodings
.length
; i
++) {
1656 if (encodings
[i
][0] === "Cursor" && !local_cursor
) {
1657 Util
.Debug("Skipping Cursor pseudo-encoding");
1658 } else if (encodings
[i
][0] === "TIGHT" && !true_color
) {
1659 // TODO: remove this when we have tight+non-true-color
1660 Util
.Warn("Skipping tight as it is only supported with true color");
1662 var enc
= encodings
[i
][1];
1663 buff
[j
] = enc
>> 24;
1664 buff
[j
+ 1] = enc
>> 16;
1665 buff
[j
+ 2] = enc
>> 8;
1673 buff
[offset
+ 2] = cnt
>> 8;
1674 buff
[offset
+ 3] = cnt
;
1676 sock
._sQlen
+= j
- offset
;
1680 fbUpdateRequests: function (sock
, onlyNonInc
, cleanDirty
, fb_width
, fb_height
) {
1681 var offsetIncrement
= 0;
1683 var cb
= cleanDirty
.cleanBox
;
1685 if (!onlyNonInc
&& (cb
.w
> 0 && cb
.h
> 0)) {
1686 w
= typeof cb
.w
=== "undefined" ? fb_width
: cb
.w
;
1687 h
= typeof cb
.h
=== "undefined" ? fb_height
: cb
.h
;
1688 // Request incremental for clean box
1689 RFB
.messages
.fbUpdateRequest(sock
, 1, cb
.x
, cb
.y
, w
, h
);
1692 for (var i
= 0; i
< cleanDirty
.dirtyBoxes
.length
; i
++) {
1693 var db
= cleanDirty
.dirtyBoxes
[i
];
1694 // Force all (non-incremental) for dirty box
1695 w
= typeof db
.w
=== "undefined" ? fb_width
: db
.w
;
1696 h
= typeof db
.h
=== "undefined" ? fb_height
: db
.h
;
1697 RFB
.messages
.fbUpdateRequest(sock
, 0, db
.x
, db
.y
, w
, h
);
1701 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1702 var buff
= sock
._sQ
;
1703 var offset
= sock
._sQlen
;
1705 if (typeof(x
) === "undefined") { x
= 0; }
1706 if (typeof(y
) === "undefined") { y
= 0; }
1708 buff
[offset
] = 3; // msg-type
1709 buff
[offset
+ 1] = incremental
;
1711 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1712 buff
[offset
+ 3] = x
& 0xFF;
1714 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1715 buff
[offset
+ 5] = y
& 0xFF;
1717 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1718 buff
[offset
+ 7] = w
& 0xFF;
1720 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1721 buff
[offset
+ 9] = h
& 0xFF;
1728 RFB
.genDES = function (password
, challenge
) {
1730 for (var i
= 0; i
< password
.length
; i
++) {
1731 passwd
.push(password
.charCodeAt(i
));
1733 return (new DES(passwd
)).encrypt(challenge
);
1736 RFB
.encodingHandlers
= {
1738 if (this._FBU
.lines
=== 0) {
1739 this._FBU
.lines
= this._FBU
.height
;
1742 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // at least a line
1743 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1744 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1745 var curr_height
= Math
.min(this._FBU
.lines
,
1746 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* this._fb_Bpp
)));
1747 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1748 curr_height
, this._sock
.get_rQ(),
1749 this._sock
.get_rQi());
1750 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* this._fb_Bpp
);
1751 this._FBU
.lines
-= curr_height
;
1753 if (this._FBU
.lines
> 0) {
1754 this._FBU
.bytes
= this._FBU
.width
* this._fb_Bpp
; // At least another line
1757 this._FBU
.bytes
= 0;
1763 COPYRECT: function () {
1764 this._FBU
.bytes
= 4;
1765 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1766 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1767 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1771 this._FBU
.bytes
= 0;
1777 if (this._FBU
.subrects
=== 0) {
1778 this._FBU
.bytes
= 4 + this._fb_Bpp
;
1779 if (this._sock
.rQwait("RRE", 4 + this._fb_Bpp
)) { return false; }
1780 this._FBU
.subrects
= this._sock
.rQshift32();
1781 color
= this._sock
.rQshiftBytes(this._fb_Bpp
); // Background
1782 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1785 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (this._fb_Bpp
+ 8)) {
1786 color
= this._sock
.rQshiftBytes(this._fb_Bpp
);
1787 var x
= this._sock
.rQshift16();
1788 var y
= this._sock
.rQshift16();
1789 var width
= this._sock
.rQshift16();
1790 var height
= this._sock
.rQshift16();
1791 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1792 this._FBU
.subrects
--;
1795 if (this._FBU
.subrects
> 0) {
1796 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1797 this._FBU
.bytes
= (this._fb_Bpp
+ 8) * chunk
;
1800 this._FBU
.bytes
= 0;
1806 HEXTILE: function () {
1807 var rQ
= this._sock
.get_rQ();
1808 var rQi
= this._sock
.get_rQi();
1810 if (this._FBU
.tiles
=== 0) {
1811 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1812 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1813 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1814 this._FBU
.tiles
= this._FBU
.total_tiles
;
1817 while (this._FBU
.tiles
> 0) {
1818 this._FBU
.bytes
= 1;
1819 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1820 var subencoding
= rQ
[rQi
]; // Peek
1821 if (subencoding
> 30) { // Raw
1822 this._fail("Disconnected: illegal hextile subencoding " + subencoding
);
1827 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1828 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1829 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1830 var x
= this._FBU
.x
+ tile_x
* 16;
1831 var y
= this._FBU
.y
+ tile_y
* 16;
1832 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1833 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1835 // Figure out how much we are expecting
1836 if (subencoding
& 0x01) { // Raw
1837 this._FBU
.bytes
+= w
* h
* this._fb_Bpp
;
1839 if (subencoding
& 0x02) { // Background
1840 this._FBU
.bytes
+= this._fb_Bpp
;
1842 if (subencoding
& 0x04) { // Foreground
1843 this._FBU
.bytes
+= this._fb_Bpp
;
1845 if (subencoding
& 0x08) { // AnySubrects
1846 this._FBU
.bytes
++; // Since we aren't shifting it off
1847 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1848 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1849 if (subencoding
& 0x10) { // SubrectsColoured
1850 this._FBU
.bytes
+= subrects
* (this._fb_Bpp
+ 2);
1852 this._FBU
.bytes
+= subrects
* 2;
1857 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1859 // We know the encoding and have a whole tile
1860 this._FBU
.subencoding
= rQ
[rQi
];
1862 if (this._FBU
.subencoding
=== 0) {
1863 if (this._FBU
.lastsubencoding
& 0x01) {
1864 // Weird: ignore blanks are RAW
1865 Util
.Debug(" Ignoring blank after RAW");
1867 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1869 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1870 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1871 rQi
+= this._FBU
.bytes
- 1;
1873 if (this._FBU
.subencoding
& 0x02) { // Background
1874 if (this._fb_Bpp
== 1) {
1875 this._FBU
.background
= rQ
[rQi
];
1878 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1880 rQi
+= this._fb_Bpp
;
1882 if (this._FBU
.subencoding
& 0x04) { // Foreground
1883 if (this._fb_Bpp
== 1) {
1884 this._FBU
.foreground
= rQ
[rQi
];
1886 // this._fb_Bpp is 4
1887 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1889 rQi
+= this._fb_Bpp
;
1892 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1893 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1897 for (var s
= 0; s
< subrects
; s
++) {
1899 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1900 if (this._fb_Bpp
=== 1) {
1904 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1906 rQi
+= this._fb_Bpp
;
1908 color
= this._FBU
.foreground
;
1913 var sy
= (xy
& 0x0f);
1917 var sw
= (wh
>> 4) + 1;
1918 var sh
= (wh
& 0x0f) + 1;
1920 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1923 this._display
.finishTile();
1925 this._sock
.set_rQi(rQi
);
1926 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
1927 this._FBU
.bytes
= 0;
1931 if (this._FBU
.tiles
=== 0) {
1938 getTightCLength: function (arr
) {
1939 var header
= 1, data
= 0;
1940 data
+= arr
[0] & 0x7f;
1941 if (arr
[0] & 0x80) {
1943 data
+= (arr
[1] & 0x7f) << 7;
1944 if (arr
[1] & 0x80) {
1946 data
+= arr
[2] << 14;
1949 return [header
, data
];
1952 display_tight: function (isTightPNG
) {
1953 if (this._fb_depth
=== 1) {
1954 this._fail("Tight protocol handler only implements true color mode");
1957 this._FBU
.bytes
= 1; // compression-control byte
1958 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
1960 var checksum = function (data
) {
1962 for (var i
= 0; i
< data
.length
; i
++) {
1964 if (sum
> 65536) sum
-= 65536;
1969 var resetStreams
= 0;
1971 var decompress = function (data
, expected
) {
1972 for (var i
= 0; i
< 4; i
++) {
1973 if ((resetStreams
>> i
) & 1) {
1974 this._FBU
.zlibs
[i
].reset();
1975 Util
.Info("Reset zlib stream " + i
);
1979 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
1980 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
1981 /*if (uncompressed.status !== 0) {
1982 Util.Error("Invalid data in zlib stream");
1985 //return uncompressed.data;
1986 return uncompressed
;
1989 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
1990 // Convert indexed (palette based) image data to RGB
1991 // TODO: reduce number of calculations inside loop
1992 var dest
= this._destBuff
;
1993 var w
= Math
.floor((width
+ 7) / 8);
1994 var w1
= Math
.floor(width
/ 8);
1996 /*for (var y = 0; y < height; y++) {
1998 var yoffset = y * width;
1999 var ybitoffset = y * w;
2000 var xoffset, targetbyte;
2001 for (x = 0; x < w1; x++) {
2002 xoffset = yoffset + x * 8;
2003 targetbyte = data[ybitoffset + x];
2004 for (b = 7; b >= 0; b--) {
2005 dp = (xoffset + 7 - b) * 3;
2006 sp = (targetbyte >> b & 1) * 3;
2007 dest[dp] = palette[sp];
2008 dest[dp + 1] = palette[sp + 1];
2009 dest[dp + 2] = palette[sp + 2];
2013 xoffset = yoffset + x * 8;
2014 targetbyte = data[ybitoffset + x];
2015 for (b = 7; b >= 8 - width % 8; b--) {
2016 dp = (xoffset + 7 - b) * 3;
2017 sp = (targetbyte >> b & 1) * 3;
2018 dest[dp] = palette[sp];
2019 dest[dp + 1] = palette[sp + 1];
2020 dest[dp + 2] = palette[sp + 2];
2024 for (var y
= 0; y
< height
; y
++) {
2026 for (x
= 0; x
< w1
; x
++) {
2027 for (b
= 7; b
>= 0; b
--) {
2028 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2029 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2030 dest
[dp
] = palette
[sp
];
2031 dest
[dp
+ 1] = palette
[sp
+ 1];
2032 dest
[dp
+ 2] = palette
[sp
+ 2];
2037 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2038 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2039 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2040 dest
[dp
] = palette
[sp
];
2041 dest
[dp
+ 1] = palette
[sp
+ 1];
2042 dest
[dp
+ 2] = palette
[sp
+ 2];
2050 var indexedToRGBX = function (data
, palette
, width
, height
) {
2051 // Convert indexed (palette based) image data to RGB
2052 var dest
= this._destBuff
;
2053 var total
= width
* height
* 4;
2054 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2055 var sp
= data
[j
] * 3;
2056 dest
[i
] = palette
[sp
];
2057 dest
[i
+ 1] = palette
[sp
+ 1];
2058 dest
[i
+ 2] = palette
[sp
+ 2];
2065 var rQi
= this._sock
.get_rQi();
2066 var rQ
= this._sock
.rQwhole();
2068 var cl_header
, cl_data
;
2070 var handlePalette = function () {
2071 var numColors
= rQ
[rQi
+ 2] + 1;
2072 var paletteSize
= numColors
* this._fb_depth
;
2073 this._FBU
.bytes
+= paletteSize
;
2074 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2076 var bpp
= (numColors
<= 2) ? 1 : 8;
2077 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2079 if (rowSize
* this._FBU
.height
< 12) {
2082 cl_data
= rowSize
* this._FBU
.height
;
2083 //clength = [0, rowSize * this._FBU.height];
2085 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2086 var cl_offset
= rQi
+ 3 + paletteSize
;
2089 cl_data
+= rQ
[cl_offset
] & 0x7f;
2090 if (rQ
[cl_offset
] & 0x80) {
2092 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2093 if (rQ
[cl_offset
+ 1] & 0x80) {
2095 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2098 // end inline getTightCLength
2101 this._FBU
.bytes
+= cl_header
+ cl_data
;
2102 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2104 // Shift ctl, filter id, num colors, palette entries, and clength off
2105 this._sock
.rQskipBytes(3);
2106 //var palette = this._sock.rQshiftBytes(paletteSize);
2107 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2108 this._sock
.rQskipBytes(cl_header
);
2111 data
= this._sock
.rQshiftBytes(cl_data
);
2113 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2116 // Convert indexed (palette based) image data to RGB
2118 if (numColors
== 2) {
2119 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2120 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2122 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2123 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2130 var handleCopy = function () {
2132 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* this._fb_depth
;
2133 if (uncompressedSize
< 12) {
2136 cl_data
= uncompressedSize
;
2138 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2139 var cl_offset
= rQi
+ 1;
2142 cl_data
+= rQ
[cl_offset
] & 0x7f;
2143 if (rQ
[cl_offset
] & 0x80) {
2145 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2146 if (rQ
[cl_offset
+ 1] & 0x80) {
2148 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2151 // end inline getTightCLength
2153 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2154 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2156 // Shift ctl, clength off
2157 this._sock
.rQshiftBytes(1 + cl_header
);
2160 data
= this._sock
.rQshiftBytes(cl_data
);
2162 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2165 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2170 var ctl
= this._sock
.rQpeek8();
2172 // Keep tight reset bits
2173 resetStreams
= ctl
& 0xF;
2175 // Figure out filter
2177 streamId
= ctl
& 0x3;
2179 if (ctl
=== 0x08) cmode
= "fill";
2180 else if (ctl
=== 0x09) cmode
= "jpeg";
2181 else if (ctl
=== 0x0A) cmode
= "png";
2182 else if (ctl
& 0x04) cmode
= "filter";
2183 else if (ctl
< 0x04) cmode
= "copy";
2184 else return this._fail("Illegal tight compression received, ctl: " + ctl
);
2186 if (isTightPNG
&& (cmode
=== "filter" || cmode
=== "copy")) {
2187 return this._fail("filter/copy received in tightPNG mode");
2191 // fill use fb_depth because TPIXELs drop the padding byte
2192 case "fill": // TPIXEL
2193 this._FBU
.bytes
+= this._fb_depth
;
2195 case "jpeg": // max clength
2196 this._FBU
.bytes
+= 3;
2198 case "png": // max clength
2199 this._FBU
.bytes
+= 3;
2201 case "filter": // filter id + num colors if palette
2202 this._FBU
.bytes
+= 2;
2208 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2210 // Determine FBU.bytes
2214 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);
2215 this._sock
.rQskipBytes(4);
2219 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2220 var cl_offset
= rQi
+ 1;
2223 cl_data
+= rQ
[cl_offset
] & 0x7f;
2224 if (rQ
[cl_offset
] & 0x80) {
2226 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2227 if (rQ
[cl_offset
+ 1] & 0x80) {
2229 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2232 // end inline getTightCLength
2233 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2234 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2236 // We have everything, render it
2237 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2238 data
= this._sock
.rQshiftBytes(cl_data
);
2239 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2242 var filterId
= rQ
[rQi
+ 1];
2243 if (filterId
=== 1) {
2244 if (!handlePalette()) { return false; }
2246 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2247 // Filter 2, Gradient is valid but not use if jpeg is enabled
2248 this._fail("Unsupported tight subencoding received, filter: " + filterId
);
2252 if (!handleCopy()) { return false; }
2257 this._FBU
.bytes
= 0;
2263 TIGHT: function () { return this._encHandlers
.display_tight(false); },
2264 TIGHT_PNG: function () { return this._encHandlers
.display_tight(true); },
2266 last_rect: function () {
2267 this._FBU
.rects
= 0;
2271 handle_FB_resize: function () {
2272 this._fb_width
= this._FBU
.width
;
2273 this._fb_height
= this._FBU
.height
;
2274 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
2275 this._display
.resize(this._fb_width
, this._fb_height
);
2276 this._onFBResize(this, this._fb_width
, this._fb_height
);
2277 this._timing
.fbu_rt_start
= (new Date()).getTime();
2278 this._updateContinuousUpdates();
2280 this._FBU
.bytes
= 0;
2281 this._FBU
.rects
-= 1;
2285 ExtendedDesktopSize: function () {
2286 this._FBU
.bytes
= 1;
2287 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2289 this._supportsSetDesktopSize
= true;
2290 var number_of_screens
= this._sock
.rQpeek8();
2292 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2293 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2295 this._sock
.rQskipBytes(1); // number-of-screens
2296 this._sock
.rQskipBytes(3); // padding
2298 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2299 // Save the id and flags of the first screen
2301 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2302 this._sock
.rQskipBytes(2); // x-position
2303 this._sock
.rQskipBytes(2); // y-position
2304 this._sock
.rQskipBytes(2); // width
2305 this._sock
.rQskipBytes(2); // height
2306 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2308 this._sock
.rQskipBytes(16);
2313 * The x-position indicates the reason for the change:
2315 * 0 - server resized on its own
2316 * 1 - this client requested the resize
2317 * 2 - another client requested the resize
2320 // We need to handle errors when we requested the resize.
2321 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2323 // The y-position indicates the status code from the server
2324 switch (this._FBU
.y
) {
2326 msg
= "Resize is administratively prohibited";
2329 msg
= "Out of resources";
2332 msg
= "Invalid screen layout";
2335 msg
= "Unknown reason";
2338 this._notification("Server did not accept the resize request: "
2343 this._encHandlers
.handle_FB_resize();
2347 DesktopSize: function () {
2348 this._encHandlers
.handle_FB_resize();
2352 Cursor: function () {
2353 Util
.Debug(">> set_cursor");
2354 var x
= this._FBU
.x
; // hotspot-x
2355 var y
= this._FBU
.y
; // hotspot-y
2356 var w
= this._FBU
.width
;
2357 var h
= this._FBU
.height
;
2359 var pixelslength
= w
* h
* this._fb_Bpp
;
2360 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2362 this._FBU
.bytes
= pixelslength
+ masklength
;
2363 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2365 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2366 this._sock
.rQshiftBytes(masklength
),
2369 this._FBU
.bytes
= 0;
2372 Util
.Debug("<< set_cursor");
2376 QEMUExtendedKeyEvent: function () {
2379 var keyboardEvent
= document
.createEvent("keyboardEvent");
2380 if (keyboardEvent
.code
!== undefined) {
2381 this._qemuExtKeyEventSupported
= true;
2382 this._keyboard
.setQEMUVNCKeyboardHandler();
2386 JPEG_quality_lo: function () {
2387 Util
.Error("Server sent jpeg_quality pseudo-encoding");
2390 compress_lo: function () {
2391 Util
.Error("Server sent compress level pseudo-encoding");