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