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