2 * noVNC: HTML5 VNC client
3 * Copyright (C) 2012 Joel Martin
4 * Copyright (C) 2016 Samuel Mannehed for Cendio AB
5 * Licensed under MPL 2.0 (see LICENSE.txt)
7 * See README.md for usage and integration instructions.
9 * TIGHT decoder portion:
10 * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca)
13 import * as Log
from './util/logging.js';
14 import _
from './util/localization.js';
15 import { decodeUTF8
} from './util/strings.js';
16 import { set_defaults
, make_properties
} from './util/properties.js';
17 import { browserSupportsCursorURIs
} from './util/browsers.js';
18 import Display
from "./display.js";
19 import Keyboard
from "./input/keyboard.js";
20 import Mouse
from "./input/mouse.js";
21 import Websock
from "./websock.js";
22 import Base64
from "./base64.js";
23 import DES
from "./des.js";
24 import KeyTable
from "./input/keysym.js";
25 import XtScancode
from "./input/xtscancodes.js";
26 import Inflator
from "./inflator.js";
27 import { encodings
, encodingName
} from "./encodings.js";
29 /*jslint white: false, browser: true */
30 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
32 export default function RFB(target
, defaults
) {
37 this._target
= target
;
41 this._rfb_credentials
= {};
44 this._rfb_connection_state
= '';
45 this._rfb_init_state
= '';
46 this._rfb_auth_scheme
= '';
47 this._rfb_disconnect_reason
= "";
49 // Server capabilities
50 this._rfb_version
= 0;
51 this._rfb_max_version
= 3.8;
52 this._rfb_tightvnc
= false;
53 this._rfb_xvp_ver
= 0;
60 this._capabilities
= { power
: false, resize
: false };
62 this._supportsFence
= false;
64 this._supportsContinuousUpdates
= false;
65 this._enabledContinuousUpdates
= false;
67 this._supportsSetDesktopSize
= false;
69 this._screen_flags
= 0;
71 this._qemuExtKeyEventSupported
= false;
74 this._sock
= null; // Websock object
75 this._display
= null; // Display object
76 this._flushing
= false; // Display flushing state
77 this._keyboard
= null; // Keyboard input handler object
78 this._mouse
= null; // Mouse input handler object
81 this._disconnTimer
= null; // disconnection timer
83 // Decoder states and stats
84 this._encHandlers
= {};
89 subrects
: 0, // RRE and HEXTILE
100 zlibs
: [] // TIGHT zlib streams
102 for (var i
= 0; i
< 4; i
++) {
103 this._FBU
.zlibs
[i
] = new Inflator();
106 this._destBuff
= null;
107 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
109 this._rre_chunk_sz
= 100;
125 this._mouse_buttonMask
= 0;
126 this._mouse_arr
= [];
127 this._viewportDragging
= false;
128 this._viewportDragPos
= {};
129 this._viewportHasMoved
= false;
131 // set the default value on user-facing properties
132 set_defaults(this, defaults
, {
133 'local_cursor': false, // Request locally rendered cursor
134 'view_only': false, // Disable client mouse/keyboard
135 'disconnectTimeout': 3, // Time (s) to wait for disconnection
136 'viewportDrag': false, // Move the viewport on mouse drags
138 // Callback functions
139 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
140 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
141 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
142 'onCredentialsRequired': function () { }, // onCredentialsRequired(rfb, types): VNC credentials are required
143 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
144 'onBell': function () { }, // onBell(rfb): RFB Bell message received
145 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
146 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
147 'onCapabilities': function () { } // onCapabilities(rfb, caps): the supported capabilities has changed
151 Log
.Debug(">> RFB.constructor");
153 // Target canvas must be able to have focus
154 if (!this._target
.hasAttribute('tabindex')) {
155 this._target
.tabIndex
= -1;
158 // populate encHandlers with bound versions
159 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this);
160 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this);
161 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this);
162 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this);
163 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this);
165 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this);
166 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this);
167 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this);
168 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this);
169 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this);
171 // NB: nothing that needs explicit teardown should be done
172 // before this point, since this can throw an exception
174 this._display
= new Display(this._target
,
175 {onFlush
: this._onFlush
.bind(this)});
177 Log
.Error("Display exception: " + exc
);
180 this._display
.clear();
182 this._keyboard
= new Keyboard(this._target
,
183 {onKeyEvent
: this._handleKeyEvent
.bind(this)});
185 this._mouse
= new Mouse(this._target
,
186 {onMouseButton
: this._handleMouseButton
.bind(this),
187 onMouseMove
: this._handleMouseMove
.bind(this)});
189 this._sock
= new Websock();
190 this._sock
.on('message', this._handle_message
.bind(this));
191 this._sock
.on('open', function () {
192 if ((this._rfb_connection_state
=== 'connecting') &&
193 (this._rfb_init_state
=== '')) {
194 this._rfb_init_state
= 'ProtocolVersion';
195 Log
.Debug("Starting VNC handshake");
197 this._fail("Unexpected server connection");
200 this._sock
.on('close', function (e
) {
201 Log
.Warn("WebSocket on-close event");
204 msg
= " (code: " + e
.code
;
206 msg
+= ", reason: " + e
.reason
;
210 switch (this._rfb_connection_state
) {
211 case 'disconnecting':
212 this._updateConnectionState('disconnected');
215 this._fail('Failed to connect to server', msg
);
218 // Handle disconnects that were initiated server-side
219 this._updateConnectionState('disconnecting');
220 this._updateConnectionState('disconnected');
223 this._fail("Unexpected server disconnect",
224 "Already disconnected: " + msg
);
227 this._fail("Unexpected server disconnect",
228 "Not in any state yet: " + msg
);
231 this._sock
.off('close');
233 this._sock
.on('error', function (e
) {
234 Log
.Warn("WebSocket on-error event");
237 Log
.Debug("<< RFB.constructor");
242 connect: function (url
, options
) {
244 this._fail(_("Must specify URL"));
250 options
= options
|| {}
252 this._rfb_credentials
= options
.credentials
|| {};
253 this._shared
= 'shared' in options
? !!options
.shared
: true;
254 this._repeaterID
= options
.repeaterID
|| '';
256 this._rfb_init_state
= '';
257 this._updateConnectionState('connecting');
261 disconnect: function () {
262 this._updateConnectionState('disconnecting');
263 this._sock
.off('error');
264 this._sock
.off('message');
265 this._sock
.off('open');
268 sendCredentials: function (creds
) {
269 this._rfb_credentials
= creds
;
270 setTimeout(this._init_msg
.bind(this), 0);
273 sendCtrlAltDel: function () {
274 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
275 Log
.Info("Sending Ctrl-Alt-Del");
277 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
278 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
279 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
280 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
281 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
282 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
287 machineShutdown: function () {
291 machineReboot: function () {
295 machineReset: function () {
299 // Send a key press. If 'down' is not specified then send a down key
300 // followed by an up key.
301 sendKey: function (keysym
, code
, down
) {
302 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return false; }
304 if (down
=== undefined) {
305 this.sendKey(keysym
, code
, true);
306 this.sendKey(keysym
, code
, false);
310 var scancode
= XtScancode
[code
];
312 if (this._qemuExtKeyEventSupported
&& scancode
) {
314 keysym
= keysym
|| 0;
316 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
318 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
323 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
324 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
330 clipboardPasteFrom: function (text
) {
331 if (this._rfb_connection_state
!== 'connected' || this._view_only
) { return; }
332 RFB
.messages
.clientCutText(this._sock
, text
);
335 autoscale: function (width
, height
, downscaleOnly
) {
336 if (this._rfb_connection_state
!== 'connected') { return; }
337 this._display
.autoscale(width
, height
, downscaleOnly
);
340 viewportChangeSize: function(width
, height
) {
341 if (this._rfb_connection_state
!== 'connected') { return; }
342 this._display
.viewportChangeSize(width
, height
);
345 clippingDisplay: function () {
346 if (this._rfb_connection_state
!== 'connected') { return false; }
347 return this._display
.clippingDisplay();
350 // Requests a change of remote desktop size. This message is an extension
351 // and may only be sent if we have received an ExtendedDesktopSize message
352 requestDesktopSize: function (width
, height
) {
353 if (this._rfb_connection_state
!== 'connected' ||
358 if (this._supportsSetDesktopSize
) {
359 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
360 this._screen_id
, this._screen_flags
);
371 _connect: function () {
372 Log
.Debug(">> RFB.connect");
374 Log
.Info("connecting to " + this._url
);
377 // WebSocket.onopen transitions to the RFB init states
378 this._sock
.open(this._url
, ['binary']);
380 if (e
.name
=== 'SyntaxError') {
381 this._fail("Invalid host or port value given", e
);
383 this._fail("Error while connecting", e
);
387 // Always grab focus on some kind of click event
388 this._target
.addEventListener("mousedown", this._focusCanvas
);
389 this._target
.addEventListener("touchstart", this._focusCanvas
);
391 Log
.Debug("<< RFB.connect");
394 _disconnect: function () {
395 Log
.Debug(">> RFB.disconnect");
396 this._target
.removeEventListener("mousedown", this._focusCanvas
);
397 this._target
.removeEventListener("touchstart", this._focusCanvas
);
401 Log
.Debug("<< RFB.disconnect");
404 _print_stats: function () {
405 var stats
= this._encStats
;
407 Log
.Info("Encoding stats for this connection:");
408 Object
.keys(stats
).forEach(function (key
) {
410 if (s
[0] + s
[1] > 0) {
411 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
415 Log
.Info("Encoding stats since page load:");
416 Object
.keys(stats
).forEach(function (key
) {
418 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
422 _cleanup: function () {
423 if (!this._view_only
) { this._keyboard
.ungrab(); }
424 if (!this._view_only
) { this._mouse
.ungrab(); }
425 this._display
.defaultCursor();
426 if (Log
.get_logging() !== 'debug') {
427 // Show noVNC logo when disconnected, unless in
429 this._display
.clear();
433 // Event handler for canvas so this points to the canvas element
434 _focusCanvas: function(event
) {
435 // Respect earlier handlers' request to not do side-effects
436 if (!event
.defaultPrevented
)
445 * disconnected - permanent state
447 _updateConnectionState: function (state
) {
448 var oldstate
= this._rfb_connection_state
;
450 if (state
=== oldstate
) {
451 Log
.Debug("Already in state '" + state
+ "', ignoring");
455 // The 'disconnected' state is permanent for each RFB object
456 if (oldstate
=== 'disconnected') {
457 Log
.Error("Tried changing state of a disconnected RFB object");
461 // Ensure proper transitions before doing anything
464 if (oldstate
!== 'connecting') {
465 Log
.Error("Bad transition to connected state, " +
466 "previous connection state: " + oldstate
);
472 if (oldstate
!== 'disconnecting') {
473 Log
.Error("Bad transition to disconnected state, " +
474 "previous connection state: " + oldstate
);
480 if (oldstate
!== '') {
481 Log
.Error("Bad transition to connecting state, " +
482 "previous connection state: " + oldstate
);
487 case 'disconnecting':
488 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
489 Log
.Error("Bad transition to disconnecting state, " +
490 "previous connection state: " + oldstate
);
496 Log
.Error("Unknown connection state: " + state
);
500 // State change actions
502 this._rfb_connection_state
= state
;
503 this._onUpdateState(this, state
, oldstate
);
505 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
508 if (this._disconnTimer
&& state
!== 'disconnecting') {
509 Log
.Debug("Clearing disconnect timer");
510 clearTimeout(this._disconnTimer
);
511 this._disconnTimer
= null;
513 // make sure we don't get a double event
514 this._sock
.off('close');
519 // Call onDisconnected callback after onUpdateState since
520 // we don't know if the UI only displays the latest message
521 if (this._rfb_disconnect_reason
!== "") {
522 this._onDisconnected(this, this._rfb_disconnect_reason
);
524 // No reason means clean disconnect
525 this._onDisconnected(this);
533 case 'disconnecting':
536 this._disconnTimer
= setTimeout(function () {
537 this._rfb_disconnect_reason
= _("Disconnect timeout");
538 this._updateConnectionState('disconnected');
539 }.bind(this), this._disconnectTimeout
* 1000);
544 /* Print errors and disconnect
546 * The optional parameter 'details' is used for information that
547 * should be logged but not sent to the user interface.
549 _fail: function (msg
, details
) {
551 if (typeof details
!== 'undefined') {
552 fullmsg
= msg
+ " (" + details
+ ")";
554 switch (this._rfb_connection_state
) {
555 case 'disconnecting':
556 Log
.Error("Failed when disconnecting: " + fullmsg
);
559 Log
.Error("Failed while connected: " + fullmsg
);
562 Log
.Error("Failed when connecting: " + fullmsg
);
565 Log
.Error("RFB failure: " + fullmsg
);
568 this._rfb_disconnect_reason
= msg
; //This is sent to the UI
570 // Transition to disconnected without waiting for socket to close
571 this._updateConnectionState('disconnecting');
572 this._updateConnectionState('disconnected');
578 * Send a notification to the UI. Valid levels are:
579 * 'normal'|'warn'|'error'
581 * NOTE: Options could be added in the future.
582 * NOTE: If this function is called multiple times, remember that the
583 * interface could be only showing the latest notification.
585 _notification: function(msg
, level
, options
) {
590 Log
.Debug("Notification[" + level
+ "]:" + msg
);
593 Log
.Error("Invalid notification level: " + level
);
598 this._onNotification(this, msg
, level
, options
);
600 this._onNotification(this, msg
, level
);
604 _setCapability: function (cap
, val
) {
605 this._capabilities
[cap
] = val
;
606 this._onCapabilities(this, this._capabilities
);
609 _handle_message: function () {
610 if (this._sock
.rQlen() === 0) {
611 Log
.Warn("handle_message called on an empty receive queue");
615 switch (this._rfb_connection_state
) {
617 Log
.Error("Got data while disconnected");
621 if (this._flushing
) {
624 if (!this._normal_msg()) {
627 if (this._sock
.rQlen() === 0) {
638 _handleKeyEvent: function (keysym
, code
, down
) {
639 this.sendKey(keysym
, code
, down
);
642 _handleMouseButton: function (x
, y
, down
, bmask
) {
644 this._mouse_buttonMask
|= bmask
;
646 this._mouse_buttonMask
&= ~bmask
;
649 if (this._viewportDrag
) {
650 if (down
&& !this._viewportDragging
) {
651 this._viewportDragging
= true;
652 this._viewportDragPos
= {'x': x
, 'y': y
};
654 // Skip sending mouse events
657 this._viewportDragging
= false;
659 // If the viewport didn't actually move, then treat as a mouse click event
660 // Send the button down event here, as the button up event is sent at the end of this function
661 if (!this._viewportHasMoved
&& !this._view_only
) {
662 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
664 this._viewportHasMoved
= false;
668 if (this._view_only
) { return; } // View only, skip mouse events
670 if (this._rfb_connection_state
!== 'connected') { return; }
671 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
674 _handleMouseMove: function (x
, y
) {
675 if (this._viewportDragging
) {
676 var deltaX
= this._viewportDragPos
.x
- x
;
677 var deltaY
= this._viewportDragPos
.y
- y
;
679 // The goal is to trigger on a certain physical width, the
680 // devicePixelRatio brings us a bit closer but is not optimal.
681 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
683 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
684 Math
.abs(deltaY
) > dragThreshold
)) {
685 this._viewportHasMoved
= true;
687 this._viewportDragPos
= {'x': x
, 'y': y
};
688 this._display
.viewportChangePos(deltaX
, deltaY
);
691 // Skip sending mouse events
695 if (this._view_only
) { return; } // View only, skip mouse events
697 if (this._rfb_connection_state
!== 'connected') { return; }
698 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
703 _negotiate_protocol_version: function () {
704 if (this._sock
.rQlen() < 12) {
705 return this._fail("Error while negotiating with server",
706 "Incomplete protocol version");
709 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
710 Log
.Info("Server ProtocolVersion: " + sversion
);
713 case "000.000": // UltraVNC repeater
717 case "003.006": // UltraVNC
718 case "003.889": // Apple Remote Desktop
719 this._rfb_version
= 3.3;
722 this._rfb_version
= 3.7;
725 case "004.000": // Intel AMT KVM
726 case "004.001": // RealVNC 4.6
727 case "005.000": // RealVNC 5.3
728 this._rfb_version
= 3.8;
731 return this._fail("Unsupported server",
732 "Invalid server version: " + sversion
);
736 var repeaterID
= "ID:" + this._repeaterID
;
737 while (repeaterID
.length
< 250) {
740 this._sock
.send_string(repeaterID
);
744 if (this._rfb_version
> this._rfb_max_version
) {
745 this._rfb_version
= this._rfb_max_version
;
748 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
749 ".00" + ((this._rfb_version
* 10) % 10);
750 this._sock
.send_string("RFB " + cversion
+ "\n");
751 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
753 this._rfb_init_state
= 'Security';
756 _negotiate_security: function () {
757 // Polyfill since IE and PhantomJS doesn't have
758 // TypedArray.includes()
759 function includes(item
, array
) {
760 for (var i
= 0; i
< array
.length
; i
++) {
761 if (array
[i
] === item
) {
768 if (this._rfb_version
>= 3.7) {
769 // Server sends supported list, client decides
770 var num_types
= this._sock
.rQshift8();
771 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
773 if (num_types
=== 0) {
774 var strlen
= this._sock
.rQshift32();
775 var reason
= this._sock
.rQshiftStr(strlen
);
776 return this._fail("Error while negotiating with server",
777 "Security failure: " + reason
);
780 var types
= this._sock
.rQshiftBytes(num_types
);
781 Log
.Debug("Server security types: " + types
);
783 // Look for each auth in preferred order
784 this._rfb_auth_scheme
= 0;
785 if (includes(1, types
)) {
786 this._rfb_auth_scheme
= 1; // None
787 } else if (includes(22, types
)) {
788 this._rfb_auth_scheme
= 22; // XVP
789 } else if (includes(16, types
)) {
790 this._rfb_auth_scheme
= 16; // Tight
791 } else if (includes(2, types
)) {
792 this._rfb_auth_scheme
= 2; // VNC Auth
794 return this._fail("Unsupported server",
795 "Unsupported security types: " + types
);
798 this._sock
.send([this._rfb_auth_scheme
]);
801 if (this._sock
.rQwait("security scheme", 4)) { return false; }
802 this._rfb_auth_scheme
= this._sock
.rQshift32();
805 this._rfb_init_state
= 'Authentication';
806 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
808 return this._init_msg(); // jump to authentication
812 _negotiate_xvp_auth: function () {
813 if (!this._rfb_credentials
.username
||
814 !this._rfb_credentials
.password
||
815 !this._rfb_credentials
.target
) {
816 this._onCredentialsRequired(this, ["username", "password", "target"]);
820 var xvp_auth_str
= String
.fromCharCode(this._rfb_credentials
.username
.length
) +
821 String
.fromCharCode(this._rfb_credentials
.target
.length
) +
822 this._rfb_credentials
.username
+
823 this._rfb_credentials
.target
;
824 this._sock
.send_string(xvp_auth_str
);
825 this._rfb_auth_scheme
= 2;
826 return this._negotiate_authentication();
829 _negotiate_std_vnc_auth: function () {
830 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
832 if (!this._rfb_credentials
.password
) {
833 this._onCredentialsRequired(this, ["password"]);
837 // TODO(directxman12): make genDES not require an Array
838 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
839 var response
= RFB
.genDES(this._rfb_credentials
.password
, challenge
);
840 this._sock
.send(response
);
841 this._rfb_init_state
= "SecurityResult";
845 _negotiate_tight_tunnels: function (numTunnels
) {
846 var clientSupportedTunnelTypes
= {
847 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
849 var serverSupportedTunnelTypes
= {};
850 // receive tunnel capabilities
851 for (var i
= 0; i
< numTunnels
; i
++) {
852 var cap_code
= this._sock
.rQshift32();
853 var cap_vendor
= this._sock
.rQshiftStr(4);
854 var cap_signature
= this._sock
.rQshiftStr(8);
855 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
858 // choose the notunnel type
859 if (serverSupportedTunnelTypes
[0]) {
860 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
861 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
862 return this._fail("Unsupported server",
863 "Client's tunnel type had the incorrect " +
864 "vendor or signature");
866 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
867 return false; // wait until we receive the sub auth count to continue
869 return this._fail("Unsupported server",
870 "Server wanted tunnels, but doesn't support " +
871 "the notunnel type");
875 _negotiate_tight_auth: function () {
876 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
877 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
878 var numTunnels
= this._sock
.rQshift32();
879 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
881 this._rfb_tightvnc
= true;
883 if (numTunnels
> 0) {
884 this._negotiate_tight_tunnels(numTunnels
);
885 return false; // wait until we receive the sub auth to continue
889 // second pass, do the sub-auth negotiation
890 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
891 var subAuthCount
= this._sock
.rQshift32();
892 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
893 this._rfb_init_state
= 'SecurityResult';
897 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
899 var clientSupportedTypes
= {
904 var serverSupportedTypes
= [];
906 for (var i
= 0; i
< subAuthCount
; i
++) {
907 var capNum
= this._sock
.rQshift32();
908 var capabilities
= this._sock
.rQshiftStr(12);
909 serverSupportedTypes
.push(capabilities
);
912 for (var authType
in clientSupportedTypes
) {
913 if (serverSupportedTypes
.indexOf(authType
) != -1) {
914 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
917 case 'STDVNOAUTH__': // no auth
918 this._rfb_init_state
= 'SecurityResult';
920 case 'STDVVNCAUTH_': // VNC auth
921 this._rfb_auth_scheme
= 2;
922 return this._init_msg();
924 return this._fail("Unsupported server",
925 "Unsupported tiny auth scheme: " +
931 return this._fail("Unsupported server",
932 "No supported sub-auth types!");
935 _negotiate_authentication: function () {
936 switch (this._rfb_auth_scheme
) {
937 case 0: // connection failed
938 if (this._sock
.rQwait("auth reason", 4)) { return false; }
939 var strlen
= this._sock
.rQshift32();
940 var reason
= this._sock
.rQshiftStr(strlen
);
941 return this._fail("Authentication failure", reason
);
944 if (this._rfb_version
>= 3.8) {
945 this._rfb_init_state
= 'SecurityResult';
948 this._rfb_init_state
= 'ClientInitialisation';
949 return this._init_msg();
952 return this._negotiate_xvp_auth();
954 case 2: // VNC authentication
955 return this._negotiate_std_vnc_auth();
957 case 16: // TightVNC Security Type
958 return this._negotiate_tight_auth();
961 return this._fail("Unsupported server",
962 "Unsupported auth scheme: " +
963 this._rfb_auth_scheme
);
967 _handle_security_result: function () {
968 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
969 switch (this._sock
.rQshift32()) {
971 this._rfb_init_state
= 'ClientInitialisation';
972 Log
.Debug('Authentication OK');
973 return this._init_msg();
975 if (this._rfb_version
>= 3.8) {
976 var length
= this._sock
.rQshift32();
977 if (this._sock
.rQwait("SecurityResult reason", length
, 8)) { return false; }
978 var reason
= this._sock
.rQshiftStr(length
);
979 return this._fail("Authentication failure", reason
);
981 return this._fail("Authentication failure");
984 return this._fail("Too many authentication attempts");
986 return this._fail("Unsupported server",
987 "Unknown SecurityResult");
991 _negotiate_server_init: function () {
992 if (this._sock
.rQwait("server initialization", 24)) { return false; }
995 var width
= this._sock
.rQshift16();
996 var height
= this._sock
.rQshift16();
999 var bpp
= this._sock
.rQshift8();
1000 var depth
= this._sock
.rQshift8();
1001 var big_endian
= this._sock
.rQshift8();
1002 var true_color
= this._sock
.rQshift8();
1004 var red_max
= this._sock
.rQshift16();
1005 var green_max
= this._sock
.rQshift16();
1006 var blue_max
= this._sock
.rQshift16();
1007 var red_shift
= this._sock
.rQshift8();
1008 var green_shift
= this._sock
.rQshift8();
1009 var blue_shift
= this._sock
.rQshift8();
1010 this._sock
.rQskipBytes(3); // padding
1012 // NB(directxman12): we don't want to call any callbacks or print messages until
1013 // *after* we're past the point where we could backtrack
1015 /* Connection name/title */
1016 var name_length = this._sock.rQshift32();
1017 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1018 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1020 if (this._rfb_tightvnc) {
1021 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1022 // In TightVNC mode, ServerInit message is extended
1023 var numServerMessages = this._sock.rQshift16();
1024 var numClientMessages = this._sock.rQshift16();
1025 var numEncodings = this._sock.rQshift16();
1026 this._sock.rQskipBytes(2); // padding
1028 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1029 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1031 // we don't actually do anything with the capability information that TIGHT sends,
1032 // so we just skip the all of this.
1034 // TIGHT server message capabilities
1035 this._sock.rQskipBytes(16 * numServerMessages);
1037 // TIGHT client message capabilities
1038 this._sock.rQskipBytes(16 * numClientMessages);
1040 // TIGHT encoding capabilities
1041 this._sock.rQskipBytes(16 * numEncodings);
1044 // NB(directxman12): these are down here so that we don't run them multiple times
1046 Log.Info("Screen: " + width + "x" + height +
1047 ", bpp: " + bpp + ", depth: " + depth +
1048 ", big_endian: " + big_endian +
1049 ", true_color: " + true_color +
1050 ", red_max: " + red_max +
1051 ", green_max: " + green_max +
1052 ", blue_max: " + blue_max +
1053 ", red_shift: " + red_shift +
1054 ", green_shift: " + green_shift +
1055 ", blue_shift: " + blue_shift);
1057 if (big_endian !== 0) {
1058 Log.Warn("Server native endian is not little endian");
1061 if (red_shift !== 16) {
1062 Log.Warn("Server native red-shift is not 16");
1065 if (blue_shift !== 0) {
1066 Log.Warn("Server native blue-shift is not 0");
1069 // we're past the point where we could backtrack, so it's safe to call this
1070 this._onDesktopName(this, this._fb_name);
1072 this._resize(width, height);
1074 if (!this._view_only) { this._keyboard.grab(); }
1075 if (!this._view_only) { this._mouse.grab(); }
1077 this._fb_depth = 24;
1079 if (this._fb_name === "Intel(r) AMT KVM") {
1080 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1084 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1085 this._sendEncodings();
1086 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1088 this._timing.fbu_rt_start = (new Date()).getTime();
1089 this._timing.pixels = 0;
1091 // Cursor will be server side until the server decides to honor
1092 // our request and send over the cursor image
1093 this._display.disableLocalCursor();
1095 this._updateConnectionState('connected');
1099 _sendEncodings: function () {
1102 // In preference order
1103 encs.push(encodings.encodingCopyRect);
1104 // Only supported with full depth support
1105 if (this._fb_depth == 24) {
1106 encs.push(encodings.encodingTight);
1107 encs.push(encodings.encodingHextile);
1108 encs.push(encodings.encodingRRE);
1110 encs.push(encodings.encodingRaw);
1112 // Psuedo-encoding settings
1113 encs.push(encodings.pseudoEncodingTightPNG);
1114 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1115 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1117 encs.push(encodings.pseudoEncodingDesktopSize);
1118 encs.push(encodings.pseudoEncodingLastRect);
1119 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1120 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1121 encs.push(encodings.pseudoEncodingXvp);
1122 encs.push(encodings.pseudoEncodingFence);
1123 encs.push(encodings.pseudoEncodingContinuousUpdates);
1125 if (this._local_cursor && this._fb_depth == 24) {
1126 encs.push(encodings.pseudoEncodingCursor);
1129 RFB.messages.clientEncodings(this._sock, encs);
1132 /* RFB protocol initialization states:
1137 * ClientInitialization - not triggered by server message
1138 * ServerInitialization
1140 _init_msg: function () {
1141 switch (this._rfb_init_state
) {
1142 case 'ProtocolVersion':
1143 return this._negotiate_protocol_version();
1146 return this._negotiate_security();
1148 case 'Authentication':
1149 return this._negotiate_authentication();
1151 case 'SecurityResult':
1152 return this._handle_security_result();
1154 case 'ClientInitialisation':
1155 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1156 this._rfb_init_state
= 'ServerInitialisation';
1159 case 'ServerInitialisation':
1160 return this._negotiate_server_init();
1163 return this._fail("Internal error", "Unknown init state: " +
1164 this._rfb_init_state
);
1168 _handle_set_colour_map_msg: function () {
1169 Log
.Debug("SetColorMapEntries");
1171 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
1174 _handle_server_cut_text: function () {
1175 Log
.Debug("ServerCutText");
1177 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1178 this._sock
.rQskipBytes(3); // Padding
1179 var length
= this._sock
.rQshift32();
1180 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1182 var text
= this._sock
.rQshiftStr(length
);
1184 if (this._view_only
) { return true; }
1186 this._onClipboard(this, text
);
1191 _handle_server_fence_msg: function() {
1192 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1193 this._sock
.rQskipBytes(3); // Padding
1194 var flags
= this._sock
.rQshift32();
1195 var length
= this._sock
.rQshift8();
1197 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1200 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1204 var payload
= this._sock
.rQshiftStr(length
);
1206 this._supportsFence
= true;
1211 * (1<<0) - BlockBefore
1212 * (1<<1) - BlockAfter
1217 if (!(flags
& (1<<31))) {
1218 return this._fail("Internal error",
1219 "Unexpected fence response");
1222 // Filter out unsupported flags
1223 // FIXME: support syncNext
1224 flags
&= (1<<0) | (1<<1);
1226 // BlockBefore and BlockAfter are automatically handled by
1227 // the fact that we process each incoming message
1229 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1234 _handle_xvp_msg: function () {
1235 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1236 this._sock
.rQskip8(); // Padding
1237 var xvp_ver
= this._sock
.rQshift8();
1238 var xvp_msg
= this._sock
.rQshift8();
1242 Log
.Error("Operation Failed");
1243 this._notification("XVP Operation Failed", 'error');
1246 this._rfb_xvp_ver
= xvp_ver
;
1247 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1248 this._setCapability("power", true);
1251 this._fail("Unexpected server message",
1252 "Illegal server XVP message " + xvp_msg
);
1259 _normal_msg: function () {
1262 if (this._FBU
.rects
> 0) {
1265 msg_type
= this._sock
.rQshift8();
1269 case 0: // FramebufferUpdate
1270 var ret
= this._framebufferUpdate();
1271 if (ret
&& !this._enabledContinuousUpdates
) {
1272 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1273 this._fb_width
, this._fb_height
);
1277 case 1: // SetColorMapEntries
1278 return this._handle_set_colour_map_msg();
1285 case 3: // ServerCutText
1286 return this._handle_server_cut_text();
1288 case 150: // EndOfContinuousUpdates
1289 var first
= !(this._supportsContinuousUpdates
);
1290 this._supportsContinuousUpdates
= true;
1291 this._enabledContinuousUpdates
= false;
1293 this._enabledContinuousUpdates
= true;
1294 this._updateContinuousUpdates();
1295 Log
.Info("Enabling continuous updates.");
1297 // FIXME: We need to send a framebufferupdaterequest here
1298 // if we add support for turning off continuous updates
1302 case 248: // ServerFence
1303 return this._handle_server_fence_msg();
1306 return this._handle_xvp_msg();
1309 this._fail("Unexpected server message", "Type:" + msg_type
);
1310 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1315 _onFlush: function() {
1316 this._flushing
= false;
1317 // Resume processing
1318 if (this._sock
.rQlen() > 0) {
1319 this._handle_message();
1323 _framebufferUpdate: function () {
1327 if (this._FBU
.rects
=== 0) {
1328 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1329 this._sock
.rQskip8(); // Padding
1330 this._FBU
.rects
= this._sock
.rQshift16();
1331 this._FBU
.bytes
= 0;
1332 this._timing
.cur_fbu
= 0;
1333 if (this._timing
.fbu_rt_start
> 0) {
1334 now
= (new Date()).getTime();
1335 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1338 // Make sure the previous frame is fully rendered first
1339 // to avoid building up an excessive queue
1340 if (this._display
.pending()) {
1341 this._flushing
= true;
1342 this._display
.flush();
1347 while (this._FBU
.rects
> 0) {
1348 if (this._rfb_connection_state
!== 'connected') { return false; }
1350 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1351 if (this._FBU
.bytes
=== 0) {
1352 if (this._sock
.rQwait("rect header", 12)) { return false; }
1353 /* New FramebufferUpdate */
1355 var hdr
= this._sock
.rQshiftBytes(12);
1356 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1357 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1358 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1359 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1360 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1361 (hdr
[10] << 8) + hdr
[11], 10);
1363 if (!this._encHandlers
[this._FBU
.encoding
]) {
1364 this._fail("Unexpected server message",
1365 "Unsupported encoding " +
1366 this._FBU
.encoding
);
1371 this._timing
.last_fbu
= (new Date()).getTime();
1373 ret
= this._encHandlers
[this._FBU
.encoding
]();
1375 now
= (new Date()).getTime();
1376 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1379 if (!(this._FBU
.encoding
in this._encStats
)) {
1380 this._encStats
[this._FBU
.encoding
] = [0, 0];
1382 this._encStats
[this._FBU
.encoding
][0]++;
1383 this._encStats
[this._FBU
.encoding
][1]++;
1384 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1387 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1388 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1389 this._timing
.fbu_rt_start
> 0) {
1390 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1391 this._timing
.full_fbu_cnt
++;
1392 Log
.Info("Timing of full FBU, curr: " +
1393 this._timing
.cur_fbu
+ ", total: " +
1394 this._timing
.full_fbu_total
+ ", cnt: " +
1395 this._timing
.full_fbu_cnt
+ ", avg: " +
1396 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1399 if (this._timing
.fbu_rt_start
> 0) {
1400 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1401 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1402 this._timing
.fbu_rt_cnt
++;
1403 Log
.Info("full FBU round-trip, cur: " +
1404 fbu_rt_diff
+ ", total: " +
1405 this._timing
.fbu_rt_total
+ ", cnt: " +
1406 this._timing
.fbu_rt_cnt
+ ", avg: " +
1407 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1408 this._timing
.fbu_rt_start
= 0;
1412 if (!ret
) { return ret
; } // need more data
1415 this._display
.flip();
1417 return true; // We finished this FBU
1420 _updateContinuousUpdates: function() {
1421 if (!this._enabledContinuousUpdates
) { return; }
1423 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1424 this._fb_width
, this._fb_height
);
1427 _resize: function(width
, height
) {
1428 this._fb_width
= width
;
1429 this._fb_height
= height
;
1431 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1433 this._display
.resize(this._fb_width
, this._fb_height
);
1434 this._onFBResize(this, this._fb_width
, this._fb_height
);
1436 this._timing
.fbu_rt_start
= (new Date()).getTime();
1437 this._updateContinuousUpdates();
1440 _xvpOp: function (ver
, op
) {
1441 if (this._rfb_xvp_ver
< ver
) { return; }
1442 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
1443 RFB
.messages
.xvpOp(this._sock
, ver
, op
);
1447 make_properties(RFB
, [
1448 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1449 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1450 ['touchButton', 'rw', 'int'], // Button mask (1, 2, 4) for touch devices (0 means ignore clicks)
1451 ['scale', 'rw', 'float'], // Display area scale factor
1452 ['viewport', 'rw', 'bool'], // Use viewport clipping
1453 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1454 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1455 ['capabilities', 'ro', 'arr'], // Supported capabilities
1457 // Callback functions
1458 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1459 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1460 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1461 ['onCredentialsRequired', 'rw', 'func'], // onCredentialsRequired(rfb, types): VNC credentials are required
1462 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1463 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1464 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1465 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1466 ['onCapabilities', 'rw', 'func'] // onCapabilities(rfb, caps): the supported capabilities has changed
1469 RFB
.prototype.set_local_cursor = function (cursor
) {
1470 if (!cursor
|| (cursor
in {'0': 1, 'no': 1, 'false': 1})) {
1471 this._local_cursor
= false;
1472 this._display
.disableLocalCursor(); //Only show server-side cursor
1474 if (browserSupportsCursorURIs()) {
1475 this._local_cursor
= true;
1477 Log
.Warn("Browser does not support local cursor");
1478 this._display
.disableLocalCursor();
1482 // Need to send an updated list of encodings if we are connected
1483 if (this._rfb_connection_state
=== "connected") {
1484 this._sendEncodings();
1488 RFB
.prototype.set_view_only = function (view_only
) {
1489 this._view_only
= view_only
;
1491 if (this._rfb_connection_state
=== "connecting" ||
1492 this._rfb_connection_state
=== "connected") {
1494 this._keyboard
.ungrab();
1495 this._mouse
.ungrab();
1497 this._keyboard
.grab();
1503 RFB
.prototype.set_touchButton = function (button
) {
1504 this._mouse
.set_touchButton(button
);
1507 RFB
.prototype.get_touchButton = function () {
1508 return this._mouse
.get_touchButton();
1511 RFB
.prototype.set_scale = function (scale
) {
1512 this._display
.set_scale(scale
);
1515 RFB
.prototype.get_scale = function () {
1516 return this._display
.get_scale();
1519 RFB
.prototype.set_viewport = function (viewport
) {
1520 this._display
.set_viewport(viewport
);
1523 RFB
.prototype.get_viewport = function () {
1524 return this._display
.get_viewport();
1529 keyEvent: function (sock
, keysym
, down
) {
1530 var buff
= sock
._sQ
;
1531 var offset
= sock
._sQlen
;
1533 buff
[offset
] = 4; // msg-type
1534 buff
[offset
+ 1] = down
;
1536 buff
[offset
+ 2] = 0;
1537 buff
[offset
+ 3] = 0;
1539 buff
[offset
+ 4] = (keysym
>> 24);
1540 buff
[offset
+ 5] = (keysym
>> 16);
1541 buff
[offset
+ 6] = (keysym
>> 8);
1542 buff
[offset
+ 7] = keysym
;
1548 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1549 function getRFBkeycode(xt_scancode
) {
1550 var upperByte
= (keycode
>> 8);
1551 var lowerByte
= (keycode
& 0x00ff);
1552 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1553 lowerByte
= lowerByte
| 0x80;
1559 var buff
= sock
._sQ
;
1560 var offset
= sock
._sQlen
;
1562 buff
[offset
] = 255; // msg-type
1563 buff
[offset
+ 1] = 0; // sub msg-type
1565 buff
[offset
+ 2] = (down
>> 8);
1566 buff
[offset
+ 3] = down
;
1568 buff
[offset
+ 4] = (keysym
>> 24);
1569 buff
[offset
+ 5] = (keysym
>> 16);
1570 buff
[offset
+ 6] = (keysym
>> 8);
1571 buff
[offset
+ 7] = keysym
;
1573 var RFBkeycode
= getRFBkeycode(keycode
);
1575 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1576 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1577 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1578 buff
[offset
+ 11] = RFBkeycode
;
1584 pointerEvent: function (sock
, x
, y
, mask
) {
1585 var buff
= sock
._sQ
;
1586 var offset
= sock
._sQlen
;
1588 buff
[offset
] = 5; // msg-type
1590 buff
[offset
+ 1] = mask
;
1592 buff
[offset
+ 2] = x
>> 8;
1593 buff
[offset
+ 3] = x
;
1595 buff
[offset
+ 4] = y
>> 8;
1596 buff
[offset
+ 5] = y
;
1602 // TODO(directxman12): make this unicode compatible?
1603 clientCutText: function (sock
, text
) {
1604 var buff
= sock
._sQ
;
1605 var offset
= sock
._sQlen
;
1607 buff
[offset
] = 6; // msg-type
1609 buff
[offset
+ 1] = 0; // padding
1610 buff
[offset
+ 2] = 0; // padding
1611 buff
[offset
+ 3] = 0; // padding
1613 var n
= text
.length
;
1615 buff
[offset
+ 4] = n
>> 24;
1616 buff
[offset
+ 5] = n
>> 16;
1617 buff
[offset
+ 6] = n
>> 8;
1618 buff
[offset
+ 7] = n
;
1620 for (var i
= 0; i
< n
; i
++) {
1621 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1624 sock
._sQlen
+= 8 + n
;
1628 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1629 var buff
= sock
._sQ
;
1630 var offset
= sock
._sQlen
;
1632 buff
[offset
] = 251; // msg-type
1633 buff
[offset
+ 1] = 0; // padding
1634 buff
[offset
+ 2] = width
>> 8; // width
1635 buff
[offset
+ 3] = width
;
1636 buff
[offset
+ 4] = height
>> 8; // height
1637 buff
[offset
+ 5] = height
;
1639 buff
[offset
+ 6] = 1; // number-of-screens
1640 buff
[offset
+ 7] = 0; // padding
1643 buff
[offset
+ 8] = id
>> 24; // id
1644 buff
[offset
+ 9] = id
>> 16;
1645 buff
[offset
+ 10] = id
>> 8;
1646 buff
[offset
+ 11] = id
;
1647 buff
[offset
+ 12] = 0; // x-position
1648 buff
[offset
+ 13] = 0;
1649 buff
[offset
+ 14] = 0; // y-position
1650 buff
[offset
+ 15] = 0;
1651 buff
[offset
+ 16] = width
>> 8; // width
1652 buff
[offset
+ 17] = width
;
1653 buff
[offset
+ 18] = height
>> 8; // height
1654 buff
[offset
+ 19] = height
;
1655 buff
[offset
+ 20] = flags
>> 24; // flags
1656 buff
[offset
+ 21] = flags
>> 16;
1657 buff
[offset
+ 22] = flags
>> 8;
1658 buff
[offset
+ 23] = flags
;
1664 clientFence: function (sock
, flags
, payload
) {
1665 var buff
= sock
._sQ
;
1666 var offset
= sock
._sQlen
;
1668 buff
[offset
] = 248; // msg-type
1670 buff
[offset
+ 1] = 0; // padding
1671 buff
[offset
+ 2] = 0; // padding
1672 buff
[offset
+ 3] = 0; // padding
1674 buff
[offset
+ 4] = flags
>> 24; // flags
1675 buff
[offset
+ 5] = flags
>> 16;
1676 buff
[offset
+ 6] = flags
>> 8;
1677 buff
[offset
+ 7] = flags
;
1679 var n
= payload
.length
;
1681 buff
[offset
+ 8] = n
; // length
1683 for (var i
= 0; i
< n
; i
++) {
1684 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1687 sock
._sQlen
+= 9 + n
;
1691 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1692 var buff
= sock
._sQ
;
1693 var offset
= sock
._sQlen
;
1695 buff
[offset
] = 150; // msg-type
1696 buff
[offset
+ 1] = enable
; // enable-flag
1698 buff
[offset
+ 2] = x
>> 8; // x
1699 buff
[offset
+ 3] = x
;
1700 buff
[offset
+ 4] = y
>> 8; // y
1701 buff
[offset
+ 5] = y
;
1702 buff
[offset
+ 6] = width
>> 8; // width
1703 buff
[offset
+ 7] = width
;
1704 buff
[offset
+ 8] = height
>> 8; // height
1705 buff
[offset
+ 9] = height
;
1711 pixelFormat: function (sock
, depth
, true_color
) {
1712 var buff
= sock
._sQ
;
1713 var offset
= sock
._sQlen
;
1719 } else if (depth
> 8) {
1725 bits
= Math
.floor(depth
/3);
1727 buff
[offset
] = 0; // msg-type
1729 buff
[offset
+ 1] = 0; // padding
1730 buff
[offset
+ 2] = 0; // padding
1731 buff
[offset
+ 3] = 0; // padding
1733 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1734 buff
[offset
+ 5] = depth
; // depth
1735 buff
[offset
+ 6] = 0; // little-endian
1736 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1738 buff
[offset
+ 8] = 0; // red-max
1739 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1741 buff
[offset
+ 10] = 0; // green-max
1742 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1744 buff
[offset
+ 12] = 0; // blue-max
1745 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1747 buff
[offset
+ 14] = bits
* 2; // red-shift
1748 buff
[offset
+ 15] = bits
* 1; // green-shift
1749 buff
[offset
+ 16] = bits
* 0; // blue-shift
1751 buff
[offset
+ 17] = 0; // padding
1752 buff
[offset
+ 18] = 0; // padding
1753 buff
[offset
+ 19] = 0; // padding
1759 clientEncodings: function (sock
, encodings
) {
1760 var buff
= sock
._sQ
;
1761 var offset
= sock
._sQlen
;
1763 buff
[offset
] = 2; // msg-type
1764 buff
[offset
+ 1] = 0; // padding
1766 buff
[offset
+ 2] = encodings
.length
>> 8;
1767 buff
[offset
+ 3] = encodings
.length
;
1769 var i
, j
= offset
+ 4;
1770 for (i
= 0; i
< encodings
.length
; i
++) {
1771 var enc
= encodings
[i
];
1772 buff
[j
] = enc
>> 24;
1773 buff
[j
+ 1] = enc
>> 16;
1774 buff
[j
+ 2] = enc
>> 8;
1780 sock
._sQlen
+= j
- offset
;
1784 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1785 var buff
= sock
._sQ
;
1786 var offset
= sock
._sQlen
;
1788 if (typeof(x
) === "undefined") { x
= 0; }
1789 if (typeof(y
) === "undefined") { y
= 0; }
1791 buff
[offset
] = 3; // msg-type
1792 buff
[offset
+ 1] = incremental
? 1 : 0;
1794 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1795 buff
[offset
+ 3] = x
& 0xFF;
1797 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1798 buff
[offset
+ 5] = y
& 0xFF;
1800 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1801 buff
[offset
+ 7] = w
& 0xFF;
1803 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1804 buff
[offset
+ 9] = h
& 0xFF;
1810 xvpOp: function (sock
, ver
, op
) {
1811 var buff
= sock
._sQ
;
1812 var offset
= sock
._sQlen
;
1814 buff
[offset
] = 250; // msg-type
1815 buff
[offset
+ 1] = 0; // padding
1817 buff
[offset
+ 2] = ver
;
1818 buff
[offset
+ 3] = op
;
1825 RFB
.genDES = function (password
, challenge
) {
1827 for (var i
= 0; i
< password
.length
; i
++) {
1828 passwd
.push(password
.charCodeAt(i
));
1830 return (new DES(passwd
)).encrypt(challenge
);
1833 RFB
.encodingHandlers
= {
1835 if (this._FBU
.lines
=== 0) {
1836 this._FBU
.lines
= this._FBU
.height
;
1839 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1840 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1841 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1842 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1843 var curr_height
= Math
.min(this._FBU
.lines
,
1844 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1845 var data
= this._sock
.get_rQ();
1846 var index
= this._sock
.get_rQi();
1847 if (this._fb_depth
== 8) {
1848 var pixels
= this._FBU
.width
* curr_height
1849 var newdata
= new Uint8Array(pixels
* 4);
1851 for (i
= 0;i
< pixels
;i
++) {
1852 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1853 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1854 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1855 newdata
[i
* 4 + 4] = 0;
1860 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1861 curr_height
, data
, index
);
1862 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1863 this._FBU
.lines
-= curr_height
;
1865 if (this._FBU
.lines
> 0) {
1866 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1869 this._FBU
.bytes
= 0;
1875 COPYRECT: function () {
1876 this._FBU
.bytes
= 4;
1877 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1878 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1879 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1883 this._FBU
.bytes
= 0;
1889 if (this._FBU
.subrects
=== 0) {
1890 this._FBU
.bytes
= 4 + 4;
1891 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1892 this._FBU
.subrects
= this._sock
.rQshift32();
1893 color
= this._sock
.rQshiftBytes(4); // Background
1894 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1897 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1898 color
= this._sock
.rQshiftBytes(4);
1899 var x
= this._sock
.rQshift16();
1900 var y
= this._sock
.rQshift16();
1901 var width
= this._sock
.rQshift16();
1902 var height
= this._sock
.rQshift16();
1903 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1904 this._FBU
.subrects
--;
1907 if (this._FBU
.subrects
> 0) {
1908 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1909 this._FBU
.bytes
= (4 + 8) * chunk
;
1912 this._FBU
.bytes
= 0;
1918 HEXTILE: function () {
1919 var rQ
= this._sock
.get_rQ();
1920 var rQi
= this._sock
.get_rQi();
1922 if (this._FBU
.tiles
=== 0) {
1923 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1924 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1925 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1926 this._FBU
.tiles
= this._FBU
.total_tiles
;
1929 while (this._FBU
.tiles
> 0) {
1930 this._FBU
.bytes
= 1;
1931 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1932 var subencoding
= rQ
[rQi
]; // Peek
1933 if (subencoding
> 30) { // Raw
1934 this._fail("Unexpected server message",
1935 "Illegal hextile subencoding: " + subencoding
);
1940 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1941 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1942 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1943 var x
= this._FBU
.x
+ tile_x
* 16;
1944 var y
= this._FBU
.y
+ tile_y
* 16;
1945 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1946 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1948 // Figure out how much we are expecting
1949 if (subencoding
& 0x01) { // Raw
1950 this._FBU
.bytes
+= w
* h
* 4;
1952 if (subencoding
& 0x02) { // Background
1953 this._FBU
.bytes
+= 4;
1955 if (subencoding
& 0x04) { // Foreground
1956 this._FBU
.bytes
+= 4;
1958 if (subencoding
& 0x08) { // AnySubrects
1959 this._FBU
.bytes
++; // Since we aren't shifting it off
1960 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1961 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1962 if (subencoding
& 0x10) { // SubrectsColoured
1963 this._FBU
.bytes
+= subrects
* (4 + 2);
1965 this._FBU
.bytes
+= subrects
* 2;
1970 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1972 // We know the encoding and have a whole tile
1973 this._FBU
.subencoding
= rQ
[rQi
];
1975 if (this._FBU
.subencoding
=== 0) {
1976 if (this._FBU
.lastsubencoding
& 0x01) {
1977 // Weird: ignore blanks are RAW
1978 Log
.Debug(" Ignoring blank after RAW");
1980 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1982 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1983 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1984 rQi
+= this._FBU
.bytes
- 1;
1986 if (this._FBU
.subencoding
& 0x02) { // Background
1987 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1990 if (this._FBU
.subencoding
& 0x04) { // Foreground
1991 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1995 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1996 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
2000 for (var s
= 0; s
< subrects
; s
++) {
2002 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
2003 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2006 color
= this._FBU
.foreground
;
2011 var sy
= (xy
& 0x0f);
2015 var sw
= (wh
>> 4) + 1;
2016 var sh
= (wh
& 0x0f) + 1;
2018 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
2021 this._display
.finishTile();
2023 this._sock
.set_rQi(rQi
);
2024 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2025 this._FBU
.bytes
= 0;
2029 if (this._FBU
.tiles
=== 0) {
2036 TIGHT: function () {
2037 this._FBU
.bytes
= 1; // compression-control byte
2038 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2040 var checksum = function (data
) {
2042 for (var i
= 0; i
< data
.length
; i
++) {
2044 if (sum
> 65536) sum
-= 65536;
2049 var resetStreams
= 0;
2051 var decompress = function (data
, expected
) {
2052 for (var i
= 0; i
< 4; i
++) {
2053 if ((resetStreams
>> i
) & 1) {
2054 this._FBU
.zlibs
[i
].reset();
2055 Log
.Info("Reset zlib stream " + i
);
2059 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2060 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2061 /*if (uncompressed.status !== 0) {
2062 Log.Error("Invalid data in zlib stream");
2065 //return uncompressed.data;
2066 return uncompressed
;
2069 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2070 // Convert indexed (palette based) image data to RGB
2071 // TODO: reduce number of calculations inside loop
2072 var dest
= this._destBuff
;
2073 var w
= Math
.floor((width
+ 7) / 8);
2074 var w1
= Math
.floor(width
/ 8);
2076 /*for (var y = 0; y < height; y++) {
2078 var yoffset = y * width;
2079 var ybitoffset = y * w;
2080 var xoffset, targetbyte;
2081 for (x = 0; x < w1; x++) {
2082 xoffset = yoffset + x * 8;
2083 targetbyte = data[ybitoffset + x];
2084 for (b = 7; b >= 0; b--) {
2085 dp = (xoffset + 7 - b) * 3;
2086 sp = (targetbyte >> b & 1) * 3;
2087 dest[dp] = palette[sp];
2088 dest[dp + 1] = palette[sp + 1];
2089 dest[dp + 2] = palette[sp + 2];
2093 xoffset = yoffset + x * 8;
2094 targetbyte = data[ybitoffset + x];
2095 for (b = 7; b >= 8 - width % 8; b--) {
2096 dp = (xoffset + 7 - b) * 3;
2097 sp = (targetbyte >> b & 1) * 3;
2098 dest[dp] = palette[sp];
2099 dest[dp + 1] = palette[sp + 1];
2100 dest[dp + 2] = palette[sp + 2];
2104 for (var y
= 0; y
< height
; y
++) {
2106 for (x
= 0; x
< w1
; x
++) {
2107 for (b
= 7; b
>= 0; b
--) {
2108 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2109 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2110 dest
[dp
] = palette
[sp
];
2111 dest
[dp
+ 1] = palette
[sp
+ 1];
2112 dest
[dp
+ 2] = palette
[sp
+ 2];
2117 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2118 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2119 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2120 dest
[dp
] = palette
[sp
];
2121 dest
[dp
+ 1] = palette
[sp
+ 1];
2122 dest
[dp
+ 2] = palette
[sp
+ 2];
2130 var indexedToRGBX = function (data
, palette
, width
, height
) {
2131 // Convert indexed (palette based) image data to RGB
2132 var dest
= this._destBuff
;
2133 var total
= width
* height
* 4;
2134 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2135 var sp
= data
[j
] * 3;
2136 dest
[i
] = palette
[sp
];
2137 dest
[i
+ 1] = palette
[sp
+ 1];
2138 dest
[i
+ 2] = palette
[sp
+ 2];
2145 var rQi
= this._sock
.get_rQi();
2146 var rQ
= this._sock
.rQwhole();
2148 var cl_header
, cl_data
;
2150 var handlePalette = function () {
2151 var numColors
= rQ
[rQi
+ 2] + 1;
2152 var paletteSize
= numColors
* 3;
2153 this._FBU
.bytes
+= paletteSize
;
2154 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2156 var bpp
= (numColors
<= 2) ? 1 : 8;
2157 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2159 if (rowSize
* this._FBU
.height
< 12) {
2162 cl_data
= rowSize
* this._FBU
.height
;
2163 //clength = [0, rowSize * this._FBU.height];
2165 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2166 var cl_offset
= rQi
+ 3 + paletteSize
;
2169 cl_data
+= rQ
[cl_offset
] & 0x7f;
2170 if (rQ
[cl_offset
] & 0x80) {
2172 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2173 if (rQ
[cl_offset
+ 1] & 0x80) {
2175 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2178 // end inline getTightCLength
2181 this._FBU
.bytes
+= cl_header
+ cl_data
;
2182 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2184 // Shift ctl, filter id, num colors, palette entries, and clength off
2185 this._sock
.rQskipBytes(3);
2186 //var palette = this._sock.rQshiftBytes(paletteSize);
2187 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2188 this._sock
.rQskipBytes(cl_header
);
2191 data
= this._sock
.rQshiftBytes(cl_data
);
2193 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2196 // Convert indexed (palette based) image data to RGB
2198 if (numColors
== 2) {
2199 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2200 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2202 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2203 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2210 var handleCopy = function () {
2212 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2213 if (uncompressedSize
< 12) {
2216 cl_data
= uncompressedSize
;
2218 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2219 var cl_offset
= rQi
+ 1;
2222 cl_data
+= rQ
[cl_offset
] & 0x7f;
2223 if (rQ
[cl_offset
] & 0x80) {
2225 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2226 if (rQ
[cl_offset
+ 1] & 0x80) {
2228 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2231 // end inline getTightCLength
2233 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2234 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2236 // Shift ctl, clength off
2237 this._sock
.rQshiftBytes(1 + cl_header
);
2240 data
= this._sock
.rQshiftBytes(cl_data
);
2242 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2245 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2250 var ctl
= this._sock
.rQpeek8();
2252 // Keep tight reset bits
2253 resetStreams
= ctl
& 0xF;
2255 // Figure out filter
2257 streamId
= ctl
& 0x3;
2259 if (ctl
=== 0x08) cmode
= "fill";
2260 else if (ctl
=== 0x09) cmode
= "jpeg";
2261 else if (ctl
=== 0x0A) cmode
= "png";
2262 else if (ctl
& 0x04) cmode
= "filter";
2263 else if (ctl
< 0x04) cmode
= "copy";
2264 else return this._fail("Unexpected server message",
2265 "Illegal tight compression received, " +
2269 // fill use depth because TPIXELs drop the padding byte
2270 case "fill": // TPIXEL
2271 this._FBU
.bytes
+= 3;
2273 case "jpeg": // max clength
2274 this._FBU
.bytes
+= 3;
2276 case "png": // max clength
2277 this._FBU
.bytes
+= 3;
2279 case "filter": // filter id + num colors if palette
2280 this._FBU
.bytes
+= 2;
2286 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2288 // Determine FBU.bytes
2292 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);
2293 this._sock
.rQskipBytes(4);
2297 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2298 var cl_offset
= rQi
+ 1;
2301 cl_data
+= rQ
[cl_offset
] & 0x7f;
2302 if (rQ
[cl_offset
] & 0x80) {
2304 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2305 if (rQ
[cl_offset
+ 1] & 0x80) {
2307 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2310 // end inline getTightCLength
2311 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2312 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2314 // We have everything, render it
2315 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2316 data
= this._sock
.rQshiftBytes(cl_data
);
2317 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2320 var filterId
= rQ
[rQi
+ 1];
2321 if (filterId
=== 1) {
2322 if (!handlePalette()) { return false; }
2324 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2325 // Filter 2, Gradient is valid but not use if jpeg is enabled
2326 this._fail("Unexpected server message",
2327 "Unsupported tight subencoding received, " +
2328 "filter: " + filterId
);
2332 if (!handleCopy()) { return false; }
2337 this._FBU
.bytes
= 0;
2343 last_rect: function () {
2344 this._FBU
.rects
= 0;
2348 ExtendedDesktopSize: function () {
2349 this._FBU
.bytes
= 1;
2350 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2352 this._supportsSetDesktopSize
= true;
2353 this._setCapability("resize", true);
2355 var number_of_screens
= this._sock
.rQpeek8();
2357 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2358 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2360 this._sock
.rQskipBytes(1); // number-of-screens
2361 this._sock
.rQskipBytes(3); // padding
2363 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2364 // Save the id and flags of the first screen
2366 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2367 this._sock
.rQskipBytes(2); // x-position
2368 this._sock
.rQskipBytes(2); // y-position
2369 this._sock
.rQskipBytes(2); // width
2370 this._sock
.rQskipBytes(2); // height
2371 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2373 this._sock
.rQskipBytes(16);
2378 * The x-position indicates the reason for the change:
2380 * 0 - server resized on its own
2381 * 1 - this client requested the resize
2382 * 2 - another client requested the resize
2385 // We need to handle errors when we requested the resize.
2386 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2388 // The y-position indicates the status code from the server
2389 switch (this._FBU
.y
) {
2391 msg
= "Resize is administratively prohibited";
2394 msg
= "Out of resources";
2397 msg
= "Invalid screen layout";
2400 msg
= "Unknown reason";
2403 this._notification("Server did not accept the resize request: "
2406 this._resize(this._FBU
.width
, this._FBU
.height
);
2409 this._FBU
.bytes
= 0;
2410 this._FBU
.rects
-= 1;
2414 DesktopSize: function () {
2415 this._resize(this._FBU
.width
, this._FBU
.height
);
2416 this._FBU
.bytes
= 0;
2417 this._FBU
.rects
-= 1;
2421 Cursor: function () {
2422 Log
.Debug(">> set_cursor");
2423 var x
= this._FBU
.x
; // hotspot-x
2424 var y
= this._FBU
.y
; // hotspot-y
2425 var w
= this._FBU
.width
;
2426 var h
= this._FBU
.height
;
2428 var pixelslength
= w
* h
* 4;
2429 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2431 this._FBU
.bytes
= pixelslength
+ masklength
;
2432 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2434 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2435 this._sock
.rQshiftBytes(masklength
),
2438 this._FBU
.bytes
= 0;
2441 Log
.Debug("<< set_cursor");
2445 QEMUExtendedKeyEvent: function () {
2448 // Old Safari doesn't support creating keyboard events
2450 var keyboardEvent
= document
.createEvent("keyboardEvent");
2451 if (keyboardEvent
.code
!== undefined) {
2452 this._qemuExtKeyEventSupported
= true;