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
) {
39 this._rfb_credentials
= {};
42 this._rfb_connection_state
= '';
43 this._rfb_init_state
= '';
44 this._rfb_auth_scheme
= '';
45 this._rfb_disconnect_reason
= "";
47 // Server capabilities
48 this._rfb_version
= 0;
49 this._rfb_max_version
= 3.8;
50 this._rfb_tightvnc
= false;
51 this._rfb_xvp_ver
= 0;
58 this._capabilities
= { power
: false, resize
: false };
60 this._supportsFence
= false;
62 this._supportsContinuousUpdates
= false;
63 this._enabledContinuousUpdates
= false;
65 this._supportsSetDesktopSize
= false;
67 this._screen_flags
= 0;
69 this._qemuExtKeyEventSupported
= false;
72 this._sock
= null; // Websock object
73 this._display
= null; // Display object
74 this._flushing
= false; // Display flushing state
75 this._keyboard
= null; // Keyboard input handler object
76 this._mouse
= null; // Mouse input handler object
79 this._disconnTimer
= null; // disconnection timer
81 // Decoder states and stats
82 this._encHandlers
= {};
87 subrects
: 0, // RRE and HEXTILE
98 zlibs
: [] // TIGHT zlib streams
100 for (var i
= 0; i
< 4; i
++) {
101 this._FBU
.zlibs
[i
] = new Inflator();
104 this._destBuff
= null;
105 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
107 this._rre_chunk_sz
= 100;
123 this._mouse_buttonMask
= 0;
124 this._mouse_arr
= [];
125 this._viewportDragging
= false;
126 this._viewportDragPos
= {};
127 this._viewportHasMoved
= false;
129 // set the default value on user-facing properties
130 set_defaults(this, defaults
, {
131 'target': 'null', // VNC display rendering Canvas object
132 'local_cursor': false, // Request locally rendered cursor
133 'shared': true, // Request shared mode
134 'view_only': false, // Disable client mouse/keyboard
135 'disconnectTimeout': 3, // Time (s) to wait for disconnection
136 'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
137 'repeaterID': '', // [UltraVNC] RepeaterID to connect to
138 'viewportDrag': false, // Move the viewport on mouse drags
140 // Callback functions
141 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
142 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
143 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
144 'onCredentialsRequired': function () { }, // onCredentialsRequired(rfb, types): VNC credentials are required
145 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
146 'onBell': function () { }, // onBell(rfb): RFB Bell message received
147 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
148 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
149 'onCapabilities': function () { } // onCapabilities(rfb, caps): the supported capabilities has changed
153 Log
.Debug(">> RFB.constructor");
155 // Target canvas must be able to have focus
156 if (!this._target
.hasAttribute('tabindex')) {
157 this._target
.tabIndex
= -1;
160 // populate encHandlers with bound versions
161 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this);
162 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this);
163 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this);
164 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this);
165 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this);
167 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this);
168 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this);
169 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this);
170 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this);
171 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this);
173 // NB: nothing that needs explicit teardown should be done
174 // before this point, since this can throw an exception
176 this._display
= new Display({target
: this._target
,
177 onFlush
: this._onFlush
.bind(this)});
179 Log
.Error("Display exception: " + exc
);
182 this._display
.clear();
184 this._keyboard
= new Keyboard({target
: this._target
,
185 onKeyEvent
: this._handleKeyEvent
.bind(this)});
187 this._mouse
= new Mouse({target
: this._target
,
188 onMouseButton
: this._handleMouseButton
.bind(this),
189 onMouseMove
: this._handleMouseMove
.bind(this)});
191 this._sock
= new Websock();
192 this._sock
.on('message', this._handle_message
.bind(this));
193 this._sock
.on('open', function () {
194 if ((this._rfb_connection_state
=== 'connecting') &&
195 (this._rfb_init_state
=== '')) {
196 this._rfb_init_state
= 'ProtocolVersion';
197 Log
.Debug("Starting VNC handshake");
199 this._fail("Unexpected server connection");
202 this._sock
.on('close', function (e
) {
203 Log
.Warn("WebSocket on-close event");
206 msg
= " (code: " + e
.code
;
208 msg
+= ", reason: " + e
.reason
;
212 switch (this._rfb_connection_state
) {
213 case 'disconnecting':
214 this._updateConnectionState('disconnected');
217 this._fail('Failed to connect to server', msg
);
220 // Handle disconnects that were initiated server-side
221 this._updateConnectionState('disconnecting');
222 this._updateConnectionState('disconnected');
225 this._fail("Unexpected server disconnect",
226 "Already disconnected: " + msg
);
229 this._fail("Unexpected server disconnect",
230 "Not in any state yet: " + msg
);
233 this._sock
.off('close');
235 this._sock
.on('error', function (e
) {
236 Log
.Warn("WebSocket on-error event");
239 var rmode
= this._display
.get_render_mode();
240 Log
.Info("Using native WebSockets, render mode: " + rmode
);
242 Log
.Debug("<< RFB.constructor");
247 connect: function (url
, creds
) {
249 this._rfb_credentials
= (creds
!== undefined) ? creds
: {};
252 this._fail(_("Must specify URL"));
256 this._rfb_init_state
= '';
257 this._updateConnectionState('connecting');
261 disconnect: function () {
262 this._updateConnectionState('disconnecting');
263 this._sock
.off('error');
264 this._sock
.off('message');
265 this._sock
.off('open');
268 sendCredentials: function (creds
) {
269 this._rfb_credentials
= creds
;
270 setTimeout(this._init_msg
.bind(this), 0);
273 sendCtrlAltDel: function () {
274 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
275 Log
.Info("Sending Ctrl-Alt-Del");
277 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
278 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
279 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
280 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
281 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
282 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
287 machineShutdown: function () {
291 machineReboot: function () {
295 machineReset: function () {
299 // Send a key press. If 'down' is not specified then send a down key
300 // followed by an up key.
301 sendKey: function (keysym
, code
, down
) {
302 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
304 if (down
=== undefined) {
305 this.sendKey(keysym
, code
, true);
306 this.sendKey(keysym
, code
, false);
310 var scancode
= XtScancode
[code
];
312 if (this._qemuExtKeyEventSupported
&& scancode
) {
314 keysym
= keysym
|| 0;
316 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
318 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
323 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
324 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
330 clipboardPasteFrom: function (text
) {
331 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return; }
332 RFB
.messages
.clientCutText(this._sock
, text
);
335 autoscale: function (width
, height
, downscaleOnly
) {
336 if (this._rfb_connection_state
!== 'connected') { return; }
337 this._display
.autoscale(width
, height
, downscaleOnly
);
340 viewportChangeSize: function(width
, height
) {
341 if (this._rfb_connection_state
!== 'connected') { return; }
342 this._display
.viewportChangeSize(width
, height
);
345 clippingDisplay: function () {
346 if (this._rfb_connection_state
!== 'connected') { return false; }
347 return this._display
.clippingDisplay();
350 // Requests a change of remote desktop size. This message is an extension
351 // and may only be sent if we have received an ExtendedDesktopSize message
352 requestDesktopSize: function (width
, height
) {
353 if (this._rfb_connection_state
!== 'connected' ||
358 if (this._supportsSetDesktopSize
) {
359 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
360 this._screen_id
, this._screen_flags
);
371 _connect: function () {
372 Log
.Debug(">> RFB.connect");
374 Log
.Info("connecting to " + this._url
);
377 // WebSocket.onopen transitions to the RFB init states
378 this._sock
.open(this._url
, this._wsProtocols
);
380 if (e
.name
=== 'SyntaxError') {
381 this._fail("Invalid host or port value given", e
);
383 this._fail("Error while connecting", e
);
387 // Always grab focus on some kind of click event
388 this._target
.addEventListener("mousedown", this._focusCanvas
);
389 this._target
.addEventListener("touchstart", this._focusCanvas
);
391 Log
.Debug("<< RFB.connect");
394 _disconnect: function () {
395 Log
.Debug(">> RFB.disconnect");
396 this._target
.removeEventListener("mousedown", this._focusCanvas
);
397 this._target
.removeEventListener("touchstart", this._focusCanvas
);
401 Log
.Debug("<< RFB.disconnect");
404 _print_stats: function () {
405 var stats
= this._encStats
;
407 Log
.Info("Encoding stats for this connection:");
408 Object
.keys(stats
).forEach(function (key
) {
410 if (s
[0] + s
[1] > 0) {
411 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
415 Log
.Info("Encoding stats since page load:");
416 Object
.keys(stats
).forEach(function (key
) {
418 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
422 _cleanup: function () {
423 if (!this._view_only
) { this._keyboard
.ungrab(); }
424 if (!this._view_only
) { this._mouse
.ungrab(); }
425 this._display
.defaultCursor();
426 if (Log
.get_logging() !== 'debug') {
427 // Show noVNC logo when disconnected, unless in
429 this._display
.clear();
433 // Event handler for canvas so this points to the canvas element
434 _focusCanvas: function(event
) {
435 // Respect earlier handlers' request to not do side-effects
436 if (!event
.defaultPrevented
)
445 * disconnected - permanent state
447 _updateConnectionState: function (state
) {
448 var oldstate
= this._rfb_connection_state
;
450 if (state
=== oldstate
) {
451 Log
.Debug("Already in state '" + state
+ "', ignoring");
455 // The 'disconnected' state is permanent for each RFB object
456 if (oldstate
=== 'disconnected') {
457 Log
.Error("Tried changing state of a disconnected RFB object");
461 // Ensure proper transitions before doing anything
464 if (oldstate
!== 'connecting') {
465 Log
.Error("Bad transition to connected state, " +
466 "previous connection state: " + oldstate
);
472 if (oldstate
!== 'disconnecting') {
473 Log
.Error("Bad transition to disconnected state, " +
474 "previous connection state: " + oldstate
);
480 if (oldstate
!== '') {
481 Log
.Error("Bad transition to connecting state, " +
482 "previous connection state: " + oldstate
);
487 case 'disconnecting':
488 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
489 Log
.Error("Bad transition to disconnecting state, " +
490 "previous connection state: " + oldstate
);
496 Log
.Error("Unknown connection state: " + state
);
500 // State change actions
502 this._rfb_connection_state
= state
;
503 this._onUpdateState(this, state
, oldstate
);
505 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
508 if (this._disconnTimer
&& state
!== 'disconnecting') {
509 Log
.Debug("Clearing disconnect timer");
510 clearTimeout(this._disconnTimer
);
511 this._disconnTimer
= null;
513 // make sure we don't get a double event
514 this._sock
.off('close');
519 // Call onDisconnected callback after onUpdateState since
520 // we don't know if the UI only displays the latest message
521 if (this._rfb_disconnect_reason
!== "") {
522 this._onDisconnected(this, this._rfb_disconnect_reason
);
524 // No reason means clean disconnect
525 this._onDisconnected(this);
533 case 'disconnecting':
536 this._disconnTimer
= setTimeout(function () {
537 this._rfb_disconnect_reason
= _("Disconnect timeout");
538 this._updateConnectionState('disconnected');
539 }.bind(this), this._disconnectTimeout
* 1000);
544 /* Print errors and disconnect
546 * The optional parameter 'details' is used for information that
547 * should be logged but not sent to the user interface.
549 _fail: function (msg
, details
) {
551 if (typeof details
!== 'undefined') {
552 fullmsg
= msg
+ " (" + details
+ ")";
554 switch (this._rfb_connection_state
) {
555 case 'disconnecting':
556 Log
.Error("Failed when disconnecting: " + fullmsg
);
559 Log
.Error("Failed while connected: " + fullmsg
);
562 Log
.Error("Failed when connecting: " + fullmsg
);
565 Log
.Error("RFB failure: " + fullmsg
);
568 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
570 // Transition to disconnected without waiting for socket to close
571 this._updateConnectionState('disconnecting');
572 this._updateConnectionState('disconnected');
578 * Send a notification to the UI. Valid levels are:
579 * 'normal'|'warn'|'error'
581 * NOTE: Options could be added in the future.
582 * NOTE: If this function is called multiple times, remember that the
583 * interface could be only showing the latest notification.
585 _notification: function(msg
, level
, options
) {
590 Log
.Debug("Notification[" + level
+ "]:" + msg
);
593 Log
.Error("Invalid notification level: " + level
);
598 this._onNotification(this, msg
, level
, options
);
600 this._onNotification(this, msg
, level
);
604 _setCapability: function (cap
, val
) {
605 this._capabilities
[cap
] = val
;
606 this._onCapabilities(this, this._capabilities
);
609 _handle_message: function () {
610 if (this._sock
.rQlen() === 0) {
611 Log
.Warn("handle_message called on an empty receive queue");
615 switch (this._rfb_connection_state
) {
617 Log
.Error("Got data while disconnected");
621 if (this._flushing
) {
624 if (!this._normal_msg()) {
627 if (this._sock
.rQlen() === 0) {
638 _handleKeyEvent: function (keysym
, code
, down
) {
639 this.sendKey(keysym
, code
, down
);
642 _handleMouseButton: function (x
, y
, down
, bmask
) {
644 this._mouse_buttonMask
|= bmask
;
646 this._mouse_buttonMask
&= ~bmask
;
649 if (this._viewportDrag
) {
650 if (down
&& !this._viewportDragging
) {
651 this._viewportDragging
= true;
652 this._viewportDragPos
= {'x': x
, 'y': y
};
654 // Skip sending mouse events
657 this._viewportDragging
= false;
659 // If the viewport didn't actually move, then treat as a mouse click event
660 // Send the button down event here, as the button up event is sent at the end of this function
661 if (!this._viewportHasMoved
&& !this._view_only
) {
662 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
664 this._viewportHasMoved
= false;
668 if (this._view_only
) { return; } // View only, skip mouse events
670 if (this._rfb_connection_state
!== 'connected') { return; }
671 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
674 _handleMouseMove: function (x
, y
) {
675 if (this._viewportDragging
) {
676 var deltaX
= this._viewportDragPos
.x
- x
;
677 var deltaY
= this._viewportDragPos
.y
- y
;
679 // The goal is to trigger on a certain physical width, the
680 // devicePixelRatio brings us a bit closer but is not optimal.
681 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
683 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
684 Math
.abs(deltaY
) > dragThreshold
)) {
685 this._viewportHasMoved
= true;
687 this._viewportDragPos
= {'x': x
, 'y': y
};
688 this._display
.viewportChangePos(deltaX
, deltaY
);
691 // Skip sending mouse events
695 if (this._view_only
) { return; } // View only, skip mouse events
697 if (this._rfb_connection_state
!== 'connected') { return; }
698 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
703 _negotiate_protocol_version: function () {
704 if (this._sock
.rQlen() < 12) {
705 return this._fail("Error while negotiating with server",
706 "Incomplete protocol version");
709 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
710 Log
.Info("Server ProtocolVersion: " + sversion
);
713 case "000.000": // UltraVNC repeater
717 case "003.006": // UltraVNC
718 case "003.889": // Apple Remote Desktop
719 this._rfb_version
= 3.3;
722 this._rfb_version
= 3.7;
725 case "004.000": // Intel AMT KVM
726 case "004.001": // RealVNC 4.6
727 case "005.000": // RealVNC 5.3
728 this._rfb_version
= 3.8;
731 return this._fail("Unsupported server",
732 "Invalid server version: " + sversion
);
736 var repeaterID
= this._repeaterID
;
737 while (repeaterID
.length
< 250) {
740 this._sock
.send_string(repeaterID
);
744 if (this._rfb_version
> this._rfb_max_version
) {
745 this._rfb_version
= this._rfb_max_version
;
748 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
749 ".00" + ((this._rfb_version
* 10) % 10);
750 this._sock
.send_string("RFB " + cversion
+ "\n");
751 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
753 this._rfb_init_state
= 'Security';
756 _negotiate_security: function () {
757 // Polyfill since IE and PhantomJS doesn't have
758 // TypedArray.includes()
759 function includes(item
, array
) {
760 for (var i
= 0; i
< array
.length
; i
++) {
761 if (array
[i
] === item
) {
768 if (this._rfb_version
>= 3.7) {
769 // Server sends supported list, client decides
770 var num_types
= this._sock
.rQshift8();
771 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
773 if (num_types
=== 0) {
774 var strlen
= this._sock
.rQshift32();
775 var reason
= this._sock
.rQshiftStr(strlen
);
776 return this._fail("Error while negotiating with server",
777 "Security failure: " + reason
);
780 var types
= this._sock
.rQshiftBytes(num_types
);
781 Log
.Debug("Server security types: " + types
);
783 // Look for each auth in preferred order
784 this._rfb_auth_scheme
= 0;
785 if (includes(1, types
)) {
786 this._rfb_auth_scheme
= 1; // None
787 } else if (includes(22, types
)) {
788 this._rfb_auth_scheme
= 22; // XVP
789 } else if (includes(16, types
)) {
790 this._rfb_auth_scheme
= 16; // Tight
791 } else if (includes(2, types
)) {
792 this._rfb_auth_scheme
= 2; // VNC Auth
794 return this._fail("Unsupported server",
795 "Unsupported security types: " + types
);
798 this._sock
.send([this._rfb_auth_scheme
]);
801 if (this._sock
.rQwait("security scheme", 4)) { return false; }
802 this._rfb_auth_scheme
= this._sock
.rQshift32();
805 this._rfb_init_state
= 'Authentication';
806 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
808 return this._init_msg(); // jump to authentication
812 _negotiate_xvp_auth: function () {
813 if (!this._rfb_credentials
.username
||
814 !this._rfb_credentials
.password
||
815 !this._rfb_credentials
.target
) {
816 this._onCredentialsRequired(this, ["username", "password", "target"]);
820 var xvp_auth_str
= String
.fromCharCode(this._rfb_credentials
.username
.length
) +
821 String
.fromCharCode(this._rfb_credentials
.target
.length
) +
822 this._rfb_credentials
.username
+
823 this._rfb_credentials
.target
;
824 this._sock
.send_string(xvp_auth_str
);
825 this._rfb_auth_scheme
= 2;
826 return this._negotiate_authentication();
829 _negotiate_std_vnc_auth: function () {
830 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
832 if (!this._rfb_credentials
.password
) {
833 this._onCredentialsRequired(this, ["password"]);
837 // TODO(directxman12): make genDES not require an Array
838 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
839 var response
= RFB
.genDES(this._rfb_credentials
.password
, challenge
);
840 this._sock
.send(response
);
841 this._rfb_init_state
= "SecurityResult";
845 _negotiate_tight_tunnels: function (numTunnels
) {
846 var clientSupportedTunnelTypes
= {
847 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
849 var serverSupportedTunnelTypes
= {};
850 // receive tunnel capabilities
851 for (var i
= 0; i
< numTunnels
; i
++) {
852 var cap_code
= this._sock
.rQshift32();
853 var cap_vendor
= this._sock
.rQshiftStr(4);
854 var cap_signature
= this._sock
.rQshiftStr(8);
855 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
858 // choose the notunnel type
859 if (serverSupportedTunnelTypes
[0]) {
860 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
861 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
862 return this._fail("Unsupported server",
863 "Client's tunnel type had the incorrect " +
864 "vendor or signature");
866 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
867 return false; // wait until we receive the sub auth count to continue
869 return this._fail("Unsupported server",
870 "Server wanted tunnels, but doesn't support " +
871 "the notunnel type");
875 _negotiate_tight_auth: function () {
876 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
877 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
878 var numTunnels
= this._sock
.rQshift32();
879 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
881 this._rfb_tightvnc
= true;
883 if (numTunnels
> 0) {
884 this._negotiate_tight_tunnels(numTunnels
);
885 return false; // wait until we receive the sub auth to continue
889 // second pass, do the sub-auth negotiation
890 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
891 var subAuthCount
= this._sock
.rQshift32();
892 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
893 this._rfb_init_state
= 'SecurityResult';
897 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
899 var clientSupportedTypes
= {
904 var serverSupportedTypes
= [];
906 for (var i
= 0; i
< subAuthCount
; i
++) {
907 var capNum
= this._sock
.rQshift32();
908 var capabilities
= this._sock
.rQshiftStr(12);
909 serverSupportedTypes
.push(capabilities
);
912 for (var authType
in clientSupportedTypes
) {
913 if (serverSupportedTypes
.indexOf(authType
) != -1) {
914 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
917 case 'STDVNOAUTH__': // no auth
918 this._rfb_init_state
= 'SecurityResult';
920 case 'STDVVNCAUTH_': // VNC auth
921 this._rfb_auth_scheme
= 2;
922 return this._init_msg();
924 return this._fail("Unsupported server",
925 "Unsupported tiny auth scheme: " +
931 return this._fail("Unsupported server",
932 "No supported sub-auth types!");
935 _negotiate_authentication: function () {
936 switch (this._rfb_auth_scheme
) {
937 case 0: // connection failed
938 if (this._sock
.rQwait("auth reason", 4)) { return false; }
939 var strlen
= this._sock
.rQshift32();
940 var reason
= this._sock
.rQshiftStr(strlen
);
941 return this._fail("Authentication failure", reason
);
944 if (this._rfb_version
>= 3.8) {
945 this._rfb_init_state
= 'SecurityResult';
948 this._rfb_init_state
= 'ClientInitialisation';
949 return this._init_msg();
952 return this._negotiate_xvp_auth();
954 case 2: // VNC authentication
955 return this._negotiate_std_vnc_auth();
957 case 16: // TightVNC Security Type
958 return this._negotiate_tight_auth();
961 return this._fail("Unsupported server",
962 "Unsupported auth scheme: " +
963 this._rfb_auth_scheme
);
967 _handle_security_result: function () {
968 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
969 switch (this._sock
.rQshift32()) {
971 this._rfb_init_state
= 'ClientInitialisation';
972 Log
.Debug('Authentication OK');
973 return this._init_msg();
975 if (this._rfb_version
>= 3.8) {
976 var length
= this._sock
.rQshift32();
977 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
978 var reason
= this._sock
.rQshiftStr(length
);
979 return this._fail("Authentication failure", reason
);
981 return this._fail("Authentication failure");
984 return this._fail("Too many authentication attempts");
986 return this._fail("Unsupported server",
987 "Unknown SecurityResult");
991 _negotiate_server_init: function () {
992 if (this._sock
.rQwait("server initialization", 24)) { return false; }
995 var width
= this._sock
.rQshift16();
996 var height
= this._sock
.rQshift16();
999 var bpp
= this._sock
.rQshift8();
1000 var depth
= this._sock
.rQshift8();
1001 var big_endian
= this._sock
.rQshift8();
1002 var true_color
= this._sock
.rQshift8();
1004 var red_max
= this._sock
.rQshift16();
1005 var green_max
= this._sock
.rQshift16();
1006 var blue_max
= this._sock
.rQshift16();
1007 var red_shift
= this._sock
.rQshift8();
1008 var green_shift
= this._sock
.rQshift8();
1009 var blue_shift
= this._sock
.rQshift8();
1010 this._sock
.rQskipBytes(3); // padding
1012 // NB(directxman12): we don't want to call any callbacks or print messages until
1013 // *after* we're past the point where we could backtrack
1015 /* Connection name/title */
1016 var name_length = this._sock.rQshift32();
1017 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1018 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1020 if (this._rfb_tightvnc) {
1021 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1022 // In TightVNC mode, ServerInit message is extended
1023 var numServerMessages = this._sock.rQshift16();
1024 var numClientMessages = this._sock.rQshift16();
1025 var numEncodings = this._sock.rQshift16();
1026 this._sock.rQskipBytes(2); // padding
1028 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1029 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1031 // we don't actually do anything with the capability information that TIGHT sends,
1032 // so we just skip the all of this.
1034 // TIGHT server message capabilities
1035 this._sock.rQskipBytes(16 * numServerMessages);
1037 // TIGHT client message capabilities
1038 this._sock.rQskipBytes(16 * numClientMessages);
1040 // TIGHT encoding capabilities
1041 this._sock.rQskipBytes(16 * numEncodings);
1044 // NB(directxman12): these are down here so that we don't run them multiple times
1046 Log.Info("Screen: " + width + "x" + height +
1047 ", bpp: " + bpp + ", depth: " + depth +
1048 ", big_endian: " + big_endian +
1049 ", true_color: " + true_color +
1050 ", red_max: " + red_max +
1051 ", green_max: " + green_max +
1052 ", blue_max: " + blue_max +
1053 ", red_shift: " + red_shift +
1054 ", green_shift: " + green_shift +
1055 ", blue_shift: " + blue_shift);
1057 if (big_endian !== 0) {
1058 Log.Warn("Server native endian is not little endian");
1061 if (red_shift !== 16) {
1062 Log.Warn("Server native red-shift is not 16");
1065 if (blue_shift !== 0) {
1066 Log.Warn("Server native blue-shift is not 0");
1069 // we're past the point where we could backtrack, so it's safe to call this
1070 this._onDesktopName(this, this._fb_name);
1072 this._resize(width, height);
1074 if (!this._view_only) { this._keyboard.grab(); }
1075 if (!this._view_only) { this._mouse.grab(); }
1077 this._fb_depth = 24;
1079 if (this._fb_name === "Intel(r) AMT KVM") {
1080 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1084 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1085 this._sendEncodings();
1086 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1088 this._timing.fbu_rt_start = (new Date()).getTime();
1089 this._timing.pixels = 0;
1091 // Cursor will be server side until the server decides to honor
1092 // our request and send over the cursor image
1093 this._display.disableLocalCursor();
1095 this._updateConnectionState('connected');
1099 _sendEncodings: function () {
1102 // In preference order
1103 encs.push(encodings.encodingCopyRect);
1104 // Only supported with full depth support
1105 if (this._fb_depth == 24) {
1106 encs.push(encodings.encodingTight);
1107 encs.push(encodings.encodingHextile);
1108 encs.push(encodings.encodingRRE);
1110 encs.push(encodings.encodingRaw);
1112 // Psuedo-encoding settings
1113 encs.push(encodings.pseudoEncodingTightPNG);
1114 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1115 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1117 encs.push(encodings.pseudoEncodingDesktopSize);
1118 encs.push(encodings.pseudoEncodingLastRect);
1119 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1120 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1121 encs.push(encodings.pseudoEncodingXvp);
1122 encs.push(encodings.pseudoEncodingFence);
1123 encs.push(encodings.pseudoEncodingContinuousUpdates);
1125 if (this._local_cursor && this._fb_depth == 24) {
1126 encs.push(encodings.pseudoEncodingCursor);
1129 RFB.messages.clientEncodings(this._sock, encs);
1132 /* RFB protocol initialization states:
1137 * ClientInitialization - not triggered by server message
1138 * ServerInitialization
1140 _init_msg: function () {
1141 switch (this._rfb_init_state
) {
1142 case 'ProtocolVersion':
1143 return this._negotiate_protocol_version();
1146 return this._negotiate_security();
1148 case 'Authentication':
1149 return this._negotiate_authentication();
1151 case 'SecurityResult':
1152 return this._handle_security_result();
1154 case 'ClientInitialisation':
1155 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1156 this._rfb_init_state
= 'ServerInitialisation';
1159 case 'ServerInitialisation':
1160 return this._negotiate_server_init();
1163 return this._fail("Internal error", "Unknown init state: " +
1164 this._rfb_init_state
);
1168 _handle_set_colour_map_msg: function () {
1169 Log
.Debug("SetColorMapEntries");
1171 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1174 _handle_server_cut_text: function () {
1175 Log
.Debug("ServerCutText");
1177 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1178 this._sock
.rQskipBytes(3); // Padding
1179 var length
= this._sock
.rQshift32();
1180 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1182 var text
= this._sock
.rQshiftStr(length
);
1184 if (this._view_only
) { return true; }
1186 this._onClipboard(this, text
);
1191 _handle_server_fence_msg: function() {
1192 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1193 this._sock
.rQskipBytes(3); // Padding
1194 var flags
= this._sock
.rQshift32();
1195 var length
= this._sock
.rQshift8();
1197 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1200 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1204 var payload
= this._sock
.rQshiftStr(length
);
1206 this._supportsFence
= true;
1211 * (1<<0) - BlockBefore
1212 * (1<<1) - BlockAfter
1217 if (!(flags
& (1<<31))) {
1218 return this._fail("Internal error",
1219 "Unexpected fence response");
1222 // Filter out unsupported flags
1223 // FIXME: support syncNext
1224 flags
&= (1<<0) | (1<<1);
1226 // BlockBefore and BlockAfter are automatically handled by
1227 // the fact that we process each incoming message
1229 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1234 _handle_xvp_msg: function () {
1235 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1236 this._sock
.rQskip8(); // Padding
1237 var xvp_ver
= this._sock
.rQshift8();
1238 var xvp_msg
= this._sock
.rQshift8();
1242 Log
.Error("Operation Failed");
1243 this._notification("XVP Operation Failed", 'error');
1246 this._rfb_xvp_ver
= xvp_ver
;
1247 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1248 this._setCapability("power", true);
1251 this._fail("Unexpected server message",
1252 "Illegal server XVP message " + xvp_msg
);
1259 _normal_msg: function () {
1262 if (this._FBU
.rects
> 0) {
1265 msg_type
= this._sock
.rQshift8();
1269 case 0: // FramebufferUpdate
1270 var ret
= this._framebufferUpdate();
1271 if (ret
&& !this._enabledContinuousUpdates
) {
1272 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1273 this._fb_width
, this._fb_height
);
1277 case 1: // SetColorMapEntries
1278 return this._handle_set_colour_map_msg();
1285 case 3: // ServerCutText
1286 return this._handle_server_cut_text();
1288 case 150: // EndOfContinuousUpdates
1289 var first
= !(this._supportsContinuousUpdates
);
1290 this._supportsContinuousUpdates
= true;
1291 this._enabledContinuousUpdates
= false;
1293 this._enabledContinuousUpdates
= true;
1294 this._updateContinuousUpdates();
1295 Log
.Info("Enabling continuous updates.");
1297 // FIXME: We need to send a framebufferupdaterequest here
1298 // if we add support for turning off continuous updates
1302 case 248: // ServerFence
1303 return this._handle_server_fence_msg();
1306 return this._handle_xvp_msg();
1309 this._fail("Unexpected server message", "Type:" + msg_type
);
1310 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1315 _onFlush: function() {
1316 this._flushing
= false;
1317 // Resume processing
1318 if (this._sock
.rQlen() > 0) {
1319 this._handle_message();
1323 _framebufferUpdate: function () {
1327 if (this._FBU
.rects
=== 0) {
1328 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1329 this._sock
.rQskip8(); // Padding
1330 this._FBU
.rects
= this._sock
.rQshift16();
1331 this._FBU
.bytes
= 0;
1332 this._timing
.cur_fbu
= 0;
1333 if (this._timing
.fbu_rt_start
> 0) {
1334 now
= (new Date()).getTime();
1335 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1338 // Make sure the previous frame is fully rendered first
1339 // to avoid building up an excessive queue
1340 if (this._display
.pending()) {
1341 this._flushing
= true;
1342 this._display
.flush();
1347 while (this._FBU
.rects
> 0) {
1348 if (this._rfb_connection_state
!== 'connected') { return false; }
1350 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1351 if (this._FBU
.bytes
=== 0) {
1352 if (this._sock
.rQwait("rect header", 12)) { return false; }
1353 /* New FramebufferUpdate */
1355 var hdr
= this._sock
.rQshiftBytes(12);
1356 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1357 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1358 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1359 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1360 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1361 (hdr
[10] << 8) + hdr
[11], 10);
1363 if (!this._encHandlers
[this._FBU
.encoding
]) {
1364 this._fail("Unexpected server message",
1365 "Unsupported encoding " +
1366 this._FBU
.encoding
);
1371 this._timing
.last_fbu
= (new Date()).getTime();
1373 ret
= this._encHandlers
[this._FBU
.encoding
]();
1375 now
= (new Date()).getTime();
1376 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1379 if (!(this._FBU
.encoding
in this._encStats
)) {
1380 this._encStats
[this._FBU
.encoding
] = [0, 0];
1382 this._encStats
[this._FBU
.encoding
][0]++;
1383 this._encStats
[this._FBU
.encoding
][1]++;
1384 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1387 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1388 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1389 this._timing
.fbu_rt_start
> 0) {
1390 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1391 this._timing
.full_fbu_cnt
++;
1392 Log
.Info("Timing of full FBU, curr: " +
1393 this._timing
.cur_fbu
+ ", total: " +
1394 this._timing
.full_fbu_total
+ ", cnt: " +
1395 this._timing
.full_fbu_cnt
+ ", avg: " +
1396 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1399 if (this._timing
.fbu_rt_start
> 0) {
1400 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1401 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1402 this._timing
.fbu_rt_cnt
++;
1403 Log
.Info("full FBU round-trip, cur: " +
1404 fbu_rt_diff
+ ", total: " +
1405 this._timing
.fbu_rt_total
+ ", cnt: " +
1406 this._timing
.fbu_rt_cnt
+ ", avg: " +
1407 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1408 this._timing
.fbu_rt_start
= 0;
1412 if (!ret
) { return ret
; } // need more data
1415 this._display
.flip();
1417 return true; // We finished this FBU
1420 _updateContinuousUpdates: function() {
1421 if (!this._enabledContinuousUpdates
) { return; }
1423 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1424 this._fb_width
, this._fb_height
);
1427 _resize: function(width
, height
) {
1428 this._fb_width
= width
;
1429 this._fb_height
= height
;
1431 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1433 this._display
.resize(this._fb_width
, this._fb_height
);
1434 this._onFBResize(this, this._fb_width
, this._fb_height
);
1436 this._timing
.fbu_rt_start
= (new Date()).getTime();
1437 this._updateContinuousUpdates();
1440 _xvpOp: function (ver
, op
) {
1441 if (this._rfb_xvp_ver
< ver
) { return; }
1442 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
1443 RFB
.messages
.xvpOp(this._sock
, ver
, op
);
1447 make_properties(RFB
, [
1448 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1449 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1450 ['shared', 'rw', 'bool'], // Request shared mode
1451 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1452 ['touchButton', 'rw', 'int'], // Button mask (1, 2, 4) for touch devices (0 means ignore clicks)
1453 ['scale', 'rw', 'float'], // Display area scale factor
1454 ['viewport', 'rw', 'bool'], // Use viewport clipping
1455 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1456 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1457 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1458 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1459 ['capabilities', 'ro', 'arr'], // Supported capabilities
1461 // Callback functions
1462 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1463 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1464 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1465 ['onCredentialsRequired', 'rw', 'func'], // onCredentialsRequired(rfb, types): VNC credentials are required
1466 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1467 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1468 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1469 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1470 ['onCapabilities', 'rw', 'func'] // onCapabilities(rfb, caps): the supported capabilities has changed
1473 RFB
.prototype.set_local_cursor = function (cursor
) {
1474 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1475 this._local_cursor
= false;
1476 this._display
.disableLocalCursor(); //Only show server-side cursor
1478 if (this._display
.get_cursor_uri()) {
1479 this._local_cursor
= true;
1481 Log
.Warn("Browser does not support local cursor");
1482 this._display
.disableLocalCursor();
1486 // Need to send an updated list of encodings if we are connected
1487 if (this._rfb_connection_state
=== "connected") {
1488 this._sendEncodings();
1492 RFB
.prototype.set_view_only = function (view_only
) {
1493 this._view_only
= view_only
;
1495 if (this._rfb_connection_state
=== "connecting" ||
1496 this._rfb_connection_state
=== "connected") {
1498 this._keyboard
.ungrab();
1499 this._mouse
.ungrab();
1501 this._keyboard
.grab();
1507 RFB
.prototype.set_touchButton = function (button
) {
1508 this._mouse
.set_touchButton(button
);
1511 RFB
.prototype.get_touchButton = function () {
1512 return this._mouse
.get_touchButton();
1515 RFB
.prototype.set_scale = function (scale
) {
1516 this._display
.set_scale(scale
);
1519 RFB
.prototype.get_scale = function () {
1520 return this._display
.get_scale();
1523 RFB
.prototype.set_viewport = function (viewport
) {
1524 this._display
.set_viewport(viewport
);
1527 RFB
.prototype.get_viewport = function () {
1528 return this._display
.get_viewport();
1533 keyEvent: function (sock
, keysym
, down
) {
1534 var buff
= sock
._sQ
;
1535 var offset
= sock
._sQlen
;
1537 buff
[offset
] = 4; // msg-type
1538 buff
[offset
+ 1] = down
;
1540 buff
[offset
+ 2] = 0;
1541 buff
[offset
+ 3] = 0;
1543 buff
[offset
+ 4] = (keysym
>> 24);
1544 buff
[offset
+ 5] = (keysym
>> 16);
1545 buff
[offset
+ 6] = (keysym
>> 8);
1546 buff
[offset
+ 7] = keysym
;
1552 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1553 function getRFBkeycode(xt_scancode
) {
1554 var upperByte
= (keycode
>> 8);
1555 var lowerByte
= (keycode
& 0x00ff);
1556 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1557 lowerByte
= lowerByte
| 0x80;
1563 var buff
= sock
._sQ
;
1564 var offset
= sock
._sQlen
;
1566 buff
[offset
] = 255; // msg-type
1567 buff
[offset
+ 1] = 0; // sub msg-type
1569 buff
[offset
+ 2] = (down
>> 8);
1570 buff
[offset
+ 3] = down
;
1572 buff
[offset
+ 4] = (keysym
>> 24);
1573 buff
[offset
+ 5] = (keysym
>> 16);
1574 buff
[offset
+ 6] = (keysym
>> 8);
1575 buff
[offset
+ 7] = keysym
;
1577 var RFBkeycode
= getRFBkeycode(keycode
);
1579 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1580 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1581 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1582 buff
[offset
+ 11] = RFBkeycode
;
1588 pointerEvent: function (sock
, x
, y
, mask
) {
1589 var buff
= sock
._sQ
;
1590 var offset
= sock
._sQlen
;
1592 buff
[offset
] = 5; // msg-type
1594 buff
[offset
+ 1] = mask
;
1596 buff
[offset
+ 2] = x
>> 8;
1597 buff
[offset
+ 3] = x
;
1599 buff
[offset
+ 4] = y
>> 8;
1600 buff
[offset
+ 5] = y
;
1606 // TODO(directxman12): make this unicode compatible?
1607 clientCutText: function (sock
, text
) {
1608 var buff
= sock
._sQ
;
1609 var offset
= sock
._sQlen
;
1611 buff
[offset
] = 6; // msg-type
1613 buff
[offset
+ 1] = 0; // padding
1614 buff
[offset
+ 2] = 0; // padding
1615 buff
[offset
+ 3] = 0; // padding
1617 var n
= text
.length
;
1619 buff
[offset
+ 4] = n
>> 24;
1620 buff
[offset
+ 5] = n
>> 16;
1621 buff
[offset
+ 6] = n
>> 8;
1622 buff
[offset
+ 7] = n
;
1624 for (var i
= 0; i
< n
; i
++) {
1625 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1628 sock
._sQlen
+= 8 + n
;
1632 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1633 var buff
= sock
._sQ
;
1634 var offset
= sock
._sQlen
;
1636 buff
[offset
] = 251; // msg-type
1637 buff
[offset
+ 1] = 0; // padding
1638 buff
[offset
+ 2] = width
>> 8; // width
1639 buff
[offset
+ 3] = width
;
1640 buff
[offset
+ 4] = height
>> 8; // height
1641 buff
[offset
+ 5] = height
;
1643 buff
[offset
+ 6] = 1; // number-of-screens
1644 buff
[offset
+ 7] = 0; // padding
1647 buff
[offset
+ 8] = id
>> 24; // id
1648 buff
[offset
+ 9] = id
>> 16;
1649 buff
[offset
+ 10] = id
>> 8;
1650 buff
[offset
+ 11] = id
;
1651 buff
[offset
+ 12] = 0; // x-position
1652 buff
[offset
+ 13] = 0;
1653 buff
[offset
+ 14] = 0; // y-position
1654 buff
[offset
+ 15] = 0;
1655 buff
[offset
+ 16] = width
>> 8; // width
1656 buff
[offset
+ 17] = width
;
1657 buff
[offset
+ 18] = height
>> 8; // height
1658 buff
[offset
+ 19] = height
;
1659 buff
[offset
+ 20] = flags
>> 24; // flags
1660 buff
[offset
+ 21] = flags
>> 16;
1661 buff
[offset
+ 22] = flags
>> 8;
1662 buff
[offset
+ 23] = flags
;
1668 clientFence: function (sock
, flags
, payload
) {
1669 var buff
= sock
._sQ
;
1670 var offset
= sock
._sQlen
;
1672 buff
[offset
] = 248; // msg-type
1674 buff
[offset
+ 1] = 0; // padding
1675 buff
[offset
+ 2] = 0; // padding
1676 buff
[offset
+ 3] = 0; // padding
1678 buff
[offset
+ 4] = flags
>> 24; // flags
1679 buff
[offset
+ 5] = flags
>> 16;
1680 buff
[offset
+ 6] = flags
>> 8;
1681 buff
[offset
+ 7] = flags
;
1683 var n
= payload
.length
;
1685 buff
[offset
+ 8] = n
; // length
1687 for (var i
= 0; i
< n
; i
++) {
1688 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1691 sock
._sQlen
+= 9 + n
;
1695 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1696 var buff
= sock
._sQ
;
1697 var offset
= sock
._sQlen
;
1699 buff
[offset
] = 150; // msg-type
1700 buff
[offset
+ 1] = enable
; // enable-flag
1702 buff
[offset
+ 2] = x
>> 8; // x
1703 buff
[offset
+ 3] = x
;
1704 buff
[offset
+ 4] = y
>> 8; // y
1705 buff
[offset
+ 5] = y
;
1706 buff
[offset
+ 6] = width
>> 8; // width
1707 buff
[offset
+ 7] = width
;
1708 buff
[offset
+ 8] = height
>> 8; // height
1709 buff
[offset
+ 9] = height
;
1715 pixelFormat: function (sock
, depth
, true_color
) {
1716 var buff
= sock
._sQ
;
1717 var offset
= sock
._sQlen
;
1723 } else if (depth
> 8) {
1729 bits
= Math
.floor(depth
/3);
1731 buff
[offset
] = 0; // msg-type
1733 buff
[offset
+ 1] = 0; // padding
1734 buff
[offset
+ 2] = 0; // padding
1735 buff
[offset
+ 3] = 0; // padding
1737 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1738 buff
[offset
+ 5] = depth
; // depth
1739 buff
[offset
+ 6] = 0; // little-endian
1740 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1742 buff
[offset
+ 8] = 0; // red-max
1743 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1745 buff
[offset
+ 10] = 0; // green-max
1746 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1748 buff
[offset
+ 12] = 0; // blue-max
1749 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1751 buff
[offset
+ 14] = bits
* 2; // red-shift
1752 buff
[offset
+ 15] = bits
* 1; // green-shift
1753 buff
[offset
+ 16] = bits
* 0; // blue-shift
1755 buff
[offset
+ 17] = 0; // padding
1756 buff
[offset
+ 18] = 0; // padding
1757 buff
[offset
+ 19] = 0; // padding
1763 clientEncodings: function (sock
, encodings
) {
1764 var buff
= sock
._sQ
;
1765 var offset
= sock
._sQlen
;
1767 buff
[offset
] = 2; // msg-type
1768 buff
[offset
+ 1] = 0; // padding
1770 buff
[offset
+ 2] = encodings
.length
>> 8;
1771 buff
[offset
+ 3] = encodings
.length
;
1773 var i
, j
= offset
+ 4;
1774 for (i
= 0; i
< encodings
.length
; i
++) {
1775 var enc
= encodings
[i
];
1776 buff
[j
] = enc
>> 24;
1777 buff
[j
+ 1] = enc
>> 16;
1778 buff
[j
+ 2] = enc
>> 8;
1784 sock
._sQlen
+= j
- offset
;
1788 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1789 var buff
= sock
._sQ
;
1790 var offset
= sock
._sQlen
;
1792 if (typeof(x
) === "undefined") { x
= 0; }
1793 if (typeof(y
) === "undefined") { y
= 0; }
1795 buff
[offset
] = 3; // msg-type
1796 buff
[offset
+ 1] = incremental
? 1 : 0;
1798 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1799 buff
[offset
+ 3] = x
& 0xFF;
1801 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1802 buff
[offset
+ 5] = y
& 0xFF;
1804 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1805 buff
[offset
+ 7] = w
& 0xFF;
1807 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1808 buff
[offset
+ 9] = h
& 0xFF;
1814 xvpOp: function (sock
, ver
, op
) {
1815 var buff
= sock
._sQ
;
1816 var offset
= sock
._sQlen
;
1818 buff
[offset
] = 250; // msg-type
1819 buff
[offset
+ 1] = 0; // padding
1821 buff
[offset
+ 2] = ver
;
1822 buff
[offset
+ 3] = op
;
1829 RFB
.genDES = function (password
, challenge
) {
1831 for (var i
= 0; i
< password
.length
; i
++) {
1832 passwd
.push(password
.charCodeAt(i
));
1834 return (new DES(passwd
)).encrypt(challenge
);
1837 RFB
.encodingHandlers
= {
1839 if (this._FBU
.lines
=== 0) {
1840 this._FBU
.lines
= this._FBU
.height
;
1843 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1844 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1845 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1846 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1847 var curr_height
= Math
.min(this._FBU
.lines
,
1848 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1849 var data
= this._sock
.get_rQ();
1850 var index
= this._sock
.get_rQi();
1851 if (this._fb_depth
== 8) {
1852 var pixels
= this._FBU
.width
* curr_height
1853 var newdata
= new Uint8Array(pixels
* 4);
1855 for (i
= 0;i
< pixels
;i
++) {
1856 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1857 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1858 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1859 newdata
[i
* 4 + 4] = 0;
1864 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1865 curr_height
, data
, index
);
1866 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1867 this._FBU
.lines
-= curr_height
;
1869 if (this._FBU
.lines
> 0) {
1870 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1873 this._FBU
.bytes
= 0;
1879 COPYRECT: function () {
1880 this._FBU
.bytes
= 4;
1881 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1882 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1883 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1887 this._FBU
.bytes
= 0;
1893 if (this._FBU
.subrects
=== 0) {
1894 this._FBU
.bytes
= 4 + 4;
1895 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1896 this._FBU
.subrects
= this._sock
.rQshift32();
1897 color
= this._sock
.rQshiftBytes(4); // Background
1898 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1901 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1902 color
= this._sock
.rQshiftBytes(4);
1903 var x
= this._sock
.rQshift16();
1904 var y
= this._sock
.rQshift16();
1905 var width
= this._sock
.rQshift16();
1906 var height
= this._sock
.rQshift16();
1907 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1908 this._FBU
.subrects
--;
1911 if (this._FBU
.subrects
> 0) {
1912 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1913 this._FBU
.bytes
= (4 + 8) * chunk
;
1916 this._FBU
.bytes
= 0;
1922 HEXTILE: function () {
1923 var rQ
= this._sock
.get_rQ();
1924 var rQi
= this._sock
.get_rQi();
1926 if (this._FBU
.tiles
=== 0) {
1927 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1928 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1929 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1930 this._FBU
.tiles
= this._FBU
.total_tiles
;
1933 while (this._FBU
.tiles
> 0) {
1934 this._FBU
.bytes
= 1;
1935 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1936 var subencoding
= rQ
[rQi
]; // Peek
1937 if (subencoding
> 30) { // Raw
1938 this._fail("Unexpected server message",
1939 "Illegal hextile subencoding: " + subencoding
);
1944 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1945 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1946 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1947 var x
= this._FBU
.x
+ tile_x
* 16;
1948 var y
= this._FBU
.y
+ tile_y
* 16;
1949 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1950 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1952 // Figure out how much we are expecting
1953 if (subencoding
& 0x01) { // Raw
1954 this._FBU
.bytes
+= w
* h
* 4;
1956 if (subencoding
& 0x02) { // Background
1957 this._FBU
.bytes
+= 4;
1959 if (subencoding
& 0x04) { // Foreground
1960 this._FBU
.bytes
+= 4;
1962 if (subencoding
& 0x08) { // AnySubrects
1963 this._FBU
.bytes
++; // Since we aren't shifting it off
1964 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1965 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1966 if (subencoding
& 0x10) { // SubrectsColoured
1967 this._FBU
.bytes
+= subrects
* (4 + 2);
1969 this._FBU
.bytes
+= subrects
* 2;
1974 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1976 // We know the encoding and have a whole tile
1977 this._FBU
.subencoding
= rQ
[rQi
];
1979 if (this._FBU
.subencoding
=== 0) {
1980 if (this._FBU
.lastsubencoding
& 0x01) {
1981 // Weird: ignore blanks are RAW
1982 Log
.Debug(" Ignoring blank after RAW");
1984 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1986 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1987 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1988 rQi
+= this._FBU
.bytes
- 1;
1990 if (this._FBU
.subencoding
& 0x02) { // Background
1991 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1994 if (this._FBU
.subencoding
& 0x04) { // Foreground
1995 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1999 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
2000 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
2004 for (var s
= 0; s
< subrects
; s
++) {
2006 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
2007 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2010 color
= this._FBU
.foreground
;
2015 var sy
= (xy
& 0x0f);
2019 var sw
= (wh
>> 4) + 1;
2020 var sh
= (wh
& 0x0f) + 1;
2022 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
2025 this._display
.finishTile();
2027 this._sock
.set_rQi(rQi
);
2028 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2029 this._FBU
.bytes
= 0;
2033 if (this._FBU
.tiles
=== 0) {
2040 TIGHT: function () {
2041 this._FBU
.bytes
= 1; // compression-control byte
2042 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2044 var checksum = function (data
) {
2046 for (var i
= 0; i
< data
.length
; i
++) {
2048 if (sum
> 65536) sum
-= 65536;
2053 var resetStreams
= 0;
2055 var decompress = function (data
, expected
) {
2056 for (var i
= 0; i
< 4; i
++) {
2057 if ((resetStreams
>> i
) & 1) {
2058 this._FBU
.zlibs
[i
].reset();
2059 Log
.Info("Reset zlib stream " + i
);
2063 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2064 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2065 /*if (uncompressed.status !== 0) {
2066 Log.Error("Invalid data in zlib stream");
2069 //return uncompressed.data;
2070 return uncompressed
;
2073 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2074 // Convert indexed (palette based) image data to RGB
2075 // TODO: reduce number of calculations inside loop
2076 var dest
= this._destBuff
;
2077 var w
= Math
.floor((width
+ 7) / 8);
2078 var w1
= Math
.floor(width
/ 8);
2080 /*for (var y = 0; y < height; y++) {
2082 var yoffset = y * width;
2083 var ybitoffset = y * w;
2084 var xoffset, targetbyte;
2085 for (x = 0; x < w1; x++) {
2086 xoffset = yoffset + x * 8;
2087 targetbyte = data[ybitoffset + x];
2088 for (b = 7; b >= 0; b--) {
2089 dp = (xoffset + 7 - b) * 3;
2090 sp = (targetbyte >> b & 1) * 3;
2091 dest[dp] = palette[sp];
2092 dest[dp + 1] = palette[sp + 1];
2093 dest[dp + 2] = palette[sp + 2];
2097 xoffset = yoffset + x * 8;
2098 targetbyte = data[ybitoffset + x];
2099 for (b = 7; b >= 8 - width % 8; b--) {
2100 dp = (xoffset + 7 - b) * 3;
2101 sp = (targetbyte >> b & 1) * 3;
2102 dest[dp] = palette[sp];
2103 dest[dp + 1] = palette[sp + 1];
2104 dest[dp + 2] = palette[sp + 2];
2108 for (var y
= 0; y
< height
; y
++) {
2110 for (x
= 0; x
< w1
; x
++) {
2111 for (b
= 7; b
>= 0; b
--) {
2112 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2113 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2114 dest
[dp
] = palette
[sp
];
2115 dest
[dp
+ 1] = palette
[sp
+ 1];
2116 dest
[dp
+ 2] = palette
[sp
+ 2];
2121 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2122 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2123 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2124 dest
[dp
] = palette
[sp
];
2125 dest
[dp
+ 1] = palette
[sp
+ 1];
2126 dest
[dp
+ 2] = palette
[sp
+ 2];
2134 var indexedToRGBX = function (data
, palette
, width
, height
) {
2135 // Convert indexed (palette based) image data to RGB
2136 var dest
= this._destBuff
;
2137 var total
= width
* height
* 4;
2138 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2139 var sp
= data
[j
] * 3;
2140 dest
[i
] = palette
[sp
];
2141 dest
[i
+ 1] = palette
[sp
+ 1];
2142 dest
[i
+ 2] = palette
[sp
+ 2];
2149 var rQi
= this._sock
.get_rQi();
2150 var rQ
= this._sock
.rQwhole();
2152 var cl_header
, cl_data
;
2154 var handlePalette = function () {
2155 var numColors
= rQ
[rQi
+ 2] + 1;
2156 var paletteSize
= numColors
* 3;
2157 this._FBU
.bytes
+= paletteSize
;
2158 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2160 var bpp
= (numColors
<= 2) ? 1 : 8;
2161 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2163 if (rowSize
* this._FBU
.height
< 12) {
2166 cl_data
= rowSize
* this._FBU
.height
;
2167 //clength = [0, rowSize * this._FBU.height];
2169 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2170 var cl_offset
= rQi
+ 3 + paletteSize
;
2173 cl_data
+= rQ
[cl_offset
] & 0x7f;
2174 if (rQ
[cl_offset
] & 0x80) {
2176 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2177 if (rQ
[cl_offset
+ 1] & 0x80) {
2179 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2182 // end inline getTightCLength
2185 this._FBU
.bytes
+= cl_header
+ cl_data
;
2186 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2188 // Shift ctl, filter id, num colors, palette entries, and clength off
2189 this._sock
.rQskipBytes(3);
2190 //var palette = this._sock.rQshiftBytes(paletteSize);
2191 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2192 this._sock
.rQskipBytes(cl_header
);
2195 data
= this._sock
.rQshiftBytes(cl_data
);
2197 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2200 // Convert indexed (palette based) image data to RGB
2202 if (numColors
== 2) {
2203 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2204 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2206 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2207 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2214 var handleCopy = function () {
2216 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2217 if (uncompressedSize
< 12) {
2220 cl_data
= uncompressedSize
;
2222 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2223 var cl_offset
= rQi
+ 1;
2226 cl_data
+= rQ
[cl_offset
] & 0x7f;
2227 if (rQ
[cl_offset
] & 0x80) {
2229 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2230 if (rQ
[cl_offset
+ 1] & 0x80) {
2232 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2235 // end inline getTightCLength
2237 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2238 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2240 // Shift ctl, clength off
2241 this._sock
.rQshiftBytes(1 + cl_header
);
2244 data
= this._sock
.rQshiftBytes(cl_data
);
2246 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2249 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2254 var ctl
= this._sock
.rQpeek8();
2256 // Keep tight reset bits
2257 resetStreams
= ctl
& 0xF;
2259 // Figure out filter
2261 streamId
= ctl
& 0x3;
2263 if (ctl
=== 0x08) cmode
= "fill";
2264 else if (ctl
=== 0x09) cmode
= "jpeg";
2265 else if (ctl
=== 0x0A) cmode
= "png";
2266 else if (ctl
& 0x04) cmode
= "filter";
2267 else if (ctl
< 0x04) cmode
= "copy";
2268 else return this._fail("Unexpected server message",
2269 "Illegal tight compression received, " +
2273 // fill use depth because TPIXELs drop the padding byte
2274 case "fill": // TPIXEL
2275 this._FBU
.bytes
+= 3;
2277 case "jpeg": // max clength
2278 this._FBU
.bytes
+= 3;
2280 case "png": // max clength
2281 this._FBU
.bytes
+= 3;
2283 case "filter": // filter id + num colors if palette
2284 this._FBU
.bytes
+= 2;
2290 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2292 // Determine FBU.bytes
2296 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);
2297 this._sock
.rQskipBytes(4);
2301 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2302 var cl_offset
= rQi
+ 1;
2305 cl_data
+= rQ
[cl_offset
] & 0x7f;
2306 if (rQ
[cl_offset
] & 0x80) {
2308 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2309 if (rQ
[cl_offset
+ 1] & 0x80) {
2311 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2314 // end inline getTightCLength
2315 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2316 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2318 // We have everything, render it
2319 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2320 data
= this._sock
.rQshiftBytes(cl_data
);
2321 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2324 var filterId
= rQ
[rQi
+ 1];
2325 if (filterId
=== 1) {
2326 if (!handlePalette()) { return false; }
2328 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2329 // Filter 2, Gradient is valid but not use if jpeg is enabled
2330 this._fail("Unexpected server message",
2331 "Unsupported tight subencoding received, " +
2332 "filter: " + filterId
);
2336 if (!handleCopy()) { return false; }
2341 this._FBU
.bytes
= 0;
2347 last_rect: function () {
2348 this._FBU
.rects
= 0;
2352 ExtendedDesktopSize: function () {
2353 this._FBU
.bytes
= 1;
2354 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2356 this._supportsSetDesktopSize
= true;
2357 this._setCapability("resize", true);
2359 var number_of_screens
= this._sock
.rQpeek8();
2361 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2362 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2364 this._sock
.rQskipBytes(1); // number-of-screens
2365 this._sock
.rQskipBytes(3); // padding
2367 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2368 // Save the id and flags of the first screen
2370 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2371 this._sock
.rQskipBytes(2); // x-position
2372 this._sock
.rQskipBytes(2); // y-position
2373 this._sock
.rQskipBytes(2); // width
2374 this._sock
.rQskipBytes(2); // height
2375 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2377 this._sock
.rQskipBytes(16);
2382 * The x-position indicates the reason for the change:
2384 * 0 - server resized on its own
2385 * 1 - this client requested the resize
2386 * 2 - another client requested the resize
2389 // We need to handle errors when we requested the resize.
2390 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2392 // The y-position indicates the status code from the server
2393 switch (this._FBU
.y
) {
2395 msg
= "Resize is administratively prohibited";
2398 msg
= "Out of resources";
2401 msg
= "Invalid screen layout";
2404 msg
= "Unknown reason";
2407 this._notification("Server did not accept the resize request: "
2410 this._resize(this._FBU
.width
, this._FBU
.height
);
2413 this._FBU
.bytes
= 0;
2414 this._FBU
.rects
-= 1;
2418 DesktopSize: function () {
2419 this._resize(this._FBU
.width
, this._FBU
.height
);
2420 this._FBU
.bytes
= 0;
2421 this._FBU
.rects
-= 1;
2425 Cursor: function () {
2426 Log
.Debug(">> set_cursor");
2427 var x
= this._FBU
.x
; // hotspot-x
2428 var y
= this._FBU
.y
; // hotspot-y
2429 var w
= this._FBU
.width
;
2430 var h
= this._FBU
.height
;
2432 var pixelslength
= w
* h
* 4;
2433 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2435 this._FBU
.bytes
= pixelslength
+ masklength
;
2436 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2438 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2439 this._sock
.rQshiftBytes(masklength
),
2442 this._FBU
.bytes
= 0;
2445 Log
.Debug("<< set_cursor");
2449 QEMUExtendedKeyEvent: function () {
2452 // Old Safari doesn't support creating keyboard events
2454 var keyboardEvent
= document
.createEvent("keyboardEvent");
2455 if (keyboardEvent
.code
!== undefined) {
2456 this._qemuExtKeyEventSupported
= true;