]> git.proxmox.com Git - mirror_novnc.git/blame - core/rfb.js
Remove render_mode property
[mirror_novnc.git] / core / rfb.js
CommitLineData
a7a89626
JM
1/*
2 * noVNC: HTML5 VNC client
d58f8b51 3 * Copyright (C) 2012 Joel Martin
7a16304e 4 * Copyright (C) 2016 Samuel Mannehed for Cendio AB
1d728ace 5 * Licensed under MPL 2.0 (see LICENSE.txt)
a7a89626
JM
6 *
7 * See README.md for usage and integration instructions.
d38db74a
MT
8 *
9 * TIGHT decoder portion:
10 * (c) 2012 Michael Tinglof, Joe Balaz, Les Piech (Mercuri.ca)
a7a89626
JM
11 */
12
6d6f0db0
SR
13import * as Log from './util/logging.js';
14import _ from './util/localization.js';
15import { decodeUTF8 } from './util/strings.js';
16import { set_defaults, make_properties } from './util/properties.js';
3ae0bb09 17import Display from "./display.js";
c1e2785f
SM
18import Keyboard from "./input/keyboard.js";
19import Mouse from "./input/mouse.js";
3ae0bb09
SR
20import Websock from "./websock.js";
21import Base64 from "./base64.js";
22import DES from "./des.js";
23import KeyTable from "./input/keysym.js";
24import XtScancode from "./input/xtscancodes.js";
fba220c6 25import Inflator from "./inflator.js";
f8ec2df2 26import { encodings, encodingName } from "./encodings.js";
3ae0bb09 27
b1dee947 28/*jslint white: false, browser: true */
ae510306 29/*global window, Util, Display, Keyboard, Mouse, Websock, Websock_native, Base64, DES, KeyTable, Inflator, XtScancode */
a7a89626 30
3d7bb020 31export default function RFB(target, defaults) {
b1dee947 32 "use strict";
ae510306
SR
33 if (!defaults) {
34 defaults = {};
35 }
3d7bb020 36 this._target = target;
ae510306 37
c7d08d72 38 // Connection details
5b4e5d01 39 this._url = '';
430f00d6 40 this._rfb_credentials = {};
ae510306 41
c7d08d72 42 // Internal state
3bb12056 43 this._rfb_connection_state = '';
c00ee156 44 this._rfb_init_state = '';
ae510306 45 this._rfb_auth_scheme = '';
3bb12056 46 this._rfb_disconnect_reason = "";
ae510306 47
c7d08d72
PO
48 // Server capabilities
49 this._rfb_version = 0;
50 this._rfb_max_version = 3.8;
ae510306
SR
51 this._rfb_tightvnc = false;
52 this._rfb_xvp_ver = 0;
53
c7d08d72
PO
54 this._fb_width = 0;
55 this._fb_height = 0;
56
57 this._fb_name = "";
58
832be262 59 this._capabilities = { power: false, resize: false };
cd523e8f 60
c7d08d72 61 this._supportsFence = false;
ae510306 62
c7d08d72
PO
63 this._supportsContinuousUpdates = false;
64 this._enabledContinuousUpdates = false;
65
66 this._supportsSetDesktopSize = false;
67 this._screen_id = 0;
68 this._screen_flags = 0;
69
70 this._qemuExtKeyEventSupported = false;
71
72 // Internal objects
ae510306
SR
73 this._sock = null; // Websock object
74 this._display = null; // Display object
d9ca5e5b 75 this._flushing = false; // Display flushing state
ae510306
SR
76 this._keyboard = null; // Keyboard input handler object
77 this._mouse = null; // Mouse input handler object
ae510306 78
c7d08d72
PO
79 // Timers
80 this._disconnTimer = null; // disconnection timer
ae510306 81
c7d08d72
PO
82 // Decoder states and stats
83 this._encHandlers = {};
84 this._encStats = {};
ae510306 85
ae510306
SR
86 this._FBU = {
87 rects: 0,
c7d08d72 88 subrects: 0, // RRE and HEXTILE
ae510306
SR
89 lines: 0, // RAW
90 tiles: 0, // HEXTILE
91 bytes: 0,
92 x: 0,
93 y: 0,
94 width: 0,
95 height: 0,
96 encoding: 0,
97 subencoding: -1,
98 background: null,
c7d08d72 99 zlibs: [] // TIGHT zlib streams
ae510306 100 };
c7d08d72
PO
101 for (var i = 0; i < 4; i++) {
102 this._FBU.zlibs[i] = new Inflator();
103 }
b1dee947 104
ae510306
SR
105 this._destBuff = null;
106 this._paletteBuff = new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
b1dee947 107
ae510306 108 this._rre_chunk_sz = 100;
b1dee947 109
ae510306
SR
110 this._timing = {
111 last_fbu: 0,
112 fbu_total: 0,
113 fbu_total_cnt: 0,
114 full_fbu_total: 0,
115 full_fbu_cnt: 0,
b1dee947 116
ae510306
SR
117 fbu_rt_start: 0,
118 fbu_rt_total: 0,
119 fbu_rt_cnt: 0,
120 pixels: 0
121 };
122
ae510306
SR
123 // Mouse state
124 this._mouse_buttonMask = 0;
125 this._mouse_arr = [];
126 this._viewportDragging = false;
127 this._viewportDragPos = {};
128 this._viewportHasMoved = false;
129
ae510306 130 // set the default value on user-facing properties
6d6f0db0 131 set_defaults(this, defaults, {
ae510306 132 'local_cursor': false, // Request locally rendered cursor
ae510306 133 'view_only': false, // Disable client mouse/keyboard
ae510306 134 'disconnectTimeout': 3, // Time (s) to wait for disconnection
ae510306
SR
135 'viewportDrag': false, // Move the viewport on mouse drags
136
137 // Callback functions
3bb12056 138 'onUpdateState': function () { }, // onUpdateState(rfb, state, oldstate): connection state change
a7127fee 139 'onNotification': function () { }, // onNotification(rfb, msg, level, options): notification for UI
3bb12056 140 'onDisconnected': function () { }, // onDisconnected(rfb, reason): disconnection finished
430f00d6 141 'onCredentialsRequired': function () { }, // onCredentialsRequired(rfb, types): VNC credentials are required
ae510306
SR
142 'onClipboard': function () { }, // onClipboard(rfb, text): RFB clipboard contents received
143 'onBell': function () { }, // onBell(rfb): RFB Bell message received
ae510306
SR
144 'onFBResize': function () { }, // onFBResize(rfb, width, height): frame buffer resized
145 'onDesktopName': function () { }, // onDesktopName(rfb, name): desktop name received
cd523e8f 146 'onCapabilities': function () { } // onCapabilities(rfb, caps): the supported capabilities has changed
ae510306
SR
147 });
148
149 // main setup
6d6f0db0 150 Log.Debug(">> RFB.constructor");
ae510306 151
45808617
PO
152 // Target canvas must be able to have focus
153 if (!this._target.hasAttribute('tabindex')) {
154 this._target.tabIndex = -1;
155 }
156
ae510306 157 // populate encHandlers with bound versions
cd230363
SM
158 this._encHandlers[encodings.encodingRaw] = RFB.encodingHandlers.RAW.bind(this);
159 this._encHandlers[encodings.encodingCopyRect] = RFB.encodingHandlers.COPYRECT.bind(this);
160 this._encHandlers[encodings.encodingRRE] = RFB.encodingHandlers.RRE.bind(this);
161 this._encHandlers[encodings.encodingHextile] = RFB.encodingHandlers.HEXTILE.bind(this);
162 this._encHandlers[encodings.encodingTight] = RFB.encodingHandlers.TIGHT.bind(this);
163
164 this._encHandlers[encodings.pseudoEncodingDesktopSize] = RFB.encodingHandlers.DesktopSize.bind(this);
165 this._encHandlers[encodings.pseudoEncodingLastRect] = RFB.encodingHandlers.last_rect.bind(this);
166 this._encHandlers[encodings.pseudoEncodingCursor] = RFB.encodingHandlers.Cursor.bind(this);
167 this._encHandlers[encodings.pseudoEncodingQEMUExtendedKeyEvent] = RFB.encodingHandlers.QEMUExtendedKeyEvent.bind(this);
168 this._encHandlers[encodings.pseudoEncodingExtendedDesktopSize] = RFB.encodingHandlers.ExtendedDesktopSize.bind(this);
ae510306
SR
169
170 // NB: nothing that needs explicit teardown should be done
171 // before this point, since this can throw an exception
172 try {
3d7bb020
PO
173 this._display = new Display(this._target,
174 {onFlush: this._onFlush.bind(this)});
ae510306 175 } catch (exc) {
6d6f0db0 176 Log.Error("Display exception: " + exc);
ae510306
SR
177 throw exc;
178 }
c7d08d72 179 this._display.clear();
ae510306 180
3d7bb020
PO
181 this._keyboard = new Keyboard(this._target,
182 {onKeyEvent: this._handleKeyEvent.bind(this)});
ae510306 183
3d7bb020
PO
184 this._mouse = new Mouse(this._target,
185 {onMouseButton: this._handleMouseButton.bind(this),
9e6f71cb 186 onMouseMove: this._handleMouseMove.bind(this)});
ae510306
SR
187
188 this._sock = new Websock();
189 this._sock.on('message', this._handle_message.bind(this));
190 this._sock.on('open', function () {
c2a4d3ef 191 if ((this._rfb_connection_state === 'connecting') &&
c00ee156
SM
192 (this._rfb_init_state === '')) {
193 this._rfb_init_state = 'ProtocolVersion';
6d6f0db0 194 Log.Debug("Starting VNC handshake");
ae510306 195 } else {
67cd2072 196 this._fail("Unexpected server connection");
ae510306
SR
197 }
198 }.bind(this));
199 this._sock.on('close', function (e) {
6d6f0db0 200 Log.Warn("WebSocket on-close event");
ae510306
SR
201 var msg = "";
202 if (e.code) {
203 msg = " (code: " + e.code;
204 if (e.reason) {
205 msg += ", reason: " + e.reason;
b1dee947 206 }
ae510306
SR
207 msg += ")";
208 }
c00ee156 209 switch (this._rfb_connection_state) {
c2a4d3ef 210 case 'disconnecting':
3bb12056 211 this._updateConnectionState('disconnected');
c00ee156 212 break;
c2a4d3ef 213 case 'connecting':
67cd2072 214 this._fail('Failed to connect to server', msg);
c00ee156 215 break;
b45905ab
SM
216 case 'connected':
217 // Handle disconnects that were initiated server-side
218 this._updateConnectionState('disconnecting');
219 this._updateConnectionState('disconnected');
220 break;
c00ee156 221 case 'disconnected':
67cd2072
SM
222 this._fail("Unexpected server disconnect",
223 "Already disconnected: " + msg);
c00ee156
SM
224 break;
225 default:
67cd2072
SM
226 this._fail("Unexpected server disconnect",
227 "Not in any state yet: " + msg);
c00ee156 228 break;
a679a97d 229 }
ae510306
SR
230 this._sock.off('close');
231 }.bind(this));
232 this._sock.on('error', function (e) {
6d6f0db0 233 Log.Warn("WebSocket on-error event");
ae510306 234 });
8db09746 235
6d6f0db0 236 Log.Debug("<< RFB.constructor");
ae510306 237};
a7a89626 238
6d6f0db0
SR
239RFB.prototype = {
240 // Public methods
3d7bb020 241 connect: function (url, options) {
5b4e5d01
PO
242 if (!url) {
243 this._fail(_("Must specify URL"));
244 return;
6d6f0db0 245 }
a7a89626 246
3d7bb020
PO
247 this._url = url;
248
249 options = options || {}
250
251 this._rfb_credentials = options.credentials || {};
252 this._shared = 'shared' in options ? !!options.shared : true;
253 this._repeaterID = options.repeaterID || '';
254
6d6f0db0
SR
255 this._rfb_init_state = '';
256 this._updateConnectionState('connecting');
257 return true;
258 },
259
260 disconnect: function () {
261 this._updateConnectionState('disconnecting');
262 this._sock.off('error');
263 this._sock.off('message');
264 this._sock.off('open');
265 },
266
430f00d6
PO
267 sendCredentials: function (creds) {
268 this._rfb_credentials = creds;
6d6f0db0
SR
269 setTimeout(this._init_msg.bind(this), 0);
270 },
271
272 sendCtrlAltDel: function () {
273 if (this._rfb_connection_state !== 'connected' || this._view_only) { return false; }
274 Log.Info("Sending Ctrl-Alt-Del");
275
94f5cf05
PO
276 this.sendKey(KeyTable.XK_Control_L, "ControlLeft", true);
277 this.sendKey(KeyTable.XK_Alt_L, "AltLeft", true);
278 this.sendKey(KeyTable.XK_Delete, "Delete", true);
279 this.sendKey(KeyTable.XK_Delete, "Delete", false);
280 this.sendKey(KeyTable.XK_Alt_L, "AltLeft", false);
281 this.sendKey(KeyTable.XK_Control_L, "ControlLeft", false);
282
6d6f0db0
SR
283 return true;
284 },
285
cd523e8f
PO
286 machineShutdown: function () {
287 this._xvpOp(1, 2);
6d6f0db0
SR
288 },
289
cd523e8f
PO
290 machineReboot: function () {
291 this._xvpOp(1, 3);
6d6f0db0
SR
292 },
293
cd523e8f
PO
294 machineReset: function () {
295 this._xvpOp(1, 4);
6d6f0db0
SR
296 },
297
298 // Send a key press. If 'down' is not specified then send a down key
299 // followed by an up key.
94f5cf05 300 sendKey: function (keysym, code, down) {
6d6f0db0 301 if (this._rfb_connection_state !== 'connected' || this._view_only) { return false; }
94f5cf05
PO
302
303 if (down === undefined) {
304 this.sendKey(keysym, code, true);
305 this.sendKey(keysym, code, false);
306 return true;
307 }
308
be70fe0a 309 var scancode = XtScancode[code];
94f5cf05 310
be70fe0a 311 if (this._qemuExtKeyEventSupported && scancode) {
459ed008
PO
312 // 0 is NoSymbol
313 keysym = keysym || 0;
314
94f5cf05
PO
315 Log.Info("Sending key (" + (down ? "down" : "up") + "): keysym " + keysym + ", scancode " + scancode);
316
317 RFB.messages.QEMUExtendedKeyEvent(this._sock, keysym, down, scancode);
318 } else {
459ed008
PO
319 if (!keysym) {
320 return false;
321 }
6d6f0db0
SR
322 Log.Info("Sending keysym (" + (down ? "down" : "up") + "): " + keysym);
323 RFB.messages.keyEvent(this._sock, keysym, down ? 1 : 0);
6d6f0db0 324 }
94f5cf05 325
6d6f0db0
SR
326 return true;
327 },
328
329 clipboardPasteFrom: function (text) {
330 if (this._rfb_connection_state !== 'connected' || this._view_only) { return; }
331 RFB.messages.clientCutText(this._sock, text);
332 },
333
b9854a5c
PO
334 autoscale: function (width, height, downscaleOnly) {
335 if (this._rfb_connection_state !== 'connected') { return; }
336 this._display.autoscale(width, height, downscaleOnly);
337 },
338
339 viewportChangeSize: function(width, height) {
340 if (this._rfb_connection_state !== 'connected') { return; }
341 this._display.viewportChangeSize(width, height);
342 },
343
344 clippingDisplay: function () {
345 if (this._rfb_connection_state !== 'connected') { return false; }
346 return this._display.clippingDisplay();
347 },
348
6d6f0db0
SR
349 // Requests a change of remote desktop size. This message is an extension
350 // and may only be sent if we have received an ExtendedDesktopSize message
351 requestDesktopSize: function (width, height) {
352 if (this._rfb_connection_state !== 'connected' ||
353 this._view_only) {
354 return false;
355 }
e3efeb32 356
6d6f0db0
SR
357 if (this._supportsSetDesktopSize) {
358 RFB.messages.setDesktopSize(this._sock, width, height,
359 this._screen_id, this._screen_flags);
360 this._sock.flush();
4e0c36dd 361 return true;
6d6f0db0
SR
362 } else {
363 return false;
364 }
365 },
b1dee947 366
b1dee947 367
6d6f0db0 368 // Private methods
b0ec6509 369
6d6f0db0
SR
370 _connect: function () {
371 Log.Debug(">> RFB.connect");
b0ec6509 372
5b4e5d01 373 Log.Info("connecting to " + this._url);
b1dee947 374
6d6f0db0
SR
375 try {
376 // WebSocket.onopen transitions to the RFB init states
f8318361 377 this._sock.open(this._url, ['binary']);
6d6f0db0
SR
378 } catch (e) {
379 if (e.name === 'SyntaxError') {
380 this._fail("Invalid host or port value given", e);
b1dee947 381 } else {
6d6f0db0 382 this._fail("Error while connecting", e);
159ad55d 383 }
6d6f0db0 384 }
e3efeb32 385
2afda544
PO
386 // Always grab focus on some kind of click event
387 this._target.addEventListener("mousedown", this._focusCanvas);
388 this._target.addEventListener("touchstart", this._focusCanvas);
389
6d6f0db0
SR
390 Log.Debug("<< RFB.connect");
391 },
392
393 _disconnect: function () {
394 Log.Debug(">> RFB.disconnect");
2afda544
PO
395 this._target.removeEventListener("mousedown", this._focusCanvas);
396 this._target.removeEventListener("touchstart", this._focusCanvas);
6d6f0db0
SR
397 this._cleanup();
398 this._sock.close();
399 this._print_stats();
400 Log.Debug("<< RFB.disconnect");
401 },
402
6d6f0db0 403 _print_stats: function () {
c3386227
PO
404 var stats = this._encStats;
405
6d6f0db0 406 Log.Info("Encoding stats for this connection:");
c3386227
PO
407 Object.keys(stats).forEach(function (key) {
408 var s = stats[key];
6d6f0db0 409 if (s[0] + s[1] > 0) {
c3386227 410 Log.Info(" " + encodingName(key) + ": " + s[0] + " rects");
b1dee947 411 }
c3386227 412 });
a7a89626 413
6d6f0db0 414 Log.Info("Encoding stats since page load:");
c3386227
PO
415 Object.keys(stats).forEach(function (key) {
416 var s = stats[key];
417 Log.Info(" " + encodingName(key) + ": " + s[1] + " rects");
418 });
6d6f0db0
SR
419 },
420
421 _cleanup: function () {
422 if (!this._view_only) { this._keyboard.ungrab(); }
423 if (!this._view_only) { this._mouse.ungrab(); }
424 this._display.defaultCursor();
425 if (Log.get_logging() !== 'debug') {
c7d08d72 426 // Show noVNC logo when disconnected, unless in
6d6f0db0
SR
427 // debug mode
428 this._display.clear();
429 }
430 },
431
2afda544
PO
432 // Event handler for canvas so this points to the canvas element
433 _focusCanvas: function(event) {
434 // Respect earlier handlers' request to not do side-effects
435 if (!event.defaultPrevented)
436 this.focus();
437 },
438
6d6f0db0
SR
439 /*
440 * Connection states:
441 * connecting
442 * connected
443 * disconnecting
444 * disconnected - permanent state
445 */
446 _updateConnectionState: function (state) {
447 var oldstate = this._rfb_connection_state;
448
449 if (state === oldstate) {
450 Log.Debug("Already in state '" + state + "', ignoring");
451 return;
452 }
453
454 // The 'disconnected' state is permanent for each RFB object
455 if (oldstate === 'disconnected') {
456 Log.Error("Tried changing state of a disconnected RFB object");
457 return;
458 }
459
460 // Ensure proper transitions before doing anything
461 switch (state) {
462 case 'connected':
463 if (oldstate !== 'connecting') {
464 Log.Error("Bad transition to connected state, " +
465 "previous connection state: " + oldstate);
466 return;
b1dee947 467 }
6d6f0db0 468 break;
a7a89626 469
6d6f0db0
SR
470 case 'disconnected':
471 if (oldstate !== 'disconnecting') {
472 Log.Error("Bad transition to disconnected state, " +
473 "previous connection state: " + oldstate);
474 return;
475 }
476 break;
a7a89626 477
6d6f0db0
SR
478 case 'connecting':
479 if (oldstate !== '') {
480 Log.Error("Bad transition to connecting state, " +
481 "previous connection state: " + oldstate);
482 return;
483 }
484 break;
b1dee947 485
6d6f0db0
SR
486 case 'disconnecting':
487 if (oldstate !== 'connected' && oldstate !== 'connecting') {
488 Log.Error("Bad transition to disconnecting state, " +
489 "previous connection state: " + oldstate);
490 return;
491 }
492 break;
a679a97d 493
6d6f0db0
SR
494 default:
495 Log.Error("Unknown connection state: " + state);
3bb12056 496 return;
6d6f0db0 497 }
b1dee947 498
6d6f0db0 499 // State change actions
3bb12056 500
6d6f0db0
SR
501 this._rfb_connection_state = state;
502 this._onUpdateState(this, state, oldstate);
b2e961d4 503
6d6f0db0
SR
504 var smsg = "New state '" + state + "', was '" + oldstate + "'.";
505 Log.Debug(smsg);
b2e961d4 506
6d6f0db0
SR
507 if (this._disconnTimer && state !== 'disconnecting') {
508 Log.Debug("Clearing disconnect timer");
509 clearTimeout(this._disconnTimer);
510 this._disconnTimer = null;
3bb12056 511
6d6f0db0
SR
512 // make sure we don't get a double event
513 this._sock.off('close');
514 }
b2e961d4 515
6d6f0db0
SR
516 switch (state) {
517 case 'disconnected':
518 // Call onDisconnected callback after onUpdateState since
519 // we don't know if the UI only displays the latest message
520 if (this._rfb_disconnect_reason !== "") {
521 this._onDisconnected(this, this._rfb_disconnect_reason);
522 } else {
523 // No reason means clean disconnect
524 this._onDisconnected(this);
525 }
526 break;
b2e961d4 527
6d6f0db0
SR
528 case 'connecting':
529 this._connect();
530 break;
b2e961d4 531
6d6f0db0
SR
532 case 'disconnecting':
533 this._disconnect();
b2e961d4 534
6d6f0db0
SR
535 this._disconnTimer = setTimeout(function () {
536 this._rfb_disconnect_reason = _("Disconnect timeout");
537 this._updateConnectionState('disconnected');
538 }.bind(this), this._disconnectTimeout * 1000);
539 break;
540 }
541 },
542
543 /* Print errors and disconnect
544 *
545 * The optional parameter 'details' is used for information that
546 * should be logged but not sent to the user interface.
547 */
548 _fail: function (msg, details) {
549 var fullmsg = msg;
550 if (typeof details !== 'undefined') {
551 fullmsg = msg + " (" + details + ")";
552 }
553 switch (this._rfb_connection_state) {
554 case 'disconnecting':
555 Log.Error("Failed when disconnecting: " + fullmsg);
556 break;
557 case 'connected':
558 Log.Error("Failed while connected: " + fullmsg);
559 break;
560 case 'connecting':
561 Log.Error("Failed when connecting: " + fullmsg);
562 break;
563 default:
564 Log.Error("RFB failure: " + fullmsg);
565 break;
566 }
567 this._rfb_disconnect_reason = msg; //This is sent to the UI
568
569 // Transition to disconnected without waiting for socket to close
570 this._updateConnectionState('disconnecting');
571 this._updateConnectionState('disconnected');
572
573 return false;
574 },
575
576 /*
577 * Send a notification to the UI. Valid levels are:
578 * 'normal'|'warn'|'error'
579 *
580 * NOTE: Options could be added in the future.
581 * NOTE: If this function is called multiple times, remember that the
582 * interface could be only showing the latest notification.
583 */
584 _notification: function(msg, level, options) {
585 switch (level) {
586 case 'normal':
587 case 'warn':
588 case 'error':
589 Log.Debug("Notification[" + level + "]:" + msg);
590 break;
591 default:
592 Log.Error("Invalid notification level: " + level);
593 return;
594 }
b2e961d4 595
6d6f0db0
SR
596 if (options) {
597 this._onNotification(this, msg, level, options);
598 } else {
599 this._onNotification(this, msg, level);
600 }
601 },
b1dee947 602
832be262
PO
603 _setCapability: function (cap, val) {
604 this._capabilities[cap] = val;
605 this._onCapabilities(this, this._capabilities);
606 },
607
6d6f0db0
SR
608 _handle_message: function () {
609 if (this._sock.rQlen() === 0) {
610 Log.Warn("handle_message called on an empty receive queue");
611 return;
612 }
b1dee947 613
6d6f0db0
SR
614 switch (this._rfb_connection_state) {
615 case 'disconnected':
616 Log.Error("Got data while disconnected");
617 break;
618 case 'connected':
619 while (true) {
620 if (this._flushing) {
621 break;
622 }
623 if (!this._normal_msg()) {
624 break;
625 }
626 if (this._sock.rQlen() === 0) {
627 break;
628 }
629 }
630 break;
631 default:
632 this._init_msg();
633 break;
634 }
635 },
3bb12056 636
d0703d1b
PO
637 _handleKeyEvent: function (keysym, code, down) {
638 this.sendKey(keysym, code, down);
6d6f0db0 639 },
06a9ef0c 640
6d6f0db0
SR
641 _handleMouseButton: function (x, y, down, bmask) {
642 if (down) {
643 this._mouse_buttonMask |= bmask;
644 } else {
270bdbd7 645 this._mouse_buttonMask &= ~bmask;
6d6f0db0 646 }
a7127fee 647
6d6f0db0
SR
648 if (this._viewportDrag) {
649 if (down && !this._viewportDragging) {
650 this._viewportDragging = true;
651 this._viewportDragPos = {'x': x, 'y': y};
a7127fee 652
6d6f0db0 653 // Skip sending mouse events
b1dee947 654 return;
6d6f0db0
SR
655 } else {
656 this._viewportDragging = false;
8db09746 657
6d6f0db0
SR
658 // If the viewport didn't actually move, then treat as a mouse click event
659 // Send the button down event here, as the button up event is sent at the end of this function
660 if (!this._viewportHasMoved && !this._view_only) {
661 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), bmask);
662 }
663 this._viewportHasMoved = false;
b1dee947 664 }
6d6f0db0 665 }
8db09746 666
6d6f0db0 667 if (this._view_only) { return; } // View only, skip mouse events
8f06673a 668
6d6f0db0
SR
669 if (this._rfb_connection_state !== 'connected') { return; }
670 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
671 },
8db09746 672
6d6f0db0
SR
673 _handleMouseMove: function (x, y) {
674 if (this._viewportDragging) {
675 var deltaX = this._viewportDragPos.x - x;
676 var deltaY = this._viewportDragPos.y - y;
8db09746 677
6d6f0db0
SR
678 // The goal is to trigger on a certain physical width, the
679 // devicePixelRatio brings us a bit closer but is not optimal.
680 var dragThreshold = 10 * (window.devicePixelRatio || 1);
8db09746 681
6d6f0db0
SR
682 if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold ||
683 Math.abs(deltaY) > dragThreshold)) {
684 this._viewportHasMoved = true;
27e77d46 685
6d6f0db0
SR
686 this._viewportDragPos = {'x': x, 'y': y};
687 this._display.viewportChangePos(deltaX, deltaY);
b50f3406 688 }
8db09746 689
6d6f0db0
SR
690 // Skip sending mouse events
691 return;
692 }
b1dee947 693
6d6f0db0 694 if (this._view_only) { return; } // View only, skip mouse events
b1dee947 695
6d6f0db0
SR
696 if (this._rfb_connection_state !== 'connected') { return; }
697 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
698 },
b1dee947 699
6d6f0db0 700 // Message Handlers
27e77d46 701
6d6f0db0
SR
702 _negotiate_protocol_version: function () {
703 if (this._sock.rQlen() < 12) {
704 return this._fail("Error while negotiating with server",
705 "Incomplete protocol version");
706 }
32df3fdb 707
6d6f0db0
SR
708 var sversion = this._sock.rQshiftStr(12).substr(4, 7);
709 Log.Info("Server ProtocolVersion: " + sversion);
710 var is_repeater = 0;
711 switch (sversion) {
712 case "000.000": // UltraVNC repeater
713 is_repeater = 1;
714 break;
715 case "003.003":
716 case "003.006": // UltraVNC
717 case "003.889": // Apple Remote Desktop
718 this._rfb_version = 3.3;
719 break;
720 case "003.007":
721 this._rfb_version = 3.7;
722 break;
723 case "003.008":
724 case "004.000": // Intel AMT KVM
725 case "004.001": // RealVNC 4.6
726 case "005.000": // RealVNC 5.3
727 this._rfb_version = 3.8;
728 break;
729 default:
730 return this._fail("Unsupported server",
731 "Invalid server version: " + sversion);
732 }
8db09746 733
6d6f0db0 734 if (is_repeater) {
ebf1c0f9 735 var repeaterID = "ID:" + this._repeaterID;
6d6f0db0
SR
736 while (repeaterID.length < 250) {
737 repeaterID += "\0";
b1dee947 738 }
6d6f0db0
SR
739 this._sock.send_string(repeaterID);
740 return true;
741 }
b1dee947 742
6d6f0db0
SR
743 if (this._rfb_version > this._rfb_max_version) {
744 this._rfb_version = this._rfb_max_version;
745 }
b1dee947 746
6d6f0db0
SR
747 var cversion = "00" + parseInt(this._rfb_version, 10) +
748 ".00" + ((this._rfb_version * 10) % 10);
749 this._sock.send_string("RFB " + cversion + "\n");
750 Log.Debug('Sent ProtocolVersion: ' + cversion);
b1dee947 751
6d6f0db0
SR
752 this._rfb_init_state = 'Security';
753 },
b1dee947 754
6d6f0db0
SR
755 _negotiate_security: function () {
756 // Polyfill since IE and PhantomJS doesn't have
757 // TypedArray.includes()
758 function includes(item, array) {
759 for (var i = 0; i < array.length; i++) {
760 if (array[i] === item) {
761 return true;
762 }
b1dee947 763 }
6d6f0db0
SR
764 return false;
765 }
b1dee947 766
6d6f0db0
SR
767 if (this._rfb_version >= 3.7) {
768 // Server sends supported list, client decides
769 var num_types = this._sock.rQshift8();
770 if (this._sock.rQwait("security type", num_types, 1)) { return false; }
b1dee947 771
6d6f0db0
SR
772 if (num_types === 0) {
773 var strlen = this._sock.rQshift32();
774 var reason = this._sock.rQshiftStr(strlen);
775 return this._fail("Error while negotiating with server",
776 "Security failure: " + reason);
777 }
778
779 var types = this._sock.rQshiftBytes(num_types);
780 Log.Debug("Server security types: " + types);
781
782 // Look for each auth in preferred order
783 this._rfb_auth_scheme = 0;
784 if (includes(1, types)) {
785 this._rfb_auth_scheme = 1; // None
786 } else if (includes(22, types)) {
787 this._rfb_auth_scheme = 22; // XVP
788 } else if (includes(16, types)) {
789 this._rfb_auth_scheme = 16; // Tight
790 } else if (includes(2, types)) {
791 this._rfb_auth_scheme = 2; // VNC Auth
792 } else {
793 return this._fail("Unsupported server",
794 "Unsupported security types: " + types);
8db09746 795 }
b1dee947 796
6d6f0db0
SR
797 this._sock.send([this._rfb_auth_scheme]);
798 } else {
799 // Server decides
800 if (this._sock.rQwait("security scheme", 4)) { return false; }
801 this._rfb_auth_scheme = this._sock.rQshift32();
802 }
b1dee947 803
6d6f0db0
SR
804 this._rfb_init_state = 'Authentication';
805 Log.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme);
b1dee947 806
6d6f0db0
SR
807 return this._init_msg(); // jump to authentication
808 },
b1dee947 809
6d6f0db0
SR
810 // authentication
811 _negotiate_xvp_auth: function () {
430f00d6
PO
812 if (!this._rfb_credentials.username ||
813 !this._rfb_credentials.password ||
814 !this._rfb_credentials.target) {
815 this._onCredentialsRequired(this, ["username", "password", "target"]);
6d6f0db0
SR
816 return false;
817 }
0ee5ca6e 818
430f00d6
PO
819 var xvp_auth_str = String.fromCharCode(this._rfb_credentials.username.length) +
820 String.fromCharCode(this._rfb_credentials.target.length) +
821 this._rfb_credentials.username +
822 this._rfb_credentials.target;
6d6f0db0 823 this._sock.send_string(xvp_auth_str);
6d6f0db0
SR
824 this._rfb_auth_scheme = 2;
825 return this._negotiate_authentication();
826 },
827
828 _negotiate_std_vnc_auth: function () {
abfe5b7a
SM
829 if (this._sock.rQwait("auth challenge", 16)) { return false; }
830
430f00d6
PO
831 if (!this._rfb_credentials.password) {
832 this._onCredentialsRequired(this, ["password"]);
6d6f0db0
SR
833 return false;
834 }
b1dee947 835
6d6f0db0
SR
836 // TODO(directxman12): make genDES not require an Array
837 var challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16));
430f00d6 838 var response = RFB.genDES(this._rfb_credentials.password, challenge);
6d6f0db0
SR
839 this._sock.send(response);
840 this._rfb_init_state = "SecurityResult";
841 return true;
842 },
843
844 _negotiate_tight_tunnels: function (numTunnels) {
845 var clientSupportedTunnelTypes = {
846 0: { vendor: 'TGHT', signature: 'NOTUNNEL' }
847 };
848 var serverSupportedTunnelTypes = {};
849 // receive tunnel capabilities
850 for (var i = 0; i < numTunnels; i++) {
851 var cap_code = this._sock.rQshift32();
852 var cap_vendor = this._sock.rQshiftStr(4);
853 var cap_signature = this._sock.rQshiftStr(8);
854 serverSupportedTunnelTypes[cap_code] = { vendor: cap_vendor, signature: cap_signature };
855 }
856
857 // choose the notunnel type
858 if (serverSupportedTunnelTypes[0]) {
859 if (serverSupportedTunnelTypes[0].vendor != clientSupportedTunnelTypes[0].vendor ||
860 serverSupportedTunnelTypes[0].signature != clientSupportedTunnelTypes[0].signature) {
861 return this._fail("Unsupported server",
862 "Client's tunnel type had the incorrect " +
863 "vendor or signature");
b1dee947 864 }
6d6f0db0
SR
865 this._sock.send([0, 0, 0, 0]); // use NOTUNNEL
866 return false; // wait until we receive the sub auth count to continue
867 } else {
868 return this._fail("Unsupported server",
869 "Server wanted tunnels, but doesn't support " +
870 "the notunnel type");
871 }
872 },
b1dee947 873
6d6f0db0
SR
874 _negotiate_tight_auth: function () {
875 if (!this._rfb_tightvnc) { // first pass, do the tunnel negotiation
876 if (this._sock.rQwait("num tunnels", 4)) { return false; }
877 var numTunnels = this._sock.rQshift32();
878 if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; }
c00ee156 879
6d6f0db0 880 this._rfb_tightvnc = true;
b1dee947 881
6d6f0db0
SR
882 if (numTunnels > 0) {
883 this._negotiate_tight_tunnels(numTunnels);
884 return false; // wait until we receive the sub auth to continue
b1dee947 885 }
6d6f0db0 886 }
b1dee947 887
6d6f0db0
SR
888 // second pass, do the sub-auth negotiation
889 if (this._sock.rQwait("sub auth count", 4)) { return false; }
890 var subAuthCount = this._sock.rQshift32();
891 if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected
892 this._rfb_init_state = 'SecurityResult';
893 return true;
894 }
b1dee947 895
6d6f0db0 896 if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; }
b1dee947 897
6d6f0db0
SR
898 var clientSupportedTypes = {
899 'STDVNOAUTH__': 1,
900 'STDVVNCAUTH_': 2
901 };
b1dee947 902
6d6f0db0 903 var serverSupportedTypes = [];
95eb681b 904
6d6f0db0
SR
905 for (var i = 0; i < subAuthCount; i++) {
906 var capNum = this._sock.rQshift32();
907 var capabilities = this._sock.rQshiftStr(12);
908 serverSupportedTypes.push(capabilities);
909 }
d86cc2d9 910
6d6f0db0
SR
911 for (var authType in clientSupportedTypes) {
912 if (serverSupportedTypes.indexOf(authType) != -1) {
913 this._sock.send([0, 0, 0, clientSupportedTypes[authType]]);
d86cc2d9 914
6d6f0db0
SR
915 switch (authType) {
916 case 'STDVNOAUTH__': // no auth
917 this._rfb_init_state = 'SecurityResult';
918 return true;
919 case 'STDVVNCAUTH_': // VNC auth
920 this._rfb_auth_scheme = 2;
921 return this._init_msg();
922 default:
923 return this._fail("Unsupported server",
924 "Unsupported tiny auth scheme: " +
925 authType);
b1dee947
SR
926 }
927 }
6d6f0db0 928 }
b1dee947 929
6d6f0db0
SR
930 return this._fail("Unsupported server",
931 "No supported sub-auth types!");
932 },
933
934 _negotiate_authentication: function () {
935 switch (this._rfb_auth_scheme) {
936 case 0: // connection failed
937 if (this._sock.rQwait("auth reason", 4)) { return false; }
938 var strlen = this._sock.rQshift32();
939 var reason = this._sock.rQshiftStr(strlen);
940 return this._fail("Authentication failure", reason);
941
942 case 1: // no auth
943 if (this._rfb_version >= 3.8) {
944 this._rfb_init_state = 'SecurityResult';
945 return true;
946 }
947 this._rfb_init_state = 'ClientInitialisation';
948 return this._init_msg();
95eb681b 949
6d6f0db0
SR
950 case 22: // XVP auth
951 return this._negotiate_xvp_auth();
d86cc2d9 952
6d6f0db0
SR
953 case 2: // VNC authentication
954 return this._negotiate_std_vnc_auth();
d86cc2d9 955
6d6f0db0
SR
956 case 16: // TightVNC Security Type
957 return this._negotiate_tight_auth();
d86cc2d9 958
6d6f0db0
SR
959 default:
960 return this._fail("Unsupported server",
961 "Unsupported auth scheme: " +
962 this._rfb_auth_scheme);
963 }
964 },
965
966 _handle_security_result: function () {
967 if (this._sock.rQwait('VNC auth response ', 4)) { return false; }
968 switch (this._sock.rQshift32()) {
969 case 0: // OK
970 this._rfb_init_state = 'ClientInitialisation';
971 Log.Debug('Authentication OK');
972 return this._init_msg();
973 case 1: // failed
974 if (this._rfb_version >= 3.8) {
975 var length = this._sock.rQshift32();
976 if (this._sock.rQwait("SecurityResult reason", length, 8)) { return false; }
977 var reason = this._sock.rQshiftStr(length);
978 return this._fail("Authentication failure", reason);
979 } else {
980 return this._fail("Authentication failure");
d86cc2d9 981 }
6d6f0db0
SR
982 case 2:
983 return this._fail("Too many authentication attempts");
984 default:
985 return this._fail("Unsupported server",
986 "Unknown SecurityResult");
987 }
988 },
989
990 _negotiate_server_init: function () {
991 if (this._sock.rQwait("server initialization", 24)) { return false; }
992
993 /* Screen size */
91d5c625
PO
994 var width = this._sock.rQshift16();
995 var height = this._sock.rQshift16();
6d6f0db0
SR
996
997 /* PIXEL_FORMAT */
998 var bpp = this._sock.rQshift8();
999 var depth = this._sock.rQshift8();
1000 var big_endian = this._sock.rQshift8();
1001 var true_color = this._sock.rQshift8();
1002
1003 var red_max = this._sock.rQshift16();
1004 var green_max = this._sock.rQshift16();
1005 var blue_max = this._sock.rQshift16();
1006 var red_shift = this._sock.rQshift8();
1007 var green_shift = this._sock.rQshift8();
1008 var blue_shift = this._sock.rQshift8();
1009 this._sock.rQskipBytes(3); // padding
1010
1011 // NB(directxman12): we don't want to call any callbacks or print messages until
1012 // *after* we're past the point where we could backtrack
1013
1014 /* Connection name/title */
1015 var name_length = this._sock.rQshift32();
1016 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1017 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1018
1019 if (this._rfb_tightvnc) {
1020 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1021 // In TightVNC mode, ServerInit message is extended
1022 var numServerMessages = this._sock.rQshift16();
1023 var numClientMessages = this._sock.rQshift16();
1024 var numEncodings = this._sock.rQshift16();
1025 this._sock.rQskipBytes(2); // padding
1026
1027 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1028 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1029
1030 // we don't actually do anything with the capability information that TIGHT sends,
1031 // so we just skip the all of this.
1032
1033 // TIGHT server message capabilities
1034 this._sock.rQskipBytes(16 * numServerMessages);
1035
1036 // TIGHT client message capabilities
1037 this._sock.rQskipBytes(16 * numClientMessages);
1038
1039 // TIGHT encoding capabilities
1040 this._sock.rQskipBytes(16 * numEncodings);
1041 }
d86cc2d9 1042
6d6f0db0
SR
1043 // NB(directxman12): these are down here so that we don't run them multiple times
1044 // if we backtrack
91d5c625 1045 Log.Info("Screen: " + width + "x" + height +
6d6f0db0
SR
1046 ", bpp: " + bpp + ", depth: " + depth +
1047 ", big_endian: " + big_endian +
1048 ", true_color: " + true_color +
1049 ", red_max: " + red_max +
1050 ", green_max: " + green_max +
1051 ", blue_max: " + blue_max +
1052 ", red_shift: " + red_shift +
1053 ", green_shift: " + green_shift +
1054 ", blue_shift: " + blue_shift);
1055
1056 if (big_endian !== 0) {
1057 Log.Warn("Server native endian is not little endian");
1058 }
b1dee947 1059
6d6f0db0
SR
1060 if (red_shift !== 16) {
1061 Log.Warn("Server native red-shift is not 16");
1062 }
b1dee947 1063
6d6f0db0
SR
1064 if (blue_shift !== 0) {
1065 Log.Warn("Server native blue-shift is not 0");
1066 }
b1dee947 1067
6d6f0db0
SR
1068 // we're past the point where we could backtrack, so it's safe to call this
1069 this._onDesktopName(this, this._fb_name);
b1dee947 1070
91d5c625 1071 this._resize(width, height);
b1dee947 1072
6d6f0db0
SR
1073 if (!this._view_only) { this._keyboard.grab(); }
1074 if (!this._view_only) { this._mouse.grab(); }
b1dee947 1075
5a5f5ada
PO
1076 this._fb_depth = 24;
1077
1078 if (this._fb_name === "Intel(r) AMT KVM") {
1079 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Using low color mode.");
1080 this._fb_depth = 8;
1081 }
1082
1083 RFB.messages.pixelFormat(this._sock, this._fb_depth, true);
49a81837 1084 this._sendEncodings();
6d6f0db0
SR
1085 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1086
1087 this._timing.fbu_rt_start = (new Date()).getTime();
1088 this._timing.pixels = 0;
1089
cd74793b
PO
1090 // Cursor will be server side until the server decides to honor
1091 // our request and send over the cursor image
1092 this._display.disableLocalCursor();
1093
6d6f0db0
SR
1094 this._updateConnectionState('connected');
1095 return true;
1096 },
1097
49a81837
PO
1098 _sendEncodings: function () {
1099 var encs = [];
1100
1101 // In preference order
1102 encs.push(encodings.encodingCopyRect);
5a5f5ada
PO
1103 // Only supported with full depth support
1104 if (this._fb_depth == 24) {
1105 encs.push(encodings.encodingTight);
1106 encs.push(encodings.encodingHextile);
1107 encs.push(encodings.encodingRRE);
1108 }
49a81837
PO
1109 encs.push(encodings.encodingRaw);
1110
1111 // Psuedo-encoding settings
1112 encs.push(encodings.pseudoEncodingTightPNG);
1113 encs.push(encodings.pseudoEncodingQualityLevel0 + 6);
1114 encs.push(encodings.pseudoEncodingCompressLevel0 + 2);
1115
1116 encs.push(encodings.pseudoEncodingDesktopSize);
1117 encs.push(encodings.pseudoEncodingLastRect);
1118 encs.push(encodings.pseudoEncodingQEMUExtendedKeyEvent);
1119 encs.push(encodings.pseudoEncodingExtendedDesktopSize);
1120 encs.push(encodings.pseudoEncodingXvp);
1121 encs.push(encodings.pseudoEncodingFence);
1122 encs.push(encodings.pseudoEncodingContinuousUpdates);
1123
5a5f5ada 1124 if (this._local_cursor && this._fb_depth == 24) {
49a81837
PO
1125 encs.push(encodings.pseudoEncodingCursor);
1126 }
1127
1128 RFB.messages.clientEncodings(this._sock, encs);
1129 },
1130
6d6f0db0
SR
1131 /* RFB protocol initialization states:
1132 * ProtocolVersion
1133 * Security
1134 * Authentication
1135 * SecurityResult
1136 * ClientInitialization - not triggered by server message
1137 * ServerInitialization
1138 */
1139 _init_msg: function () {
1140 switch (this._rfb_init_state) {
1141 case 'ProtocolVersion':
1142 return this._negotiate_protocol_version();
1143
1144 case 'Security':
1145 return this._negotiate_security();
1146
1147 case 'Authentication':
1148 return this._negotiate_authentication();
1149
1150 case 'SecurityResult':
1151 return this._handle_security_result();
1152
1153 case 'ClientInitialisation':
1154 this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation
1155 this._rfb_init_state = 'ServerInitialisation';
1156 return true;
b1dee947 1157
6d6f0db0
SR
1158 case 'ServerInitialisation':
1159 return this._negotiate_server_init();
b1dee947 1160
6d6f0db0
SR
1161 default:
1162 return this._fail("Internal error", "Unknown init state: " +
1163 this._rfb_init_state);
1164 }
1165 },
b1dee947 1166
6d6f0db0
SR
1167 _handle_set_colour_map_msg: function () {
1168 Log.Debug("SetColorMapEntries");
b1dee947 1169
26586b9d 1170 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
6d6f0db0 1171 },
b1dee947 1172
6d6f0db0
SR
1173 _handle_server_cut_text: function () {
1174 Log.Debug("ServerCutText");
b1dee947 1175
6d6f0db0
SR
1176 if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; }
1177 this._sock.rQskipBytes(3); // Padding
1178 var length = this._sock.rQshift32();
1179 if (this._sock.rQwait("ServerCutText", length, 8)) { return false; }
b1dee947 1180
6d6f0db0 1181 var text = this._sock.rQshiftStr(length);
b4ff032e
SR
1182
1183 if (this._view_only) { return true; }
1184
6d6f0db0 1185 this._onClipboard(this, text);
b1dee947 1186
6d6f0db0
SR
1187 return true;
1188 },
b1dee947 1189
6d6f0db0
SR
1190 _handle_server_fence_msg: function() {
1191 if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; }
1192 this._sock.rQskipBytes(3); // Padding
1193 var flags = this._sock.rQshift32();
1194 var length = this._sock.rQshift8();
b1dee947 1195
6d6f0db0 1196 if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; }
b1dee947 1197
6d6f0db0
SR
1198 if (length > 64) {
1199 Log.Warn("Bad payload length (" + length + ") in fence response");
1200 length = 64;
1201 }
4e0c36dd 1202
6d6f0db0 1203 var payload = this._sock.rQshiftStr(length);
b1dee947 1204
6d6f0db0 1205 this._supportsFence = true;
b1dee947 1206
6d6f0db0
SR
1207 /*
1208 * Fence flags
1209 *
1210 * (1<<0) - BlockBefore
1211 * (1<<1) - BlockAfter
1212 * (1<<2) - SyncNext
1213 * (1<<31) - Request
1214 */
b1dee947 1215
6d6f0db0
SR
1216 if (!(flags & (1<<31))) {
1217 return this._fail("Internal error",
1218 "Unexpected fence response");
1219 }
b1dee947 1220
6d6f0db0
SR
1221 // Filter out unsupported flags
1222 // FIXME: support syncNext
1223 flags &= (1<<0) | (1<<1);
b1dee947 1224
6d6f0db0
SR
1225 // BlockBefore and BlockAfter are automatically handled by
1226 // the fact that we process each incoming message
1227 // synchronuosly.
1228 RFB.messages.clientFence(this._sock, flags, payload);
f78a652e 1229
6d6f0db0
SR
1230 return true;
1231 },
b1dee947 1232
6d6f0db0
SR
1233 _handle_xvp_msg: function () {
1234 if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; }
1235 this._sock.rQskip8(); // Padding
1236 var xvp_ver = this._sock.rQshift8();
1237 var xvp_msg = this._sock.rQshift8();
b1dee947 1238
6d6f0db0
SR
1239 switch (xvp_msg) {
1240 case 0: // XVP_FAIL
1241 Log.Error("Operation Failed");
1242 this._notification("XVP Operation Failed", 'error');
1243 break;
1244 case 1: // XVP_INIT
1245 this._rfb_xvp_ver = xvp_ver;
1246 Log.Info("XVP extensions enabled (version " + this._rfb_xvp_ver + ")");
832be262 1247 this._setCapability("power", true);
6d6f0db0
SR
1248 break;
1249 default:
1250 this._fail("Unexpected server message",
1251 "Illegal server XVP message " + xvp_msg);
1252 break;
1253 }
b1dee947 1254
6d6f0db0
SR
1255 return true;
1256 },
3df13262 1257
6d6f0db0
SR
1258 _normal_msg: function () {
1259 var msg_type;
76a86ff5 1260
6d6f0db0
SR
1261 if (this._FBU.rects > 0) {
1262 msg_type = 0;
1263 } else {
1264 msg_type = this._sock.rQshift8();
1265 }
76a86ff5 1266
6d6f0db0
SR
1267 switch (msg_type) {
1268 case 0: // FramebufferUpdate
1269 var ret = this._framebufferUpdate();
1270 if (ret && !this._enabledContinuousUpdates) {
1271 RFB.messages.fbUpdateRequest(this._sock, true, 0, 0,
1272 this._fb_width, this._fb_height);
1273 }
1274 return ret;
3df13262 1275
6d6f0db0
SR
1276 case 1: // SetColorMapEntries
1277 return this._handle_set_colour_map_msg();
1278
1279 case 2: // Bell
1280 Log.Debug("Bell");
1281 this._onBell(this);
1282 return true;
1283
1284 case 3: // ServerCutText
1285 return this._handle_server_cut_text();
1286
1287 case 150: // EndOfContinuousUpdates
1288 var first = !(this._supportsContinuousUpdates);
1289 this._supportsContinuousUpdates = true;
1290 this._enabledContinuousUpdates = false;
1291 if (first) {
1292 this._enabledContinuousUpdates = true;
1293 this._updateContinuousUpdates();
1294 Log.Info("Enabling continuous updates.");
1295 } else {
1296 // FIXME: We need to send a framebufferupdaterequest here
1297 // if we add support for turning off continuous updates
1298 }
1299 return true;
3df13262 1300
6d6f0db0
SR
1301 case 248: // ServerFence
1302 return this._handle_server_fence_msg();
3df13262 1303
6d6f0db0
SR
1304 case 250: // XVP
1305 return this._handle_xvp_msg();
3df13262 1306
6d6f0db0
SR
1307 default:
1308 this._fail("Unexpected server message", "Type:" + msg_type);
1309 Log.Debug("sock.rQslice(0, 30): " + this._sock.rQslice(0, 30));
1310 return true;
1311 }
1312 },
3df13262 1313
6d6f0db0
SR
1314 _onFlush: function() {
1315 this._flushing = false;
1316 // Resume processing
1317 if (this._sock.rQlen() > 0) {
1318 this._handle_message();
1319 }
1320 },
3df13262 1321
6d6f0db0
SR
1322 _framebufferUpdate: function () {
1323 var ret = true;
1324 var now;
3df13262 1325
6d6f0db0
SR
1326 if (this._FBU.rects === 0) {
1327 if (this._sock.rQwait("FBU header", 3, 1)) { return false; }
b1dee947 1328 this._sock.rQskip8(); // Padding
6d6f0db0
SR
1329 this._FBU.rects = this._sock.rQshift16();
1330 this._FBU.bytes = 0;
1331 this._timing.cur_fbu = 0;
1332 if (this._timing.fbu_rt_start > 0) {
1333 now = (new Date()).getTime();
1334 Log.Info("First FBU latency: " + (now - this._timing.fbu_rt_start));
b1dee947
SR
1335 }
1336
6d6f0db0
SR
1337 // Make sure the previous frame is fully rendered first
1338 // to avoid building up an excessive queue
1339 if (this._display.pending()) {
1340 this._flushing = true;
1341 this._display.flush();
1342 return false;
1343 }
1344 }
b1dee947 1345
6d6f0db0
SR
1346 while (this._FBU.rects > 0) {
1347 if (this._rfb_connection_state !== 'connected') { return false; }
b1dee947 1348
6d6f0db0
SR
1349 if (this._sock.rQwait("FBU", this._FBU.bytes)) { return false; }
1350 if (this._FBU.bytes === 0) {
1351 if (this._sock.rQwait("rect header", 12)) { return false; }
1352 /* New FramebufferUpdate */
b1dee947 1353
6d6f0db0
SR
1354 var hdr = this._sock.rQshiftBytes(12);
1355 this._FBU.x = (hdr[0] << 8) + hdr[1];
1356 this._FBU.y = (hdr[2] << 8) + hdr[3];
1357 this._FBU.width = (hdr[4] << 8) + hdr[5];
1358 this._FBU.height = (hdr[6] << 8) + hdr[7];
1359 this._FBU.encoding = parseInt((hdr[8] << 24) + (hdr[9] << 16) +
1360 (hdr[10] << 8) + hdr[11], 10);
b1dee947 1361
49a81837 1362 if (!this._encHandlers[this._FBU.encoding]) {
6d6f0db0
SR
1363 this._fail("Unexpected server message",
1364 "Unsupported encoding " +
1365 this._FBU.encoding);
1366 return false;
1367 }
1368 }
b1dee947 1369
6d6f0db0 1370 this._timing.last_fbu = (new Date()).getTime();
76a86ff5 1371
6d6f0db0 1372 ret = this._encHandlers[this._FBU.encoding]();
3df13262 1373
6d6f0db0
SR
1374 now = (new Date()).getTime();
1375 this._timing.cur_fbu += (now - this._timing.last_fbu);
b1dee947 1376
6d6f0db0 1377 if (ret) {
c3386227
PO
1378 if (!(this._FBU.encoding in this._encStats)) {
1379 this._encStats[this._FBU.encoding] = [0, 0];
1380 }
6d6f0db0
SR
1381 this._encStats[this._FBU.encoding][0]++;
1382 this._encStats[this._FBU.encoding][1]++;
1383 this._timing.pixels += this._FBU.width * this._FBU.height;
b1dee947 1384 }
b1dee947 1385
6d6f0db0
SR
1386 if (this._timing.pixels >= (this._fb_width * this._fb_height)) {
1387 if ((this._FBU.width === this._fb_width && this._FBU.height === this._fb_height) ||
1388 this._timing.fbu_rt_start > 0) {
1389 this._timing.full_fbu_total += this._timing.cur_fbu;
1390 this._timing.full_fbu_cnt++;
1391 Log.Info("Timing of full FBU, curr: " +
1392 this._timing.cur_fbu + ", total: " +
1393 this._timing.full_fbu_total + ", cnt: " +
1394 this._timing.full_fbu_cnt + ", avg: " +
1395 (this._timing.full_fbu_total / this._timing.full_fbu_cnt));
b1dee947 1396 }
d9ca5e5b 1397
6d6f0db0
SR
1398 if (this._timing.fbu_rt_start > 0) {
1399 var fbu_rt_diff = now - this._timing.fbu_rt_start;
1400 this._timing.fbu_rt_total += fbu_rt_diff;
1401 this._timing.fbu_rt_cnt++;
1402 Log.Info("full FBU round-trip, cur: " +
1403 fbu_rt_diff + ", total: " +
1404 this._timing.fbu_rt_total + ", cnt: " +
1405 this._timing.fbu_rt_cnt + ", avg: " +
1406 (this._timing.fbu_rt_total / this._timing.fbu_rt_cnt));
1407 this._timing.fbu_rt_start = 0;
d9ca5e5b 1408 }
b1dee947
SR
1409 }
1410
6d6f0db0
SR
1411 if (!ret) { return ret; } // need more data
1412 }
b1dee947 1413
6d6f0db0 1414 this._display.flip();
b1dee947 1415
6d6f0db0
SR
1416 return true; // We finished this FBU
1417 },
b1dee947 1418
6d6f0db0
SR
1419 _updateContinuousUpdates: function() {
1420 if (!this._enabledContinuousUpdates) { return; }
b1dee947 1421
6d6f0db0
SR
1422 RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0,
1423 this._fb_width, this._fb_height);
91d5c625
PO
1424 },
1425
1426 _resize: function(width, height) {
1427 this._fb_width = width;
1428 this._fb_height = height;
1429
1430 this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
1431
1432 this._display.resize(this._fb_width, this._fb_height);
1433 this._onFBResize(this, this._fb_width, this._fb_height);
1434
1435 this._timing.fbu_rt_start = (new Date()).getTime();
1436 this._updateContinuousUpdates();
cd523e8f
PO
1437 },
1438
1439 _xvpOp: function (ver, op) {
1440 if (this._rfb_xvp_ver < ver) { return; }
1441 Log.Info("Sending XVP operation " + op + " (version " + ver + ")");
1442 RFB.messages.xvpOp(this._sock, ver, op);
1443 },
6d6f0db0 1444};
8db09746 1445
6d6f0db0 1446make_properties(RFB, [
6d6f0db0 1447 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
6d6f0db0 1448 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
f976b550 1449 ['touchButton', 'rw', 'int'], // Button mask (1, 2, 4) for touch devices (0 means ignore clicks)
b9854a5c
PO
1450 ['scale', 'rw', 'float'], // Display area scale factor
1451 ['viewport', 'rw', 'bool'], // Use viewport clipping
6d6f0db0 1452 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
6d6f0db0 1453 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
cd523e8f 1454 ['capabilities', 'ro', 'arr'], // Supported capabilities
6d6f0db0
SR
1455
1456 // Callback functions
1457 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1458 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1459 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
430f00d6 1460 ['onCredentialsRequired', 'rw', 'func'], // onCredentialsRequired(rfb, types): VNC credentials are required
6d6f0db0
SR
1461 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1462 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
6d6f0db0
SR
1463 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1464 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
cd523e8f 1465 ['onCapabilities', 'rw', 'func'] // onCapabilities(rfb, caps): the supported capabilities has changed
6d6f0db0
SR
1466]);
1467
1468RFB.prototype.set_local_cursor = function (cursor) {
1469 if (!cursor || (cursor in {'0': 1, 'no': 1, 'false': 1})) {
1470 this._local_cursor = false;
1471 this._display.disableLocalCursor(); //Only show server-side cursor
1472 } else {
1473 if (this._display.get_cursor_uri()) {
1474 this._local_cursor = true;
1475 } else {
1476 Log.Warn("Browser does not support local cursor");
1477 this._display.disableLocalCursor();
1478 }
1479 }
d86cc2d9 1480
6d6f0db0
SR
1481 // Need to send an updated list of encodings if we are connected
1482 if (this._rfb_connection_state === "connected") {
49a81837 1483 this._sendEncodings();
6d6f0db0
SR
1484 }
1485};
2ba767a7 1486
6d6f0db0
SR
1487RFB.prototype.set_view_only = function (view_only) {
1488 this._view_only = view_only;
8db09746 1489
6d6f0db0
SR
1490 if (this._rfb_connection_state === "connecting" ||
1491 this._rfb_connection_state === "connected") {
1492 if (view_only) {
1493 this._keyboard.ungrab();
1494 this._mouse.ungrab();
1495 } else {
1496 this._keyboard.grab();
1497 this._mouse.grab();
1498 }
1499 }
1500};
76a86ff5 1501
f976b550
PO
1502RFB.prototype.set_touchButton = function (button) {
1503 this._mouse.set_touchButton(button);
1504};
1505
1506RFB.prototype.get_touchButton = function () {
1507 return this._mouse.get_touchButton();
1508};
1509
b9854a5c
PO
1510RFB.prototype.set_scale = function (scale) {
1511 this._display.set_scale(scale);
1512};
1513
1514RFB.prototype.get_scale = function () {
1515 return this._display.get_scale();
1516};
1517
1518RFB.prototype.set_viewport = function (viewport) {
1519 this._display.set_viewport(viewport);
1520};
1521
1522RFB.prototype.get_viewport = function () {
1523 return this._display.get_viewport();
1524};
1525
6d6f0db0
SR
1526// Class Methods
1527RFB.messages = {
1528 keyEvent: function (sock, keysym, down) {
1529 var buff = sock._sQ;
1530 var offset = sock._sQlen;
8db09746 1531
6d6f0db0
SR
1532 buff[offset] = 4; // msg-type
1533 buff[offset + 1] = down;
b1dee947 1534
6d6f0db0
SR
1535 buff[offset + 2] = 0;
1536 buff[offset + 3] = 0;
fb49f91b 1537
6d6f0db0
SR
1538 buff[offset + 4] = (keysym >> 24);
1539 buff[offset + 5] = (keysym >> 16);
1540 buff[offset + 6] = (keysym >> 8);
1541 buff[offset + 7] = keysym;
b1dee947 1542
6d6f0db0
SR
1543 sock._sQlen += 8;
1544 sock.flush();
1545 },
ef1e8bab 1546
6d6f0db0
SR
1547 QEMUExtendedKeyEvent: function (sock, keysym, down, keycode) {
1548 function getRFBkeycode(xt_scancode) {
1549 var upperByte = (keycode >> 8);
1550 var lowerByte = (keycode & 0x00ff);
1551 if (upperByte === 0xe0 && lowerByte < 0x7f) {
1552 lowerByte = lowerByte | 0x80;
1553 return lowerByte;
ef1e8bab 1554 }
6d6f0db0 1555 return xt_scancode;
ef1e8bab 1556 }
b1dee947 1557
6d6f0db0
SR
1558 var buff = sock._sQ;
1559 var offset = sock._sQlen;
8f06673a 1560
6d6f0db0
SR
1561 buff[offset] = 255; // msg-type
1562 buff[offset + 1] = 0; // sub msg-type
8f06673a 1563
6d6f0db0
SR
1564 buff[offset + 2] = (down >> 8);
1565 buff[offset + 3] = down;
8f06673a 1566
6d6f0db0
SR
1567 buff[offset + 4] = (keysym >> 24);
1568 buff[offset + 5] = (keysym >> 16);
1569 buff[offset + 6] = (keysym >> 8);
1570 buff[offset + 7] = keysym;
8f06673a 1571
6d6f0db0 1572 var RFBkeycode = getRFBkeycode(keycode);
8f06673a 1573
6d6f0db0
SR
1574 buff[offset + 8] = (RFBkeycode >> 24);
1575 buff[offset + 9] = (RFBkeycode >> 16);
1576 buff[offset + 10] = (RFBkeycode >> 8);
1577 buff[offset + 11] = RFBkeycode;
8f06673a 1578
6d6f0db0
SR
1579 sock._sQlen += 12;
1580 sock.flush();
1581 },
8f06673a 1582
6d6f0db0
SR
1583 pointerEvent: function (sock, x, y, mask) {
1584 var buff = sock._sQ;
1585 var offset = sock._sQlen;
8f06673a 1586
6d6f0db0 1587 buff[offset] = 5; // msg-type
9ff86fb7 1588
6d6f0db0 1589 buff[offset + 1] = mask;
9ff86fb7 1590
6d6f0db0
SR
1591 buff[offset + 2] = x >> 8;
1592 buff[offset + 3] = x;
9ff86fb7 1593
6d6f0db0
SR
1594 buff[offset + 4] = y >> 8;
1595 buff[offset + 5] = y;
9ff86fb7 1596
6d6f0db0
SR
1597 sock._sQlen += 6;
1598 sock.flush();
1599 },
9ff86fb7 1600
6d6f0db0
SR
1601 // TODO(directxman12): make this unicode compatible?
1602 clientCutText: function (sock, text) {
1603 var buff = sock._sQ;
1604 var offset = sock._sQlen;
b1dee947 1605
6d6f0db0 1606 buff[offset] = 6; // msg-type
9ff86fb7 1607
6d6f0db0
SR
1608 buff[offset + 1] = 0; // padding
1609 buff[offset + 2] = 0; // padding
1610 buff[offset + 3] = 0; // padding
9ff86fb7 1611
6d6f0db0 1612 var n = text.length;
9ff86fb7 1613
6d6f0db0
SR
1614 buff[offset + 4] = n >> 24;
1615 buff[offset + 5] = n >> 16;
1616 buff[offset + 6] = n >> 8;
1617 buff[offset + 7] = n;
9ff86fb7 1618
6d6f0db0
SR
1619 for (var i = 0; i < n; i++) {
1620 buff[offset + 8 + i] = text.charCodeAt(i);
1621 }
9ff86fb7 1622
6d6f0db0
SR
1623 sock._sQlen += 8 + n;
1624 sock.flush();
1625 },
1626
1627 setDesktopSize: function (sock, width, height, id, flags) {
1628 var buff = sock._sQ;
1629 var offset = sock._sQlen;
1630
1631 buff[offset] = 251; // msg-type
1632 buff[offset + 1] = 0; // padding
1633 buff[offset + 2] = width >> 8; // width
1634 buff[offset + 3] = width;
1635 buff[offset + 4] = height >> 8; // height
1636 buff[offset + 5] = height;
1637
1638 buff[offset + 6] = 1; // number-of-screens
1639 buff[offset + 7] = 0; // padding
1640
1641 // screen array
1642 buff[offset + 8] = id >> 24; // id
1643 buff[offset + 9] = id >> 16;
1644 buff[offset + 10] = id >> 8;
1645 buff[offset + 11] = id;
1646 buff[offset + 12] = 0; // x-position
1647 buff[offset + 13] = 0;
1648 buff[offset + 14] = 0; // y-position
1649 buff[offset + 15] = 0;
1650 buff[offset + 16] = width >> 8; // width
1651 buff[offset + 17] = width;
1652 buff[offset + 18] = height >> 8; // height
1653 buff[offset + 19] = height;
1654 buff[offset + 20] = flags >> 24; // flags
1655 buff[offset + 21] = flags >> 16;
1656 buff[offset + 22] = flags >> 8;
1657 buff[offset + 23] = flags;
1658
1659 sock._sQlen += 24;
1660 sock.flush();
1661 },
1662
1663 clientFence: function (sock, flags, payload) {
1664 var buff = sock._sQ;
1665 var offset = sock._sQlen;
1666
1667 buff[offset] = 248; // msg-type
1668
1669 buff[offset + 1] = 0; // padding
1670 buff[offset + 2] = 0; // padding
1671 buff[offset + 3] = 0; // padding
1672
1673 buff[offset + 4] = flags >> 24; // flags
1674 buff[offset + 5] = flags >> 16;
1675 buff[offset + 6] = flags >> 8;
1676 buff[offset + 7] = flags;
1677
1678 var n = payload.length;
1679
1680 buff[offset + 8] = n; // length
1681
1682 for (var i = 0; i < n; i++) {
1683 buff[offset + 9 + i] = payload.charCodeAt(i);
1684 }
a7a89626 1685
6d6f0db0
SR
1686 sock._sQlen += 9 + n;
1687 sock.flush();
1688 },
3df13262 1689
6d6f0db0
SR
1690 enableContinuousUpdates: function (sock, enable, x, y, width, height) {
1691 var buff = sock._sQ;
1692 var offset = sock._sQlen;
3df13262 1693
6d6f0db0
SR
1694 buff[offset] = 150; // msg-type
1695 buff[offset + 1] = enable; // enable-flag
76a86ff5 1696
6d6f0db0
SR
1697 buff[offset + 2] = x >> 8; // x
1698 buff[offset + 3] = x;
1699 buff[offset + 4] = y >> 8; // y
1700 buff[offset + 5] = y;
1701 buff[offset + 6] = width >> 8; // width
1702 buff[offset + 7] = width;
1703 buff[offset + 8] = height >> 8; // height
1704 buff[offset + 9] = height;
76a86ff5 1705
6d6f0db0
SR
1706 sock._sQlen += 10;
1707 sock.flush();
1708 },
76a86ff5 1709
5a5f5ada 1710 pixelFormat: function (sock, depth, true_color) {
6d6f0db0
SR
1711 var buff = sock._sQ;
1712 var offset = sock._sQlen;
ae116051 1713
5a5f5ada
PO
1714 var bpp, bits;
1715
1716 if (depth > 16) {
1717 bpp = 32;
1718 } else if (depth > 8) {
1719 bpp = 16;
1720 } else {
1721 bpp = 8;
1722 }
1723
1724 bits = Math.floor(depth/3);
1725
6d6f0db0 1726 buff[offset] = 0; // msg-type
9ff86fb7 1727
6d6f0db0
SR
1728 buff[offset + 1] = 0; // padding
1729 buff[offset + 2] = 0; // padding
1730 buff[offset + 3] = 0; // padding
9ff86fb7 1731
5a5f5ada
PO
1732 buff[offset + 4] = bpp; // bits-per-pixel
1733 buff[offset + 5] = depth; // depth
6d6f0db0
SR
1734 buff[offset + 6] = 0; // little-endian
1735 buff[offset + 7] = true_color ? 1 : 0; // true-color
9ff86fb7 1736
6d6f0db0 1737 buff[offset + 8] = 0; // red-max
5a5f5ada 1738 buff[offset + 9] = (1 << bits) - 1; // red-max
9ff86fb7 1739
6d6f0db0 1740 buff[offset + 10] = 0; // green-max
5a5f5ada 1741 buff[offset + 11] = (1 << bits) - 1; // green-max
9ff86fb7 1742
6d6f0db0 1743 buff[offset + 12] = 0; // blue-max
5a5f5ada 1744 buff[offset + 13] = (1 << bits) - 1; // blue-max
9ff86fb7 1745
5a5f5ada
PO
1746 buff[offset + 14] = bits * 2; // red-shift
1747 buff[offset + 15] = bits * 1; // green-shift
1748 buff[offset + 16] = bits * 0; // blue-shift
9ff86fb7 1749
6d6f0db0
SR
1750 buff[offset + 17] = 0; // padding
1751 buff[offset + 18] = 0; // padding
1752 buff[offset + 19] = 0; // padding
9ff86fb7 1753
6d6f0db0
SR
1754 sock._sQlen += 20;
1755 sock.flush();
1756 },
9ff86fb7 1757
49a81837 1758 clientEncodings: function (sock, encodings) {
6d6f0db0
SR
1759 var buff = sock._sQ;
1760 var offset = sock._sQlen;
b1dee947 1761
6d6f0db0
SR
1762 buff[offset] = 2; // msg-type
1763 buff[offset + 1] = 0; // padding
b1dee947 1764
49a81837
PO
1765 buff[offset + 2] = encodings.length >> 8;
1766 buff[offset + 3] = encodings.length;
9ff86fb7 1767
49a81837 1768 var i, j = offset + 4;
6d6f0db0 1769 for (i = 0; i < encodings.length; i++) {
49a81837
PO
1770 var enc = encodings[i];
1771 buff[j] = enc >> 24;
1772 buff[j + 1] = enc >> 16;
1773 buff[j + 2] = enc >> 8;
1774 buff[j + 3] = enc;
a7a89626 1775
49a81837
PO
1776 j += 4;
1777 }
a7a89626 1778
6d6f0db0
SR
1779 sock._sQlen += j - offset;
1780 sock.flush();
1781 },
a679a97d 1782
6d6f0db0
SR
1783 fbUpdateRequest: function (sock, incremental, x, y, w, h) {
1784 var buff = sock._sQ;
1785 var offset = sock._sQlen;
9ff86fb7 1786
6d6f0db0
SR
1787 if (typeof(x) === "undefined") { x = 0; }
1788 if (typeof(y) === "undefined") { y = 0; }
b1dee947 1789
6d6f0db0
SR
1790 buff[offset] = 3; // msg-type
1791 buff[offset + 1] = incremental ? 1 : 0;
9ff86fb7 1792
6d6f0db0
SR
1793 buff[offset + 2] = (x >> 8) & 0xFF;
1794 buff[offset + 3] = x & 0xFF;
9ff86fb7 1795
6d6f0db0
SR
1796 buff[offset + 4] = (y >> 8) & 0xFF;
1797 buff[offset + 5] = y & 0xFF;
9ff86fb7 1798
6d6f0db0
SR
1799 buff[offset + 6] = (w >> 8) & 0xFF;
1800 buff[offset + 7] = w & 0xFF;
9ff86fb7 1801
6d6f0db0
SR
1802 buff[offset + 8] = (h >> 8) & 0xFF;
1803 buff[offset + 9] = h & 0xFF;
b1dee947 1804
6d6f0db0
SR
1805 sock._sQlen += 10;
1806 sock.flush();
85b35fc0
PO
1807 },
1808
1809 xvpOp: function (sock, ver, op) {
1810 var buff = sock._sQ;
1811 var offset = sock._sQlen;
1812
1813 buff[offset] = 250; // msg-type
1814 buff[offset + 1] = 0; // padding
1815
1816 buff[offset + 2] = ver;
1817 buff[offset + 3] = op;
1818
1819 sock._sQlen += 4;
1820 sock.flush();
1821 },
6d6f0db0 1822};
b1dee947 1823
6d6f0db0
SR
1824RFB.genDES = function (password, challenge) {
1825 var passwd = [];
1826 for (var i = 0; i < password.length; i++) {
1827 passwd.push(password.charCodeAt(i));
1828 }
1829 return (new DES(passwd)).encrypt(challenge);
1830};
b1dee947 1831
6d6f0db0
SR
1832RFB.encodingHandlers = {
1833 RAW: function () {
1834 if (this._FBU.lines === 0) {
1835 this._FBU.lines = this._FBU.height;
1836 }
a7a89626 1837
5a5f5ada
PO
1838 var pixelSize = this._fb_depth == 8 ? 1 : 4;
1839 this._FBU.bytes = this._FBU.width * pixelSize; // at least a line
6d6f0db0
SR
1840 if (this._sock.rQwait("RAW", this._FBU.bytes)) { return false; }
1841 var cur_y = this._FBU.y + (this._FBU.height - this._FBU.lines);
1842 var curr_height = Math.min(this._FBU.lines,
5a5f5ada
PO
1843 Math.floor(this._sock.rQlen() / (this._FBU.width * pixelSize)));
1844 var data = this._sock.get_rQ();
1845 var index = this._sock.get_rQi();
1846 if (this._fb_depth == 8) {
1847 var pixels = this._FBU.width * curr_height
1848 var newdata = new Uint8Array(pixels * 4);
1849 var i;
1850 for (i = 0;i < pixels;i++) {
1851 newdata[i * 4 + 0] = ((data[index + i] >> 0) & 0x3) * 255 / 3;
1852 newdata[i * 4 + 1] = ((data[index + i] >> 2) & 0x3) * 255 / 3;
1853 newdata[i * 4 + 2] = ((data[index + i] >> 4) & 0x3) * 255 / 3;
1854 newdata[i * 4 + 4] = 0;
1855 }
1856 data = newdata;
1857 index = 0;
1858 }
6d6f0db0 1859 this._display.blitImage(this._FBU.x, cur_y, this._FBU.width,
5a5f5ada
PO
1860 curr_height, data, index);
1861 this._sock.rQskipBytes(this._FBU.width * curr_height * pixelSize);
6d6f0db0
SR
1862 this._FBU.lines -= curr_height;
1863
1864 if (this._FBU.lines > 0) {
5a5f5ada 1865 this._FBU.bytes = this._FBU.width * pixelSize; // At least another line
6d6f0db0
SR
1866 } else {
1867 this._FBU.rects--;
1868 this._FBU.bytes = 0;
1869 }
b1dee947 1870
6d6f0db0
SR
1871 return true;
1872 },
1873
1874 COPYRECT: function () {
1875 this._FBU.bytes = 4;
1876 if (this._sock.rQwait("COPYRECT", 4)) { return false; }
1877 this._display.copyImage(this._sock.rQshift16(), this._sock.rQshift16(),
1878 this._FBU.x, this._FBU.y, this._FBU.width,
1879 this._FBU.height);
1880
1881 this._FBU.rects--;
1882 this._FBU.bytes = 0;
1883 return true;
1884 },
1885
1886 RRE: function () {
1887 var color;
1888 if (this._FBU.subrects === 0) {
26586b9d
PO
1889 this._FBU.bytes = 4 + 4;
1890 if (this._sock.rQwait("RRE", 4 + 4)) { return false; }
6d6f0db0 1891 this._FBU.subrects = this._sock.rQshift32();
26586b9d 1892 color = this._sock.rQshiftBytes(4); // Background
6d6f0db0
SR
1893 this._display.fillRect(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, color);
1894 }
b1dee947 1895
26586b9d
PO
1896 while (this._FBU.subrects > 0 && this._sock.rQlen() >= (4 + 8)) {
1897 color = this._sock.rQshiftBytes(4);
6d6f0db0
SR
1898 var x = this._sock.rQshift16();
1899 var y = this._sock.rQshift16();
1900 var width = this._sock.rQshift16();
1901 var height = this._sock.rQshift16();
1902 this._display.fillRect(this._FBU.x + x, this._FBU.y + y, width, height, color);
1903 this._FBU.subrects--;
1904 }
f00193e0 1905
6d6f0db0
SR
1906 if (this._FBU.subrects > 0) {
1907 var chunk = Math.min(this._rre_chunk_sz, this._FBU.subrects);
26586b9d 1908 this._FBU.bytes = (4 + 8) * chunk;
6d6f0db0 1909 } else {
b1dee947
SR
1910 this._FBU.rects--;
1911 this._FBU.bytes = 0;
6d6f0db0 1912 }
b1dee947 1913
6d6f0db0
SR
1914 return true;
1915 },
b1dee947 1916
6d6f0db0
SR
1917 HEXTILE: function () {
1918 var rQ = this._sock.get_rQ();
1919 var rQi = this._sock.get_rQi();
b1dee947 1920
6d6f0db0
SR
1921 if (this._FBU.tiles === 0) {
1922 this._FBU.tiles_x = Math.ceil(this._FBU.width / 16);
1923 this._FBU.tiles_y = Math.ceil(this._FBU.height / 16);
1924 this._FBU.total_tiles = this._FBU.tiles_x * this._FBU.tiles_y;
1925 this._FBU.tiles = this._FBU.total_tiles;
1926 }
b1dee947 1927
6d6f0db0
SR
1928 while (this._FBU.tiles > 0) {
1929 this._FBU.bytes = 1;
1930 if (this._sock.rQwait("HEXTILE subencoding", this._FBU.bytes)) { return false; }
1931 var subencoding = rQ[rQi]; // Peek
1932 if (subencoding > 30) { // Raw
1933 this._fail("Unexpected server message",
1934 "Illegal hextile subencoding: " + subencoding);
1935 return false;
b1dee947
SR
1936 }
1937
6d6f0db0
SR
1938 var subrects = 0;
1939 var curr_tile = this._FBU.total_tiles - this._FBU.tiles;
1940 var tile_x = curr_tile % this._FBU.tiles_x;
1941 var tile_y = Math.floor(curr_tile / this._FBU.tiles_x);
1942 var x = this._FBU.x + tile_x * 16;
1943 var y = this._FBU.y + tile_y * 16;
1944 var w = Math.min(16, (this._FBU.x + this._FBU.width) - x);
1945 var h = Math.min(16, (this._FBU.y + this._FBU.height) - y);
b1dee947 1946
6d6f0db0
SR
1947 // Figure out how much we are expecting
1948 if (subencoding & 0x01) { // Raw
26586b9d 1949 this._FBU.bytes += w * h * 4;
6d6f0db0
SR
1950 } else {
1951 if (subencoding & 0x02) { // Background
26586b9d 1952 this._FBU.bytes += 4;
6d6f0db0
SR
1953 }
1954 if (subencoding & 0x04) { // Foreground
26586b9d 1955 this._FBU.bytes += 4;
6d6f0db0
SR
1956 }
1957 if (subencoding & 0x08) { // AnySubrects
1958 this._FBU.bytes++; // Since we aren't shifting it off
1959 if (this._sock.rQwait("hextile subrects header", this._FBU.bytes)) { return false; }
1960 subrects = rQ[rQi + this._FBU.bytes - 1]; // Peek
1961 if (subencoding & 0x10) { // SubrectsColoured
26586b9d 1962 this._FBU.bytes += subrects * (4 + 2);
6d6f0db0
SR
1963 } else {
1964 this._FBU.bytes += subrects * 2;
b1dee947
SR
1965 }
1966 }
6d6f0db0 1967 }
b1dee947 1968
6d6f0db0 1969 if (this._sock.rQwait("hextile", this._FBU.bytes)) { return false; }
b1dee947 1970
6d6f0db0
SR
1971 // We know the encoding and have a whole tile
1972 this._FBU.subencoding = rQ[rQi];
1973 rQi++;
1974 if (this._FBU.subencoding === 0) {
1975 if (this._FBU.lastsubencoding & 0x01) {
1976 // Weird: ignore blanks are RAW
1977 Log.Debug(" Ignoring blank after RAW");
b1dee947 1978 } else {
6d6f0db0
SR
1979 this._display.fillRect(x, y, w, h, this._FBU.background);
1980 }
1981 } else if (this._FBU.subencoding & 0x01) { // Raw
1982 this._display.blitImage(x, y, w, h, rQ, rQi);
1983 rQi += this._FBU.bytes - 1;
1984 } else {
1985 if (this._FBU.subencoding & 0x02) { // Background
26586b9d
PO
1986 this._FBU.background = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1987 rQi += 4;
6d6f0db0
SR
1988 }
1989 if (this._FBU.subencoding & 0x04) { // Foreground
26586b9d
PO
1990 this._FBU.foreground = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1991 rQi += 4;
6d6f0db0 1992 }
b1dee947 1993
6d6f0db0
SR
1994 this._display.startTile(x, y, w, h, this._FBU.background);
1995 if (this._FBU.subencoding & 0x08) { // AnySubrects
1996 subrects = rQ[rQi];
1997 rQi++;
b1dee947 1998
6d6f0db0
SR
1999 for (var s = 0; s < subrects; s++) {
2000 var color;
2001 if (this._FBU.subencoding & 0x10) { // SubrectsColoured
26586b9d
PO
2002 color = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
2003 rQi += 4;
6d6f0db0
SR
2004 } else {
2005 color = this._FBU.foreground;
2006 }
2007 var xy = rQ[rQi];
2008 rQi++;
2009 var sx = (xy >> 4);
2010 var sy = (xy & 0x0f);
a7a89626 2011
6d6f0db0
SR
2012 var wh = rQ[rQi];
2013 rQi++;
2014 var sw = (wh >> 4) + 1;
2015 var sh = (wh & 0x0f) + 1;
a7a89626 2016
6d6f0db0 2017 this._display.subTile(sx, sy, sw, sh, color);
b1dee947 2018 }
a7a89626 2019 }
6d6f0db0 2020 this._display.finishTile();
a7a89626 2021 }
6d6f0db0
SR
2022 this._sock.set_rQi(rQi);
2023 this._FBU.lastsubencoding = this._FBU.subencoding;
2024 this._FBU.bytes = 0;
2025 this._FBU.tiles--;
2026 }
d065cad9 2027
6d6f0db0
SR
2028 if (this._FBU.tiles === 0) {
2029 this._FBU.rects--;
2030 }
b1dee947 2031
6d6f0db0
SR
2032 return true;
2033 },
b1dee947 2034
3e8b26ab 2035 TIGHT: function () {
6d6f0db0
SR
2036 this._FBU.bytes = 1; // compression-control byte
2037 if (this._sock.rQwait("TIGHT compression-control", this._FBU.bytes)) { return false; }
2038
2039 var checksum = function (data) {
2040 var sum = 0;
2041 for (var i = 0; i < data.length; i++) {
2042 sum += data[i];
2043 if (sum > 65536) sum -= 65536;
2044 }
2045 return sum;
2046 };
2047
2048 var resetStreams = 0;
2049 var streamId = -1;
2050 var decompress = function (data, expected) {
2051 for (var i = 0; i < 4; i++) {
2052 if ((resetStreams >> i) & 1) {
2053 this._FBU.zlibs[i].reset();
2054 Log.Info("Reset zlib stream " + i);
b1dee947 2055 }
6d6f0db0 2056 }
de84e098 2057
6d6f0db0
SR
2058 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2059 var uncompressed = this._FBU.zlibs[streamId].inflate(data, true, expected);
2060 /*if (uncompressed.status !== 0) {
2061 Log.Error("Invalid data in zlib stream");
2062 }*/
2063
2064 //return uncompressed.data;
2065 return uncompressed;
2066 }.bind(this);
2067
2068 var indexedToRGBX2Color = function (data, palette, width, height) {
2069 // Convert indexed (palette based) image data to RGB
2070 // TODO: reduce number of calculations inside loop
2071 var dest = this._destBuff;
2072 var w = Math.floor((width + 7) / 8);
2073 var w1 = Math.floor(width / 8);
2074
2075 /*for (var y = 0; y < height; y++) {
2076 var b, x, dp, sp;
2077 var yoffset = y * width;
2078 var ybitoffset = y * w;
2079 var xoffset, targetbyte;
2080 for (x = 0; x < w1; x++) {
d1800d09
SR
2081 xoffset = yoffset + x * 8;
2082 targetbyte = data[ybitoffset + x];
6d6f0db0 2083 for (b = 7; b >= 0; b--) {
d1800d09
SR
2084 dp = (xoffset + 7 - b) * 3;
2085 sp = (targetbyte >> b & 1) * 3;
2086 dest[dp] = palette[sp];
2087 dest[dp + 1] = palette[sp + 1];
2088 dest[dp + 2] = palette[sp + 2];
2089 }
6d6f0db0
SR
2090 }
2091
2092 xoffset = yoffset + x * 8;
2093 targetbyte = data[ybitoffset + x];
2094 for (b = 7; b >= 8 - width % 8; b--) {
2095 dp = (xoffset + 7 - b) * 3;
2096 sp = (targetbyte >> b & 1) * 3;
2097 dest[dp] = palette[sp];
2098 dest[dp + 1] = palette[sp + 1];
2099 dest[dp + 2] = palette[sp + 2];
2100 }
2101 }*/
d1800d09 2102
6d6f0db0
SR
2103 for (var y = 0; y < height; y++) {
2104 var b, x, dp, sp;
2105 for (x = 0; x < w1; x++) {
2106 for (b = 7; b >= 0; b--) {
d1800d09
SR
2107 dp = (y * width + x * 8 + 7 - b) * 4;
2108 sp = (data[y * w + x] >> b & 1) * 3;
2109 dest[dp] = palette[sp];
2110 dest[dp + 1] = palette[sp + 1];
2111 dest[dp + 2] = palette[sp + 2];
2112 dest[dp + 3] = 255;
e16ad2fd
JM
2113 }
2114 }
b1dee947 2115
6d6f0db0
SR
2116 for (b = 7; b >= 8 - width % 8; b--) {
2117 dp = (y * width + x * 8 + 7 - b) * 4;
2118 sp = (data[y * w + x] >> b & 1) * 3;
2119 dest[dp] = palette[sp];
2120 dest[dp + 1] = palette[sp + 1];
2121 dest[dp + 2] = palette[sp + 2];
2122 dest[dp + 3] = 255;
d1800d09 2123 }
6d6f0db0 2124 }
d1800d09 2125
6d6f0db0
SR
2126 return dest;
2127 }.bind(this);
2128
2129 var indexedToRGBX = function (data, palette, width, height) {
2130 // Convert indexed (palette based) image data to RGB
2131 var dest = this._destBuff;
2132 var total = width * height * 4;
2133 for (var i = 0, j = 0; i < total; i += 4, j++) {
2134 var sp = data[j] * 3;
2135 dest[i] = palette[sp];
2136 dest[i + 1] = palette[sp + 1];
2137 dest[i + 2] = palette[sp + 2];
2138 dest[i + 3] = 255;
2139 }
2140
2141 return dest;
2142 }.bind(this);
2143
2144 var rQi = this._sock.get_rQi();
2145 var rQ = this._sock.rQwhole();
2146 var cmode, data;
2147 var cl_header, cl_data;
2148
2149 var handlePalette = function () {
2150 var numColors = rQ[rQi + 2] + 1;
26586b9d 2151 var paletteSize = numColors * 3;
6d6f0db0
SR
2152 this._FBU.bytes += paletteSize;
2153 if (this._sock.rQwait("TIGHT palette " + cmode, this._FBU.bytes)) { return false; }
2154
2155 var bpp = (numColors <= 2) ? 1 : 8;
2156 var rowSize = Math.floor((this._FBU.width * bpp + 7) / 8);
2157 var raw = false;
2158 if (rowSize * this._FBU.height < 12) {
2159 raw = true;
2160 cl_header = 0;
2161 cl_data = rowSize * this._FBU.height;
2162 //clength = [0, rowSize * this._FBU.height];
2163 } else {
2164 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2165 var cl_offset = rQi + 3 + paletteSize;
2166 cl_header = 1;
2167 cl_data = 0;
2168 cl_data += rQ[cl_offset] & 0x7f;
2169 if (rQ[cl_offset] & 0x80) {
2170 cl_header++;
2171 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2172 if (rQ[cl_offset + 1] & 0x80) {
d1800d09 2173 cl_header++;
6d6f0db0 2174 cl_data += rQ[cl_offset + 2] << 14;
d1800d09 2175 }
e16ad2fd 2176 }
6d6f0db0
SR
2177 // end inline getTightCLength
2178 }
b1dee947 2179
6d6f0db0
SR
2180 this._FBU.bytes += cl_header + cl_data;
2181 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
b1dee947 2182
6d6f0db0
SR
2183 // Shift ctl, filter id, num colors, palette entries, and clength off
2184 this._sock.rQskipBytes(3);
2185 //var palette = this._sock.rQshiftBytes(paletteSize);
2186 this._sock.rQshiftTo(this._paletteBuff, paletteSize);
2187 this._sock.rQskipBytes(cl_header);
b1dee947 2188
6d6f0db0
SR
2189 if (raw) {
2190 data = this._sock.rQshiftBytes(cl_data);
2191 } else {
2192 data = decompress(this._sock.rQshiftBytes(cl_data), rowSize * this._FBU.height);
2193 }
b1dee947 2194
6d6f0db0
SR
2195 // Convert indexed (palette based) image data to RGB
2196 var rgbx;
2197 if (numColors == 2) {
2198 rgbx = indexedToRGBX2Color(data, this._paletteBuff, this._FBU.width, this._FBU.height);
2199 this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
2200 } else {
2201 rgbx = indexedToRGBX(data, this._paletteBuff, this._FBU.width, this._FBU.height);
2202 this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
2203 }
b1dee947 2204
b1dee947 2205
6d6f0db0
SR
2206 return true;
2207 }.bind(this);
2208
2209 var handleCopy = function () {
2210 var raw = false;
26586b9d 2211 var uncompressedSize = this._FBU.width * this._FBU.height * 3;
6d6f0db0
SR
2212 if (uncompressedSize < 12) {
2213 raw = true;
2214 cl_header = 0;
2215 cl_data = uncompressedSize;
2216 } else {
2217 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2218 var cl_offset = rQi + 1;
2219 cl_header = 1;
2220 cl_data = 0;
2221 cl_data += rQ[cl_offset] & 0x7f;
2222 if (rQ[cl_offset] & 0x80) {
2223 cl_header++;
2224 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2225 if (rQ[cl_offset + 1] & 0x80) {
d1800d09 2226 cl_header++;
6d6f0db0 2227 cl_data += rQ[cl_offset + 2] << 14;
d1800d09 2228 }
b1dee947 2229 }
6d6f0db0
SR
2230 // end inline getTightCLength
2231 }
2232 this._FBU.bytes = 1 + cl_header + cl_data;
2233 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
b1dee947 2234
6d6f0db0
SR
2235 // Shift ctl, clength off
2236 this._sock.rQshiftBytes(1 + cl_header);
b1dee947 2237
6d6f0db0
SR
2238 if (raw) {
2239 data = this._sock.rQshiftBytes(cl_data);
2240 } else {
2241 data = decompress(this._sock.rQshiftBytes(cl_data), uncompressedSize);
2242 }
b1dee947 2243
6d6f0db0 2244 this._display.blitRgbImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, data, 0, false);
b1dee947 2245
6d6f0db0
SR
2246 return true;
2247 }.bind(this);
b1dee947 2248
6d6f0db0 2249 var ctl = this._sock.rQpeek8();
b1dee947 2250
6d6f0db0
SR
2251 // Keep tight reset bits
2252 resetStreams = ctl & 0xF;
b1dee947 2253
6d6f0db0
SR
2254 // Figure out filter
2255 ctl = ctl >> 4;
2256 streamId = ctl & 0x3;
b1dee947 2257
6d6f0db0
SR
2258 if (ctl === 0x08) cmode = "fill";
2259 else if (ctl === 0x09) cmode = "jpeg";
2260 else if (ctl === 0x0A) cmode = "png";
2261 else if (ctl & 0x04) cmode = "filter";
2262 else if (ctl < 0x04) cmode = "copy";
2263 else return this._fail("Unexpected server message",
2264 "Illegal tight compression received, " +
2265 "ctl: " + ctl);
b1dee947 2266
6d6f0db0 2267 switch (cmode) {
26586b9d 2268 // fill use depth because TPIXELs drop the padding byte
6d6f0db0 2269 case "fill": // TPIXEL
26586b9d 2270 this._FBU.bytes += 3;
6d6f0db0
SR
2271 break;
2272 case "jpeg": // max clength
2273 this._FBU.bytes += 3;
2274 break;
2275 case "png": // max clength
2276 this._FBU.bytes += 3;
2277 break;
2278 case "filter": // filter id + num colors if palette
2279 this._FBU.bytes += 2;
2280 break;
2281 case "copy":
2282 break;
2283 }
d065cad9 2284
6d6f0db0 2285 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
b1dee947 2286
6d6f0db0
SR
2287 // Determine FBU.bytes
2288 switch (cmode) {
2289 case "fill":
2290 // skip ctl byte
2291 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);
2292 this._sock.rQskipBytes(4);
2293 break;
2294 case "png":
2295 case "jpeg":
2296 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2297 var cl_offset = rQi + 1;
2298 cl_header = 1;
2299 cl_data = 0;
2300 cl_data += rQ[cl_offset] & 0x7f;
2301 if (rQ[cl_offset] & 0x80) {
2302 cl_header++;
2303 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2304 if (rQ[cl_offset + 1] & 0x80) {
d1800d09 2305 cl_header++;
6d6f0db0 2306 cl_data += rQ[cl_offset + 2] << 14;
b1dee947 2307 }
6d6f0db0
SR
2308 }
2309 // end inline getTightCLength
2310 this._FBU.bytes = 1 + cl_header + cl_data; // ctl + clength size + jpeg-data
2311 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
798340b9 2312
6d6f0db0
SR
2313 // We have everything, render it
2314 this._sock.rQskipBytes(1 + cl_header); // shift off clt + compact length
2315 data = this._sock.rQshiftBytes(cl_data);
2316 this._display.imageRect(this._FBU.x, this._FBU.y, "image/" + cmode, data);
2317 break;
2318 case "filter":
2319 var filterId = rQ[rQi + 1];
2320 if (filterId === 1) {
2321 if (!handlePalette()) { return false; }
b0ec6509 2322 } else {
6d6f0db0
SR
2323 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2324 // Filter 2, Gradient is valid but not use if jpeg is enabled
2325 this._fail("Unexpected server message",
2326 "Unsupported tight subencoding received, " +
2327 "filter: " + filterId);
b0ec6509 2328 }
6d6f0db0
SR
2329 break;
2330 case "copy":
2331 if (!handleCopy()) { return false; }
2332 break;
2333 }
b0ec6509 2334
6d6f0db0
SR
2335
2336 this._FBU.bytes = 0;
2337 this._FBU.rects--;
2338
2339 return true;
2340 },
2341
6d6f0db0
SR
2342 last_rect: function () {
2343 this._FBU.rects = 0;
2344 return true;
2345 },
2346
6d6f0db0
SR
2347 ExtendedDesktopSize: function () {
2348 this._FBU.bytes = 1;
2349 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2350
2351 this._supportsSetDesktopSize = true;
832be262
PO
2352 this._setCapability("resize", true);
2353
6d6f0db0
SR
2354 var number_of_screens = this._sock.rQpeek8();
2355
2356 this._FBU.bytes = 4 + (number_of_screens * 16);
2357 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2358
2359 this._sock.rQskipBytes(1); // number-of-screens
2360 this._sock.rQskipBytes(3); // padding
2361
2362 for (var i = 0; i < number_of_screens; i += 1) {
2363 // Save the id and flags of the first screen
2364 if (i === 0) {
2365 this._screen_id = this._sock.rQshiftBytes(4); // id
2366 this._sock.rQskipBytes(2); // x-position
2367 this._sock.rQskipBytes(2); // y-position
2368 this._sock.rQskipBytes(2); // width
2369 this._sock.rQskipBytes(2); // height
2370 this._screen_flags = this._sock.rQshiftBytes(4); // flags
2371 } else {
2372 this._sock.rQskipBytes(16);
798340b9 2373 }
6d6f0db0 2374 }
b0ec6509 2375
6d6f0db0
SR
2376 /*
2377 * The x-position indicates the reason for the change:
2378 *
2379 * 0 - server resized on its own
2380 * 1 - this client requested the resize
2381 * 2 - another client requested the resize
2382 */
b0ec6509 2383
6d6f0db0
SR
2384 // We need to handle errors when we requested the resize.
2385 if (this._FBU.x === 1 && this._FBU.y !== 0) {
2386 var msg = "";
2387 // The y-position indicates the status code from the server
2388 switch (this._FBU.y) {
2389 case 1:
2390 msg = "Resize is administratively prohibited";
2391 break;
2392 case 2:
2393 msg = "Out of resources";
2394 break;
2395 case 3:
2396 msg = "Invalid screen layout";
2397 break;
2398 default:
2399 msg = "Unknown reason";
2400 break;
2401 }
2402 this._notification("Server did not accept the resize request: "
2403 + msg, 'normal');
910fd3af
PO
2404 } else {
2405 this._resize(this._FBU.width, this._FBU.height);
6d6f0db0 2406 }
b1dee947 2407
91d5c625
PO
2408 this._FBU.bytes = 0;
2409 this._FBU.rects -= 1;
6d6f0db0
SR
2410 return true;
2411 },
b1dee947 2412
6d6f0db0 2413 DesktopSize: function () {
91d5c625
PO
2414 this._resize(this._FBU.width, this._FBU.height);
2415 this._FBU.bytes = 0;
2416 this._FBU.rects -= 1;
6d6f0db0
SR
2417 return true;
2418 },
8db09746 2419
6d6f0db0
SR
2420 Cursor: function () {
2421 Log.Debug(">> set_cursor");
2422 var x = this._FBU.x; // hotspot-x
2423 var y = this._FBU.y; // hotspot-y
2424 var w = this._FBU.width;
2425 var h = this._FBU.height;
8db09746 2426
26586b9d 2427 var pixelslength = w * h * 4;
6d6f0db0 2428 var masklength = Math.floor((w + 7) / 8) * h;
a7a89626 2429
6d6f0db0
SR
2430 this._FBU.bytes = pixelslength + masklength;
2431 if (this._sock.rQwait("cursor encoding", this._FBU.bytes)) { return false; }
b1dee947 2432
6d6f0db0
SR
2433 this._display.changeCursor(this._sock.rQshiftBytes(pixelslength),
2434 this._sock.rQshiftBytes(masklength),
2435 x, y, w, h);
b1dee947 2436
6d6f0db0
SR
2437 this._FBU.bytes = 0;
2438 this._FBU.rects--;
8f06673a 2439
6d6f0db0
SR
2440 Log.Debug("<< set_cursor");
2441 return true;
2442 },
25e4928f 2443
6d6f0db0
SR
2444 QEMUExtendedKeyEvent: function () {
2445 this._FBU.rects--;
25e4928f 2446
2bf4cf5a
PO
2447 // Old Safari doesn't support creating keyboard events
2448 try {
2449 var keyboardEvent = document.createEvent("keyboardEvent");
2450 if (keyboardEvent.code !== undefined) {
2451 this._qemuExtKeyEventSupported = true;
2452 }
2453 } catch (err) {
058be785 2454 }
6d6f0db0 2455 },
6d6f0db0 2456};