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