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
) {
35 this._target
= target
;
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;
130 Log
.Debug(">> RFB.constructor");
132 // Target canvas must be able to have focus
133 if (!this._target
.hasAttribute('tabindex')) {
134 this._target
.tabIndex
= -1;
137 // populate encHandlers with bound versions
138 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this);
139 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this);
140 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this);
141 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this);
142 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this);
144 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this);
145 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this);
146 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this);
147 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this);
148 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this);
150 // NB: nothing that needs explicit teardown should be done
151 // before this point, since this can throw an exception
153 this._display
= new Display(this._target
);
155 Log
.Error("Display exception: " + exc
);
158 this._display
.onflush
= this._onFlush
.bind(this);
159 this._display
.clear();
161 this._keyboard
= new Keyboard(this._target
);
162 this._keyboard
.onkeyevent
= this._handleKeyEvent
.bind(this);
164 this._mouse
= new Mouse(this._target
);
165 this._mouse
.onmousebutton
= this._handleMouseButton
.bind(this);
166 this._mouse
.onmousemove
= this._handleMouseMove
.bind(this);
168 this._sock
= new Websock();
169 this._sock
.on('message', this._handle_message
.bind(this));
170 this._sock
.on('open', function () {
171 if ((this._rfb_connection_state
=== 'connecting') &&
172 (this._rfb_init_state
=== '')) {
173 this._rfb_init_state
= 'ProtocolVersion';
174 Log
.Debug("Starting VNC handshake");
176 this._fail("Unexpected server connection");
179 this._sock
.on('close', function (e
) {
180 Log
.Warn("WebSocket on-close event");
183 msg
= " (code: " + e
.code
;
185 msg
+= ", reason: " + e
.reason
;
189 switch (this._rfb_connection_state
) {
190 case 'disconnecting':
191 this._updateConnectionState('disconnected');
194 this._fail('Failed to connect to server', msg
);
197 // Handle disconnects that were initiated server-side
198 this._updateConnectionState('disconnecting');
199 this._updateConnectionState('disconnected');
202 this._fail("Unexpected server disconnect",
203 "Already disconnected: " + msg
);
206 this._fail("Unexpected server disconnect",
207 "Not in any state yet: " + msg
);
210 this._sock
.off('close');
212 this._sock
.on('error', function (e
) {
213 Log
.Warn("WebSocket on-error event");
216 Log
.Debug("<< RFB.constructor");
220 // ===== PROPERTIES =====
225 get viewOnly() { return this._viewOnly
; },
226 set viewOnly(viewOnly
) {
227 this._viewOnly
= viewOnly
;
229 if (this._rfb_connection_state
=== "connecting" ||
230 this._rfb_connection_state
=== "connected") {
232 this._keyboard
.ungrab();
233 this._mouse
.ungrab();
235 this._keyboard
.grab();
241 get capabilities() { return this._capabilities
; },
243 get touchButton() { return this._mouse
.touchButton
; },
244 set touchButton(button
) { this._mouse
.touchButton
= button
; },
246 get viewportScale() { return this._display
.scale
; },
247 set viewportScale(scale
) { this._display
.scale
= scale
; },
249 get clipViewport() { return this._display
.clipViewport
; },
250 set clipViewport(viewport
) { this._display
.clipViewport
= viewport
; },
252 get isClipped() { return this._display
.isClipped
; },
254 // ===== EVENT HANDLERS =====
256 onupdatestate: function () {}, // onupdatestate(rfb, state, oldstate): connection state change
257 onnotification: function () {}, // onnotification(rfb, msg, level, options): notification for the UI
258 ondisconnected: function () {}, // ondisconnected(rfb, reason): disconnection finished
259 oncredentialsrequired: function () {}, // oncredentialsrequired(rfb, types): VNC credentials are required
260 onclipboard: function () {}, // onclipboard(rfb, text): RFB clipboard contents received
261 onbell: function () {}, // onbell(rfb): RFB Bell message received
262 onfbresize: function () {}, // onfbresize(rfb, width, height): frame buffer resized
263 ondesktopname: function () {}, // ondesktopname(rfb, name): desktop name received
264 oncapabilities: function () {}, // oncapabilities(rfb, caps): the supported capabilities has changed
266 // ===== PUBLIC METHODS =====
268 connect: function (url
, options
) {
270 this._fail(_("Must specify URL"));
276 options
= options
|| {}
278 this._rfb_credentials
= options
.credentials
|| {};
279 this._shared
= 'shared' in options
? !!options
.shared
: true;
280 this._repeaterID
= options
.repeaterID
|| '';
282 this._rfb_init_state
= '';
283 this._updateConnectionState('connecting');
286 disconnect: function () {
287 this._updateConnectionState('disconnecting');
288 this._sock
.off('error');
289 this._sock
.off('message');
290 this._sock
.off('open');
293 sendCredentials: function (creds
) {
294 this._rfb_credentials
= creds
;
295 setTimeout(this._init_msg
.bind(this), 0);
298 sendCtrlAltDel: function () {
299 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
300 Log
.Info("Sending Ctrl-Alt-Del");
302 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
303 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
304 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
305 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
306 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
307 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
310 machineShutdown: function () {
314 machineReboot: function () {
318 machineReset: function () {
322 // Send a key press. If 'down' is not specified then send a down key
323 // followed by an up key.
324 sendKey: function (keysym
, code
, down
) {
325 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
327 if (down
=== undefined) {
328 this.sendKey(keysym
, code
, true);
329 this.sendKey(keysym
, code
, false);
333 var scancode
= XtScancode
[code
];
335 if (this._qemuExtKeyEventSupported
&& scancode
) {
337 keysym
= keysym
|| 0;
339 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
341 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
346 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
347 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
351 clipboardPasteFrom: function (text
) {
352 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
353 RFB
.messages
.clientCutText(this._sock
, text
);
356 autoscale: function (width
, height
) {
357 if (this._rfb_connection_state
!== 'connected') { return; }
358 this._display
.autoscale(width
, height
);
361 viewportChangeSize: function(width
, height
) {
362 if (this._rfb_connection_state
!== 'connected') { return; }
363 this._display
.viewportChangeSize(width
, height
);
366 // Requests a change of remote desktop size. This message is an extension
367 // and may only be sent if we have received an ExtendedDesktopSize message
368 requestDesktopSize: function (width
, height
) {
369 if (this._rfb_connection_state
!== 'connected' ||
374 if (!this._supportsSetDesktopSize
) {
378 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
379 this._screen_id
, this._screen_flags
);
383 // ===== PRIVATE METHODS =====
385 _connect: function () {
386 Log
.Debug(">> RFB.connect");
388 Log
.Info("connecting to " + this._url
);
391 // WebSocket.onopen transitions to the RFB init states
392 this._sock
.open(this._url
, ['binary']);
394 if (e
.name
=== 'SyntaxError') {
395 this._fail("Invalid host or port value given", e
);
397 this._fail("Error while connecting", e
);
401 // Always grab focus on some kind of click event
402 this._target
.addEventListener("mousedown", this._focusCanvas
);
403 this._target
.addEventListener("touchstart", this._focusCanvas
);
405 Log
.Debug("<< RFB.connect");
408 _disconnect: function () {
409 Log
.Debug(">> RFB.disconnect");
410 this._target
.removeEventListener("mousedown", this._focusCanvas
);
411 this._target
.removeEventListener("touchstart", this._focusCanvas
);
415 Log
.Debug("<< RFB.disconnect");
418 _print_stats: function () {
419 var stats
= this._encStats
;
421 Log
.Info("Encoding stats for this connection:");
422 Object
.keys(stats
).forEach(function (key
) {
424 if (s
[0] + s
[1] > 0) {
425 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
429 Log
.Info("Encoding stats since page load:");
430 Object
.keys(stats
).forEach(function (key
) {
432 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
436 _cleanup: function () {
437 if (!this._viewOnly
) { this._keyboard
.ungrab(); }
438 if (!this._viewOnly
) { this._mouse
.ungrab(); }
439 this._display
.defaultCursor();
440 if (Log
.get_logging() !== 'debug') {
441 // Show noVNC logo when disconnected, unless in
443 this._display
.clear();
447 // Event handler for canvas so this points to the canvas element
448 _focusCanvas: function(event
) {
449 // Respect earlier handlers' request to not do side-effects
450 if (!event
.defaultPrevented
)
459 * disconnected - permanent state
461 _updateConnectionState: function (state
) {
462 var oldstate
= this._rfb_connection_state
;
464 if (state
=== oldstate
) {
465 Log
.Debug("Already in state '" + state
+ "', ignoring");
469 // The 'disconnected' state is permanent for each RFB object
470 if (oldstate
=== 'disconnected') {
471 Log
.Error("Tried changing state of a disconnected RFB object");
475 // Ensure proper transitions before doing anything
478 if (oldstate
!== 'connecting') {
479 Log
.Error("Bad transition to connected state, " +
480 "previous connection state: " + oldstate
);
486 if (oldstate
!== 'disconnecting') {
487 Log
.Error("Bad transition to disconnected state, " +
488 "previous connection state: " + oldstate
);
494 if (oldstate
!== '') {
495 Log
.Error("Bad transition to connecting state, " +
496 "previous connection state: " + oldstate
);
501 case 'disconnecting':
502 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
503 Log
.Error("Bad transition to disconnecting state, " +
504 "previous connection state: " + oldstate
);
510 Log
.Error("Unknown connection state: " + state
);
514 // State change actions
516 this._rfb_connection_state
= state
;
517 this.onupdatestate(this, state
, oldstate
);
519 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
522 if (this._disconnTimer
&& state
!== 'disconnecting') {
523 Log
.Debug("Clearing disconnect timer");
524 clearTimeout(this._disconnTimer
);
525 this._disconnTimer
= null;
527 // make sure we don't get a double event
528 this._sock
.off('close');
533 // Call ondisconnected callback after onupdatestate since
534 // we don't know if the UI only displays the latest message
535 if (this._rfb_disconnect_reason
!== "") {
536 this.ondisconnected(this, this._rfb_disconnect_reason
);
538 // No reason means clean disconnect
539 this.ondisconnected(this);
547 case 'disconnecting':
550 this._disconnTimer
= setTimeout(function () {
551 this._rfb_disconnect_reason
= _("Disconnect timeout");
552 this._updateConnectionState('disconnected');
553 }.bind(this), DISCONNECT_TIMEOUT
* 1000);
558 /* Print errors and disconnect
560 * The optional parameter 'details' is used for information that
561 * should be logged but not sent to the user interface.
563 _fail: function (msg
, details
) {
565 if (typeof details
!== 'undefined') {
566 fullmsg
= msg
+ " (" + details
+ ")";
568 switch (this._rfb_connection_state
) {
569 case 'disconnecting':
570 Log
.Error("Failed when disconnecting: " + fullmsg
);
573 Log
.Error("Failed while connected: " + fullmsg
);
576 Log
.Error("Failed when connecting: " + fullmsg
);
579 Log
.Error("RFB failure: " + fullmsg
);
582 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
584 // Transition to disconnected without waiting for socket to close
585 this._updateConnectionState('disconnecting');
586 this._updateConnectionState('disconnected');
592 * Send a notification to the UI. Valid levels are:
593 * 'normal'|'warn'|'error'
595 * NOTE: Options could be added in the future.
596 * NOTE: If this function is called multiple times, remember that the
597 * interface could be only showing the latest notification.
599 _notification: function(msg
, level
, options
) {
604 Log
.Debug("Notification[" + level
+ "]:" + msg
);
607 Log
.Error("Invalid notification level: " + level
);
612 this.onnotification(this, msg
, level
, options
);
614 this.onnotification(this, msg
, level
);
618 _setCapability: function (cap
, val
) {
619 this._capabilities
[cap
] = val
;
620 this.oncapabilities(this, this._capabilities
);
623 _handle_message: function () {
624 if (this._sock
.rQlen() === 0) {
625 Log
.Warn("handle_message called on an empty receive queue");
629 switch (this._rfb_connection_state
) {
631 Log
.Error("Got data while disconnected");
635 if (this._flushing
) {
638 if (!this._normal_msg()) {
641 if (this._sock
.rQlen() === 0) {
652 _handleKeyEvent: function (keysym
, code
, down
) {
653 this.sendKey(keysym
, code
, down
);
656 _handleMouseButton: function (x
, y
, down
, bmask
) {
658 this._mouse_buttonMask
|= bmask
;
660 this._mouse_buttonMask
&= ~bmask
;
663 if (this.dragViewport
) {
664 if (down
&& !this._viewportDragging
) {
665 this._viewportDragging
= true;
666 this._viewportDragPos
= {'x': x
, 'y': y
};
668 // Skip sending mouse events
671 this._viewportDragging
= false;
673 // If the viewport didn't actually move, then treat as a mouse click event
674 // Send the button down event here, as the button up event is sent at the end of this function
675 if (!this._viewportHasMoved
&& !this._viewOnly
) {
676 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
678 this._viewportHasMoved
= false;
682 if (this._viewOnly
) { return; } // View only, skip mouse events
684 if (this._rfb_connection_state
!== 'connected') { return; }
685 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
688 _handleMouseMove: function (x
, y
) {
689 if (this._viewportDragging
) {
690 var deltaX
= this._viewportDragPos
.x
- x
;
691 var deltaY
= this._viewportDragPos
.y
- y
;
693 // The goal is to trigger on a certain physical width, the
694 // devicePixelRatio brings us a bit closer but is not optimal.
695 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
697 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
698 Math
.abs(deltaY
) > dragThreshold
)) {
699 this._viewportHasMoved
= true;
701 this._viewportDragPos
= {'x': x
, 'y': y
};
702 this._display
.viewportChangePos(deltaX
, deltaY
);
705 // Skip sending mouse events
709 if (this._viewOnly
) { return; } // View only, skip mouse events
711 if (this._rfb_connection_state
!== 'connected') { return; }
712 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
717 _negotiate_protocol_version: function () {
718 if (this._sock
.rQlen() < 12) {
719 return this._fail("Error while negotiating with server",
720 "Incomplete protocol version");
723 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
724 Log
.Info("Server ProtocolVersion: " + sversion
);
727 case "000.000": // UltraVNC repeater
731 case "003.006": // UltraVNC
732 case "003.889": // Apple Remote Desktop
733 this._rfb_version
= 3.3;
736 this._rfb_version
= 3.7;
739 case "004.000": // Intel AMT KVM
740 case "004.001": // RealVNC 4.6
741 case "005.000": // RealVNC 5.3
742 this._rfb_version
= 3.8;
745 return this._fail("Unsupported server",
746 "Invalid server version: " + sversion
);
750 var repeaterID
= "ID:" + this._repeaterID
;
751 while (repeaterID
.length
< 250) {
754 this._sock
.send_string(repeaterID
);
758 if (this._rfb_version
> this._rfb_max_version
) {
759 this._rfb_version
= this._rfb_max_version
;
762 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
763 ".00" + ((this._rfb_version
* 10) % 10);
764 this._sock
.send_string("RFB " + cversion
+ "\n");
765 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
767 this._rfb_init_state
= 'Security';
770 _negotiate_security: function () {
771 // Polyfill since IE and PhantomJS doesn't have
772 // TypedArray.includes()
773 function includes(item
, array
) {
774 for (var i
= 0; i
< array
.length
; i
++) {
775 if (array
[i
] === item
) {
782 if (this._rfb_version
>= 3.7) {
783 // Server sends supported list, client decides
784 var num_types
= this._sock
.rQshift8();
785 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
787 if (num_types
=== 0) {
788 var strlen
= this._sock
.rQshift32();
789 var reason
= this._sock
.rQshiftStr(strlen
);
790 return this._fail("Error while negotiating with server",
791 "Security failure: " + reason
);
794 var types
= this._sock
.rQshiftBytes(num_types
);
795 Log
.Debug("Server security types: " + types
);
797 // Look for each auth in preferred order
798 this._rfb_auth_scheme
= 0;
799 if (includes(1, types
)) {
800 this._rfb_auth_scheme
= 1; // None
801 } else if (includes(22, types
)) {
802 this._rfb_auth_scheme
= 22; // XVP
803 } else if (includes(16, types
)) {
804 this._rfb_auth_scheme
= 16; // Tight
805 } else if (includes(2, types
)) {
806 this._rfb_auth_scheme
= 2; // VNC Auth
808 return this._fail("Unsupported server",
809 "Unsupported security types: " + types
);
812 this._sock
.send([this._rfb_auth_scheme
]);
815 if (this._sock
.rQwait("security scheme", 4)) { return false; }
816 this._rfb_auth_scheme
= this._sock
.rQshift32();
819 this._rfb_init_state
= 'Authentication';
820 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
822 return this._init_msg(); // jump to authentication
826 _negotiate_xvp_auth: function () {
827 if (!this._rfb_credentials
.username
||
828 !this._rfb_credentials
.password
||
829 !this._rfb_credentials
.target
) {
830 this.oncredentialsrequired(this, ["username", "password", "target"]);
834 var xvp_auth_str
= String
.fromCharCode(this._rfb_credentials
.username
.length
) +
835 String
.fromCharCode(this._rfb_credentials
.target
.length
) +
836 this._rfb_credentials
.username
+
837 this._rfb_credentials
.target
;
838 this._sock
.send_string(xvp_auth_str
);
839 this._rfb_auth_scheme
= 2;
840 return this._negotiate_authentication();
843 _negotiate_std_vnc_auth: function () {
844 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
846 if (!this._rfb_credentials
.password
) {
847 this.oncredentialsrequired(this, ["password"]);
851 // TODO(directxman12): make genDES not require an Array
852 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
853 var response
= RFB
.genDES(this._rfb_credentials
.password
, challenge
);
854 this._sock
.send(response
);
855 this._rfb_init_state
= "SecurityResult";
859 _negotiate_tight_tunnels: function (numTunnels
) {
860 var clientSupportedTunnelTypes
= {
861 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
863 var serverSupportedTunnelTypes
= {};
864 // receive tunnel capabilities
865 for (var i
= 0; i
< numTunnels
; i
++) {
866 var cap_code
= this._sock
.rQshift32();
867 var cap_vendor
= this._sock
.rQshiftStr(4);
868 var cap_signature
= this._sock
.rQshiftStr(8);
869 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
872 // choose the notunnel type
873 if (serverSupportedTunnelTypes
[0]) {
874 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
875 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
876 return this._fail("Unsupported server",
877 "Client's tunnel type had the incorrect " +
878 "vendor or signature");
880 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
881 return false; // wait until we receive the sub auth count to continue
883 return this._fail("Unsupported server",
884 "Server wanted tunnels, but doesn't support " +
885 "the notunnel type");
889 _negotiate_tight_auth: function () {
890 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
891 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
892 var numTunnels
= this._sock
.rQshift32();
893 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
895 this._rfb_tightvnc
= true;
897 if (numTunnels
> 0) {
898 this._negotiate_tight_tunnels(numTunnels
);
899 return false; // wait until we receive the sub auth to continue
903 // second pass, do the sub-auth negotiation
904 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
905 var subAuthCount
= this._sock
.rQshift32();
906 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
907 this._rfb_init_state
= 'SecurityResult';
911 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
913 var clientSupportedTypes
= {
918 var serverSupportedTypes
= [];
920 for (var i
= 0; i
< subAuthCount
; i
++) {
921 var capNum
= this._sock
.rQshift32();
922 var capabilities
= this._sock
.rQshiftStr(12);
923 serverSupportedTypes
.push(capabilities
);
926 for (var authType
in clientSupportedTypes
) {
927 if (serverSupportedTypes
.indexOf(authType
) != -1) {
928 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
931 case 'STDVNOAUTH__': // no auth
932 this._rfb_init_state
= 'SecurityResult';
934 case 'STDVVNCAUTH_': // VNC auth
935 this._rfb_auth_scheme
= 2;
936 return this._init_msg();
938 return this._fail("Unsupported server",
939 "Unsupported tiny auth scheme: " +
945 return this._fail("Unsupported server",
946 "No supported sub-auth types!");
949 _negotiate_authentication: function () {
950 switch (this._rfb_auth_scheme
) {
951 case 0: // connection failed
952 if (this._sock
.rQwait("auth reason", 4)) { return false; }
953 var strlen
= this._sock
.rQshift32();
954 var reason
= this._sock
.rQshiftStr(strlen
);
955 return this._fail("Authentication failure", reason
);
958 if (this._rfb_version
>= 3.8) {
959 this._rfb_init_state
= 'SecurityResult';
962 this._rfb_init_state
= 'ClientInitialisation';
963 return this._init_msg();
966 return this._negotiate_xvp_auth();
968 case 2: // VNC authentication
969 return this._negotiate_std_vnc_auth();
971 case 16: // TightVNC Security Type
972 return this._negotiate_tight_auth();
975 return this._fail("Unsupported server",
976 "Unsupported auth scheme: " +
977 this._rfb_auth_scheme
);
981 _handle_security_result: function () {
982 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
983 switch (this._sock
.rQshift32()) {
985 this._rfb_init_state
= 'ClientInitialisation';
986 Log
.Debug('Authentication OK');
987 return this._init_msg();
989 if (this._rfb_version
>= 3.8) {
990 var length
= this._sock
.rQshift32();
991 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
992 var reason
= this._sock
.rQshiftStr(length
);
993 return this._fail("Authentication failure", reason
);
995 return this._fail("Authentication failure");
998 return this._fail("Too many authentication attempts");
1000 return this._fail("Unsupported server",
1001 "Unknown SecurityResult");
1005 _negotiate_server_init: function () {
1006 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1009 var width
= this._sock
.rQshift16();
1010 var height
= this._sock
.rQshift16();
1013 var bpp
= this._sock
.rQshift8();
1014 var depth
= this._sock
.rQshift8();
1015 var big_endian
= this._sock
.rQshift8();
1016 var true_color
= this._sock
.rQshift8();
1018 var red_max
= this._sock
.rQshift16();
1019 var green_max
= this._sock
.rQshift16();
1020 var blue_max
= this._sock
.rQshift16();
1021 var red_shift
= this._sock
.rQshift8();
1022 var green_shift
= this._sock
.rQshift8();
1023 var blue_shift
= this._sock
.rQshift8();
1024 this._sock
.rQskipBytes(3); // padding
1026 // NB(directxman12): we don't want to call any callbacks or print messages until
1027 // *after* we're past the point where we could backtrack
1029 /* Connection name/title */
1030 var name_length = this._sock.rQshift32();
1031 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1032 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1034 if (this._rfb_tightvnc) {
1035 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1036 // In TightVNC mode, ServerInit message is extended
1037 var numServerMessages = this._sock.rQshift16();
1038 var numClientMessages = this._sock.rQshift16();
1039 var numEncodings = this._sock.rQshift16();
1040 this._sock.rQskipBytes(2); // padding
1042 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1043 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1045 // we don't actually do anything with the capability information that TIGHT sends,
1046 // so we just skip the all of this.
1048 // TIGHT server message capabilities
1049 this._sock.rQskipBytes(16 * numServerMessages);
1051 // TIGHT client message capabilities
1052 this._sock.rQskipBytes(16 * numClientMessages);
1054 // TIGHT encoding capabilities
1055 this._sock.rQskipBytes(16 * numEncodings);
1058 // NB(directxman12): these are down here so that we don't run them multiple times
1060 Log.Info("Screen: " + width + "x" + height +
1061 ", bpp: " + bpp + ", depth: " + depth +
1062 ", big_endian: " + big_endian +
1063 ", true_color: " + true_color +
1064 ", red_max: " + red_max +
1065 ", green_max: " + green_max +
1066 ", blue_max: " + blue_max +
1067 ", red_shift: " + red_shift +
1068 ", green_shift: " + green_shift +
1069 ", blue_shift: " + blue_shift);
1071 if (big_endian !== 0) {
1072 Log.Warn("Server native endian is not little endian");
1075 if (red_shift !== 16) {
1076 Log.Warn("Server native red-shift is not 16");
1079 if (blue_shift !== 0) {
1080 Log.Warn("Server native blue-shift is not 0");
1083 // we're past the point where we could backtrack, so it's safe to call this
1084 this.ondesktopname(this, this._fb_name);
1086 this._resize(width, height);
1088 if (!this._viewOnly) { this._keyboard.grab(); }
1089 if (!this._viewOnly) { this._mouse.grab(); }
1091 this._fb_depth = 24;
1093 if (this._fb_name === "Intel(r) AMT KVM") {
1094 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1098 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1099 this._sendEncodings();
1100 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1102 this._timing.fbu_rt_start = (new Date()).getTime();
1103 this._timing.pixels = 0;
1105 // Cursor will be server side until the server decides to honor
1106 // our request and send over the cursor image
1107 this._display.disableLocalCursor();
1109 this._updateConnectionState('connected');
1113 _sendEncodings: function () {
1116 // In preference order
1117 encs.push(encodings.encodingCopyRect);
1118 // Only supported with full depth support
1119 if (this._fb_depth == 24) {
1120 encs.push(encodings.encodingTight);
1121 encs.push(encodings.encodingHextile);
1122 encs.push(encodings.encodingRRE);
1124 encs.push(encodings.encodingRaw);
1126 // Psuedo-encoding settings
1127 encs.push(encodings.pseudoEncodingTightPNG);
1128 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1129 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1131 encs.push(encodings.pseudoEncodingDesktopSize);
1132 encs.push(encodings.pseudoEncodingLastRect);
1133 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1134 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1135 encs.push(encodings.pseudoEncodingXvp);
1136 encs.push(encodings.pseudoEncodingFence);
1137 encs.push(encodings.pseudoEncodingContinuousUpdates);
1139 if (browserSupportsCursorURIs() &&
1140 !isTouchDevice && this._fb_depth == 24) {
1141 encs.push(encodings.pseudoEncodingCursor);
1144 RFB.messages.clientEncodings(this._sock, encs);
1147 /* RFB protocol initialization states:
1152 * ClientInitialization - not triggered by server message
1153 * ServerInitialization
1155 _init_msg: function () {
1156 switch (this._rfb_init_state
) {
1157 case 'ProtocolVersion':
1158 return this._negotiate_protocol_version();
1161 return this._negotiate_security();
1163 case 'Authentication':
1164 return this._negotiate_authentication();
1166 case 'SecurityResult':
1167 return this._handle_security_result();
1169 case 'ClientInitialisation':
1170 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1171 this._rfb_init_state
= 'ServerInitialisation';
1174 case 'ServerInitialisation':
1175 return this._negotiate_server_init();
1178 return this._fail("Internal error", "Unknown init state: " +
1179 this._rfb_init_state
);
1183 _handle_set_colour_map_msg: function () {
1184 Log
.Debug("SetColorMapEntries");
1186 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1189 _handle_server_cut_text: function () {
1190 Log
.Debug("ServerCutText");
1192 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1193 this._sock
.rQskipBytes(3); // Padding
1194 var length
= this._sock
.rQshift32();
1195 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1197 var text
= this._sock
.rQshiftStr(length
);
1199 if (this._viewOnly
) { return true; }
1201 this.onclipboard(this, text
);
1206 _handle_server_fence_msg: function() {
1207 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1208 this._sock
.rQskipBytes(3); // Padding
1209 var flags
= this._sock
.rQshift32();
1210 var length
= this._sock
.rQshift8();
1212 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1215 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1219 var payload
= this._sock
.rQshiftStr(length
);
1221 this._supportsFence
= true;
1226 * (1<<0) - BlockBefore
1227 * (1<<1) - BlockAfter
1232 if (!(flags
& (1<<31))) {
1233 return this._fail("Internal error",
1234 "Unexpected fence response");
1237 // Filter out unsupported flags
1238 // FIXME: support syncNext
1239 flags
&= (1<<0) | (1<<1);
1241 // BlockBefore and BlockAfter are automatically handled by
1242 // the fact that we process each incoming message
1244 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1249 _handle_xvp_msg: function () {
1250 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1251 this._sock
.rQskip8(); // Padding
1252 var xvp_ver
= this._sock
.rQshift8();
1253 var xvp_msg
= this._sock
.rQshift8();
1257 Log
.Error("Operation Failed");
1258 this._notification("XVP Operation Failed", 'error');
1261 this._rfb_xvp_ver
= xvp_ver
;
1262 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1263 this._setCapability("power", true);
1266 this._fail("Unexpected server message",
1267 "Illegal server XVP message " + xvp_msg
);
1274 _normal_msg: function () {
1277 if (this._FBU
.rects
> 0) {
1280 msg_type
= this._sock
.rQshift8();
1284 case 0: // FramebufferUpdate
1285 var ret
= this._framebufferUpdate();
1286 if (ret
&& !this._enabledContinuousUpdates
) {
1287 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1288 this._fb_width
, this._fb_height
);
1292 case 1: // SetColorMapEntries
1293 return this._handle_set_colour_map_msg();
1300 case 3: // ServerCutText
1301 return this._handle_server_cut_text();
1303 case 150: // EndOfContinuousUpdates
1304 var first
= !(this._supportsContinuousUpdates
);
1305 this._supportsContinuousUpdates
= true;
1306 this._enabledContinuousUpdates
= false;
1308 this._enabledContinuousUpdates
= true;
1309 this._updateContinuousUpdates();
1310 Log
.Info("Enabling continuous updates.");
1312 // FIXME: We need to send a framebufferupdaterequest here
1313 // if we add support for turning off continuous updates
1317 case 248: // ServerFence
1318 return this._handle_server_fence_msg();
1321 return this._handle_xvp_msg();
1324 this._fail("Unexpected server message", "Type:" + msg_type
);
1325 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1330 _onFlush: function() {
1331 this._flushing
= false;
1332 // Resume processing
1333 if (this._sock
.rQlen() > 0) {
1334 this._handle_message();
1338 _framebufferUpdate: function () {
1342 if (this._FBU
.rects
=== 0) {
1343 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1344 this._sock
.rQskip8(); // Padding
1345 this._FBU
.rects
= this._sock
.rQshift16();
1346 this._FBU
.bytes
= 0;
1347 this._timing
.cur_fbu
= 0;
1348 if (this._timing
.fbu_rt_start
> 0) {
1349 now
= (new Date()).getTime();
1350 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1353 // Make sure the previous frame is fully rendered first
1354 // to avoid building up an excessive queue
1355 if (this._display
.pending()) {
1356 this._flushing
= true;
1357 this._display
.flush();
1362 while (this._FBU
.rects
> 0) {
1363 if (this._rfb_connection_state
!== 'connected') { return false; }
1365 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1366 if (this._FBU
.bytes
=== 0) {
1367 if (this._sock
.rQwait("rect header", 12)) { return false; }
1368 /* New FramebufferUpdate */
1370 var hdr
= this._sock
.rQshiftBytes(12);
1371 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1372 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1373 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1374 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1375 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1376 (hdr
[10] << 8) + hdr
[11], 10);
1378 if (!this._encHandlers
[this._FBU
.encoding
]) {
1379 this._fail("Unexpected server message",
1380 "Unsupported encoding " +
1381 this._FBU
.encoding
);
1386 this._timing
.last_fbu
= (new Date()).getTime();
1388 ret
= this._encHandlers
[this._FBU
.encoding
]();
1390 now
= (new Date()).getTime();
1391 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1394 if (!(this._FBU
.encoding
in this._encStats
)) {
1395 this._encStats
[this._FBU
.encoding
] = [0, 0];
1397 this._encStats
[this._FBU
.encoding
][0]++;
1398 this._encStats
[this._FBU
.encoding
][1]++;
1399 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1402 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1403 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1404 this._timing
.fbu_rt_start
> 0) {
1405 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1406 this._timing
.full_fbu_cnt
++;
1407 Log
.Info("Timing of full FBU, curr: " +
1408 this._timing
.cur_fbu
+ ", total: " +
1409 this._timing
.full_fbu_total
+ ", cnt: " +
1410 this._timing
.full_fbu_cnt
+ ", avg: " +
1411 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1414 if (this._timing
.fbu_rt_start
> 0) {
1415 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1416 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1417 this._timing
.fbu_rt_cnt
++;
1418 Log
.Info("full FBU round-trip, cur: " +
1419 fbu_rt_diff
+ ", total: " +
1420 this._timing
.fbu_rt_total
+ ", cnt: " +
1421 this._timing
.fbu_rt_cnt
+ ", avg: " +
1422 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1423 this._timing
.fbu_rt_start
= 0;
1427 if (!ret
) { return ret
; } // need more data
1430 this._display
.flip();
1432 return true; // We finished this FBU
1435 _updateContinuousUpdates: function() {
1436 if (!this._enabledContinuousUpdates
) { return; }
1438 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1439 this._fb_width
, this._fb_height
);
1442 _resize: function(width
, height
) {
1443 this._fb_width
= width
;
1444 this._fb_height
= height
;
1446 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1448 this._display
.resize(this._fb_width
, this._fb_height
);
1449 this.onfbresize(this, this._fb_width
, this._fb_height
);
1451 this._timing
.fbu_rt_start
= (new Date()).getTime();
1452 this._updateContinuousUpdates();
1455 _xvpOp: function (ver
, op
) {
1456 if (this._rfb_xvp_ver
< ver
) { return; }
1457 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
1458 RFB
.messages
.xvpOp(this._sock
, ver
, op
);
1464 keyEvent: function (sock
, keysym
, down
) {
1465 var buff
= sock
._sQ
;
1466 var offset
= sock
._sQlen
;
1468 buff
[offset
] = 4; // msg-type
1469 buff
[offset
+ 1] = down
;
1471 buff
[offset
+ 2] = 0;
1472 buff
[offset
+ 3] = 0;
1474 buff
[offset
+ 4] = (keysym
>> 24);
1475 buff
[offset
+ 5] = (keysym
>> 16);
1476 buff
[offset
+ 6] = (keysym
>> 8);
1477 buff
[offset
+ 7] = keysym
;
1483 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1484 function getRFBkeycode(xt_scancode
) {
1485 var upperByte
= (keycode
>> 8);
1486 var lowerByte
= (keycode
& 0x00ff);
1487 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1488 lowerByte
= lowerByte
| 0x80;
1494 var buff
= sock
._sQ
;
1495 var offset
= sock
._sQlen
;
1497 buff
[offset
] = 255; // msg-type
1498 buff
[offset
+ 1] = 0; // sub msg-type
1500 buff
[offset
+ 2] = (down
>> 8);
1501 buff
[offset
+ 3] = down
;
1503 buff
[offset
+ 4] = (keysym
>> 24);
1504 buff
[offset
+ 5] = (keysym
>> 16);
1505 buff
[offset
+ 6] = (keysym
>> 8);
1506 buff
[offset
+ 7] = keysym
;
1508 var RFBkeycode
= getRFBkeycode(keycode
);
1510 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1511 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1512 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1513 buff
[offset
+ 11] = RFBkeycode
;
1519 pointerEvent: function (sock
, x
, y
, mask
) {
1520 var buff
= sock
._sQ
;
1521 var offset
= sock
._sQlen
;
1523 buff
[offset
] = 5; // msg-type
1525 buff
[offset
+ 1] = mask
;
1527 buff
[offset
+ 2] = x
>> 8;
1528 buff
[offset
+ 3] = x
;
1530 buff
[offset
+ 4] = y
>> 8;
1531 buff
[offset
+ 5] = y
;
1537 // TODO(directxman12): make this unicode compatible?
1538 clientCutText: function (sock
, text
) {
1539 var buff
= sock
._sQ
;
1540 var offset
= sock
._sQlen
;
1542 buff
[offset
] = 6; // msg-type
1544 buff
[offset
+ 1] = 0; // padding
1545 buff
[offset
+ 2] = 0; // padding
1546 buff
[offset
+ 3] = 0; // padding
1548 var n
= text
.length
;
1550 buff
[offset
+ 4] = n
>> 24;
1551 buff
[offset
+ 5] = n
>> 16;
1552 buff
[offset
+ 6] = n
>> 8;
1553 buff
[offset
+ 7] = n
;
1555 for (var i
= 0; i
< n
; i
++) {
1556 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1559 sock
._sQlen
+= 8 + n
;
1563 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1564 var buff
= sock
._sQ
;
1565 var offset
= sock
._sQlen
;
1567 buff
[offset
] = 251; // msg-type
1568 buff
[offset
+ 1] = 0; // padding
1569 buff
[offset
+ 2] = width
>> 8; // width
1570 buff
[offset
+ 3] = width
;
1571 buff
[offset
+ 4] = height
>> 8; // height
1572 buff
[offset
+ 5] = height
;
1574 buff
[offset
+ 6] = 1; // number-of-screens
1575 buff
[offset
+ 7] = 0; // padding
1578 buff
[offset
+ 8] = id
>> 24; // id
1579 buff
[offset
+ 9] = id
>> 16;
1580 buff
[offset
+ 10] = id
>> 8;
1581 buff
[offset
+ 11] = id
;
1582 buff
[offset
+ 12] = 0; // x-position
1583 buff
[offset
+ 13] = 0;
1584 buff
[offset
+ 14] = 0; // y-position
1585 buff
[offset
+ 15] = 0;
1586 buff
[offset
+ 16] = width
>> 8; // width
1587 buff
[offset
+ 17] = width
;
1588 buff
[offset
+ 18] = height
>> 8; // height
1589 buff
[offset
+ 19] = height
;
1590 buff
[offset
+ 20] = flags
>> 24; // flags
1591 buff
[offset
+ 21] = flags
>> 16;
1592 buff
[offset
+ 22] = flags
>> 8;
1593 buff
[offset
+ 23] = flags
;
1599 clientFence: function (sock
, flags
, payload
) {
1600 var buff
= sock
._sQ
;
1601 var offset
= sock
._sQlen
;
1603 buff
[offset
] = 248; // msg-type
1605 buff
[offset
+ 1] = 0; // padding
1606 buff
[offset
+ 2] = 0; // padding
1607 buff
[offset
+ 3] = 0; // padding
1609 buff
[offset
+ 4] = flags
>> 24; // flags
1610 buff
[offset
+ 5] = flags
>> 16;
1611 buff
[offset
+ 6] = flags
>> 8;
1612 buff
[offset
+ 7] = flags
;
1614 var n
= payload
.length
;
1616 buff
[offset
+ 8] = n
; // length
1618 for (var i
= 0; i
< n
; i
++) {
1619 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1622 sock
._sQlen
+= 9 + n
;
1626 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1627 var buff
= sock
._sQ
;
1628 var offset
= sock
._sQlen
;
1630 buff
[offset
] = 150; // msg-type
1631 buff
[offset
+ 1] = enable
; // enable-flag
1633 buff
[offset
+ 2] = x
>> 8; // x
1634 buff
[offset
+ 3] = x
;
1635 buff
[offset
+ 4] = y
>> 8; // y
1636 buff
[offset
+ 5] = y
;
1637 buff
[offset
+ 6] = width
>> 8; // width
1638 buff
[offset
+ 7] = width
;
1639 buff
[offset
+ 8] = height
>> 8; // height
1640 buff
[offset
+ 9] = height
;
1646 pixelFormat: function (sock
, depth
, true_color
) {
1647 var buff
= sock
._sQ
;
1648 var offset
= sock
._sQlen
;
1654 } else if (depth
> 8) {
1660 bits
= Math
.floor(depth
/3);
1662 buff
[offset
] = 0; // msg-type
1664 buff
[offset
+ 1] = 0; // padding
1665 buff
[offset
+ 2] = 0; // padding
1666 buff
[offset
+ 3] = 0; // padding
1668 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1669 buff
[offset
+ 5] = depth
; // depth
1670 buff
[offset
+ 6] = 0; // little-endian
1671 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1673 buff
[offset
+ 8] = 0; // red-max
1674 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1676 buff
[offset
+ 10] = 0; // green-max
1677 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1679 buff
[offset
+ 12] = 0; // blue-max
1680 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1682 buff
[offset
+ 14] = bits
* 2; // red-shift
1683 buff
[offset
+ 15] = bits
* 1; // green-shift
1684 buff
[offset
+ 16] = bits
* 0; // blue-shift
1686 buff
[offset
+ 17] = 0; // padding
1687 buff
[offset
+ 18] = 0; // padding
1688 buff
[offset
+ 19] = 0; // padding
1694 clientEncodings: function (sock
, encodings
) {
1695 var buff
= sock
._sQ
;
1696 var offset
= sock
._sQlen
;
1698 buff
[offset
] = 2; // msg-type
1699 buff
[offset
+ 1] = 0; // padding
1701 buff
[offset
+ 2] = encodings
.length
>> 8;
1702 buff
[offset
+ 3] = encodings
.length
;
1704 var i
, j
= offset
+ 4;
1705 for (i
= 0; i
< encodings
.length
; i
++) {
1706 var enc
= encodings
[i
];
1707 buff
[j
] = enc
>> 24;
1708 buff
[j
+ 1] = enc
>> 16;
1709 buff
[j
+ 2] = enc
>> 8;
1715 sock
._sQlen
+= j
- offset
;
1719 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1720 var buff
= sock
._sQ
;
1721 var offset
= sock
._sQlen
;
1723 if (typeof(x
) === "undefined") { x
= 0; }
1724 if (typeof(y
) === "undefined") { y
= 0; }
1726 buff
[offset
] = 3; // msg-type
1727 buff
[offset
+ 1] = incremental
? 1 : 0;
1729 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1730 buff
[offset
+ 3] = x
& 0xFF;
1732 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1733 buff
[offset
+ 5] = y
& 0xFF;
1735 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1736 buff
[offset
+ 7] = w
& 0xFF;
1738 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1739 buff
[offset
+ 9] = h
& 0xFF;
1745 xvpOp: function (sock
, ver
, op
) {
1746 var buff
= sock
._sQ
;
1747 var offset
= sock
._sQlen
;
1749 buff
[offset
] = 250; // msg-type
1750 buff
[offset
+ 1] = 0; // padding
1752 buff
[offset
+ 2] = ver
;
1753 buff
[offset
+ 3] = op
;
1760 RFB
.genDES = function (password
, challenge
) {
1762 for (var i
= 0; i
< password
.length
; i
++) {
1763 passwd
.push(password
.charCodeAt(i
));
1765 return (new DES(passwd
)).encrypt(challenge
);
1768 RFB
.encodingHandlers
= {
1770 if (this._FBU
.lines
=== 0) {
1771 this._FBU
.lines
= this._FBU
.height
;
1774 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1775 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1776 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1777 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1778 var curr_height
= Math
.min(this._FBU
.lines
,
1779 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1780 var data
= this._sock
.get_rQ();
1781 var index
= this._sock
.get_rQi();
1782 if (this._fb_depth
== 8) {
1783 var pixels
= this._FBU
.width
* curr_height
1784 var newdata
= new Uint8Array(pixels
* 4);
1786 for (i
= 0;i
< pixels
;i
++) {
1787 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1788 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1789 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1790 newdata
[i
* 4 + 4] = 0;
1795 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1796 curr_height
, data
, index
);
1797 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1798 this._FBU
.lines
-= curr_height
;
1800 if (this._FBU
.lines
> 0) {
1801 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1804 this._FBU
.bytes
= 0;
1810 COPYRECT: function () {
1811 this._FBU
.bytes
= 4;
1812 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1813 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1814 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1818 this._FBU
.bytes
= 0;
1824 if (this._FBU
.subrects
=== 0) {
1825 this._FBU
.bytes
= 4 + 4;
1826 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1827 this._FBU
.subrects
= this._sock
.rQshift32();
1828 color
= this._sock
.rQshiftBytes(4); // Background
1829 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1832 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1833 color
= this._sock
.rQshiftBytes(4);
1834 var x
= this._sock
.rQshift16();
1835 var y
= this._sock
.rQshift16();
1836 var width
= this._sock
.rQshift16();
1837 var height
= this._sock
.rQshift16();
1838 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1839 this._FBU
.subrects
--;
1842 if (this._FBU
.subrects
> 0) {
1843 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1844 this._FBU
.bytes
= (4 + 8) * chunk
;
1847 this._FBU
.bytes
= 0;
1853 HEXTILE: function () {
1854 var rQ
= this._sock
.get_rQ();
1855 var rQi
= this._sock
.get_rQi();
1857 if (this._FBU
.tiles
=== 0) {
1858 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1859 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1860 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1861 this._FBU
.tiles
= this._FBU
.total_tiles
;
1864 while (this._FBU
.tiles
> 0) {
1865 this._FBU
.bytes
= 1;
1866 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1867 var subencoding
= rQ
[rQi
]; // Peek
1868 if (subencoding
> 30) { // Raw
1869 this._fail("Unexpected server message",
1870 "Illegal hextile subencoding: " + subencoding
);
1875 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1876 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1877 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1878 var x
= this._FBU
.x
+ tile_x
* 16;
1879 var y
= this._FBU
.y
+ tile_y
* 16;
1880 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1881 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1883 // Figure out how much we are expecting
1884 if (subencoding
& 0x01) { // Raw
1885 this._FBU
.bytes
+= w
* h
* 4;
1887 if (subencoding
& 0x02) { // Background
1888 this._FBU
.bytes
+= 4;
1890 if (subencoding
& 0x04) { // Foreground
1891 this._FBU
.bytes
+= 4;
1893 if (subencoding
& 0x08) { // AnySubrects
1894 this._FBU
.bytes
++; // Since we aren't shifting it off
1895 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1896 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1897 if (subencoding
& 0x10) { // SubrectsColoured
1898 this._FBU
.bytes
+= subrects
* (4 + 2);
1900 this._FBU
.bytes
+= subrects
* 2;
1905 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1907 // We know the encoding and have a whole tile
1908 this._FBU
.subencoding
= rQ
[rQi
];
1910 if (this._FBU
.subencoding
=== 0) {
1911 if (this._FBU
.lastsubencoding
& 0x01) {
1912 // Weird: ignore blanks are RAW
1913 Log
.Debug(" Ignoring blank after RAW");
1915 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1917 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1918 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1919 rQi
+= this._FBU
.bytes
- 1;
1921 if (this._FBU
.subencoding
& 0x02) { // Background
1922 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1925 if (this._FBU
.subencoding
& 0x04) { // Foreground
1926 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1930 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1931 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1935 for (var s
= 0; s
< subrects
; s
++) {
1937 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1938 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1941 color
= this._FBU
.foreground
;
1946 var sy
= (xy
& 0x0f);
1950 var sw
= (wh
>> 4) + 1;
1951 var sh
= (wh
& 0x0f) + 1;
1953 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1956 this._display
.finishTile();
1958 this._sock
.set_rQi(rQi
);
1959 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
1960 this._FBU
.bytes
= 0;
1964 if (this._FBU
.tiles
=== 0) {
1971 TIGHT: function () {
1972 this._FBU
.bytes
= 1; // compression-control byte
1973 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
1975 var checksum = function (data
) {
1977 for (var i
= 0; i
< data
.length
; i
++) {
1979 if (sum
> 65536) sum
-= 65536;
1984 var resetStreams
= 0;
1986 var decompress = function (data
, expected
) {
1987 for (var i
= 0; i
< 4; i
++) {
1988 if ((resetStreams
>> i
) & 1) {
1989 this._FBU
.zlibs
[i
].reset();
1990 Log
.Info("Reset zlib stream " + i
);
1994 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
1995 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
1996 /*if (uncompressed.status !== 0) {
1997 Log.Error("Invalid data in zlib stream");
2000 //return uncompressed.data;
2001 return uncompressed
;
2004 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2005 // Convert indexed (palette based) image data to RGB
2006 // TODO: reduce number of calculations inside loop
2007 var dest
= this._destBuff
;
2008 var w
= Math
.floor((width
+ 7) / 8);
2009 var w1
= Math
.floor(width
/ 8);
2011 /*for (var y = 0; y < height; y++) {
2013 var yoffset = y * width;
2014 var ybitoffset = y * w;
2015 var xoffset, targetbyte;
2016 for (x = 0; x < w1; x++) {
2017 xoffset = yoffset + x * 8;
2018 targetbyte = data[ybitoffset + x];
2019 for (b = 7; b >= 0; b--) {
2020 dp = (xoffset + 7 - b) * 3;
2021 sp = (targetbyte >> b & 1) * 3;
2022 dest[dp] = palette[sp];
2023 dest[dp + 1] = palette[sp + 1];
2024 dest[dp + 2] = palette[sp + 2];
2028 xoffset = yoffset + x * 8;
2029 targetbyte = data[ybitoffset + x];
2030 for (b = 7; b >= 8 - width % 8; b--) {
2031 dp = (xoffset + 7 - b) * 3;
2032 sp = (targetbyte >> b & 1) * 3;
2033 dest[dp] = palette[sp];
2034 dest[dp + 1] = palette[sp + 1];
2035 dest[dp + 2] = palette[sp + 2];
2039 for (var y
= 0; y
< height
; y
++) {
2041 for (x
= 0; x
< w1
; x
++) {
2042 for (b
= 7; b
>= 0; b
--) {
2043 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2044 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2045 dest
[dp
] = palette
[sp
];
2046 dest
[dp
+ 1] = palette
[sp
+ 1];
2047 dest
[dp
+ 2] = palette
[sp
+ 2];
2052 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2053 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2054 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2055 dest
[dp
] = palette
[sp
];
2056 dest
[dp
+ 1] = palette
[sp
+ 1];
2057 dest
[dp
+ 2] = palette
[sp
+ 2];
2065 var indexedToRGBX = function (data
, palette
, width
, height
) {
2066 // Convert indexed (palette based) image data to RGB
2067 var dest
= this._destBuff
;
2068 var total
= width
* height
* 4;
2069 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2070 var sp
= data
[j
] * 3;
2071 dest
[i
] = palette
[sp
];
2072 dest
[i
+ 1] = palette
[sp
+ 1];
2073 dest
[i
+ 2] = palette
[sp
+ 2];
2080 var rQi
= this._sock
.get_rQi();
2081 var rQ
= this._sock
.rQwhole();
2083 var cl_header
, cl_data
;
2085 var handlePalette = function () {
2086 var numColors
= rQ
[rQi
+ 2] + 1;
2087 var paletteSize
= numColors
* 3;
2088 this._FBU
.bytes
+= paletteSize
;
2089 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2091 var bpp
= (numColors
<= 2) ? 1 : 8;
2092 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2094 if (rowSize
* this._FBU
.height
< 12) {
2097 cl_data
= rowSize
* this._FBU
.height
;
2098 //clength = [0, rowSize * this._FBU.height];
2100 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2101 var cl_offset
= rQi
+ 3 + paletteSize
;
2104 cl_data
+= rQ
[cl_offset
] & 0x7f;
2105 if (rQ
[cl_offset
] & 0x80) {
2107 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2108 if (rQ
[cl_offset
+ 1] & 0x80) {
2110 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2113 // end inline getTightCLength
2116 this._FBU
.bytes
+= cl_header
+ cl_data
;
2117 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2119 // Shift ctl, filter id, num colors, palette entries, and clength off
2120 this._sock
.rQskipBytes(3);
2121 //var palette = this._sock.rQshiftBytes(paletteSize);
2122 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2123 this._sock
.rQskipBytes(cl_header
);
2126 data
= this._sock
.rQshiftBytes(cl_data
);
2128 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2131 // Convert indexed (palette based) image data to RGB
2133 if (numColors
== 2) {
2134 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2135 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2137 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2138 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2145 var handleCopy = function () {
2147 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2148 if (uncompressedSize
< 12) {
2151 cl_data
= uncompressedSize
;
2153 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2154 var cl_offset
= rQi
+ 1;
2157 cl_data
+= rQ
[cl_offset
] & 0x7f;
2158 if (rQ
[cl_offset
] & 0x80) {
2160 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2161 if (rQ
[cl_offset
+ 1] & 0x80) {
2163 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2166 // end inline getTightCLength
2168 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2169 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2171 // Shift ctl, clength off
2172 this._sock
.rQshiftBytes(1 + cl_header
);
2175 data
= this._sock
.rQshiftBytes(cl_data
);
2177 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2180 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2185 var ctl
= this._sock
.rQpeek8();
2187 // Keep tight reset bits
2188 resetStreams
= ctl
& 0xF;
2190 // Figure out filter
2192 streamId
= ctl
& 0x3;
2194 if (ctl
=== 0x08) cmode
= "fill";
2195 else if (ctl
=== 0x09) cmode
= "jpeg";
2196 else if (ctl
=== 0x0A) cmode
= "png";
2197 else if (ctl
& 0x04) cmode
= "filter";
2198 else if (ctl
< 0x04) cmode
= "copy";
2199 else return this._fail("Unexpected server message",
2200 "Illegal tight compression received, " +
2204 // fill use depth because TPIXELs drop the padding byte
2205 case "fill": // TPIXEL
2206 this._FBU
.bytes
+= 3;
2208 case "jpeg": // max clength
2209 this._FBU
.bytes
+= 3;
2211 case "png": // max clength
2212 this._FBU
.bytes
+= 3;
2214 case "filter": // filter id + num colors if palette
2215 this._FBU
.bytes
+= 2;
2221 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2223 // Determine FBU.bytes
2227 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);
2228 this._sock
.rQskipBytes(4);
2232 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2233 var cl_offset
= rQi
+ 1;
2236 cl_data
+= rQ
[cl_offset
] & 0x7f;
2237 if (rQ
[cl_offset
] & 0x80) {
2239 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2240 if (rQ
[cl_offset
+ 1] & 0x80) {
2242 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2245 // end inline getTightCLength
2246 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2247 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2249 // We have everything, render it
2250 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2251 data
= this._sock
.rQshiftBytes(cl_data
);
2252 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2255 var filterId
= rQ
[rQi
+ 1];
2256 if (filterId
=== 1) {
2257 if (!handlePalette()) { return false; }
2259 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2260 // Filter 2, Gradient is valid but not use if jpeg is enabled
2261 this._fail("Unexpected server message",
2262 "Unsupported tight subencoding received, " +
2263 "filter: " + filterId
);
2267 if (!handleCopy()) { return false; }
2272 this._FBU
.bytes
= 0;
2278 last_rect: function () {
2279 this._FBU
.rects
= 0;
2283 ExtendedDesktopSize: function () {
2284 this._FBU
.bytes
= 1;
2285 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2287 this._supportsSetDesktopSize
= true;
2288 this._setCapability("resize", true);
2290 var number_of_screens
= this._sock
.rQpeek8();
2292 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2293 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2295 this._sock
.rQskipBytes(1); // number-of-screens
2296 this._sock
.rQskipBytes(3); // padding
2298 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2299 // Save the id and flags of the first screen
2301 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2302 this._sock
.rQskipBytes(2); // x-position
2303 this._sock
.rQskipBytes(2); // y-position
2304 this._sock
.rQskipBytes(2); // width
2305 this._sock
.rQskipBytes(2); // height
2306 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2308 this._sock
.rQskipBytes(16);
2313 * The x-position indicates the reason for the change:
2315 * 0 - server resized on its own
2316 * 1 - this client requested the resize
2317 * 2 - another client requested the resize
2320 // We need to handle errors when we requested the resize.
2321 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2323 // The y-position indicates the status code from the server
2324 switch (this._FBU
.y
) {
2326 msg
= "Resize is administratively prohibited";
2329 msg
= "Out of resources";
2332 msg
= "Invalid screen layout";
2335 msg
= "Unknown reason";
2338 this._notification("Server did not accept the resize request: "
2341 this._resize(this._FBU
.width
, this._FBU
.height
);
2344 this._FBU
.bytes
= 0;
2345 this._FBU
.rects
-= 1;
2349 DesktopSize: function () {
2350 this._resize(this._FBU
.width
, this._FBU
.height
);
2351 this._FBU
.bytes
= 0;
2352 this._FBU
.rects
-= 1;
2356 Cursor: function () {
2357 Log
.Debug(">> set_cursor");
2358 var x
= this._FBU
.x
; // hotspot-x
2359 var y
= this._FBU
.y
; // hotspot-y
2360 var w
= this._FBU
.width
;
2361 var h
= this._FBU
.height
;
2363 var pixelslength
= w
* h
* 4;
2364 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2366 this._FBU
.bytes
= pixelslength
+ masklength
;
2367 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2369 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2370 this._sock
.rQshiftBytes(masklength
),
2373 this._FBU
.bytes
= 0;
2376 Log
.Debug("<< set_cursor");
2380 QEMUExtendedKeyEvent: function () {
2383 // Old Safari doesn't support creating keyboard events
2385 var keyboardEvent
= document
.createEvent("keyboardEvent");
2386 if (keyboardEvent
.code
!== undefined) {
2387 this._qemuExtKeyEventSupported
= true;