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