]> git.proxmox.com Git - mirror_novnc.git/blame - core/rfb.js
Build encoding stats array dynamically
[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";
f8ec2df2 25import { encodings, encodingName } from "./encodings.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 = {};
ae510306
SR
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]];
ae510306
SR
186 }
187
188 // NB: nothing that needs explicit teardown should be done
189 // before this point, since this can throw an exception
190 try {
d9ca5e5b
PO
191 this._display = new Display({target: this._target,
192 onFlush: this._onFlush.bind(this)});
ae510306 193 } catch (exc) {
6d6f0db0 194 Log.Error("Display exception: " + exc);
ae510306
SR
195 throw exc;
196 }
197
198 this._keyboard = new Keyboard({target: this._focusContainer,
d0703d1b 199 onKeyEvent: this._handleKeyEvent.bind(this)});
ae510306
SR
200
201 this._mouse = new Mouse({target: this._target,
202 onMouseButton: this._handleMouseButton.bind(this),
9e6f71cb 203 onMouseMove: this._handleMouseMove.bind(this)});
ae510306
SR
204
205 this._sock = new Websock();
206 this._sock.on('message', this._handle_message.bind(this));
207 this._sock.on('open', function () {
c2a4d3ef 208 if ((this._rfb_connection_state === 'connecting') &&
c00ee156
SM
209 (this._rfb_init_state === '')) {
210 this._rfb_init_state = 'ProtocolVersion';
6d6f0db0 211 Log.Debug("Starting VNC handshake");
ae510306 212 } else {
67cd2072 213 this._fail("Unexpected server connection");
ae510306
SR
214 }
215 }.bind(this));
216 this._sock.on('close', function (e) {
6d6f0db0 217 Log.Warn("WebSocket on-close event");
ae510306
SR
218 var msg = "";
219 if (e.code) {
220 msg = " (code: " + e.code;
221 if (e.reason) {
222 msg += ", reason: " + e.reason;
b1dee947 223 }
ae510306
SR
224 msg += ")";
225 }
c00ee156 226 switch (this._rfb_connection_state) {
c2a4d3ef 227 case 'disconnecting':
3bb12056 228 this._updateConnectionState('disconnected');
c00ee156 229 break;
c2a4d3ef 230 case 'connecting':
67cd2072 231 this._fail('Failed to connect to server', msg);
c00ee156 232 break;
b45905ab
SM
233 case 'connected':
234 // Handle disconnects that were initiated server-side
235 this._updateConnectionState('disconnecting');
236 this._updateConnectionState('disconnected');
237 break;
c00ee156 238 case 'disconnected':
67cd2072
SM
239 this._fail("Unexpected server disconnect",
240 "Already disconnected: " + msg);
c00ee156
SM
241 break;
242 default:
67cd2072
SM
243 this._fail("Unexpected server disconnect",
244 "Not in any state yet: " + msg);
c00ee156 245 break;
a679a97d 246 }
ae510306
SR
247 this._sock.off('close');
248 }.bind(this));
249 this._sock.on('error', function (e) {
6d6f0db0 250 Log.Warn("WebSocket on-error event");
ae510306 251 });
8db09746 252
ae510306 253 this._init_vars();
6c145147 254 this._cleanup();
ae510306
SR
255
256 var rmode = this._display.get_render_mode();
6d6f0db0 257 Log.Info("Using native WebSockets, render mode: " + rmode);
ae510306 258
6d6f0db0 259 Log.Debug("<< RFB.constructor");
ae510306 260};
a7a89626 261
6d6f0db0
SR
262RFB.prototype = {
263 // Public methods
264 connect: function (host, port, password, path) {
265 this._rfb_host = host;
266 this._rfb_port = port;
267 this._rfb_password = (password !== undefined) ? password : "";
268 this._rfb_path = (path !== undefined) ? path : "";
269
270 if (!this._rfb_host || !this._rfb_port) {
271 return this._fail(
272 _("Must set host and port"));
273 }
a7a89626 274
6d6f0db0
SR
275 this._rfb_init_state = '';
276 this._updateConnectionState('connecting');
277 return true;
278 },
279
280 disconnect: function () {
281 this._updateConnectionState('disconnecting');
282 this._sock.off('error');
283 this._sock.off('message');
284 this._sock.off('open');
285 },
286
287 sendPassword: function (passwd) {
288 this._rfb_password = passwd;
289 setTimeout(this._init_msg.bind(this), 0);
290 },
291
292 sendCtrlAltDel: function () {
293 if (this._rfb_connection_state !== 'connected' || this._view_only) { return false; }
294 Log.Info("Sending Ctrl-Alt-Del");
295
94f5cf05
PO
296 this.sendKey(KeyTable.XK_Control_L, "ControlLeft", true);
297 this.sendKey(KeyTable.XK_Alt_L, "AltLeft", true);
298 this.sendKey(KeyTable.XK_Delete, "Delete", true);
299 this.sendKey(KeyTable.XK_Delete, "Delete", false);
300 this.sendKey(KeyTable.XK_Alt_L, "AltLeft", false);
301 this.sendKey(KeyTable.XK_Control_L, "ControlLeft", false);
302
6d6f0db0
SR
303 return true;
304 },
305
306 xvpOp: function (ver, op) {
307 if (this._rfb_xvp_ver < ver) { return false; }
308 Log.Info("Sending XVP operation " + op + " (version " + ver + ")");
309 this._sock.send_string("\xFA\x00" + String.fromCharCode(ver) + String.fromCharCode(op));
310 return true;
311 },
312
313 xvpShutdown: function () {
314 return this.xvpOp(1, 2);
315 },
316
317 xvpReboot: function () {
318 return this.xvpOp(1, 3);
319 },
320
321 xvpReset: function () {
322 return this.xvpOp(1, 4);
323 },
324
325 // Send a key press. If 'down' is not specified then send a down key
326 // followed by an up key.
94f5cf05 327 sendKey: function (keysym, code, down) {
6d6f0db0 328 if (this._rfb_connection_state !== 'connected' || this._view_only) { return false; }
94f5cf05
PO
329
330 if (down === undefined) {
331 this.sendKey(keysym, code, true);
332 this.sendKey(keysym, code, false);
333 return true;
334 }
335
be70fe0a 336 var scancode = XtScancode[code];
94f5cf05 337
be70fe0a 338 if (this._qemuExtKeyEventSupported && scancode) {
459ed008
PO
339 // 0 is NoSymbol
340 keysym = keysym || 0;
341
94f5cf05
PO
342 Log.Info("Sending key (" + (down ? "down" : "up") + "): keysym " + keysym + ", scancode " + scancode);
343
344 RFB.messages.QEMUExtendedKeyEvent(this._sock, keysym, down, scancode);
345 } else {
459ed008
PO
346 if (!keysym) {
347 return false;
348 }
6d6f0db0
SR
349 Log.Info("Sending keysym (" + (down ? "down" : "up") + "): " + keysym);
350 RFB.messages.keyEvent(this._sock, keysym, down ? 1 : 0);
6d6f0db0 351 }
94f5cf05 352
6d6f0db0
SR
353 return true;
354 },
355
356 clipboardPasteFrom: function (text) {
357 if (this._rfb_connection_state !== 'connected' || this._view_only) { return; }
358 RFB.messages.clientCutText(this._sock, text);
359 },
360
361 // Requests a change of remote desktop size. This message is an extension
362 // and may only be sent if we have received an ExtendedDesktopSize message
363 requestDesktopSize: function (width, height) {
364 if (this._rfb_connection_state !== 'connected' ||
365 this._view_only) {
366 return false;
367 }
e3efeb32 368
6d6f0db0
SR
369 if (this._supportsSetDesktopSize) {
370 RFB.messages.setDesktopSize(this._sock, width, height,
371 this._screen_id, this._screen_flags);
372 this._sock.flush();
4e0c36dd 373 return true;
6d6f0db0
SR
374 } else {
375 return false;
376 }
377 },
b1dee947 378
b1dee947 379
6d6f0db0 380 // Private methods
b0ec6509 381
6d6f0db0
SR
382 _connect: function () {
383 Log.Debug(">> RFB.connect");
384 this._init_vars();
b0ec6509 385
6d6f0db0
SR
386 var uri;
387 if (typeof UsingSocketIO !== 'undefined') {
388 uri = 'http';
389 } else {
390 uri = this._encrypt ? 'wss' : 'ws';
391 }
b1dee947 392
6d6f0db0
SR
393 uri += '://' + this._rfb_host + ':' + this._rfb_port + '/' + this._rfb_path;
394 Log.Info("connecting to " + uri);
b1dee947 395
6d6f0db0
SR
396 try {
397 // WebSocket.onopen transitions to the RFB init states
398 this._sock.open(uri, this._wsProtocols);
399 } catch (e) {
400 if (e.name === 'SyntaxError') {
401 this._fail("Invalid host or port value given", e);
b1dee947 402 } else {
6d6f0db0 403 this._fail("Error while connecting", e);
159ad55d 404 }
6d6f0db0 405 }
e3efeb32 406
6d6f0db0
SR
407 Log.Debug("<< RFB.connect");
408 },
409
410 _disconnect: function () {
411 Log.Debug(">> RFB.disconnect");
412 this._cleanup();
413 this._sock.close();
414 this._print_stats();
415 Log.Debug("<< RFB.disconnect");
416 },
417
418 _init_vars: function () {
419 // reset state
420 this._FBU.rects = 0;
421 this._FBU.subrects = 0; // RRE and HEXTILE
422 this._FBU.lines = 0; // RAW
423 this._FBU.tiles = 0; // HEXTILE
424 this._FBU.zlibs = []; // TIGHT zlib encoders
425 this._mouse_buttonMask = 0;
426 this._mouse_arr = [];
427 this._rfb_tightvnc = false;
428
429 // Clear the per connection encoding stats
c3386227
PO
430 var stats = this._encStats;
431 Object.keys(stats).forEach(function (key) {
432 stats[key][0] = 0;
433 });
a7a89626 434
c3386227 435 var i;
6d6f0db0
SR
436 for (i = 0; i < 4; i++) {
437 this._FBU.zlibs[i] = new Inflator();
438 }
439 },
a7a89626 440
6d6f0db0 441 _print_stats: function () {
c3386227
PO
442 var stats = this._encStats;
443
6d6f0db0 444 Log.Info("Encoding stats for this connection:");
c3386227
PO
445 Object.keys(stats).forEach(function (key) {
446 var s = stats[key];
6d6f0db0 447 if (s[0] + s[1] > 0) {
c3386227 448 Log.Info(" " + encodingName(key) + ": " + s[0] + " rects");
b1dee947 449 }
c3386227 450 });
a7a89626 451
6d6f0db0 452 Log.Info("Encoding stats since page load:");
c3386227
PO
453 Object.keys(stats).forEach(function (key) {
454 var s = stats[key];
455 Log.Info(" " + encodingName(key) + ": " + s[1] + " rects");
456 });
6d6f0db0
SR
457 },
458
459 _cleanup: function () {
460 if (!this._view_only) { this._keyboard.ungrab(); }
461 if (!this._view_only) { this._mouse.ungrab(); }
462 this._display.defaultCursor();
463 if (Log.get_logging() !== 'debug') {
464 // Show noVNC logo on load and when disconnected, unless in
465 // debug mode
466 this._display.clear();
467 }
468 },
469
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 */
91d5c625
PO
1023 var width = this._sock.rQshift16();
1024 var height = this._sock.rQshift16();
6d6f0db0
SR
1025
1026 /* PIXEL_FORMAT */
1027 var bpp = this._sock.rQshift8();
1028 var depth = this._sock.rQshift8();
1029 var big_endian = this._sock.rQshift8();
1030 var true_color = this._sock.rQshift8();
1031
1032 var red_max = this._sock.rQshift16();
1033 var green_max = this._sock.rQshift16();
1034 var blue_max = this._sock.rQshift16();
1035 var red_shift = this._sock.rQshift8();
1036 var green_shift = this._sock.rQshift8();
1037 var blue_shift = this._sock.rQshift8();
1038 this._sock.rQskipBytes(3); // padding
1039
1040 // NB(directxman12): we don't want to call any callbacks or print messages until
1041 // *after* we're past the point where we could backtrack
1042
1043 /* Connection name/title */
1044 var name_length = this._sock.rQshift32();
1045 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1046 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1047
1048 if (this._rfb_tightvnc) {
1049 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1050 // In TightVNC mode, ServerInit message is extended
1051 var numServerMessages = this._sock.rQshift16();
1052 var numClientMessages = this._sock.rQshift16();
1053 var numEncodings = this._sock.rQshift16();
1054 this._sock.rQskipBytes(2); // padding
1055
1056 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1057 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1058
1059 // we don't actually do anything with the capability information that TIGHT sends,
1060 // so we just skip the all of this.
1061
1062 // TIGHT server message capabilities
1063 this._sock.rQskipBytes(16 * numServerMessages);
1064
1065 // TIGHT client message capabilities
1066 this._sock.rQskipBytes(16 * numClientMessages);
1067
1068 // TIGHT encoding capabilities
1069 this._sock.rQskipBytes(16 * numEncodings);
1070 }
d86cc2d9 1071
6d6f0db0
SR
1072 // NB(directxman12): these are down here so that we don't run them multiple times
1073 // if we backtrack
91d5c625 1074 Log.Info("Screen: " + width + "x" + height +
6d6f0db0
SR
1075 ", bpp: " + bpp + ", depth: " + depth +
1076 ", big_endian: " + big_endian +
1077 ", true_color: " + true_color +
1078 ", red_max: " + red_max +
1079 ", green_max: " + green_max +
1080 ", blue_max: " + blue_max +
1081 ", red_shift: " + red_shift +
1082 ", green_shift: " + green_shift +
1083 ", blue_shift: " + blue_shift);
1084
1085 if (big_endian !== 0) {
1086 Log.Warn("Server native endian is not little endian");
1087 }
b1dee947 1088
6d6f0db0
SR
1089 if (red_shift !== 16) {
1090 Log.Warn("Server native red-shift is not 16");
1091 }
b1dee947 1092
6d6f0db0
SR
1093 if (blue_shift !== 0) {
1094 Log.Warn("Server native blue-shift is not 0");
1095 }
b1dee947 1096
6d6f0db0
SR
1097 // we're past the point where we could backtrack, so it's safe to call this
1098 this._onDesktopName(this, this._fb_name);
b1dee947 1099
91d5c625 1100 this._resize(width, height);
b1dee947 1101
6d6f0db0
SR
1102 if (!this._view_only) { this._keyboard.grab(); }
1103 if (!this._view_only) { this._mouse.grab(); }
b1dee947 1104
26586b9d
PO
1105 RFB.messages.pixelFormat(this._sock, 4, 3, true);
1106 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor);
6d6f0db0
SR
1107 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1108
1109 this._timing.fbu_rt_start = (new Date()).getTime();
1110 this._timing.pixels = 0;
1111
1112 this._updateConnectionState('connected');
1113 return true;
1114 },
1115
1116 /* RFB protocol initialization states:
1117 * ProtocolVersion
1118 * Security
1119 * Authentication
1120 * SecurityResult
1121 * ClientInitialization - not triggered by server message
1122 * ServerInitialization
1123 */
1124 _init_msg: function () {
1125 switch (this._rfb_init_state) {
1126 case 'ProtocolVersion':
1127 return this._negotiate_protocol_version();
1128
1129 case 'Security':
1130 return this._negotiate_security();
1131
1132 case 'Authentication':
1133 return this._negotiate_authentication();
1134
1135 case 'SecurityResult':
1136 return this._handle_security_result();
1137
1138 case 'ClientInitialisation':
1139 this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation
1140 this._rfb_init_state = 'ServerInitialisation';
1141 return true;
b1dee947 1142
6d6f0db0
SR
1143 case 'ServerInitialisation':
1144 return this._negotiate_server_init();
b1dee947 1145
6d6f0db0
SR
1146 default:
1147 return this._fail("Internal error", "Unknown init state: " +
1148 this._rfb_init_state);
1149 }
1150 },
b1dee947 1151
6d6f0db0
SR
1152 _handle_set_colour_map_msg: function () {
1153 Log.Debug("SetColorMapEntries");
b1dee947 1154
26586b9d 1155 return this._fail("Protocol error", "Unexpected SetColorMapEntries message");
6d6f0db0 1156 },
b1dee947 1157
6d6f0db0
SR
1158 _handle_server_cut_text: function () {
1159 Log.Debug("ServerCutText");
b1dee947 1160
6d6f0db0
SR
1161 if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; }
1162 this._sock.rQskipBytes(3); // Padding
1163 var length = this._sock.rQshift32();
1164 if (this._sock.rQwait("ServerCutText", length, 8)) { return false; }
b1dee947 1165
6d6f0db0 1166 var text = this._sock.rQshiftStr(length);
b4ff032e
SR
1167
1168 if (this._view_only) { return true; }
1169
6d6f0db0 1170 this._onClipboard(this, text);
b1dee947 1171
6d6f0db0
SR
1172 return true;
1173 },
b1dee947 1174
6d6f0db0
SR
1175 _handle_server_fence_msg: function() {
1176 if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; }
1177 this._sock.rQskipBytes(3); // Padding
1178 var flags = this._sock.rQshift32();
1179 var length = this._sock.rQshift8();
b1dee947 1180
6d6f0db0 1181 if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; }
b1dee947 1182
6d6f0db0
SR
1183 if (length > 64) {
1184 Log.Warn("Bad payload length (" + length + ") in fence response");
1185 length = 64;
1186 }
4e0c36dd 1187
6d6f0db0 1188 var payload = this._sock.rQshiftStr(length);
b1dee947 1189
6d6f0db0 1190 this._supportsFence = true;
b1dee947 1191
6d6f0db0
SR
1192 /*
1193 * Fence flags
1194 *
1195 * (1<<0) - BlockBefore
1196 * (1<<1) - BlockAfter
1197 * (1<<2) - SyncNext
1198 * (1<<31) - Request
1199 */
b1dee947 1200
6d6f0db0
SR
1201 if (!(flags & (1<<31))) {
1202 return this._fail("Internal error",
1203 "Unexpected fence response");
1204 }
b1dee947 1205
6d6f0db0
SR
1206 // Filter out unsupported flags
1207 // FIXME: support syncNext
1208 flags &= (1<<0) | (1<<1);
b1dee947 1209
6d6f0db0
SR
1210 // BlockBefore and BlockAfter are automatically handled by
1211 // the fact that we process each incoming message
1212 // synchronuosly.
1213 RFB.messages.clientFence(this._sock, flags, payload);
f78a652e 1214
6d6f0db0
SR
1215 return true;
1216 },
b1dee947 1217
6d6f0db0
SR
1218 _handle_xvp_msg: function () {
1219 if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; }
1220 this._sock.rQskip8(); // Padding
1221 var xvp_ver = this._sock.rQshift8();
1222 var xvp_msg = this._sock.rQshift8();
b1dee947 1223
6d6f0db0
SR
1224 switch (xvp_msg) {
1225 case 0: // XVP_FAIL
1226 Log.Error("Operation Failed");
1227 this._notification("XVP Operation Failed", 'error');
1228 break;
1229 case 1: // XVP_INIT
1230 this._rfb_xvp_ver = xvp_ver;
1231 Log.Info("XVP extensions enabled (version " + this._rfb_xvp_ver + ")");
1232 this._onXvpInit(this._rfb_xvp_ver);
1233 break;
1234 default:
1235 this._fail("Unexpected server message",
1236 "Illegal server XVP message " + xvp_msg);
1237 break;
1238 }
b1dee947 1239
6d6f0db0
SR
1240 return true;
1241 },
3df13262 1242
6d6f0db0
SR
1243 _normal_msg: function () {
1244 var msg_type;
76a86ff5 1245
6d6f0db0
SR
1246 if (this._FBU.rects > 0) {
1247 msg_type = 0;
1248 } else {
1249 msg_type = this._sock.rQshift8();
1250 }
76a86ff5 1251
6d6f0db0
SR
1252 switch (msg_type) {
1253 case 0: // FramebufferUpdate
1254 var ret = this._framebufferUpdate();
1255 if (ret && !this._enabledContinuousUpdates) {
1256 RFB.messages.fbUpdateRequest(this._sock, true, 0, 0,
1257 this._fb_width, this._fb_height);
1258 }
1259 return ret;
3df13262 1260
6d6f0db0
SR
1261 case 1: // SetColorMapEntries
1262 return this._handle_set_colour_map_msg();
1263
1264 case 2: // Bell
1265 Log.Debug("Bell");
1266 this._onBell(this);
1267 return true;
1268
1269 case 3: // ServerCutText
1270 return this._handle_server_cut_text();
1271
1272 case 150: // EndOfContinuousUpdates
1273 var first = !(this._supportsContinuousUpdates);
1274 this._supportsContinuousUpdates = true;
1275 this._enabledContinuousUpdates = false;
1276 if (first) {
1277 this._enabledContinuousUpdates = true;
1278 this._updateContinuousUpdates();
1279 Log.Info("Enabling continuous updates.");
1280 } else {
1281 // FIXME: We need to send a framebufferupdaterequest here
1282 // if we add support for turning off continuous updates
1283 }
1284 return true;
3df13262 1285
6d6f0db0
SR
1286 case 248: // ServerFence
1287 return this._handle_server_fence_msg();
3df13262 1288
6d6f0db0
SR
1289 case 250: // XVP
1290 return this._handle_xvp_msg();
3df13262 1291
6d6f0db0
SR
1292 default:
1293 this._fail("Unexpected server message", "Type:" + msg_type);
1294 Log.Debug("sock.rQslice(0, 30): " + this._sock.rQslice(0, 30));
1295 return true;
1296 }
1297 },
3df13262 1298
6d6f0db0
SR
1299 _onFlush: function() {
1300 this._flushing = false;
1301 // Resume processing
1302 if (this._sock.rQlen() > 0) {
1303 this._handle_message();
1304 }
1305 },
3df13262 1306
6d6f0db0
SR
1307 _framebufferUpdate: function () {
1308 var ret = true;
1309 var now;
3df13262 1310
6d6f0db0
SR
1311 if (this._FBU.rects === 0) {
1312 if (this._sock.rQwait("FBU header", 3, 1)) { return false; }
b1dee947 1313 this._sock.rQskip8(); // Padding
6d6f0db0
SR
1314 this._FBU.rects = this._sock.rQshift16();
1315 this._FBU.bytes = 0;
1316 this._timing.cur_fbu = 0;
1317 if (this._timing.fbu_rt_start > 0) {
1318 now = (new Date()).getTime();
1319 Log.Info("First FBU latency: " + (now - this._timing.fbu_rt_start));
b1dee947
SR
1320 }
1321
6d6f0db0
SR
1322 // Make sure the previous frame is fully rendered first
1323 // to avoid building up an excessive queue
1324 if (this._display.pending()) {
1325 this._flushing = true;
1326 this._display.flush();
1327 return false;
1328 }
1329 }
b1dee947 1330
6d6f0db0
SR
1331 while (this._FBU.rects > 0) {
1332 if (this._rfb_connection_state !== 'connected') { return false; }
b1dee947 1333
6d6f0db0
SR
1334 if (this._sock.rQwait("FBU", this._FBU.bytes)) { return false; }
1335 if (this._FBU.bytes === 0) {
1336 if (this._sock.rQwait("rect header", 12)) { return false; }
1337 /* New FramebufferUpdate */
b1dee947 1338
6d6f0db0
SR
1339 var hdr = this._sock.rQshiftBytes(12);
1340 this._FBU.x = (hdr[0] << 8) + hdr[1];
1341 this._FBU.y = (hdr[2] << 8) + hdr[3];
1342 this._FBU.width = (hdr[4] << 8) + hdr[5];
1343 this._FBU.height = (hdr[6] << 8) + hdr[7];
1344 this._FBU.encoding = parseInt((hdr[8] << 24) + (hdr[9] << 16) +
1345 (hdr[10] << 8) + hdr[11], 10);
b1dee947 1346
6d6f0db0
SR
1347 this._onFBUReceive(this,
1348 {'x': this._FBU.x, 'y': this._FBU.y,
1349 'width': this._FBU.width, 'height': this._FBU.height,
1350 'encoding': this._FBU.encoding,
f8ec2df2
PO
1351 'encodingName': encodingName(this._FBU.encoding)});
1352 }
b1dee947 1353
6d6f0db0
SR
1354 if (!this._encNames[this._FBU.encoding]) {
1355 this._fail("Unexpected server message",
1356 "Unsupported encoding " +
1357 this._FBU.encoding);
1358 return false;
1359 }
1360 }
b1dee947 1361
6d6f0db0 1362 this._timing.last_fbu = (new Date()).getTime();
76a86ff5 1363
6d6f0db0 1364 ret = this._encHandlers[this._FBU.encoding]();
3df13262 1365
6d6f0db0
SR
1366 now = (new Date()).getTime();
1367 this._timing.cur_fbu += (now - this._timing.last_fbu);
b1dee947 1368
6d6f0db0 1369 if (ret) {
c3386227
PO
1370 if (!(this._FBU.encoding in this._encStats)) {
1371 this._encStats[this._FBU.encoding] = [0, 0];
1372 }
6d6f0db0
SR
1373 this._encStats[this._FBU.encoding][0]++;
1374 this._encStats[this._FBU.encoding][1]++;
1375 this._timing.pixels += this._FBU.width * this._FBU.height;
b1dee947 1376 }
b1dee947 1377
6d6f0db0
SR
1378 if (this._timing.pixels >= (this._fb_width * this._fb_height)) {
1379 if ((this._FBU.width === this._fb_width && this._FBU.height === this._fb_height) ||
1380 this._timing.fbu_rt_start > 0) {
1381 this._timing.full_fbu_total += this._timing.cur_fbu;
1382 this._timing.full_fbu_cnt++;
1383 Log.Info("Timing of full FBU, curr: " +
1384 this._timing.cur_fbu + ", total: " +
1385 this._timing.full_fbu_total + ", cnt: " +
1386 this._timing.full_fbu_cnt + ", avg: " +
1387 (this._timing.full_fbu_total / this._timing.full_fbu_cnt));
b1dee947 1388 }
d9ca5e5b 1389
6d6f0db0
SR
1390 if (this._timing.fbu_rt_start > 0) {
1391 var fbu_rt_diff = now - this._timing.fbu_rt_start;
1392 this._timing.fbu_rt_total += fbu_rt_diff;
1393 this._timing.fbu_rt_cnt++;
1394 Log.Info("full FBU round-trip, cur: " +
1395 fbu_rt_diff + ", total: " +
1396 this._timing.fbu_rt_total + ", cnt: " +
1397 this._timing.fbu_rt_cnt + ", avg: " +
1398 (this._timing.fbu_rt_total / this._timing.fbu_rt_cnt));
1399 this._timing.fbu_rt_start = 0;
d9ca5e5b 1400 }
b1dee947
SR
1401 }
1402
6d6f0db0
SR
1403 if (!ret) { return ret; } // need more data
1404 }
b1dee947 1405
6d6f0db0 1406 this._display.flip();
b1dee947 1407
6d6f0db0
SR
1408 this._onFBUComplete(this,
1409 {'x': this._FBU.x, 'y': this._FBU.y,
1410 'width': this._FBU.width, 'height': this._FBU.height,
1411 'encoding': this._FBU.encoding,
f8ec2df2 1412 'encodingName': encodingName(this._FBU.encoding)});
b1dee947 1413
6d6f0db0
SR
1414 return true; // We finished this FBU
1415 },
b1dee947 1416
6d6f0db0
SR
1417 _updateContinuousUpdates: function() {
1418 if (!this._enabledContinuousUpdates) { return; }
b1dee947 1419
6d6f0db0
SR
1420 RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0,
1421 this._fb_width, this._fb_height);
91d5c625
PO
1422 },
1423
1424 _resize: function(width, height) {
1425 this._fb_width = width;
1426 this._fb_height = height;
1427
1428 this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
1429
1430 this._display.resize(this._fb_width, this._fb_height);
1431 this._onFBResize(this, this._fb_width, this._fb_height);
1432
1433 this._timing.fbu_rt_start = (new Date()).getTime();
1434 this._updateContinuousUpdates();
6d6f0db0
SR
1435 }
1436};
8db09746 1437
6d6f0db0
SR
1438make_properties(RFB, [
1439 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1440 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1441 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
6d6f0db0
SR
1442 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1443 ['shared', 'rw', 'bool'], // Request shared mode
1444 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1445 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1446 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1447 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1448 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1449 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1450
1451 // Callback functions
1452 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1453 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1454 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1455 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1456 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1457 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1458 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1459 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1460 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1461 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1462 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1463]);
1464
1465RFB.prototype.set_local_cursor = function (cursor) {
1466 if (!cursor || (cursor in {'0': 1, 'no': 1, 'false': 1})) {
1467 this._local_cursor = false;
1468 this._display.disableLocalCursor(); //Only show server-side cursor
1469 } else {
1470 if (this._display.get_cursor_uri()) {
1471 this._local_cursor = true;
1472 } else {
1473 Log.Warn("Browser does not support local cursor");
1474 this._display.disableLocalCursor();
1475 }
1476 }
d86cc2d9 1477
6d6f0db0
SR
1478 // Need to send an updated list of encodings if we are connected
1479 if (this._rfb_connection_state === "connected") {
26586b9d 1480 RFB.messages.clientEncodings(this._sock, this._encodings, cursor);
6d6f0db0
SR
1481 }
1482};
2ba767a7 1483
6d6f0db0
SR
1484RFB.prototype.set_view_only = function (view_only) {
1485 this._view_only = view_only;
8db09746 1486
6d6f0db0
SR
1487 if (this._rfb_connection_state === "connecting" ||
1488 this._rfb_connection_state === "connected") {
1489 if (view_only) {
1490 this._keyboard.ungrab();
1491 this._mouse.ungrab();
1492 } else {
1493 this._keyboard.grab();
1494 this._mouse.grab();
1495 }
1496 }
1497};
76a86ff5 1498
6d6f0db0
SR
1499RFB.prototype.get_display = function () { return this._display; };
1500RFB.prototype.get_keyboard = function () { return this._keyboard; };
1501RFB.prototype.get_mouse = function () { return this._mouse; };
76a86ff5 1502
6d6f0db0
SR
1503// Class Methods
1504RFB.messages = {
1505 keyEvent: function (sock, keysym, down) {
1506 var buff = sock._sQ;
1507 var offset = sock._sQlen;
8db09746 1508
6d6f0db0
SR
1509 buff[offset] = 4; // msg-type
1510 buff[offset + 1] = down;
b1dee947 1511
6d6f0db0
SR
1512 buff[offset + 2] = 0;
1513 buff[offset + 3] = 0;
fb49f91b 1514
6d6f0db0
SR
1515 buff[offset + 4] = (keysym >> 24);
1516 buff[offset + 5] = (keysym >> 16);
1517 buff[offset + 6] = (keysym >> 8);
1518 buff[offset + 7] = keysym;
b1dee947 1519
6d6f0db0
SR
1520 sock._sQlen += 8;
1521 sock.flush();
1522 },
ef1e8bab 1523
6d6f0db0
SR
1524 QEMUExtendedKeyEvent: function (sock, keysym, down, keycode) {
1525 function getRFBkeycode(xt_scancode) {
1526 var upperByte = (keycode >> 8);
1527 var lowerByte = (keycode & 0x00ff);
1528 if (upperByte === 0xe0 && lowerByte < 0x7f) {
1529 lowerByte = lowerByte | 0x80;
1530 return lowerByte;
ef1e8bab 1531 }
6d6f0db0 1532 return xt_scancode;
ef1e8bab 1533 }
b1dee947 1534
6d6f0db0
SR
1535 var buff = sock._sQ;
1536 var offset = sock._sQlen;
8f06673a 1537
6d6f0db0
SR
1538 buff[offset] = 255; // msg-type
1539 buff[offset + 1] = 0; // sub msg-type
8f06673a 1540
6d6f0db0
SR
1541 buff[offset + 2] = (down >> 8);
1542 buff[offset + 3] = down;
8f06673a 1543
6d6f0db0
SR
1544 buff[offset + 4] = (keysym >> 24);
1545 buff[offset + 5] = (keysym >> 16);
1546 buff[offset + 6] = (keysym >> 8);
1547 buff[offset + 7] = keysym;
8f06673a 1548
6d6f0db0 1549 var RFBkeycode = getRFBkeycode(keycode);
8f06673a 1550
6d6f0db0
SR
1551 buff[offset + 8] = (RFBkeycode >> 24);
1552 buff[offset + 9] = (RFBkeycode >> 16);
1553 buff[offset + 10] = (RFBkeycode >> 8);
1554 buff[offset + 11] = RFBkeycode;
8f06673a 1555
6d6f0db0
SR
1556 sock._sQlen += 12;
1557 sock.flush();
1558 },
8f06673a 1559
6d6f0db0
SR
1560 pointerEvent: function (sock, x, y, mask) {
1561 var buff = sock._sQ;
1562 var offset = sock._sQlen;
8f06673a 1563
6d6f0db0 1564 buff[offset] = 5; // msg-type
9ff86fb7 1565
6d6f0db0 1566 buff[offset + 1] = mask;
9ff86fb7 1567
6d6f0db0
SR
1568 buff[offset + 2] = x >> 8;
1569 buff[offset + 3] = x;
9ff86fb7 1570
6d6f0db0
SR
1571 buff[offset + 4] = y >> 8;
1572 buff[offset + 5] = y;
9ff86fb7 1573
6d6f0db0
SR
1574 sock._sQlen += 6;
1575 sock.flush();
1576 },
9ff86fb7 1577
6d6f0db0
SR
1578 // TODO(directxman12): make this unicode compatible?
1579 clientCutText: function (sock, text) {
1580 var buff = sock._sQ;
1581 var offset = sock._sQlen;
b1dee947 1582
6d6f0db0 1583 buff[offset] = 6; // msg-type
9ff86fb7 1584
6d6f0db0
SR
1585 buff[offset + 1] = 0; // padding
1586 buff[offset + 2] = 0; // padding
1587 buff[offset + 3] = 0; // padding
9ff86fb7 1588
6d6f0db0 1589 var n = text.length;
9ff86fb7 1590
6d6f0db0
SR
1591 buff[offset + 4] = n >> 24;
1592 buff[offset + 5] = n >> 16;
1593 buff[offset + 6] = n >> 8;
1594 buff[offset + 7] = n;
9ff86fb7 1595
6d6f0db0
SR
1596 for (var i = 0; i < n; i++) {
1597 buff[offset + 8 + i] = text.charCodeAt(i);
1598 }
9ff86fb7 1599
6d6f0db0
SR
1600 sock._sQlen += 8 + n;
1601 sock.flush();
1602 },
1603
1604 setDesktopSize: function (sock, width, height, id, flags) {
1605 var buff = sock._sQ;
1606 var offset = sock._sQlen;
1607
1608 buff[offset] = 251; // msg-type
1609 buff[offset + 1] = 0; // padding
1610 buff[offset + 2] = width >> 8; // width
1611 buff[offset + 3] = width;
1612 buff[offset + 4] = height >> 8; // height
1613 buff[offset + 5] = height;
1614
1615 buff[offset + 6] = 1; // number-of-screens
1616 buff[offset + 7] = 0; // padding
1617
1618 // screen array
1619 buff[offset + 8] = id >> 24; // id
1620 buff[offset + 9] = id >> 16;
1621 buff[offset + 10] = id >> 8;
1622 buff[offset + 11] = id;
1623 buff[offset + 12] = 0; // x-position
1624 buff[offset + 13] = 0;
1625 buff[offset + 14] = 0; // y-position
1626 buff[offset + 15] = 0;
1627 buff[offset + 16] = width >> 8; // width
1628 buff[offset + 17] = width;
1629 buff[offset + 18] = height >> 8; // height
1630 buff[offset + 19] = height;
1631 buff[offset + 20] = flags >> 24; // flags
1632 buff[offset + 21] = flags >> 16;
1633 buff[offset + 22] = flags >> 8;
1634 buff[offset + 23] = flags;
1635
1636 sock._sQlen += 24;
1637 sock.flush();
1638 },
1639
1640 clientFence: function (sock, flags, payload) {
1641 var buff = sock._sQ;
1642 var offset = sock._sQlen;
1643
1644 buff[offset] = 248; // msg-type
1645
1646 buff[offset + 1] = 0; // padding
1647 buff[offset + 2] = 0; // padding
1648 buff[offset + 3] = 0; // padding
1649
1650 buff[offset + 4] = flags >> 24; // flags
1651 buff[offset + 5] = flags >> 16;
1652 buff[offset + 6] = flags >> 8;
1653 buff[offset + 7] = flags;
1654
1655 var n = payload.length;
1656
1657 buff[offset + 8] = n; // length
1658
1659 for (var i = 0; i < n; i++) {
1660 buff[offset + 9 + i] = payload.charCodeAt(i);
1661 }
a7a89626 1662
6d6f0db0
SR
1663 sock._sQlen += 9 + n;
1664 sock.flush();
1665 },
3df13262 1666
6d6f0db0
SR
1667 enableContinuousUpdates: function (sock, enable, x, y, width, height) {
1668 var buff = sock._sQ;
1669 var offset = sock._sQlen;
3df13262 1670
6d6f0db0
SR
1671 buff[offset] = 150; // msg-type
1672 buff[offset + 1] = enable; // enable-flag
76a86ff5 1673
6d6f0db0
SR
1674 buff[offset + 2] = x >> 8; // x
1675 buff[offset + 3] = x;
1676 buff[offset + 4] = y >> 8; // y
1677 buff[offset + 5] = y;
1678 buff[offset + 6] = width >> 8; // width
1679 buff[offset + 7] = width;
1680 buff[offset + 8] = height >> 8; // height
1681 buff[offset + 9] = height;
76a86ff5 1682
6d6f0db0
SR
1683 sock._sQlen += 10;
1684 sock.flush();
1685 },
76a86ff5 1686
6d6f0db0
SR
1687 pixelFormat: function (sock, bpp, depth, true_color) {
1688 var buff = sock._sQ;
1689 var offset = sock._sQlen;
ae116051 1690
6d6f0db0 1691 buff[offset] = 0; // msg-type
9ff86fb7 1692
6d6f0db0
SR
1693 buff[offset + 1] = 0; // padding
1694 buff[offset + 2] = 0; // padding
1695 buff[offset + 3] = 0; // padding
9ff86fb7 1696
6d6f0db0
SR
1697 buff[offset + 4] = bpp * 8; // bits-per-pixel
1698 buff[offset + 5] = depth * 8; // depth
1699 buff[offset + 6] = 0; // little-endian
1700 buff[offset + 7] = true_color ? 1 : 0; // true-color
9ff86fb7 1701
6d6f0db0
SR
1702 buff[offset + 8] = 0; // red-max
1703 buff[offset + 9] = 255; // red-max
9ff86fb7 1704
6d6f0db0
SR
1705 buff[offset + 10] = 0; // green-max
1706 buff[offset + 11] = 255; // green-max
9ff86fb7 1707
6d6f0db0
SR
1708 buff[offset + 12] = 0; // blue-max
1709 buff[offset + 13] = 255; // blue-max
9ff86fb7 1710
6d6f0db0
SR
1711 buff[offset + 14] = 16; // red-shift
1712 buff[offset + 15] = 8; // green-shift
1713 buff[offset + 16] = 0; // blue-shift
9ff86fb7 1714
6d6f0db0
SR
1715 buff[offset + 17] = 0; // padding
1716 buff[offset + 18] = 0; // padding
1717 buff[offset + 19] = 0; // padding
9ff86fb7 1718
6d6f0db0
SR
1719 sock._sQlen += 20;
1720 sock.flush();
1721 },
9ff86fb7 1722
26586b9d 1723 clientEncodings: function (sock, encodings, local_cursor) {
6d6f0db0
SR
1724 var buff = sock._sQ;
1725 var offset = sock._sQlen;
b1dee947 1726
6d6f0db0
SR
1727 buff[offset] = 2; // msg-type
1728 buff[offset + 1] = 0; // padding
b1dee947 1729
6d6f0db0 1730 // offset + 2 and offset + 3 are encoding count
9ff86fb7 1731
6d6f0db0
SR
1732 var i, j = offset + 4, cnt = 0;
1733 for (i = 0; i < encodings.length; i++) {
1734 if (encodings[i][0] === "Cursor" && !local_cursor) {
1735 Log.Debug("Skipping Cursor pseudo-encoding");
6d6f0db0
SR
1736 } else {
1737 var enc = encodings[i][1];
1738 buff[j] = enc >> 24;
1739 buff[j + 1] = enc >> 16;
1740 buff[j + 2] = enc >> 8;
1741 buff[j + 3] = enc;
9ff86fb7 1742
6d6f0db0
SR
1743 j += 4;
1744 cnt++;
b1dee947 1745 }
6d6f0db0 1746 }
a7a89626 1747
6d6f0db0
SR
1748 buff[offset + 2] = cnt >> 8;
1749 buff[offset + 3] = cnt;
a7a89626 1750
6d6f0db0
SR
1751 sock._sQlen += j - offset;
1752 sock.flush();
1753 },
a679a97d 1754
6d6f0db0
SR
1755 fbUpdateRequest: function (sock, incremental, x, y, w, h) {
1756 var buff = sock._sQ;
1757 var offset = sock._sQlen;
9ff86fb7 1758
6d6f0db0
SR
1759 if (typeof(x) === "undefined") { x = 0; }
1760 if (typeof(y) === "undefined") { y = 0; }
b1dee947 1761
6d6f0db0
SR
1762 buff[offset] = 3; // msg-type
1763 buff[offset + 1] = incremental ? 1 : 0;
9ff86fb7 1764
6d6f0db0
SR
1765 buff[offset + 2] = (x >> 8) & 0xFF;
1766 buff[offset + 3] = x & 0xFF;
9ff86fb7 1767
6d6f0db0
SR
1768 buff[offset + 4] = (y >> 8) & 0xFF;
1769 buff[offset + 5] = y & 0xFF;
9ff86fb7 1770
6d6f0db0
SR
1771 buff[offset + 6] = (w >> 8) & 0xFF;
1772 buff[offset + 7] = w & 0xFF;
9ff86fb7 1773
6d6f0db0
SR
1774 buff[offset + 8] = (h >> 8) & 0xFF;
1775 buff[offset + 9] = h & 0xFF;
b1dee947 1776
6d6f0db0
SR
1777 sock._sQlen += 10;
1778 sock.flush();
1779 }
1780};
b1dee947 1781
6d6f0db0
SR
1782RFB.genDES = function (password, challenge) {
1783 var passwd = [];
1784 for (var i = 0; i < password.length; i++) {
1785 passwd.push(password.charCodeAt(i));
1786 }
1787 return (new DES(passwd)).encrypt(challenge);
1788};
b1dee947 1789
6d6f0db0
SR
1790RFB.encodingHandlers = {
1791 RAW: function () {
1792 if (this._FBU.lines === 0) {
1793 this._FBU.lines = this._FBU.height;
1794 }
a7a89626 1795
26586b9d 1796 this._FBU.bytes = this._FBU.width * 4; // at least a line
6d6f0db0
SR
1797 if (this._sock.rQwait("RAW", this._FBU.bytes)) { return false; }
1798 var cur_y = this._FBU.y + (this._FBU.height - this._FBU.lines);
1799 var curr_height = Math.min(this._FBU.lines,
26586b9d 1800 Math.floor(this._sock.rQlen() / (this._FBU.width * 4)));
6d6f0db0
SR
1801 this._display.blitImage(this._FBU.x, cur_y, this._FBU.width,
1802 curr_height, this._sock.get_rQ(),
1803 this._sock.get_rQi());
26586b9d 1804 this._sock.rQskipBytes(this._FBU.width * curr_height * 4);
6d6f0db0
SR
1805 this._FBU.lines -= curr_height;
1806
1807 if (this._FBU.lines > 0) {
26586b9d 1808 this._FBU.bytes = this._FBU.width * 4; // At least another line
6d6f0db0
SR
1809 } else {
1810 this._FBU.rects--;
1811 this._FBU.bytes = 0;
1812 }
b1dee947 1813
6d6f0db0
SR
1814 return true;
1815 },
1816
1817 COPYRECT: function () {
1818 this._FBU.bytes = 4;
1819 if (this._sock.rQwait("COPYRECT", 4)) { return false; }
1820 this._display.copyImage(this._sock.rQshift16(), this._sock.rQshift16(),
1821 this._FBU.x, this._FBU.y, this._FBU.width,
1822 this._FBU.height);
1823
1824 this._FBU.rects--;
1825 this._FBU.bytes = 0;
1826 return true;
1827 },
1828
1829 RRE: function () {
1830 var color;
1831 if (this._FBU.subrects === 0) {
26586b9d
PO
1832 this._FBU.bytes = 4 + 4;
1833 if (this._sock.rQwait("RRE", 4 + 4)) { return false; }
6d6f0db0 1834 this._FBU.subrects = this._sock.rQshift32();
26586b9d 1835 color = this._sock.rQshiftBytes(4); // Background
6d6f0db0
SR
1836 this._display.fillRect(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, color);
1837 }
b1dee947 1838
26586b9d
PO
1839 while (this._FBU.subrects > 0 && this._sock.rQlen() >= (4 + 8)) {
1840 color = this._sock.rQshiftBytes(4);
6d6f0db0
SR
1841 var x = this._sock.rQshift16();
1842 var y = this._sock.rQshift16();
1843 var width = this._sock.rQshift16();
1844 var height = this._sock.rQshift16();
1845 this._display.fillRect(this._FBU.x + x, this._FBU.y + y, width, height, color);
1846 this._FBU.subrects--;
1847 }
f00193e0 1848
6d6f0db0
SR
1849 if (this._FBU.subrects > 0) {
1850 var chunk = Math.min(this._rre_chunk_sz, this._FBU.subrects);
26586b9d 1851 this._FBU.bytes = (4 + 8) * chunk;
6d6f0db0 1852 } else {
b1dee947
SR
1853 this._FBU.rects--;
1854 this._FBU.bytes = 0;
6d6f0db0 1855 }
b1dee947 1856
6d6f0db0
SR
1857 return true;
1858 },
b1dee947 1859
6d6f0db0
SR
1860 HEXTILE: function () {
1861 var rQ = this._sock.get_rQ();
1862 var rQi = this._sock.get_rQi();
b1dee947 1863
6d6f0db0
SR
1864 if (this._FBU.tiles === 0) {
1865 this._FBU.tiles_x = Math.ceil(this._FBU.width / 16);
1866 this._FBU.tiles_y = Math.ceil(this._FBU.height / 16);
1867 this._FBU.total_tiles = this._FBU.tiles_x * this._FBU.tiles_y;
1868 this._FBU.tiles = this._FBU.total_tiles;
1869 }
b1dee947 1870
6d6f0db0
SR
1871 while (this._FBU.tiles > 0) {
1872 this._FBU.bytes = 1;
1873 if (this._sock.rQwait("HEXTILE subencoding", this._FBU.bytes)) { return false; }
1874 var subencoding = rQ[rQi]; // Peek
1875 if (subencoding > 30) { // Raw
1876 this._fail("Unexpected server message",
1877 "Illegal hextile subencoding: " + subencoding);
1878 return false;
b1dee947
SR
1879 }
1880
6d6f0db0
SR
1881 var subrects = 0;
1882 var curr_tile = this._FBU.total_tiles - this._FBU.tiles;
1883 var tile_x = curr_tile % this._FBU.tiles_x;
1884 var tile_y = Math.floor(curr_tile / this._FBU.tiles_x);
1885 var x = this._FBU.x + tile_x * 16;
1886 var y = this._FBU.y + tile_y * 16;
1887 var w = Math.min(16, (this._FBU.x + this._FBU.width) - x);
1888 var h = Math.min(16, (this._FBU.y + this._FBU.height) - y);
b1dee947 1889
6d6f0db0
SR
1890 // Figure out how much we are expecting
1891 if (subencoding & 0x01) { // Raw
26586b9d 1892 this._FBU.bytes += w * h * 4;
6d6f0db0
SR
1893 } else {
1894 if (subencoding & 0x02) { // Background
26586b9d 1895 this._FBU.bytes += 4;
6d6f0db0
SR
1896 }
1897 if (subencoding & 0x04) { // Foreground
26586b9d 1898 this._FBU.bytes += 4;
6d6f0db0
SR
1899 }
1900 if (subencoding & 0x08) { // AnySubrects
1901 this._FBU.bytes++; // Since we aren't shifting it off
1902 if (this._sock.rQwait("hextile subrects header", this._FBU.bytes)) { return false; }
1903 subrects = rQ[rQi + this._FBU.bytes - 1]; // Peek
1904 if (subencoding & 0x10) { // SubrectsColoured
26586b9d 1905 this._FBU.bytes += subrects * (4 + 2);
6d6f0db0
SR
1906 } else {
1907 this._FBU.bytes += subrects * 2;
b1dee947
SR
1908 }
1909 }
6d6f0db0 1910 }
b1dee947 1911
6d6f0db0 1912 if (this._sock.rQwait("hextile", this._FBU.bytes)) { return false; }
b1dee947 1913
6d6f0db0
SR
1914 // We know the encoding and have a whole tile
1915 this._FBU.subencoding = rQ[rQi];
1916 rQi++;
1917 if (this._FBU.subencoding === 0) {
1918 if (this._FBU.lastsubencoding & 0x01) {
1919 // Weird: ignore blanks are RAW
1920 Log.Debug(" Ignoring blank after RAW");
b1dee947 1921 } else {
6d6f0db0
SR
1922 this._display.fillRect(x, y, w, h, this._FBU.background);
1923 }
1924 } else if (this._FBU.subencoding & 0x01) { // Raw
1925 this._display.blitImage(x, y, w, h, rQ, rQi);
1926 rQi += this._FBU.bytes - 1;
1927 } else {
1928 if (this._FBU.subencoding & 0x02) { // Background
26586b9d
PO
1929 this._FBU.background = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1930 rQi += 4;
6d6f0db0
SR
1931 }
1932 if (this._FBU.subencoding & 0x04) { // Foreground
26586b9d
PO
1933 this._FBU.foreground = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1934 rQi += 4;
6d6f0db0 1935 }
b1dee947 1936
6d6f0db0
SR
1937 this._display.startTile(x, y, w, h, this._FBU.background);
1938 if (this._FBU.subencoding & 0x08) { // AnySubrects
1939 subrects = rQ[rQi];
1940 rQi++;
b1dee947 1941
6d6f0db0
SR
1942 for (var s = 0; s < subrects; s++) {
1943 var color;
1944 if (this._FBU.subencoding & 0x10) { // SubrectsColoured
26586b9d
PO
1945 color = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
1946 rQi += 4;
6d6f0db0
SR
1947 } else {
1948 color = this._FBU.foreground;
1949 }
1950 var xy = rQ[rQi];
1951 rQi++;
1952 var sx = (xy >> 4);
1953 var sy = (xy & 0x0f);
a7a89626 1954
6d6f0db0
SR
1955 var wh = rQ[rQi];
1956 rQi++;
1957 var sw = (wh >> 4) + 1;
1958 var sh = (wh & 0x0f) + 1;
a7a89626 1959
6d6f0db0 1960 this._display.subTile(sx, sy, sw, sh, color);
b1dee947 1961 }
a7a89626 1962 }
6d6f0db0 1963 this._display.finishTile();
a7a89626 1964 }
6d6f0db0
SR
1965 this._sock.set_rQi(rQi);
1966 this._FBU.lastsubencoding = this._FBU.subencoding;
1967 this._FBU.bytes = 0;
1968 this._FBU.tiles--;
1969 }
d065cad9 1970
6d6f0db0
SR
1971 if (this._FBU.tiles === 0) {
1972 this._FBU.rects--;
1973 }
b1dee947 1974
6d6f0db0
SR
1975 return true;
1976 },
b1dee947 1977
3e8b26ab 1978 TIGHT: function () {
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 2210 switch (cmode) {
26586b9d 2211 // fill use depth because TPIXELs drop the padding byte
6d6f0db0 2212 case "fill": // TPIXEL
26586b9d 2213 this._FBU.bytes += 3;
6d6f0db0
SR
2214 break;
2215 case "jpeg": // max clength
2216 this._FBU.bytes += 3;
2217 break;
2218 case "png": // max clength
2219 this._FBU.bytes += 3;
2220 break;
2221 case "filter": // filter id + num colors if palette
2222 this._FBU.bytes += 2;
2223 break;
2224 case "copy":
2225 break;
2226 }
d065cad9 2227
6d6f0db0 2228 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
b1dee947 2229
6d6f0db0
SR
2230 // Determine FBU.bytes
2231 switch (cmode) {
2232 case "fill":
2233 // skip ctl byte
2234 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);
2235 this._sock.rQskipBytes(4);
2236 break;
2237 case "png":
2238 case "jpeg":
2239 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2240 var cl_offset = rQi + 1;
2241 cl_header = 1;
2242 cl_data = 0;
2243 cl_data += rQ[cl_offset] & 0x7f;
2244 if (rQ[cl_offset] & 0x80) {
2245 cl_header++;
2246 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2247 if (rQ[cl_offset + 1] & 0x80) {
d1800d09 2248 cl_header++;
6d6f0db0 2249 cl_data += rQ[cl_offset + 2] << 14;
b1dee947 2250 }
6d6f0db0
SR
2251 }
2252 // end inline getTightCLength
2253 this._FBU.bytes = 1 + cl_header + cl_data; // ctl + clength size + jpeg-data
2254 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
798340b9 2255
6d6f0db0
SR
2256 // We have everything, render it
2257 this._sock.rQskipBytes(1 + cl_header); // shift off clt + compact length
2258 data = this._sock.rQshiftBytes(cl_data);
2259 this._display.imageRect(this._FBU.x, this._FBU.y, "image/" + cmode, data);
2260 break;
2261 case "filter":
2262 var filterId = rQ[rQi + 1];
2263 if (filterId === 1) {
2264 if (!handlePalette()) { return false; }
b0ec6509 2265 } else {
6d6f0db0
SR
2266 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2267 // Filter 2, Gradient is valid but not use if jpeg is enabled
2268 this._fail("Unexpected server message",
2269 "Unsupported tight subencoding received, " +
2270 "filter: " + filterId);
b0ec6509 2271 }
6d6f0db0
SR
2272 break;
2273 case "copy":
2274 if (!handleCopy()) { return false; }
2275 break;
2276 }
b0ec6509 2277
6d6f0db0
SR
2278
2279 this._FBU.bytes = 0;
2280 this._FBU.rects--;
2281
2282 return true;
2283 },
2284
6d6f0db0
SR
2285 last_rect: function () {
2286 this._FBU.rects = 0;
2287 return true;
2288 },
2289
6d6f0db0
SR
2290 ExtendedDesktopSize: function () {
2291 this._FBU.bytes = 1;
2292 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2293
2294 this._supportsSetDesktopSize = true;
2295 var number_of_screens = this._sock.rQpeek8();
2296
2297 this._FBU.bytes = 4 + (number_of_screens * 16);
2298 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2299
2300 this._sock.rQskipBytes(1); // number-of-screens
2301 this._sock.rQskipBytes(3); // padding
2302
2303 for (var i = 0; i < number_of_screens; i += 1) {
2304 // Save the id and flags of the first screen
2305 if (i === 0) {
2306 this._screen_id = this._sock.rQshiftBytes(4); // id
2307 this._sock.rQskipBytes(2); // x-position
2308 this._sock.rQskipBytes(2); // y-position
2309 this._sock.rQskipBytes(2); // width
2310 this._sock.rQskipBytes(2); // height
2311 this._screen_flags = this._sock.rQshiftBytes(4); // flags
2312 } else {
2313 this._sock.rQskipBytes(16);
798340b9 2314 }
6d6f0db0 2315 }
b0ec6509 2316
6d6f0db0
SR
2317 /*
2318 * The x-position indicates the reason for the change:
2319 *
2320 * 0 - server resized on its own
2321 * 1 - this client requested the resize
2322 * 2 - another client requested the resize
2323 */
b0ec6509 2324
6d6f0db0
SR
2325 // We need to handle errors when we requested the resize.
2326 if (this._FBU.x === 1 && this._FBU.y !== 0) {
2327 var msg = "";
2328 // The y-position indicates the status code from the server
2329 switch (this._FBU.y) {
2330 case 1:
2331 msg = "Resize is administratively prohibited";
2332 break;
2333 case 2:
2334 msg = "Out of resources";
2335 break;
2336 case 3:
2337 msg = "Invalid screen layout";
2338 break;
2339 default:
2340 msg = "Unknown reason";
2341 break;
2342 }
2343 this._notification("Server did not accept the resize request: "
2344 + msg, 'normal');
910fd3af
PO
2345 } else {
2346 this._resize(this._FBU.width, this._FBU.height);
6d6f0db0 2347 }
b1dee947 2348
91d5c625
PO
2349 this._FBU.bytes = 0;
2350 this._FBU.rects -= 1;
6d6f0db0
SR
2351 return true;
2352 },
b1dee947 2353
6d6f0db0 2354 DesktopSize: function () {
91d5c625
PO
2355 this._resize(this._FBU.width, this._FBU.height);
2356 this._FBU.bytes = 0;
2357 this._FBU.rects -= 1;
6d6f0db0
SR
2358 return true;
2359 },
8db09746 2360
6d6f0db0
SR
2361 Cursor: function () {
2362 Log.Debug(">> set_cursor");
2363 var x = this._FBU.x; // hotspot-x
2364 var y = this._FBU.y; // hotspot-y
2365 var w = this._FBU.width;
2366 var h = this._FBU.height;
8db09746 2367
26586b9d 2368 var pixelslength = w * h * 4;
6d6f0db0 2369 var masklength = Math.floor((w + 7) / 8) * h;
a7a89626 2370
6d6f0db0
SR
2371 this._FBU.bytes = pixelslength + masklength;
2372 if (this._sock.rQwait("cursor encoding", this._FBU.bytes)) { return false; }
b1dee947 2373
6d6f0db0
SR
2374 this._display.changeCursor(this._sock.rQshiftBytes(pixelslength),
2375 this._sock.rQshiftBytes(masklength),
2376 x, y, w, h);
b1dee947 2377
6d6f0db0
SR
2378 this._FBU.bytes = 0;
2379 this._FBU.rects--;
8f06673a 2380
6d6f0db0
SR
2381 Log.Debug("<< set_cursor");
2382 return true;
2383 },
25e4928f 2384
6d6f0db0
SR
2385 QEMUExtendedKeyEvent: function () {
2386 this._FBU.rects--;
25e4928f 2387
2bf4cf5a
PO
2388 // Old Safari doesn't support creating keyboard events
2389 try {
2390 var keyboardEvent = document.createEvent("keyboardEvent");
2391 if (keyboardEvent.code !== undefined) {
2392 this._qemuExtKeyEventSupported = true;
2393 }
2394 } catch (err) {
058be785 2395 }
6d6f0db0 2396 },
6d6f0db0 2397};