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)
13 import * as Log
from './util/logging.js';
14 import _
from './util/localization.js';
15 import { decodeUTF8
} from './util/strings.js';
16 import { set_defaults
, make_properties
} from './util/properties.js';
17 import Display
from "./display.js";
18 import Keyboard
from "./input/keyboard.js";
19 import Mouse
from "./input/mouse.js";
20 import Websock
from "./websock.js";
21 import Base64
from "./base64.js";
22 import DES
from "./des.js";
23 import KeyTable
from "./input/keysym.js";
24 import XtScancode
from "./input/xtscancodes.js";
25 import Inflator
from "./inflator.js";
27 /*jslint white: false, browser: true */
28 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
30 export default function RFB(defaults
) {
37 this._rfb_port
= 5900;
38 this._rfb_password
= '';
41 this._rfb_connection_state
= '';
42 this._rfb_init_state
= '';
43 this._rfb_version
= 0;
44 this._rfb_max_version
= 3.8;
45 this._rfb_auth_scheme
= '';
46 this._rfb_disconnect_reason
= "";
48 this._rfb_tightvnc
= false;
49 this._rfb_xvp_ver
= 0;
51 // In preference order
60 // Psuedo-encoding settings
62 //['JPEG_quality_lo', -32 ],
63 ['JPEG_quality_med', -26 ],
64 //['JPEG_quality_hi', -23 ],
65 //['compress_lo', -255 ],
66 ['compress_hi', -254 ],
67 //['compress_max', -247 ],
69 ['DesktopSize', -223 ],
72 ['QEMUExtendedKeyEvent', -258 ],
73 ['ExtendedDesktopSize', -308 ],
76 ['ContinuousUpdates', -313 ]
79 this._encHandlers
= {};
83 this._sock
= null; // Websock object
84 this._display
= null; // Display object
85 this._flushing
= false; // Display flushing state
86 this._keyboard
= null; // Keyboard input handler object
87 this._mouse
= null; // Mouse input handler object
88 this._disconnTimer
= null; // disconnection timer
90 this._supportsFence
= false;
92 this._supportsContinuousUpdates
= false;
93 this._enabledContinuousUpdates
= false;
95 // Frame buffer update state
109 zlib
: [] // TIGHT zlib streams
116 this._destBuff
= null;
117 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
119 this._rre_chunk_sz
= 100;
134 this._supportsSetDesktopSize
= false;
136 this._screen_flags
= 0;
139 this._mouse_buttonMask
= 0;
140 this._mouse_arr
= [];
141 this._viewportDragging
= false;
142 this._viewportDragPos
= {};
143 this._viewportHasMoved
= false;
145 // QEMU Extended Key Event support - default to false
146 this._qemuExtKeyEventSupported
= false;
148 // set the default value on user-facing properties
149 set_defaults(this, defaults
, {
150 'target': 'null', // VNC display rendering Canvas object
151 'focusContainer': document
, // DOM element that captures keyboard input
152 'encrypt': false, // Use TLS/SSL/wss encryption
153 'local_cursor': false, // Request locally rendered cursor
154 'shared': true, // Request shared mode
155 'view_only': false, // Disable client mouse/keyboard
156 'xvp_password_sep': '@', // Separator for XVP password fields
157 'disconnectTimeout': 3, // Time (s) to wait for disconnection
158 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
159 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
160 'viewportDrag': false, // Move the viewport on mouse drags
162 // Callback functions
163 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
164 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
165 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
166 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
167 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
168 'onBell': function () { }, // onBell(rfb): RFB Bell message received
169 'onFBUReceive': function () { }, // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
170 'onFBUComplete': function () { }, // onFBUComplete(rfb, fbu): RFB FBU received and processed
171 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
172 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
173 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
177 Log
.Debug(">> RFB.constructor");
179 // populate encHandlers with bound versions
180 Object
.keys(RFB
.encodingHandlers
).forEach(function (encName
) {
181 this._encHandlers
[encName
] = RFB
.encodingHandlers
[encName
].bind(this);
184 // Create lookup tables based on encoding number
185 for (var i
= 0; i
< this._encodings
.length
; i
++) {
186 this._encHandlers
[this._encodings
[i
][1]] = this._encHandlers
[this._encodings
[i
][0]];
187 this._encNames
[this._encodings
[i
][1]] = this._encodings
[i
][0];
188 this._encStats
[this._encodings
[i
][1]] = [0, 0];
191 // NB: nothing that needs explicit teardown should be done
192 // before this point, since this can throw an exception
194 this._display
= new Display({target
: this._target
,
195 onFlush
: this._onFlush
.bind(this)});
197 Log
.Error("Display exception: " + exc
);
201 this._keyboard
= new Keyboard({target
: this._focusContainer
,
202 onKeyEvent
: this._handleKeyEvent
.bind(this)});
204 this._mouse
= new Mouse({target
: this._target
,
205 onMouseButton
: this._handleMouseButton
.bind(this),
206 onMouseMove
: this._handleMouseMove
.bind(this)});
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 Log
.Debug("Starting VNC handshake");
216 this._fail("Unexpected server connection");
219 this._sock
.on('close', function (e
) {
220 Log
.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 // Handle disconnects that were initiated server-side
238 this._updateConnectionState('disconnecting');
239 this._updateConnectionState('disconnected');
242 this._fail("Unexpected server disconnect",
243 "Already disconnected: " + msg
);
246 this._fail("Unexpected server disconnect",
247 "Not in any state yet: " + msg
);
250 this._sock
.off('close');
252 this._sock
.on('error', function (e
) {
253 Log
.Warn("WebSocket on-error event");
259 var rmode
= this._display
.get_render_mode();
260 Log
.Info("Using native WebSockets, render mode: " + rmode
);
262 Log
.Debug("<< RFB.constructor");
267 connect: function (host
, port
, password
, path
) {
268 this._rfb_host
= host
;
269 this._rfb_port
= port
;
270 this._rfb_password
= (password
!== undefined) ? password
: "";
271 this._rfb_path
= (path
!== undefined) ? path
: "";
273 if (!this._rfb_host
) {
278 this._rfb_init_state
= '';
279 this._updateConnectionState('connecting');
283 disconnect: function () {
284 this._updateConnectionState('disconnecting');
285 this._sock
.off('error');
286 this._sock
.off('message');
287 this._sock
.off('open');
290 sendPassword: function (passwd
) {
291 this._rfb_password
= passwd
;
292 setTimeout(this._init_msg
.bind(this), 0);
295 sendCtrlAltDel: function () {
296 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
297 Log
.Info("Sending Ctrl-Alt-Del");
299 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
300 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
301 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
302 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
303 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
304 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
309 xvpOp: function (ver
, op
) {
310 if (this._rfb_xvp_ver
< ver
) { return false; }
311 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
312 this._sock
.send_string("\xFA\x00" + String
.fromCharCode(ver
) + String
.fromCharCode(op
));
316 xvpShutdown: function () {
317 return this.xvpOp(1, 2);
320 xvpReboot: function () {
321 return this.xvpOp(1, 3);
324 xvpReset: function () {
325 return this.xvpOp(1, 4);
328 // Send a key press. If 'down' is not specified then send a down key
329 // followed by an up key.
330 sendKey: function (keysym
, code
, down
) {
331 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
333 if (down
=== undefined) {
334 this.sendKey(keysym
, code
, true);
335 this.sendKey(keysym
, code
, false);
339 var scancode
= XtScancode
[code
];
341 if (this._qemuExtKeyEventSupported
&& scancode
) {
343 keysym
= keysym
|| 0;
345 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
347 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
352 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
353 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
359 clipboardPasteFrom: function (text
) {
360 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return; }
361 RFB
.messages
.clientCutText(this._sock
, text
);
364 // Requests a change of remote desktop size. This message is an extension
365 // and may only be sent if we have received an ExtendedDesktopSize message
366 requestDesktopSize: function (width
, height
) {
367 if (this._rfb_connection_state
!== 'connected' ||
372 if (this._supportsSetDesktopSize
) {
373 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
374 this._screen_id
, this._screen_flags
);
385 _connect: function () {
386 Log
.Debug(">> RFB.connect");
390 if (typeof UsingSocketIO
!== 'undefined') {
393 uri
= this._encrypt
? 'wss' : 'ws';
396 uri
+= '://' + this._rfb_host
;
398 uri
+= ':' + this._rfb_port
;
400 uri
+= '/' + this._rfb_path
;
402 Log
.Info("connecting to " + uri
);
405 // WebSocket.onopen transitions to the RFB init states
406 this._sock
.open(uri
, this._wsProtocols
);
408 if (e
.name
=== 'SyntaxError') {
409 this._fail("Invalid host or port value given", e
);
411 this._fail("Error while connecting", e
);
415 Log
.Debug("<< RFB.connect");
418 _disconnect: function () {
419 Log
.Debug(">> RFB.disconnect");
423 Log
.Debug("<< RFB.disconnect");
426 _init_vars: function () {
429 this._FBU
.subrects
= 0; // RRE and HEXTILE
430 this._FBU
.lines
= 0; // RAW
431 this._FBU
.tiles
= 0; // HEXTILE
432 this._FBU
.zlibs
= []; // TIGHT zlib encoders
433 this._mouse_buttonMask
= 0;
434 this._mouse_arr
= [];
435 this._rfb_tightvnc
= false;
437 // Clear the per connection encoding stats
439 for (i
= 0; i
< this._encodings
.length
; i
++) {
440 this._encStats
[this._encodings
[i
][1]][0] = 0;
443 for (i
= 0; i
< 4; i
++) {
444 this._FBU
.zlibs
[i
] = new Inflator();
448 _print_stats: function () {
449 Log
.Info("Encoding stats for this connection:");
451 for (i
= 0; i
< this._encodings
.length
; i
++) {
452 s
= this._encStats
[this._encodings
[i
][1]];
453 if (s
[0] + s
[1] > 0) {
454 Log
.Info(" " + this._encodings
[i
][0] + ": " + s
[0] + " rects");
458 Log
.Info("Encoding stats since page load:");
459 for (i
= 0; i
< this._encodings
.length
; i
++) {
460 s
= this._encStats
[this._encodings
[i
][1]];
461 Log
.Info(" " + this._encodings
[i
][0] + ": " + s
[1] + " rects");
465 _cleanup: function () {
466 if (!this._view_only
) { this._keyboard
.ungrab(); }
467 if (!this._view_only
) { this._mouse
.ungrab(); }
468 this._display
.defaultCursor();
469 if (Log
.get_logging() !== 'debug') {
470 // Show noVNC logo on load and when disconnected, unless in
472 this._display
.clear();
481 * disconnected - permanent state
483 _updateConnectionState: function (state
) {
484 var oldstate
= this._rfb_connection_state
;
486 if (state
=== oldstate
) {
487 Log
.Debug("Already in state '" + state
+ "', ignoring");
491 // The 'disconnected' state is permanent for each RFB object
492 if (oldstate
=== 'disconnected') {
493 Log
.Error("Tried changing state of a disconnected RFB object");
497 // Ensure proper transitions before doing anything
500 if (oldstate
!== 'connecting') {
501 Log
.Error("Bad transition to connected state, " +
502 "previous connection state: " + oldstate
);
508 if (oldstate
!== 'disconnecting') {
509 Log
.Error("Bad transition to disconnected state, " +
510 "previous connection state: " + oldstate
);
516 if (oldstate
!== '') {
517 Log
.Error("Bad transition to connecting state, " +
518 "previous connection state: " + oldstate
);
523 case 'disconnecting':
524 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
525 Log
.Error("Bad transition to disconnecting state, " +
526 "previous connection state: " + oldstate
);
532 Log
.Error("Unknown connection state: " + state
);
536 // State change actions
538 this._rfb_connection_state
= state
;
539 this._onUpdateState(this, state
, oldstate
);
541 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
544 if (this._disconnTimer
&& state
!== 'disconnecting') {
545 Log
.Debug("Clearing disconnect timer");
546 clearTimeout(this._disconnTimer
);
547 this._disconnTimer
= null;
549 // make sure we don't get a double event
550 this._sock
.off('close');
555 // Call onDisconnected callback after onUpdateState since
556 // we don't know if the UI only displays the latest message
557 if (this._rfb_disconnect_reason
!== "") {
558 this._onDisconnected(this, this._rfb_disconnect_reason
);
560 // No reason means clean disconnect
561 this._onDisconnected(this);
569 case 'disconnecting':
572 this._disconnTimer
= setTimeout(function () {
573 this._rfb_disconnect_reason
= _("Disconnect timeout");
574 this._updateConnectionState('disconnected');
575 }.bind(this), this._disconnectTimeout
* 1000);
580 /* Print errors and disconnect
582 * The optional parameter 'details' is used for information that
583 * should be logged but not sent to the user interface.
585 _fail: function (msg
, details
) {
587 if (typeof details
!== 'undefined') {
588 fullmsg
= msg
+ " (" + details
+ ")";
590 switch (this._rfb_connection_state
) {
591 case 'disconnecting':
592 Log
.Error("Failed when disconnecting: " + fullmsg
);
595 Log
.Error("Failed while connected: " + fullmsg
);
598 Log
.Error("Failed when connecting: " + fullmsg
);
601 Log
.Error("RFB failure: " + fullmsg
);
604 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
606 // Transition to disconnected without waiting for socket to close
607 this._updateConnectionState('disconnecting');
608 this._updateConnectionState('disconnected');
614 * Send a notification to the UI. Valid levels are:
615 * 'normal'|'warn'|'error'
617 * NOTE: Options could be added in the future.
618 * NOTE: If this function is called multiple times, remember that the
619 * interface could be only showing the latest notification.
621 _notification: function(msg
, level
, options
) {
626 Log
.Debug("Notification[" + level
+ "]:" + msg
);
629 Log
.Error("Invalid notification level: " + level
);
634 this._onNotification(this, msg
, level
, options
);
636 this._onNotification(this, msg
, level
);
640 _handle_message: function () {
641 if (this._sock
.rQlen() === 0) {
642 Log
.Warn("handle_message called on an empty receive queue");
646 switch (this._rfb_connection_state
) {
648 Log
.Error("Got data while disconnected");
652 if (this._flushing
) {
655 if (!this._normal_msg()) {
658 if (this._sock
.rQlen() === 0) {
669 _handleKeyEvent: function (keysym
, code
, down
) {
670 this.sendKey(keysym
, code
, down
);
673 _handleMouseButton: function (x
, y
, down
, bmask
) {
675 this._mouse_buttonMask
|= bmask
;
677 this._mouse_buttonMask
&= ~bmask
;
680 if (this._viewportDrag
) {
681 if (down
&& !this._viewportDragging
) {
682 this._viewportDragging
= true;
683 this._viewportDragPos
= {'x': x
, 'y': y
};
685 // Skip sending mouse events
688 this._viewportDragging
= false;
690 // If the viewport didn't actually move, then treat as a mouse click event
691 // Send the button down event here, as the button up event is sent at the end of this function
692 if (!this._viewportHasMoved
&& !this._view_only
) {
693 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
695 this._viewportHasMoved
= false;
699 if (this._view_only
) { return; } // View only, skip mouse events
701 if (this._rfb_connection_state
!== 'connected') { return; }
702 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
705 _handleMouseMove: function (x
, y
) {
706 if (this._viewportDragging
) {
707 var deltaX
= this._viewportDragPos
.x
- x
;
708 var deltaY
= this._viewportDragPos
.y
- y
;
710 // The goal is to trigger on a certain physical width, the
711 // devicePixelRatio brings us a bit closer but is not optimal.
712 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
714 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
715 Math
.abs(deltaY
) > dragThreshold
)) {
716 this._viewportHasMoved
= true;
718 this._viewportDragPos
= {'x': x
, 'y': y
};
719 this._display
.viewportChangePos(deltaX
, deltaY
);
722 // Skip sending mouse events
726 if (this._view_only
) { return; } // View only, skip mouse events
728 if (this._rfb_connection_state
!== 'connected') { return; }
729 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
734 _negotiate_protocol_version: function () {
735 if (this._sock
.rQlen() < 12) {
736 return this._fail("Error while negotiating with server",
737 "Incomplete protocol version");
740 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
741 Log
.Info("Server ProtocolVersion: " + sversion
);
744 case "000.000": // UltraVNC repeater
748 case "003.006": // UltraVNC
749 case "003.889": // Apple Remote Desktop
750 this._rfb_version
= 3.3;
753 this._rfb_version
= 3.7;
756 case "004.000": // Intel AMT KVM
757 case "004.001": // RealVNC 4.6
758 case "005.000": // RealVNC 5.3
759 this._rfb_version
= 3.8;
762 return this._fail("Unsupported server",
763 "Invalid server version: " + sversion
);
767 var repeaterID
= this._repeaterID
;
768 while (repeaterID
.length
< 250) {
771 this._sock
.send_string(repeaterID
);
775 if (this._rfb_version
> this._rfb_max_version
) {
776 this._rfb_version
= this._rfb_max_version
;
779 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
780 ".00" + ((this._rfb_version
* 10) % 10);
781 this._sock
.send_string("RFB " + cversion
+ "\n");
782 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
784 this._rfb_init_state
= 'Security';
787 _negotiate_security: function () {
788 // Polyfill since IE and PhantomJS doesn't have
789 // TypedArray.includes()
790 function includes(item
, array
) {
791 for (var i
= 0; i
< array
.length
; i
++) {
792 if (array
[i
] === item
) {
799 if (this._rfb_version
>= 3.7) {
800 // Server sends supported list, client decides
801 var num_types
= this._sock
.rQshift8();
802 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
804 if (num_types
=== 0) {
805 var strlen
= this._sock
.rQshift32();
806 var reason
= this._sock
.rQshiftStr(strlen
);
807 return this._fail("Error while negotiating with server",
808 "Security failure: " + reason
);
811 var types
= this._sock
.rQshiftBytes(num_types
);
812 Log
.Debug("Server security types: " + types
);
814 // Look for each auth in preferred order
815 this._rfb_auth_scheme
= 0;
816 if (includes(1, types
)) {
817 this._rfb_auth_scheme
= 1; // None
818 } else if (includes(22, types
)) {
819 this._rfb_auth_scheme
= 22; // XVP
820 } else if (includes(16, types
)) {
821 this._rfb_auth_scheme
= 16; // Tight
822 } else if (includes(2, types
)) {
823 this._rfb_auth_scheme
= 2; // VNC Auth
825 return this._fail("Unsupported server",
826 "Unsupported security types: " + types
);
829 this._sock
.send([this._rfb_auth_scheme
]);
832 if (this._sock
.rQwait("security scheme", 4)) { return false; }
833 this._rfb_auth_scheme
= this._sock
.rQshift32();
836 this._rfb_init_state
= 'Authentication';
837 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
839 return this._init_msg(); // jump to authentication
843 _negotiate_xvp_auth: function () {
844 var xvp_sep
= this._xvp_password_sep
;
845 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
846 if (xvp_auth
.length
< 3) {
847 var msg
= 'XVP credentials required (user' + xvp_sep
+
848 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
849 this._onPasswordRequired(this, msg
);
853 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
854 String
.fromCharCode(xvp_auth
[1].length
) +
857 this._sock
.send_string(xvp_auth_str
);
858 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
859 this._rfb_auth_scheme
= 2;
860 return this._negotiate_authentication();
863 _negotiate_std_vnc_auth: function () {
864 if (this._rfb_password
.length
=== 0) {
865 this._onPasswordRequired(this);
869 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
871 // TODO(directxman12): make genDES not require an Array
872 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
873 var response
= RFB
.genDES(this._rfb_password
, challenge
);
874 this._sock
.send(response
);
875 this._rfb_init_state
= "SecurityResult";
879 _negotiate_tight_tunnels: function (numTunnels
) {
880 var clientSupportedTunnelTypes
= {
881 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
883 var serverSupportedTunnelTypes
= {};
884 // receive tunnel capabilities
885 for (var i
= 0; i
< numTunnels
; i
++) {
886 var cap_code
= this._sock
.rQshift32();
887 var cap_vendor
= this._sock
.rQshiftStr(4);
888 var cap_signature
= this._sock
.rQshiftStr(8);
889 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
892 // choose the notunnel type
893 if (serverSupportedTunnelTypes
[0]) {
894 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
895 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
896 return this._fail("Unsupported server",
897 "Client's tunnel type had the incorrect " +
898 "vendor or signature");
900 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
901 return false; // wait until we receive the sub auth count to continue
903 return this._fail("Unsupported server",
904 "Server wanted tunnels, but doesn't support " +
905 "the notunnel type");
909 _negotiate_tight_auth: function () {
910 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
911 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
912 var numTunnels
= this._sock
.rQshift32();
913 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
915 this._rfb_tightvnc
= true;
917 if (numTunnels
> 0) {
918 this._negotiate_tight_tunnels(numTunnels
);
919 return false; // wait until we receive the sub auth to continue
923 // second pass, do the sub-auth negotiation
924 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
925 var subAuthCount
= this._sock
.rQshift32();
926 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
927 this._rfb_init_state
= 'SecurityResult';
931 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
933 var clientSupportedTypes
= {
938 var serverSupportedTypes
= [];
940 for (var i
= 0; i
< subAuthCount
; i
++) {
941 var capNum
= this._sock
.rQshift32();
942 var capabilities
= this._sock
.rQshiftStr(12);
943 serverSupportedTypes
.push(capabilities
);
946 for (var authType
in clientSupportedTypes
) {
947 if (serverSupportedTypes
.indexOf(authType
) != -1) {
948 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
951 case 'STDVNOAUTH__': // no auth
952 this._rfb_init_state
= 'SecurityResult';
954 case 'STDVVNCAUTH_': // VNC auth
955 this._rfb_auth_scheme
= 2;
956 return this._init_msg();
958 return this._fail("Unsupported server",
959 "Unsupported tiny auth scheme: " +
965 return this._fail("Unsupported server",
966 "No supported sub-auth types!");
969 _negotiate_authentication: function () {
970 switch (this._rfb_auth_scheme
) {
971 case 0: // connection failed
972 if (this._sock
.rQwait("auth reason", 4)) { return false; }
973 var strlen
= this._sock
.rQshift32();
974 var reason
= this._sock
.rQshiftStr(strlen
);
975 return this._fail("Authentication failure", reason
);
978 if (this._rfb_version
>= 3.8) {
979 this._rfb_init_state
= 'SecurityResult';
982 this._rfb_init_state
= 'ClientInitialisation';
983 return this._init_msg();
986 return this._negotiate_xvp_auth();
988 case 2: // VNC authentication
989 return this._negotiate_std_vnc_auth();
991 case 16: // TightVNC Security Type
992 return this._negotiate_tight_auth();
995 return this._fail("Unsupported server",
996 "Unsupported auth scheme: " +
997 this._rfb_auth_scheme
);
1001 _handle_security_result: function () {
1002 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
1003 switch (this._sock
.rQshift32()) {
1005 this._rfb_init_state
= 'ClientInitialisation';
1006 Log
.Debug('Authentication OK');
1007 return this._init_msg();
1009 if (this._rfb_version
>= 3.8) {
1010 var length
= this._sock
.rQshift32();
1011 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
1012 var reason
= this._sock
.rQshiftStr(length
);
1013 return this._fail("Authentication failure", reason
);
1015 return this._fail("Authentication failure");
1018 return this._fail("Too many authentication attempts");
1020 return this._fail("Unsupported server",
1021 "Unknown SecurityResult");
1025 _negotiate_server_init: function () {
1026 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1029 this._fb_width
= this._sock
.rQshift16();
1030 this._fb_height
= this._sock
.rQshift16();
1031 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1034 var bpp
= this._sock
.rQshift8();
1035 var depth
= this._sock
.rQshift8();
1036 var big_endian
= this._sock
.rQshift8();
1037 var true_color
= this._sock
.rQshift8();
1039 var red_max
= this._sock
.rQshift16();
1040 var green_max
= this._sock
.rQshift16();
1041 var blue_max
= this._sock
.rQshift16();
1042 var red_shift
= this._sock
.rQshift8();
1043 var green_shift
= this._sock
.rQshift8();
1044 var blue_shift
= this._sock
.rQshift8();
1045 this._sock
.rQskipBytes(3); // padding
1047 // NB(directxman12): we don't want to call any callbacks or print messages until
1048 // *after* we're past the point where we could backtrack
1050 /* Connection name/title */
1051 var name_length = this._sock.rQshift32();
1052 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1053 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1055 if (this._rfb_tightvnc) {
1056 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1057 // In TightVNC mode, ServerInit message is extended
1058 var numServerMessages = this._sock.rQshift16();
1059 var numClientMessages = this._sock.rQshift16();
1060 var numEncodings = this._sock.rQshift16();
1061 this._sock.rQskipBytes(2); // padding
1063 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1064 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1066 // we don't actually do anything with the capability information that TIGHT sends,
1067 // so we just skip the all of this.
1069 // TIGHT server message capabilities
1070 this._sock.rQskipBytes(16 * numServerMessages);
1072 // TIGHT client message capabilities
1073 this._sock.rQskipBytes(16 * numClientMessages);
1075 // TIGHT encoding capabilities
1076 this._sock.rQskipBytes(16 * numEncodings);
1079 // NB(directxman12): these are down here so that we don't run them multiple times
1081 Log.Info("Screen: " + this._fb_width + "x" + this._fb_height +
1082 ", bpp: " + bpp + ", depth: " + depth +
1083 ", big_endian: " + big_endian +
1084 ", true_color: " + true_color +
1085 ", red_max: " + red_max +
1086 ", green_max: " + green_max +
1087 ", blue_max: " + blue_max +
1088 ", red_shift: " + red_shift +
1089 ", green_shift: " + green_shift +
1090 ", blue_shift: " + blue_shift);
1092 if (big_endian !== 0) {
1093 Log.Warn("Server native endian is not little endian");
1096 if (red_shift !== 16) {
1097 Log.Warn("Server native red-shift is not 16");
1100 if (blue_shift !== 0) {
1101 Log.Warn("Server native blue-shift is not 0");
1104 // we're past the point where we could backtrack, so it's safe to call this
1105 this._onDesktopName(this, this._fb_name);
1107 this._display.resize(this._fb_width, this._fb_height);
1108 this._onFBResize(this, this._fb_width, this._fb_height);
1110 if (!this._view_only) { this._keyboard.grab(); }
1111 if (!this._view_only) { this._mouse.grab(); }
1113 RFB.messages.pixelFormat(this._sock, 4, 3, true);
1114 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor);
1115 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1117 this._timing.fbu_rt_start = (new Date()).getTime();
1118 this._timing.pixels = 0;
1120 this._updateConnectionState('connected');
1124 /* RFB protocol initialization states:
1129 * ClientInitialization - not triggered by server message
1130 * ServerInitialization
1132 _init_msg: function () {
1133 switch (this._rfb_init_state
) {
1134 case 'ProtocolVersion':
1135 return this._negotiate_protocol_version();
1138 return this._negotiate_security();
1140 case 'Authentication':
1141 return this._negotiate_authentication();
1143 case 'SecurityResult':
1144 return this._handle_security_result();
1146 case 'ClientInitialisation':
1147 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1148 this._rfb_init_state
= 'ServerInitialisation';
1151 case 'ServerInitialisation':
1152 return this._negotiate_server_init();
1155 return this._fail("Internal error", "Unknown init state: " +
1156 this._rfb_init_state
);
1160 _handle_set_colour_map_msg: function () {
1161 Log
.Debug("SetColorMapEntries");
1163 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1166 _handle_server_cut_text: function () {
1167 Log
.Debug("ServerCutText");
1169 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1170 this._sock
.rQskipBytes(3); // Padding
1171 var length
= this._sock
.rQshift32();
1172 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1174 var text
= this._sock
.rQshiftStr(length
);
1176 if (this._view_only
) { return true; }
1178 this._onClipboard(this, text
);
1183 _handle_server_fence_msg: function() {
1184 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1185 this._sock
.rQskipBytes(3); // Padding
1186 var flags
= this._sock
.rQshift32();
1187 var length
= this._sock
.rQshift8();
1189 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1192 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1196 var payload
= this._sock
.rQshiftStr(length
);
1198 this._supportsFence
= true;
1203 * (1<<0) - BlockBefore
1204 * (1<<1) - BlockAfter
1209 if (!(flags
& (1<<31))) {
1210 return this._fail("Internal error",
1211 "Unexpected fence response");
1214 // Filter out unsupported flags
1215 // FIXME: support syncNext
1216 flags
&= (1<<0) | (1<<1);
1218 // BlockBefore and BlockAfter are automatically handled by
1219 // the fact that we process each incoming message
1221 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1226 _handle_xvp_msg: function () {
1227 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1228 this._sock
.rQskip8(); // Padding
1229 var xvp_ver
= this._sock
.rQshift8();
1230 var xvp_msg
= this._sock
.rQshift8();
1234 Log
.Error("Operation Failed");
1235 this._notification("XVP Operation Failed", 'error');
1238 this._rfb_xvp_ver
= xvp_ver
;
1239 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1240 this._onXvpInit(this._rfb_xvp_ver
);
1243 this._fail("Unexpected server message",
1244 "Illegal server XVP message " + xvp_msg
);
1251 _normal_msg: function () {
1254 if (this._FBU
.rects
> 0) {
1257 msg_type
= this._sock
.rQshift8();
1261 case 0: // FramebufferUpdate
1262 var ret
= this._framebufferUpdate();
1263 if (ret
&& !this._enabledContinuousUpdates
) {
1264 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1265 this._fb_width
, this._fb_height
);
1269 case 1: // SetColorMapEntries
1270 return this._handle_set_colour_map_msg();
1277 case 3: // ServerCutText
1278 return this._handle_server_cut_text();
1280 case 150: // EndOfContinuousUpdates
1281 var first
= !(this._supportsContinuousUpdates
);
1282 this._supportsContinuousUpdates
= true;
1283 this._enabledContinuousUpdates
= false;
1285 this._enabledContinuousUpdates
= true;
1286 this._updateContinuousUpdates();
1287 Log
.Info("Enabling continuous updates.");
1289 // FIXME: We need to send a framebufferupdaterequest here
1290 // if we add support for turning off continuous updates
1294 case 248: // ServerFence
1295 return this._handle_server_fence_msg();
1298 return this._handle_xvp_msg();
1301 this._fail("Unexpected server message", "Type:" + msg_type
);
1302 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1307 _onFlush: function() {
1308 this._flushing
= false;
1309 // Resume processing
1310 if (this._sock
.rQlen() > 0) {
1311 this._handle_message();
1315 _framebufferUpdate: function () {
1319 if (this._FBU
.rects
=== 0) {
1320 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1321 this._sock
.rQskip8(); // Padding
1322 this._FBU
.rects
= this._sock
.rQshift16();
1323 this._FBU
.bytes
= 0;
1324 this._timing
.cur_fbu
= 0;
1325 if (this._timing
.fbu_rt_start
> 0) {
1326 now
= (new Date()).getTime();
1327 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1330 // Make sure the previous frame is fully rendered first
1331 // to avoid building up an excessive queue
1332 if (this._display
.pending()) {
1333 this._flushing
= true;
1334 this._display
.flush();
1339 while (this._FBU
.rects
> 0) {
1340 if (this._rfb_connection_state
!== 'connected') { return false; }
1342 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1343 if (this._FBU
.bytes
=== 0) {
1344 if (this._sock
.rQwait("rect header", 12)) { return false; }
1345 /* New FramebufferUpdate */
1347 var hdr
= this._sock
.rQshiftBytes(12);
1348 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1349 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1350 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1351 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1352 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1353 (hdr
[10] << 8) + hdr
[11], 10);
1355 this._onFBUReceive(this,
1356 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1357 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1358 'encoding': this._FBU
.encoding
,
1359 'encodingName': this._encNames
[this._FBU
.encoding
]});
1361 if (!this._encNames
[this._FBU
.encoding
]) {
1362 this._fail("Unexpected server message",
1363 "Unsupported encoding " +
1364 this._FBU
.encoding
);
1369 this._timing
.last_fbu
= (new Date()).getTime();
1371 ret
= this._encHandlers
[this._FBU
.encoding
]();
1373 now
= (new Date()).getTime();
1374 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1377 this._encStats
[this._FBU
.encoding
][0]++;
1378 this._encStats
[this._FBU
.encoding
][1]++;
1379 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1382 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1383 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1384 this._timing
.fbu_rt_start
> 0) {
1385 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1386 this._timing
.full_fbu_cnt
++;
1387 Log
.Info("Timing of full FBU, curr: " +
1388 this._timing
.cur_fbu
+ ", total: " +
1389 this._timing
.full_fbu_total
+ ", cnt: " +
1390 this._timing
.full_fbu_cnt
+ ", avg: " +
1391 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1394 if (this._timing
.fbu_rt_start
> 0) {
1395 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1396 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1397 this._timing
.fbu_rt_cnt
++;
1398 Log
.Info("full FBU round-trip, cur: " +
1399 fbu_rt_diff
+ ", total: " +
1400 this._timing
.fbu_rt_total
+ ", cnt: " +
1401 this._timing
.fbu_rt_cnt
+ ", avg: " +
1402 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1403 this._timing
.fbu_rt_start
= 0;
1407 if (!ret
) { return ret
; } // need more data
1410 this._display
.flip();
1412 this._onFBUComplete(this,
1413 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1414 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1415 'encoding': this._FBU
.encoding
,
1416 'encodingName': this._encNames
[this._FBU
.encoding
]});
1418 return true; // We finished this FBU
1421 _updateContinuousUpdates: function() {
1422 if (!this._enabledContinuousUpdates
) { return; }
1424 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1425 this._fb_width
, this._fb_height
);
1429 make_properties(RFB
, [
1430 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1431 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1432 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1433 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1434 ['shared', 'rw', 'bool'], // Request shared mode
1435 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1436 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1437 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1438 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1439 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1440 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1442 // Callback functions
1443 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1444 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1445 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1446 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1447 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1448 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1449 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1450 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1451 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1452 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1453 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1456 RFB
.prototype.set_local_cursor = function (cursor
) {
1457 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1458 this._local_cursor
= false;
1459 this._display
.disableLocalCursor(); //Only show server-side cursor
1461 if (this._display
.get_cursor_uri()) {
1462 this._local_cursor
= true;
1464 Log
.Warn("Browser does not support local cursor");
1465 this._display
.disableLocalCursor();
1469 // Need to send an updated list of encodings if we are connected
1470 if (this._rfb_connection_state
=== "connected") {
1471 RFB
.messages
.clientEncodings(this._sock
, this._encodings
, cursor
);
1475 RFB
.prototype.set_view_only = function (view_only
) {
1476 this._view_only
= view_only
;
1478 if (this._rfb_connection_state
=== "connecting" ||
1479 this._rfb_connection_state
=== "connected") {
1481 this._keyboard
.ungrab();
1482 this._mouse
.ungrab();
1484 this._keyboard
.grab();
1490 RFB
.prototype.get_display = function () { return this._display
; };
1491 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1492 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1496 keyEvent: function (sock
, keysym
, down
) {
1497 var buff
= sock
._sQ
;
1498 var offset
= sock
._sQlen
;
1500 buff
[offset
] = 4; // msg-type
1501 buff
[offset
+ 1] = down
;
1503 buff
[offset
+ 2] = 0;
1504 buff
[offset
+ 3] = 0;
1506 buff
[offset
+ 4] = (keysym
>> 24);
1507 buff
[offset
+ 5] = (keysym
>> 16);
1508 buff
[offset
+ 6] = (keysym
>> 8);
1509 buff
[offset
+ 7] = keysym
;
1515 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1516 function getRFBkeycode(xt_scancode
) {
1517 var upperByte
= (keycode
>> 8);
1518 var lowerByte
= (keycode
& 0x00ff);
1519 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1520 lowerByte
= lowerByte
| 0x80;
1526 var buff
= sock
._sQ
;
1527 var offset
= sock
._sQlen
;
1529 buff
[offset
] = 255; // msg-type
1530 buff
[offset
+ 1] = 0; // sub msg-type
1532 buff
[offset
+ 2] = (down
>> 8);
1533 buff
[offset
+ 3] = down
;
1535 buff
[offset
+ 4] = (keysym
>> 24);
1536 buff
[offset
+ 5] = (keysym
>> 16);
1537 buff
[offset
+ 6] = (keysym
>> 8);
1538 buff
[offset
+ 7] = keysym
;
1540 var RFBkeycode
= getRFBkeycode(keycode
);
1542 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1543 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1544 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1545 buff
[offset
+ 11] = RFBkeycode
;
1551 pointerEvent: function (sock
, x
, y
, mask
) {
1552 var buff
= sock
._sQ
;
1553 var offset
= sock
._sQlen
;
1555 buff
[offset
] = 5; // msg-type
1557 buff
[offset
+ 1] = mask
;
1559 buff
[offset
+ 2] = x
>> 8;
1560 buff
[offset
+ 3] = x
;
1562 buff
[offset
+ 4] = y
>> 8;
1563 buff
[offset
+ 5] = y
;
1569 // TODO(directxman12): make this unicode compatible?
1570 clientCutText: function (sock
, text
) {
1571 var buff
= sock
._sQ
;
1572 var offset
= sock
._sQlen
;
1574 buff
[offset
] = 6; // msg-type
1576 buff
[offset
+ 1] = 0; // padding
1577 buff
[offset
+ 2] = 0; // padding
1578 buff
[offset
+ 3] = 0; // padding
1580 var n
= text
.length
;
1582 buff
[offset
+ 4] = n
>> 24;
1583 buff
[offset
+ 5] = n
>> 16;
1584 buff
[offset
+ 6] = n
>> 8;
1585 buff
[offset
+ 7] = n
;
1587 for (var i
= 0; i
< n
; i
++) {
1588 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1591 sock
._sQlen
+= 8 + n
;
1595 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1596 var buff
= sock
._sQ
;
1597 var offset
= sock
._sQlen
;
1599 buff
[offset
] = 251; // msg-type
1600 buff
[offset
+ 1] = 0; // padding
1601 buff
[offset
+ 2] = width
>> 8; // width
1602 buff
[offset
+ 3] = width
;
1603 buff
[offset
+ 4] = height
>> 8; // height
1604 buff
[offset
+ 5] = height
;
1606 buff
[offset
+ 6] = 1; // number-of-screens
1607 buff
[offset
+ 7] = 0; // padding
1610 buff
[offset
+ 8] = id
>> 24; // id
1611 buff
[offset
+ 9] = id
>> 16;
1612 buff
[offset
+ 10] = id
>> 8;
1613 buff
[offset
+ 11] = id
;
1614 buff
[offset
+ 12] = 0; // x-position
1615 buff
[offset
+ 13] = 0;
1616 buff
[offset
+ 14] = 0; // y-position
1617 buff
[offset
+ 15] = 0;
1618 buff
[offset
+ 16] = width
>> 8; // width
1619 buff
[offset
+ 17] = width
;
1620 buff
[offset
+ 18] = height
>> 8; // height
1621 buff
[offset
+ 19] = height
;
1622 buff
[offset
+ 20] = flags
>> 24; // flags
1623 buff
[offset
+ 21] = flags
>> 16;
1624 buff
[offset
+ 22] = flags
>> 8;
1625 buff
[offset
+ 23] = flags
;
1631 clientFence: function (sock
, flags
, payload
) {
1632 var buff
= sock
._sQ
;
1633 var offset
= sock
._sQlen
;
1635 buff
[offset
] = 248; // msg-type
1637 buff
[offset
+ 1] = 0; // padding
1638 buff
[offset
+ 2] = 0; // padding
1639 buff
[offset
+ 3] = 0; // padding
1641 buff
[offset
+ 4] = flags
>> 24; // flags
1642 buff
[offset
+ 5] = flags
>> 16;
1643 buff
[offset
+ 6] = flags
>> 8;
1644 buff
[offset
+ 7] = flags
;
1646 var n
= payload
.length
;
1648 buff
[offset
+ 8] = n
; // length
1650 for (var i
= 0; i
< n
; i
++) {
1651 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1654 sock
._sQlen
+= 9 + n
;
1658 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1659 var buff
= sock
._sQ
;
1660 var offset
= sock
._sQlen
;
1662 buff
[offset
] = 150; // msg-type
1663 buff
[offset
+ 1] = enable
; // enable-flag
1665 buff
[offset
+ 2] = x
>> 8; // x
1666 buff
[offset
+ 3] = x
;
1667 buff
[offset
+ 4] = y
>> 8; // y
1668 buff
[offset
+ 5] = y
;
1669 buff
[offset
+ 6] = width
>> 8; // width
1670 buff
[offset
+ 7] = width
;
1671 buff
[offset
+ 8] = height
>> 8; // height
1672 buff
[offset
+ 9] = height
;
1678 pixelFormat: function (sock
, bpp
, depth
, true_color
) {
1679 var buff
= sock
._sQ
;
1680 var offset
= sock
._sQlen
;
1682 buff
[offset
] = 0; // msg-type
1684 buff
[offset
+ 1] = 0; // padding
1685 buff
[offset
+ 2] = 0; // padding
1686 buff
[offset
+ 3] = 0; // padding
1688 buff
[offset
+ 4] = bpp
* 8; // bits-per-pixel
1689 buff
[offset
+ 5] = depth
* 8; // depth
1690 buff
[offset
+ 6] = 0; // little-endian
1691 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1693 buff
[offset
+ 8] = 0; // red-max
1694 buff
[offset
+ 9] = 255; // red-max
1696 buff
[offset
+ 10] = 0; // green-max
1697 buff
[offset
+ 11] = 255; // green-max
1699 buff
[offset
+ 12] = 0; // blue-max
1700 buff
[offset
+ 13] = 255; // blue-max
1702 buff
[offset
+ 14] = 16; // red-shift
1703 buff
[offset
+ 15] = 8; // green-shift
1704 buff
[offset
+ 16] = 0; // blue-shift
1706 buff
[offset
+ 17] = 0; // padding
1707 buff
[offset
+ 18] = 0; // padding
1708 buff
[offset
+ 19] = 0; // padding
1714 clientEncodings: function (sock
, encodings
, local_cursor
) {
1715 var buff
= sock
._sQ
;
1716 var offset
= sock
._sQlen
;
1718 buff
[offset
] = 2; // msg-type
1719 buff
[offset
+ 1] = 0; // padding
1721 // offset + 2 and offset + 3 are encoding count
1723 var i
, j
= offset
+ 4, cnt
= 0;
1724 for (i
= 0; i
< encodings
.length
; i
++) {
1725 if (encodings
[i
][0] === "Cursor" && !local_cursor
) {
1726 Log
.Debug("Skipping Cursor pseudo-encoding");
1728 var enc
= encodings
[i
][1];
1729 buff
[j
] = enc
>> 24;
1730 buff
[j
+ 1] = enc
>> 16;
1731 buff
[j
+ 2] = enc
>> 8;
1739 buff
[offset
+ 2] = cnt
>> 8;
1740 buff
[offset
+ 3] = cnt
;
1742 sock
._sQlen
+= j
- offset
;
1746 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1747 var buff
= sock
._sQ
;
1748 var offset
= sock
._sQlen
;
1750 if (typeof(x
) === "undefined") { x
= 0; }
1751 if (typeof(y
) === "undefined") { y
= 0; }
1753 buff
[offset
] = 3; // msg-type
1754 buff
[offset
+ 1] = incremental
? 1 : 0;
1756 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1757 buff
[offset
+ 3] = x
& 0xFF;
1759 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1760 buff
[offset
+ 5] = y
& 0xFF;
1762 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1763 buff
[offset
+ 7] = w
& 0xFF;
1765 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1766 buff
[offset
+ 9] = h
& 0xFF;
1773 RFB
.genDES = function (password
, challenge
) {
1775 for (var i
= 0; i
< password
.length
; i
++) {
1776 passwd
.push(password
.charCodeAt(i
));
1778 return (new DES(passwd
)).encrypt(challenge
);
1781 RFB
.encodingHandlers
= {
1783 if (this._FBU
.lines
=== 0) {
1784 this._FBU
.lines
= this._FBU
.height
;
1787 this._FBU
.bytes
= this._FBU
.width
* 4; // at least a line
1788 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1789 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1790 var curr_height
= Math
.min(this._FBU
.lines
,
1791 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* 4)));
1792 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1793 curr_height
, this._sock
.get_rQ(),
1794 this._sock
.get_rQi());
1795 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* 4);
1796 this._FBU
.lines
-= curr_height
;
1798 if (this._FBU
.lines
> 0) {
1799 this._FBU
.bytes
= this._FBU
.width
* 4; // At least another line
1802 this._FBU
.bytes
= 0;
1808 COPYRECT: function () {
1809 this._FBU
.bytes
= 4;
1810 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1811 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1812 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1816 this._FBU
.bytes
= 0;
1822 if (this._FBU
.subrects
=== 0) {
1823 this._FBU
.bytes
= 4 + 4;
1824 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1825 this._FBU
.subrects
= this._sock
.rQshift32();
1826 color
= this._sock
.rQshiftBytes(4); // Background
1827 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1830 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1831 color
= this._sock
.rQshiftBytes(4);
1832 var x
= this._sock
.rQshift16();
1833 var y
= this._sock
.rQshift16();
1834 var width
= this._sock
.rQshift16();
1835 var height
= this._sock
.rQshift16();
1836 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1837 this._FBU
.subrects
--;
1840 if (this._FBU
.subrects
> 0) {
1841 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1842 this._FBU
.bytes
= (4 + 8) * chunk
;
1845 this._FBU
.bytes
= 0;
1851 HEXTILE: function () {
1852 var rQ
= this._sock
.get_rQ();
1853 var rQi
= this._sock
.get_rQi();
1855 if (this._FBU
.tiles
=== 0) {
1856 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1857 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1858 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1859 this._FBU
.tiles
= this._FBU
.total_tiles
;
1862 while (this._FBU
.tiles
> 0) {
1863 this._FBU
.bytes
= 1;
1864 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1865 var subencoding
= rQ
[rQi
]; // Peek
1866 if (subencoding
> 30) { // Raw
1867 this._fail("Unexpected server message",
1868 "Illegal hextile subencoding: " + subencoding
);
1873 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1874 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1875 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1876 var x
= this._FBU
.x
+ tile_x
* 16;
1877 var y
= this._FBU
.y
+ tile_y
* 16;
1878 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1879 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1881 // Figure out how much we are expecting
1882 if (subencoding
& 0x01) { // Raw
1883 this._FBU
.bytes
+= w
* h
* 4;
1885 if (subencoding
& 0x02) { // Background
1886 this._FBU
.bytes
+= 4;
1888 if (subencoding
& 0x04) { // Foreground
1889 this._FBU
.bytes
+= 4;
1891 if (subencoding
& 0x08) { // AnySubrects
1892 this._FBU
.bytes
++; // Since we aren't shifting it off
1893 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1894 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1895 if (subencoding
& 0x10) { // SubrectsColoured
1896 this._FBU
.bytes
+= subrects
* (4 + 2);
1898 this._FBU
.bytes
+= subrects
* 2;
1903 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1905 // We know the encoding and have a whole tile
1906 this._FBU
.subencoding
= rQ
[rQi
];
1908 if (this._FBU
.subencoding
=== 0) {
1909 if (this._FBU
.lastsubencoding
& 0x01) {
1910 // Weird: ignore blanks are RAW
1911 Log
.Debug(" Ignoring blank after RAW");
1913 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1915 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1916 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1917 rQi
+= this._FBU
.bytes
- 1;
1919 if (this._FBU
.subencoding
& 0x02) { // Background
1920 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1923 if (this._FBU
.subencoding
& 0x04) { // Foreground
1924 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1928 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1929 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1933 for (var s
= 0; s
< subrects
; s
++) {
1935 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1936 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1939 color
= this._FBU
.foreground
;
1944 var sy
= (xy
& 0x0f);
1948 var sw
= (wh
>> 4) + 1;
1949 var sh
= (wh
& 0x0f) + 1;
1951 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1954 this._display
.finishTile();
1956 this._sock
.set_rQi(rQi
);
1957 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
1958 this._FBU
.bytes
= 0;
1962 if (this._FBU
.tiles
=== 0) {
1969 getTightCLength: function (arr
) {
1970 var header
= 1, data
= 0;
1971 data
+= arr
[0] & 0x7f;
1972 if (arr
[0] & 0x80) {
1974 data
+= (arr
[1] & 0x7f) << 7;
1975 if (arr
[1] & 0x80) {
1977 data
+= arr
[2] << 14;
1980 return [header
, data
];
1983 display_tight: function (isTightPNG
) {
1984 this._FBU
.bytes
= 1; // compression-control byte
1985 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
1987 var checksum = function (data
) {
1989 for (var i
= 0; i
< data
.length
; i
++) {
1991 if (sum
> 65536) sum
-= 65536;
1996 var resetStreams
= 0;
1998 var decompress = function (data
, expected
) {
1999 for (var i
= 0; i
< 4; i
++) {
2000 if ((resetStreams
>> i
) & 1) {
2001 this._FBU
.zlibs
[i
].reset();
2002 Log
.Info("Reset zlib stream " + i
);
2006 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2007 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2008 /*if (uncompressed.status !== 0) {
2009 Log.Error("Invalid data in zlib stream");
2012 //return uncompressed.data;
2013 return uncompressed
;
2016 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2017 // Convert indexed (palette based) image data to RGB
2018 // TODO: reduce number of calculations inside loop
2019 var dest
= this._destBuff
;
2020 var w
= Math
.floor((width
+ 7) / 8);
2021 var w1
= Math
.floor(width
/ 8);
2023 /*for (var y = 0; y < height; y++) {
2025 var yoffset = y * width;
2026 var ybitoffset = y * w;
2027 var xoffset, targetbyte;
2028 for (x = 0; x < w1; x++) {
2029 xoffset = yoffset + x * 8;
2030 targetbyte = data[ybitoffset + x];
2031 for (b = 7; b >= 0; b--) {
2032 dp = (xoffset + 7 - b) * 3;
2033 sp = (targetbyte >> b & 1) * 3;
2034 dest[dp] = palette[sp];
2035 dest[dp + 1] = palette[sp + 1];
2036 dest[dp + 2] = palette[sp + 2];
2040 xoffset = yoffset + x * 8;
2041 targetbyte = data[ybitoffset + x];
2042 for (b = 7; b >= 8 - width % 8; b--) {
2043 dp = (xoffset + 7 - b) * 3;
2044 sp = (targetbyte >> b & 1) * 3;
2045 dest[dp] = palette[sp];
2046 dest[dp + 1] = palette[sp + 1];
2047 dest[dp + 2] = palette[sp + 2];
2051 for (var y
= 0; y
< height
; y
++) {
2053 for (x
= 0; x
< w1
; x
++) {
2054 for (b
= 7; b
>= 0; b
--) {
2055 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2056 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2057 dest
[dp
] = palette
[sp
];
2058 dest
[dp
+ 1] = palette
[sp
+ 1];
2059 dest
[dp
+ 2] = palette
[sp
+ 2];
2064 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2065 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2066 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2067 dest
[dp
] = palette
[sp
];
2068 dest
[dp
+ 1] = palette
[sp
+ 1];
2069 dest
[dp
+ 2] = palette
[sp
+ 2];
2077 var indexedToRGBX = function (data
, palette
, width
, height
) {
2078 // Convert indexed (palette based) image data to RGB
2079 var dest
= this._destBuff
;
2080 var total
= width
* height
* 4;
2081 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2082 var sp
= data
[j
] * 3;
2083 dest
[i
] = palette
[sp
];
2084 dest
[i
+ 1] = palette
[sp
+ 1];
2085 dest
[i
+ 2] = palette
[sp
+ 2];
2092 var rQi
= this._sock
.get_rQi();
2093 var rQ
= this._sock
.rQwhole();
2095 var cl_header
, cl_data
;
2097 var handlePalette = function () {
2098 var numColors
= rQ
[rQi
+ 2] + 1;
2099 var paletteSize
= numColors
* 3;
2100 this._FBU
.bytes
+= paletteSize
;
2101 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2103 var bpp
= (numColors
<= 2) ? 1 : 8;
2104 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2106 if (rowSize
* this._FBU
.height
< 12) {
2109 cl_data
= rowSize
* this._FBU
.height
;
2110 //clength = [0, rowSize * this._FBU.height];
2112 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2113 var cl_offset
= rQi
+ 3 + paletteSize
;
2116 cl_data
+= rQ
[cl_offset
] & 0x7f;
2117 if (rQ
[cl_offset
] & 0x80) {
2119 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2120 if (rQ
[cl_offset
+ 1] & 0x80) {
2122 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2125 // end inline getTightCLength
2128 this._FBU
.bytes
+= cl_header
+ cl_data
;
2129 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2131 // Shift ctl, filter id, num colors, palette entries, and clength off
2132 this._sock
.rQskipBytes(3);
2133 //var palette = this._sock.rQshiftBytes(paletteSize);
2134 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2135 this._sock
.rQskipBytes(cl_header
);
2138 data
= this._sock
.rQshiftBytes(cl_data
);
2140 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2143 // Convert indexed (palette based) image data to RGB
2145 if (numColors
== 2) {
2146 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2147 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2149 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2150 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2157 var handleCopy = function () {
2159 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2160 if (uncompressedSize
< 12) {
2163 cl_data
= uncompressedSize
;
2165 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2166 var cl_offset
= rQi
+ 1;
2169 cl_data
+= rQ
[cl_offset
] & 0x7f;
2170 if (rQ
[cl_offset
] & 0x80) {
2172 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2173 if (rQ
[cl_offset
+ 1] & 0x80) {
2175 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2178 // end inline getTightCLength
2180 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2181 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2183 // Shift ctl, clength off
2184 this._sock
.rQshiftBytes(1 + cl_header
);
2187 data
= this._sock
.rQshiftBytes(cl_data
);
2189 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2192 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2197 var ctl
= this._sock
.rQpeek8();
2199 // Keep tight reset bits
2200 resetStreams
= ctl
& 0xF;
2202 // Figure out filter
2204 streamId
= ctl
& 0x3;
2206 if (ctl
=== 0x08) cmode
= "fill";
2207 else if (ctl
=== 0x09) cmode
= "jpeg";
2208 else if (ctl
=== 0x0A) cmode
= "png";
2209 else if (ctl
& 0x04) cmode
= "filter";
2210 else if (ctl
< 0x04) cmode
= "copy";
2211 else return this._fail("Unexpected server message",
2212 "Illegal tight compression received, " +
2215 if (isTightPNG
&& (cmode
=== "filter" || cmode
=== "copy")) {
2216 return this._fail("Unexpected server message",
2217 "filter/copy received in tightPNG mode");
2221 // fill use depth because TPIXELs drop the padding byte
2222 case "fill": // TPIXEL
2223 this._FBU
.bytes
+= 3;
2225 case "jpeg": // max clength
2226 this._FBU
.bytes
+= 3;
2228 case "png": // max clength
2229 this._FBU
.bytes
+= 3;
2231 case "filter": // filter id + num colors if palette
2232 this._FBU
.bytes
+= 2;
2238 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2240 // Determine FBU.bytes
2244 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);
2245 this._sock
.rQskipBytes(4);
2249 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2250 var cl_offset
= rQi
+ 1;
2253 cl_data
+= rQ
[cl_offset
] & 0x7f;
2254 if (rQ
[cl_offset
] & 0x80) {
2256 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2257 if (rQ
[cl_offset
+ 1] & 0x80) {
2259 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2262 // end inline getTightCLength
2263 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2264 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2266 // We have everything, render it
2267 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2268 data
= this._sock
.rQshiftBytes(cl_data
);
2269 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2272 var filterId
= rQ
[rQi
+ 1];
2273 if (filterId
=== 1) {
2274 if (!handlePalette()) { return false; }
2276 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2277 // Filter 2, Gradient is valid but not use if jpeg is enabled
2278 this._fail("Unexpected server message",
2279 "Unsupported tight subencoding received, " +
2280 "filter: " + filterId
);
2284 if (!handleCopy()) { return false; }
2289 this._FBU
.bytes
= 0;
2295 TIGHT: function () { return this._encHandlers
.display_tight(false); },
2296 TIGHT_PNG: function () { return this._encHandlers
.display_tight(true); },
2298 last_rect: function () {
2299 this._FBU
.rects
= 0;
2303 handle_FB_resize: function () {
2304 this._fb_width
= this._FBU
.width
;
2305 this._fb_height
= this._FBU
.height
;
2306 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
2307 this._display
.resize(this._fb_width
, this._fb_height
);
2308 this._onFBResize(this, this._fb_width
, this._fb_height
);
2309 this._timing
.fbu_rt_start
= (new Date()).getTime();
2310 this._updateContinuousUpdates();
2312 this._FBU
.bytes
= 0;
2313 this._FBU
.rects
-= 1;
2317 ExtendedDesktopSize: function () {
2318 this._FBU
.bytes
= 1;
2319 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2321 this._supportsSetDesktopSize
= true;
2322 var number_of_screens
= this._sock
.rQpeek8();
2324 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2325 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2327 this._sock
.rQskipBytes(1); // number-of-screens
2328 this._sock
.rQskipBytes(3); // padding
2330 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2331 // Save the id and flags of the first screen
2333 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2334 this._sock
.rQskipBytes(2); // x-position
2335 this._sock
.rQskipBytes(2); // y-position
2336 this._sock
.rQskipBytes(2); // width
2337 this._sock
.rQskipBytes(2); // height
2338 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2340 this._sock
.rQskipBytes(16);
2345 * The x-position indicates the reason for the change:
2347 * 0 - server resized on its own
2348 * 1 - this client requested the resize
2349 * 2 - another client requested the resize
2352 // We need to handle errors when we requested the resize.
2353 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2355 // The y-position indicates the status code from the server
2356 switch (this._FBU
.y
) {
2358 msg
= "Resize is administratively prohibited";
2361 msg
= "Out of resources";
2364 msg
= "Invalid screen layout";
2367 msg
= "Unknown reason";
2370 this._notification("Server did not accept the resize request: "
2375 this._encHandlers
.handle_FB_resize();
2379 DesktopSize: function () {
2380 this._encHandlers
.handle_FB_resize();
2384 Cursor: function () {
2385 Log
.Debug(">> set_cursor");
2386 var x
= this._FBU
.x
; // hotspot-x
2387 var y
= this._FBU
.y
; // hotspot-y
2388 var w
= this._FBU
.width
;
2389 var h
= this._FBU
.height
;
2391 var pixelslength
= w
* h
* 4;
2392 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2394 this._FBU
.bytes
= pixelslength
+ masklength
;
2395 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2397 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2398 this._sock
.rQshiftBytes(masklength
),
2401 this._FBU
.bytes
= 0;
2404 Log
.Debug("<< set_cursor");
2408 QEMUExtendedKeyEvent: function () {
2411 // Old Safari doesn't support creating keyboard events
2413 var keyboardEvent
= document
.createEvent("keyboardEvent");
2414 if (keyboardEvent
.code
!== undefined) {
2415 this._qemuExtKeyEventSupported
= true;
2421 JPEG_quality_lo: function () {
2422 Log
.Error("Server sent jpeg_quality pseudo-encoding");
2425 compress_lo: function () {
2426 Log
.Error("Server sent compress level pseudo-encoding");