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