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