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";
26 import { encodings
, encodingName
} from "./encodings.js";
28 /*jslint white: false, browser: true */
29 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
31 export default function RFB(defaults
) {
38 this._rfb_port
= 5900;
39 this._rfb_password
= '';
42 this._rfb_connection_state
= '';
43 this._rfb_init_state
= '';
44 this._rfb_version
= 0;
45 this._rfb_max_version
= 3.8;
46 this._rfb_auth_scheme
= '';
47 this._rfb_disconnect_reason
= "";
49 this._rfb_tightvnc
= false;
50 this._rfb_xvp_ver
= 0;
52 this._encHandlers
= {};
55 this._sock
= null; // Websock object
56 this._display
= null; // Display object
57 this._flushing
= false; // Display flushing state
58 this._keyboard
= null; // Keyboard input handler object
59 this._mouse
= null; // Mouse input handler object
60 this._disconnTimer
= null; // disconnection timer
62 this._supportsFence
= false;
64 this._supportsContinuousUpdates
= false;
65 this._enabledContinuousUpdates
= false;
67 // Frame buffer update state
81 zlib
: [] // TIGHT zlib streams
88 this._destBuff
= null;
89 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
91 this._rre_chunk_sz
= 100;
106 this._supportsSetDesktopSize
= false;
108 this._screen_flags
= 0;
111 this._mouse_buttonMask
= 0;
112 this._mouse_arr
= [];
113 this._viewportDragging
= false;
114 this._viewportDragPos
= {};
115 this._viewportHasMoved
= false;
117 // QEMU Extended Key Event support - default to false
118 this._qemuExtKeyEventSupported
= false;
120 // set the default value on user-facing properties
121 set_defaults(this, defaults
, {
122 'target': 'null', // VNC display rendering Canvas object
123 'focusContainer': document
, // DOM element that captures keyboard input
124 'encrypt': false, // Use TLS/SSL/wss encryption
125 'local_cursor': false, // Request locally rendered cursor
126 'shared': true, // Request shared mode
127 'view_only': false, // Disable client mouse/keyboard
128 'xvp_password_sep': '@', // Separator for XVP password fields
129 'disconnectTimeout': 3, // Time (s) to wait for disconnection
130 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
131 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
132 'viewportDrag': false, // Move the viewport on mouse drags
134 // Callback functions
135 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
136 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
137 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
138 'onPasswordRequired': function () { }, // onPasswordRequired(rfb, msg): VNC password is required
139 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
140 'onBell': function () { }, // onBell(rfb): RFB Bell message received
141 'onFBUReceive': function () { }, // onFBUReceive(rfb, rect): RFB FBU rect received but not yet processed
142 'onFBUComplete': function () { }, // onFBUComplete(rfb): RFB FBU received and processed
143 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
144 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
145 'onXvpInit': function () { } // onXvpInit(version): XVP extensions active for this connection
149 Log
.Debug(">> RFB.constructor");
151 // populate encHandlers with bound versions
152 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this);
153 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this);
154 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this);
155 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this);
156 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this);
158 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this);
159 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this);
160 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this);
161 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this);
162 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this);
164 // NB: nothing that needs explicit teardown should be done
165 // before this point, since this can throw an exception
167 this._display
= new Display({target
: this._target
,
168 onFlush
: this._onFlush
.bind(this)});
170 Log
.Error("Display exception: " + exc
);
174 this._keyboard
= new Keyboard({target
: this._focusContainer
,
175 onKeyEvent
: this._handleKeyEvent
.bind(this)});
177 this._mouse
= new Mouse({target
: this._target
,
178 onMouseButton
: this._handleMouseButton
.bind(this),
179 onMouseMove
: this._handleMouseMove
.bind(this)});
181 this._sock
= new Websock();
182 this._sock
.on('message', this._handle_message
.bind(this));
183 this._sock
.on('open', function () {
184 if ((this._rfb_connection_state
=== 'connecting') &&
185 (this._rfb_init_state
=== '')) {
186 this._rfb_init_state
= 'ProtocolVersion';
187 Log
.Debug("Starting VNC handshake");
189 this._fail("Unexpected server connection");
192 this._sock
.on('close', function (e
) {
193 Log
.Warn("WebSocket on-close event");
196 msg
= " (code: " + e
.code
;
198 msg
+= ", reason: " + e
.reason
;
202 switch (this._rfb_connection_state
) {
203 case 'disconnecting':
204 this._updateConnectionState('disconnected');
207 this._fail('Failed to connect to server', msg
);
210 // Handle disconnects that were initiated server-side
211 this._updateConnectionState('disconnecting');
212 this._updateConnectionState('disconnected');
215 this._fail("Unexpected server disconnect",
216 "Already disconnected: " + msg
);
219 this._fail("Unexpected server disconnect",
220 "Not in any state yet: " + msg
);
223 this._sock
.off('close');
225 this._sock
.on('error', function (e
) {
226 Log
.Warn("WebSocket on-error event");
232 var rmode
= this._display
.get_render_mode();
233 Log
.Info("Using native WebSockets, render mode: " + rmode
);
235 Log
.Debug("<< RFB.constructor");
240 connect: function (host
, port
, password
, path
) {
241 this._rfb_host
= host
;
242 this._rfb_port
= port
;
243 this._rfb_password
= (password
!== undefined) ? password
: "";
244 this._rfb_path
= (path
!== undefined) ? path
: "";
246 if (!this._rfb_host
) {
251 this._rfb_init_state
= '';
252 this._updateConnectionState('connecting');
256 disconnect: function () {
257 this._updateConnectionState('disconnecting');
258 this._sock
.off('error');
259 this._sock
.off('message');
260 this._sock
.off('open');
263 sendPassword: function (passwd
) {
264 this._rfb_password
= passwd
;
265 setTimeout(this._init_msg
.bind(this), 0);
268 sendCtrlAltDel: function () {
269 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
270 Log
.Info("Sending Ctrl-Alt-Del");
272 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
273 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
274 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
275 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
276 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
277 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
282 xvpOp: function (ver
, op
) {
283 if (this._rfb_xvp_ver
< ver
) { return false; }
284 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
285 this._sock
.send_string("\xFA\x00" + String
.fromCharCode(ver
) + String
.fromCharCode(op
));
289 xvpShutdown: function () {
290 return this.xvpOp(1, 2);
293 xvpReboot: function () {
294 return this.xvpOp(1, 3);
297 xvpReset: function () {
298 return this.xvpOp(1, 4);
301 // Send a key press. If 'down' is not specified then send a down key
302 // followed by an up key.
303 sendKey: function (keysym
, code
, down
) {
304 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
306 if (down
=== undefined) {
307 this.sendKey(keysym
, code
, true);
308 this.sendKey(keysym
, code
, false);
312 var scancode
= XtScancode
[code
];
314 if (this._qemuExtKeyEventSupported
&& scancode
) {
316 keysym
= keysym
|| 0;
318 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
320 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
325 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
326 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
332 clipboardPasteFrom: function (text
) {
333 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return; }
334 RFB
.messages
.clientCutText(this._sock
, text
);
337 // Requests a change of remote desktop size. This message is an extension
338 // and may only be sent if we have received an ExtendedDesktopSize message
339 requestDesktopSize: function (width
, height
) {
340 if (this._rfb_connection_state
!== 'connected' ||
345 if (this._supportsSetDesktopSize
) {
346 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
347 this._screen_id
, this._screen_flags
);
358 _connect: function () {
359 Log
.Debug(">> RFB.connect");
363 if (typeof UsingSocketIO
!== 'undefined') {
366 uri
= this._encrypt
? 'wss' : 'ws';
369 uri
+= '://' + this._rfb_host
;
371 uri
+= ':' + this._rfb_port
;
373 uri
+= '/' + this._rfb_path
;
375 Log
.Info("connecting to " + uri
);
378 // WebSocket.onopen transitions to the RFB init states
379 this._sock
.open(uri
, this._wsProtocols
);
381 if (e
.name
=== 'SyntaxError') {
382 this._fail("Invalid host or port value given", e
);
384 this._fail("Error while connecting", e
);
388 Log
.Debug("<< RFB.connect");
391 _disconnect: function () {
392 Log
.Debug(">> RFB.disconnect");
396 Log
.Debug("<< RFB.disconnect");
399 _init_vars: function () {
402 this._FBU
.subrects
= 0; // RRE and HEXTILE
403 this._FBU
.lines
= 0; // RAW
404 this._FBU
.tiles
= 0; // HEXTILE
405 this._FBU
.zlibs
= []; // TIGHT zlib encoders
406 this._mouse_buttonMask
= 0;
407 this._mouse_arr
= [];
408 this._rfb_tightvnc
= false;
410 // Clear the per connection encoding stats
411 var stats
= this._encStats
;
412 Object
.keys(stats
).forEach(function (key
) {
417 for (i
= 0; i
< 4; i
++) {
418 this._FBU
.zlibs
[i
] = new Inflator();
422 _print_stats: function () {
423 var stats
= this._encStats
;
425 Log
.Info("Encoding stats for this connection:");
426 Object
.keys(stats
).forEach(function (key
) {
428 if (s
[0] + s
[1] > 0) {
429 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
433 Log
.Info("Encoding stats since page load:");
434 Object
.keys(stats
).forEach(function (key
) {
436 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
440 _cleanup: function () {
441 if (!this._view_only
) { this._keyboard
.ungrab(); }
442 if (!this._view_only
) { this._mouse
.ungrab(); }
443 this._display
.defaultCursor();
444 if (Log
.get_logging() !== 'debug') {
445 // Show noVNC logo on load and when disconnected, unless in
447 this._display
.clear();
456 * disconnected - permanent state
458 _updateConnectionState: function (state
) {
459 var oldstate
= this._rfb_connection_state
;
461 if (state
=== oldstate
) {
462 Log
.Debug("Already in state '" + state
+ "', ignoring");
466 // The 'disconnected' state is permanent for each RFB object
467 if (oldstate
=== 'disconnected') {
468 Log
.Error("Tried changing state of a disconnected RFB object");
472 // Ensure proper transitions before doing anything
475 if (oldstate
!== 'connecting') {
476 Log
.Error("Bad transition to connected state, " +
477 "previous connection state: " + oldstate
);
483 if (oldstate
!== 'disconnecting') {
484 Log
.Error("Bad transition to disconnected state, " +
485 "previous connection state: " + oldstate
);
491 if (oldstate
!== '') {
492 Log
.Error("Bad transition to connecting state, " +
493 "previous connection state: " + oldstate
);
498 case 'disconnecting':
499 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
500 Log
.Error("Bad transition to disconnecting state, " +
501 "previous connection state: " + oldstate
);
507 Log
.Error("Unknown connection state: " + state
);
511 // State change actions
513 this._rfb_connection_state
= state
;
514 this._onUpdateState(this, state
, oldstate
);
516 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
519 if (this._disconnTimer
&& state
!== 'disconnecting') {
520 Log
.Debug("Clearing disconnect timer");
521 clearTimeout(this._disconnTimer
);
522 this._disconnTimer
= null;
524 // make sure we don't get a double event
525 this._sock
.off('close');
530 // Call onDisconnected callback after onUpdateState since
531 // we don't know if the UI only displays the latest message
532 if (this._rfb_disconnect_reason
!== "") {
533 this._onDisconnected(this, this._rfb_disconnect_reason
);
535 // No reason means clean disconnect
536 this._onDisconnected(this);
544 case 'disconnecting':
547 this._disconnTimer
= setTimeout(function () {
548 this._rfb_disconnect_reason
= _("Disconnect timeout");
549 this._updateConnectionState('disconnected');
550 }.bind(this), this._disconnectTimeout
* 1000);
555 /* Print errors and disconnect
557 * The optional parameter 'details' is used for information that
558 * should be logged but not sent to the user interface.
560 _fail: function (msg
, details
) {
562 if (typeof details
!== 'undefined') {
563 fullmsg
= msg
+ " (" + details
+ ")";
565 switch (this._rfb_connection_state
) {
566 case 'disconnecting':
567 Log
.Error("Failed when disconnecting: " + fullmsg
);
570 Log
.Error("Failed while connected: " + fullmsg
);
573 Log
.Error("Failed when connecting: " + fullmsg
);
576 Log
.Error("RFB failure: " + fullmsg
);
579 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
581 // Transition to disconnected without waiting for socket to close
582 this._updateConnectionState('disconnecting');
583 this._updateConnectionState('disconnected');
589 * Send a notification to the UI. Valid levels are:
590 * 'normal'|'warn'|'error'
592 * NOTE: Options could be added in the future.
593 * NOTE: If this function is called multiple times, remember that the
594 * interface could be only showing the latest notification.
596 _notification: function(msg
, level
, options
) {
601 Log
.Debug("Notification[" + level
+ "]:" + msg
);
604 Log
.Error("Invalid notification level: " + level
);
609 this._onNotification(this, msg
, level
, options
);
611 this._onNotification(this, msg
, level
);
615 _handle_message: function () {
616 if (this._sock
.rQlen() === 0) {
617 Log
.Warn("handle_message called on an empty receive queue");
621 switch (this._rfb_connection_state
) {
623 Log
.Error("Got data while disconnected");
627 if (this._flushing
) {
630 if (!this._normal_msg()) {
633 if (this._sock
.rQlen() === 0) {
644 _handleKeyEvent: function (keysym
, code
, down
) {
645 this.sendKey(keysym
, code
, down
);
648 _handleMouseButton: function (x
, y
, down
, bmask
) {
650 this._mouse_buttonMask
|= bmask
;
652 this._mouse_buttonMask
&= ~bmask
;
655 if (this._viewportDrag
) {
656 if (down
&& !this._viewportDragging
) {
657 this._viewportDragging
= true;
658 this._viewportDragPos
= {'x': x
, 'y': y
};
660 // Skip sending mouse events
663 this._viewportDragging
= false;
665 // If the viewport didn't actually move, then treat as a mouse click event
666 // Send the button down event here, as the button up event is sent at the end of this function
667 if (!this._viewportHasMoved
&& !this._view_only
) {
668 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
670 this._viewportHasMoved
= false;
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
);
680 _handleMouseMove: function (x
, y
) {
681 if (this._viewportDragging
) {
682 var deltaX
= this._viewportDragPos
.x
- x
;
683 var deltaY
= this._viewportDragPos
.y
- y
;
685 // The goal is to trigger on a certain physical width, the
686 // devicePixelRatio brings us a bit closer but is not optimal.
687 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
689 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
690 Math
.abs(deltaY
) > dragThreshold
)) {
691 this._viewportHasMoved
= true;
693 this._viewportDragPos
= {'x': x
, 'y': y
};
694 this._display
.viewportChangePos(deltaX
, deltaY
);
697 // Skip sending mouse events
701 if (this._view_only
) { return; } // View only, skip mouse events
703 if (this._rfb_connection_state
!== 'connected') { return; }
704 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
709 _negotiate_protocol_version: function () {
710 if (this._sock
.rQlen() < 12) {
711 return this._fail("Error while negotiating with server",
712 "Incomplete protocol version");
715 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
716 Log
.Info("Server ProtocolVersion: " + sversion
);
719 case "000.000": // UltraVNC repeater
723 case "003.006": // UltraVNC
724 case "003.889": // Apple Remote Desktop
725 this._rfb_version
= 3.3;
728 this._rfb_version
= 3.7;
731 case "004.000": // Intel AMT KVM
732 case "004.001": // RealVNC 4.6
733 case "005.000": // RealVNC 5.3
734 this._rfb_version
= 3.8;
737 return this._fail("Unsupported server",
738 "Invalid server version: " + sversion
);
742 var repeaterID
= this._repeaterID
;
743 while (repeaterID
.length
< 250) {
746 this._sock
.send_string(repeaterID
);
750 if (this._rfb_version
> this._rfb_max_version
) {
751 this._rfb_version
= this._rfb_max_version
;
754 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
755 ".00" + ((this._rfb_version
* 10) % 10);
756 this._sock
.send_string("RFB " + cversion
+ "\n");
757 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
759 this._rfb_init_state
= 'Security';
762 _negotiate_security: function () {
763 // Polyfill since IE and PhantomJS doesn't have
764 // TypedArray.includes()
765 function includes(item
, array
) {
766 for (var i
= 0; i
< array
.length
; i
++) {
767 if (array
[i
] === item
) {
774 if (this._rfb_version
>= 3.7) {
775 // Server sends supported list, client decides
776 var num_types
= this._sock
.rQshift8();
777 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
779 if (num_types
=== 0) {
780 var strlen
= this._sock
.rQshift32();
781 var reason
= this._sock
.rQshiftStr(strlen
);
782 return this._fail("Error while negotiating with server",
783 "Security failure: " + reason
);
786 var types
= this._sock
.rQshiftBytes(num_types
);
787 Log
.Debug("Server security types: " + types
);
789 // Look for each auth in preferred order
790 this._rfb_auth_scheme
= 0;
791 if (includes(1, types
)) {
792 this._rfb_auth_scheme
= 1; // None
793 } else if (includes(22, types
)) {
794 this._rfb_auth_scheme
= 22; // XVP
795 } else if (includes(16, types
)) {
796 this._rfb_auth_scheme
= 16; // Tight
797 } else if (includes(2, types
)) {
798 this._rfb_auth_scheme
= 2; // VNC Auth
800 return this._fail("Unsupported server",
801 "Unsupported security types: " + types
);
804 this._sock
.send([this._rfb_auth_scheme
]);
807 if (this._sock
.rQwait("security scheme", 4)) { return false; }
808 this._rfb_auth_scheme
= this._sock
.rQshift32();
811 this._rfb_init_state
= 'Authentication';
812 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
814 return this._init_msg(); // jump to authentication
818 _negotiate_xvp_auth: function () {
819 var xvp_sep
= this._xvp_password_sep
;
820 var xvp_auth
= this._rfb_password
.split(xvp_sep
);
821 if (xvp_auth
.length
< 3) {
822 var msg
= 'XVP credentials required (user' + xvp_sep
+
823 'target' + xvp_sep
+ 'password) -- got only ' + this._rfb_password
;
824 this._onPasswordRequired(this, msg
);
828 var xvp_auth_str
= String
.fromCharCode(xvp_auth
[0].length
) +
829 String
.fromCharCode(xvp_auth
[1].length
) +
832 this._sock
.send_string(xvp_auth_str
);
833 this._rfb_password
= xvp_auth
.slice(2).join(xvp_sep
);
834 this._rfb_auth_scheme
= 2;
835 return this._negotiate_authentication();
838 _negotiate_std_vnc_auth: function () {
839 if (this._rfb_password
.length
=== 0) {
840 this._onPasswordRequired(this);
844 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
846 // TODO(directxman12): make genDES not require an Array
847 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
848 var response
= RFB
.genDES(this._rfb_password
, challenge
);
849 this._sock
.send(response
);
850 this._rfb_init_state
= "SecurityResult";
854 _negotiate_tight_tunnels: function (numTunnels
) {
855 var clientSupportedTunnelTypes
= {
856 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
858 var serverSupportedTunnelTypes
= {};
859 // receive tunnel capabilities
860 for (var i
= 0; i
< numTunnels
; i
++) {
861 var cap_code
= this._sock
.rQshift32();
862 var cap_vendor
= this._sock
.rQshiftStr(4);
863 var cap_signature
= this._sock
.rQshiftStr(8);
864 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
867 // choose the notunnel type
868 if (serverSupportedTunnelTypes
[0]) {
869 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
870 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
871 return this._fail("Unsupported server",
872 "Client's tunnel type had the incorrect " +
873 "vendor or signature");
875 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
876 return false; // wait until we receive the sub auth count to continue
878 return this._fail("Unsupported server",
879 "Server wanted tunnels, but doesn't support " +
880 "the notunnel type");
884 _negotiate_tight_auth: function () {
885 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
886 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
887 var numTunnels
= this._sock
.rQshift32();
888 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
890 this._rfb_tightvnc
= true;
892 if (numTunnels
> 0) {
893 this._negotiate_tight_tunnels(numTunnels
);
894 return false; // wait until we receive the sub auth to continue
898 // second pass, do the sub-auth negotiation
899 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
900 var subAuthCount
= this._sock
.rQshift32();
901 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
902 this._rfb_init_state
= 'SecurityResult';
906 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
908 var clientSupportedTypes
= {
913 var serverSupportedTypes
= [];
915 for (var i
= 0; i
< subAuthCount
; i
++) {
916 var capNum
= this._sock
.rQshift32();
917 var capabilities
= this._sock
.rQshiftStr(12);
918 serverSupportedTypes
.push(capabilities
);
921 for (var authType
in clientSupportedTypes
) {
922 if (serverSupportedTypes
.indexOf(authType
) != -1) {
923 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
926 case 'STDVNOAUTH__': // no auth
927 this._rfb_init_state
= 'SecurityResult';
929 case 'STDVVNCAUTH_': // VNC auth
930 this._rfb_auth_scheme
= 2;
931 return this._init_msg();
933 return this._fail("Unsupported server",
934 "Unsupported tiny auth scheme: " +
940 return this._fail("Unsupported server",
941 "No supported sub-auth types!");
944 _negotiate_authentication: function () {
945 switch (this._rfb_auth_scheme
) {
946 case 0: // connection failed
947 if (this._sock
.rQwait("auth reason", 4)) { return false; }
948 var strlen
= this._sock
.rQshift32();
949 var reason
= this._sock
.rQshiftStr(strlen
);
950 return this._fail("Authentication failure", reason
);
953 if (this._rfb_version
>= 3.8) {
954 this._rfb_init_state
= 'SecurityResult';
957 this._rfb_init_state
= 'ClientInitialisation';
958 return this._init_msg();
961 return this._negotiate_xvp_auth();
963 case 2: // VNC authentication
964 return this._negotiate_std_vnc_auth();
966 case 16: // TightVNC Security Type
967 return this._negotiate_tight_auth();
970 return this._fail("Unsupported server",
971 "Unsupported auth scheme: " +
972 this._rfb_auth_scheme
);
976 _handle_security_result: function () {
977 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
978 switch (this._sock
.rQshift32()) {
980 this._rfb_init_state
= 'ClientInitialisation';
981 Log
.Debug('Authentication OK');
982 return this._init_msg();
984 if (this._rfb_version
>= 3.8) {
985 var length
= this._sock
.rQshift32();
986 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
987 var reason
= this._sock
.rQshiftStr(length
);
988 return this._fail("Authentication failure", reason
);
990 return this._fail("Authentication failure");
993 return this._fail("Too many authentication attempts");
995 return this._fail("Unsupported server",
996 "Unknown SecurityResult");
1000 _negotiate_server_init: function () {
1001 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1004 var width
= this._sock
.rQshift16();
1005 var height
= this._sock
.rQshift16();
1008 var bpp
= this._sock
.rQshift8();
1009 var depth
= this._sock
.rQshift8();
1010 var big_endian
= this._sock
.rQshift8();
1011 var true_color
= this._sock
.rQshift8();
1013 var red_max
= this._sock
.rQshift16();
1014 var green_max
= this._sock
.rQshift16();
1015 var blue_max
= this._sock
.rQshift16();
1016 var red_shift
= this._sock
.rQshift8();
1017 var green_shift
= this._sock
.rQshift8();
1018 var blue_shift
= this._sock
.rQshift8();
1019 this._sock
.rQskipBytes(3); // padding
1021 // NB(directxman12): we don't want to call any callbacks or print messages until
1022 // *after* we're past the point where we could backtrack
1024 /* Connection name/title */
1025 var name_length = this._sock.rQshift32();
1026 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1027 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1029 if (this._rfb_tightvnc) {
1030 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1031 // In TightVNC mode, ServerInit message is extended
1032 var numServerMessages = this._sock.rQshift16();
1033 var numClientMessages = this._sock.rQshift16();
1034 var numEncodings = this._sock.rQshift16();
1035 this._sock.rQskipBytes(2); // padding
1037 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1038 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1040 // we don't actually do anything with the capability information that TIGHT sends,
1041 // so we just skip the all of this.
1043 // TIGHT server message capabilities
1044 this._sock.rQskipBytes(16 * numServerMessages);
1046 // TIGHT client message capabilities
1047 this._sock.rQskipBytes(16 * numClientMessages);
1049 // TIGHT encoding capabilities
1050 this._sock.rQskipBytes(16 * numEncodings);
1053 // NB(directxman12): these are down here so that we don't run them multiple times
1055 Log.Info("Screen: " + width + "x" + height +
1056 ", bpp: " + bpp + ", depth: " + depth +
1057 ", big_endian: " + big_endian +
1058 ", true_color: " + true_color +
1059 ", red_max: " + red_max +
1060 ", green_max: " + green_max +
1061 ", blue_max: " + blue_max +
1062 ", red_shift: " + red_shift +
1063 ", green_shift: " + green_shift +
1064 ", blue_shift: " + blue_shift);
1066 if (big_endian !== 0) {
1067 Log.Warn("Server native endian is not little endian");
1070 if (red_shift !== 16) {
1071 Log.Warn("Server native red-shift is not 16");
1074 if (blue_shift !== 0) {
1075 Log.Warn("Server native blue-shift is not 0");
1078 // we're past the point where we could backtrack, so it's safe to call this
1079 this._onDesktopName(this, this._fb_name);
1081 this._resize(width, height);
1083 if (!this._view_only) { this._keyboard.grab(); }
1084 if (!this._view_only) { this._mouse.grab(); }
1086 this._fb_depth = 24;
1088 if (this._fb_name === "Intel(r) AMT KVM") {
1089 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1093 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1094 this._sendEncodings();
1095 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1097 this._timing.fbu_rt_start = (new Date()).getTime();
1098 this._timing.pixels = 0;
1100 // Cursor will be server side until the server decides to honor
1101 // our request and send over the cursor image
1102 this._display.disableLocalCursor();
1104 this._updateConnectionState('connected');
1108 _sendEncodings: function () {
1111 // In preference order
1112 encs.push(encodings.encodingCopyRect);
1113 // Only supported with full depth support
1114 if (this._fb_depth == 24) {
1115 encs.push(encodings.encodingTight);
1116 encs.push(encodings.encodingHextile);
1117 encs.push(encodings.encodingRRE);
1119 encs.push(encodings.encodingRaw);
1121 // Psuedo-encoding settings
1122 encs.push(encodings.pseudoEncodingTightPNG);
1123 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1124 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1126 encs.push(encodings.pseudoEncodingDesktopSize);
1127 encs.push(encodings.pseudoEncodingLastRect);
1128 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1129 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1130 encs.push(encodings.pseudoEncodingXvp);
1131 encs.push(encodings.pseudoEncodingFence);
1132 encs.push(encodings.pseudoEncodingContinuousUpdates);
1134 if (this._local_cursor && this._fb_depth == 24) {
1135 encs.push(encodings.pseudoEncodingCursor);
1138 RFB.messages.clientEncodings(this._sock, encs);
1141 /* RFB protocol initialization states:
1146 * ClientInitialization - not triggered by server message
1147 * ServerInitialization
1149 _init_msg: function () {
1150 switch (this._rfb_init_state
) {
1151 case 'ProtocolVersion':
1152 return this._negotiate_protocol_version();
1155 return this._negotiate_security();
1157 case 'Authentication':
1158 return this._negotiate_authentication();
1160 case 'SecurityResult':
1161 return this._handle_security_result();
1163 case 'ClientInitialisation':
1164 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1165 this._rfb_init_state
= 'ServerInitialisation';
1168 case 'ServerInitialisation':
1169 return this._negotiate_server_init();
1172 return this._fail("Internal error", "Unknown init state: " +
1173 this._rfb_init_state
);
1177 _handle_set_colour_map_msg: function () {
1178 Log
.Debug("SetColorMapEntries");
1180 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1183 _handle_server_cut_text: function () {
1184 Log
.Debug("ServerCutText");
1186 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1187 this._sock
.rQskipBytes(3); // Padding
1188 var length
= this._sock
.rQshift32();
1189 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1191 var text
= this._sock
.rQshiftStr(length
);
1193 if (this._view_only
) { return true; }
1195 this._onClipboard(this, text
);
1200 _handle_server_fence_msg: function() {
1201 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1202 this._sock
.rQskipBytes(3); // Padding
1203 var flags
= this._sock
.rQshift32();
1204 var length
= this._sock
.rQshift8();
1206 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1209 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1213 var payload
= this._sock
.rQshiftStr(length
);
1215 this._supportsFence
= true;
1220 * (1<<0) - BlockBefore
1221 * (1<<1) - BlockAfter
1226 if (!(flags
& (1<<31))) {
1227 return this._fail("Internal error",
1228 "Unexpected fence response");
1231 // Filter out unsupported flags
1232 // FIXME: support syncNext
1233 flags
&= (1<<0) | (1<<1);
1235 // BlockBefore and BlockAfter are automatically handled by
1236 // the fact that we process each incoming message
1238 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1243 _handle_xvp_msg: function () {
1244 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1245 this._sock
.rQskip8(); // Padding
1246 var xvp_ver
= this._sock
.rQshift8();
1247 var xvp_msg
= this._sock
.rQshift8();
1251 Log
.Error("Operation Failed");
1252 this._notification("XVP Operation Failed", 'error');
1255 this._rfb_xvp_ver
= xvp_ver
;
1256 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1257 this._onXvpInit(this._rfb_xvp_ver
);
1260 this._fail("Unexpected server message",
1261 "Illegal server XVP message " + xvp_msg
);
1268 _normal_msg: function () {
1271 if (this._FBU
.rects
> 0) {
1274 msg_type
= this._sock
.rQshift8();
1278 case 0: // FramebufferUpdate
1279 var ret
= this._framebufferUpdate();
1280 if (ret
&& !this._enabledContinuousUpdates
) {
1281 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1282 this._fb_width
, this._fb_height
);
1286 case 1: // SetColorMapEntries
1287 return this._handle_set_colour_map_msg();
1294 case 3: // ServerCutText
1295 return this._handle_server_cut_text();
1297 case 150: // EndOfContinuousUpdates
1298 var first
= !(this._supportsContinuousUpdates
);
1299 this._supportsContinuousUpdates
= true;
1300 this._enabledContinuousUpdates
= false;
1302 this._enabledContinuousUpdates
= true;
1303 this._updateContinuousUpdates();
1304 Log
.Info("Enabling continuous updates.");
1306 // FIXME: We need to send a framebufferupdaterequest here
1307 // if we add support for turning off continuous updates
1311 case 248: // ServerFence
1312 return this._handle_server_fence_msg();
1315 return this._handle_xvp_msg();
1318 this._fail("Unexpected server message", "Type:" + msg_type
);
1319 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1324 _onFlush: function() {
1325 this._flushing
= false;
1326 // Resume processing
1327 if (this._sock
.rQlen() > 0) {
1328 this._handle_message();
1332 _framebufferUpdate: function () {
1336 if (this._FBU
.rects
=== 0) {
1337 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1338 this._sock
.rQskip8(); // Padding
1339 this._FBU
.rects
= this._sock
.rQshift16();
1340 this._FBU
.bytes
= 0;
1341 this._timing
.cur_fbu
= 0;
1342 if (this._timing
.fbu_rt_start
> 0) {
1343 now
= (new Date()).getTime();
1344 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1347 // Make sure the previous frame is fully rendered first
1348 // to avoid building up an excessive queue
1349 if (this._display
.pending()) {
1350 this._flushing
= true;
1351 this._display
.flush();
1356 while (this._FBU
.rects
> 0) {
1357 if (this._rfb_connection_state
!== 'connected') { return false; }
1359 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1360 if (this._FBU
.bytes
=== 0) {
1361 if (this._sock
.rQwait("rect header", 12)) { return false; }
1362 /* New FramebufferUpdate */
1364 var hdr
= this._sock
.rQshiftBytes(12);
1365 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1366 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1367 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1368 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1369 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1370 (hdr
[10] << 8) + hdr
[11], 10);
1372 this._onFBUReceive(this,
1373 {'x': this._FBU
.x
, 'y': this._FBU
.y
,
1374 'width': this._FBU
.width
, 'height': this._FBU
.height
,
1375 'encoding': this._FBU
.encoding
,
1376 'encodingName': encodingName(this._FBU
.encoding
)});
1378 if (!this._encHandlers
[this._FBU
.encoding
]) {
1379 this._fail("Unexpected server message",
1380 "Unsupported encoding " +
1381 this._FBU
.encoding
);
1386 this._timing
.last_fbu
= (new Date()).getTime();
1388 ret
= this._encHandlers
[this._FBU
.encoding
]();
1390 now
= (new Date()).getTime();
1391 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1394 if (!(this._FBU
.encoding
in this._encStats
)) {
1395 this._encStats
[this._FBU
.encoding
] = [0, 0];
1397 this._encStats
[this._FBU
.encoding
][0]++;
1398 this._encStats
[this._FBU
.encoding
][1]++;
1399 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1402 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1403 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1404 this._timing
.fbu_rt_start
> 0) {
1405 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1406 this._timing
.full_fbu_cnt
++;
1407 Log
.Info("Timing of full FBU, curr: " +
1408 this._timing
.cur_fbu
+ ", total: " +
1409 this._timing
.full_fbu_total
+ ", cnt: " +
1410 this._timing
.full_fbu_cnt
+ ", avg: " +
1411 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1414 if (this._timing
.fbu_rt_start
> 0) {
1415 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1416 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1417 this._timing
.fbu_rt_cnt
++;
1418 Log
.Info("full FBU round-trip, cur: " +
1419 fbu_rt_diff
+ ", total: " +
1420 this._timing
.fbu_rt_total
+ ", cnt: " +
1421 this._timing
.fbu_rt_cnt
+ ", avg: " +
1422 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1423 this._timing
.fbu_rt_start
= 0;
1427 if (!ret
) { return ret
; } // need more data
1430 this._display
.flip();
1432 this._onFBUComplete(this);
1434 return true; // We finished this FBU
1437 _updateContinuousUpdates: function() {
1438 if (!this._enabledContinuousUpdates
) { return; }
1440 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1441 this._fb_width
, this._fb_height
);
1444 _resize: function(width
, height
) {
1445 this._fb_width
= width
;
1446 this._fb_height
= height
;
1448 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1450 this._display
.resize(this._fb_width
, this._fb_height
);
1451 this._onFBResize(this, this._fb_width
, this._fb_height
);
1453 this._timing
.fbu_rt_start
= (new Date()).getTime();
1454 this._updateContinuousUpdates();
1458 make_properties(RFB
, [
1459 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1460 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1461 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1462 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1463 ['shared', 'rw', 'bool'], // Request shared mode
1464 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1465 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1466 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1467 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1468 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1469 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1471 // Callback functions
1472 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1473 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1474 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1475 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1476 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1477 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1478 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1479 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1480 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1481 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1482 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1485 RFB
.prototype.set_local_cursor = function (cursor
) {
1486 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1487 this._local_cursor
= false;
1488 this._display
.disableLocalCursor(); //Only show server-side cursor
1490 if (this._display
.get_cursor_uri()) {
1491 this._local_cursor
= true;
1493 Log
.Warn("Browser does not support local cursor");
1494 this._display
.disableLocalCursor();
1498 // Need to send an updated list of encodings if we are connected
1499 if (this._rfb_connection_state
=== "connected") {
1500 this._sendEncodings();
1504 RFB
.prototype.set_view_only = function (view_only
) {
1505 this._view_only
= view_only
;
1507 if (this._rfb_connection_state
=== "connecting" ||
1508 this._rfb_connection_state
=== "connected") {
1510 this._keyboard
.ungrab();
1511 this._mouse
.ungrab();
1513 this._keyboard
.grab();
1519 RFB
.prototype.get_display = function () { return this._display
; };
1520 RFB
.prototype.get_keyboard = function () { return this._keyboard
; };
1521 RFB
.prototype.get_mouse = function () { return this._mouse
; };
1525 keyEvent: function (sock
, keysym
, down
) {
1526 var buff
= sock
._sQ
;
1527 var offset
= sock
._sQlen
;
1529 buff
[offset
] = 4; // msg-type
1530 buff
[offset
+ 1] = down
;
1532 buff
[offset
+ 2] = 0;
1533 buff
[offset
+ 3] = 0;
1535 buff
[offset
+ 4] = (keysym
>> 24);
1536 buff
[offset
+ 5] = (keysym
>> 16);
1537 buff
[offset
+ 6] = (keysym
>> 8);
1538 buff
[offset
+ 7] = keysym
;
1544 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1545 function getRFBkeycode(xt_scancode
) {
1546 var upperByte
= (keycode
>> 8);
1547 var lowerByte
= (keycode
& 0x00ff);
1548 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1549 lowerByte
= lowerByte
| 0x80;
1555 var buff
= sock
._sQ
;
1556 var offset
= sock
._sQlen
;
1558 buff
[offset
] = 255; // msg-type
1559 buff
[offset
+ 1] = 0; // sub msg-type
1561 buff
[offset
+ 2] = (down
>> 8);
1562 buff
[offset
+ 3] = down
;
1564 buff
[offset
+ 4] = (keysym
>> 24);
1565 buff
[offset
+ 5] = (keysym
>> 16);
1566 buff
[offset
+ 6] = (keysym
>> 8);
1567 buff
[offset
+ 7] = keysym
;
1569 var RFBkeycode
= getRFBkeycode(keycode
);
1571 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1572 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1573 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1574 buff
[offset
+ 11] = RFBkeycode
;
1580 pointerEvent: function (sock
, x
, y
, mask
) {
1581 var buff
= sock
._sQ
;
1582 var offset
= sock
._sQlen
;
1584 buff
[offset
] = 5; // msg-type
1586 buff
[offset
+ 1] = mask
;
1588 buff
[offset
+ 2] = x
>> 8;
1589 buff
[offset
+ 3] = x
;
1591 buff
[offset
+ 4] = y
>> 8;
1592 buff
[offset
+ 5] = y
;
1598 // TODO(directxman12): make this unicode compatible?
1599 clientCutText: function (sock
, text
) {
1600 var buff
= sock
._sQ
;
1601 var offset
= sock
._sQlen
;
1603 buff
[offset
] = 6; // msg-type
1605 buff
[offset
+ 1] = 0; // padding
1606 buff
[offset
+ 2] = 0; // padding
1607 buff
[offset
+ 3] = 0; // padding
1609 var n
= text
.length
;
1611 buff
[offset
+ 4] = n
>> 24;
1612 buff
[offset
+ 5] = n
>> 16;
1613 buff
[offset
+ 6] = n
>> 8;
1614 buff
[offset
+ 7] = n
;
1616 for (var i
= 0; i
< n
; i
++) {
1617 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1620 sock
._sQlen
+= 8 + n
;
1624 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1625 var buff
= sock
._sQ
;
1626 var offset
= sock
._sQlen
;
1628 buff
[offset
] = 251; // msg-type
1629 buff
[offset
+ 1] = 0; // padding
1630 buff
[offset
+ 2] = width
>> 8; // width
1631 buff
[offset
+ 3] = width
;
1632 buff
[offset
+ 4] = height
>> 8; // height
1633 buff
[offset
+ 5] = height
;
1635 buff
[offset
+ 6] = 1; // number-of-screens
1636 buff
[offset
+ 7] = 0; // padding
1639 buff
[offset
+ 8] = id
>> 24; // id
1640 buff
[offset
+ 9] = id
>> 16;
1641 buff
[offset
+ 10] = id
>> 8;
1642 buff
[offset
+ 11] = id
;
1643 buff
[offset
+ 12] = 0; // x-position
1644 buff
[offset
+ 13] = 0;
1645 buff
[offset
+ 14] = 0; // y-position
1646 buff
[offset
+ 15] = 0;
1647 buff
[offset
+ 16] = width
>> 8; // width
1648 buff
[offset
+ 17] = width
;
1649 buff
[offset
+ 18] = height
>> 8; // height
1650 buff
[offset
+ 19] = height
;
1651 buff
[offset
+ 20] = flags
>> 24; // flags
1652 buff
[offset
+ 21] = flags
>> 16;
1653 buff
[offset
+ 22] = flags
>> 8;
1654 buff
[offset
+ 23] = flags
;
1660 clientFence: function (sock
, flags
, payload
) {
1661 var buff
= sock
._sQ
;
1662 var offset
= sock
._sQlen
;
1664 buff
[offset
] = 248; // msg-type
1666 buff
[offset
+ 1] = 0; // padding
1667 buff
[offset
+ 2] = 0; // padding
1668 buff
[offset
+ 3] = 0; // padding
1670 buff
[offset
+ 4] = flags
>> 24; // flags
1671 buff
[offset
+ 5] = flags
>> 16;
1672 buff
[offset
+ 6] = flags
>> 8;
1673 buff
[offset
+ 7] = flags
;
1675 var n
= payload
.length
;
1677 buff
[offset
+ 8] = n
; // length
1679 for (var i
= 0; i
< n
; i
++) {
1680 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1683 sock
._sQlen
+= 9 + n
;
1687 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1688 var buff
= sock
._sQ
;
1689 var offset
= sock
._sQlen
;
1691 buff
[offset
] = 150; // msg-type
1692 buff
[offset
+ 1] = enable
; // enable-flag
1694 buff
[offset
+ 2] = x
>> 8; // x
1695 buff
[offset
+ 3] = x
;
1696 buff
[offset
+ 4] = y
>> 8; // y
1697 buff
[offset
+ 5] = y
;
1698 buff
[offset
+ 6] = width
>> 8; // width
1699 buff
[offset
+ 7] = width
;
1700 buff
[offset
+ 8] = height
>> 8; // height
1701 buff
[offset
+ 9] = height
;
1707 pixelFormat: function (sock
, depth
, true_color
) {
1708 var buff
= sock
._sQ
;
1709 var offset
= sock
._sQlen
;
1715 } else if (depth
> 8) {
1721 bits
= Math
.floor(depth
/3);
1723 buff
[offset
] = 0; // msg-type
1725 buff
[offset
+ 1] = 0; // padding
1726 buff
[offset
+ 2] = 0; // padding
1727 buff
[offset
+ 3] = 0; // padding
1729 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1730 buff
[offset
+ 5] = depth
; // depth
1731 buff
[offset
+ 6] = 0; // little-endian
1732 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1734 buff
[offset
+ 8] = 0; // red-max
1735 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1737 buff
[offset
+ 10] = 0; // green-max
1738 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1740 buff
[offset
+ 12] = 0; // blue-max
1741 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1743 buff
[offset
+ 14] = bits
* 2; // red-shift
1744 buff
[offset
+ 15] = bits
* 1; // green-shift
1745 buff
[offset
+ 16] = bits
* 0; // blue-shift
1747 buff
[offset
+ 17] = 0; // padding
1748 buff
[offset
+ 18] = 0; // padding
1749 buff
[offset
+ 19] = 0; // padding
1755 clientEncodings: function (sock
, encodings
) {
1756 var buff
= sock
._sQ
;
1757 var offset
= sock
._sQlen
;
1759 buff
[offset
] = 2; // msg-type
1760 buff
[offset
+ 1] = 0; // padding
1762 buff
[offset
+ 2] = encodings
.length
>> 8;
1763 buff
[offset
+ 3] = encodings
.length
;
1765 var i
, j
= offset
+ 4;
1766 for (i
= 0; i
< encodings
.length
; i
++) {
1767 var enc
= encodings
[i
];
1768 buff
[j
] = enc
>> 24;
1769 buff
[j
+ 1] = enc
>> 16;
1770 buff
[j
+ 2] = enc
>> 8;
1776 sock
._sQlen
+= j
- offset
;
1780 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1781 var buff
= sock
._sQ
;
1782 var offset
= sock
._sQlen
;
1784 if (typeof(x
) === "undefined") { x
= 0; }
1785 if (typeof(y
) === "undefined") { y
= 0; }
1787 buff
[offset
] = 3; // msg-type
1788 buff
[offset
+ 1] = incremental
? 1 : 0;
1790 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1791 buff
[offset
+ 3] = x
& 0xFF;
1793 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1794 buff
[offset
+ 5] = y
& 0xFF;
1796 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1797 buff
[offset
+ 7] = w
& 0xFF;
1799 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1800 buff
[offset
+ 9] = h
& 0xFF;
1807 RFB
.genDES = function (password
, challenge
) {
1809 for (var i
= 0; i
< password
.length
; i
++) {
1810 passwd
.push(password
.charCodeAt(i
));
1812 return (new DES(passwd
)).encrypt(challenge
);
1815 RFB
.encodingHandlers
= {
1817 if (this._FBU
.lines
=== 0) {
1818 this._FBU
.lines
= this._FBU
.height
;
1821 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1822 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1823 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1824 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1825 var curr_height
= Math
.min(this._FBU
.lines
,
1826 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1827 var data
= this._sock
.get_rQ();
1828 var index
= this._sock
.get_rQi();
1829 if (this._fb_depth
== 8) {
1830 var pixels
= this._FBU
.width
* curr_height
1831 var newdata
= new Uint8Array(pixels
* 4);
1833 for (i
= 0;i
< pixels
;i
++) {
1834 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1835 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1836 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1837 newdata
[i
* 4 + 4] = 0;
1842 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1843 curr_height
, data
, index
);
1844 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1845 this._FBU
.lines
-= curr_height
;
1847 if (this._FBU
.lines
> 0) {
1848 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1851 this._FBU
.bytes
= 0;
1857 COPYRECT: function () {
1858 this._FBU
.bytes
= 4;
1859 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1860 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1861 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1865 this._FBU
.bytes
= 0;
1871 if (this._FBU
.subrects
=== 0) {
1872 this._FBU
.bytes
= 4 + 4;
1873 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1874 this._FBU
.subrects
= this._sock
.rQshift32();
1875 color
= this._sock
.rQshiftBytes(4); // Background
1876 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1879 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1880 color
= this._sock
.rQshiftBytes(4);
1881 var x
= this._sock
.rQshift16();
1882 var y
= this._sock
.rQshift16();
1883 var width
= this._sock
.rQshift16();
1884 var height
= this._sock
.rQshift16();
1885 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1886 this._FBU
.subrects
--;
1889 if (this._FBU
.subrects
> 0) {
1890 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1891 this._FBU
.bytes
= (4 + 8) * chunk
;
1894 this._FBU
.bytes
= 0;
1900 HEXTILE: function () {
1901 var rQ
= this._sock
.get_rQ();
1902 var rQi
= this._sock
.get_rQi();
1904 if (this._FBU
.tiles
=== 0) {
1905 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1906 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1907 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1908 this._FBU
.tiles
= this._FBU
.total_tiles
;
1911 while (this._FBU
.tiles
> 0) {
1912 this._FBU
.bytes
= 1;
1913 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1914 var subencoding
= rQ
[rQi
]; // Peek
1915 if (subencoding
> 30) { // Raw
1916 this._fail("Unexpected server message",
1917 "Illegal hextile subencoding: " + subencoding
);
1922 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1923 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1924 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1925 var x
= this._FBU
.x
+ tile_x
* 16;
1926 var y
= this._FBU
.y
+ tile_y
* 16;
1927 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1928 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1930 // Figure out how much we are expecting
1931 if (subencoding
& 0x01) { // Raw
1932 this._FBU
.bytes
+= w
* h
* 4;
1934 if (subencoding
& 0x02) { // Background
1935 this._FBU
.bytes
+= 4;
1937 if (subencoding
& 0x04) { // Foreground
1938 this._FBU
.bytes
+= 4;
1940 if (subencoding
& 0x08) { // AnySubrects
1941 this._FBU
.bytes
++; // Since we aren't shifting it off
1942 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1943 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1944 if (subencoding
& 0x10) { // SubrectsColoured
1945 this._FBU
.bytes
+= subrects
* (4 + 2);
1947 this._FBU
.bytes
+= subrects
* 2;
1952 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1954 // We know the encoding and have a whole tile
1955 this._FBU
.subencoding
= rQ
[rQi
];
1957 if (this._FBU
.subencoding
=== 0) {
1958 if (this._FBU
.lastsubencoding
& 0x01) {
1959 // Weird: ignore blanks are RAW
1960 Log
.Debug(" Ignoring blank after RAW");
1962 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1964 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1965 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1966 rQi
+= this._FBU
.bytes
- 1;
1968 if (this._FBU
.subencoding
& 0x02) { // Background
1969 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1972 if (this._FBU
.subencoding
& 0x04) { // Foreground
1973 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1977 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1978 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1982 for (var s
= 0; s
< subrects
; s
++) {
1984 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1985 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1988 color
= this._FBU
.foreground
;
1993 var sy
= (xy
& 0x0f);
1997 var sw
= (wh
>> 4) + 1;
1998 var sh
= (wh
& 0x0f) + 1;
2000 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
2003 this._display
.finishTile();
2005 this._sock
.set_rQi(rQi
);
2006 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2007 this._FBU
.bytes
= 0;
2011 if (this._FBU
.tiles
=== 0) {
2018 TIGHT: function () {
2019 this._FBU
.bytes
= 1; // compression-control byte
2020 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2022 var checksum = function (data
) {
2024 for (var i
= 0; i
< data
.length
; i
++) {
2026 if (sum
> 65536) sum
-= 65536;
2031 var resetStreams
= 0;
2033 var decompress = function (data
, expected
) {
2034 for (var i
= 0; i
< 4; i
++) {
2035 if ((resetStreams
>> i
) & 1) {
2036 this._FBU
.zlibs
[i
].reset();
2037 Log
.Info("Reset zlib stream " + i
);
2041 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2042 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2043 /*if (uncompressed.status !== 0) {
2044 Log.Error("Invalid data in zlib stream");
2047 //return uncompressed.data;
2048 return uncompressed
;
2051 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2052 // Convert indexed (palette based) image data to RGB
2053 // TODO: reduce number of calculations inside loop
2054 var dest
= this._destBuff
;
2055 var w
= Math
.floor((width
+ 7) / 8);
2056 var w1
= Math
.floor(width
/ 8);
2058 /*for (var y = 0; y < height; y++) {
2060 var yoffset = y * width;
2061 var ybitoffset = y * w;
2062 var xoffset, targetbyte;
2063 for (x = 0; x < w1; x++) {
2064 xoffset = yoffset + x * 8;
2065 targetbyte = data[ybitoffset + x];
2066 for (b = 7; b >= 0; b--) {
2067 dp = (xoffset + 7 - b) * 3;
2068 sp = (targetbyte >> b & 1) * 3;
2069 dest[dp] = palette[sp];
2070 dest[dp + 1] = palette[sp + 1];
2071 dest[dp + 2] = palette[sp + 2];
2075 xoffset = yoffset + x * 8;
2076 targetbyte = data[ybitoffset + x];
2077 for (b = 7; b >= 8 - width % 8; b--) {
2078 dp = (xoffset + 7 - b) * 3;
2079 sp = (targetbyte >> b & 1) * 3;
2080 dest[dp] = palette[sp];
2081 dest[dp + 1] = palette[sp + 1];
2082 dest[dp + 2] = palette[sp + 2];
2086 for (var y
= 0; y
< height
; y
++) {
2088 for (x
= 0; x
< w1
; x
++) {
2089 for (b
= 7; b
>= 0; b
--) {
2090 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2091 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2092 dest
[dp
] = palette
[sp
];
2093 dest
[dp
+ 1] = palette
[sp
+ 1];
2094 dest
[dp
+ 2] = palette
[sp
+ 2];
2099 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2100 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2101 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2102 dest
[dp
] = palette
[sp
];
2103 dest
[dp
+ 1] = palette
[sp
+ 1];
2104 dest
[dp
+ 2] = palette
[sp
+ 2];
2112 var indexedToRGBX = function (data
, palette
, width
, height
) {
2113 // Convert indexed (palette based) image data to RGB
2114 var dest
= this._destBuff
;
2115 var total
= width
* height
* 4;
2116 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2117 var sp
= data
[j
] * 3;
2118 dest
[i
] = palette
[sp
];
2119 dest
[i
+ 1] = palette
[sp
+ 1];
2120 dest
[i
+ 2] = palette
[sp
+ 2];
2127 var rQi
= this._sock
.get_rQi();
2128 var rQ
= this._sock
.rQwhole();
2130 var cl_header
, cl_data
;
2132 var handlePalette = function () {
2133 var numColors
= rQ
[rQi
+ 2] + 1;
2134 var paletteSize
= numColors
* 3;
2135 this._FBU
.bytes
+= paletteSize
;
2136 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2138 var bpp
= (numColors
<= 2) ? 1 : 8;
2139 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2141 if (rowSize
* this._FBU
.height
< 12) {
2144 cl_data
= rowSize
* this._FBU
.height
;
2145 //clength = [0, rowSize * this._FBU.height];
2147 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2148 var cl_offset
= rQi
+ 3 + paletteSize
;
2151 cl_data
+= rQ
[cl_offset
] & 0x7f;
2152 if (rQ
[cl_offset
] & 0x80) {
2154 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2155 if (rQ
[cl_offset
+ 1] & 0x80) {
2157 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2160 // end inline getTightCLength
2163 this._FBU
.bytes
+= cl_header
+ cl_data
;
2164 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2166 // Shift ctl, filter id, num colors, palette entries, and clength off
2167 this._sock
.rQskipBytes(3);
2168 //var palette = this._sock.rQshiftBytes(paletteSize);
2169 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2170 this._sock
.rQskipBytes(cl_header
);
2173 data
= this._sock
.rQshiftBytes(cl_data
);
2175 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2178 // Convert indexed (palette based) image data to RGB
2180 if (numColors
== 2) {
2181 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2182 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2184 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2185 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2192 var handleCopy = function () {
2194 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2195 if (uncompressedSize
< 12) {
2198 cl_data
= uncompressedSize
;
2200 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2201 var cl_offset
= rQi
+ 1;
2204 cl_data
+= rQ
[cl_offset
] & 0x7f;
2205 if (rQ
[cl_offset
] & 0x80) {
2207 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2208 if (rQ
[cl_offset
+ 1] & 0x80) {
2210 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2213 // end inline getTightCLength
2215 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2216 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2218 // Shift ctl, clength off
2219 this._sock
.rQshiftBytes(1 + cl_header
);
2222 data
= this._sock
.rQshiftBytes(cl_data
);
2224 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2227 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2232 var ctl
= this._sock
.rQpeek8();
2234 // Keep tight reset bits
2235 resetStreams
= ctl
& 0xF;
2237 // Figure out filter
2239 streamId
= ctl
& 0x3;
2241 if (ctl
=== 0x08) cmode
= "fill";
2242 else if (ctl
=== 0x09) cmode
= "jpeg";
2243 else if (ctl
=== 0x0A) cmode
= "png";
2244 else if (ctl
& 0x04) cmode
= "filter";
2245 else if (ctl
< 0x04) cmode
= "copy";
2246 else return this._fail("Unexpected server message",
2247 "Illegal tight compression received, " +
2251 // fill use depth because TPIXELs drop the padding byte
2252 case "fill": // TPIXEL
2253 this._FBU
.bytes
+= 3;
2255 case "jpeg": // max clength
2256 this._FBU
.bytes
+= 3;
2258 case "png": // max clength
2259 this._FBU
.bytes
+= 3;
2261 case "filter": // filter id + num colors if palette
2262 this._FBU
.bytes
+= 2;
2268 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2270 // Determine FBU.bytes
2274 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);
2275 this._sock
.rQskipBytes(4);
2279 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2280 var cl_offset
= rQi
+ 1;
2283 cl_data
+= rQ
[cl_offset
] & 0x7f;
2284 if (rQ
[cl_offset
] & 0x80) {
2286 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2287 if (rQ
[cl_offset
+ 1] & 0x80) {
2289 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2292 // end inline getTightCLength
2293 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2294 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2296 // We have everything, render it
2297 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2298 data
= this._sock
.rQshiftBytes(cl_data
);
2299 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2302 var filterId
= rQ
[rQi
+ 1];
2303 if (filterId
=== 1) {
2304 if (!handlePalette()) { return false; }
2306 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2307 // Filter 2, Gradient is valid but not use if jpeg is enabled
2308 this._fail("Unexpected server message",
2309 "Unsupported tight subencoding received, " +
2310 "filter: " + filterId
);
2314 if (!handleCopy()) { return false; }
2319 this._FBU
.bytes
= 0;
2325 last_rect: function () {
2326 this._FBU
.rects
= 0;
2330 ExtendedDesktopSize: function () {
2331 this._FBU
.bytes
= 1;
2332 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2334 this._supportsSetDesktopSize
= true;
2335 var number_of_screens
= this._sock
.rQpeek8();
2337 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2338 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2340 this._sock
.rQskipBytes(1); // number-of-screens
2341 this._sock
.rQskipBytes(3); // padding
2343 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2344 // Save the id and flags of the first screen
2346 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2347 this._sock
.rQskipBytes(2); // x-position
2348 this._sock
.rQskipBytes(2); // y-position
2349 this._sock
.rQskipBytes(2); // width
2350 this._sock
.rQskipBytes(2); // height
2351 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2353 this._sock
.rQskipBytes(16);
2358 * The x-position indicates the reason for the change:
2360 * 0 - server resized on its own
2361 * 1 - this client requested the resize
2362 * 2 - another client requested the resize
2365 // We need to handle errors when we requested the resize.
2366 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2368 // The y-position indicates the status code from the server
2369 switch (this._FBU
.y
) {
2371 msg
= "Resize is administratively prohibited";
2374 msg
= "Out of resources";
2377 msg
= "Invalid screen layout";
2380 msg
= "Unknown reason";
2383 this._notification("Server did not accept the resize request: "
2386 this._resize(this._FBU
.width
, this._FBU
.height
);
2389 this._FBU
.bytes
= 0;
2390 this._FBU
.rects
-= 1;
2394 DesktopSize: function () {
2395 this._resize(this._FBU
.width
, this._FBU
.height
);
2396 this._FBU
.bytes
= 0;
2397 this._FBU
.rects
-= 1;
2401 Cursor: function () {
2402 Log
.Debug(">> set_cursor");
2403 var x
= this._FBU
.x
; // hotspot-x
2404 var y
= this._FBU
.y
; // hotspot-y
2405 var w
= this._FBU
.width
;
2406 var h
= this._FBU
.height
;
2408 var pixelslength
= w
* h
* 4;
2409 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2411 this._FBU
.bytes
= pixelslength
+ masklength
;
2412 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2414 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2415 this._sock
.rQshiftBytes(masklength
),
2418 this._FBU
.bytes
= 0;
2421 Log
.Debug("<< set_cursor");
2425 QEMUExtendedKeyEvent: function () {
2428 // Old Safari doesn't support creating keyboard events
2430 var keyboardEvent
= document
.createEvent("keyboardEvent");
2431 if (keyboardEvent
.code
!== undefined) {
2432 this._qemuExtKeyEventSupported
= true;