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