2 * noVNC: HTML5 VNC client
3 * Copyright (C) 2012 Joel Martin
4 * Copyright (C) 2017 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 { decodeUTF8
} from './util/strings.js';
15 import { browserSupportsCursorURIs
, isTouchDevice
} from './util/browsers.js';
16 import EventTargetMixin
from './util/eventtarget.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";
27 import "./util/polyfill.js";
29 /*jslint white: false, browser: true */
30 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
32 // How many seconds to wait for a disconnect to finish
33 var DISCONNECT_TIMEOUT
= 3;
35 export default function RFB(target
, url
, options
) {
37 throw Error("Must specify target");
40 throw Error("Must specify URL");
43 this._target
= target
;
47 options
= options
|| {};
48 this._rfb_credentials
= options
.credentials
|| {};
49 this._shared
= 'shared' in options
? !!options
.shared
: true;
50 this._repeaterID
= options
.repeaterID
|| '';
53 this._rfb_connection_state
= '';
54 this._rfb_init_state
= '';
55 this._rfb_auth_scheme
= '';
56 this._rfb_clean_disconnect
= true;
58 // Server capabilities
59 this._rfb_version
= 0;
60 this._rfb_max_version
= 3.8;
61 this._rfb_tightvnc
= false;
62 this._rfb_xvp_ver
= 0;
69 this._capabilities
= { power
: false, resize
: false };
71 this._supportsFence
= false;
73 this._supportsContinuousUpdates
= false;
74 this._enabledContinuousUpdates
= false;
76 this._supportsSetDesktopSize
= false;
78 this._screen_flags
= 0;
80 this._qemuExtKeyEventSupported
= false;
83 this._sock
= null; // Websock object
84 this._display
= null; // Display object
85 this._flushing
= false; // Display flushing state
86 this._keyboard
= null; // Keyboard input handler object
87 this._mouse
= null; // Mouse input handler object
90 this._disconnTimer
= null; // disconnection timer
92 // Decoder states and stats
93 this._encHandlers
= {};
98 subrects
: 0, // RRE and HEXTILE
109 zlibs
: [] // TIGHT zlib streams
111 for (var i
= 0; i
< 4; i
++) {
112 this._FBU
.zlibs
[i
] = new Inflator();
115 this._destBuff
= null;
116 this._paletteBuff
= new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
118 this._rre_chunk_sz
= 100;
134 this._mouse_buttonMask
= 0;
135 this._mouse_arr
= [];
136 this._viewportDragging
= false;
137 this._viewportDragPos
= {};
138 this._viewportHasMoved
= false;
140 // Bound event handlers
141 this._eventHandlers
= {
142 focusCanvas
: this._focusCanvas
.bind(this),
146 Log
.Debug(">> RFB.constructor");
148 // Target canvas must be able to have focus
149 if (!this._target
.hasAttribute('tabindex')) {
150 this._target
.tabIndex
= -1;
153 // populate encHandlers with bound versions
154 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this);
155 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this);
156 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this);
157 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this);
158 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this);
160 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this);
161 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this);
162 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this);
163 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this);
164 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this);
166 // NB: nothing that needs explicit teardown should be done
167 // before this point, since this can throw an exception
169 this._display
= new Display(this._target
);
171 Log
.Error("Display exception: " + exc
);
174 this._display
.onflush
= this._onFlush
.bind(this);
175 this._display
.clear();
177 this._keyboard
= new Keyboard(this._target
);
178 this._keyboard
.onkeyevent
= this._handleKeyEvent
.bind(this);
180 this._mouse
= new Mouse(this._target
);
181 this._mouse
.onmousebutton
= this._handleMouseButton
.bind(this);
182 this._mouse
.onmousemove
= this._handleMouseMove
.bind(this);
184 this._sock
= new Websock();
185 this._sock
.on('message', this._handle_message
.bind(this));
186 this._sock
.on('open', function () {
187 if ((this._rfb_connection_state
=== 'connecting') &&
188 (this._rfb_init_state
=== '')) {
189 this._rfb_init_state
= 'ProtocolVersion';
190 Log
.Debug("Starting VNC handshake");
192 this._fail("Unexpected server connection while " +
193 this._rfb_connection_state
);
196 this._sock
.on('close', function (e
) {
197 Log
.Warn("WebSocket on-close event");
200 msg
= "(code: " + e
.code
;
202 msg
+= ", reason: " + e
.reason
;
206 switch (this._rfb_connection_state
) {
208 this._fail("Connection closed " + msg
);
211 // Handle disconnects that were initiated server-side
212 this._updateConnectionState('disconnecting');
213 this._updateConnectionState('disconnected');
215 case 'disconnecting':
216 // Normal disconnection path
217 this._updateConnectionState('disconnected');
220 this._fail("Unexpected server disconnect " +
221 "when already disconnected " + msg
);
224 this._fail("Unexpected server disconnect before connecting " +
228 this._sock
.off('close');
230 this._sock
.on('error', function (e
) {
231 Log
.Warn("WebSocket on-error event");
234 // Slight delay of the actual connection so that the caller has
235 // time to set up callbacks
236 setTimeout(this._updateConnectionState
.bind(this, 'connecting'));
238 Log
.Debug("<< RFB.constructor");
242 // ===== PROPERTIES =====
248 get viewOnly() { return this._viewOnly
; },
249 set viewOnly(viewOnly
) {
250 this._viewOnly
= viewOnly
;
252 if (this._rfb_connection_state
=== "connecting" ||
253 this._rfb_connection_state
=== "connected") {
255 this._keyboard
.ungrab();
256 this._mouse
.ungrab();
258 this._keyboard
.grab();
264 get capabilities() { return this._capabilities
; },
266 get touchButton() { return this._mouse
.touchButton
; },
267 set touchButton(button
) { this._mouse
.touchButton
= button
; },
269 get viewportScale() { return this._display
.scale
; },
270 set viewportScale(scale
) { this._display
.scale
= scale
; },
272 get clipViewport() { return this._display
.clipViewport
; },
273 set clipViewport(viewport
) { this._display
.clipViewport
= viewport
; },
275 get isClipped() { return this._display
.isClipped
; },
277 // ===== PUBLIC METHODS =====
279 disconnect: function () {
280 this._updateConnectionState('disconnecting');
281 this._sock
.off('error');
282 this._sock
.off('message');
283 this._sock
.off('open');
286 sendCredentials: function (creds
) {
287 this._rfb_credentials
= creds
;
288 setTimeout(this._init_msg
.bind(this), 0);
291 sendCtrlAltDel: function () {
292 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
293 Log
.Info("Sending Ctrl-Alt-Del");
295 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
296 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
297 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
298 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
299 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
300 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
303 machineShutdown: function () {
307 machineReboot: function () {
311 machineReset: function () {
315 // Send a key press. If 'down' is not specified then send a down key
316 // followed by an up key.
317 sendKey: function (keysym
, code
, down
) {
318 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
320 if (down
=== undefined) {
321 this.sendKey(keysym
, code
, true);
322 this.sendKey(keysym
, code
, false);
326 var scancode
= XtScancode
[code
];
328 if (this._qemuExtKeyEventSupported
&& scancode
) {
330 keysym
= keysym
|| 0;
332 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
334 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
339 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
340 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
344 clipboardPasteFrom: function (text
) {
345 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
346 RFB
.messages
.clientCutText(this._sock
, text
);
349 autoscale: function (width
, height
) {
350 if (this._rfb_connection_state
!== 'connected') { return; }
351 this._display
.autoscale(width
, height
);
354 viewportChangeSize: function(width
, height
) {
355 if (this._rfb_connection_state
!== 'connected') { return; }
356 this._display
.viewportChangeSize(width
, height
);
359 // Requests a change of remote desktop size. This message is an extension
360 // and may only be sent if we have received an ExtendedDesktopSize message
361 requestDesktopSize: function (width
, height
) {
362 if (this._rfb_connection_state
!== 'connected' ||
367 if (!this._supportsSetDesktopSize
) {
371 RFB
.messages
.setDesktopSize(this._sock
, width
, height
,
372 this._screen_id
, this._screen_flags
);
376 // ===== PRIVATE METHODS =====
378 _connect: function () {
379 Log
.Debug(">> RFB.connect");
381 Log
.Info("connecting to " + this._url
);
384 // WebSocket.onopen transitions to the RFB init states
385 this._sock
.open(this._url
, ['binary']);
387 if (e
.name
=== 'SyntaxError') {
388 this._fail("Invalid host or port (" + e
+ ")");
390 this._fail("Error when opening socket (" + e
+ ")");
394 // Always grab focus on some kind of click event
395 this._target
.addEventListener("mousedown", this._eventHandlers
.focusCanvas
);
396 this._target
.addEventListener("touchstart", this._eventHandlers
.focusCanvas
);
398 Log
.Debug("<< RFB.connect");
401 _disconnect: function () {
402 Log
.Debug(">> RFB.disconnect");
403 this._target
.removeEventListener("mousedown", this._eventHandlers
.focusCanvas
);
404 this._target
.removeEventListener("touchstart", this._eventHandlers
.focusCanvas
);
408 Log
.Debug("<< RFB.disconnect");
411 _print_stats: function () {
412 var stats
= this._encStats
;
414 Log
.Info("Encoding stats for this connection:");
415 Object
.keys(stats
).forEach(function (key
) {
417 if (s
[0] + s
[1] > 0) {
418 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
422 Log
.Info("Encoding stats since page load:");
423 Object
.keys(stats
).forEach(function (key
) {
425 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
429 _cleanup: function () {
430 if (!this._viewOnly
) { this._keyboard
.ungrab(); }
431 if (!this._viewOnly
) { this._mouse
.ungrab(); }
432 this._display
.defaultCursor();
433 if (Log
.get_logging() !== 'debug') {
434 // Show noVNC logo when disconnected, unless in
436 this._display
.clear();
440 _focusCanvas: function(event
) {
441 // Respect earlier handlers' request to not do side-effects
442 if (event
.defaultPrevented
) {
446 if (!this.focusOnClick
) {
450 this._target
.focus();
458 * disconnected - permanent state
460 _updateConnectionState: function (state
) {
461 var oldstate
= this._rfb_connection_state
;
463 if (state
=== oldstate
) {
464 Log
.Debug("Already in state '" + state
+ "', ignoring");
468 // The 'disconnected' state is permanent for each RFB object
469 if (oldstate
=== 'disconnected') {
470 Log
.Error("Tried changing state of a disconnected RFB object");
474 // Ensure proper transitions before doing anything
477 if (oldstate
!== 'connecting') {
478 Log
.Error("Bad transition to connected state, " +
479 "previous connection state: " + oldstate
);
485 if (oldstate
!== 'disconnecting') {
486 Log
.Error("Bad transition to disconnected state, " +
487 "previous connection state: " + oldstate
);
493 if (oldstate
!== '') {
494 Log
.Error("Bad transition to connecting state, " +
495 "previous connection state: " + oldstate
);
500 case 'disconnecting':
501 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
502 Log
.Error("Bad transition to disconnecting state, " +
503 "previous connection state: " + oldstate
);
509 Log
.Error("Unknown connection state: " + state
);
513 // State change actions
515 this._rfb_connection_state
= state
;
517 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
520 if (this._disconnTimer
&& state
!== 'disconnecting') {
521 Log
.Debug("Clearing disconnect timer");
522 clearTimeout(this._disconnTimer
);
523 this._disconnTimer
= null;
525 // make sure we don't get a double event
526 this._sock
.off('close');
535 var event
= new CustomEvent("connect", { detail
: {} });
536 this.dispatchEvent(event
);
539 case 'disconnecting':
542 this._disconnTimer
= setTimeout(function () {
543 Log
.Error("Disconnection timed out.");
544 this._updateConnectionState('disconnected');
545 }.bind(this), DISCONNECT_TIMEOUT
* 1000);
549 event
= new CustomEvent(
550 "disconnect", { detail
:
551 { clean
: this._rfb_clean_disconnect
} });
552 this.dispatchEvent(event
);
557 /* Print errors and disconnect
559 * The parameter 'details' is used for information that
560 * should be logged but not sent to the user interface.
562 _fail: function (details
) {
563 switch (this._rfb_connection_state
) {
564 case 'disconnecting':
565 Log
.Error("Failed when disconnecting: " + details
);
568 Log
.Error("Failed while connected: " + details
);
571 Log
.Error("Failed when connecting: " + details
);
574 Log
.Error("RFB failure: " + details
);
577 this._rfb_clean_disconnect
= false; //This is sent to the UI
579 // Transition to disconnected without waiting for socket to close
580 this._updateConnectionState('disconnecting');
581 this._updateConnectionState('disconnected');
586 _setCapability: function (cap
, val
) {
587 this._capabilities
[cap
] = val
;
588 var event
= new CustomEvent("capabilities",
589 { detail
: { capabilities
: this._capabilities
} });
590 this.dispatchEvent(event
);
593 _handle_message: function () {
594 if (this._sock
.rQlen() === 0) {
595 Log
.Warn("handle_message called on an empty receive queue");
599 switch (this._rfb_connection_state
) {
601 Log
.Error("Got data while disconnected");
605 if (this._flushing
) {
608 if (!this._normal_msg()) {
611 if (this._sock
.rQlen() === 0) {
622 _handleKeyEvent: function (keysym
, code
, down
) {
623 this.sendKey(keysym
, code
, down
);
626 _handleMouseButton: function (x
, y
, down
, bmask
) {
628 this._mouse_buttonMask
|= bmask
;
630 this._mouse_buttonMask
&= ~bmask
;
633 if (this.dragViewport
) {
634 if (down
&& !this._viewportDragging
) {
635 this._viewportDragging
= true;
636 this._viewportDragPos
= {'x': x
, 'y': y
};
638 // Skip sending mouse events
641 this._viewportDragging
= false;
643 // If the viewport didn't actually move, then treat as a mouse click event
644 // Send the button down event here, as the button up event is sent at the end of this function
645 if (!this._viewportHasMoved
&& !this._viewOnly
) {
646 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), bmask
);
648 this._viewportHasMoved
= false;
652 if (this._viewOnly
) { return; } // View only, skip mouse events
654 if (this._rfb_connection_state
!== 'connected') { return; }
655 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
658 _handleMouseMove: function (x
, y
) {
659 if (this._viewportDragging
) {
660 var deltaX
= this._viewportDragPos
.x
- x
;
661 var deltaY
= this._viewportDragPos
.y
- y
;
663 // The goal is to trigger on a certain physical width, the
664 // devicePixelRatio brings us a bit closer but is not optimal.
665 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
667 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
668 Math
.abs(deltaY
) > dragThreshold
)) {
669 this._viewportHasMoved
= true;
671 this._viewportDragPos
= {'x': x
, 'y': y
};
672 this._display
.viewportChangePos(deltaX
, deltaY
);
675 // Skip sending mouse events
679 if (this._viewOnly
) { return; } // View only, skip mouse events
681 if (this._rfb_connection_state
!== 'connected') { return; }
682 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
687 _negotiate_protocol_version: function () {
688 if (this._sock
.rQlen() < 12) {
689 return this._fail("Received incomplete protocol version.");
692 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
693 Log
.Info("Server ProtocolVersion: " + sversion
);
696 case "000.000": // UltraVNC repeater
700 case "003.006": // UltraVNC
701 case "003.889": // Apple Remote Desktop
702 this._rfb_version
= 3.3;
705 this._rfb_version
= 3.7;
708 case "004.000": // Intel AMT KVM
709 case "004.001": // RealVNC 4.6
710 case "005.000": // RealVNC 5.3
711 this._rfb_version
= 3.8;
714 return this._fail("Invalid server version " + sversion
);
718 var repeaterID
= "ID:" + this._repeaterID
;
719 while (repeaterID
.length
< 250) {
722 this._sock
.send_string(repeaterID
);
726 if (this._rfb_version
> this._rfb_max_version
) {
727 this._rfb_version
= this._rfb_max_version
;
730 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
731 ".00" + ((this._rfb_version
* 10) % 10);
732 this._sock
.send_string("RFB " + cversion
+ "\n");
733 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
735 this._rfb_init_state
= 'Security';
738 _negotiate_security: function () {
739 // Polyfill since IE and PhantomJS doesn't have
740 // TypedArray.includes()
741 function includes(item
, array
) {
742 for (var i
= 0; i
< array
.length
; i
++) {
743 if (array
[i
] === item
) {
750 if (this._rfb_version
>= 3.7) {
751 // Server sends supported list, client decides
752 var num_types
= this._sock
.rQshift8();
753 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
755 if (num_types
=== 0) {
756 return this._handle_security_failure("no security types");
759 var types
= this._sock
.rQshiftBytes(num_types
);
760 Log
.Debug("Server security types: " + types
);
762 // Look for each auth in preferred order
763 this._rfb_auth_scheme
= 0;
764 if (includes(1, types
)) {
765 this._rfb_auth_scheme
= 1; // None
766 } else if (includes(22, types
)) {
767 this._rfb_auth_scheme
= 22; // XVP
768 } else if (includes(16, types
)) {
769 this._rfb_auth_scheme
= 16; // Tight
770 } else if (includes(2, types
)) {
771 this._rfb_auth_scheme
= 2; // VNC Auth
773 return this._fail("Unsupported security types (types: " + types
+ ")");
776 this._sock
.send([this._rfb_auth_scheme
]);
779 if (this._sock
.rQwait("security scheme", 4)) { return false; }
780 this._rfb_auth_scheme
= this._sock
.rQshift32();
783 this._rfb_init_state
= 'Authentication';
784 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
786 return this._init_msg(); // jump to authentication
790 * Get the security failure reason if sent from the server and
791 * send the 'securityfailure' event.
793 * - The optional parameter context can be used to add some extra
794 * context to the log output.
796 * - The optional parameter security_result_status can be used to
797 * add a custom status code to the event.
799 _handle_security_failure: function (context
, security_result_status
) {
801 if (typeof context
=== 'undefined') {
804 context
= " on " + context
;
807 if (typeof security_result_status
=== 'undefined') {
808 security_result_status
= 1; // fail
811 if (this._sock
.rQwait("reason length", 4)) {
814 let strlen
= this._sock
.rQshift32();
818 if (this._sock
.rQwait("reason", strlen
, 8)) { return false; }
819 reason
= this._sock
.rQshiftStr(strlen
);
824 let event
= new CustomEvent(
826 { detail
: { status
: security_result_status
, reason
: reason
} });
827 this.dispatchEvent(event
);
829 return this._fail("Security negotiation failed" + context
+
830 " (reason: " + reason
+ ")");
833 let event
= new CustomEvent(
835 { detail
: { status
: security_result_status
} });
836 this.dispatchEvent(event
);
838 return this._fail("Security negotiation failed" + context
);
843 _negotiate_xvp_auth: function () {
844 if (!this._rfb_credentials
.username
||
845 !this._rfb_credentials
.password
||
846 !this._rfb_credentials
.target
) {
847 var event
= new CustomEvent("credentialsrequired",
848 { detail
: { types
: ["username", "password", "target"] } });
849 this.dispatchEvent(event
);
853 var xvp_auth_str
= String
.fromCharCode(this._rfb_credentials
.username
.length
) +
854 String
.fromCharCode(this._rfb_credentials
.target
.length
) +
855 this._rfb_credentials
.username
+
856 this._rfb_credentials
.target
;
857 this._sock
.send_string(xvp_auth_str
);
858 this._rfb_auth_scheme
= 2;
859 return this._negotiate_authentication();
862 _negotiate_std_vnc_auth: function () {
863 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
865 if (!this._rfb_credentials
.password
) {
866 var event
= new CustomEvent("credentialsrequired",
867 { detail
: { types
: ["password"] } });
868 this.dispatchEvent(event
);
872 // TODO(directxman12): make genDES not require an Array
873 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
874 var response
= RFB
.genDES(this._rfb_credentials
.password
, challenge
);
875 this._sock
.send(response
);
876 this._rfb_init_state
= "SecurityResult";
880 _negotiate_tight_tunnels: function (numTunnels
) {
881 var clientSupportedTunnelTypes
= {
882 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
884 var serverSupportedTunnelTypes
= {};
885 // receive tunnel capabilities
886 for (var i
= 0; i
< numTunnels
; i
++) {
887 var cap_code
= this._sock
.rQshift32();
888 var cap_vendor
= this._sock
.rQshiftStr(4);
889 var cap_signature
= this._sock
.rQshiftStr(8);
890 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
893 // choose the notunnel type
894 if (serverSupportedTunnelTypes
[0]) {
895 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
896 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
897 return this._fail("Client's tunnel type had the incorrect " +
898 "vendor or signature");
900 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
901 return false; // wait until we receive the sub auth count to continue
903 return this._fail("Server wanted tunnels, but doesn't support " +
904 "the notunnel type");
908 _negotiate_tight_auth: function () {
909 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
910 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
911 var numTunnels
= this._sock
.rQshift32();
912 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
914 this._rfb_tightvnc
= true;
916 if (numTunnels
> 0) {
917 this._negotiate_tight_tunnels(numTunnels
);
918 return false; // wait until we receive the sub auth to continue
922 // second pass, do the sub-auth negotiation
923 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
924 var subAuthCount
= this._sock
.rQshift32();
925 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
926 this._rfb_init_state
= 'SecurityResult';
930 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
932 var clientSupportedTypes
= {
937 var serverSupportedTypes
= [];
939 for (var i
= 0; i
< subAuthCount
; i
++) {
940 var capNum
= this._sock
.rQshift32();
941 var capabilities
= this._sock
.rQshiftStr(12);
942 serverSupportedTypes
.push(capabilities
);
945 for (var authType
in clientSupportedTypes
) {
946 if (serverSupportedTypes
.indexOf(authType
) != -1) {
947 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
950 case 'STDVNOAUTH__': // no auth
951 this._rfb_init_state
= 'SecurityResult';
953 case 'STDVVNCAUTH_': // VNC auth
954 this._rfb_auth_scheme
= 2;
955 return this._init_msg();
957 return this._fail("Unsupported tiny auth scheme " +
958 "(scheme: " + authType
+ ")");
963 return this._fail("No supported sub-auth types!");
966 _negotiate_authentication: function () {
967 switch (this._rfb_auth_scheme
) {
968 case 0: // connection failed
969 return this._handle_security_failure("authentication scheme");
972 if (this._rfb_version
>= 3.8) {
973 this._rfb_init_state
= 'SecurityResult';
976 this._rfb_init_state
= 'ClientInitialisation';
977 return this._init_msg();
980 return this._negotiate_xvp_auth();
982 case 2: // VNC authentication
983 return this._negotiate_std_vnc_auth();
985 case 16: // TightVNC Security Type
986 return this._negotiate_tight_auth();
989 return this._fail("Unsupported auth scheme (scheme: " +
990 this._rfb_auth_scheme
+ ")");
994 _handle_security_result: function () {
995 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
997 let status
= this._sock
.rQshift32();
999 if (status
=== 0) { // OK
1000 this._rfb_init_state
= 'ClientInitialisation';
1001 Log
.Debug('Authentication OK');
1002 return this._init_msg();
1004 if (this._rfb_version
>= 3.8) {
1005 return this._handle_security_failure("security result", status
);
1007 let event
= new CustomEvent("securityfailure",
1008 { detail
: { status
: status
} });
1009 this.dispatchEvent(event
);
1011 return this._fail("Security handshake failed");
1016 _negotiate_server_init: function () {
1017 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1020 var width
= this._sock
.rQshift16();
1021 var height
= this._sock
.rQshift16();
1024 var bpp
= this._sock
.rQshift8();
1025 var depth
= this._sock
.rQshift8();
1026 var big_endian
= this._sock
.rQshift8();
1027 var true_color
= this._sock
.rQshift8();
1029 var red_max
= this._sock
.rQshift16();
1030 var green_max
= this._sock
.rQshift16();
1031 var blue_max
= this._sock
.rQshift16();
1032 var red_shift
= this._sock
.rQshift8();
1033 var green_shift
= this._sock
.rQshift8();
1034 var blue_shift
= this._sock
.rQshift8();
1035 this._sock
.rQskipBytes(3); // padding
1037 // NB(directxman12): we don't want to call any callbacks or print messages until
1038 // *after* we're past the point where we could backtrack
1040 /* Connection name/title */
1041 var name_length = this._sock.rQshift32();
1042 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1043 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1045 if (this._rfb_tightvnc) {
1046 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1047 // In TightVNC mode, ServerInit message is extended
1048 var numServerMessages = this._sock.rQshift16();
1049 var numClientMessages = this._sock.rQshift16();
1050 var numEncodings = this._sock.rQshift16();
1051 this._sock.rQskipBytes(2); // padding
1053 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1054 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1056 // we don't actually do anything with the capability information that TIGHT sends,
1057 // so we just skip the all of this.
1059 // TIGHT server message capabilities
1060 this._sock.rQskipBytes(16 * numServerMessages);
1062 // TIGHT client message capabilities
1063 this._sock.rQskipBytes(16 * numClientMessages);
1065 // TIGHT encoding capabilities
1066 this._sock.rQskipBytes(16 * numEncodings);
1069 // NB(directxman12): these are down here so that we don't run them multiple times
1071 Log.Info("Screen: " + width + "x" + height +
1072 ", bpp: " + bpp + ", depth: " + depth +
1073 ", big_endian: " + big_endian +
1074 ", true_color: " + true_color +
1075 ", red_max: " + red_max +
1076 ", green_max: " + green_max +
1077 ", blue_max: " + blue_max +
1078 ", red_shift: " + red_shift +
1079 ", green_shift: " + green_shift +
1080 ", blue_shift: " + blue_shift);
1082 if (big_endian !== 0) {
1083 Log.Warn("Server native endian is not little endian");
1086 if (red_shift !== 16) {
1087 Log.Warn("Server native red-shift is not 16");
1090 if (blue_shift !== 0) {
1091 Log.Warn("Server native blue-shift is not 0");
1094 // we're past the point where we could backtrack, so it's safe to call this
1095 var event = new CustomEvent("desktopname",
1096 { detail: { name: this._fb_name } });
1097 this.dispatchEvent(event);
1099 this._resize(width, height);
1101 if (!this._viewOnly) { this._keyboard.grab(); }
1102 if (!this._viewOnly) { this._mouse.grab(); }
1104 this._fb_depth = 24;
1106 if (this._fb_name === "Intel(r) AMT KVM") {
1107 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1111 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1112 this._sendEncodings();
1113 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1115 this._timing.fbu_rt_start = (new Date()).getTime();
1116 this._timing.pixels = 0;
1118 // Cursor will be server side until the server decides to honor
1119 // our request and send over the cursor image
1120 this._display.disableLocalCursor();
1122 this._updateConnectionState('connected');
1126 _sendEncodings: function () {
1129 // In preference order
1130 encs.push(encodings.encodingCopyRect);
1131 // Only supported with full depth support
1132 if (this._fb_depth == 24) {
1133 encs.push(encodings.encodingTight);
1134 encs.push(encodings.encodingHextile);
1135 encs.push(encodings.encodingRRE);
1137 encs.push(encodings.encodingRaw);
1139 // Psuedo-encoding settings
1140 encs.push(encodings.pseudoEncodingTightPNG);
1141 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1142 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1144 encs.push(encodings.pseudoEncodingDesktopSize);
1145 encs.push(encodings.pseudoEncodingLastRect);
1146 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1147 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1148 encs.push(encodings.pseudoEncodingXvp);
1149 encs.push(encodings.pseudoEncodingFence);
1150 encs.push(encodings.pseudoEncodingContinuousUpdates);
1152 if (browserSupportsCursorURIs() &&
1153 !isTouchDevice && this._fb_depth == 24) {
1154 encs.push(encodings.pseudoEncodingCursor);
1157 RFB.messages.clientEncodings(this._sock, encs);
1160 /* RFB protocol initialization states:
1165 * ClientInitialization - not triggered by server message
1166 * ServerInitialization
1168 _init_msg: function () {
1169 switch (this._rfb_init_state
) {
1170 case 'ProtocolVersion':
1171 return this._negotiate_protocol_version();
1174 return this._negotiate_security();
1176 case 'Authentication':
1177 return this._negotiate_authentication();
1179 case 'SecurityResult':
1180 return this._handle_security_result();
1182 case 'ClientInitialisation':
1183 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1184 this._rfb_init_state
= 'ServerInitialisation';
1187 case 'ServerInitialisation':
1188 return this._negotiate_server_init();
1191 return this._fail("Unknown init state (state: " +
1192 this._rfb_init_state
+ ")");
1196 _handle_set_colour_map_msg: function () {
1197 Log
.Debug("SetColorMapEntries");
1199 return this._fail("Unexpected SetColorMapEntries message");
1202 _handle_server_cut_text: function () {
1203 Log
.Debug("ServerCutText");
1205 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1206 this._sock
.rQskipBytes(3); // Padding
1207 var length
= this._sock
.rQshift32();
1208 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1210 var text
= this._sock
.rQshiftStr(length
);
1212 if (this._viewOnly
) { return true; }
1214 var event
= new CustomEvent("clipboard",
1215 { detail
: { text
: text
} });
1216 this.dispatchEvent(event
);
1221 _handle_server_fence_msg: function() {
1222 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1223 this._sock
.rQskipBytes(3); // Padding
1224 var flags
= this._sock
.rQshift32();
1225 var length
= this._sock
.rQshift8();
1227 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1230 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1234 var payload
= this._sock
.rQshiftStr(length
);
1236 this._supportsFence
= true;
1241 * (1<<0) - BlockBefore
1242 * (1<<1) - BlockAfter
1247 if (!(flags
& (1<<31))) {
1248 return this._fail("Unexpected fence response");
1251 // Filter out unsupported flags
1252 // FIXME: support syncNext
1253 flags
&= (1<<0) | (1<<1);
1255 // BlockBefore and BlockAfter are automatically handled by
1256 // the fact that we process each incoming message
1258 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1263 _handle_xvp_msg: function () {
1264 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1265 this._sock
.rQskip8(); // Padding
1266 var xvp_ver
= this._sock
.rQshift8();
1267 var xvp_msg
= this._sock
.rQshift8();
1271 Log
.Error("XVP Operation Failed");
1274 this._rfb_xvp_ver
= xvp_ver
;
1275 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1276 this._setCapability("power", true);
1279 this._fail("Illegal server XVP message (msg: " + xvp_msg
+ ")");
1286 _normal_msg: function () {
1289 if (this._FBU
.rects
> 0) {
1292 msg_type
= this._sock
.rQshift8();
1296 case 0: // FramebufferUpdate
1297 var ret
= this._framebufferUpdate();
1298 if (ret
&& !this._enabledContinuousUpdates
) {
1299 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1300 this._fb_width
, this._fb_height
);
1304 case 1: // SetColorMapEntries
1305 return this._handle_set_colour_map_msg();
1309 var event
= new CustomEvent("bell", { detail
: {} });
1310 this.dispatchEvent(event
);
1313 case 3: // ServerCutText
1314 return this._handle_server_cut_text();
1316 case 150: // EndOfContinuousUpdates
1317 var first
= !(this._supportsContinuousUpdates
);
1318 this._supportsContinuousUpdates
= true;
1319 this._enabledContinuousUpdates
= false;
1321 this._enabledContinuousUpdates
= true;
1322 this._updateContinuousUpdates();
1323 Log
.Info("Enabling continuous updates.");
1325 // FIXME: We need to send a framebufferupdaterequest here
1326 // if we add support for turning off continuous updates
1330 case 248: // ServerFence
1331 return this._handle_server_fence_msg();
1334 return this._handle_xvp_msg();
1337 this._fail("Unexpected server message (type " + msg_type
+ ")");
1338 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1343 _onFlush: function() {
1344 this._flushing
= false;
1345 // Resume processing
1346 if (this._sock
.rQlen() > 0) {
1347 this._handle_message();
1351 _framebufferUpdate: function () {
1355 if (this._FBU
.rects
=== 0) {
1356 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1357 this._sock
.rQskip8(); // Padding
1358 this._FBU
.rects
= this._sock
.rQshift16();
1359 this._FBU
.bytes
= 0;
1360 this._timing
.cur_fbu
= 0;
1361 if (this._timing
.fbu_rt_start
> 0) {
1362 now
= (new Date()).getTime();
1363 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1366 // Make sure the previous frame is fully rendered first
1367 // to avoid building up an excessive queue
1368 if (this._display
.pending()) {
1369 this._flushing
= true;
1370 this._display
.flush();
1375 while (this._FBU
.rects
> 0) {
1376 if (this._rfb_connection_state
!== 'connected') { return false; }
1378 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1379 if (this._FBU
.bytes
=== 0) {
1380 if (this._sock
.rQwait("rect header", 12)) { return false; }
1381 /* New FramebufferUpdate */
1383 var hdr
= this._sock
.rQshiftBytes(12);
1384 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1385 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1386 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1387 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1388 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1389 (hdr
[10] << 8) + hdr
[11], 10);
1391 if (!this._encHandlers
[this._FBU
.encoding
]) {
1392 this._fail("Unsupported encoding (encoding: " +
1393 this._FBU
.encoding
+ ")");
1398 this._timing
.last_fbu
= (new Date()).getTime();
1400 ret
= this._encHandlers
[this._FBU
.encoding
]();
1402 now
= (new Date()).getTime();
1403 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1406 if (!(this._FBU
.encoding
in this._encStats
)) {
1407 this._encStats
[this._FBU
.encoding
] = [0, 0];
1409 this._encStats
[this._FBU
.encoding
][0]++;
1410 this._encStats
[this._FBU
.encoding
][1]++;
1411 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1414 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1415 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1416 this._timing
.fbu_rt_start
> 0) {
1417 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1418 this._timing
.full_fbu_cnt
++;
1419 Log
.Info("Timing of full FBU, curr: " +
1420 this._timing
.cur_fbu
+ ", total: " +
1421 this._timing
.full_fbu_total
+ ", cnt: " +
1422 this._timing
.full_fbu_cnt
+ ", avg: " +
1423 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1426 if (this._timing
.fbu_rt_start
> 0) {
1427 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1428 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1429 this._timing
.fbu_rt_cnt
++;
1430 Log
.Info("full FBU round-trip, cur: " +
1431 fbu_rt_diff
+ ", total: " +
1432 this._timing
.fbu_rt_total
+ ", cnt: " +
1433 this._timing
.fbu_rt_cnt
+ ", avg: " +
1434 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1435 this._timing
.fbu_rt_start
= 0;
1439 if (!ret
) { return ret
; } // need more data
1442 this._display
.flip();
1444 return true; // We finished this FBU
1447 _updateContinuousUpdates: function() {
1448 if (!this._enabledContinuousUpdates
) { return; }
1450 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1451 this._fb_width
, this._fb_height
);
1454 _resize: function(width
, height
) {
1455 this._fb_width
= width
;
1456 this._fb_height
= height
;
1458 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1460 this._display
.resize(this._fb_width
, this._fb_height
);
1462 var event
= new CustomEvent("fbresize",
1463 { detail
: { width
: this._fb_width
,
1464 height
: this._fb_height
} });
1465 this.dispatchEvent(event
);
1467 this._timing
.fbu_rt_start
= (new Date()).getTime();
1468 this._updateContinuousUpdates();
1471 _xvpOp: function (ver
, op
) {
1472 if (this._rfb_xvp_ver
< ver
) { return; }
1473 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
1474 RFB
.messages
.xvpOp(this._sock
, ver
, op
);
1478 Object
.assign(RFB
.prototype, EventTargetMixin
);
1482 keyEvent: function (sock
, keysym
, down
) {
1483 var buff
= sock
._sQ
;
1484 var offset
= sock
._sQlen
;
1486 buff
[offset
] = 4; // msg-type
1487 buff
[offset
+ 1] = down
;
1489 buff
[offset
+ 2] = 0;
1490 buff
[offset
+ 3] = 0;
1492 buff
[offset
+ 4] = (keysym
>> 24);
1493 buff
[offset
+ 5] = (keysym
>> 16);
1494 buff
[offset
+ 6] = (keysym
>> 8);
1495 buff
[offset
+ 7] = keysym
;
1501 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1502 function getRFBkeycode(xt_scancode
) {
1503 var upperByte
= (keycode
>> 8);
1504 var lowerByte
= (keycode
& 0x00ff);
1505 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1506 lowerByte
= lowerByte
| 0x80;
1512 var buff
= sock
._sQ
;
1513 var offset
= sock
._sQlen
;
1515 buff
[offset
] = 255; // msg-type
1516 buff
[offset
+ 1] = 0; // sub msg-type
1518 buff
[offset
+ 2] = (down
>> 8);
1519 buff
[offset
+ 3] = down
;
1521 buff
[offset
+ 4] = (keysym
>> 24);
1522 buff
[offset
+ 5] = (keysym
>> 16);
1523 buff
[offset
+ 6] = (keysym
>> 8);
1524 buff
[offset
+ 7] = keysym
;
1526 var RFBkeycode
= getRFBkeycode(keycode
);
1528 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1529 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1530 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1531 buff
[offset
+ 11] = RFBkeycode
;
1537 pointerEvent: function (sock
, x
, y
, mask
) {
1538 var buff
= sock
._sQ
;
1539 var offset
= sock
._sQlen
;
1541 buff
[offset
] = 5; // msg-type
1543 buff
[offset
+ 1] = mask
;
1545 buff
[offset
+ 2] = x
>> 8;
1546 buff
[offset
+ 3] = x
;
1548 buff
[offset
+ 4] = y
>> 8;
1549 buff
[offset
+ 5] = y
;
1555 // TODO(directxman12): make this unicode compatible?
1556 clientCutText: function (sock
, text
) {
1557 var buff
= sock
._sQ
;
1558 var offset
= sock
._sQlen
;
1560 buff
[offset
] = 6; // msg-type
1562 buff
[offset
+ 1] = 0; // padding
1563 buff
[offset
+ 2] = 0; // padding
1564 buff
[offset
+ 3] = 0; // padding
1566 var n
= text
.length
;
1568 buff
[offset
+ 4] = n
>> 24;
1569 buff
[offset
+ 5] = n
>> 16;
1570 buff
[offset
+ 6] = n
>> 8;
1571 buff
[offset
+ 7] = n
;
1573 for (var i
= 0; i
< n
; i
++) {
1574 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1577 sock
._sQlen
+= 8 + n
;
1581 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1582 var buff
= sock
._sQ
;
1583 var offset
= sock
._sQlen
;
1585 buff
[offset
] = 251; // msg-type
1586 buff
[offset
+ 1] = 0; // padding
1587 buff
[offset
+ 2] = width
>> 8; // width
1588 buff
[offset
+ 3] = width
;
1589 buff
[offset
+ 4] = height
>> 8; // height
1590 buff
[offset
+ 5] = height
;
1592 buff
[offset
+ 6] = 1; // number-of-screens
1593 buff
[offset
+ 7] = 0; // padding
1596 buff
[offset
+ 8] = id
>> 24; // id
1597 buff
[offset
+ 9] = id
>> 16;
1598 buff
[offset
+ 10] = id
>> 8;
1599 buff
[offset
+ 11] = id
;
1600 buff
[offset
+ 12] = 0; // x-position
1601 buff
[offset
+ 13] = 0;
1602 buff
[offset
+ 14] = 0; // y-position
1603 buff
[offset
+ 15] = 0;
1604 buff
[offset
+ 16] = width
>> 8; // width
1605 buff
[offset
+ 17] = width
;
1606 buff
[offset
+ 18] = height
>> 8; // height
1607 buff
[offset
+ 19] = height
;
1608 buff
[offset
+ 20] = flags
>> 24; // flags
1609 buff
[offset
+ 21] = flags
>> 16;
1610 buff
[offset
+ 22] = flags
>> 8;
1611 buff
[offset
+ 23] = flags
;
1617 clientFence: function (sock
, flags
, payload
) {
1618 var buff
= sock
._sQ
;
1619 var offset
= sock
._sQlen
;
1621 buff
[offset
] = 248; // msg-type
1623 buff
[offset
+ 1] = 0; // padding
1624 buff
[offset
+ 2] = 0; // padding
1625 buff
[offset
+ 3] = 0; // padding
1627 buff
[offset
+ 4] = flags
>> 24; // flags
1628 buff
[offset
+ 5] = flags
>> 16;
1629 buff
[offset
+ 6] = flags
>> 8;
1630 buff
[offset
+ 7] = flags
;
1632 var n
= payload
.length
;
1634 buff
[offset
+ 8] = n
; // length
1636 for (var i
= 0; i
< n
; i
++) {
1637 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1640 sock
._sQlen
+= 9 + n
;
1644 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1645 var buff
= sock
._sQ
;
1646 var offset
= sock
._sQlen
;
1648 buff
[offset
] = 150; // msg-type
1649 buff
[offset
+ 1] = enable
; // enable-flag
1651 buff
[offset
+ 2] = x
>> 8; // x
1652 buff
[offset
+ 3] = x
;
1653 buff
[offset
+ 4] = y
>> 8; // y
1654 buff
[offset
+ 5] = y
;
1655 buff
[offset
+ 6] = width
>> 8; // width
1656 buff
[offset
+ 7] = width
;
1657 buff
[offset
+ 8] = height
>> 8; // height
1658 buff
[offset
+ 9] = height
;
1664 pixelFormat: function (sock
, depth
, true_color
) {
1665 var buff
= sock
._sQ
;
1666 var offset
= sock
._sQlen
;
1672 } else if (depth
> 8) {
1678 bits
= Math
.floor(depth
/3);
1680 buff
[offset
] = 0; // msg-type
1682 buff
[offset
+ 1] = 0; // padding
1683 buff
[offset
+ 2] = 0; // padding
1684 buff
[offset
+ 3] = 0; // padding
1686 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1687 buff
[offset
+ 5] = depth
; // depth
1688 buff
[offset
+ 6] = 0; // little-endian
1689 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1691 buff
[offset
+ 8] = 0; // red-max
1692 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1694 buff
[offset
+ 10] = 0; // green-max
1695 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1697 buff
[offset
+ 12] = 0; // blue-max
1698 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1700 buff
[offset
+ 14] = bits
* 2; // red-shift
1701 buff
[offset
+ 15] = bits
* 1; // green-shift
1702 buff
[offset
+ 16] = bits
* 0; // blue-shift
1704 buff
[offset
+ 17] = 0; // padding
1705 buff
[offset
+ 18] = 0; // padding
1706 buff
[offset
+ 19] = 0; // padding
1712 clientEncodings: function (sock
, encodings
) {
1713 var buff
= sock
._sQ
;
1714 var offset
= sock
._sQlen
;
1716 buff
[offset
] = 2; // msg-type
1717 buff
[offset
+ 1] = 0; // padding
1719 buff
[offset
+ 2] = encodings
.length
>> 8;
1720 buff
[offset
+ 3] = encodings
.length
;
1722 var i
, j
= offset
+ 4;
1723 for (i
= 0; i
< encodings
.length
; i
++) {
1724 var enc
= encodings
[i
];
1725 buff
[j
] = enc
>> 24;
1726 buff
[j
+ 1] = enc
>> 16;
1727 buff
[j
+ 2] = enc
>> 8;
1733 sock
._sQlen
+= j
- offset
;
1737 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1738 var buff
= sock
._sQ
;
1739 var offset
= sock
._sQlen
;
1741 if (typeof(x
) === "undefined") { x
= 0; }
1742 if (typeof(y
) === "undefined") { y
= 0; }
1744 buff
[offset
] = 3; // msg-type
1745 buff
[offset
+ 1] = incremental
? 1 : 0;
1747 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1748 buff
[offset
+ 3] = x
& 0xFF;
1750 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1751 buff
[offset
+ 5] = y
& 0xFF;
1753 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1754 buff
[offset
+ 7] = w
& 0xFF;
1756 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1757 buff
[offset
+ 9] = h
& 0xFF;
1763 xvpOp: function (sock
, ver
, op
) {
1764 var buff
= sock
._sQ
;
1765 var offset
= sock
._sQlen
;
1767 buff
[offset
] = 250; // msg-type
1768 buff
[offset
+ 1] = 0; // padding
1770 buff
[offset
+ 2] = ver
;
1771 buff
[offset
+ 3] = op
;
1778 RFB
.genDES = function (password
, challenge
) {
1780 for (var i
= 0; i
< password
.length
; i
++) {
1781 passwd
.push(password
.charCodeAt(i
));
1783 return (new DES(passwd
)).encrypt(challenge
);
1786 RFB
.encodingHandlers
= {
1788 if (this._FBU
.lines
=== 0) {
1789 this._FBU
.lines
= this._FBU
.height
;
1792 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1793 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1794 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1795 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1796 var curr_height
= Math
.min(this._FBU
.lines
,
1797 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1798 var data
= this._sock
.get_rQ();
1799 var index
= this._sock
.get_rQi();
1800 if (this._fb_depth
== 8) {
1801 var pixels
= this._FBU
.width
* curr_height
1802 var newdata
= new Uint8Array(pixels
* 4);
1804 for (i
= 0;i
< pixels
;i
++) {
1805 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1806 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1807 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1808 newdata
[i
* 4 + 4] = 0;
1813 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1814 curr_height
, data
, index
);
1815 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1816 this._FBU
.lines
-= curr_height
;
1818 if (this._FBU
.lines
> 0) {
1819 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1822 this._FBU
.bytes
= 0;
1828 COPYRECT: function () {
1829 this._FBU
.bytes
= 4;
1830 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1831 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1832 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1836 this._FBU
.bytes
= 0;
1842 if (this._FBU
.subrects
=== 0) {
1843 this._FBU
.bytes
= 4 + 4;
1844 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1845 this._FBU
.subrects
= this._sock
.rQshift32();
1846 color
= this._sock
.rQshiftBytes(4); // Background
1847 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1850 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1851 color
= this._sock
.rQshiftBytes(4);
1852 var x
= this._sock
.rQshift16();
1853 var y
= this._sock
.rQshift16();
1854 var width
= this._sock
.rQshift16();
1855 var height
= this._sock
.rQshift16();
1856 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1857 this._FBU
.subrects
--;
1860 if (this._FBU
.subrects
> 0) {
1861 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1862 this._FBU
.bytes
= (4 + 8) * chunk
;
1865 this._FBU
.bytes
= 0;
1871 HEXTILE: function () {
1872 var rQ
= this._sock
.get_rQ();
1873 var rQi
= this._sock
.get_rQi();
1875 if (this._FBU
.tiles
=== 0) {
1876 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
1877 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
1878 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
1879 this._FBU
.tiles
= this._FBU
.total_tiles
;
1882 while (this._FBU
.tiles
> 0) {
1883 this._FBU
.bytes
= 1;
1884 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
1885 var subencoding
= rQ
[rQi
]; // Peek
1886 if (subencoding
> 30) { // Raw
1887 this._fail("Illegal hextile subencoding (subencoding: " +
1893 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
1894 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
1895 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
1896 var x
= this._FBU
.x
+ tile_x
* 16;
1897 var y
= this._FBU
.y
+ tile_y
* 16;
1898 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
1899 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
1901 // Figure out how much we are expecting
1902 if (subencoding
& 0x01) { // Raw
1903 this._FBU
.bytes
+= w
* h
* 4;
1905 if (subencoding
& 0x02) { // Background
1906 this._FBU
.bytes
+= 4;
1908 if (subencoding
& 0x04) { // Foreground
1909 this._FBU
.bytes
+= 4;
1911 if (subencoding
& 0x08) { // AnySubrects
1912 this._FBU
.bytes
++; // Since we aren't shifting it off
1913 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
1914 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
1915 if (subencoding
& 0x10) { // SubrectsColoured
1916 this._FBU
.bytes
+= subrects
* (4 + 2);
1918 this._FBU
.bytes
+= subrects
* 2;
1923 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
1925 // We know the encoding and have a whole tile
1926 this._FBU
.subencoding
= rQ
[rQi
];
1928 if (this._FBU
.subencoding
=== 0) {
1929 if (this._FBU
.lastsubencoding
& 0x01) {
1930 // Weird: ignore blanks are RAW
1931 Log
.Debug(" Ignoring blank after RAW");
1933 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
1935 } else if (this._FBU
.subencoding
& 0x01) { // Raw
1936 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
1937 rQi
+= this._FBU
.bytes
- 1;
1939 if (this._FBU
.subencoding
& 0x02) { // Background
1940 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1943 if (this._FBU
.subencoding
& 0x04) { // Foreground
1944 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1948 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
1949 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
1953 for (var s
= 0; s
< subrects
; s
++) {
1955 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
1956 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
1959 color
= this._FBU
.foreground
;
1964 var sy
= (xy
& 0x0f);
1968 var sw
= (wh
>> 4) + 1;
1969 var sh
= (wh
& 0x0f) + 1;
1971 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
1974 this._display
.finishTile();
1976 this._sock
.set_rQi(rQi
);
1977 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
1978 this._FBU
.bytes
= 0;
1982 if (this._FBU
.tiles
=== 0) {
1989 TIGHT: function () {
1990 this._FBU
.bytes
= 1; // compression-control byte
1991 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
1993 var checksum = function (data
) {
1995 for (var i
= 0; i
< data
.length
; i
++) {
1997 if (sum
> 65536) sum
-= 65536;
2002 var resetStreams
= 0;
2004 var decompress = function (data
, expected
) {
2005 for (var i
= 0; i
< 4; i
++) {
2006 if ((resetStreams
>> i
) & 1) {
2007 this._FBU
.zlibs
[i
].reset();
2008 Log
.Info("Reset zlib stream " + i
);
2012 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2013 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2014 /*if (uncompressed.status !== 0) {
2015 Log.Error("Invalid data in zlib stream");
2018 //return uncompressed.data;
2019 return uncompressed
;
2022 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2023 // Convert indexed (palette based) image data to RGB
2024 // TODO: reduce number of calculations inside loop
2025 var dest
= this._destBuff
;
2026 var w
= Math
.floor((width
+ 7) / 8);
2027 var w1
= Math
.floor(width
/ 8);
2029 /*for (var y = 0; y < height; y++) {
2031 var yoffset = y * width;
2032 var ybitoffset = y * w;
2033 var xoffset, targetbyte;
2034 for (x = 0; x < w1; x++) {
2035 xoffset = yoffset + x * 8;
2036 targetbyte = data[ybitoffset + x];
2037 for (b = 7; b >= 0; b--) {
2038 dp = (xoffset + 7 - b) * 3;
2039 sp = (targetbyte >> b & 1) * 3;
2040 dest[dp] = palette[sp];
2041 dest[dp + 1] = palette[sp + 1];
2042 dest[dp + 2] = palette[sp + 2];
2046 xoffset = yoffset + x * 8;
2047 targetbyte = data[ybitoffset + x];
2048 for (b = 7; b >= 8 - width % 8; b--) {
2049 dp = (xoffset + 7 - b) * 3;
2050 sp = (targetbyte >> b & 1) * 3;
2051 dest[dp] = palette[sp];
2052 dest[dp + 1] = palette[sp + 1];
2053 dest[dp + 2] = palette[sp + 2];
2057 for (var y
= 0; y
< height
; y
++) {
2059 for (x
= 0; x
< w1
; x
++) {
2060 for (b
= 7; b
>= 0; b
--) {
2061 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2062 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2063 dest
[dp
] = palette
[sp
];
2064 dest
[dp
+ 1] = palette
[sp
+ 1];
2065 dest
[dp
+ 2] = palette
[sp
+ 2];
2070 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2071 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2072 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2073 dest
[dp
] = palette
[sp
];
2074 dest
[dp
+ 1] = palette
[sp
+ 1];
2075 dest
[dp
+ 2] = palette
[sp
+ 2];
2083 var indexedToRGBX = function (data
, palette
, width
, height
) {
2084 // Convert indexed (palette based) image data to RGB
2085 var dest
= this._destBuff
;
2086 var total
= width
* height
* 4;
2087 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2088 var sp
= data
[j
] * 3;
2089 dest
[i
] = palette
[sp
];
2090 dest
[i
+ 1] = palette
[sp
+ 1];
2091 dest
[i
+ 2] = palette
[sp
+ 2];
2098 var rQi
= this._sock
.get_rQi();
2099 var rQ
= this._sock
.rQwhole();
2101 var cl_header
, cl_data
;
2103 var handlePalette = function () {
2104 var numColors
= rQ
[rQi
+ 2] + 1;
2105 var paletteSize
= numColors
* 3;
2106 this._FBU
.bytes
+= paletteSize
;
2107 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2109 var bpp
= (numColors
<= 2) ? 1 : 8;
2110 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2112 if (rowSize
* this._FBU
.height
< 12) {
2115 cl_data
= rowSize
* this._FBU
.height
;
2116 //clength = [0, rowSize * this._FBU.height];
2118 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2119 var cl_offset
= rQi
+ 3 + paletteSize
;
2122 cl_data
+= rQ
[cl_offset
] & 0x7f;
2123 if (rQ
[cl_offset
] & 0x80) {
2125 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2126 if (rQ
[cl_offset
+ 1] & 0x80) {
2128 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2131 // end inline getTightCLength
2134 this._FBU
.bytes
+= cl_header
+ cl_data
;
2135 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2137 // Shift ctl, filter id, num colors, palette entries, and clength off
2138 this._sock
.rQskipBytes(3);
2139 //var palette = this._sock.rQshiftBytes(paletteSize);
2140 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2141 this._sock
.rQskipBytes(cl_header
);
2144 data
= this._sock
.rQshiftBytes(cl_data
);
2146 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2149 // Convert indexed (palette based) image data to RGB
2151 if (numColors
== 2) {
2152 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2153 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2155 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2156 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2163 var handleCopy = function () {
2165 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2166 if (uncompressedSize
< 12) {
2169 cl_data
= uncompressedSize
;
2171 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2172 var cl_offset
= rQi
+ 1;
2175 cl_data
+= rQ
[cl_offset
] & 0x7f;
2176 if (rQ
[cl_offset
] & 0x80) {
2178 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2179 if (rQ
[cl_offset
+ 1] & 0x80) {
2181 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2184 // end inline getTightCLength
2186 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2187 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2189 // Shift ctl, clength off
2190 this._sock
.rQshiftBytes(1 + cl_header
);
2193 data
= this._sock
.rQshiftBytes(cl_data
);
2195 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2198 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2203 var ctl
= this._sock
.rQpeek8();
2205 // Keep tight reset bits
2206 resetStreams
= ctl
& 0xF;
2208 // Figure out filter
2210 streamId
= ctl
& 0x3;
2212 if (ctl
=== 0x08) cmode
= "fill";
2213 else if (ctl
=== 0x09) cmode
= "jpeg";
2214 else if (ctl
=== 0x0A) cmode
= "png";
2215 else if (ctl
& 0x04) cmode
= "filter";
2216 else if (ctl
< 0x04) cmode
= "copy";
2217 else return this._fail("Illegal tight compression received (ctl: " +
2221 // fill use depth because TPIXELs drop the padding byte
2222 case "fill": // TPIXEL
2223 this._FBU
.bytes
+= 3;
2225 case "jpeg": // max clength
2226 this._FBU
.bytes
+= 3;
2228 case "png": // max clength
2229 this._FBU
.bytes
+= 3;
2231 case "filter": // filter id + num colors if palette
2232 this._FBU
.bytes
+= 2;
2238 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2240 // Determine FBU.bytes
2244 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);
2245 this._sock
.rQskipBytes(4);
2249 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2250 var cl_offset
= rQi
+ 1;
2253 cl_data
+= rQ
[cl_offset
] & 0x7f;
2254 if (rQ
[cl_offset
] & 0x80) {
2256 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2257 if (rQ
[cl_offset
+ 1] & 0x80) {
2259 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2262 // end inline getTightCLength
2263 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2264 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2266 // We have everything, render it
2267 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2268 data
= this._sock
.rQshiftBytes(cl_data
);
2269 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2272 var filterId
= rQ
[rQi
+ 1];
2273 if (filterId
=== 1) {
2274 if (!handlePalette()) { return false; }
2276 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2277 // Filter 2, Gradient is valid but not use if jpeg is enabled
2278 this._fail("Unsupported tight subencoding received " +
2279 "(filter: " + filterId
+ ")");
2283 if (!handleCopy()) { return false; }
2288 this._FBU
.bytes
= 0;
2294 last_rect: function () {
2295 this._FBU
.rects
= 0;
2299 ExtendedDesktopSize: function () {
2300 this._FBU
.bytes
= 1;
2301 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2303 this._supportsSetDesktopSize
= true;
2304 this._setCapability("resize", true);
2306 var number_of_screens
= this._sock
.rQpeek8();
2308 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2309 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2311 this._sock
.rQskipBytes(1); // number-of-screens
2312 this._sock
.rQskipBytes(3); // padding
2314 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2315 // Save the id and flags of the first screen
2317 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2318 this._sock
.rQskipBytes(2); // x-position
2319 this._sock
.rQskipBytes(2); // y-position
2320 this._sock
.rQskipBytes(2); // width
2321 this._sock
.rQskipBytes(2); // height
2322 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2324 this._sock
.rQskipBytes(16);
2329 * The x-position indicates the reason for the change:
2331 * 0 - server resized on its own
2332 * 1 - this client requested the resize
2333 * 2 - another client requested the resize
2336 // We need to handle errors when we requested the resize.
2337 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2339 // The y-position indicates the status code from the server
2340 switch (this._FBU
.y
) {
2342 msg
= "Resize is administratively prohibited";
2345 msg
= "Out of resources";
2348 msg
= "Invalid screen layout";
2351 msg
= "Unknown reason";
2354 Log
.Warn("Server did not accept the resize request: "
2357 this._resize(this._FBU
.width
, this._FBU
.height
);
2360 this._FBU
.bytes
= 0;
2361 this._FBU
.rects
-= 1;
2365 DesktopSize: function () {
2366 this._resize(this._FBU
.width
, this._FBU
.height
);
2367 this._FBU
.bytes
= 0;
2368 this._FBU
.rects
-= 1;
2372 Cursor: function () {
2373 Log
.Debug(">> set_cursor");
2374 var x
= this._FBU
.x
; // hotspot-x
2375 var y
= this._FBU
.y
; // hotspot-y
2376 var w
= this._FBU
.width
;
2377 var h
= this._FBU
.height
;
2379 var pixelslength
= w
* h
* 4;
2380 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2382 this._FBU
.bytes
= pixelslength
+ masklength
;
2383 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2385 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2386 this._sock
.rQshiftBytes(masklength
),
2389 this._FBU
.bytes
= 0;
2392 Log
.Debug("<< set_cursor");
2396 QEMUExtendedKeyEvent: function () {
2399 // Old Safari doesn't support creating keyboard events
2401 var keyboardEvent
= document
.createEvent("keyboardEvent");
2402 if (keyboardEvent
.code
!== undefined) {
2403 this._qemuExtKeyEventSupported
= true;