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 { supportsCursorURIs
, isTouchDevice
} from './util/browser.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 DES
from "./des.js";
22 import KeyTable
from "./input/keysym.js";
23 import XtScancode
from "./input/xtscancodes.js";
24 import Inflator
from "./inflator.js";
25 import { encodings
, encodingName
} from "./encodings.js";
26 import "./util/polyfill.js";
28 /*jslint white: false, browser: true */
29 /*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
31 // How many seconds to wait for a disconnect to finish
32 var DISCONNECT_TIMEOUT
= 3;
34 export default function RFB(target
, url
, options
) {
36 throw Error("Must specify target");
39 throw Error("Must specify URL");
42 this._target
= target
;
46 options
= options
|| {};
47 this._rfb_credentials
= options
.credentials
|| {};
48 this._shared
= 'shared' in options
? !!options
.shared
: true;
49 this._repeaterID
= options
.repeaterID
|| '';
52 this._rfb_connection_state
= '';
53 this._rfb_init_state
= '';
54 this._rfb_auth_scheme
= '';
55 this._rfb_clean_disconnect
= true;
57 // Server capabilities
58 this._rfb_version
= 0;
59 this._rfb_max_version
= 3.8;
60 this._rfb_tightvnc
= false;
61 this._rfb_xvp_ver
= 0;
68 this._capabilities
= { power
: false };
70 this._supportsFence
= false;
72 this._supportsContinuousUpdates
= false;
73 this._enabledContinuousUpdates
= false;
75 this._supportsSetDesktopSize
= false;
77 this._screen_flags
= 0;
79 this._qemuExtKeyEventSupported
= false;
82 this._sock
= null; // Websock object
83 this._display
= null; // Display object
84 this._flushing
= false; // Display flushing state
85 this._keyboard
= null; // Keyboard input handler object
86 this._mouse
= null; // Mouse input handler object
89 this._disconnTimer
= null; // disconnection timer
90 this._resizeTimeout
= null; // resize rate limiting
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),
143 windowResize
: this._windowResize
.bind(this),
147 Log
.Debug(">> RFB.constructor");
149 // Create DOM elements
150 this._screen
= document
.createElement('div');
151 this._screen
.style
.display
= 'flex';
152 this._screen
.style
.width
= '100%';
153 this._screen
.style
.height
= '100%';
154 this._screen
.style
.overflow
= 'auto';
155 this._screen
.style
.backgroundColor
= 'rgb(40, 40, 40)';
156 this._canvas
= document
.createElement('canvas');
157 this._canvas
.style
.margin
= 'auto';
158 // Some browsers add an outline on focus
159 this._canvas
.style
.outline
= 'none';
160 // IE miscalculates width without this :(
161 this._canvas
.style
.flexShrink
= '0';
162 this._canvas
.width
= 0;
163 this._canvas
.height
= 0;
164 this._canvas
.tabIndex
= -1;
165 this._screen
.appendChild(this._canvas
);
167 // populate encHandlers with bound versions
168 this._encHandlers
[encodings
.encodingRaw
] = RFB
.encodingHandlers
.RAW
.bind(this);
169 this._encHandlers
[encodings
.encodingCopyRect
] = RFB
.encodingHandlers
.COPYRECT
.bind(this);
170 this._encHandlers
[encodings
.encodingRRE
] = RFB
.encodingHandlers
.RRE
.bind(this);
171 this._encHandlers
[encodings
.encodingHextile
] = RFB
.encodingHandlers
.HEXTILE
.bind(this);
172 this._encHandlers
[encodings
.encodingTight
] = RFB
.encodingHandlers
.TIGHT
.bind(this);
174 this._encHandlers
[encodings
.pseudoEncodingDesktopSize
] = RFB
.encodingHandlers
.DesktopSize
.bind(this);
175 this._encHandlers
[encodings
.pseudoEncodingLastRect
] = RFB
.encodingHandlers
.last_rect
.bind(this);
176 this._encHandlers
[encodings
.pseudoEncodingCursor
] = RFB
.encodingHandlers
.Cursor
.bind(this);
177 this._encHandlers
[encodings
.pseudoEncodingQEMUExtendedKeyEvent
] = RFB
.encodingHandlers
.QEMUExtendedKeyEvent
.bind(this);
178 this._encHandlers
[encodings
.pseudoEncodingExtendedDesktopSize
] = RFB
.encodingHandlers
.ExtendedDesktopSize
.bind(this);
180 // NB: nothing that needs explicit teardown should be done
181 // before this point, since this can throw an exception
183 this._display
= new Display(this._canvas
);
185 Log
.Error("Display exception: " + exc
);
188 this._display
.onflush
= this._onFlush
.bind(this);
189 this._display
.clear();
191 this._keyboard
= new Keyboard(this._canvas
);
192 this._keyboard
.onkeyevent
= this._handleKeyEvent
.bind(this);
194 this._mouse
= new Mouse(this._canvas
);
195 this._mouse
.onmousebutton
= this._handleMouseButton
.bind(this);
196 this._mouse
.onmousemove
= this._handleMouseMove
.bind(this);
198 this._sock
= new Websock();
199 this._sock
.on('message', this._handle_message
.bind(this));
200 this._sock
.on('open', function () {
201 if ((this._rfb_connection_state
=== 'connecting') &&
202 (this._rfb_init_state
=== '')) {
203 this._rfb_init_state
= 'ProtocolVersion';
204 Log
.Debug("Starting VNC handshake");
206 this._fail("Unexpected server connection while " +
207 this._rfb_connection_state
);
210 this._sock
.on('close', function (e
) {
211 Log
.Debug("WebSocket on-close event");
214 msg
= "(code: " + e
.code
;
216 msg
+= ", reason: " + e
.reason
;
220 switch (this._rfb_connection_state
) {
222 this._fail("Connection closed " + msg
);
225 // Handle disconnects that were initiated server-side
226 this._updateConnectionState('disconnecting');
227 this._updateConnectionState('disconnected');
229 case 'disconnecting':
230 // Normal disconnection path
231 this._updateConnectionState('disconnected');
234 this._fail("Unexpected server disconnect " +
235 "when already disconnected " + msg
);
238 this._fail("Unexpected server disconnect before connecting " +
242 this._sock
.off('close');
244 this._sock
.on('error', function (e
) {
245 Log
.Warn("WebSocket on-error event");
248 // Slight delay of the actual connection so that the caller has
249 // time to set up callbacks
250 setTimeout(this._updateConnectionState
.bind(this, 'connecting'));
252 Log
.Debug("<< RFB.constructor");
256 // ===== PROPERTIES =====
262 get viewOnly() { return this._viewOnly
; },
263 set viewOnly(viewOnly
) {
264 this._viewOnly
= viewOnly
;
266 if (this._rfb_connection_state
=== "connecting" ||
267 this._rfb_connection_state
=== "connected") {
269 this._keyboard
.ungrab();
270 this._mouse
.ungrab();
272 this._keyboard
.grab();
278 get capabilities() { return this._capabilities
; },
280 get touchButton() { return this._mouse
.touchButton
; },
281 set touchButton(button
) { this._mouse
.touchButton
= button
; },
283 _clipViewport
: false,
284 get clipViewport() { return this._clipViewport
; },
285 set clipViewport(viewport
) {
286 this._clipViewport
= viewport
;
290 _scaleViewport
: false,
291 get scaleViewport() { return this._scaleViewport
; },
292 set scaleViewport(scale
) {
293 this._scaleViewport
= scale
;
294 // Scaling trumps clipping, so we may need to adjust
295 // clipping when enabling or disabling scaling
296 if (scale
&& this._clipViewport
) {
300 if (!scale
&& this._clipViewport
) {
305 _resizeSession
: false,
306 get resizeSession() { return this._resizeSession
; },
307 set resizeSession(resize
) {
308 this._resizeSession
= resize
;
310 this._requestRemoteResize();
314 // ===== PUBLIC METHODS =====
316 disconnect: function () {
317 this._updateConnectionState('disconnecting');
318 this._sock
.off('error');
319 this._sock
.off('message');
320 this._sock
.off('open');
323 sendCredentials: function (creds
) {
324 this._rfb_credentials
= creds
;
325 setTimeout(this._init_msg
.bind(this), 0);
328 sendCtrlAltDel: function () {
329 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
330 Log
.Info("Sending Ctrl-Alt-Del");
332 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", true);
333 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", true);
334 this.sendKey(KeyTable
.XK_Delete
, "Delete", true);
335 this.sendKey(KeyTable
.XK_Delete
, "Delete", false);
336 this.sendKey(KeyTable
.XK_Alt_L
, "AltLeft", false);
337 this.sendKey(KeyTable
.XK_Control_L
, "ControlLeft", false);
340 machineShutdown: function () {
344 machineReboot: function () {
348 machineReset: function () {
352 // Send a key press. If 'down' is not specified then send a down key
353 // followed by an up key.
354 sendKey: function (keysym
, code
, down
) {
355 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
357 if (down
=== undefined) {
358 this.sendKey(keysym
, code
, true);
359 this.sendKey(keysym
, code
, false);
363 var scancode
= XtScancode
[code
];
365 if (this._qemuExtKeyEventSupported
&& scancode
) {
367 keysym
= keysym
|| 0;
369 Log
.Info("Sending key (" + (down
? "down" : "up") + "): keysym " + keysym
+ ", scancode " + scancode
);
371 RFB
.messages
.QEMUExtendedKeyEvent(this._sock
, keysym
, down
, scancode
);
376 Log
.Info("Sending keysym (" + (down
? "down" : "up") + "): " + keysym
);
377 RFB
.messages
.keyEvent(this._sock
, keysym
, down
? 1 : 0);
382 this._canvas
.focus();
389 clipboardPasteFrom: function (text
) {
390 if (this._rfb_connection_state
!== 'connected' || this._viewOnly
) { return; }
391 RFB
.messages
.clientCutText(this._sock
, text
);
394 // ===== PRIVATE METHODS =====
396 _connect: function () {
397 Log
.Debug(">> RFB.connect");
399 Log
.Info("connecting to " + this._url
);
402 // WebSocket.onopen transitions to the RFB init states
403 this._sock
.open(this._url
, ['binary']);
405 if (e
.name
=== 'SyntaxError') {
406 this._fail("Invalid host or port (" + e
+ ")");
408 this._fail("Error when opening socket (" + e
+ ")");
412 // Make our elements part of the page
413 this._target
.appendChild(this._screen
);
415 // Monitor size changes of the screen
416 // FIXME: Use ResizeObserver, or hidden overflow
417 window
.addEventListener('resize', this._eventHandlers
.windowResize
);
419 // Always grab focus on some kind of click event
420 this._canvas
.addEventListener("mousedown", this._eventHandlers
.focusCanvas
);
421 this._canvas
.addEventListener("touchstart", this._eventHandlers
.focusCanvas
);
423 Log
.Debug("<< RFB.connect");
426 _disconnect: function () {
427 Log
.Debug(">> RFB.disconnect");
428 this._canvas
.removeEventListener("mousedown", this._eventHandlers
.focusCanvas
);
429 this._canvas
.removeEventListener("touchstart", this._eventHandlers
.focusCanvas
);
430 window
.removeEventListener('resize', this._eventHandlers
.windowResize
);
431 this._keyboard
.ungrab();
432 this._mouse
.ungrab();
436 this._target
.removeChild(this._screen
);
438 if (e
.name
=== 'NotFoundError') {
439 // Some cases where the initial connection fails
440 // can disconnect before the _screen is created
445 clearTimeout(this._resizeTimeout
);
446 Log
.Debug("<< RFB.disconnect");
449 _print_stats: function () {
450 var stats
= this._encStats
;
452 Log
.Info("Encoding stats for this connection:");
453 Object
.keys(stats
).forEach(function (key
) {
455 if (s
[0] + s
[1] > 0) {
456 Log
.Info(" " + encodingName(key
) + ": " + s
[0] + " rects");
460 Log
.Info("Encoding stats since page load:");
461 Object
.keys(stats
).forEach(function (key
) {
463 Log
.Info(" " + encodingName(key
) + ": " + s
[1] + " rects");
467 _focusCanvas: function(event
) {
468 // Respect earlier handlers' request to not do side-effects
469 if (event
.defaultPrevented
) {
473 if (!this.focusOnClick
) {
480 _windowResize: function (event
) {
481 // If the window resized then our screen element might have
482 // as well. Update the viewport dimensions.
483 window
.requestAnimationFrame(function () {
488 if (this._resizeSession
) {
489 // Request changing the resolution of the remote display to
490 // the size of the local browser viewport.
492 // In order to not send multiple requests before the browser-resize
493 // is finished we wait 0.5 seconds before sending the request.
494 clearTimeout(this._resizeTimeout
);
495 this._resizeTimeout
= setTimeout(this._requestRemoteResize
.bind(this), 500);
499 // Update state of clipping in Display object, and make sure the
500 // configured viewport matches the current screen size
501 _updateClip: function () {
502 var cur_clip
= this._display
.clipViewport
;
503 var new_clip
= this._clipViewport
;
505 if (this._scaleViewport
) {
506 // Disable viewport clipping if we are scaling
510 if (cur_clip
!== new_clip
) {
511 this._display
.clipViewport
= new_clip
;
515 // When clipping is enabled, the screen is limited to
516 // the size of the container.
517 let size
= this._screenSize();
518 this._display
.viewportChangeSize(size
.w
, size
.h
);
519 this._fixScrollbars();
523 _updateScale: function () {
524 if (!this._scaleViewport
) {
525 this._display
.scale
= 1.0;
527 let size
= this._screenSize();
528 this._display
.autoscale(size
.w
, size
.h
);
530 this._fixScrollbars();
533 // Requests a change of remote desktop size. This message is an extension
534 // and may only be sent if we have received an ExtendedDesktopSize message
535 _requestRemoteResize: function () {
536 clearTimeout(this._resizeTimeout
);
537 this._resizeTimeout
= null;
539 if (!this._resizeSession
|| this._viewOnly
||
540 !this._supportsSetDesktopSize
) {
544 let size
= this._screenSize();
545 RFB
.messages
.setDesktopSize(this._sock
, size
.w
, size
.h
,
546 this._screen_id
, this._screen_flags
);
548 Log
.Debug('Requested new desktop size: ' +
549 size
.w
+ 'x' + size
.h
);
552 // Gets the the size of the available screen
553 _screenSize: function () {
554 return { w
: this._screen
.offsetWidth
,
555 h
: this._screen
.offsetHeight
};
558 _fixScrollbars: function () {
559 // This is a hack because Chrome screws up the calculation
560 // for when scrollbars are needed. So to fix it we temporarily
561 // toggle them off and on.
562 var orig
= this._screen
.style
.overflow
;
563 this._screen
.style
.overflow
= 'hidden';
564 // Force Chrome to recalculate the layout by asking for
565 // an element's dimensions
566 this._screen
.getBoundingClientRect();
567 this._screen
.style
.overflow
= orig
;
575 * disconnected - permanent state
577 _updateConnectionState: function (state
) {
578 var oldstate
= this._rfb_connection_state
;
580 if (state
=== oldstate
) {
581 Log
.Debug("Already in state '" + state
+ "', ignoring");
585 // The 'disconnected' state is permanent for each RFB object
586 if (oldstate
=== 'disconnected') {
587 Log
.Error("Tried changing state of a disconnected RFB object");
591 // Ensure proper transitions before doing anything
594 if (oldstate
!== 'connecting') {
595 Log
.Error("Bad transition to connected state, " +
596 "previous connection state: " + oldstate
);
602 if (oldstate
!== 'disconnecting') {
603 Log
.Error("Bad transition to disconnected state, " +
604 "previous connection state: " + oldstate
);
610 if (oldstate
!== '') {
611 Log
.Error("Bad transition to connecting state, " +
612 "previous connection state: " + oldstate
);
617 case 'disconnecting':
618 if (oldstate
!== 'connected' && oldstate
!== 'connecting') {
619 Log
.Error("Bad transition to disconnecting state, " +
620 "previous connection state: " + oldstate
);
626 Log
.Error("Unknown connection state: " + state
);
630 // State change actions
632 this._rfb_connection_state
= state
;
634 var smsg
= "New state '" + state
+ "', was '" + oldstate
+ "'.";
637 if (this._disconnTimer
&& state
!== 'disconnecting') {
638 Log
.Debug("Clearing disconnect timer");
639 clearTimeout(this._disconnTimer
);
640 this._disconnTimer
= null;
642 // make sure we don't get a double event
643 this._sock
.off('close');
652 var event
= new CustomEvent("connect", { detail
: {} });
653 this.dispatchEvent(event
);
656 case 'disconnecting':
659 this._disconnTimer
= setTimeout(function () {
660 Log
.Error("Disconnection timed out.");
661 this._updateConnectionState('disconnected');
662 }.bind(this), DISCONNECT_TIMEOUT
* 1000);
666 event
= new CustomEvent(
667 "disconnect", { detail
:
668 { clean
: this._rfb_clean_disconnect
} });
669 this.dispatchEvent(event
);
674 /* Print errors and disconnect
676 * The parameter 'details' is used for information that
677 * should be logged but not sent to the user interface.
679 _fail: function (details
) {
680 switch (this._rfb_connection_state
) {
681 case 'disconnecting':
682 Log
.Error("Failed when disconnecting: " + details
);
685 Log
.Error("Failed while connected: " + details
);
688 Log
.Error("Failed when connecting: " + details
);
691 Log
.Error("RFB failure: " + details
);
694 this._rfb_clean_disconnect
= false; //This is sent to the UI
696 // Transition to disconnected without waiting for socket to close
697 this._updateConnectionState('disconnecting');
698 this._updateConnectionState('disconnected');
703 _setCapability: function (cap
, val
) {
704 this._capabilities
[cap
] = val
;
705 var event
= new CustomEvent("capabilities",
706 { detail
: { capabilities
: this._capabilities
} });
707 this.dispatchEvent(event
);
710 _handle_message: function () {
711 if (this._sock
.rQlen() === 0) {
712 Log
.Warn("handle_message called on an empty receive queue");
716 switch (this._rfb_connection_state
) {
718 Log
.Error("Got data while disconnected");
722 if (this._flushing
) {
725 if (!this._normal_msg()) {
728 if (this._sock
.rQlen() === 0) {
739 _handleKeyEvent: function (keysym
, code
, down
) {
740 this.sendKey(keysym
, code
, down
);
743 _handleMouseButton: function (x
, y
, down
, bmask
) {
745 this._mouse_buttonMask
|= bmask
;
747 this._mouse_buttonMask
&= ~bmask
;
750 if (this.dragViewport
) {
751 if (down
&& !this._viewportDragging
) {
752 this._viewportDragging
= true;
753 this._viewportDragPos
= {'x': x
, 'y': y
};
754 this._viewportHasMoved
= false;
756 // Skip sending mouse events
759 this._viewportDragging
= false;
761 // If we actually performed a drag then we are done
762 // here and should not send any mouse events
763 if (this._viewportHasMoved
) {
767 // Otherwise we treat this as a mouse click event.
768 // Send the button down event here, as the button up
769 // event is sent at the end of this function.
770 RFB
.messages
.pointerEvent(this._sock
,
771 this._display
.absX(x
),
772 this._display
.absY(y
),
777 if (this._viewOnly
) { return; } // View only, skip mouse events
779 if (this._rfb_connection_state
!== 'connected') { return; }
780 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
783 _handleMouseMove: function (x
, y
) {
784 if (this._viewportDragging
) {
785 var deltaX
= this._viewportDragPos
.x
- x
;
786 var deltaY
= this._viewportDragPos
.y
- y
;
788 // The goal is to trigger on a certain physical width, the
789 // devicePixelRatio brings us a bit closer but is not optimal.
790 var dragThreshold
= 10 * (window
.devicePixelRatio
|| 1);
792 if (this._viewportHasMoved
|| (Math
.abs(deltaX
) > dragThreshold
||
793 Math
.abs(deltaY
) > dragThreshold
)) {
794 this._viewportHasMoved
= true;
796 this._viewportDragPos
= {'x': x
, 'y': y
};
797 this._display
.viewportChangePos(deltaX
, deltaY
);
800 // Skip sending mouse events
804 if (this._viewOnly
) { return; } // View only, skip mouse events
806 if (this._rfb_connection_state
!== 'connected') { return; }
807 RFB
.messages
.pointerEvent(this._sock
, this._display
.absX(x
), this._display
.absY(y
), this._mouse_buttonMask
);
812 _negotiate_protocol_version: function () {
813 if (this._sock
.rQlen() < 12) {
814 return this._fail("Received incomplete protocol version.");
817 var sversion
= this._sock
.rQshiftStr(12).substr(4, 7);
818 Log
.Info("Server ProtocolVersion: " + sversion
);
821 case "000.000": // UltraVNC repeater
825 case "003.006": // UltraVNC
826 case "003.889": // Apple Remote Desktop
827 this._rfb_version
= 3.3;
830 this._rfb_version
= 3.7;
833 case "004.000": // Intel AMT KVM
834 case "004.001": // RealVNC 4.6
835 case "005.000": // RealVNC 5.3
836 this._rfb_version
= 3.8;
839 return this._fail("Invalid server version " + sversion
);
843 var repeaterID
= "ID:" + this._repeaterID
;
844 while (repeaterID
.length
< 250) {
847 this._sock
.send_string(repeaterID
);
851 if (this._rfb_version
> this._rfb_max_version
) {
852 this._rfb_version
= this._rfb_max_version
;
855 var cversion
= "00" + parseInt(this._rfb_version
, 10) +
856 ".00" + ((this._rfb_version
* 10) % 10);
857 this._sock
.send_string("RFB " + cversion
+ "\n");
858 Log
.Debug('Sent ProtocolVersion: ' + cversion
);
860 this._rfb_init_state
= 'Security';
863 _negotiate_security: function () {
864 // Polyfill since IE and PhantomJS doesn't have
865 // TypedArray.includes()
866 function includes(item
, array
) {
867 for (var i
= 0; i
< array
.length
; i
++) {
868 if (array
[i
] === item
) {
875 if (this._rfb_version
>= 3.7) {
876 // Server sends supported list, client decides
877 var num_types
= this._sock
.rQshift8();
878 if (this._sock
.rQwait("security type", num_types
, 1)) { return false; }
880 if (num_types
=== 0) {
881 return this._handle_security_failure("no security types");
884 var types
= this._sock
.rQshiftBytes(num_types
);
885 Log
.Debug("Server security types: " + types
);
887 // Look for each auth in preferred order
888 this._rfb_auth_scheme
= 0;
889 if (includes(1, types
)) {
890 this._rfb_auth_scheme
= 1; // None
891 } else if (includes(22, types
)) {
892 this._rfb_auth_scheme
= 22; // XVP
893 } else if (includes(16, types
)) {
894 this._rfb_auth_scheme
= 16; // Tight
895 } else if (includes(2, types
)) {
896 this._rfb_auth_scheme
= 2; // VNC Auth
898 return this._fail("Unsupported security types (types: " + types
+ ")");
901 this._sock
.send([this._rfb_auth_scheme
]);
904 if (this._sock
.rQwait("security scheme", 4)) { return false; }
905 this._rfb_auth_scheme
= this._sock
.rQshift32();
908 this._rfb_init_state
= 'Authentication';
909 Log
.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme
);
911 return this._init_msg(); // jump to authentication
915 * Get the security failure reason if sent from the server and
916 * send the 'securityfailure' event.
918 * - The optional parameter context can be used to add some extra
919 * context to the log output.
921 * - The optional parameter security_result_status can be used to
922 * add a custom status code to the event.
924 _handle_security_failure: function (context
, security_result_status
) {
926 if (typeof context
=== 'undefined') {
929 context
= " on " + context
;
932 if (typeof security_result_status
=== 'undefined') {
933 security_result_status
= 1; // fail
936 if (this._sock
.rQwait("reason length", 4)) {
939 let strlen
= this._sock
.rQshift32();
943 if (this._sock
.rQwait("reason", strlen
, 8)) { return false; }
944 reason
= this._sock
.rQshiftStr(strlen
);
949 let event
= new CustomEvent(
951 { detail
: { status
: security_result_status
, reason
: reason
} });
952 this.dispatchEvent(event
);
954 return this._fail("Security negotiation failed" + context
+
955 " (reason: " + reason
+ ")");
958 let event
= new CustomEvent(
960 { detail
: { status
: security_result_status
} });
961 this.dispatchEvent(event
);
963 return this._fail("Security negotiation failed" + context
);
968 _negotiate_xvp_auth: function () {
969 if (!this._rfb_credentials
.username
||
970 !this._rfb_credentials
.password
||
971 !this._rfb_credentials
.target
) {
972 var event
= new CustomEvent("credentialsrequired",
973 { detail
: { types
: ["username", "password", "target"] } });
974 this.dispatchEvent(event
);
978 var xvp_auth_str
= String
.fromCharCode(this._rfb_credentials
.username
.length
) +
979 String
.fromCharCode(this._rfb_credentials
.target
.length
) +
980 this._rfb_credentials
.username
+
981 this._rfb_credentials
.target
;
982 this._sock
.send_string(xvp_auth_str
);
983 this._rfb_auth_scheme
= 2;
984 return this._negotiate_authentication();
987 _negotiate_std_vnc_auth: function () {
988 if (this._sock
.rQwait("auth challenge", 16)) { return false; }
990 if (!this._rfb_credentials
.password
) {
991 var event
= new CustomEvent("credentialsrequired",
992 { detail
: { types
: ["password"] } });
993 this.dispatchEvent(event
);
997 // TODO(directxman12): make genDES not require an Array
998 var challenge
= Array
.prototype.slice
.call(this._sock
.rQshiftBytes(16));
999 var response
= RFB
.genDES(this._rfb_credentials
.password
, challenge
);
1000 this._sock
.send(response
);
1001 this._rfb_init_state
= "SecurityResult";
1005 _negotiate_tight_tunnels: function (numTunnels
) {
1006 var clientSupportedTunnelTypes
= {
1007 0: { vendor
: 'TGHT', signature
: 'NOTUNNEL' }
1009 var serverSupportedTunnelTypes
= {};
1010 // receive tunnel capabilities
1011 for (var i
= 0; i
< numTunnels
; i
++) {
1012 var cap_code
= this._sock
.rQshift32();
1013 var cap_vendor
= this._sock
.rQshiftStr(4);
1014 var cap_signature
= this._sock
.rQshiftStr(8);
1015 serverSupportedTunnelTypes
[cap_code
] = { vendor
: cap_vendor
, signature
: cap_signature
};
1018 // choose the notunnel type
1019 if (serverSupportedTunnelTypes
[0]) {
1020 if (serverSupportedTunnelTypes
[0].vendor
!= clientSupportedTunnelTypes
[0].vendor
||
1021 serverSupportedTunnelTypes
[0].signature
!= clientSupportedTunnelTypes
[0].signature
) {
1022 return this._fail("Client's tunnel type had the incorrect " +
1023 "vendor or signature");
1025 this._sock
.send([0, 0, 0, 0]); // use NOTUNNEL
1026 return false; // wait until we receive the sub auth count to continue
1028 return this._fail("Server wanted tunnels, but doesn't support " +
1029 "the notunnel type");
1033 _negotiate_tight_auth: function () {
1034 if (!this._rfb_tightvnc
) { // first pass, do the tunnel negotiation
1035 if (this._sock
.rQwait("num tunnels", 4)) { return false; }
1036 var numTunnels
= this._sock
.rQshift32();
1037 if (numTunnels
> 0 && this._sock
.rQwait("tunnel capabilities", 16 * numTunnels
, 4)) { return false; }
1039 this._rfb_tightvnc
= true;
1041 if (numTunnels
> 0) {
1042 this._negotiate_tight_tunnels(numTunnels
);
1043 return false; // wait until we receive the sub auth to continue
1047 // second pass, do the sub-auth negotiation
1048 if (this._sock
.rQwait("sub auth count", 4)) { return false; }
1049 var subAuthCount
= this._sock
.rQshift32();
1050 if (subAuthCount
=== 0) { // empty sub-auth list received means 'no auth' subtype selected
1051 this._rfb_init_state
= 'SecurityResult';
1055 if (this._sock
.rQwait("sub auth capabilities", 16 * subAuthCount
, 4)) { return false; }
1057 var clientSupportedTypes
= {
1062 var serverSupportedTypes
= [];
1064 for (var i
= 0; i
< subAuthCount
; i
++) {
1065 var capNum
= this._sock
.rQshift32();
1066 var capabilities
= this._sock
.rQshiftStr(12);
1067 serverSupportedTypes
.push(capabilities
);
1070 for (var authType
in clientSupportedTypes
) {
1071 if (serverSupportedTypes
.indexOf(authType
) != -1) {
1072 this._sock
.send([0, 0, 0, clientSupportedTypes
[authType
]]);
1075 case 'STDVNOAUTH__': // no auth
1076 this._rfb_init_state
= 'SecurityResult';
1078 case 'STDVVNCAUTH_': // VNC auth
1079 this._rfb_auth_scheme
= 2;
1080 return this._init_msg();
1082 return this._fail("Unsupported tiny auth scheme " +
1083 "(scheme: " + authType
+ ")");
1088 return this._fail("No supported sub-auth types!");
1091 _negotiate_authentication: function () {
1092 switch (this._rfb_auth_scheme
) {
1093 case 0: // connection failed
1094 return this._handle_security_failure("authentication scheme");
1097 if (this._rfb_version
>= 3.8) {
1098 this._rfb_init_state
= 'SecurityResult';
1101 this._rfb_init_state
= 'ClientInitialisation';
1102 return this._init_msg();
1104 case 22: // XVP auth
1105 return this._negotiate_xvp_auth();
1107 case 2: // VNC authentication
1108 return this._negotiate_std_vnc_auth();
1110 case 16: // TightVNC Security Type
1111 return this._negotiate_tight_auth();
1114 return this._fail("Unsupported auth scheme (scheme: " +
1115 this._rfb_auth_scheme
+ ")");
1119 _handle_security_result: function () {
1120 if (this._sock
.rQwait('VNC auth response ', 4)) { return false; }
1122 let status
= this._sock
.rQshift32();
1124 if (status
=== 0) { // OK
1125 this._rfb_init_state
= 'ClientInitialisation';
1126 Log
.Debug('Authentication OK');
1127 return this._init_msg();
1129 if (this._rfb_version
>= 3.8) {
1130 return this._handle_security_failure("security result", status
);
1132 let event
= new CustomEvent("securityfailure",
1133 { detail
: { status
: status
} });
1134 this.dispatchEvent(event
);
1136 return this._fail("Security handshake failed");
1141 _negotiate_server_init: function () {
1142 if (this._sock
.rQwait("server initialization", 24)) { return false; }
1145 var width
= this._sock
.rQshift16();
1146 var height
= this._sock
.rQshift16();
1149 var bpp
= this._sock
.rQshift8();
1150 var depth
= this._sock
.rQshift8();
1151 var big_endian
= this._sock
.rQshift8();
1152 var true_color
= this._sock
.rQshift8();
1154 var red_max
= this._sock
.rQshift16();
1155 var green_max
= this._sock
.rQshift16();
1156 var blue_max
= this._sock
.rQshift16();
1157 var red_shift
= this._sock
.rQshift8();
1158 var green_shift
= this._sock
.rQshift8();
1159 var blue_shift
= this._sock
.rQshift8();
1160 this._sock
.rQskipBytes(3); // padding
1162 // NB(directxman12): we don't want to call any callbacks or print messages until
1163 // *after* we're past the point where we could backtrack
1165 /* Connection name/title */
1166 var name_length = this._sock.rQshift32();
1167 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1168 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1170 if (this._rfb_tightvnc) {
1171 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1172 // In TightVNC mode, ServerInit message is extended
1173 var numServerMessages = this._sock.rQshift16();
1174 var numClientMessages = this._sock.rQshift16();
1175 var numEncodings = this._sock.rQshift16();
1176 this._sock.rQskipBytes(2); // padding
1178 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1179 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1181 // we don't actually do anything with the capability information that TIGHT sends,
1182 // so we just skip the all of this.
1184 // TIGHT server message capabilities
1185 this._sock.rQskipBytes(16 * numServerMessages);
1187 // TIGHT client message capabilities
1188 this._sock.rQskipBytes(16 * numClientMessages);
1190 // TIGHT encoding capabilities
1191 this._sock.rQskipBytes(16 * numEncodings);
1194 // NB(directxman12): these are down here so that we don't run them multiple times
1196 Log.Info("Screen: " + width + "x" + height +
1197 ", bpp: " + bpp + ", depth: " + depth +
1198 ", big_endian: " + big_endian +
1199 ", true_color: " + true_color +
1200 ", red_max: " + red_max +
1201 ", green_max: " + green_max +
1202 ", blue_max: " + blue_max +
1203 ", red_shift: " + red_shift +
1204 ", green_shift: " + green_shift +
1205 ", blue_shift: " + blue_shift);
1207 if (big_endian !== 0) {
1208 Log.Warn("Server native endian is not little endian");
1211 if (red_shift !== 16) {
1212 Log.Warn("Server native red-shift is not 16");
1215 if (blue_shift !== 0) {
1216 Log.Warn("Server native blue-shift is not 0");
1219 // we're past the point where we could backtrack, so it's safe to call this
1220 var event = new CustomEvent("desktopname",
1221 { detail: { name: this._fb_name } });
1222 this.dispatchEvent(event);
1224 this._resize(width, height);
1226 if (!this._viewOnly) { this._keyboard.grab(); }
1227 if (!this._viewOnly) { this._mouse.grab(); }
1229 this._fb_depth = 24;
1231 if (this._fb_name === "Intel(r) AMT KVM") {
1232 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1236 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
1237 this._sendEncodings();
1238 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1240 this._timing.fbu_rt_start = (new Date()).getTime();
1241 this._timing.pixels = 0;
1243 // Cursor will be server side until the server decides to honor
1244 // our request and send over the cursor image
1245 this._display.disableLocalCursor();
1247 this._updateConnectionState('connected');
1251 _sendEncodings: function () {
1254 // In preference order
1255 encs.push(encodings.encodingCopyRect);
1256 // Only supported with full depth support
1257 if (this._fb_depth == 24) {
1258 encs.push(encodings.encodingTight);
1259 encs.push(encodings.encodingHextile);
1260 encs.push(encodings.encodingRRE);
1262 encs.push(encodings.encodingRaw);
1264 // Psuedo-encoding settings
1265 encs.push(encodings.pseudoEncodingTightPNG);
1266 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1267 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1269 encs.push(encodings.pseudoEncodingDesktopSize);
1270 encs.push(encodings.pseudoEncodingLastRect);
1271 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1272 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1273 encs.push(encodings.pseudoEncodingXvp);
1274 encs.push(encodings.pseudoEncodingFence);
1275 encs.push(encodings.pseudoEncodingContinuousUpdates);
1277 if (supportsCursorURIs() &&
1278 !isTouchDevice && this._fb_depth == 24) {
1279 encs.push(encodings.pseudoEncodingCursor);
1282 RFB.messages.clientEncodings(this._sock, encs);
1285 /* RFB protocol initialization states:
1290 * ClientInitialization - not triggered by server message
1291 * ServerInitialization
1293 _init_msg: function () {
1294 switch (this._rfb_init_state
) {
1295 case 'ProtocolVersion':
1296 return this._negotiate_protocol_version();
1299 return this._negotiate_security();
1301 case 'Authentication':
1302 return this._negotiate_authentication();
1304 case 'SecurityResult':
1305 return this._handle_security_result();
1307 case 'ClientInitialisation':
1308 this._sock
.send([this._shared
? 1 : 0]); // ClientInitialisation
1309 this._rfb_init_state
= 'ServerInitialisation';
1312 case 'ServerInitialisation':
1313 return this._negotiate_server_init();
1316 return this._fail("Unknown init state (state: " +
1317 this._rfb_init_state
+ ")");
1321 _handle_set_colour_map_msg: function () {
1322 Log
.Debug("SetColorMapEntries");
1324 return this._fail("Unexpected SetColorMapEntries message");
1327 _handle_server_cut_text: function () {
1328 Log
.Debug("ServerCutText");
1330 if (this._sock
.rQwait("ServerCutText header", 7, 1)) { return false; }
1331 this._sock
.rQskipBytes(3); // Padding
1332 var length
= this._sock
.rQshift32();
1333 if (this._sock
.rQwait("ServerCutText", length
, 8)) { return false; }
1335 var text
= this._sock
.rQshiftStr(length
);
1337 if (this._viewOnly
) { return true; }
1339 var event
= new CustomEvent("clipboard",
1340 { detail
: { text
: text
} });
1341 this.dispatchEvent(event
);
1346 _handle_server_fence_msg: function() {
1347 if (this._sock
.rQwait("ServerFence header", 8, 1)) { return false; }
1348 this._sock
.rQskipBytes(3); // Padding
1349 var flags
= this._sock
.rQshift32();
1350 var length
= this._sock
.rQshift8();
1352 if (this._sock
.rQwait("ServerFence payload", length
, 9)) { return false; }
1355 Log
.Warn("Bad payload length (" + length
+ ") in fence response");
1359 var payload
= this._sock
.rQshiftStr(length
);
1361 this._supportsFence
= true;
1366 * (1<<0) - BlockBefore
1367 * (1<<1) - BlockAfter
1372 if (!(flags
& (1<<31))) {
1373 return this._fail("Unexpected fence response");
1376 // Filter out unsupported flags
1377 // FIXME: support syncNext
1378 flags
&= (1<<0) | (1<<1);
1380 // BlockBefore and BlockAfter are automatically handled by
1381 // the fact that we process each incoming message
1383 RFB
.messages
.clientFence(this._sock
, flags
, payload
);
1388 _handle_xvp_msg: function () {
1389 if (this._sock
.rQwait("XVP version and message", 3, 1)) { return false; }
1390 this._sock
.rQskip8(); // Padding
1391 var xvp_ver
= this._sock
.rQshift8();
1392 var xvp_msg
= this._sock
.rQshift8();
1396 Log
.Error("XVP Operation Failed");
1399 this._rfb_xvp_ver
= xvp_ver
;
1400 Log
.Info("XVP extensions enabled (version " + this._rfb_xvp_ver
+ ")");
1401 this._setCapability("power", true);
1404 this._fail("Illegal server XVP message (msg: " + xvp_msg
+ ")");
1411 _normal_msg: function () {
1414 if (this._FBU
.rects
> 0) {
1417 msg_type
= this._sock
.rQshift8();
1421 case 0: // FramebufferUpdate
1422 var ret
= this._framebufferUpdate();
1423 if (ret
&& !this._enabledContinuousUpdates
) {
1424 RFB
.messages
.fbUpdateRequest(this._sock
, true, 0, 0,
1425 this._fb_width
, this._fb_height
);
1429 case 1: // SetColorMapEntries
1430 return this._handle_set_colour_map_msg();
1434 var event
= new CustomEvent("bell", { detail
: {} });
1435 this.dispatchEvent(event
);
1438 case 3: // ServerCutText
1439 return this._handle_server_cut_text();
1441 case 150: // EndOfContinuousUpdates
1442 var first
= !(this._supportsContinuousUpdates
);
1443 this._supportsContinuousUpdates
= true;
1444 this._enabledContinuousUpdates
= false;
1446 this._enabledContinuousUpdates
= true;
1447 this._updateContinuousUpdates();
1448 Log
.Info("Enabling continuous updates.");
1450 // FIXME: We need to send a framebufferupdaterequest here
1451 // if we add support for turning off continuous updates
1455 case 248: // ServerFence
1456 return this._handle_server_fence_msg();
1459 return this._handle_xvp_msg();
1462 this._fail("Unexpected server message (type " + msg_type
+ ")");
1463 Log
.Debug("sock.rQslice(0, 30): " + this._sock
.rQslice(0, 30));
1468 _onFlush: function() {
1469 this._flushing
= false;
1470 // Resume processing
1471 if (this._sock
.rQlen() > 0) {
1472 this._handle_message();
1476 _framebufferUpdate: function () {
1480 if (this._FBU
.rects
=== 0) {
1481 if (this._sock
.rQwait("FBU header", 3, 1)) { return false; }
1482 this._sock
.rQskip8(); // Padding
1483 this._FBU
.rects
= this._sock
.rQshift16();
1484 this._FBU
.bytes
= 0;
1485 this._timing
.cur_fbu
= 0;
1486 if (this._timing
.fbu_rt_start
> 0) {
1487 now
= (new Date()).getTime();
1488 Log
.Info("First FBU latency: " + (now
- this._timing
.fbu_rt_start
));
1491 // Make sure the previous frame is fully rendered first
1492 // to avoid building up an excessive queue
1493 if (this._display
.pending()) {
1494 this._flushing
= true;
1495 this._display
.flush();
1500 while (this._FBU
.rects
> 0) {
1501 if (this._rfb_connection_state
!== 'connected') { return false; }
1503 if (this._sock
.rQwait("FBU", this._FBU
.bytes
)) { return false; }
1504 if (this._FBU
.bytes
=== 0) {
1505 if (this._sock
.rQwait("rect header", 12)) { return false; }
1506 /* New FramebufferUpdate */
1508 var hdr
= this._sock
.rQshiftBytes(12);
1509 this._FBU
.x
= (hdr
[0] << 8) + hdr
[1];
1510 this._FBU
.y
= (hdr
[2] << 8) + hdr
[3];
1511 this._FBU
.width
= (hdr
[4] << 8) + hdr
[5];
1512 this._FBU
.height
= (hdr
[6] << 8) + hdr
[7];
1513 this._FBU
.encoding
= parseInt((hdr
[8] << 24) + (hdr
[9] << 16) +
1514 (hdr
[10] << 8) + hdr
[11], 10);
1516 if (!this._encHandlers
[this._FBU
.encoding
]) {
1517 this._fail("Unsupported encoding (encoding: " +
1518 this._FBU
.encoding
+ ")");
1523 this._timing
.last_fbu
= (new Date()).getTime();
1525 ret
= this._encHandlers
[this._FBU
.encoding
]();
1527 now
= (new Date()).getTime();
1528 this._timing
.cur_fbu
+= (now
- this._timing
.last_fbu
);
1531 if (!(this._FBU
.encoding
in this._encStats
)) {
1532 this._encStats
[this._FBU
.encoding
] = [0, 0];
1534 this._encStats
[this._FBU
.encoding
][0]++;
1535 this._encStats
[this._FBU
.encoding
][1]++;
1536 this._timing
.pixels
+= this._FBU
.width
* this._FBU
.height
;
1539 if (this._timing
.pixels
>= (this._fb_width
* this._fb_height
)) {
1540 if ((this._FBU
.width
=== this._fb_width
&& this._FBU
.height
=== this._fb_height
) ||
1541 this._timing
.fbu_rt_start
> 0) {
1542 this._timing
.full_fbu_total
+= this._timing
.cur_fbu
;
1543 this._timing
.full_fbu_cnt
++;
1544 Log
.Info("Timing of full FBU, curr: " +
1545 this._timing
.cur_fbu
+ ", total: " +
1546 this._timing
.full_fbu_total
+ ", cnt: " +
1547 this._timing
.full_fbu_cnt
+ ", avg: " +
1548 (this._timing
.full_fbu_total
/ this._timing
.full_fbu_cnt
));
1551 if (this._timing
.fbu_rt_start
> 0) {
1552 var fbu_rt_diff
= now
- this._timing
.fbu_rt_start
;
1553 this._timing
.fbu_rt_total
+= fbu_rt_diff
;
1554 this._timing
.fbu_rt_cnt
++;
1555 Log
.Info("full FBU round-trip, cur: " +
1556 fbu_rt_diff
+ ", total: " +
1557 this._timing
.fbu_rt_total
+ ", cnt: " +
1558 this._timing
.fbu_rt_cnt
+ ", avg: " +
1559 (this._timing
.fbu_rt_total
/ this._timing
.fbu_rt_cnt
));
1560 this._timing
.fbu_rt_start
= 0;
1564 if (!ret
) { return ret
; } // need more data
1567 this._display
.flip();
1569 return true; // We finished this FBU
1572 _updateContinuousUpdates: function() {
1573 if (!this._enabledContinuousUpdates
) { return; }
1575 RFB
.messages
.enableContinuousUpdates(this._sock
, true, 0, 0,
1576 this._fb_width
, this._fb_height
);
1579 _resize: function(width
, height
) {
1580 this._fb_width
= width
;
1581 this._fb_height
= height
;
1583 this._destBuff
= new Uint8Array(this._fb_width
* this._fb_height
* 4);
1585 this._display
.resize(this._fb_width
, this._fb_height
);
1587 // Adjust the visible viewport based on the new dimensions
1589 this._updateScale();
1591 this._timing
.fbu_rt_start
= (new Date()).getTime();
1592 this._updateContinuousUpdates();
1595 _xvpOp: function (ver
, op
) {
1596 if (this._rfb_xvp_ver
< ver
) { return; }
1597 Log
.Info("Sending XVP operation " + op
+ " (version " + ver
+ ")");
1598 RFB
.messages
.xvpOp(this._sock
, ver
, op
);
1602 Object
.assign(RFB
.prototype, EventTargetMixin
);
1606 keyEvent: function (sock
, keysym
, down
) {
1607 var buff
= sock
._sQ
;
1608 var offset
= sock
._sQlen
;
1610 buff
[offset
] = 4; // msg-type
1611 buff
[offset
+ 1] = down
;
1613 buff
[offset
+ 2] = 0;
1614 buff
[offset
+ 3] = 0;
1616 buff
[offset
+ 4] = (keysym
>> 24);
1617 buff
[offset
+ 5] = (keysym
>> 16);
1618 buff
[offset
+ 6] = (keysym
>> 8);
1619 buff
[offset
+ 7] = keysym
;
1625 QEMUExtendedKeyEvent: function (sock
, keysym
, down
, keycode
) {
1626 function getRFBkeycode(xt_scancode
) {
1627 var upperByte
= (keycode
>> 8);
1628 var lowerByte
= (keycode
& 0x00ff);
1629 if (upperByte
=== 0xe0 && lowerByte
< 0x7f) {
1630 lowerByte
= lowerByte
| 0x80;
1636 var buff
= sock
._sQ
;
1637 var offset
= sock
._sQlen
;
1639 buff
[offset
] = 255; // msg-type
1640 buff
[offset
+ 1] = 0; // sub msg-type
1642 buff
[offset
+ 2] = (down
>> 8);
1643 buff
[offset
+ 3] = down
;
1645 buff
[offset
+ 4] = (keysym
>> 24);
1646 buff
[offset
+ 5] = (keysym
>> 16);
1647 buff
[offset
+ 6] = (keysym
>> 8);
1648 buff
[offset
+ 7] = keysym
;
1650 var RFBkeycode
= getRFBkeycode(keycode
);
1652 buff
[offset
+ 8] = (RFBkeycode
>> 24);
1653 buff
[offset
+ 9] = (RFBkeycode
>> 16);
1654 buff
[offset
+ 10] = (RFBkeycode
>> 8);
1655 buff
[offset
+ 11] = RFBkeycode
;
1661 pointerEvent: function (sock
, x
, y
, mask
) {
1662 var buff
= sock
._sQ
;
1663 var offset
= sock
._sQlen
;
1665 buff
[offset
] = 5; // msg-type
1667 buff
[offset
+ 1] = mask
;
1669 buff
[offset
+ 2] = x
>> 8;
1670 buff
[offset
+ 3] = x
;
1672 buff
[offset
+ 4] = y
>> 8;
1673 buff
[offset
+ 5] = y
;
1679 // TODO(directxman12): make this unicode compatible?
1680 clientCutText: function (sock
, text
) {
1681 var buff
= sock
._sQ
;
1682 var offset
= sock
._sQlen
;
1684 buff
[offset
] = 6; // msg-type
1686 buff
[offset
+ 1] = 0; // padding
1687 buff
[offset
+ 2] = 0; // padding
1688 buff
[offset
+ 3] = 0; // padding
1690 var n
= text
.length
;
1692 buff
[offset
+ 4] = n
>> 24;
1693 buff
[offset
+ 5] = n
>> 16;
1694 buff
[offset
+ 6] = n
>> 8;
1695 buff
[offset
+ 7] = n
;
1697 for (var i
= 0; i
< n
; i
++) {
1698 buff
[offset
+ 8 + i
] = text
.charCodeAt(i
);
1701 sock
._sQlen
+= 8 + n
;
1705 setDesktopSize: function (sock
, width
, height
, id
, flags
) {
1706 var buff
= sock
._sQ
;
1707 var offset
= sock
._sQlen
;
1709 buff
[offset
] = 251; // msg-type
1710 buff
[offset
+ 1] = 0; // padding
1711 buff
[offset
+ 2] = width
>> 8; // width
1712 buff
[offset
+ 3] = width
;
1713 buff
[offset
+ 4] = height
>> 8; // height
1714 buff
[offset
+ 5] = height
;
1716 buff
[offset
+ 6] = 1; // number-of-screens
1717 buff
[offset
+ 7] = 0; // padding
1720 buff
[offset
+ 8] = id
>> 24; // id
1721 buff
[offset
+ 9] = id
>> 16;
1722 buff
[offset
+ 10] = id
>> 8;
1723 buff
[offset
+ 11] = id
;
1724 buff
[offset
+ 12] = 0; // x-position
1725 buff
[offset
+ 13] = 0;
1726 buff
[offset
+ 14] = 0; // y-position
1727 buff
[offset
+ 15] = 0;
1728 buff
[offset
+ 16] = width
>> 8; // width
1729 buff
[offset
+ 17] = width
;
1730 buff
[offset
+ 18] = height
>> 8; // height
1731 buff
[offset
+ 19] = height
;
1732 buff
[offset
+ 20] = flags
>> 24; // flags
1733 buff
[offset
+ 21] = flags
>> 16;
1734 buff
[offset
+ 22] = flags
>> 8;
1735 buff
[offset
+ 23] = flags
;
1741 clientFence: function (sock
, flags
, payload
) {
1742 var buff
= sock
._sQ
;
1743 var offset
= sock
._sQlen
;
1745 buff
[offset
] = 248; // msg-type
1747 buff
[offset
+ 1] = 0; // padding
1748 buff
[offset
+ 2] = 0; // padding
1749 buff
[offset
+ 3] = 0; // padding
1751 buff
[offset
+ 4] = flags
>> 24; // flags
1752 buff
[offset
+ 5] = flags
>> 16;
1753 buff
[offset
+ 6] = flags
>> 8;
1754 buff
[offset
+ 7] = flags
;
1756 var n
= payload
.length
;
1758 buff
[offset
+ 8] = n
; // length
1760 for (var i
= 0; i
< n
; i
++) {
1761 buff
[offset
+ 9 + i
] = payload
.charCodeAt(i
);
1764 sock
._sQlen
+= 9 + n
;
1768 enableContinuousUpdates: function (sock
, enable
, x
, y
, width
, height
) {
1769 var buff
= sock
._sQ
;
1770 var offset
= sock
._sQlen
;
1772 buff
[offset
] = 150; // msg-type
1773 buff
[offset
+ 1] = enable
; // enable-flag
1775 buff
[offset
+ 2] = x
>> 8; // x
1776 buff
[offset
+ 3] = x
;
1777 buff
[offset
+ 4] = y
>> 8; // y
1778 buff
[offset
+ 5] = y
;
1779 buff
[offset
+ 6] = width
>> 8; // width
1780 buff
[offset
+ 7] = width
;
1781 buff
[offset
+ 8] = height
>> 8; // height
1782 buff
[offset
+ 9] = height
;
1788 pixelFormat: function (sock
, depth
, true_color
) {
1789 var buff
= sock
._sQ
;
1790 var offset
= sock
._sQlen
;
1796 } else if (depth
> 8) {
1802 bits
= Math
.floor(depth
/3);
1804 buff
[offset
] = 0; // msg-type
1806 buff
[offset
+ 1] = 0; // padding
1807 buff
[offset
+ 2] = 0; // padding
1808 buff
[offset
+ 3] = 0; // padding
1810 buff
[offset
+ 4] = bpp
; // bits-per-pixel
1811 buff
[offset
+ 5] = depth
; // depth
1812 buff
[offset
+ 6] = 0; // little-endian
1813 buff
[offset
+ 7] = true_color
? 1 : 0; // true-color
1815 buff
[offset
+ 8] = 0; // red-max
1816 buff
[offset
+ 9] = (1 << bits
) - 1; // red-max
1818 buff
[offset
+ 10] = 0; // green-max
1819 buff
[offset
+ 11] = (1 << bits
) - 1; // green-max
1821 buff
[offset
+ 12] = 0; // blue-max
1822 buff
[offset
+ 13] = (1 << bits
) - 1; // blue-max
1824 buff
[offset
+ 14] = bits
* 2; // red-shift
1825 buff
[offset
+ 15] = bits
* 1; // green-shift
1826 buff
[offset
+ 16] = bits
* 0; // blue-shift
1828 buff
[offset
+ 17] = 0; // padding
1829 buff
[offset
+ 18] = 0; // padding
1830 buff
[offset
+ 19] = 0; // padding
1836 clientEncodings: function (sock
, encodings
) {
1837 var buff
= sock
._sQ
;
1838 var offset
= sock
._sQlen
;
1840 buff
[offset
] = 2; // msg-type
1841 buff
[offset
+ 1] = 0; // padding
1843 buff
[offset
+ 2] = encodings
.length
>> 8;
1844 buff
[offset
+ 3] = encodings
.length
;
1846 var i
, j
= offset
+ 4;
1847 for (i
= 0; i
< encodings
.length
; i
++) {
1848 var enc
= encodings
[i
];
1849 buff
[j
] = enc
>> 24;
1850 buff
[j
+ 1] = enc
>> 16;
1851 buff
[j
+ 2] = enc
>> 8;
1857 sock
._sQlen
+= j
- offset
;
1861 fbUpdateRequest: function (sock
, incremental
, x
, y
, w
, h
) {
1862 var buff
= sock
._sQ
;
1863 var offset
= sock
._sQlen
;
1865 if (typeof(x
) === "undefined") { x
= 0; }
1866 if (typeof(y
) === "undefined") { y
= 0; }
1868 buff
[offset
] = 3; // msg-type
1869 buff
[offset
+ 1] = incremental
? 1 : 0;
1871 buff
[offset
+ 2] = (x
>> 8) & 0xFF;
1872 buff
[offset
+ 3] = x
& 0xFF;
1874 buff
[offset
+ 4] = (y
>> 8) & 0xFF;
1875 buff
[offset
+ 5] = y
& 0xFF;
1877 buff
[offset
+ 6] = (w
>> 8) & 0xFF;
1878 buff
[offset
+ 7] = w
& 0xFF;
1880 buff
[offset
+ 8] = (h
>> 8) & 0xFF;
1881 buff
[offset
+ 9] = h
& 0xFF;
1887 xvpOp: function (sock
, ver
, op
) {
1888 var buff
= sock
._sQ
;
1889 var offset
= sock
._sQlen
;
1891 buff
[offset
] = 250; // msg-type
1892 buff
[offset
+ 1] = 0; // padding
1894 buff
[offset
+ 2] = ver
;
1895 buff
[offset
+ 3] = op
;
1902 RFB
.genDES = function (password
, challenge
) {
1904 for (var i
= 0; i
< password
.length
; i
++) {
1905 passwd
.push(password
.charCodeAt(i
));
1907 return (new DES(passwd
)).encrypt(challenge
);
1910 RFB
.encodingHandlers
= {
1912 if (this._FBU
.lines
=== 0) {
1913 this._FBU
.lines
= this._FBU
.height
;
1916 var pixelSize
= this._fb_depth
== 8 ? 1 : 4;
1917 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // at least a line
1918 if (this._sock
.rQwait("RAW", this._FBU
.bytes
)) { return false; }
1919 var cur_y
= this._FBU
.y
+ (this._FBU
.height
- this._FBU
.lines
);
1920 var curr_height
= Math
.min(this._FBU
.lines
,
1921 Math
.floor(this._sock
.rQlen() / (this._FBU
.width
* pixelSize
)));
1922 var data
= this._sock
.get_rQ();
1923 var index
= this._sock
.get_rQi();
1924 if (this._fb_depth
== 8) {
1925 var pixels
= this._FBU
.width
* curr_height
1926 var newdata
= new Uint8Array(pixels
* 4);
1928 for (i
= 0;i
< pixels
;i
++) {
1929 newdata
[i
* 4 + 0] = ((data
[index
+ i
] >> 0) & 0x3) * 255 / 3;
1930 newdata
[i
* 4 + 1] = ((data
[index
+ i
] >> 2) & 0x3) * 255 / 3;
1931 newdata
[i
* 4 + 2] = ((data
[index
+ i
] >> 4) & 0x3) * 255 / 3;
1932 newdata
[i
* 4 + 4] = 0;
1937 this._display
.blitImage(this._FBU
.x
, cur_y
, this._FBU
.width
,
1938 curr_height
, data
, index
);
1939 this._sock
.rQskipBytes(this._FBU
.width
* curr_height
* pixelSize
);
1940 this._FBU
.lines
-= curr_height
;
1942 if (this._FBU
.lines
> 0) {
1943 this._FBU
.bytes
= this._FBU
.width
* pixelSize
; // At least another line
1946 this._FBU
.bytes
= 0;
1952 COPYRECT: function () {
1953 this._FBU
.bytes
= 4;
1954 if (this._sock
.rQwait("COPYRECT", 4)) { return false; }
1955 this._display
.copyImage(this._sock
.rQshift16(), this._sock
.rQshift16(),
1956 this._FBU
.x
, this._FBU
.y
, this._FBU
.width
,
1960 this._FBU
.bytes
= 0;
1966 if (this._FBU
.subrects
=== 0) {
1967 this._FBU
.bytes
= 4 + 4;
1968 if (this._sock
.rQwait("RRE", 4 + 4)) { return false; }
1969 this._FBU
.subrects
= this._sock
.rQshift32();
1970 color
= this._sock
.rQshiftBytes(4); // Background
1971 this._display
.fillRect(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, color
);
1974 while (this._FBU
.subrects
> 0 && this._sock
.rQlen() >= (4 + 8)) {
1975 color
= this._sock
.rQshiftBytes(4);
1976 var x
= this._sock
.rQshift16();
1977 var y
= this._sock
.rQshift16();
1978 var width
= this._sock
.rQshift16();
1979 var height
= this._sock
.rQshift16();
1980 this._display
.fillRect(this._FBU
.x
+ x
, this._FBU
.y
+ y
, width
, height
, color
);
1981 this._FBU
.subrects
--;
1984 if (this._FBU
.subrects
> 0) {
1985 var chunk
= Math
.min(this._rre_chunk_sz
, this._FBU
.subrects
);
1986 this._FBU
.bytes
= (4 + 8) * chunk
;
1989 this._FBU
.bytes
= 0;
1995 HEXTILE: function () {
1996 var rQ
= this._sock
.get_rQ();
1997 var rQi
= this._sock
.get_rQi();
1999 if (this._FBU
.tiles
=== 0) {
2000 this._FBU
.tiles_x
= Math
.ceil(this._FBU
.width
/ 16);
2001 this._FBU
.tiles_y
= Math
.ceil(this._FBU
.height
/ 16);
2002 this._FBU
.total_tiles
= this._FBU
.tiles_x
* this._FBU
.tiles_y
;
2003 this._FBU
.tiles
= this._FBU
.total_tiles
;
2006 while (this._FBU
.tiles
> 0) {
2007 this._FBU
.bytes
= 1;
2008 if (this._sock
.rQwait("HEXTILE subencoding", this._FBU
.bytes
)) { return false; }
2009 var subencoding
= rQ
[rQi
]; // Peek
2010 if (subencoding
> 30) { // Raw
2011 this._fail("Illegal hextile subencoding (subencoding: " +
2017 var curr_tile
= this._FBU
.total_tiles
- this._FBU
.tiles
;
2018 var tile_x
= curr_tile
% this._FBU
.tiles_x
;
2019 var tile_y
= Math
.floor(curr_tile
/ this._FBU
.tiles_x
);
2020 var x
= this._FBU
.x
+ tile_x
* 16;
2021 var y
= this._FBU
.y
+ tile_y
* 16;
2022 var w
= Math
.min(16, (this._FBU
.x
+ this._FBU
.width
) - x
);
2023 var h
= Math
.min(16, (this._FBU
.y
+ this._FBU
.height
) - y
);
2025 // Figure out how much we are expecting
2026 if (subencoding
& 0x01) { // Raw
2027 this._FBU
.bytes
+= w
* h
* 4;
2029 if (subencoding
& 0x02) { // Background
2030 this._FBU
.bytes
+= 4;
2032 if (subencoding
& 0x04) { // Foreground
2033 this._FBU
.bytes
+= 4;
2035 if (subencoding
& 0x08) { // AnySubrects
2036 this._FBU
.bytes
++; // Since we aren't shifting it off
2037 if (this._sock
.rQwait("hextile subrects header", this._FBU
.bytes
)) { return false; }
2038 subrects
= rQ
[rQi
+ this._FBU
.bytes
- 1]; // Peek
2039 if (subencoding
& 0x10) { // SubrectsColoured
2040 this._FBU
.bytes
+= subrects
* (4 + 2);
2042 this._FBU
.bytes
+= subrects
* 2;
2047 if (this._sock
.rQwait("hextile", this._FBU
.bytes
)) { return false; }
2049 // We know the encoding and have a whole tile
2050 this._FBU
.subencoding
= rQ
[rQi
];
2052 if (this._FBU
.subencoding
=== 0) {
2053 if (this._FBU
.lastsubencoding
& 0x01) {
2054 // Weird: ignore blanks are RAW
2055 Log
.Debug(" Ignoring blank after RAW");
2057 this._display
.fillRect(x
, y
, w
, h
, this._FBU
.background
);
2059 } else if (this._FBU
.subencoding
& 0x01) { // Raw
2060 this._display
.blitImage(x
, y
, w
, h
, rQ
, rQi
);
2061 rQi
+= this._FBU
.bytes
- 1;
2063 if (this._FBU
.subencoding
& 0x02) { // Background
2064 this._FBU
.background
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2067 if (this._FBU
.subencoding
& 0x04) { // Foreground
2068 this._FBU
.foreground
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2072 this._display
.startTile(x
, y
, w
, h
, this._FBU
.background
);
2073 if (this._FBU
.subencoding
& 0x08) { // AnySubrects
2077 for (var s
= 0; s
< subrects
; s
++) {
2079 if (this._FBU
.subencoding
& 0x10) { // SubrectsColoured
2080 color
= [rQ
[rQi
], rQ
[rQi
+ 1], rQ
[rQi
+ 2], rQ
[rQi
+ 3]];
2083 color
= this._FBU
.foreground
;
2088 var sy
= (xy
& 0x0f);
2092 var sw
= (wh
>> 4) + 1;
2093 var sh
= (wh
& 0x0f) + 1;
2095 this._display
.subTile(sx
, sy
, sw
, sh
, color
);
2098 this._display
.finishTile();
2100 this._sock
.set_rQi(rQi
);
2101 this._FBU
.lastsubencoding
= this._FBU
.subencoding
;
2102 this._FBU
.bytes
= 0;
2106 if (this._FBU
.tiles
=== 0) {
2113 TIGHT: function () {
2114 this._FBU
.bytes
= 1; // compression-control byte
2115 if (this._sock
.rQwait("TIGHT compression-control", this._FBU
.bytes
)) { return false; }
2117 var checksum = function (data
) {
2119 for (var i
= 0; i
< data
.length
; i
++) {
2121 if (sum
> 65536) sum
-= 65536;
2126 var resetStreams
= 0;
2128 var decompress = function (data
, expected
) {
2129 for (var i
= 0; i
< 4; i
++) {
2130 if ((resetStreams
>> i
) & 1) {
2131 this._FBU
.zlibs
[i
].reset();
2132 Log
.Info("Reset zlib stream " + i
);
2136 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2137 var uncompressed
= this._FBU
.zlibs
[streamId
].inflate(data
, true, expected
);
2138 /*if (uncompressed.status !== 0) {
2139 Log.Error("Invalid data in zlib stream");
2142 //return uncompressed.data;
2143 return uncompressed
;
2146 var indexedToRGBX2Color = function (data
, palette
, width
, height
) {
2147 // Convert indexed (palette based) image data to RGB
2148 // TODO: reduce number of calculations inside loop
2149 var dest
= this._destBuff
;
2150 var w
= Math
.floor((width
+ 7) / 8);
2151 var w1
= Math
.floor(width
/ 8);
2153 /*for (var y = 0; y < height; y++) {
2155 var yoffset = y * width;
2156 var ybitoffset = y * w;
2157 var xoffset, targetbyte;
2158 for (x = 0; x < w1; x++) {
2159 xoffset = yoffset + x * 8;
2160 targetbyte = data[ybitoffset + x];
2161 for (b = 7; b >= 0; b--) {
2162 dp = (xoffset + 7 - b) * 3;
2163 sp = (targetbyte >> b & 1) * 3;
2164 dest[dp] = palette[sp];
2165 dest[dp + 1] = palette[sp + 1];
2166 dest[dp + 2] = palette[sp + 2];
2170 xoffset = yoffset + x * 8;
2171 targetbyte = data[ybitoffset + x];
2172 for (b = 7; b >= 8 - width % 8; b--) {
2173 dp = (xoffset + 7 - b) * 3;
2174 sp = (targetbyte >> b & 1) * 3;
2175 dest[dp] = palette[sp];
2176 dest[dp + 1] = palette[sp + 1];
2177 dest[dp + 2] = palette[sp + 2];
2181 for (var y
= 0; y
< height
; y
++) {
2183 for (x
= 0; x
< w1
; x
++) {
2184 for (b
= 7; b
>= 0; b
--) {
2185 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2186 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2187 dest
[dp
] = palette
[sp
];
2188 dest
[dp
+ 1] = palette
[sp
+ 1];
2189 dest
[dp
+ 2] = palette
[sp
+ 2];
2194 for (b
= 7; b
>= 8 - width
% 8; b
--) {
2195 dp
= (y
* width
+ x
* 8 + 7 - b
) * 4;
2196 sp
= (data
[y
* w
+ x
] >> b
& 1) * 3;
2197 dest
[dp
] = palette
[sp
];
2198 dest
[dp
+ 1] = palette
[sp
+ 1];
2199 dest
[dp
+ 2] = palette
[sp
+ 2];
2207 var indexedToRGBX = function (data
, palette
, width
, height
) {
2208 // Convert indexed (palette based) image data to RGB
2209 var dest
= this._destBuff
;
2210 var total
= width
* height
* 4;
2211 for (var i
= 0, j
= 0; i
< total
; i
+= 4, j
++) {
2212 var sp
= data
[j
] * 3;
2213 dest
[i
] = palette
[sp
];
2214 dest
[i
+ 1] = palette
[sp
+ 1];
2215 dest
[i
+ 2] = palette
[sp
+ 2];
2222 var rQi
= this._sock
.get_rQi();
2223 var rQ
= this._sock
.rQwhole();
2225 var cl_header
, cl_data
;
2227 var handlePalette = function () {
2228 var numColors
= rQ
[rQi
+ 2] + 1;
2229 var paletteSize
= numColors
* 3;
2230 this._FBU
.bytes
+= paletteSize
;
2231 if (this._sock
.rQwait("TIGHT palette " + cmode
, this._FBU
.bytes
)) { return false; }
2233 var bpp
= (numColors
<= 2) ? 1 : 8;
2234 var rowSize
= Math
.floor((this._FBU
.width
* bpp
+ 7) / 8);
2236 if (rowSize
* this._FBU
.height
< 12) {
2239 cl_data
= rowSize
* this._FBU
.height
;
2240 //clength = [0, rowSize * this._FBU.height];
2242 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2243 var cl_offset
= rQi
+ 3 + paletteSize
;
2246 cl_data
+= rQ
[cl_offset
] & 0x7f;
2247 if (rQ
[cl_offset
] & 0x80) {
2249 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2250 if (rQ
[cl_offset
+ 1] & 0x80) {
2252 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2255 // end inline getTightCLength
2258 this._FBU
.bytes
+= cl_header
+ cl_data
;
2259 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2261 // Shift ctl, filter id, num colors, palette entries, and clength off
2262 this._sock
.rQskipBytes(3);
2263 //var palette = this._sock.rQshiftBytes(paletteSize);
2264 this._sock
.rQshiftTo(this._paletteBuff
, paletteSize
);
2265 this._sock
.rQskipBytes(cl_header
);
2268 data
= this._sock
.rQshiftBytes(cl_data
);
2270 data
= decompress(this._sock
.rQshiftBytes(cl_data
), rowSize
* this._FBU
.height
);
2273 // Convert indexed (palette based) image data to RGB
2275 if (numColors
== 2) {
2276 rgbx
= indexedToRGBX2Color(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2277 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2279 rgbx
= indexedToRGBX(data
, this._paletteBuff
, this._FBU
.width
, this._FBU
.height
);
2280 this._display
.blitRgbxImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, rgbx
, 0, false);
2287 var handleCopy = function () {
2289 var uncompressedSize
= this._FBU
.width
* this._FBU
.height
* 3;
2290 if (uncompressedSize
< 12) {
2293 cl_data
= uncompressedSize
;
2295 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2296 var cl_offset
= rQi
+ 1;
2299 cl_data
+= rQ
[cl_offset
] & 0x7f;
2300 if (rQ
[cl_offset
] & 0x80) {
2302 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2303 if (rQ
[cl_offset
+ 1] & 0x80) {
2305 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2308 // end inline getTightCLength
2310 this._FBU
.bytes
= 1 + cl_header
+ cl_data
;
2311 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2313 // Shift ctl, clength off
2314 this._sock
.rQshiftBytes(1 + cl_header
);
2317 data
= this._sock
.rQshiftBytes(cl_data
);
2319 data
= decompress(this._sock
.rQshiftBytes(cl_data
), uncompressedSize
);
2322 this._display
.blitRgbImage(this._FBU
.x
, this._FBU
.y
, this._FBU
.width
, this._FBU
.height
, data
, 0, false);
2327 var ctl
= this._sock
.rQpeek8();
2329 // Keep tight reset bits
2330 resetStreams
= ctl
& 0xF;
2332 // Figure out filter
2334 streamId
= ctl
& 0x3;
2336 if (ctl
=== 0x08) cmode
= "fill";
2337 else if (ctl
=== 0x09) cmode
= "jpeg";
2338 else if (ctl
=== 0x0A) cmode
= "png";
2339 else if (ctl
& 0x04) cmode
= "filter";
2340 else if (ctl
< 0x04) cmode
= "copy";
2341 else return this._fail("Illegal tight compression received (ctl: " +
2345 // fill use depth because TPIXELs drop the padding byte
2346 case "fill": // TPIXEL
2347 this._FBU
.bytes
+= 3;
2349 case "jpeg": // max clength
2350 this._FBU
.bytes
+= 3;
2352 case "png": // max clength
2353 this._FBU
.bytes
+= 3;
2355 case "filter": // filter id + num colors if palette
2356 this._FBU
.bytes
+= 2;
2362 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2364 // Determine FBU.bytes
2368 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);
2369 this._sock
.rQskipBytes(4);
2373 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2374 var cl_offset
= rQi
+ 1;
2377 cl_data
+= rQ
[cl_offset
] & 0x7f;
2378 if (rQ
[cl_offset
] & 0x80) {
2380 cl_data
+= (rQ
[cl_offset
+ 1] & 0x7f) << 7;
2381 if (rQ
[cl_offset
+ 1] & 0x80) {
2383 cl_data
+= rQ
[cl_offset
+ 2] << 14;
2386 // end inline getTightCLength
2387 this._FBU
.bytes
= 1 + cl_header
+ cl_data
; // ctl + clength size + jpeg-data
2388 if (this._sock
.rQwait("TIGHT " + cmode
, this._FBU
.bytes
)) { return false; }
2390 // We have everything, render it
2391 this._sock
.rQskipBytes(1 + cl_header
); // shift off clt + compact length
2392 data
= this._sock
.rQshiftBytes(cl_data
);
2393 this._display
.imageRect(this._FBU
.x
, this._FBU
.y
, "image/" + cmode
, data
);
2396 var filterId
= rQ
[rQi
+ 1];
2397 if (filterId
=== 1) {
2398 if (!handlePalette()) { return false; }
2400 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2401 // Filter 2, Gradient is valid but not use if jpeg is enabled
2402 this._fail("Unsupported tight subencoding received " +
2403 "(filter: " + filterId
+ ")");
2407 if (!handleCopy()) { return false; }
2412 this._FBU
.bytes
= 0;
2418 last_rect: function () {
2419 this._FBU
.rects
= 0;
2423 ExtendedDesktopSize: function () {
2424 this._FBU
.bytes
= 1;
2425 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2427 var firstUpdate
= !this._supportsSetDesktopSize
;
2428 this._supportsSetDesktopSize
= true;
2430 // Normally we only apply the current resize mode after a
2431 // window resize event. However there is no such trigger on the
2432 // initial connect. And we don't know if the server supports
2433 // resizing until we've gotten here.
2435 this._requestRemoteResize();
2438 var number_of_screens
= this._sock
.rQpeek8();
2440 this._FBU
.bytes
= 4 + (number_of_screens
* 16);
2441 if (this._sock
.rQwait("ExtendedDesktopSize", this._FBU
.bytes
)) { return false; }
2443 this._sock
.rQskipBytes(1); // number-of-screens
2444 this._sock
.rQskipBytes(3); // padding
2446 for (var i
= 0; i
< number_of_screens
; i
+= 1) {
2447 // Save the id and flags of the first screen
2449 this._screen_id
= this._sock
.rQshiftBytes(4); // id
2450 this._sock
.rQskipBytes(2); // x-position
2451 this._sock
.rQskipBytes(2); // y-position
2452 this._sock
.rQskipBytes(2); // width
2453 this._sock
.rQskipBytes(2); // height
2454 this._screen_flags
= this._sock
.rQshiftBytes(4); // flags
2456 this._sock
.rQskipBytes(16);
2461 * The x-position indicates the reason for the change:
2463 * 0 - server resized on its own
2464 * 1 - this client requested the resize
2465 * 2 - another client requested the resize
2468 // We need to handle errors when we requested the resize.
2469 if (this._FBU
.x
=== 1 && this._FBU
.y
!== 0) {
2471 // The y-position indicates the status code from the server
2472 switch (this._FBU
.y
) {
2474 msg
= "Resize is administratively prohibited";
2477 msg
= "Out of resources";
2480 msg
= "Invalid screen layout";
2483 msg
= "Unknown reason";
2486 Log
.Warn("Server did not accept the resize request: "
2489 this._resize(this._FBU
.width
, this._FBU
.height
);
2492 this._FBU
.bytes
= 0;
2493 this._FBU
.rects
-= 1;
2497 DesktopSize: function () {
2498 this._resize(this._FBU
.width
, this._FBU
.height
);
2499 this._FBU
.bytes
= 0;
2500 this._FBU
.rects
-= 1;
2504 Cursor: function () {
2505 Log
.Debug(">> set_cursor");
2506 var x
= this._FBU
.x
; // hotspot-x
2507 var y
= this._FBU
.y
; // hotspot-y
2508 var w
= this._FBU
.width
;
2509 var h
= this._FBU
.height
;
2511 var pixelslength
= w
* h
* 4;
2512 var masklength
= Math
.floor((w
+ 7) / 8) * h
;
2514 this._FBU
.bytes
= pixelslength
+ masklength
;
2515 if (this._sock
.rQwait("cursor encoding", this._FBU
.bytes
)) { return false; }
2517 this._display
.changeCursor(this._sock
.rQshiftBytes(pixelslength
),
2518 this._sock
.rQshiftBytes(masklength
),
2521 this._FBU
.bytes
= 0;
2524 Log
.Debug("<< set_cursor");
2528 QEMUExtendedKeyEvent: function () {
2531 // Old Safari doesn't support creating keyboard events
2533 var keyboardEvent
= document
.createEvent("keyboardEvent");
2534 if (keyboardEvent
.code
!== undefined) {
2535 this._qemuExtKeyEventSupported
= true;