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(target
, defaults
) {
36 this._target
= target
;
40 this._rfb_credentials
= {};
43 this._rfb_connection_state
= '';
44 this._rfb_init_state
= '';
45 this._rfb_auth_scheme
= '';
46 this._rfb_disconnect_reason
= "";
48 // Server capabilities
49 this._rfb_version
= 0;
50 this._rfb_max_version
= 3.8;
51 this._rfb_tightvnc
= false;
52 this._rfb_xvp_ver
= 0;
59 this._capabilities
= { power
: false, resize
: false };
61 this._supportsFence
= false;
63 this._supportsContinuousUpdates
= false;
64 this._enabledContinuousUpdates
= false;
66 this._supportsSetDesktopSize
= false;
68 this._screen_flags
= 0;
70 this._qemuExtKeyEventSupported
= false;
73 this._sock
= null; // Websock object
74 this._display
= null; // Display object
75 this._flushing
= false; // Display flushing state
76 this._keyboard
= null; // Keyboard input handler object
77 this._mouse
= null; // Mouse input handler object
80 this._disconnTimer
= null; // disconnection timer
82 // Decoder states and stats
83 this._encHandlers
= {};
88 subrects
: 0, // RRE and HEXTILE
99 zlibs
: [] // TIGHT zlib streams
101 for (var i
= 0; i
< 4; i
++) {
102 this._FBU
.zlibs
[i
] = new Inflator();
105 this._destBuff
= null;
106 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
108 this._rre_chunk_sz
= 100;
124 this._mouse_buttonMask
= 0;
125 this._mouse_arr
= [];
126 this._viewportDragging
= false;
127 this._viewportDragPos
= {};
128 this._viewportHasMoved
= false;
130 // set the default value on user-facing properties
131 set_defaults(this, defaults
, {
132 'local_cursor': false, // Request locally rendered cursor
133 'view_only': false, // Disable client mouse/keyboard
134 'disconnectTimeout': 3, // Time (s) to wait for disconnection
135 'viewportDrag': false, // Move the viewport on mouse drags
137 // Callback functions
138 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
139 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
140 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
141 'onCredentialsRequired': function () { }, // onCredentialsRequired(rfb, types): VNC credentials are required
142 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
143 'onBell': function () { }, // onBell(rfb): RFB Bell message received
144 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
145 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
146 'onCapabilities': function () { } // onCapabilities(rfb, caps): the supported capabilities has changed
150 Log
.Debug(">> RFB.constructor");
152 // Target canvas must be able to have focus
153 if (!this._target
.hasAttribute('tabindex')) {
154 this._target
.tabIndex
= -1;
157 // populate encHandlers with bound versions
158 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this);
159 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this);
160 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this);
161 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this);
162 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this);
164 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this);
165 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this);
166 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this);
167 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this);
168 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this);
170 // NB: nothing that needs explicit teardown should be done
171 // before this point, since this can throw an exception
173 this._display
= new Display(this._target
,
174 {onFlush
: this._onFlush
.bind(this)});
176 Log
.Error("Display exception: " + exc
);
179 this._display
.clear();
181 this._keyboard
= new Keyboard(this._target
,
182 {onKeyEvent
: this._handleKeyEvent
.bind(this)});
184 this._mouse
= new Mouse(this._target
,
185 {onMouseButton
: this._handleMouseButton
.bind(this),
186 onMouseMove
: this._handleMouseMove
.bind(this)});
188 this._sock
= new Websock();
189 this._sock
.on('message', this._handle_message
.bind(this));
190 this._sock
.on('open', function () {
191 if ((this._rfb_connection_state
=== 'connecting') &&
192 (this._rfb_init_state
=== '')) {
193 this._rfb_init_state
= 'ProtocolVersion';
194 Log
.Debug("Starting VNC handshake");
196 this._fail("Unexpected server connection");
199 this._sock
.on('close', function (e
) {
200 Log
.Warn("WebSocket on-close event");
203 msg
= " (code: " + e
.code
;
205 msg
+= ", reason: " + e
.reason
;
209 switch (this._rfb_connection_state
) {
210 case 'disconnecting':
211 this._updateConnectionState('disconnected');
214 this._fail('Failed to connect to server', msg
);
217 // Handle disconnects that were initiated server-side
218 this._updateConnectionState('disconnecting');
219 this._updateConnectionState('disconnected');
222 this._fail("Unexpected server disconnect",
223 "Already disconnected: " + msg
);
226 this._fail("Unexpected server disconnect",
227 "Not in any state yet: " + msg
);
230 this._sock
.off('close');
232 this._sock
.on('error', function (e
) {
233 Log
.Warn("WebSocket on-error event");
236 Log
.Debug("<< RFB.constructor");
241 connect: function (url
, options
) {
243 this._fail(_("Must specify URL"));
249 options
= options
|| {}
251 this._rfb_credentials
= options
.credentials
|| {};
252 this._shared
= 'shared' in options
? !!options
.shared
: true;
253 this._repeaterID
= options
.repeaterID
|| '';
255 this._rfb_init_state
= '';
256 this._updateConnectionState('connecting');
260 disconnect: function () {
261 this._updateConnectionState('disconnecting');
262 this._sock
.off('error');
263 this._sock
.off('message');
264 this._sock
.off('open');
267 sendCredentials: function (creds
) {
268 this._rfb_credentials
= creds
;
269 setTimeout(this._init_msg
.bind(this), 0);
272 sendCtrlAltDel: function () {
273 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
274 Log
.Info("Sending Ctrl-Alt-Del");
276 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
277 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
278 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
279 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
280 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
281 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
286 machineShutdown: function () {
290 machineReboot: function () {
294 machineReset: function () {
298 // Send a key press. If 'down' is not specified then send a down key
299 // followed by an up key.
300 sendKey: function (keysym
, code
, down
) {
301 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
303 if (down
=== undefined) {
304 this.sendKey(keysym
, code
, true);
305 this.sendKey(keysym
, code
, false);
309 var scancode
= XtScancode
[code
];
311 if (this._qemuExtKeyEventSupported
&& scancode
) {
313 keysym
= keysym
|| 0;
315 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
317 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
322 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
323 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
329 clipboardPasteFrom: function (text
) {
330 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return; }
331 RFB
.messages
.clientCutText(this._sock
, text
);
334 autoscale: function (width
, height
, downscaleOnly
) {
335 if (this._rfb_connection_state
!== 'connected') { return; }
336 this._display
.autoscale(width
, height
, downscaleOnly
);
339 viewportChangeSize: function(width
, height
) {
340 if (this._rfb_connection_state
!== 'connected') { return; }
341 this._display
.viewportChangeSize(width
, height
);
344 clippingDisplay: function () {
345 if (this._rfb_connection_state
!== 'connected') { return false; }
346 return this._display
.clippingDisplay();
349 // Requests a change of remote desktop size. This message is an extension
350 // and may only be sent if we have received an ExtendedDesktopSize message
351 requestDesktopSize: function (width
, height
) {
352 if (this._rfb_connection_state
!== 'connected' ||
357 if (this._supportsSetDesktopSize
) {
358 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
359 this._screen_id
, this._screen_flags
);
370 _connect: function () {
371 Log
.Debug(">> RFB.connect");
373 Log
.Info("connecting to " + this._url
);
376 // WebSocket.onopen transitions to the RFB init states
377 this._sock
.open(this._url
, ['binary']);
379 if (e
.name
=== 'SyntaxError') {
380 this._fail("Invalid host or port value given", e
);
382 this._fail("Error while connecting", e
);
386 // Always grab focus on some kind of click event
387 this._target
.addEventListener("mousedown", this._focusCanvas
);
388 this._target
.addEventListener("touchstart", this._focusCanvas
);
390 Log
.Debug("<< RFB.connect");
393 _disconnect: function () {
394 Log
.Debug(">> RFB.disconnect");
395 this._target
.removeEventListener("mousedown", this._focusCanvas
);
396 this._target
.removeEventListener("touchstart", this._focusCanvas
);
400 Log
.Debug("<< RFB.disconnect");
403 _print_stats: function () {
404 var stats
= this._encStats
;
406 Log
.Info("Encoding stats for this connection:");
407 Object
.keys(stats
).forEach(function (key
) {
409 if (s
[0] + s
[1] > 0) {
410 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
414 Log
.Info("Encoding stats since page load:");
415 Object
.keys(stats
).forEach(function (key
) {
417 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
421 _cleanup: function () {
422 if (!this._view_only
) { this._keyboard
.ungrab(); }
423 if (!this._view_only
) { this._mouse
.ungrab(); }
424 this._display
.defaultCursor();
425 if (Log
.get_logging() !== 'debug') {
426 // Show noVNC logo when disconnected, unless in
428 this._display
.clear();
432 // Event handler for canvas so this points to the canvas element
433 _focusCanvas: function(event
) {
434 // Respect earlier handlers' request to not do side-effects
435 if (!event
.defaultPrevented
)
444 * disconnected - permanent state
446 _updateConnectionState: function (state
) {
447 var oldstate
= this._rfb_connection_state
;
449 if (state
=== oldstate
) {
450 Log
.Debug("Already in state '" + state
+ "', ignoring");
454 // The 'disconnected' state is permanent for each RFB object
455 if (oldstate
=== 'disconnected') {
456 Log
.Error("Tried changing state of a disconnected RFB object");
460 // Ensure proper transitions before doing anything
463 if (oldstate
!== 'connecting') {
464 Log
.Error("Bad transition to connected state, " +
465 "previous connection state: " + oldstate
);
471 if (oldstate
!== 'disconnecting') {
472 Log
.Error("Bad transition to disconnected state, " +
473 "previous connection state: " + oldstate
);
479 if (oldstate
!== '') {
480 Log
.Error("Bad transition to connecting state, " +
481 "previous connection state: " + oldstate
);
486 case 'disconnecting':
487 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
488 Log
.Error("Bad transition to disconnecting state, " +
489 "previous connection state: " + oldstate
);
495 Log
.Error("Unknown connection state: " + state
);
499 // State change actions
501 this._rfb_connection_state
= state
;
502 this._onUpdateState(this, state
, oldstate
);
504 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
507 if (this._disconnTimer
&& state
!== 'disconnecting') {
508 Log
.Debug("Clearing disconnect timer");
509 clearTimeout(this._disconnTimer
);
510 this._disconnTimer
= null;
512 // make sure we don't get a double event
513 this._sock
.off('close');
518 // Call onDisconnected callback after onUpdateState since
519 // we don't know if the UI only displays the latest message
520 if (this._rfb_disconnect_reason
!== "") {
521 this._onDisconnected(this, this._rfb_disconnect_reason
);
523 // No reason means clean disconnect
524 this._onDisconnected(this);
532 case 'disconnecting':
535 this._disconnTimer
= setTimeout(function () {
536 this._rfb_disconnect_reason
= _("Disconnect timeout");
537 this._updateConnectionState('disconnected');
538 }.bind(this), this._disconnectTimeout
* 1000);
543 /* Print errors and disconnect
545 * The optional parameter 'details' is used for information that
546 * should be logged but not sent to the user interface.
548 _fail: function (msg
, details
) {
550 if (typeof details
!== 'undefined') {
551 fullmsg
= msg
+ " (" + details
+ ")";
553 switch (this._rfb_connection_state
) {
554 case 'disconnecting':
555 Log
.Error("Failed when disconnecting: " + fullmsg
);
558 Log
.Error("Failed while connected: " + fullmsg
);
561 Log
.Error("Failed when connecting: " + fullmsg
);
564 Log
.Error("RFB failure: " + fullmsg
);
567 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
569 // Transition to disconnected without waiting for socket to close
570 this._updateConnectionState('disconnecting');
571 this._updateConnectionState('disconnected');
577 * Send a notification to the UI. Valid levels are:
578 * 'normal'|'warn'|'error'
580 * NOTE: Options could be added in the future.
581 * NOTE: If this function is called multiple times, remember that the
582 * interface could be only showing the latest notification.
584 _notification: function(msg
, level
, options
) {
589 Log
.Debug("Notification[" + level
+ "]:" + msg
);
592 Log
.Error("Invalid notification level: " + level
);
597 this._onNotification(this, msg
, level
, options
);
599 this._onNotification(this, msg
, level
);
603 _setCapability: function (cap
, val
) {
604 this._capabilities
[cap
] = val
;
605 this._onCapabilities(this, this._capabilities
);
608 _handle_message: function () {
609 if (this._sock
.rQlen() === 0) {
610 Log
.Warn("handle_message called on an empty receive queue");
614 switch (this._rfb_connection_state
) {
616 Log
.Error("Got data while disconnected");
620 if (this._flushing
) {
623 if (!this._normal_msg()) {
626 if (this._sock
.rQlen() === 0) {
637 _handleKeyEvent: function (keysym
, code
, down
) {
638 this.sendKey(keysym
, code
, down
);
641 _handleMouseButton: function (x
, y
, down
, bmask
) {
643 this._mouse_buttonMask
|= bmask
;
645 this._mouse_buttonMask
&= ~bmask
;
648 if (this._viewportDrag
) {
649 if (down
&& !this._viewportDragging
) {
650 this._viewportDragging
= true;
651 this._viewportDragPos
= {'x': x
, 'y': y
};
653 // Skip sending mouse events
656 this._viewportDragging
= false;
658 // If the viewport didn't actually move, then treat as a mouse click event
659 // Send the button down event here, as the button up event is sent at the end of this function
660 if (!this._viewportHasMoved
&& !this._view_only
) {
661 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
663 this._viewportHasMoved
= false;
667 if (this._view_only
) { return; } // View only, skip mouse events
669 if (this._rfb_connection_state
!== 'connected') { return; }
670 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
673 _handleMouseMove: function (x
, y
) {
674 if (this._viewportDragging
) {
675 var deltaX
= this._viewportDragPos
.x
- x
;
676 var deltaY
= this._viewportDragPos
.y
- y
;
678 // The goal is to trigger on a certain physical width, the
679 // devicePixelRatio brings us a bit closer but is not optimal.
680 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
682 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
683 Math
.abs(deltaY
) > dragThreshold
)) {
684 this._viewportHasMoved
= true;
686 this._viewportDragPos
= {'x': x
, 'y': y
};
687 this._display
.viewportChangePos(deltaX
, deltaY
);
690 // Skip sending mouse events
694 if (this._view_only
) { return; } // View only, skip mouse events
696 if (this._rfb_connection_state
!== 'connected') { return; }
697 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
702 _negotiate_protocol_version: function () {
703 if (this._sock
.rQlen() < 12) {
704 return this._fail("Error while negotiating with server",
705 "Incomplete protocol version");
708 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
709 Log
.Info("Server ProtocolVersion: " + sversion
);
712 case "000.000": // UltraVNC repeater
716 case "003.006": // UltraVNC
717 case "003.889": // Apple Remote Desktop
718 this._rfb_version
= 3.3;
721 this._rfb_version
= 3.7;
724 case "004.000": // Intel AMT KVM
725 case "004.001": // RealVNC 4.6
726 case "005.000": // RealVNC 5.3
727 this._rfb_version
= 3.8;
730 return this._fail("Unsupported server",
731 "Invalid server version: " + sversion
);
735 var repeaterID
= "ID:" + this._repeaterID
;
736 while (repeaterID
.length
< 250) {
739 this._sock
.send_string(repeaterID
);
743 if (this._rfb_version
> this._rfb_max_version
) {
744 this._rfb_version
= this._rfb_max_version
;
747 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
748 ".00" + ((this._rfb_version
* 10) % 10);
749 this._sock
.send_string("RFB " + cversion
+ "\n");
750 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
752 this._rfb_init_state
= 'Security';
755 _negotiate_security: function () {
756 // Polyfill since IE and PhantomJS doesn't have
757 // TypedArray.includes()
758 function includes(item
, array
) {
759 for (var i
= 0; i
< array
.length
; i
++) {
760 if (array
[i
] === item
) {
767 if (this._rfb_version
>= 3.7) {
768 // Server sends supported list, client decides
769 var num_types
= this._sock
.rQshift8();
770 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
772 if (num_types
=== 0) {
773 var strlen
= this._sock
.rQshift32();
774 var reason
= this._sock
.rQshiftStr(strlen
);
775 return this._fail("Error while negotiating with server",
776 "Security failure: " + reason
);
779 var types
= this._sock
.rQshiftBytes(num_types
);
780 Log
.Debug("Server security types: " + types
);
782 // Look for each auth in preferred order
783 this._rfb_auth_scheme
= 0;
784 if (includes(1, types
)) {
785 this._rfb_auth_scheme
= 1; // None
786 } else if (includes(22, types
)) {
787 this._rfb_auth_scheme
= 22; // XVP
788 } else if (includes(16, types
)) {
789 this._rfb_auth_scheme
= 16; // Tight
790 } else if (includes(2, types
)) {
791 this._rfb_auth_scheme
= 2; // VNC Auth
793 return this._fail("Unsupported server",
794 "Unsupported security types: " + types
);
797 this._sock
.send([this._rfb_auth_scheme
]);
800 if (this._sock
.rQwait("security scheme", 4)) { return false; }
801 this._rfb_auth_scheme
= this._sock
.rQshift32();
804 this._rfb_init_state
= 'Authentication';
805 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
807 return this._init_msg(); // jump to authentication
811 _negotiate_xvp_auth: function () {
812 if (!this._rfb_credentials
.username
||
813 !this._rfb_credentials
.password
||
814 !this._rfb_credentials
.target
) {
815 this._onCredentialsRequired(this, ["username", "password", "target"]);
819 var xvp_auth_str
= String
.fromCharCode(this._rfb_credentials
.username
.length
) +
820 String
.fromCharCode(this._rfb_credentials
.target
.length
) +
821 this._rfb_credentials
.username
+
822 this._rfb_credentials
.target
;
823 this._sock
.send_string(xvp_auth_str
);
824 this._rfb_auth_scheme
= 2;
825 return this._negotiate_authentication();
828 _negotiate_std_vnc_auth: function () {
829 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
831 if (!this._rfb_credentials
.password
) {
832 this._onCredentialsRequired(this, ["password"]);
836 // TODO(directxman12): make genDES not require an Array
837 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
838 var response
= RFB
.genDES(this._rfb_credentials
.password
, challenge
);
839 this._sock
.send(response
);
840 this._rfb_init_state
= "SecurityResult";
844 _negotiate_tight_tunnels: function (numTunnels
) {
845 var clientSupportedTunnelTypes
= {
846 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
848 var serverSupportedTunnelTypes
= {};
849 // receive tunnel capabilities
850 for (var i
= 0; i
< numTunnels
; i
++) {
851 var cap_code
= this._sock
.rQshift32();
852 var cap_vendor
= this._sock
.rQshiftStr(4);
853 var cap_signature
= this._sock
.rQshiftStr(8);
854 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
857 // choose the notunnel type
858 if (serverSupportedTunnelTypes
[0]) {
859 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
860 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
861 return this._fail("Unsupported server",
862 "Client's tunnel type had the incorrect " +
863 "vendor or signature");
865 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
866 return false; // wait until we receive the sub auth count to continue
868 return this._fail("Unsupported server",
869 "Server wanted tunnels, but doesn't support " +
870 "the notunnel type");
874 _negotiate_tight_auth: function () {
875 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
876 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
877 var numTunnels
= this._sock
.rQshift32();
878 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
880 this._rfb_tightvnc
= true;
882 if (numTunnels
> 0) {
883 this._negotiate_tight_tunnels(numTunnels
);
884 return false; // wait until we receive the sub auth to continue
888 // second pass, do the sub-auth negotiation
889 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
890 var subAuthCount
= this._sock
.rQshift32();
891 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
892 this._rfb_init_state
= 'SecurityResult';
896 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
898 var clientSupportedTypes
= {
903 var serverSupportedTypes
= [];
905 for (var i
= 0; i
< subAuthCount
; i
++) {
906 var capNum
= this._sock
.rQshift32();
907 var capabilities
= this._sock
.rQshiftStr(12);
908 serverSupportedTypes
.push(capabilities
);
911 for (var authType
in clientSupportedTypes
) {
912 if (serverSupportedTypes
.indexOf(authType
) != -1) {
913 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
916 case 'STDVNOAUTH__': // no auth
917 this._rfb_init_state
= 'SecurityResult';
919 case 'STDVVNCAUTH_': // VNC auth
920 this._rfb_auth_scheme
= 2;
921 return this._init_msg();
923 return this._fail("Unsupported server",
924 "Unsupported tiny auth scheme: " +
930 return this._fail("Unsupported server",
931 "No supported sub-auth types!");
934 _negotiate_authentication: function () {
935 switch (this._rfb_auth_scheme
) {
936 case 0: // connection failed
937 if (this._sock
.rQwait("auth reason", 4)) { return false; }
938 var strlen
= this._sock
.rQshift32();
939 var reason
= this._sock
.rQshiftStr(strlen
);
940 return this._fail("Authentication failure", reason
);
943 if (this._rfb_version
>= 3.8) {
944 this._rfb_init_state
= 'SecurityResult';
947 this._rfb_init_state
= 'ClientInitialisation';
948 return this._init_msg();
951 return this._negotiate_xvp_auth();
953 case 2: // VNC authentication
954 return this._negotiate_std_vnc_auth();
956 case 16: // TightVNC Security Type
957 return this._negotiate_tight_auth();
960 return this._fail("Unsupported server",
961 "Unsupported auth scheme: " +
962 this._rfb_auth_scheme
);
966 _handle_security_result: function () {
967 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
968 switch (this._sock
.rQshift32()) {
970 this._rfb_init_state
= 'ClientInitialisation';
971 Log
.Debug('Authentication OK');
972 return this._init_msg();
974 if (this._rfb_version
>= 3.8) {
975 var length
= this._sock
.rQshift32();
976 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
977 var reason
= this._sock
.rQshiftStr(length
);
978 return this._fail("Authentication failure", reason
);
980 return this._fail("Authentication failure");
983 return this._fail("Too many authentication attempts");
985 return this._fail("Unsupported server",
986 "Unknown SecurityResult");
990 _negotiate_server_init: function () {
991 if (this._sock
.rQwait("server initialization", 24)) { return false; }
994 var width
= this._sock
.rQshift16();
995 var height
= this._sock
.rQshift16();
998 var bpp
= this._sock
.rQshift8();
999 var depth
= this._sock
.rQshift8();
1000 var big_endian
= this._sock
.rQshift8();
1001 var true_color
= this._sock
.rQshift8();
1003 var red_max
= this._sock
.rQshift16();
1004 var green_max
= this._sock
.rQshift16();
1005 var blue_max
= this._sock
.rQshift16();
1006 var red_shift
= this._sock
.rQshift8();
1007 var green_shift
= this._sock
.rQshift8();
1008 var blue_shift
= this._sock
.rQshift8();
1009 this._sock
.rQskipBytes(3); // padding
1011 // NB(directxman12): we don't want to call any callbacks or print messages until
1012 // *after* we're past the point where we could backtrack
1014 /* Connection name/title */
1015 var name_length = this._sock.rQshift32();
1016 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1017 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1019 if (this._rfb_tightvnc) {
1020 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1021 // In TightVNC mode, ServerInit message is extended
1022 var numServerMessages = this._sock.rQshift16();
1023 var numClientMessages = this._sock.rQshift16();
1024 var numEncodings = this._sock.rQshift16();
1025 this._sock.rQskipBytes(2); // padding
1027 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1028 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1030 // we don't actually do anything with the capability information that TIGHT sends,
1031 // so we just skip the all of this.
1033 // TIGHT server message capabilities
1034 this._sock.rQskipBytes(16 * numServerMessages);
1036 // TIGHT client message capabilities
1037 this._sock.rQskipBytes(16 * numClientMessages);
1039 // TIGHT encoding capabilities
1040 this._sock.rQskipBytes(16 * numEncodings);
1043 // NB(directxman12): these are down here so that we don't run them multiple times
1045 Log.Info("Screen: " + width + "x" + height +
1046 ", bpp: " + bpp + ", depth: " + depth +
1047 ", big_endian: " + big_endian +
1048 ", true_color: " + true_color +
1049 ", red_max: " + red_max +
1050 ", green_max: " + green_max +
1051 ", blue_max: " + blue_max +
1052 ", red_shift: " + red_shift +
1053 ", green_shift: " + green_shift +
1054 ", blue_shift: " + blue_shift);
1056 if (big_endian !== 0) {
1057 Log.Warn("Server native endian is not little endian");
1060 if (red_shift !== 16) {
1061 Log.Warn("Server native red-shift is not 16");
1064 if (blue_shift !== 0) {
1065 Log.Warn("Server native blue-shift is not 0");
1068 // we're past the point where we could backtrack, so it's safe to call this
1069 this._onDesktopName(this, this._fb_name);
1071 this._resize(width, height);
1073 if (!this._view_only) { this._keyboard.grab(); }
1074 if (!this._view_only) { this._mouse.grab(); }
1076 this._fb_depth = 24;
1078 if (this._fb_name === "Intel(r) AMT KVM") {
1079 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1083 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1084 this._sendEncodings();
1085 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1087 this._timing.fbu_rt_start = (new Date()).getTime();
1088 this._timing.pixels = 0;
1090 // Cursor will be server side until the server decides to honor
1091 // our request and send over the cursor image
1092 this._display.disableLocalCursor();
1094 this._updateConnectionState('connected');
1098 _sendEncodings: function () {
1101 // In preference order
1102 encs.push(encodings.encodingCopyRect);
1103 // Only supported with full depth support
1104 if (this._fb_depth == 24) {
1105 encs.push(encodings.encodingTight);
1106 encs.push(encodings.encodingHextile);
1107 encs.push(encodings.encodingRRE);
1109 encs.push(encodings.encodingRaw);
1111 // Psuedo-encoding settings
1112 encs.push(encodings.pseudoEncodingTightPNG);
1113 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1114 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1116 encs.push(encodings.pseudoEncodingDesktopSize);
1117 encs.push(encodings.pseudoEncodingLastRect);
1118 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1119 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1120 encs.push(encodings.pseudoEncodingXvp);
1121 encs.push(encodings.pseudoEncodingFence);
1122 encs.push(encodings.pseudoEncodingContinuousUpdates);
1124 if (this._local_cursor && this._fb_depth == 24) {
1125 encs.push(encodings.pseudoEncodingCursor);
1128 RFB.messages.clientEncodings(this._sock, encs);
1131 /* RFB protocol initialization states:
1136 * ClientInitialization - not triggered by server message
1137 * ServerInitialization
1139 _init_msg: function () {
1140 switch (this._rfb_init_state
) {
1141 case 'ProtocolVersion':
1142 return this._negotiate_protocol_version();
1145 return this._negotiate_security();
1147 case 'Authentication':
1148 return this._negotiate_authentication();
1150 case 'SecurityResult':
1151 return this._handle_security_result();
1153 case 'ClientInitialisation':
1154 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1155 this._rfb_init_state
= 'ServerInitialisation';
1158 case 'ServerInitialisation':
1159 return this._negotiate_server_init();
1162 return this._fail("Internal error", "Unknown init state: " +
1163 this._rfb_init_state
);
1167 _handle_set_colour_map_msg: function () {
1168 Log
.Debug("SetColorMapEntries");
1170 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1173 _handle_server_cut_text: function () {
1174 Log
.Debug("ServerCutText");
1176 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1177 this._sock
.rQskipBytes(3); // Padding
1178 var length
= this._sock
.rQshift32();
1179 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1181 var text
= this._sock
.rQshiftStr(length
);
1183 if (this._view_only
) { return true; }
1185 this._onClipboard(this, text
);
1190 _handle_server_fence_msg: function() {
1191 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1192 this._sock
.rQskipBytes(3); // Padding
1193 var flags
= this._sock
.rQshift32();
1194 var length
= this._sock
.rQshift8();
1196 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1199 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1203 var payload
= this._sock
.rQshiftStr(length
);
1205 this._supportsFence
= true;
1210 * (1<<0) - BlockBefore
1211 * (1<<1) - BlockAfter
1216 if (!(flags
& (1<<31))) {
1217 return this._fail("Internal error",
1218 "Unexpected fence response");
1221 // Filter out unsupported flags
1222 // FIXME: support syncNext
1223 flags
&= (1<<0) | (1<<1);
1225 // BlockBefore and BlockAfter are automatically handled by
1226 // the fact that we process each incoming message
1228 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1233 _handle_xvp_msg: function () {
1234 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1235 this._sock
.rQskip8(); // Padding
1236 var xvp_ver
= this._sock
.rQshift8();
1237 var xvp_msg
= this._sock
.rQshift8();
1241 Log
.Error("Operation Failed");
1242 this._notification("XVP Operation Failed", 'error');
1245 this._rfb_xvp_ver
= xvp_ver
;
1246 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1247 this._setCapability("power", true);
1250 this._fail("Unexpected server message",
1251 "Illegal server XVP message " + xvp_msg
);
1258 _normal_msg: function () {
1261 if (this._FBU
.rects
> 0) {
1264 msg_type
= this._sock
.rQshift8();
1268 case 0: // FramebufferUpdate
1269 var ret
= this._framebufferUpdate();
1270 if (ret
&& !this._enabledContinuousUpdates
) {
1271 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1272 this._fb_width
, this._fb_height
);
1276 case 1: // SetColorMapEntries
1277 return this._handle_set_colour_map_msg();
1284 case 3: // ServerCutText
1285 return this._handle_server_cut_text();
1287 case 150: // EndOfContinuousUpdates
1288 var first
= !(this._supportsContinuousUpdates
);
1289 this._supportsContinuousUpdates
= true;
1290 this._enabledContinuousUpdates
= false;
1292 this._enabledContinuousUpdates
= true;
1293 this._updateContinuousUpdates();
1294 Log
.Info("Enabling continuous updates.");
1296 // FIXME: We need to send a framebufferupdaterequest here
1297 // if we add support for turning off continuous updates
1301 case 248: // ServerFence
1302 return this._handle_server_fence_msg();
1305 return this._handle_xvp_msg();
1308 this._fail("Unexpected server message", "Type:" + msg_type
);
1309 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1314 _onFlush: function() {
1315 this._flushing
= false;
1316 // Resume processing
1317 if (this._sock
.rQlen() > 0) {
1318 this._handle_message();
1322 _framebufferUpdate: function () {
1326 if (this._FBU
.rects
=== 0) {
1327 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1328 this._sock
.rQskip8(); // Padding
1329 this._FBU
.rects
= this._sock
.rQshift16();
1330 this._FBU
.bytes
= 0;
1331 this._timing
.cur_fbu
= 0;
1332 if (this._timing
.fbu_rt_start
> 0) {
1333 now
= (new Date()).getTime();
1334 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1337 // Make sure the previous frame is fully rendered first
1338 // to avoid building up an excessive queue
1339 if (this._display
.pending()) {
1340 this._flushing
= true;
1341 this._display
.flush();
1346 while (this._FBU
.rects
> 0) {
1347 if (this._rfb_connection_state
!== 'connected') { return false; }
1349 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1350 if (this._FBU
.bytes
=== 0) {
1351 if (this._sock
.rQwait("rect header", 12)) { return false; }
1352 /* New FramebufferUpdate */
1354 var hdr
= this._sock
.rQshiftBytes(12);
1355 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1356 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1357 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1358 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1359 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1360 (hdr
[10] << 8) + hdr
[11], 10);
1362 if (!this._encHandlers
[this._FBU
.encoding
]) {
1363 this._fail("Unexpected server message",
1364 "Unsupported encoding " +
1365 this._FBU
.encoding
);
1370 this._timing
.last_fbu
= (new Date()).getTime();
1372 ret
= this._encHandlers
[this._FBU
.encoding
]();
1374 now
= (new Date()).getTime();
1375 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1378 if (!(this._FBU
.encoding
in this._encStats
)) {
1379 this._encStats
[this._FBU
.encoding
] = [0, 0];
1381 this._encStats
[this._FBU
.encoding
][0]++;
1382 this._encStats
[this._FBU
.encoding
][1]++;
1383 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1386 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1387 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1388 this._timing
.fbu_rt_start
> 0) {
1389 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1390 this._timing
.full_fbu_cnt
++;
1391 Log
.Info("Timing of full FBU, curr: " +
1392 this._timing
.cur_fbu
+ ", total: " +
1393 this._timing
.full_fbu_total
+ ", cnt: " +
1394 this._timing
.full_fbu_cnt
+ ", avg: " +
1395 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1398 if (this._timing
.fbu_rt_start
> 0) {
1399 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1400 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1401 this._timing
.fbu_rt_cnt
++;
1402 Log
.Info("full FBU round-trip, cur: " +
1403 fbu_rt_diff
+ ", total: " +
1404 this._timing
.fbu_rt_total
+ ", cnt: " +
1405 this._timing
.fbu_rt_cnt
+ ", avg: " +
1406 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1407 this._timing
.fbu_rt_start
= 0;
1411 if (!ret
) { return ret
; } // need more data
1414 this._display
.flip();
1416 return true; // We finished this FBU
1419 _updateContinuousUpdates: function() {
1420 if (!this._enabledContinuousUpdates
) { return; }
1422 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1423 this._fb_width
, this._fb_height
);
1426 _resize: function(width
, height
) {
1427 this._fb_width
= width
;
1428 this._fb_height
= height
;
1430 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1432 this._display
.resize(this._fb_width
, this._fb_height
);
1433 this._onFBResize(this, this._fb_width
, this._fb_height
);
1435 this._timing
.fbu_rt_start
= (new Date()).getTime();
1436 this._updateContinuousUpdates();
1439 _xvpOp: function (ver
, op
) {
1440 if (this._rfb_xvp_ver
< ver
) { return; }
1441 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
1442 RFB
.messages
.xvpOp(this._sock
, ver
, op
);
1446 make_properties(RFB
, [
1447 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1448 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1449 ['touchButton', 'rw', 'int'], // Button mask (1, 2, 4) for touch devices (0 means ignore clicks)
1450 ['scale', 'rw', 'float'], // Display area scale factor
1451 ['viewport', 'rw', 'bool'], // Use viewport clipping
1452 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1453 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1454 ['capabilities', 'ro', 'arr'], // Supported capabilities
1456 // Callback functions
1457 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1458 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1459 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1460 ['onCredentialsRequired', 'rw', 'func'], // onCredentialsRequired(rfb, types): VNC credentials are required
1461 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1462 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1463 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1464 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1465 ['onCapabilities', 'rw', 'func'] // onCapabilities(rfb, caps): the supported capabilities has changed
1468 RFB
.prototype.set_local_cursor = function (cursor
) {
1469 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1470 this._local_cursor
= false;
1471 this._display
.disableLocalCursor(); //Only show server-side cursor
1473 if (this._display
.get_cursor_uri()) {
1474 this._local_cursor
= true;
1476 Log
.Warn("Browser does not support local cursor");
1477 this._display
.disableLocalCursor();
1481 // Need to send an updated list of encodings if we are connected
1482 if (this._rfb_connection_state
=== "connected") {
1483 this._sendEncodings();
1487 RFB
.prototype.set_view_only = function (view_only
) {
1488 this._view_only
= view_only
;
1490 if (this._rfb_connection_state
=== "connecting" ||
1491 this._rfb_connection_state
=== "connected") {
1493 this._keyboard
.ungrab();
1494 this._mouse
.ungrab();
1496 this._keyboard
.grab();
1502 RFB
.prototype.set_touchButton = function (button
) {
1503 this._mouse
.set_touchButton(button
);
1506 RFB
.prototype.get_touchButton = function () {
1507 return this._mouse
.get_touchButton();
1510 RFB
.prototype.set_scale = function (scale
) {
1511 this._display
.set_scale(scale
);
1514 RFB
.prototype.get_scale = function () {
1515 return this._display
.get_scale();
1518 RFB
.prototype.set_viewport = function (viewport
) {
1519 this._display
.set_viewport(viewport
);
1522 RFB
.prototype.get_viewport = function () {
1523 return this._display
.get_viewport();
1528 keyEvent: function (sock
, keysym
, down
) {
1529 var buff
= sock
._sQ
;
1530 var offset
= sock
._sQlen
;
1532 buff
[offset
] = 4; // msg-type
1533 buff
[offset
+ 1] = down
;
1535 buff
[offset
+ 2] = 0;
1536 buff
[offset
+ 3] = 0;
1538 buff
[offset
+ 4] = (keysym
>> 24);
1539 buff
[offset
+ 5] = (keysym
>> 16);
1540 buff
[offset
+ 6] = (keysym
>> 8);
1541 buff
[offset
+ 7] = keysym
;
1547 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1548 function getRFBkeycode(xt_scancode
) {
1549 var upperByte
= (keycode
>> 8);
1550 var lowerByte
= (keycode
& 0x00ff);
1551 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1552 lowerByte
= lowerByte
| 0x80;
1558 var buff
= sock
._sQ
;
1559 var offset
= sock
._sQlen
;
1561 buff
[offset
] = 255; // msg-type
1562 buff
[offset
+ 1] = 0; // sub msg-type
1564 buff
[offset
+ 2] = (down
>> 8);
1565 buff
[offset
+ 3] = down
;
1567 buff
[offset
+ 4] = (keysym
>> 24);
1568 buff
[offset
+ 5] = (keysym
>> 16);
1569 buff
[offset
+ 6] = (keysym
>> 8);
1570 buff
[offset
+ 7] = keysym
;
1572 var RFBkeycode
= getRFBkeycode(keycode
);
1574 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1575 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1576 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1577 buff
[offset
+ 11] = RFBkeycode
;
1583 pointerEvent: function (sock
, x
, y
, mask
) {
1584 var buff
= sock
._sQ
;
1585 var offset
= sock
._sQlen
;
1587 buff
[offset
] = 5; // msg-type
1589 buff
[offset
+ 1] = mask
;
1591 buff
[offset
+ 2] = x
>> 8;
1592 buff
[offset
+ 3] = x
;
1594 buff
[offset
+ 4] = y
>> 8;
1595 buff
[offset
+ 5] = y
;
1601 // TODO(directxman12): make this unicode compatible?
1602 clientCutText: function (sock
, text
) {
1603 var buff
= sock
._sQ
;
1604 var offset
= sock
._sQlen
;
1606 buff
[offset
] = 6; // msg-type
1608 buff
[offset
+ 1] = 0; // padding
1609 buff
[offset
+ 2] = 0; // padding
1610 buff
[offset
+ 3] = 0; // padding
1612 var n
= text
.length
;
1614 buff
[offset
+ 4] = n
>> 24;
1615 buff
[offset
+ 5] = n
>> 16;
1616 buff
[offset
+ 6] = n
>> 8;
1617 buff
[offset
+ 7] = n
;
1619 for (var i
= 0; i
< n
; i
++) {
1620 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1623 sock
._sQlen
+= 8 + n
;
1627 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1628 var buff
= sock
._sQ
;
1629 var offset
= sock
._sQlen
;
1631 buff
[offset
] = 251; // msg-type
1632 buff
[offset
+ 1] = 0; // padding
1633 buff
[offset
+ 2] = width
>> 8; // width
1634 buff
[offset
+ 3] = width
;
1635 buff
[offset
+ 4] = height
>> 8; // height
1636 buff
[offset
+ 5] = height
;
1638 buff
[offset
+ 6] = 1; // number-of-screens
1639 buff
[offset
+ 7] = 0; // padding
1642 buff
[offset
+ 8] = id
>> 24; // id
1643 buff
[offset
+ 9] = id
>> 16;
1644 buff
[offset
+ 10] = id
>> 8;
1645 buff
[offset
+ 11] = id
;
1646 buff
[offset
+ 12] = 0; // x-position
1647 buff
[offset
+ 13] = 0;
1648 buff
[offset
+ 14] = 0; // y-position
1649 buff
[offset
+ 15] = 0;
1650 buff
[offset
+ 16] = width
>> 8; // width
1651 buff
[offset
+ 17] = width
;
1652 buff
[offset
+ 18] = height
>> 8; // height
1653 buff
[offset
+ 19] = height
;
1654 buff
[offset
+ 20] = flags
>> 24; // flags
1655 buff
[offset
+ 21] = flags
>> 16;
1656 buff
[offset
+ 22] = flags
>> 8;
1657 buff
[offset
+ 23] = flags
;
1663 clientFence: function (sock
, flags
, payload
) {
1664 var buff
= sock
._sQ
;
1665 var offset
= sock
._sQlen
;
1667 buff
[offset
] = 248; // msg-type
1669 buff
[offset
+ 1] = 0; // padding
1670 buff
[offset
+ 2] = 0; // padding
1671 buff
[offset
+ 3] = 0; // padding
1673 buff
[offset
+ 4] = flags
>> 24; // flags
1674 buff
[offset
+ 5] = flags
>> 16;
1675 buff
[offset
+ 6] = flags
>> 8;
1676 buff
[offset
+ 7] = flags
;
1678 var n
= payload
.length
;
1680 buff
[offset
+ 8] = n
; // length
1682 for (var i
= 0; i
< n
; i
++) {
1683 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1686 sock
._sQlen
+= 9 + n
;
1690 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1691 var buff
= sock
._sQ
;
1692 var offset
= sock
._sQlen
;
1694 buff
[offset
] = 150; // msg-type
1695 buff
[offset
+ 1] = enable
; // enable-flag
1697 buff
[offset
+ 2] = x
>> 8; // x
1698 buff
[offset
+ 3] = x
;
1699 buff
[offset
+ 4] = y
>> 8; // y
1700 buff
[offset
+ 5] = y
;
1701 buff
[offset
+ 6] = width
>> 8; // width
1702 buff
[offset
+ 7] = width
;
1703 buff
[offset
+ 8] = height
>> 8; // height
1704 buff
[offset
+ 9] = height
;
1710 pixelFormat: function (sock
, depth
, true_color
) {
1711 var buff
= sock
._sQ
;
1712 var offset
= sock
._sQlen
;
1718 } else if (depth
> 8) {
1724 bits
= Math
.floor(depth
/3);
1726 buff
[offset
] = 0; // msg-type
1728 buff
[offset
+ 1] = 0; // padding
1729 buff
[offset
+ 2] = 0; // padding
1730 buff
[offset
+ 3] = 0; // padding
1732 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1733 buff
[offset
+ 5] = depth
; // depth
1734 buff
[offset
+ 6] = 0; // little-endian
1735 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1737 buff
[offset
+ 8] = 0; // red-max
1738 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1740 buff
[offset
+ 10] = 0; // green-max
1741 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1743 buff
[offset
+ 12] = 0; // blue-max
1744 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1746 buff
[offset
+ 14] = bits
* 2; // red-shift
1747 buff
[offset
+ 15] = bits
* 1; // green-shift
1748 buff
[offset
+ 16] = bits
* 0; // blue-shift
1750 buff
[offset
+ 17] = 0; // padding
1751 buff
[offset
+ 18] = 0; // padding
1752 buff
[offset
+ 19] = 0; // padding
1758 clientEncodings: function (sock
, encodings
) {
1759 var buff
= sock
._sQ
;
1760 var offset
= sock
._sQlen
;
1762 buff
[offset
] = 2; // msg-type
1763 buff
[offset
+ 1] = 0; // padding
1765 buff
[offset
+ 2] = encodings
.length
>> 8;
1766 buff
[offset
+ 3] = encodings
.length
;
1768 var i
, j
= offset
+ 4;
1769 for (i
= 0; i
< encodings
.length
; i
++) {
1770 var enc
= encodings
[i
];
1771 buff
[j
] = enc
>> 24;
1772 buff
[j
+ 1] = enc
>> 16;
1773 buff
[j
+ 2] = enc
>> 8;
1779 sock
._sQlen
+= j
- offset
;
1783 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1784 var buff
= sock
._sQ
;
1785 var offset
= sock
._sQlen
;
1787 if (typeof(x
) === "undefined") { x
= 0; }
1788 if (typeof(y
) === "undefined") { y
= 0; }
1790 buff
[offset
] = 3; // msg-type
1791 buff
[offset
+ 1] = incremental
? 1 : 0;
1793 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1794 buff
[offset
+ 3] = x
& 0xFF;
1796 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1797 buff
[offset
+ 5] = y
& 0xFF;
1799 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1800 buff
[offset
+ 7] = w
& 0xFF;
1802 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1803 buff
[offset
+ 9] = h
& 0xFF;
1809 xvpOp: function (sock
, ver
, op
) {
1810 var buff
= sock
._sQ
;
1811 var offset
= sock
._sQlen
;
1813 buff
[offset
] = 250; // msg-type
1814 buff
[offset
+ 1] = 0; // padding
1816 buff
[offset
+ 2] = ver
;
1817 buff
[offset
+ 3] = op
;
1824 RFB
.genDES = function (password
, challenge
) {
1826 for (var i
= 0; i
< password
.length
; i
++) {
1827 passwd
.push(password
.charCodeAt(i
));
1829 return (new DES(passwd
)).encrypt(challenge
);
1832 RFB
.encodingHandlers
= {
1834 if (this._FBU
.lines
=== 0) {
1835 this._FBU
.lines
= this._FBU
.height
;
1838 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1839 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1840 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1841 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1842 var curr_height
= Math
.min(this._FBU
.lines
,
1843 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1844 var data
= this._sock
.get_rQ();
1845 var index
= this._sock
.get_rQi();
1846 if (this._fb_depth
== 8) {
1847 var pixels
= this._FBU
.width
* curr_height
1848 var newdata
= new Uint8Array(pixels
* 4);
1850 for (i
= 0;i
< pixels
;i
++) {
1851 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1852 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1853 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1854 newdata
[i
* 4 + 4] = 0;
1859 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1860 curr_height
, data
, index
);
1861 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1862 this._FBU
.lines
-= curr_height
;
1864 if (this._FBU
.lines
> 0) {
1865 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1868 this._FBU
.bytes
= 0;
1874 COPYRECT: function () {
1875 this._FBU
.bytes
= 4;
1876 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1877 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1878 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1882 this._FBU
.bytes
= 0;
1888 if (this._FBU
.subrects
=== 0) {
1889 this._FBU
.bytes
= 4 + 4;
1890 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1891 this._FBU
.subrects
= this._sock
.rQshift32();
1892 color
= this._sock
.rQshiftBytes(4); // Background
1893 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1896 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1897 color
= this._sock
.rQshiftBytes(4);
1898 var x
= this._sock
.rQshift16();
1899 var y
= this._sock
.rQshift16();
1900 var width
= this._sock
.rQshift16();
1901 var height
= this._sock
.rQshift16();
1902 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1903 this._FBU
.subrects
--;
1906 if (this._FBU
.subrects
> 0) {
1907 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1908 this._FBU
.bytes
= (4 + 8) * chunk
;
1911 this._FBU
.bytes
= 0;
1917 HEXTILE: function () {
1918 var rQ
= this._sock
.get_rQ();
1919 var rQi
= this._sock
.get_rQi();
1921 if (this._FBU
.tiles
=== 0) {
1922 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1923 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1924 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1925 this._FBU
.tiles
= this._FBU
.total_tiles
;
1928 while (this._FBU
.tiles
> 0) {
1929 this._FBU
.bytes
= 1;
1930 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1931 var subencoding
= rQ
[rQi
]; // Peek
1932 if (subencoding
> 30) { // Raw
1933 this._fail("Unexpected server message",
1934 "Illegal hextile subencoding: " + subencoding
);
1939 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1940 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1941 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1942 var x
= this._FBU
.x
+ tile_x
* 16;
1943 var y
= this._FBU
.y
+ tile_y
* 16;
1944 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1945 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1947 // Figure out how much we are expecting
1948 if (subencoding
& 0x01) { // Raw
1949 this._FBU
.bytes
+= w
* h
* 4;
1951 if (subencoding
& 0x02) { // Background
1952 this._FBU
.bytes
+= 4;
1954 if (subencoding
& 0x04) { // Foreground
1955 this._FBU
.bytes
+= 4;
1957 if (subencoding
& 0x08) { // AnySubrects
1958 this._FBU
.bytes
++; // Since we aren't shifting it off
1959 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1960 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1961 if (subencoding
& 0x10) { // SubrectsColoured
1962 this._FBU
.bytes
+= subrects
* (4 + 2);
1964 this._FBU
.bytes
+= subrects
* 2;
1969 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1971 // We know the encoding and have a whole tile
1972 this._FBU
.subencoding
= rQ
[rQi
];
1974 if (this._FBU
.subencoding
=== 0) {
1975 if (this._FBU
.lastsubencoding
& 0x01) {
1976 // Weird: ignore blanks are RAW
1977 Log
.Debug(" Ignoring blank after RAW");
1979 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1981 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1982 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1983 rQi
+= this._FBU
.bytes
- 1;
1985 if (this._FBU
.subencoding
& 0x02) { // Background
1986 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1989 if (this._FBU
.subencoding
& 0x04) { // Foreground
1990 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1994 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1995 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1999 for (var s
= 0; s
< subrects
; s
++) {
2001 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
2002 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2005 color
= this._FBU
.foreground
;
2010 var sy
= (xy
& 0x0f);
2014 var sw
= (wh
>> 4) + 1;
2015 var sh
= (wh
& 0x0f) + 1;
2017 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
2020 this._display
.finishTile();
2022 this._sock
.set_rQi(rQi
);
2023 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2024 this._FBU
.bytes
= 0;
2028 if (this._FBU
.tiles
=== 0) {
2035 TIGHT: function () {
2036 this._FBU
.bytes
= 1; // compression-control byte
2037 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2039 var checksum = function (data
) {
2041 for (var i
= 0; i
< data
.length
; i
++) {
2043 if (sum
> 65536) sum
-= 65536;
2048 var resetStreams
= 0;
2050 var decompress = function (data
, expected
) {
2051 for (var i
= 0; i
< 4; i
++) {
2052 if ((resetStreams
>> i
) & 1) {
2053 this._FBU
.zlibs
[i
].reset();
2054 Log
.Info("Reset zlib stream " + i
);
2058 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2059 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2060 /*if (uncompressed.status !== 0) {
2061 Log.Error("Invalid data in zlib stream");
2064 //return uncompressed.data;
2065 return uncompressed
;
2068 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2069 // Convert indexed (palette based) image data to RGB
2070 // TODO: reduce number of calculations inside loop
2071 var dest
= this._destBuff
;
2072 var w
= Math
.floor((width
+ 7) / 8);
2073 var w1
= Math
.floor(width
/ 8);
2075 /*for (var y = 0; y < height; y++) {
2077 var yoffset = y * width;
2078 var ybitoffset = y * w;
2079 var xoffset, targetbyte;
2080 for (x = 0; x < w1; x++) {
2081 xoffset = yoffset + x * 8;
2082 targetbyte = data[ybitoffset + x];
2083 for (b = 7; b >= 0; b--) {
2084 dp = (xoffset + 7 - b) * 3;
2085 sp = (targetbyte >> b & 1) * 3;
2086 dest[dp] = palette[sp];
2087 dest[dp + 1] = palette[sp + 1];
2088 dest[dp + 2] = palette[sp + 2];
2092 xoffset = yoffset + x * 8;
2093 targetbyte = data[ybitoffset + x];
2094 for (b = 7; b >= 8 - width % 8; b--) {
2095 dp = (xoffset + 7 - b) * 3;
2096 sp = (targetbyte >> b & 1) * 3;
2097 dest[dp] = palette[sp];
2098 dest[dp + 1] = palette[sp + 1];
2099 dest[dp + 2] = palette[sp + 2];
2103 for (var y
= 0; y
< height
; y
++) {
2105 for (x
= 0; x
< w1
; x
++) {
2106 for (b
= 7; b
>= 0; b
--) {
2107 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2108 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2109 dest
[dp
] = palette
[sp
];
2110 dest
[dp
+ 1] = palette
[sp
+ 1];
2111 dest
[dp
+ 2] = palette
[sp
+ 2];
2116 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2117 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2118 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2119 dest
[dp
] = palette
[sp
];
2120 dest
[dp
+ 1] = palette
[sp
+ 1];
2121 dest
[dp
+ 2] = palette
[sp
+ 2];
2129 var indexedToRGBX = function (data
, palette
, width
, height
) {
2130 // Convert indexed (palette based) image data to RGB
2131 var dest
= this._destBuff
;
2132 var total
= width
* height
* 4;
2133 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2134 var sp
= data
[j
] * 3;
2135 dest
[i
] = palette
[sp
];
2136 dest
[i
+ 1] = palette
[sp
+ 1];
2137 dest
[i
+ 2] = palette
[sp
+ 2];
2144 var rQi
= this._sock
.get_rQi();
2145 var rQ
= this._sock
.rQwhole();
2147 var cl_header
, cl_data
;
2149 var handlePalette = function () {
2150 var numColors
= rQ
[rQi
+ 2] + 1;
2151 var paletteSize
= numColors
* 3;
2152 this._FBU
.bytes
+= paletteSize
;
2153 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2155 var bpp
= (numColors
<= 2) ? 1 : 8;
2156 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2158 if (rowSize
* this._FBU
.height
< 12) {
2161 cl_data
= rowSize
* this._FBU
.height
;
2162 //clength = [0, rowSize * this._FBU.height];
2164 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2165 var cl_offset
= rQi
+ 3 + paletteSize
;
2168 cl_data
+= rQ
[cl_offset
] & 0x7f;
2169 if (rQ
[cl_offset
] & 0x80) {
2171 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2172 if (rQ
[cl_offset
+ 1] & 0x80) {
2174 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2177 // end inline getTightCLength
2180 this._FBU
.bytes
+= cl_header
+ cl_data
;
2181 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2183 // Shift ctl, filter id, num colors, palette entries, and clength off
2184 this._sock
.rQskipBytes(3);
2185 //var palette = this._sock.rQshiftBytes(paletteSize);
2186 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2187 this._sock
.rQskipBytes(cl_header
);
2190 data
= this._sock
.rQshiftBytes(cl_data
);
2192 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2195 // Convert indexed (palette based) image data to RGB
2197 if (numColors
== 2) {
2198 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2199 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2201 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2202 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2209 var handleCopy = function () {
2211 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2212 if (uncompressedSize
< 12) {
2215 cl_data
= uncompressedSize
;
2217 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2218 var cl_offset
= rQi
+ 1;
2221 cl_data
+= rQ
[cl_offset
] & 0x7f;
2222 if (rQ
[cl_offset
] & 0x80) {
2224 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2225 if (rQ
[cl_offset
+ 1] & 0x80) {
2227 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2230 // end inline getTightCLength
2232 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2233 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2235 // Shift ctl, clength off
2236 this._sock
.rQshiftBytes(1 + cl_header
);
2239 data
= this._sock
.rQshiftBytes(cl_data
);
2241 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2244 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2249 var ctl
= this._sock
.rQpeek8();
2251 // Keep tight reset bits
2252 resetStreams
= ctl
& 0xF;
2254 // Figure out filter
2256 streamId
= ctl
& 0x3;
2258 if (ctl
=== 0x08) cmode
= "fill";
2259 else if (ctl
=== 0x09) cmode
= "jpeg";
2260 else if (ctl
=== 0x0A) cmode
= "png";
2261 else if (ctl
& 0x04) cmode
= "filter";
2262 else if (ctl
< 0x04) cmode
= "copy";
2263 else return this._fail("Unexpected server message",
2264 "Illegal tight compression received, " +
2268 // fill use depth because TPIXELs drop the padding byte
2269 case "fill": // TPIXEL
2270 this._FBU
.bytes
+= 3;
2272 case "jpeg": // max clength
2273 this._FBU
.bytes
+= 3;
2275 case "png": // max clength
2276 this._FBU
.bytes
+= 3;
2278 case "filter": // filter id + num colors if palette
2279 this._FBU
.bytes
+= 2;
2285 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2287 // Determine FBU.bytes
2291 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);
2292 this._sock
.rQskipBytes(4);
2296 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2297 var cl_offset
= rQi
+ 1;
2300 cl_data
+= rQ
[cl_offset
] & 0x7f;
2301 if (rQ
[cl_offset
] & 0x80) {
2303 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2304 if (rQ
[cl_offset
+ 1] & 0x80) {
2306 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2309 // end inline getTightCLength
2310 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2311 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2313 // We have everything, render it
2314 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2315 data
= this._sock
.rQshiftBytes(cl_data
);
2316 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2319 var filterId
= rQ
[rQi
+ 1];
2320 if (filterId
=== 1) {
2321 if (!handlePalette()) { return false; }
2323 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2324 // Filter 2, Gradient is valid but not use if jpeg is enabled
2325 this._fail("Unexpected server message",
2326 "Unsupported tight subencoding received, " +
2327 "filter: " + filterId
);
2331 if (!handleCopy()) { return false; }
2336 this._FBU
.bytes
= 0;
2342 last_rect: function () {
2343 this._FBU
.rects
= 0;
2347 ExtendedDesktopSize: function () {
2348 this._FBU
.bytes
= 1;
2349 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2351 this._supportsSetDesktopSize
= true;
2352 this._setCapability("resize", true);
2354 var number_of_screens
= this._sock
.rQpeek8();
2356 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2357 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2359 this._sock
.rQskipBytes(1); // number-of-screens
2360 this._sock
.rQskipBytes(3); // padding
2362 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2363 // Save the id and flags of the first screen
2365 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2366 this._sock
.rQskipBytes(2); // x-position
2367 this._sock
.rQskipBytes(2); // y-position
2368 this._sock
.rQskipBytes(2); // width
2369 this._sock
.rQskipBytes(2); // height
2370 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2372 this._sock
.rQskipBytes(16);
2377 * The x-position indicates the reason for the change:
2379 * 0 - server resized on its own
2380 * 1 - this client requested the resize
2381 * 2 - another client requested the resize
2384 // We need to handle errors when we requested the resize.
2385 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2387 // The y-position indicates the status code from the server
2388 switch (this._FBU
.y
) {
2390 msg
= "Resize is administratively prohibited";
2393 msg
= "Out of resources";
2396 msg
= "Invalid screen layout";
2399 msg
= "Unknown reason";
2402 this._notification("Server did not accept the resize request: "
2405 this._resize(this._FBU
.width
, this._FBU
.height
);
2408 this._FBU
.bytes
= 0;
2409 this._FBU
.rects
-= 1;
2413 DesktopSize: function () {
2414 this._resize(this._FBU
.width
, this._FBU
.height
);
2415 this._FBU
.bytes
= 0;
2416 this._FBU
.rects
-= 1;
2420 Cursor: function () {
2421 Log
.Debug(">> set_cursor");
2422 var x
= this._FBU
.x
; // hotspot-x
2423 var y
= this._FBU
.y
; // hotspot-y
2424 var w
= this._FBU
.width
;
2425 var h
= this._FBU
.height
;
2427 var pixelslength
= w
* h
* 4;
2428 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2430 this._FBU
.bytes
= pixelslength
+ masklength
;
2431 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2433 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2434 this._sock
.rQshiftBytes(masklength
),
2437 this._FBU
.bytes
= 0;
2440 Log
.Debug("<< set_cursor");
2444 QEMUExtendedKeyEvent: function () {
2447 // Old Safari doesn't support creating keyboard events
2449 var keyboardEvent
= document
.createEvent("keyboardEvent");
2450 if (keyboardEvent
.code
!== undefined) {
2451 this._qemuExtKeyEventSupported
= true;