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 { browserSupportsCursorURIs
, isTouchDevice
} from './util/browsers.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 // How many seconds to wait for a disconnect to finish
32 var DISCONNECT_TIMEOUT
= 3;
34 export default function RFB(target
, url
, options
) {
36 throw Error("Must specify target");
39 throw Error("Must specify URL");
42 this._target
= target
;
46 options
= options
|| {}
47 this._rfb_credentials
= options
.credentials
|| {};
48 this._shared
= 'shared' in options
? !!options
.shared
: true;
49 this._repeaterID
= options
.repeaterID
|| '';
52 this._rfb_connection_state
= '';
53 this._rfb_init_state
= '';
54 this._rfb_auth_scheme
= '';
55 this._rfb_disconnect_reason
= "";
57 // Server capabilities
58 this._rfb_version
= 0;
59 this._rfb_max_version
= 3.8;
60 this._rfb_tightvnc
= false;
61 this._rfb_xvp_ver
= 0;
68 this._capabilities
= { power
: false, resize
: false };
70 this._supportsFence
= false;
72 this._supportsContinuousUpdates
= false;
73 this._enabledContinuousUpdates
= false;
75 this._supportsSetDesktopSize
= false;
77 this._screen_flags
= 0;
79 this._qemuExtKeyEventSupported
= false;
82 this._sock
= null; // Websock object
83 this._display
= null; // Display object
84 this._flushing
= false; // Display flushing state
85 this._keyboard
= null; // Keyboard input handler object
86 this._mouse
= null; // Mouse input handler object
89 this._disconnTimer
= null; // disconnection timer
91 // Decoder states and stats
92 this._encHandlers
= {};
97 subrects
: 0, // RRE and HEXTILE
108 zlibs
: [] // TIGHT zlib streams
110 for (var i
= 0; i
< 4; i
++) {
111 this._FBU
.zlibs
[i
] = new Inflator();
114 this._destBuff
= null;
115 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
117 this._rre_chunk_sz
= 100;
133 this._mouse_buttonMask
= 0;
134 this._mouse_arr
= [];
135 this._viewportDragging
= false;
136 this._viewportDragPos
= {};
137 this._viewportHasMoved
= false;
140 Log
.Debug(">> RFB.constructor");
142 // Target canvas must be able to have focus
143 if (!this._target
.hasAttribute('tabindex')) {
144 this._target
.tabIndex
= -1;
147 // populate encHandlers with bound versions
148 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this);
149 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this);
150 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this);
151 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this);
152 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this);
154 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this);
155 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this);
156 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this);
157 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this);
158 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this);
160 // NB: nothing that needs explicit teardown should be done
161 // before this point, since this can throw an exception
163 this._display
= new Display(this._target
);
165 Log
.Error("Display exception: " + exc
);
168 this._display
.onflush
= this._onFlush
.bind(this);
169 this._display
.clear();
171 this._keyboard
= new Keyboard(this._target
);
172 this._keyboard
.onkeyevent
= this._handleKeyEvent
.bind(this);
174 this._mouse
= new Mouse(this._target
);
175 this._mouse
.onmousebutton
= this._handleMouseButton
.bind(this);
176 this._mouse
.onmousemove
= this._handleMouseMove
.bind(this);
178 this._sock
= new Websock();
179 this._sock
.on('message', this._handle_message
.bind(this));
180 this._sock
.on('open', function () {
181 if ((this._rfb_connection_state
=== 'connecting') &&
182 (this._rfb_init_state
=== '')) {
183 this._rfb_init_state
= 'ProtocolVersion';
184 Log
.Debug("Starting VNC handshake");
186 this._fail("Unexpected server connection");
189 this._sock
.on('close', function (e
) {
190 Log
.Warn("WebSocket on-close event");
193 msg
= " (code: " + e
.code
;
195 msg
+= ", reason: " + e
.reason
;
199 switch (this._rfb_connection_state
) {
200 case 'disconnecting':
201 this._updateConnectionState('disconnected');
204 this._fail('Failed to connect to server', msg
);
207 // Handle disconnects that were initiated server-side
208 this._updateConnectionState('disconnecting');
209 this._updateConnectionState('disconnected');
212 this._fail("Unexpected server disconnect",
213 "Already disconnected: " + msg
);
216 this._fail("Unexpected server disconnect",
217 "Not in any state yet: " + msg
);
220 this._sock
.off('close');
222 this._sock
.on('error', function (e
) {
223 Log
.Warn("WebSocket on-error event");
226 // Slight delay of the actual connection so that the caller has
227 // time to set up callbacks
228 setTimeout(this._updateConnectionState
.bind(this, 'connecting'));
230 Log
.Debug("<< RFB.constructor");
234 // ===== PROPERTIES =====
239 get viewOnly() { return this._viewOnly
; },
240 set viewOnly(viewOnly
) {
241 this._viewOnly
= viewOnly
;
243 if (this._rfb_connection_state
=== "connecting" ||
244 this._rfb_connection_state
=== "connected") {
246 this._keyboard
.ungrab();
247 this._mouse
.ungrab();
249 this._keyboard
.grab();
255 get capabilities() { return this._capabilities
; },
257 get touchButton() { return this._mouse
.touchButton
; },
258 set touchButton(button
) { this._mouse
.touchButton
= button
; },
260 get viewportScale() { return this._display
.scale
; },
261 set viewportScale(scale
) { this._display
.scale
= scale
; },
263 get clipViewport() { return this._display
.clipViewport
; },
264 set clipViewport(viewport
) { this._display
.clipViewport
= viewport
; },
266 get isClipped() { return this._display
.isClipped
; },
268 // ===== EVENT HANDLERS =====
270 onupdatestate: function () {}, // onupdatestate(rfb, state, oldstate): connection state change
271 onnotification: function () {}, // onnotification(rfb, msg, level, options): notification for the UI
272 ondisconnected: function () {}, // ondisconnected(rfb, reason): disconnection finished
273 oncredentialsrequired: function () {}, // oncredentialsrequired(rfb, types): VNC credentials are required
274 onclipboard: function () {}, // onclipboard(rfb, text): RFB clipboard contents received
275 onbell: function () {}, // onbell(rfb): RFB Bell message received
276 onfbresize: function () {}, // onfbresize(rfb, width, height): frame buffer resized
277 ondesktopname: function () {}, // ondesktopname(rfb, name): desktop name received
278 oncapabilities: function () {}, // oncapabilities(rfb, caps): the supported capabilities has changed
280 // ===== PUBLIC METHODS =====
282 disconnect: function () {
283 this._updateConnectionState('disconnecting');
284 this._sock
.off('error');
285 this._sock
.off('message');
286 this._sock
.off('open');
289 sendCredentials: function (creds
) {
290 this._rfb_credentials
= creds
;
291 setTimeout(this._init_msg
.bind(this), 0);
294 sendCtrlAltDel: function () {
295 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
296 Log
.Info("Sending Ctrl-Alt-Del");
298 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
299 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
300 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
301 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
302 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
303 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
306 machineShutdown: function () {
310 machineReboot: function () {
314 machineReset: function () {
318 // Send a key press. If 'down' is not specified then send a down key
319 // followed by an up key.
320 sendKey: function (keysym
, code
, down
) {
321 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
323 if (down
=== undefined) {
324 this.sendKey(keysym
, code
, true);
325 this.sendKey(keysym
, code
, false);
329 var scancode
= XtScancode
[code
];
331 if (this._qemuExtKeyEventSupported
&& scancode
) {
333 keysym
= keysym
|| 0;
335 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
337 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
342 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
343 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
347 clipboardPasteFrom: function (text
) {
348 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
349 RFB
.messages
.clientCutText(this._sock
, text
);
352 autoscale: function (width
, height
) {
353 if (this._rfb_connection_state
!== 'connected') { return; }
354 this._display
.autoscale(width
, height
);
357 viewportChangeSize: function(width
, height
) {
358 if (this._rfb_connection_state
!== 'connected') { return; }
359 this._display
.viewportChangeSize(width
, height
);
362 // Requests a change of remote desktop size. This message is an extension
363 // and may only be sent if we have received an ExtendedDesktopSize message
364 requestDesktopSize: function (width
, height
) {
365 if (this._rfb_connection_state
!== 'connected' ||
370 if (!this._supportsSetDesktopSize
) {
374 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
375 this._screen_id
, this._screen_flags
);
379 // ===== PRIVATE METHODS =====
381 _connect: function () {
382 Log
.Debug(">> RFB.connect");
384 Log
.Info("connecting to " + this._url
);
387 // WebSocket.onopen transitions to the RFB init states
388 this._sock
.open(this._url
, ['binary']);
390 if (e
.name
=== 'SyntaxError') {
391 this._fail("Invalid host or port value given", e
);
393 this._fail("Error while connecting", e
);
397 // Always grab focus on some kind of click event
398 this._target
.addEventListener("mousedown", this._focusCanvas
);
399 this._target
.addEventListener("touchstart", this._focusCanvas
);
401 Log
.Debug("<< RFB.connect");
404 _disconnect: function () {
405 Log
.Debug(">> RFB.disconnect");
406 this._target
.removeEventListener("mousedown", this._focusCanvas
);
407 this._target
.removeEventListener("touchstart", this._focusCanvas
);
411 Log
.Debug("<< RFB.disconnect");
414 _print_stats: function () {
415 var stats
= this._encStats
;
417 Log
.Info("Encoding stats for this connection:");
418 Object
.keys(stats
).forEach(function (key
) {
420 if (s
[0] + s
[1] > 0) {
421 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
425 Log
.Info("Encoding stats since page load:");
426 Object
.keys(stats
).forEach(function (key
) {
428 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
432 _cleanup: function () {
433 if (!this._viewOnly
) { this._keyboard
.ungrab(); }
434 if (!this._viewOnly
) { this._mouse
.ungrab(); }
435 this._display
.defaultCursor();
436 if (Log
.get_logging() !== 'debug') {
437 // Show noVNC logo when disconnected, unless in
439 this._display
.clear();
443 // Event handler for canvas so this points to the canvas element
444 _focusCanvas: function(event
) {
445 // Respect earlier handlers' request to not do side-effects
446 if (!event
.defaultPrevented
)
455 * disconnected - permanent state
457 _updateConnectionState: function (state
) {
458 var oldstate
= this._rfb_connection_state
;
460 if (state
=== oldstate
) {
461 Log
.Debug("Already in state '" + state
+ "', ignoring");
465 // The 'disconnected' state is permanent for each RFB object
466 if (oldstate
=== 'disconnected') {
467 Log
.Error("Tried changing state of a disconnected RFB object");
471 // Ensure proper transitions before doing anything
474 if (oldstate
!== 'connecting') {
475 Log
.Error("Bad transition to connected state, " +
476 "previous connection state: " + oldstate
);
482 if (oldstate
!== 'disconnecting') {
483 Log
.Error("Bad transition to disconnected state, " +
484 "previous connection state: " + oldstate
);
490 if (oldstate
!== '') {
491 Log
.Error("Bad transition to connecting state, " +
492 "previous connection state: " + oldstate
);
497 case 'disconnecting':
498 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
499 Log
.Error("Bad transition to disconnecting state, " +
500 "previous connection state: " + oldstate
);
506 Log
.Error("Unknown connection state: " + state
);
510 // State change actions
512 this._rfb_connection_state
= state
;
513 this.onupdatestate(this, state
, oldstate
);
515 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
518 if (this._disconnTimer
&& state
!== 'disconnecting') {
519 Log
.Debug("Clearing disconnect timer");
520 clearTimeout(this._disconnTimer
);
521 this._disconnTimer
= null;
523 // make sure we don't get a double event
524 this._sock
.off('close');
529 // Call ondisconnected callback after onupdatestate since
530 // we don't know if the UI only displays the latest message
531 if (this._rfb_disconnect_reason
!== "") {
532 this.ondisconnected(this, this._rfb_disconnect_reason
);
534 // No reason means clean disconnect
535 this.ondisconnected(this);
543 case 'disconnecting':
546 this._disconnTimer
= setTimeout(function () {
547 this._rfb_disconnect_reason
= _("Disconnect timeout");
548 this._updateConnectionState('disconnected');
549 }.bind(this), DISCONNECT_TIMEOUT
* 1000);
554 /* Print errors and disconnect
556 * The optional parameter 'details' is used for information that
557 * should be logged but not sent to the user interface.
559 _fail: function (msg
, details
) {
561 if (typeof details
!== 'undefined') {
562 fullmsg
= msg
+ " (" + details
+ ")";
564 switch (this._rfb_connection_state
) {
565 case 'disconnecting':
566 Log
.Error("Failed when disconnecting: " + fullmsg
);
569 Log
.Error("Failed while connected: " + fullmsg
);
572 Log
.Error("Failed when connecting: " + fullmsg
);
575 Log
.Error("RFB failure: " + fullmsg
);
578 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
580 // Transition to disconnected without waiting for socket to close
581 this._updateConnectionState('disconnecting');
582 this._updateConnectionState('disconnected');
588 * Send a notification to the UI. Valid levels are:
589 * 'normal'|'warn'|'error'
591 * NOTE: If this function is called multiple times, remember that the
592 * interface could be only showing the latest notification.
594 _notification: function(msg
, level
) {
599 Log
.Debug("Notification[" + level
+ "]:" + msg
);
602 Log
.Error("Invalid notification level: " + level
);
606 this.onnotification(this, msg
, level
);
609 _setCapability: function (cap
, val
) {
610 this._capabilities
[cap
] = val
;
611 this.oncapabilities(this, this._capabilities
);
614 _handle_message: function () {
615 if (this._sock
.rQlen() === 0) {
616 Log
.Warn("handle_message called on an empty receive queue");
620 switch (this._rfb_connection_state
) {
622 Log
.Error("Got data while disconnected");
626 if (this._flushing
) {
629 if (!this._normal_msg()) {
632 if (this._sock
.rQlen() === 0) {
643 _handleKeyEvent: function (keysym
, code
, down
) {
644 this.sendKey(keysym
, code
, down
);
647 _handleMouseButton: function (x
, y
, down
, bmask
) {
649 this._mouse_buttonMask
|= bmask
;
651 this._mouse_buttonMask
&= ~bmask
;
654 if (this.dragViewport
) {
655 if (down
&& !this._viewportDragging
) {
656 this._viewportDragging
= true;
657 this._viewportDragPos
= {'x': x
, 'y': y
};
659 // Skip sending mouse events
662 this._viewportDragging
= false;
664 // If the viewport didn't actually move, then treat as a mouse click event
665 // Send the button down event here, as the button up event is sent at the end of this function
666 if (!this._viewportHasMoved
&& !this._viewOnly
) {
667 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
669 this._viewportHasMoved
= false;
673 if (this._viewOnly
) { return; } // View only, skip mouse events
675 if (this._rfb_connection_state
!== 'connected') { return; }
676 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
679 _handleMouseMove: function (x
, y
) {
680 if (this._viewportDragging
) {
681 var deltaX
= this._viewportDragPos
.x
- x
;
682 var deltaY
= this._viewportDragPos
.y
- y
;
684 // The goal is to trigger on a certain physical width, the
685 // devicePixelRatio brings us a bit closer but is not optimal.
686 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
688 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
689 Math
.abs(deltaY
) > dragThreshold
)) {
690 this._viewportHasMoved
= true;
692 this._viewportDragPos
= {'x': x
, 'y': y
};
693 this._display
.viewportChangePos(deltaX
, deltaY
);
696 // Skip sending mouse events
700 if (this._viewOnly
) { return; } // View only, skip mouse events
702 if (this._rfb_connection_state
!== 'connected') { return; }
703 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
708 _negotiate_protocol_version: function () {
709 if (this._sock
.rQlen() < 12) {
710 return this._fail("Error while negotiating with server",
711 "Incomplete protocol version");
714 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
715 Log
.Info("Server ProtocolVersion: " + sversion
);
718 case "000.000": // UltraVNC repeater
722 case "003.006": // UltraVNC
723 case "003.889": // Apple Remote Desktop
724 this._rfb_version
= 3.3;
727 this._rfb_version
= 3.7;
730 case "004.000": // Intel AMT KVM
731 case "004.001": // RealVNC 4.6
732 case "005.000": // RealVNC 5.3
733 this._rfb_version
= 3.8;
736 return this._fail("Unsupported server",
737 "Invalid server version: " + sversion
);
741 var repeaterID
= "ID:" + this._repeaterID
;
742 while (repeaterID
.length
< 250) {
745 this._sock
.send_string(repeaterID
);
749 if (this._rfb_version
> this._rfb_max_version
) {
750 this._rfb_version
= this._rfb_max_version
;
753 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
754 ".00" + ((this._rfb_version
* 10) % 10);
755 this._sock
.send_string("RFB " + cversion
+ "\n");
756 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
758 this._rfb_init_state
= 'Security';
761 _negotiate_security: function () {
762 // Polyfill since IE and PhantomJS doesn't have
763 // TypedArray.includes()
764 function includes(item
, array
) {
765 for (var i
= 0; i
< array
.length
; i
++) {
766 if (array
[i
] === item
) {
773 if (this._rfb_version
>= 3.7) {
774 // Server sends supported list, client decides
775 var num_types
= this._sock
.rQshift8();
776 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
778 if (num_types
=== 0) {
779 var strlen
= this._sock
.rQshift32();
780 var reason
= this._sock
.rQshiftStr(strlen
);
781 return this._fail("Error while negotiating with server",
782 "Security failure: " + reason
);
785 var types
= this._sock
.rQshiftBytes(num_types
);
786 Log
.Debug("Server security types: " + types
);
788 // Look for each auth in preferred order
789 this._rfb_auth_scheme
= 0;
790 if (includes(1, types
)) {
791 this._rfb_auth_scheme
= 1; // None
792 } else if (includes(22, types
)) {
793 this._rfb_auth_scheme
= 22; // XVP
794 } else if (includes(16, types
)) {
795 this._rfb_auth_scheme
= 16; // Tight
796 } else if (includes(2, types
)) {
797 this._rfb_auth_scheme
= 2; // VNC Auth
799 return this._fail("Unsupported server",
800 "Unsupported security types: " + types
);
803 this._sock
.send([this._rfb_auth_scheme
]);
806 if (this._sock
.rQwait("security scheme", 4)) { return false; }
807 this._rfb_auth_scheme
= this._sock
.rQshift32();
810 this._rfb_init_state
= 'Authentication';
811 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
813 return this._init_msg(); // jump to authentication
817 _negotiate_xvp_auth: function () {
818 if (!this._rfb_credentials
.username
||
819 !this._rfb_credentials
.password
||
820 !this._rfb_credentials
.target
) {
821 this.oncredentialsrequired(this, ["username", "password", "target"]);
825 var xvp_auth_str
= String
.fromCharCode(this._rfb_credentials
.username
.length
) +
826 String
.fromCharCode(this._rfb_credentials
.target
.length
) +
827 this._rfb_credentials
.username
+
828 this._rfb_credentials
.target
;
829 this._sock
.send_string(xvp_auth_str
);
830 this._rfb_auth_scheme
= 2;
831 return this._negotiate_authentication();
834 _negotiate_std_vnc_auth: function () {
835 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
837 if (!this._rfb_credentials
.password
) {
838 this.oncredentialsrequired(this, ["password"]);
842 // TODO(directxman12): make genDES not require an Array
843 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
844 var response
= RFB
.genDES(this._rfb_credentials
.password
, challenge
);
845 this._sock
.send(response
);
846 this._rfb_init_state
= "SecurityResult";
850 _negotiate_tight_tunnels: function (numTunnels
) {
851 var clientSupportedTunnelTypes
= {
852 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
854 var serverSupportedTunnelTypes
= {};
855 // receive tunnel capabilities
856 for (var i
= 0; i
< numTunnels
; i
++) {
857 var cap_code
= this._sock
.rQshift32();
858 var cap_vendor
= this._sock
.rQshiftStr(4);
859 var cap_signature
= this._sock
.rQshiftStr(8);
860 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
863 // choose the notunnel type
864 if (serverSupportedTunnelTypes
[0]) {
865 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
866 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
867 return this._fail("Unsupported server",
868 "Client's tunnel type had the incorrect " +
869 "vendor or signature");
871 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
872 return false; // wait until we receive the sub auth count to continue
874 return this._fail("Unsupported server",
875 "Server wanted tunnels, but doesn't support " +
876 "the notunnel type");
880 _negotiate_tight_auth: function () {
881 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
882 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
883 var numTunnels
= this._sock
.rQshift32();
884 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
886 this._rfb_tightvnc
= true;
888 if (numTunnels
> 0) {
889 this._negotiate_tight_tunnels(numTunnels
);
890 return false; // wait until we receive the sub auth to continue
894 // second pass, do the sub-auth negotiation
895 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
896 var subAuthCount
= this._sock
.rQshift32();
897 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
898 this._rfb_init_state
= 'SecurityResult';
902 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
904 var clientSupportedTypes
= {
909 var serverSupportedTypes
= [];
911 for (var i
= 0; i
< subAuthCount
; i
++) {
912 var capNum
= this._sock
.rQshift32();
913 var capabilities
= this._sock
.rQshiftStr(12);
914 serverSupportedTypes
.push(capabilities
);
917 for (var authType
in clientSupportedTypes
) {
918 if (serverSupportedTypes
.indexOf(authType
) != -1) {
919 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
922 case 'STDVNOAUTH__': // no auth
923 this._rfb_init_state
= 'SecurityResult';
925 case 'STDVVNCAUTH_': // VNC auth
926 this._rfb_auth_scheme
= 2;
927 return this._init_msg();
929 return this._fail("Unsupported server",
930 "Unsupported tiny auth scheme: " +
936 return this._fail("Unsupported server",
937 "No supported sub-auth types!");
940 _negotiate_authentication: function () {
941 switch (this._rfb_auth_scheme
) {
942 case 0: // connection failed
943 if (this._sock
.rQwait("auth reason", 4)) { return false; }
944 var strlen
= this._sock
.rQshift32();
945 var reason
= this._sock
.rQshiftStr(strlen
);
946 return this._fail("Authentication failure", reason
);
949 if (this._rfb_version
>= 3.8) {
950 this._rfb_init_state
= 'SecurityResult';
953 this._rfb_init_state
= 'ClientInitialisation';
954 return this._init_msg();
957 return this._negotiate_xvp_auth();
959 case 2: // VNC authentication
960 return this._negotiate_std_vnc_auth();
962 case 16: // TightVNC Security Type
963 return this._negotiate_tight_auth();
966 return this._fail("Unsupported server",
967 "Unsupported auth scheme: " +
968 this._rfb_auth_scheme
);
972 _handle_security_result: function () {
973 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
974 switch (this._sock
.rQshift32()) {
976 this._rfb_init_state
= 'ClientInitialisation';
977 Log
.Debug('Authentication OK');
978 return this._init_msg();
980 if (this._rfb_version
>= 3.8) {
981 var length
= this._sock
.rQshift32();
982 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
983 var reason
= this._sock
.rQshiftStr(length
);
984 return this._fail("Authentication failure", reason
);
986 return this._fail("Authentication failure");
989 return this._fail("Too many authentication attempts");
991 return this._fail("Unsupported server",
992 "Unknown SecurityResult");
996 _negotiate_server_init: function () {
997 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1000 var width
= this._sock
.rQshift16();
1001 var height
= this._sock
.rQshift16();
1004 var bpp
= this._sock
.rQshift8();
1005 var depth
= this._sock
.rQshift8();
1006 var big_endian
= this._sock
.rQshift8();
1007 var true_color
= this._sock
.rQshift8();
1009 var red_max
= this._sock
.rQshift16();
1010 var green_max
= this._sock
.rQshift16();
1011 var blue_max
= this._sock
.rQshift16();
1012 var red_shift
= this._sock
.rQshift8();
1013 var green_shift
= this._sock
.rQshift8();
1014 var blue_shift
= this._sock
.rQshift8();
1015 this._sock
.rQskipBytes(3); // padding
1017 // NB(directxman12): we don't want to call any callbacks or print messages until
1018 // *after* we're past the point where we could backtrack
1020 /* Connection name/title */
1021 var name_length = this._sock.rQshift32();
1022 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1023 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1025 if (this._rfb_tightvnc) {
1026 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1027 // In TightVNC mode, ServerInit message is extended
1028 var numServerMessages = this._sock.rQshift16();
1029 var numClientMessages = this._sock.rQshift16();
1030 var numEncodings = this._sock.rQshift16();
1031 this._sock.rQskipBytes(2); // padding
1033 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1034 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1036 // we don't actually do anything with the capability information that TIGHT sends,
1037 // so we just skip the all of this.
1039 // TIGHT server message capabilities
1040 this._sock.rQskipBytes(16 * numServerMessages);
1042 // TIGHT client message capabilities
1043 this._sock.rQskipBytes(16 * numClientMessages);
1045 // TIGHT encoding capabilities
1046 this._sock.rQskipBytes(16 * numEncodings);
1049 // NB(directxman12): these are down here so that we don't run them multiple times
1051 Log.Info("Screen: " + width + "x" + height +
1052 ", bpp: " + bpp + ", depth: " + depth +
1053 ", big_endian: " + big_endian +
1054 ", true_color: " + true_color +
1055 ", red_max: " + red_max +
1056 ", green_max: " + green_max +
1057 ", blue_max: " + blue_max +
1058 ", red_shift: " + red_shift +
1059 ", green_shift: " + green_shift +
1060 ", blue_shift: " + blue_shift);
1062 if (big_endian !== 0) {
1063 Log.Warn("Server native endian is not little endian");
1066 if (red_shift !== 16) {
1067 Log.Warn("Server native red-shift is not 16");
1070 if (blue_shift !== 0) {
1071 Log.Warn("Server native blue-shift is not 0");
1074 // we're past the point where we could backtrack, so it's safe to call this
1075 this.ondesktopname(this, this._fb_name);
1077 this._resize(width, height);
1079 if (!this._viewOnly) { this._keyboard.grab(); }
1080 if (!this._viewOnly) { this._mouse.grab(); }
1082 this._fb_depth = 24;
1084 if (this._fb_name === "Intel(r) AMT KVM") {
1085 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1089 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1090 this._sendEncodings();
1091 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1093 this._timing.fbu_rt_start = (new Date()).getTime();
1094 this._timing.pixels = 0;
1096 // Cursor will be server side until the server decides to honor
1097 // our request and send over the cursor image
1098 this._display.disableLocalCursor();
1100 this._updateConnectionState('connected');
1104 _sendEncodings: function () {
1107 // In preference order
1108 encs.push(encodings.encodingCopyRect);
1109 // Only supported with full depth support
1110 if (this._fb_depth == 24) {
1111 encs.push(encodings.encodingTight);
1112 encs.push(encodings.encodingHextile);
1113 encs.push(encodings.encodingRRE);
1115 encs.push(encodings.encodingRaw);
1117 // Psuedo-encoding settings
1118 encs.push(encodings.pseudoEncodingTightPNG);
1119 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1120 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1122 encs.push(encodings.pseudoEncodingDesktopSize);
1123 encs.push(encodings.pseudoEncodingLastRect);
1124 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1125 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1126 encs.push(encodings.pseudoEncodingXvp);
1127 encs.push(encodings.pseudoEncodingFence);
1128 encs.push(encodings.pseudoEncodingContinuousUpdates);
1130 if (browserSupportsCursorURIs() &&
1131 !isTouchDevice && this._fb_depth == 24) {
1132 encs.push(encodings.pseudoEncodingCursor);
1135 RFB.messages.clientEncodings(this._sock, encs);
1138 /* RFB protocol initialization states:
1143 * ClientInitialization - not triggered by server message
1144 * ServerInitialization
1146 _init_msg: function () {
1147 switch (this._rfb_init_state
) {
1148 case 'ProtocolVersion':
1149 return this._negotiate_protocol_version();
1152 return this._negotiate_security();
1154 case 'Authentication':
1155 return this._negotiate_authentication();
1157 case 'SecurityResult':
1158 return this._handle_security_result();
1160 case 'ClientInitialisation':
1161 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1162 this._rfb_init_state
= 'ServerInitialisation';
1165 case 'ServerInitialisation':
1166 return this._negotiate_server_init();
1169 return this._fail("Internal error", "Unknown init state: " +
1170 this._rfb_init_state
);
1174 _handle_set_colour_map_msg: function () {
1175 Log
.Debug("SetColorMapEntries");
1177 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1180 _handle_server_cut_text: function () {
1181 Log
.Debug("ServerCutText");
1183 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1184 this._sock
.rQskipBytes(3); // Padding
1185 var length
= this._sock
.rQshift32();
1186 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1188 var text
= this._sock
.rQshiftStr(length
);
1190 if (this._viewOnly
) { return true; }
1192 this.onclipboard(this, text
);
1197 _handle_server_fence_msg: function() {
1198 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1199 this._sock
.rQskipBytes(3); // Padding
1200 var flags
= this._sock
.rQshift32();
1201 var length
= this._sock
.rQshift8();
1203 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1206 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1210 var payload
= this._sock
.rQshiftStr(length
);
1212 this._supportsFence
= true;
1217 * (1<<0) - BlockBefore
1218 * (1<<1) - BlockAfter
1223 if (!(flags
& (1<<31))) {
1224 return this._fail("Internal error",
1225 "Unexpected fence response");
1228 // Filter out unsupported flags
1229 // FIXME: support syncNext
1230 flags
&= (1<<0) | (1<<1);
1232 // BlockBefore and BlockAfter are automatically handled by
1233 // the fact that we process each incoming message
1235 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1240 _handle_xvp_msg: function () {
1241 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1242 this._sock
.rQskip8(); // Padding
1243 var xvp_ver
= this._sock
.rQshift8();
1244 var xvp_msg
= this._sock
.rQshift8();
1248 Log
.Error("Operation Failed");
1249 this._notification("XVP Operation Failed", 'error');
1252 this._rfb_xvp_ver
= xvp_ver
;
1253 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1254 this._setCapability("power", true);
1257 this._fail("Unexpected server message",
1258 "Illegal server XVP message " + xvp_msg
);
1265 _normal_msg: function () {
1268 if (this._FBU
.rects
> 0) {
1271 msg_type
= this._sock
.rQshift8();
1275 case 0: // FramebufferUpdate
1276 var ret
= this._framebufferUpdate();
1277 if (ret
&& !this._enabledContinuousUpdates
) {
1278 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1279 this._fb_width
, this._fb_height
);
1283 case 1: // SetColorMapEntries
1284 return this._handle_set_colour_map_msg();
1291 case 3: // ServerCutText
1292 return this._handle_server_cut_text();
1294 case 150: // EndOfContinuousUpdates
1295 var first
= !(this._supportsContinuousUpdates
);
1296 this._supportsContinuousUpdates
= true;
1297 this._enabledContinuousUpdates
= false;
1299 this._enabledContinuousUpdates
= true;
1300 this._updateContinuousUpdates();
1301 Log
.Info("Enabling continuous updates.");
1303 // FIXME: We need to send a framebufferupdaterequest here
1304 // if we add support for turning off continuous updates
1308 case 248: // ServerFence
1309 return this._handle_server_fence_msg();
1312 return this._handle_xvp_msg();
1315 this._fail("Unexpected server message", "Type:" + msg_type
);
1316 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1321 _onFlush: function() {
1322 this._flushing
= false;
1323 // Resume processing
1324 if (this._sock
.rQlen() > 0) {
1325 this._handle_message();
1329 _framebufferUpdate: function () {
1333 if (this._FBU
.rects
=== 0) {
1334 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1335 this._sock
.rQskip8(); // Padding
1336 this._FBU
.rects
= this._sock
.rQshift16();
1337 this._FBU
.bytes
= 0;
1338 this._timing
.cur_fbu
= 0;
1339 if (this._timing
.fbu_rt_start
> 0) {
1340 now
= (new Date()).getTime();
1341 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1344 // Make sure the previous frame is fully rendered first
1345 // to avoid building up an excessive queue
1346 if (this._display
.pending()) {
1347 this._flushing
= true;
1348 this._display
.flush();
1353 while (this._FBU
.rects
> 0) {
1354 if (this._rfb_connection_state
!== 'connected') { return false; }
1356 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1357 if (this._FBU
.bytes
=== 0) {
1358 if (this._sock
.rQwait("rect header", 12)) { return false; }
1359 /* New FramebufferUpdate */
1361 var hdr
= this._sock
.rQshiftBytes(12);
1362 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1363 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1364 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1365 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1366 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1367 (hdr
[10] << 8) + hdr
[11], 10);
1369 if (!this._encHandlers
[this._FBU
.encoding
]) {
1370 this._fail("Unexpected server message",
1371 "Unsupported encoding " +
1372 this._FBU
.encoding
);
1377 this._timing
.last_fbu
= (new Date()).getTime();
1379 ret
= this._encHandlers
[this._FBU
.encoding
]();
1381 now
= (new Date()).getTime();
1382 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1385 if (!(this._FBU
.encoding
in this._encStats
)) {
1386 this._encStats
[this._FBU
.encoding
] = [0, 0];
1388 this._encStats
[this._FBU
.encoding
][0]++;
1389 this._encStats
[this._FBU
.encoding
][1]++;
1390 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1393 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1394 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1395 this._timing
.fbu_rt_start
> 0) {
1396 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1397 this._timing
.full_fbu_cnt
++;
1398 Log
.Info("Timing of full FBU, curr: " +
1399 this._timing
.cur_fbu
+ ", total: " +
1400 this._timing
.full_fbu_total
+ ", cnt: " +
1401 this._timing
.full_fbu_cnt
+ ", avg: " +
1402 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1405 if (this._timing
.fbu_rt_start
> 0) {
1406 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1407 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1408 this._timing
.fbu_rt_cnt
++;
1409 Log
.Info("full FBU round-trip, cur: " +
1410 fbu_rt_diff
+ ", total: " +
1411 this._timing
.fbu_rt_total
+ ", cnt: " +
1412 this._timing
.fbu_rt_cnt
+ ", avg: " +
1413 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1414 this._timing
.fbu_rt_start
= 0;
1418 if (!ret
) { return ret
; } // need more data
1421 this._display
.flip();
1423 return true; // We finished this FBU
1426 _updateContinuousUpdates: function() {
1427 if (!this._enabledContinuousUpdates
) { return; }
1429 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1430 this._fb_width
, this._fb_height
);
1433 _resize: function(width
, height
) {
1434 this._fb_width
= width
;
1435 this._fb_height
= height
;
1437 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1439 this._display
.resize(this._fb_width
, this._fb_height
);
1440 this.onfbresize(this, this._fb_width
, this._fb_height
);
1442 this._timing
.fbu_rt_start
= (new Date()).getTime();
1443 this._updateContinuousUpdates();
1446 _xvpOp: function (ver
, op
) {
1447 if (this._rfb_xvp_ver
< ver
) { return; }
1448 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
1449 RFB
.messages
.xvpOp(this._sock
, ver
, op
);
1455 keyEvent: function (sock
, keysym
, down
) {
1456 var buff
= sock
._sQ
;
1457 var offset
= sock
._sQlen
;
1459 buff
[offset
] = 4; // msg-type
1460 buff
[offset
+ 1] = down
;
1462 buff
[offset
+ 2] = 0;
1463 buff
[offset
+ 3] = 0;
1465 buff
[offset
+ 4] = (keysym
>> 24);
1466 buff
[offset
+ 5] = (keysym
>> 16);
1467 buff
[offset
+ 6] = (keysym
>> 8);
1468 buff
[offset
+ 7] = keysym
;
1474 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1475 function getRFBkeycode(xt_scancode
) {
1476 var upperByte
= (keycode
>> 8);
1477 var lowerByte
= (keycode
& 0x00ff);
1478 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1479 lowerByte
= lowerByte
| 0x80;
1485 var buff
= sock
._sQ
;
1486 var offset
= sock
._sQlen
;
1488 buff
[offset
] = 255; // msg-type
1489 buff
[offset
+ 1] = 0; // sub msg-type
1491 buff
[offset
+ 2] = (down
>> 8);
1492 buff
[offset
+ 3] = down
;
1494 buff
[offset
+ 4] = (keysym
>> 24);
1495 buff
[offset
+ 5] = (keysym
>> 16);
1496 buff
[offset
+ 6] = (keysym
>> 8);
1497 buff
[offset
+ 7] = keysym
;
1499 var RFBkeycode
= getRFBkeycode(keycode
);
1501 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1502 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1503 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1504 buff
[offset
+ 11] = RFBkeycode
;
1510 pointerEvent: function (sock
, x
, y
, mask
) {
1511 var buff
= sock
._sQ
;
1512 var offset
= sock
._sQlen
;
1514 buff
[offset
] = 5; // msg-type
1516 buff
[offset
+ 1] = mask
;
1518 buff
[offset
+ 2] = x
>> 8;
1519 buff
[offset
+ 3] = x
;
1521 buff
[offset
+ 4] = y
>> 8;
1522 buff
[offset
+ 5] = y
;
1528 // TODO(directxman12): make this unicode compatible?
1529 clientCutText: function (sock
, text
) {
1530 var buff
= sock
._sQ
;
1531 var offset
= sock
._sQlen
;
1533 buff
[offset
] = 6; // msg-type
1535 buff
[offset
+ 1] = 0; // padding
1536 buff
[offset
+ 2] = 0; // padding
1537 buff
[offset
+ 3] = 0; // padding
1539 var n
= text
.length
;
1541 buff
[offset
+ 4] = n
>> 24;
1542 buff
[offset
+ 5] = n
>> 16;
1543 buff
[offset
+ 6] = n
>> 8;
1544 buff
[offset
+ 7] = n
;
1546 for (var i
= 0; i
< n
; i
++) {
1547 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1550 sock
._sQlen
+= 8 + n
;
1554 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1555 var buff
= sock
._sQ
;
1556 var offset
= sock
._sQlen
;
1558 buff
[offset
] = 251; // msg-type
1559 buff
[offset
+ 1] = 0; // padding
1560 buff
[offset
+ 2] = width
>> 8; // width
1561 buff
[offset
+ 3] = width
;
1562 buff
[offset
+ 4] = height
>> 8; // height
1563 buff
[offset
+ 5] = height
;
1565 buff
[offset
+ 6] = 1; // number-of-screens
1566 buff
[offset
+ 7] = 0; // padding
1569 buff
[offset
+ 8] = id
>> 24; // id
1570 buff
[offset
+ 9] = id
>> 16;
1571 buff
[offset
+ 10] = id
>> 8;
1572 buff
[offset
+ 11] = id
;
1573 buff
[offset
+ 12] = 0; // x-position
1574 buff
[offset
+ 13] = 0;
1575 buff
[offset
+ 14] = 0; // y-position
1576 buff
[offset
+ 15] = 0;
1577 buff
[offset
+ 16] = width
>> 8; // width
1578 buff
[offset
+ 17] = width
;
1579 buff
[offset
+ 18] = height
>> 8; // height
1580 buff
[offset
+ 19] = height
;
1581 buff
[offset
+ 20] = flags
>> 24; // flags
1582 buff
[offset
+ 21] = flags
>> 16;
1583 buff
[offset
+ 22] = flags
>> 8;
1584 buff
[offset
+ 23] = flags
;
1590 clientFence: function (sock
, flags
, payload
) {
1591 var buff
= sock
._sQ
;
1592 var offset
= sock
._sQlen
;
1594 buff
[offset
] = 248; // msg-type
1596 buff
[offset
+ 1] = 0; // padding
1597 buff
[offset
+ 2] = 0; // padding
1598 buff
[offset
+ 3] = 0; // padding
1600 buff
[offset
+ 4] = flags
>> 24; // flags
1601 buff
[offset
+ 5] = flags
>> 16;
1602 buff
[offset
+ 6] = flags
>> 8;
1603 buff
[offset
+ 7] = flags
;
1605 var n
= payload
.length
;
1607 buff
[offset
+ 8] = n
; // length
1609 for (var i
= 0; i
< n
; i
++) {
1610 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1613 sock
._sQlen
+= 9 + n
;
1617 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1618 var buff
= sock
._sQ
;
1619 var offset
= sock
._sQlen
;
1621 buff
[offset
] = 150; // msg-type
1622 buff
[offset
+ 1] = enable
; // enable-flag
1624 buff
[offset
+ 2] = x
>> 8; // x
1625 buff
[offset
+ 3] = x
;
1626 buff
[offset
+ 4] = y
>> 8; // y
1627 buff
[offset
+ 5] = y
;
1628 buff
[offset
+ 6] = width
>> 8; // width
1629 buff
[offset
+ 7] = width
;
1630 buff
[offset
+ 8] = height
>> 8; // height
1631 buff
[offset
+ 9] = height
;
1637 pixelFormat: function (sock
, depth
, true_color
) {
1638 var buff
= sock
._sQ
;
1639 var offset
= sock
._sQlen
;
1645 } else if (depth
> 8) {
1651 bits
= Math
.floor(depth
/3);
1653 buff
[offset
] = 0; // msg-type
1655 buff
[offset
+ 1] = 0; // padding
1656 buff
[offset
+ 2] = 0; // padding
1657 buff
[offset
+ 3] = 0; // padding
1659 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1660 buff
[offset
+ 5] = depth
; // depth
1661 buff
[offset
+ 6] = 0; // little-endian
1662 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1664 buff
[offset
+ 8] = 0; // red-max
1665 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1667 buff
[offset
+ 10] = 0; // green-max
1668 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1670 buff
[offset
+ 12] = 0; // blue-max
1671 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1673 buff
[offset
+ 14] = bits
* 2; // red-shift
1674 buff
[offset
+ 15] = bits
* 1; // green-shift
1675 buff
[offset
+ 16] = bits
* 0; // blue-shift
1677 buff
[offset
+ 17] = 0; // padding
1678 buff
[offset
+ 18] = 0; // padding
1679 buff
[offset
+ 19] = 0; // padding
1685 clientEncodings: function (sock
, encodings
) {
1686 var buff
= sock
._sQ
;
1687 var offset
= sock
._sQlen
;
1689 buff
[offset
] = 2; // msg-type
1690 buff
[offset
+ 1] = 0; // padding
1692 buff
[offset
+ 2] = encodings
.length
>> 8;
1693 buff
[offset
+ 3] = encodings
.length
;
1695 var i
, j
= offset
+ 4;
1696 for (i
= 0; i
< encodings
.length
; i
++) {
1697 var enc
= encodings
[i
];
1698 buff
[j
] = enc
>> 24;
1699 buff
[j
+ 1] = enc
>> 16;
1700 buff
[j
+ 2] = enc
>> 8;
1706 sock
._sQlen
+= j
- offset
;
1710 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1711 var buff
= sock
._sQ
;
1712 var offset
= sock
._sQlen
;
1714 if (typeof(x
) === "undefined") { x
= 0; }
1715 if (typeof(y
) === "undefined") { y
= 0; }
1717 buff
[offset
] = 3; // msg-type
1718 buff
[offset
+ 1] = incremental
? 1 : 0;
1720 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1721 buff
[offset
+ 3] = x
& 0xFF;
1723 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1724 buff
[offset
+ 5] = y
& 0xFF;
1726 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1727 buff
[offset
+ 7] = w
& 0xFF;
1729 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1730 buff
[offset
+ 9] = h
& 0xFF;
1736 xvpOp: function (sock
, ver
, op
) {
1737 var buff
= sock
._sQ
;
1738 var offset
= sock
._sQlen
;
1740 buff
[offset
] = 250; // msg-type
1741 buff
[offset
+ 1] = 0; // padding
1743 buff
[offset
+ 2] = ver
;
1744 buff
[offset
+ 3] = op
;
1751 RFB
.genDES = function (password
, challenge
) {
1753 for (var i
= 0; i
< password
.length
; i
++) {
1754 passwd
.push(password
.charCodeAt(i
));
1756 return (new DES(passwd
)).encrypt(challenge
);
1759 RFB
.encodingHandlers
= {
1761 if (this._FBU
.lines
=== 0) {
1762 this._FBU
.lines
= this._FBU
.height
;
1765 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1766 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1767 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1768 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1769 var curr_height
= Math
.min(this._FBU
.lines
,
1770 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1771 var data
= this._sock
.get_rQ();
1772 var index
= this._sock
.get_rQi();
1773 if (this._fb_depth
== 8) {
1774 var pixels
= this._FBU
.width
* curr_height
1775 var newdata
= new Uint8Array(pixels
* 4);
1777 for (i
= 0;i
< pixels
;i
++) {
1778 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1779 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1780 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1781 newdata
[i
* 4 + 4] = 0;
1786 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1787 curr_height
, data
, index
);
1788 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1789 this._FBU
.lines
-= curr_height
;
1791 if (this._FBU
.lines
> 0) {
1792 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1795 this._FBU
.bytes
= 0;
1801 COPYRECT: function () {
1802 this._FBU
.bytes
= 4;
1803 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1804 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1805 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1809 this._FBU
.bytes
= 0;
1815 if (this._FBU
.subrects
=== 0) {
1816 this._FBU
.bytes
= 4 + 4;
1817 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1818 this._FBU
.subrects
= this._sock
.rQshift32();
1819 color
= this._sock
.rQshiftBytes(4); // Background
1820 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1823 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1824 color
= this._sock
.rQshiftBytes(4);
1825 var x
= this._sock
.rQshift16();
1826 var y
= this._sock
.rQshift16();
1827 var width
= this._sock
.rQshift16();
1828 var height
= this._sock
.rQshift16();
1829 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1830 this._FBU
.subrects
--;
1833 if (this._FBU
.subrects
> 0) {
1834 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1835 this._FBU
.bytes
= (4 + 8) * chunk
;
1838 this._FBU
.bytes
= 0;
1844 HEXTILE: function () {
1845 var rQ
= this._sock
.get_rQ();
1846 var rQi
= this._sock
.get_rQi();
1848 if (this._FBU
.tiles
=== 0) {
1849 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1850 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1851 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1852 this._FBU
.tiles
= this._FBU
.total_tiles
;
1855 while (this._FBU
.tiles
> 0) {
1856 this._FBU
.bytes
= 1;
1857 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1858 var subencoding
= rQ
[rQi
]; // Peek
1859 if (subencoding
> 30) { // Raw
1860 this._fail("Unexpected server message",
1861 "Illegal hextile subencoding: " + subencoding
);
1866 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1867 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1868 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1869 var x
= this._FBU
.x
+ tile_x
* 16;
1870 var y
= this._FBU
.y
+ tile_y
* 16;
1871 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1872 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1874 // Figure out how much we are expecting
1875 if (subencoding
& 0x01) { // Raw
1876 this._FBU
.bytes
+= w
* h
* 4;
1878 if (subencoding
& 0x02) { // Background
1879 this._FBU
.bytes
+= 4;
1881 if (subencoding
& 0x04) { // Foreground
1882 this._FBU
.bytes
+= 4;
1884 if (subencoding
& 0x08) { // AnySubrects
1885 this._FBU
.bytes
++; // Since we aren't shifting it off
1886 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1887 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1888 if (subencoding
& 0x10) { // SubrectsColoured
1889 this._FBU
.bytes
+= subrects
* (4 + 2);
1891 this._FBU
.bytes
+= subrects
* 2;
1896 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1898 // We know the encoding and have a whole tile
1899 this._FBU
.subencoding
= rQ
[rQi
];
1901 if (this._FBU
.subencoding
=== 0) {
1902 if (this._FBU
.lastsubencoding
& 0x01) {
1903 // Weird: ignore blanks are RAW
1904 Log
.Debug(" Ignoring blank after RAW");
1906 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1908 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1909 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1910 rQi
+= this._FBU
.bytes
- 1;
1912 if (this._FBU
.subencoding
& 0x02) { // Background
1913 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1916 if (this._FBU
.subencoding
& 0x04) { // Foreground
1917 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1921 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1922 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1926 for (var s
= 0; s
< subrects
; s
++) {
1928 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1929 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1932 color
= this._FBU
.foreground
;
1937 var sy
= (xy
& 0x0f);
1941 var sw
= (wh
>> 4) + 1;
1942 var sh
= (wh
& 0x0f) + 1;
1944 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1947 this._display
.finishTile();
1949 this._sock
.set_rQi(rQi
);
1950 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
1951 this._FBU
.bytes
= 0;
1955 if (this._FBU
.tiles
=== 0) {
1962 TIGHT: function () {
1963 this._FBU
.bytes
= 1; // compression-control byte
1964 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
1966 var checksum = function (data
) {
1968 for (var i
= 0; i
< data
.length
; i
++) {
1970 if (sum
> 65536) sum
-= 65536;
1975 var resetStreams
= 0;
1977 var decompress = function (data
, expected
) {
1978 for (var i
= 0; i
< 4; i
++) {
1979 if ((resetStreams
>> i
) & 1) {
1980 this._FBU
.zlibs
[i
].reset();
1981 Log
.Info("Reset zlib stream " + i
);
1985 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
1986 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
1987 /*if (uncompressed.status !== 0) {
1988 Log.Error("Invalid data in zlib stream");
1991 //return uncompressed.data;
1992 return uncompressed
;
1995 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
1996 // Convert indexed (palette based) image data to RGB
1997 // TODO: reduce number of calculations inside loop
1998 var dest
= this._destBuff
;
1999 var w
= Math
.floor((width
+ 7) / 8);
2000 var w1
= Math
.floor(width
/ 8);
2002 /*for (var y = 0; y < height; y++) {
2004 var yoffset = y * width;
2005 var ybitoffset = y * w;
2006 var xoffset, targetbyte;
2007 for (x = 0; x < w1; x++) {
2008 xoffset = yoffset + x * 8;
2009 targetbyte = data[ybitoffset + x];
2010 for (b = 7; b >= 0; b--) {
2011 dp = (xoffset + 7 - b) * 3;
2012 sp = (targetbyte >> b & 1) * 3;
2013 dest[dp] = palette[sp];
2014 dest[dp + 1] = palette[sp + 1];
2015 dest[dp + 2] = palette[sp + 2];
2019 xoffset = yoffset + x * 8;
2020 targetbyte = data[ybitoffset + x];
2021 for (b = 7; b >= 8 - width % 8; b--) {
2022 dp = (xoffset + 7 - b) * 3;
2023 sp = (targetbyte >> b & 1) * 3;
2024 dest[dp] = palette[sp];
2025 dest[dp + 1] = palette[sp + 1];
2026 dest[dp + 2] = palette[sp + 2];
2030 for (var y
= 0; y
< height
; y
++) {
2032 for (x
= 0; x
< w1
; x
++) {
2033 for (b
= 7; b
>= 0; b
--) {
2034 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2035 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2036 dest
[dp
] = palette
[sp
];
2037 dest
[dp
+ 1] = palette
[sp
+ 1];
2038 dest
[dp
+ 2] = palette
[sp
+ 2];
2043 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2044 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2045 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2046 dest
[dp
] = palette
[sp
];
2047 dest
[dp
+ 1] = palette
[sp
+ 1];
2048 dest
[dp
+ 2] = palette
[sp
+ 2];
2056 var indexedToRGBX = function (data
, palette
, width
, height
) {
2057 // Convert indexed (palette based) image data to RGB
2058 var dest
= this._destBuff
;
2059 var total
= width
* height
* 4;
2060 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2061 var sp
= data
[j
] * 3;
2062 dest
[i
] = palette
[sp
];
2063 dest
[i
+ 1] = palette
[sp
+ 1];
2064 dest
[i
+ 2] = palette
[sp
+ 2];
2071 var rQi
= this._sock
.get_rQi();
2072 var rQ
= this._sock
.rQwhole();
2074 var cl_header
, cl_data
;
2076 var handlePalette = function () {
2077 var numColors
= rQ
[rQi
+ 2] + 1;
2078 var paletteSize
= numColors
* 3;
2079 this._FBU
.bytes
+= paletteSize
;
2080 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2082 var bpp
= (numColors
<= 2) ? 1 : 8;
2083 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2085 if (rowSize
* this._FBU
.height
< 12) {
2088 cl_data
= rowSize
* this._FBU
.height
;
2089 //clength = [0, rowSize * this._FBU.height];
2091 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2092 var cl_offset
= rQi
+ 3 + paletteSize
;
2095 cl_data
+= rQ
[cl_offset
] & 0x7f;
2096 if (rQ
[cl_offset
] & 0x80) {
2098 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2099 if (rQ
[cl_offset
+ 1] & 0x80) {
2101 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2104 // end inline getTightCLength
2107 this._FBU
.bytes
+= cl_header
+ cl_data
;
2108 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2110 // Shift ctl, filter id, num colors, palette entries, and clength off
2111 this._sock
.rQskipBytes(3);
2112 //var palette = this._sock.rQshiftBytes(paletteSize);
2113 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2114 this._sock
.rQskipBytes(cl_header
);
2117 data
= this._sock
.rQshiftBytes(cl_data
);
2119 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2122 // Convert indexed (palette based) image data to RGB
2124 if (numColors
== 2) {
2125 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2126 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2128 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2129 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2136 var handleCopy = function () {
2138 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2139 if (uncompressedSize
< 12) {
2142 cl_data
= uncompressedSize
;
2144 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2145 var cl_offset
= rQi
+ 1;
2148 cl_data
+= rQ
[cl_offset
] & 0x7f;
2149 if (rQ
[cl_offset
] & 0x80) {
2151 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2152 if (rQ
[cl_offset
+ 1] & 0x80) {
2154 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2157 // end inline getTightCLength
2159 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2160 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2162 // Shift ctl, clength off
2163 this._sock
.rQshiftBytes(1 + cl_header
);
2166 data
= this._sock
.rQshiftBytes(cl_data
);
2168 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2171 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2176 var ctl
= this._sock
.rQpeek8();
2178 // Keep tight reset bits
2179 resetStreams
= ctl
& 0xF;
2181 // Figure out filter
2183 streamId
= ctl
& 0x3;
2185 if (ctl
=== 0x08) cmode
= "fill";
2186 else if (ctl
=== 0x09) cmode
= "jpeg";
2187 else if (ctl
=== 0x0A) cmode
= "png";
2188 else if (ctl
& 0x04) cmode
= "filter";
2189 else if (ctl
< 0x04) cmode
= "copy";
2190 else return this._fail("Unexpected server message",
2191 "Illegal tight compression received, " +
2195 // fill use depth because TPIXELs drop the padding byte
2196 case "fill": // TPIXEL
2197 this._FBU
.bytes
+= 3;
2199 case "jpeg": // max clength
2200 this._FBU
.bytes
+= 3;
2202 case "png": // max clength
2203 this._FBU
.bytes
+= 3;
2205 case "filter": // filter id + num colors if palette
2206 this._FBU
.bytes
+= 2;
2212 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2214 // Determine FBU.bytes
2218 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);
2219 this._sock
.rQskipBytes(4);
2223 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2224 var cl_offset
= rQi
+ 1;
2227 cl_data
+= rQ
[cl_offset
] & 0x7f;
2228 if (rQ
[cl_offset
] & 0x80) {
2230 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2231 if (rQ
[cl_offset
+ 1] & 0x80) {
2233 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2236 // end inline getTightCLength
2237 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2238 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2240 // We have everything, render it
2241 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2242 data
= this._sock
.rQshiftBytes(cl_data
);
2243 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2246 var filterId
= rQ
[rQi
+ 1];
2247 if (filterId
=== 1) {
2248 if (!handlePalette()) { return false; }
2250 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2251 // Filter 2, Gradient is valid but not use if jpeg is enabled
2252 this._fail("Unexpected server message",
2253 "Unsupported tight subencoding received, " +
2254 "filter: " + filterId
);
2258 if (!handleCopy()) { return false; }
2263 this._FBU
.bytes
= 0;
2269 last_rect: function () {
2270 this._FBU
.rects
= 0;
2274 ExtendedDesktopSize: function () {
2275 this._FBU
.bytes
= 1;
2276 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2278 this._supportsSetDesktopSize
= true;
2279 this._setCapability("resize", true);
2281 var number_of_screens
= this._sock
.rQpeek8();
2283 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2284 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2286 this._sock
.rQskipBytes(1); // number-of-screens
2287 this._sock
.rQskipBytes(3); // padding
2289 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2290 // Save the id and flags of the first screen
2292 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2293 this._sock
.rQskipBytes(2); // x-position
2294 this._sock
.rQskipBytes(2); // y-position
2295 this._sock
.rQskipBytes(2); // width
2296 this._sock
.rQskipBytes(2); // height
2297 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2299 this._sock
.rQskipBytes(16);
2304 * The x-position indicates the reason for the change:
2306 * 0 - server resized on its own
2307 * 1 - this client requested the resize
2308 * 2 - another client requested the resize
2311 // We need to handle errors when we requested the resize.
2312 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2314 // The y-position indicates the status code from the server
2315 switch (this._FBU
.y
) {
2317 msg
= "Resize is administratively prohibited";
2320 msg
= "Out of resources";
2323 msg
= "Invalid screen layout";
2326 msg
= "Unknown reason";
2329 this._notification("Server did not accept the resize request: "
2332 this._resize(this._FBU
.width
, this._FBU
.height
);
2335 this._FBU
.bytes
= 0;
2336 this._FBU
.rects
-= 1;
2340 DesktopSize: function () {
2341 this._resize(this._FBU
.width
, this._FBU
.height
);
2342 this._FBU
.bytes
= 0;
2343 this._FBU
.rects
-= 1;
2347 Cursor: function () {
2348 Log
.Debug(">> set_cursor");
2349 var x
= this._FBU
.x
; // hotspot-x
2350 var y
= this._FBU
.y
; // hotspot-y
2351 var w
= this._FBU
.width
;
2352 var h
= this._FBU
.height
;
2354 var pixelslength
= w
* h
* 4;
2355 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2357 this._FBU
.bytes
= pixelslength
+ masklength
;
2358 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2360 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2361 this._sock
.rQshiftBytes(masklength
),
2364 this._FBU
.bytes
= 0;
2367 Log
.Debug("<< set_cursor");
2371 QEMUExtendedKeyEvent: function () {
2374 // Old Safari doesn't support creating keyboard events
2376 var keyboardEvent
= document
.createEvent("keyboardEvent");
2377 if (keyboardEvent
.code
!== undefined) {
2378 this._qemuExtKeyEventSupported
= true;