]> git.proxmox.com Git - mirror_novnc.git/blame - core/rfb.js
Simplify keyboard event API
[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,
d0703d1b 203 onKeyEvent: this._handleKeyEvent.bind(this)});
ae510306
SR
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
d0703d1b
PO
667 _handleKeyEvent: function (keysym, code, down) {
668 this.sendKey(keysym, code, down);
6d6f0db0 669 },
06a9ef0c 670
6d6f0db0
SR
671 _handleMouseButton: function (x, y, down, bmask) {
672 if (down) {
673 this._mouse_buttonMask |= bmask;
674 } else {
675 this._mouse_buttonMask ^= bmask;
676 }
a7127fee 677
6d6f0db0
SR
678 if (this._viewportDrag) {
679 if (down && !this._viewportDragging) {
680 this._viewportDragging = true;
681 this._viewportDragPos = {'x': x, 'y': y};
a7127fee 682
6d6f0db0 683 // Skip sending mouse events
b1dee947 684 return;
6d6f0db0
SR
685 } else {
686 this._viewportDragging = false;
8db09746 687
6d6f0db0
SR
688 // If the viewport didn't actually move, then treat as a mouse click event
689 // Send the button down event here, as the button up event is sent at the end of this function
690 if (!this._viewportHasMoved && !this._view_only) {
691 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), bmask);
692 }
693 this._viewportHasMoved = false;
b1dee947 694 }
6d6f0db0 695 }
8db09746 696
6d6f0db0 697 if (this._view_only) { return; } // View only, skip mouse events
8f06673a 698
6d6f0db0
SR
699 if (this._rfb_connection_state !== 'connected') { return; }
700 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
701 },
8db09746 702
6d6f0db0
SR
703 _handleMouseMove: function (x, y) {
704 if (this._viewportDragging) {
705 var deltaX = this._viewportDragPos.x - x;
706 var deltaY = this._viewportDragPos.y - y;
8db09746 707
6d6f0db0
SR
708 // The goal is to trigger on a certain physical width, the
709 // devicePixelRatio brings us a bit closer but is not optimal.
710 var dragThreshold = 10 * (window.devicePixelRatio || 1);
8db09746 711
6d6f0db0
SR
712 if (this._viewportHasMoved || (Math.abs(deltaX) > dragThreshold ||
713 Math.abs(deltaY) > dragThreshold)) {
714 this._viewportHasMoved = true;
27e77d46 715
6d6f0db0
SR
716 this._viewportDragPos = {'x': x, 'y': y};
717 this._display.viewportChangePos(deltaX, deltaY);
b50f3406 718 }
8db09746 719
6d6f0db0
SR
720 // Skip sending mouse events
721 return;
722 }
b1dee947 723
6d6f0db0 724 if (this._view_only) { return; } // View only, skip mouse events
b1dee947 725
6d6f0db0
SR
726 if (this._rfb_connection_state !== 'connected') { return; }
727 RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
728 },
b1dee947 729
6d6f0db0 730 // Message Handlers
27e77d46 731
6d6f0db0
SR
732 _negotiate_protocol_version: function () {
733 if (this._sock.rQlen() < 12) {
734 return this._fail("Error while negotiating with server",
735 "Incomplete protocol version");
736 }
32df3fdb 737
6d6f0db0
SR
738 var sversion = this._sock.rQshiftStr(12).substr(4, 7);
739 Log.Info("Server ProtocolVersion: " + sversion);
740 var is_repeater = 0;
741 switch (sversion) {
742 case "000.000": // UltraVNC repeater
743 is_repeater = 1;
744 break;
745 case "003.003":
746 case "003.006": // UltraVNC
747 case "003.889": // Apple Remote Desktop
748 this._rfb_version = 3.3;
749 break;
750 case "003.007":
751 this._rfb_version = 3.7;
752 break;
753 case "003.008":
754 case "004.000": // Intel AMT KVM
755 case "004.001": // RealVNC 4.6
756 case "005.000": // RealVNC 5.3
757 this._rfb_version = 3.8;
758 break;
759 default:
760 return this._fail("Unsupported server",
761 "Invalid server version: " + sversion);
762 }
8db09746 763
6d6f0db0
SR
764 if (is_repeater) {
765 var repeaterID = this._repeaterID;
766 while (repeaterID.length < 250) {
767 repeaterID += "\0";
b1dee947 768 }
6d6f0db0
SR
769 this._sock.send_string(repeaterID);
770 return true;
771 }
b1dee947 772
6d6f0db0
SR
773 if (this._rfb_version > this._rfb_max_version) {
774 this._rfb_version = this._rfb_max_version;
775 }
b1dee947 776
6d6f0db0
SR
777 var cversion = "00" + parseInt(this._rfb_version, 10) +
778 ".00" + ((this._rfb_version * 10) % 10);
779 this._sock.send_string("RFB " + cversion + "\n");
780 Log.Debug('Sent ProtocolVersion: ' + cversion);
b1dee947 781
6d6f0db0
SR
782 this._rfb_init_state = 'Security';
783 },
b1dee947 784
6d6f0db0
SR
785 _negotiate_security: function () {
786 // Polyfill since IE and PhantomJS doesn't have
787 // TypedArray.includes()
788 function includes(item, array) {
789 for (var i = 0; i < array.length; i++) {
790 if (array[i] === item) {
791 return true;
792 }
b1dee947 793 }
6d6f0db0
SR
794 return false;
795 }
b1dee947 796
6d6f0db0
SR
797 if (this._rfb_version >= 3.7) {
798 // Server sends supported list, client decides
799 var num_types = this._sock.rQshift8();
800 if (this._sock.rQwait("security type", num_types, 1)) { return false; }
b1dee947 801
6d6f0db0
SR
802 if (num_types === 0) {
803 var strlen = this._sock.rQshift32();
804 var reason = this._sock.rQshiftStr(strlen);
805 return this._fail("Error while negotiating with server",
806 "Security failure: " + reason);
807 }
808
809 var types = this._sock.rQshiftBytes(num_types);
810 Log.Debug("Server security types: " + types);
811
812 // Look for each auth in preferred order
813 this._rfb_auth_scheme = 0;
814 if (includes(1, types)) {
815 this._rfb_auth_scheme = 1; // None
816 } else if (includes(22, types)) {
817 this._rfb_auth_scheme = 22; // XVP
818 } else if (includes(16, types)) {
819 this._rfb_auth_scheme = 16; // Tight
820 } else if (includes(2, types)) {
821 this._rfb_auth_scheme = 2; // VNC Auth
822 } else {
823 return this._fail("Unsupported server",
824 "Unsupported security types: " + types);
8db09746 825 }
b1dee947 826
6d6f0db0
SR
827 this._sock.send([this._rfb_auth_scheme]);
828 } else {
829 // Server decides
830 if (this._sock.rQwait("security scheme", 4)) { return false; }
831 this._rfb_auth_scheme = this._sock.rQshift32();
832 }
b1dee947 833
6d6f0db0
SR
834 this._rfb_init_state = 'Authentication';
835 Log.Debug('Authenticating using scheme: ' + this._rfb_auth_scheme);
b1dee947 836
6d6f0db0
SR
837 return this._init_msg(); // jump to authentication
838 },
b1dee947 839
6d6f0db0
SR
840 // authentication
841 _negotiate_xvp_auth: function () {
842 var xvp_sep = this._xvp_password_sep;
843 var xvp_auth = this._rfb_password.split(xvp_sep);
844 if (xvp_auth.length < 3) {
845 var msg = 'XVP credentials required (user' + xvp_sep +
846 'target' + xvp_sep + 'password) -- got only ' + this._rfb_password;
847 this._onPasswordRequired(this, msg);
848 return false;
849 }
0ee5ca6e 850
6d6f0db0
SR
851 var xvp_auth_str = String.fromCharCode(xvp_auth[0].length) +
852 String.fromCharCode(xvp_auth[1].length) +
853 xvp_auth[0] +
854 xvp_auth[1];
855 this._sock.send_string(xvp_auth_str);
856 this._rfb_password = xvp_auth.slice(2).join(xvp_sep);
857 this._rfb_auth_scheme = 2;
858 return this._negotiate_authentication();
859 },
860
861 _negotiate_std_vnc_auth: function () {
862 if (this._rfb_password.length === 0) {
863 this._onPasswordRequired(this);
864 return false;
865 }
b1dee947 866
6d6f0db0
SR
867 if (this._sock.rQwait("auth challenge", 16)) { return false; }
868
869 // TODO(directxman12): make genDES not require an Array
870 var challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16));
871 var response = RFB.genDES(this._rfb_password, challenge);
872 this._sock.send(response);
873 this._rfb_init_state = "SecurityResult";
874 return true;
875 },
876
877 _negotiate_tight_tunnels: function (numTunnels) {
878 var clientSupportedTunnelTypes = {
879 0: { vendor: 'TGHT', signature: 'NOTUNNEL' }
880 };
881 var serverSupportedTunnelTypes = {};
882 // receive tunnel capabilities
883 for (var i = 0; i < numTunnels; i++) {
884 var cap_code = this._sock.rQshift32();
885 var cap_vendor = this._sock.rQshiftStr(4);
886 var cap_signature = this._sock.rQshiftStr(8);
887 serverSupportedTunnelTypes[cap_code] = { vendor: cap_vendor, signature: cap_signature };
888 }
889
890 // choose the notunnel type
891 if (serverSupportedTunnelTypes[0]) {
892 if (serverSupportedTunnelTypes[0].vendor != clientSupportedTunnelTypes[0].vendor ||
893 serverSupportedTunnelTypes[0].signature != clientSupportedTunnelTypes[0].signature) {
894 return this._fail("Unsupported server",
895 "Client's tunnel type had the incorrect " +
896 "vendor or signature");
b1dee947 897 }
6d6f0db0
SR
898 this._sock.send([0, 0, 0, 0]); // use NOTUNNEL
899 return false; // wait until we receive the sub auth count to continue
900 } else {
901 return this._fail("Unsupported server",
902 "Server wanted tunnels, but doesn't support " +
903 "the notunnel type");
904 }
905 },
b1dee947 906
6d6f0db0
SR
907 _negotiate_tight_auth: function () {
908 if (!this._rfb_tightvnc) { // first pass, do the tunnel negotiation
909 if (this._sock.rQwait("num tunnels", 4)) { return false; }
910 var numTunnels = this._sock.rQshift32();
911 if (numTunnels > 0 && this._sock.rQwait("tunnel capabilities", 16 * numTunnels, 4)) { return false; }
c00ee156 912
6d6f0db0 913 this._rfb_tightvnc = true;
b1dee947 914
6d6f0db0
SR
915 if (numTunnels > 0) {
916 this._negotiate_tight_tunnels(numTunnels);
917 return false; // wait until we receive the sub auth to continue
b1dee947 918 }
6d6f0db0 919 }
b1dee947 920
6d6f0db0
SR
921 // second pass, do the sub-auth negotiation
922 if (this._sock.rQwait("sub auth count", 4)) { return false; }
923 var subAuthCount = this._sock.rQshift32();
924 if (subAuthCount === 0) { // empty sub-auth list received means 'no auth' subtype selected
925 this._rfb_init_state = 'SecurityResult';
926 return true;
927 }
b1dee947 928
6d6f0db0 929 if (this._sock.rQwait("sub auth capabilities", 16 * subAuthCount, 4)) { return false; }
b1dee947 930
6d6f0db0
SR
931 var clientSupportedTypes = {
932 'STDVNOAUTH__': 1,
933 'STDVVNCAUTH_': 2
934 };
b1dee947 935
6d6f0db0 936 var serverSupportedTypes = [];
95eb681b 937
6d6f0db0
SR
938 for (var i = 0; i < subAuthCount; i++) {
939 var capNum = this._sock.rQshift32();
940 var capabilities = this._sock.rQshiftStr(12);
941 serverSupportedTypes.push(capabilities);
942 }
d86cc2d9 943
6d6f0db0
SR
944 for (var authType in clientSupportedTypes) {
945 if (serverSupportedTypes.indexOf(authType) != -1) {
946 this._sock.send([0, 0, 0, clientSupportedTypes[authType]]);
d86cc2d9 947
6d6f0db0
SR
948 switch (authType) {
949 case 'STDVNOAUTH__': // no auth
950 this._rfb_init_state = 'SecurityResult';
951 return true;
952 case 'STDVVNCAUTH_': // VNC auth
953 this._rfb_auth_scheme = 2;
954 return this._init_msg();
955 default:
956 return this._fail("Unsupported server",
957 "Unsupported tiny auth scheme: " +
958 authType);
b1dee947
SR
959 }
960 }
6d6f0db0 961 }
b1dee947 962
6d6f0db0
SR
963 return this._fail("Unsupported server",
964 "No supported sub-auth types!");
965 },
966
967 _negotiate_authentication: function () {
968 switch (this._rfb_auth_scheme) {
969 case 0: // connection failed
970 if (this._sock.rQwait("auth reason", 4)) { return false; }
971 var strlen = this._sock.rQshift32();
972 var reason = this._sock.rQshiftStr(strlen);
973 return this._fail("Authentication failure", reason);
974
975 case 1: // no auth
976 if (this._rfb_version >= 3.8) {
977 this._rfb_init_state = 'SecurityResult';
978 return true;
979 }
980 this._rfb_init_state = 'ClientInitialisation';
981 return this._init_msg();
95eb681b 982
6d6f0db0
SR
983 case 22: // XVP auth
984 return this._negotiate_xvp_auth();
d86cc2d9 985
6d6f0db0
SR
986 case 2: // VNC authentication
987 return this._negotiate_std_vnc_auth();
d86cc2d9 988
6d6f0db0
SR
989 case 16: // TightVNC Security Type
990 return this._negotiate_tight_auth();
d86cc2d9 991
6d6f0db0
SR
992 default:
993 return this._fail("Unsupported server",
994 "Unsupported auth scheme: " +
995 this._rfb_auth_scheme);
996 }
997 },
998
999 _handle_security_result: function () {
1000 if (this._sock.rQwait('VNC auth response ', 4)) { return false; }
1001 switch (this._sock.rQshift32()) {
1002 case 0: // OK
1003 this._rfb_init_state = 'ClientInitialisation';
1004 Log.Debug('Authentication OK');
1005 return this._init_msg();
1006 case 1: // failed
1007 if (this._rfb_version >= 3.8) {
1008 var length = this._sock.rQshift32();
1009 if (this._sock.rQwait("SecurityResult reason", length, 8)) { return false; }
1010 var reason = this._sock.rQshiftStr(length);
1011 return this._fail("Authentication failure", reason);
1012 } else {
1013 return this._fail("Authentication failure");
d86cc2d9 1014 }
6d6f0db0
SR
1015 return false;
1016 case 2:
1017 return this._fail("Too many authentication attempts");
1018 default:
1019 return this._fail("Unsupported server",
1020 "Unknown SecurityResult");
1021 }
1022 },
1023
1024 _negotiate_server_init: function () {
1025 if (this._sock.rQwait("server initialization", 24)) { return false; }
1026
1027 /* Screen size */
1028 this._fb_width = this._sock.rQshift16();
1029 this._fb_height = this._sock.rQshift16();
1030 this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
1031
1032 /* PIXEL_FORMAT */
1033 var bpp = this._sock.rQshift8();
1034 var depth = this._sock.rQshift8();
1035 var big_endian = this._sock.rQshift8();
1036 var true_color = this._sock.rQshift8();
1037
1038 var red_max = this._sock.rQshift16();
1039 var green_max = this._sock.rQshift16();
1040 var blue_max = this._sock.rQshift16();
1041 var red_shift = this._sock.rQshift8();
1042 var green_shift = this._sock.rQshift8();
1043 var blue_shift = this._sock.rQshift8();
1044 this._sock.rQskipBytes(3); // padding
1045
1046 // NB(directxman12): we don't want to call any callbacks or print messages until
1047 // *after* we're past the point where we could backtrack
1048
1049 /* Connection name/title */
1050 var name_length = this._sock.rQshift32();
1051 if (this._sock.rQwait('server init name', name_length, 24)) { return false; }
1052 this._fb_name = decodeUTF8(this._sock.rQshiftStr(name_length));
1053
1054 if (this._rfb_tightvnc) {
1055 if (this._sock.rQwait('TightVNC extended server init header', 8, 24 + name_length)) { return false; }
1056 // In TightVNC mode, ServerInit message is extended
1057 var numServerMessages = this._sock.rQshift16();
1058 var numClientMessages = this._sock.rQshift16();
1059 var numEncodings = this._sock.rQshift16();
1060 this._sock.rQskipBytes(2); // padding
1061
1062 var totalMessagesLength = (numServerMessages + numClientMessages + numEncodings) * 16;
1063 if (this._sock.rQwait('TightVNC extended server init header', totalMessagesLength, 32 + name_length)) { return false; }
1064
1065 // we don't actually do anything with the capability information that TIGHT sends,
1066 // so we just skip the all of this.
1067
1068 // TIGHT server message capabilities
1069 this._sock.rQskipBytes(16 * numServerMessages);
1070
1071 // TIGHT client message capabilities
1072 this._sock.rQskipBytes(16 * numClientMessages);
1073
1074 // TIGHT encoding capabilities
1075 this._sock.rQskipBytes(16 * numEncodings);
1076 }
d86cc2d9 1077
6d6f0db0
SR
1078 // NB(directxman12): these are down here so that we don't run them multiple times
1079 // if we backtrack
1080 Log.Info("Screen: " + this._fb_width + "x" + this._fb_height +
1081 ", bpp: " + bpp + ", depth: " + depth +
1082 ", big_endian: " + big_endian +
1083 ", true_color: " + true_color +
1084 ", red_max: " + red_max +
1085 ", green_max: " + green_max +
1086 ", blue_max: " + blue_max +
1087 ", red_shift: " + red_shift +
1088 ", green_shift: " + green_shift +
1089 ", blue_shift: " + blue_shift);
1090
1091 if (big_endian !== 0) {
1092 Log.Warn("Server native endian is not little endian");
1093 }
b1dee947 1094
6d6f0db0
SR
1095 if (red_shift !== 16) {
1096 Log.Warn("Server native red-shift is not 16");
1097 }
b1dee947 1098
6d6f0db0
SR
1099 if (blue_shift !== 0) {
1100 Log.Warn("Server native blue-shift is not 0");
1101 }
b1dee947 1102
6d6f0db0
SR
1103 // we're past the point where we could backtrack, so it's safe to call this
1104 this._onDesktopName(this, this._fb_name);
b1dee947 1105
6d6f0db0
SR
1106 if (this._true_color && this._fb_name === "Intel(r) AMT KVM") {
1107 Log.Warn("Intel AMT KVM only supports 8/16 bit depths. Disabling true color");
1108 this._true_color = false;
1109 }
b1dee947 1110
6d6f0db0
SR
1111 this._display.set_true_color(this._true_color);
1112 this._display.resize(this._fb_width, this._fb_height);
1113 this._onFBResize(this, this._fb_width, this._fb_height);
b1dee947 1114
6d6f0db0
SR
1115 if (!this._view_only) { this._keyboard.grab(); }
1116 if (!this._view_only) { this._mouse.grab(); }
b1dee947 1117
6d6f0db0
SR
1118 if (this._true_color) {
1119 this._fb_Bpp = 4;
1120 this._fb_depth = 3;
1121 } else {
1122 this._fb_Bpp = 1;
1123 this._fb_depth = 1;
1124 }
b1dee947 1125
6d6f0db0
SR
1126 RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
1127 RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
1128 RFB.messages.fbUpdateRequest(this._sock, false, 0, 0, this._fb_width, this._fb_height);
1129
1130 this._timing.fbu_rt_start = (new Date()).getTime();
1131 this._timing.pixels = 0;
1132
1133 this._updateConnectionState('connected');
1134 return true;
1135 },
1136
1137 /* RFB protocol initialization states:
1138 * ProtocolVersion
1139 * Security
1140 * Authentication
1141 * SecurityResult
1142 * ClientInitialization - not triggered by server message
1143 * ServerInitialization
1144 */
1145 _init_msg: function () {
1146 switch (this._rfb_init_state) {
1147 case 'ProtocolVersion':
1148 return this._negotiate_protocol_version();
1149
1150 case 'Security':
1151 return this._negotiate_security();
1152
1153 case 'Authentication':
1154 return this._negotiate_authentication();
1155
1156 case 'SecurityResult':
1157 return this._handle_security_result();
1158
1159 case 'ClientInitialisation':
1160 this._sock.send([this._shared ? 1 : 0]); // ClientInitialisation
1161 this._rfb_init_state = 'ServerInitialisation';
1162 return true;
b1dee947 1163
6d6f0db0
SR
1164 case 'ServerInitialisation':
1165 return this._negotiate_server_init();
b1dee947 1166
6d6f0db0
SR
1167 default:
1168 return this._fail("Internal error", "Unknown init state: " +
1169 this._rfb_init_state);
1170 }
1171 },
b1dee947 1172
6d6f0db0
SR
1173 _handle_set_colour_map_msg: function () {
1174 Log.Debug("SetColorMapEntries");
1175 this._sock.rQskip8(); // Padding
81bd2d66 1176
6d6f0db0
SR
1177 var first_colour = this._sock.rQshift16();
1178 var num_colours = this._sock.rQshift16();
1179 if (this._sock.rQwait('SetColorMapEntries', num_colours * 6, 6)) { return false; }
b1dee947 1180
6d6f0db0
SR
1181 for (var c = 0; c < num_colours; c++) {
1182 var red = parseInt(this._sock.rQshift16() / 256, 10);
1183 var green = parseInt(this._sock.rQshift16() / 256, 10);
1184 var blue = parseInt(this._sock.rQshift16() / 256, 10);
1185 this._display.set_colourMap([blue, green, red], first_colour + c);
1186 }
1187 Log.Debug("colourMap: " + this._display.get_colourMap());
1188 Log.Info("Registered " + num_colours + " colourMap entries");
b1dee947 1189
6d6f0db0
SR
1190 return true;
1191 },
b1dee947 1192
6d6f0db0
SR
1193 _handle_server_cut_text: function () {
1194 Log.Debug("ServerCutText");
b1dee947 1195
6d6f0db0
SR
1196 if (this._sock.rQwait("ServerCutText header", 7, 1)) { return false; }
1197 this._sock.rQskipBytes(3); // Padding
1198 var length = this._sock.rQshift32();
1199 if (this._sock.rQwait("ServerCutText", length, 8)) { return false; }
b1dee947 1200
6d6f0db0 1201 var text = this._sock.rQshiftStr(length);
b4ff032e
SR
1202
1203 if (this._view_only) { return true; }
1204
6d6f0db0 1205 this._onClipboard(this, text);
b1dee947 1206
6d6f0db0
SR
1207 return true;
1208 },
b1dee947 1209
6d6f0db0
SR
1210 _handle_server_fence_msg: function() {
1211 if (this._sock.rQwait("ServerFence header", 8, 1)) { return false; }
1212 this._sock.rQskipBytes(3); // Padding
1213 var flags = this._sock.rQshift32();
1214 var length = this._sock.rQshift8();
b1dee947 1215
6d6f0db0 1216 if (this._sock.rQwait("ServerFence payload", length, 9)) { return false; }
b1dee947 1217
6d6f0db0
SR
1218 if (length > 64) {
1219 Log.Warn("Bad payload length (" + length + ") in fence response");
1220 length = 64;
1221 }
4e0c36dd 1222
6d6f0db0 1223 var payload = this._sock.rQshiftStr(length);
b1dee947 1224
6d6f0db0 1225 this._supportsFence = true;
b1dee947 1226
6d6f0db0
SR
1227 /*
1228 * Fence flags
1229 *
1230 * (1<<0) - BlockBefore
1231 * (1<<1) - BlockAfter
1232 * (1<<2) - SyncNext
1233 * (1<<31) - Request
1234 */
b1dee947 1235
6d6f0db0
SR
1236 if (!(flags & (1<<31))) {
1237 return this._fail("Internal error",
1238 "Unexpected fence response");
1239 }
b1dee947 1240
6d6f0db0
SR
1241 // Filter out unsupported flags
1242 // FIXME: support syncNext
1243 flags &= (1<<0) | (1<<1);
b1dee947 1244
6d6f0db0
SR
1245 // BlockBefore and BlockAfter are automatically handled by
1246 // the fact that we process each incoming message
1247 // synchronuosly.
1248 RFB.messages.clientFence(this._sock, flags, payload);
f78a652e 1249
6d6f0db0
SR
1250 return true;
1251 },
b1dee947 1252
6d6f0db0
SR
1253 _handle_xvp_msg: function () {
1254 if (this._sock.rQwait("XVP version and message", 3, 1)) { return false; }
1255 this._sock.rQskip8(); // Padding
1256 var xvp_ver = this._sock.rQshift8();
1257 var xvp_msg = this._sock.rQshift8();
b1dee947 1258
6d6f0db0
SR
1259 switch (xvp_msg) {
1260 case 0: // XVP_FAIL
1261 Log.Error("Operation Failed");
1262 this._notification("XVP Operation Failed", 'error');
1263 break;
1264 case 1: // XVP_INIT
1265 this._rfb_xvp_ver = xvp_ver;
1266 Log.Info("XVP extensions enabled (version " + this._rfb_xvp_ver + ")");
1267 this._onXvpInit(this._rfb_xvp_ver);
1268 break;
1269 default:
1270 this._fail("Unexpected server message",
1271 "Illegal server XVP message " + xvp_msg);
1272 break;
1273 }
b1dee947 1274
6d6f0db0
SR
1275 return true;
1276 },
3df13262 1277
6d6f0db0
SR
1278 _normal_msg: function () {
1279 var msg_type;
76a86ff5 1280
6d6f0db0
SR
1281 if (this._FBU.rects > 0) {
1282 msg_type = 0;
1283 } else {
1284 msg_type = this._sock.rQshift8();
1285 }
76a86ff5 1286
6d6f0db0
SR
1287 switch (msg_type) {
1288 case 0: // FramebufferUpdate
1289 var ret = this._framebufferUpdate();
1290 if (ret && !this._enabledContinuousUpdates) {
1291 RFB.messages.fbUpdateRequest(this._sock, true, 0, 0,
1292 this._fb_width, this._fb_height);
1293 }
1294 return ret;
3df13262 1295
6d6f0db0
SR
1296 case 1: // SetColorMapEntries
1297 return this._handle_set_colour_map_msg();
1298
1299 case 2: // Bell
1300 Log.Debug("Bell");
1301 this._onBell(this);
1302 return true;
1303
1304 case 3: // ServerCutText
1305 return this._handle_server_cut_text();
1306
1307 case 150: // EndOfContinuousUpdates
1308 var first = !(this._supportsContinuousUpdates);
1309 this._supportsContinuousUpdates = true;
1310 this._enabledContinuousUpdates = false;
1311 if (first) {
1312 this._enabledContinuousUpdates = true;
1313 this._updateContinuousUpdates();
1314 Log.Info("Enabling continuous updates.");
1315 } else {
1316 // FIXME: We need to send a framebufferupdaterequest here
1317 // if we add support for turning off continuous updates
1318 }
1319 return true;
3df13262 1320
6d6f0db0
SR
1321 case 248: // ServerFence
1322 return this._handle_server_fence_msg();
3df13262 1323
6d6f0db0
SR
1324 case 250: // XVP
1325 return this._handle_xvp_msg();
3df13262 1326
6d6f0db0
SR
1327 default:
1328 this._fail("Unexpected server message", "Type:" + msg_type);
1329 Log.Debug("sock.rQslice(0, 30): " + this._sock.rQslice(0, 30));
1330 return true;
1331 }
1332 },
3df13262 1333
6d6f0db0
SR
1334 _onFlush: function() {
1335 this._flushing = false;
1336 // Resume processing
1337 if (this._sock.rQlen() > 0) {
1338 this._handle_message();
1339 }
1340 },
3df13262 1341
6d6f0db0
SR
1342 _framebufferUpdate: function () {
1343 var ret = true;
1344 var now;
3df13262 1345
6d6f0db0
SR
1346 if (this._FBU.rects === 0) {
1347 if (this._sock.rQwait("FBU header", 3, 1)) { return false; }
b1dee947 1348 this._sock.rQskip8(); // Padding
6d6f0db0
SR
1349 this._FBU.rects = this._sock.rQshift16();
1350 this._FBU.bytes = 0;
1351 this._timing.cur_fbu = 0;
1352 if (this._timing.fbu_rt_start > 0) {
1353 now = (new Date()).getTime();
1354 Log.Info("First FBU latency: " + (now - this._timing.fbu_rt_start));
b1dee947
SR
1355 }
1356
6d6f0db0
SR
1357 // Make sure the previous frame is fully rendered first
1358 // to avoid building up an excessive queue
1359 if (this._display.pending()) {
1360 this._flushing = true;
1361 this._display.flush();
1362 return false;
1363 }
1364 }
b1dee947 1365
6d6f0db0
SR
1366 while (this._FBU.rects > 0) {
1367 if (this._rfb_connection_state !== 'connected') { return false; }
b1dee947 1368
6d6f0db0
SR
1369 if (this._sock.rQwait("FBU", this._FBU.bytes)) { return false; }
1370 if (this._FBU.bytes === 0) {
1371 if (this._sock.rQwait("rect header", 12)) { return false; }
1372 /* New FramebufferUpdate */
b1dee947 1373
6d6f0db0
SR
1374 var hdr = this._sock.rQshiftBytes(12);
1375 this._FBU.x = (hdr[0] << 8) + hdr[1];
1376 this._FBU.y = (hdr[2] << 8) + hdr[3];
1377 this._FBU.width = (hdr[4] << 8) + hdr[5];
1378 this._FBU.height = (hdr[6] << 8) + hdr[7];
1379 this._FBU.encoding = parseInt((hdr[8] << 24) + (hdr[9] << 16) +
1380 (hdr[10] << 8) + hdr[11], 10);
b1dee947 1381
6d6f0db0
SR
1382 this._onFBUReceive(this,
1383 {'x': this._FBU.x, 'y': this._FBU.y,
1384 'width': this._FBU.width, 'height': this._FBU.height,
1385 'encoding': this._FBU.encoding,
1386 'encodingName': this._encNames[this._FBU.encoding]});
b1dee947 1387
6d6f0db0
SR
1388 if (!this._encNames[this._FBU.encoding]) {
1389 this._fail("Unexpected server message",
1390 "Unsupported encoding " +
1391 this._FBU.encoding);
1392 return false;
1393 }
1394 }
b1dee947 1395
6d6f0db0 1396 this._timing.last_fbu = (new Date()).getTime();
76a86ff5 1397
6d6f0db0 1398 ret = this._encHandlers[this._FBU.encoding]();
3df13262 1399
6d6f0db0
SR
1400 now = (new Date()).getTime();
1401 this._timing.cur_fbu += (now - this._timing.last_fbu);
b1dee947 1402
6d6f0db0
SR
1403 if (ret) {
1404 this._encStats[this._FBU.encoding][0]++;
1405 this._encStats[this._FBU.encoding][1]++;
1406 this._timing.pixels += this._FBU.width * this._FBU.height;
b1dee947 1407 }
b1dee947 1408
6d6f0db0
SR
1409 if (this._timing.pixels >= (this._fb_width * this._fb_height)) {
1410 if ((this._FBU.width === this._fb_width && this._FBU.height === this._fb_height) ||
1411 this._timing.fbu_rt_start > 0) {
1412 this._timing.full_fbu_total += this._timing.cur_fbu;
1413 this._timing.full_fbu_cnt++;
1414 Log.Info("Timing of full FBU, curr: " +
1415 this._timing.cur_fbu + ", total: " +
1416 this._timing.full_fbu_total + ", cnt: " +
1417 this._timing.full_fbu_cnt + ", avg: " +
1418 (this._timing.full_fbu_total / this._timing.full_fbu_cnt));
b1dee947 1419 }
d9ca5e5b 1420
6d6f0db0
SR
1421 if (this._timing.fbu_rt_start > 0) {
1422 var fbu_rt_diff = now - this._timing.fbu_rt_start;
1423 this._timing.fbu_rt_total += fbu_rt_diff;
1424 this._timing.fbu_rt_cnt++;
1425 Log.Info("full FBU round-trip, cur: " +
1426 fbu_rt_diff + ", total: " +
1427 this._timing.fbu_rt_total + ", cnt: " +
1428 this._timing.fbu_rt_cnt + ", avg: " +
1429 (this._timing.fbu_rt_total / this._timing.fbu_rt_cnt));
1430 this._timing.fbu_rt_start = 0;
d9ca5e5b 1431 }
b1dee947
SR
1432 }
1433
6d6f0db0
SR
1434 if (!ret) { return ret; } // need more data
1435 }
b1dee947 1436
6d6f0db0 1437 this._display.flip();
b1dee947 1438
6d6f0db0
SR
1439 this._onFBUComplete(this,
1440 {'x': this._FBU.x, 'y': this._FBU.y,
1441 'width': this._FBU.width, 'height': this._FBU.height,
1442 'encoding': this._FBU.encoding,
1443 'encodingName': this._encNames[this._FBU.encoding]});
b1dee947 1444
6d6f0db0
SR
1445 return true; // We finished this FBU
1446 },
b1dee947 1447
6d6f0db0
SR
1448 _updateContinuousUpdates: function() {
1449 if (!this._enabledContinuousUpdates) { return; }
b1dee947 1450
6d6f0db0
SR
1451 RFB.messages.enableContinuousUpdates(this._sock, true, 0, 0,
1452 this._fb_width, this._fb_height);
1453 }
1454};
8db09746 1455
6d6f0db0
SR
1456make_properties(RFB, [
1457 ['target', 'wo', 'dom'], // VNC display rendering Canvas object
1458 ['focusContainer', 'wo', 'dom'], // DOM element that captures keyboard input
1459 ['encrypt', 'rw', 'bool'], // Use TLS/SSL/wss encryption
1460 ['true_color', 'rw', 'bool'], // Request true color pixel data
1461 ['local_cursor', 'rw', 'bool'], // Request locally rendered cursor
1462 ['shared', 'rw', 'bool'], // Request shared mode
1463 ['view_only', 'rw', 'bool'], // Disable client mouse/keyboard
1464 ['xvp_password_sep', 'rw', 'str'], // Separator for XVP password fields
1465 ['disconnectTimeout', 'rw', 'int'], // Time (s) to wait for disconnection
1466 ['wsProtocols', 'rw', 'arr'], // Protocols to use in the WebSocket connection
1467 ['repeaterID', 'rw', 'str'], // [UltraVNC] RepeaterID to connect to
1468 ['viewportDrag', 'rw', 'bool'], // Move the viewport on mouse drags
1469
1470 // Callback functions
1471 ['onUpdateState', 'rw', 'func'], // onUpdateState(rfb, state, oldstate): connection state change
1472 ['onNotification', 'rw', 'func'], // onNotification(rfb, msg, level, options): notification for the UI
1473 ['onDisconnected', 'rw', 'func'], // onDisconnected(rfb, reason): disconnection finished
1474 ['onPasswordRequired', 'rw', 'func'], // onPasswordRequired(rfb, msg): VNC password is required
1475 ['onClipboard', 'rw', 'func'], // onClipboard(rfb, text): RFB clipboard contents received
1476 ['onBell', 'rw', 'func'], // onBell(rfb): RFB Bell message received
1477 ['onFBUReceive', 'rw', 'func'], // onFBUReceive(rfb, fbu): RFB FBU received but not yet processed
1478 ['onFBUComplete', 'rw', 'func'], // onFBUComplete(rfb, fbu): RFB FBU received and processed
1479 ['onFBResize', 'rw', 'func'], // onFBResize(rfb, width, height): frame buffer resized
1480 ['onDesktopName', 'rw', 'func'], // onDesktopName(rfb, name): desktop name received
1481 ['onXvpInit', 'rw', 'func'] // onXvpInit(version): XVP extensions active for this connection
1482]);
1483
1484RFB.prototype.set_local_cursor = function (cursor) {
1485 if (!cursor || (cursor in {'0': 1, 'no': 1, 'false': 1})) {
1486 this._local_cursor = false;
1487 this._display.disableLocalCursor(); //Only show server-side cursor
1488 } else {
1489 if (this._display.get_cursor_uri()) {
1490 this._local_cursor = true;
1491 } else {
1492 Log.Warn("Browser does not support local cursor");
1493 this._display.disableLocalCursor();
1494 }
1495 }
d86cc2d9 1496
6d6f0db0
SR
1497 // Need to send an updated list of encodings if we are connected
1498 if (this._rfb_connection_state === "connected") {
1499 RFB.messages.clientEncodings(this._sock, this._encodings, cursor,
1500 this._true_color);
1501 }
1502};
2ba767a7 1503
6d6f0db0
SR
1504RFB.prototype.set_view_only = function (view_only) {
1505 this._view_only = view_only;
8db09746 1506
6d6f0db0
SR
1507 if (this._rfb_connection_state === "connecting" ||
1508 this._rfb_connection_state === "connected") {
1509 if (view_only) {
1510 this._keyboard.ungrab();
1511 this._mouse.ungrab();
1512 } else {
1513 this._keyboard.grab();
1514 this._mouse.grab();
1515 }
1516 }
1517};
76a86ff5 1518
6d6f0db0
SR
1519RFB.prototype.get_display = function () { return this._display; };
1520RFB.prototype.get_keyboard = function () { return this._keyboard; };
1521RFB.prototype.get_mouse = function () { return this._mouse; };
76a86ff5 1522
6d6f0db0
SR
1523// Class Methods
1524RFB.messages = {
1525 keyEvent: function (sock, keysym, down) {
1526 var buff = sock._sQ;
1527 var offset = sock._sQlen;
8db09746 1528
6d6f0db0
SR
1529 buff[offset] = 4; // msg-type
1530 buff[offset + 1] = down;
b1dee947 1531
6d6f0db0
SR
1532 buff[offset + 2] = 0;
1533 buff[offset + 3] = 0;
fb49f91b 1534
6d6f0db0
SR
1535 buff[offset + 4] = (keysym >> 24);
1536 buff[offset + 5] = (keysym >> 16);
1537 buff[offset + 6] = (keysym >> 8);
1538 buff[offset + 7] = keysym;
b1dee947 1539
6d6f0db0
SR
1540 sock._sQlen += 8;
1541 sock.flush();
1542 },
ef1e8bab 1543
6d6f0db0
SR
1544 QEMUExtendedKeyEvent: function (sock, keysym, down, keycode) {
1545 function getRFBkeycode(xt_scancode) {
1546 var upperByte = (keycode >> 8);
1547 var lowerByte = (keycode & 0x00ff);
1548 if (upperByte === 0xe0 && lowerByte < 0x7f) {
1549 lowerByte = lowerByte | 0x80;
1550 return lowerByte;
ef1e8bab 1551 }
6d6f0db0 1552 return xt_scancode;
ef1e8bab 1553 }
b1dee947 1554
6d6f0db0
SR
1555 var buff = sock._sQ;
1556 var offset = sock._sQlen;
8f06673a 1557
6d6f0db0
SR
1558 buff[offset] = 255; // msg-type
1559 buff[offset + 1] = 0; // sub msg-type
8f06673a 1560
6d6f0db0
SR
1561 buff[offset + 2] = (down >> 8);
1562 buff[offset + 3] = down;
8f06673a 1563
6d6f0db0
SR
1564 buff[offset + 4] = (keysym >> 24);
1565 buff[offset + 5] = (keysym >> 16);
1566 buff[offset + 6] = (keysym >> 8);
1567 buff[offset + 7] = keysym;
8f06673a 1568
6d6f0db0 1569 var RFBkeycode = getRFBkeycode(keycode);
8f06673a 1570
6d6f0db0
SR
1571 buff[offset + 8] = (RFBkeycode >> 24);
1572 buff[offset + 9] = (RFBkeycode >> 16);
1573 buff[offset + 10] = (RFBkeycode >> 8);
1574 buff[offset + 11] = RFBkeycode;
8f06673a 1575
6d6f0db0
SR
1576 sock._sQlen += 12;
1577 sock.flush();
1578 },
8f06673a 1579
6d6f0db0
SR
1580 pointerEvent: function (sock, x, y, mask) {
1581 var buff = sock._sQ;
1582 var offset = sock._sQlen;
8f06673a 1583
6d6f0db0 1584 buff[offset] = 5; // msg-type
9ff86fb7 1585
6d6f0db0 1586 buff[offset + 1] = mask;
9ff86fb7 1587
6d6f0db0
SR
1588 buff[offset + 2] = x >> 8;
1589 buff[offset + 3] = x;
9ff86fb7 1590
6d6f0db0
SR
1591 buff[offset + 4] = y >> 8;
1592 buff[offset + 5] = y;
9ff86fb7 1593
6d6f0db0
SR
1594 sock._sQlen += 6;
1595 sock.flush();
1596 },
9ff86fb7 1597
6d6f0db0
SR
1598 // TODO(directxman12): make this unicode compatible?
1599 clientCutText: function (sock, text) {
1600 var buff = sock._sQ;
1601 var offset = sock._sQlen;
b1dee947 1602
6d6f0db0 1603 buff[offset] = 6; // msg-type
9ff86fb7 1604
6d6f0db0
SR
1605 buff[offset + 1] = 0; // padding
1606 buff[offset + 2] = 0; // padding
1607 buff[offset + 3] = 0; // padding
9ff86fb7 1608
6d6f0db0 1609 var n = text.length;
9ff86fb7 1610
6d6f0db0
SR
1611 buff[offset + 4] = n >> 24;
1612 buff[offset + 5] = n >> 16;
1613 buff[offset + 6] = n >> 8;
1614 buff[offset + 7] = n;
9ff86fb7 1615
6d6f0db0
SR
1616 for (var i = 0; i < n; i++) {
1617 buff[offset + 8 + i] = text.charCodeAt(i);
1618 }
9ff86fb7 1619
6d6f0db0
SR
1620 sock._sQlen += 8 + n;
1621 sock.flush();
1622 },
1623
1624 setDesktopSize: function (sock, width, height, id, flags) {
1625 var buff = sock._sQ;
1626 var offset = sock._sQlen;
1627
1628 buff[offset] = 251; // msg-type
1629 buff[offset + 1] = 0; // padding
1630 buff[offset + 2] = width >> 8; // width
1631 buff[offset + 3] = width;
1632 buff[offset + 4] = height >> 8; // height
1633 buff[offset + 5] = height;
1634
1635 buff[offset + 6] = 1; // number-of-screens
1636 buff[offset + 7] = 0; // padding
1637
1638 // screen array
1639 buff[offset + 8] = id >> 24; // id
1640 buff[offset + 9] = id >> 16;
1641 buff[offset + 10] = id >> 8;
1642 buff[offset + 11] = id;
1643 buff[offset + 12] = 0; // x-position
1644 buff[offset + 13] = 0;
1645 buff[offset + 14] = 0; // y-position
1646 buff[offset + 15] = 0;
1647 buff[offset + 16] = width >> 8; // width
1648 buff[offset + 17] = width;
1649 buff[offset + 18] = height >> 8; // height
1650 buff[offset + 19] = height;
1651 buff[offset + 20] = flags >> 24; // flags
1652 buff[offset + 21] = flags >> 16;
1653 buff[offset + 22] = flags >> 8;
1654 buff[offset + 23] = flags;
1655
1656 sock._sQlen += 24;
1657 sock.flush();
1658 },
1659
1660 clientFence: function (sock, flags, payload) {
1661 var buff = sock._sQ;
1662 var offset = sock._sQlen;
1663
1664 buff[offset] = 248; // msg-type
1665
1666 buff[offset + 1] = 0; // padding
1667 buff[offset + 2] = 0; // padding
1668 buff[offset + 3] = 0; // padding
1669
1670 buff[offset + 4] = flags >> 24; // flags
1671 buff[offset + 5] = flags >> 16;
1672 buff[offset + 6] = flags >> 8;
1673 buff[offset + 7] = flags;
1674
1675 var n = payload.length;
1676
1677 buff[offset + 8] = n; // length
1678
1679 for (var i = 0; i < n; i++) {
1680 buff[offset + 9 + i] = payload.charCodeAt(i);
1681 }
a7a89626 1682
6d6f0db0
SR
1683 sock._sQlen += 9 + n;
1684 sock.flush();
1685 },
3df13262 1686
6d6f0db0
SR
1687 enableContinuousUpdates: function (sock, enable, x, y, width, height) {
1688 var buff = sock._sQ;
1689 var offset = sock._sQlen;
3df13262 1690
6d6f0db0
SR
1691 buff[offset] = 150; // msg-type
1692 buff[offset + 1] = enable; // enable-flag
76a86ff5 1693
6d6f0db0
SR
1694 buff[offset + 2] = x >> 8; // x
1695 buff[offset + 3] = x;
1696 buff[offset + 4] = y >> 8; // y
1697 buff[offset + 5] = y;
1698 buff[offset + 6] = width >> 8; // width
1699 buff[offset + 7] = width;
1700 buff[offset + 8] = height >> 8; // height
1701 buff[offset + 9] = height;
76a86ff5 1702
6d6f0db0
SR
1703 sock._sQlen += 10;
1704 sock.flush();
1705 },
76a86ff5 1706
6d6f0db0
SR
1707 pixelFormat: function (sock, bpp, depth, true_color) {
1708 var buff = sock._sQ;
1709 var offset = sock._sQlen;
ae116051 1710
6d6f0db0 1711 buff[offset] = 0; // msg-type
9ff86fb7 1712
6d6f0db0
SR
1713 buff[offset + 1] = 0; // padding
1714 buff[offset + 2] = 0; // padding
1715 buff[offset + 3] = 0; // padding
9ff86fb7 1716
6d6f0db0
SR
1717 buff[offset + 4] = bpp * 8; // bits-per-pixel
1718 buff[offset + 5] = depth * 8; // depth
1719 buff[offset + 6] = 0; // little-endian
1720 buff[offset + 7] = true_color ? 1 : 0; // true-color
9ff86fb7 1721
6d6f0db0
SR
1722 buff[offset + 8] = 0; // red-max
1723 buff[offset + 9] = 255; // red-max
9ff86fb7 1724
6d6f0db0
SR
1725 buff[offset + 10] = 0; // green-max
1726 buff[offset + 11] = 255; // green-max
9ff86fb7 1727
6d6f0db0
SR
1728 buff[offset + 12] = 0; // blue-max
1729 buff[offset + 13] = 255; // blue-max
9ff86fb7 1730
6d6f0db0
SR
1731 buff[offset + 14] = 16; // red-shift
1732 buff[offset + 15] = 8; // green-shift
1733 buff[offset + 16] = 0; // blue-shift
9ff86fb7 1734
6d6f0db0
SR
1735 buff[offset + 17] = 0; // padding
1736 buff[offset + 18] = 0; // padding
1737 buff[offset + 19] = 0; // padding
9ff86fb7 1738
6d6f0db0
SR
1739 sock._sQlen += 20;
1740 sock.flush();
1741 },
9ff86fb7 1742
6d6f0db0
SR
1743 clientEncodings: function (sock, encodings, local_cursor, true_color) {
1744 var buff = sock._sQ;
1745 var offset = sock._sQlen;
b1dee947 1746
6d6f0db0
SR
1747 buff[offset] = 2; // msg-type
1748 buff[offset + 1] = 0; // padding
b1dee947 1749
6d6f0db0 1750 // offset + 2 and offset + 3 are encoding count
9ff86fb7 1751
6d6f0db0
SR
1752 var i, j = offset + 4, cnt = 0;
1753 for (i = 0; i < encodings.length; i++) {
1754 if (encodings[i][0] === "Cursor" && !local_cursor) {
1755 Log.Debug("Skipping Cursor pseudo-encoding");
1756 } else if (encodings[i][0] === "TIGHT" && !true_color) {
1757 // TODO: remove this when we have tight+non-true-color
1758 Log.Warn("Skipping tight as it is only supported with true color");
1759 } else {
1760 var enc = encodings[i][1];
1761 buff[j] = enc >> 24;
1762 buff[j + 1] = enc >> 16;
1763 buff[j + 2] = enc >> 8;
1764 buff[j + 3] = enc;
9ff86fb7 1765
6d6f0db0
SR
1766 j += 4;
1767 cnt++;
b1dee947 1768 }
6d6f0db0 1769 }
a7a89626 1770
6d6f0db0
SR
1771 buff[offset + 2] = cnt >> 8;
1772 buff[offset + 3] = cnt;
a7a89626 1773
6d6f0db0
SR
1774 sock._sQlen += j - offset;
1775 sock.flush();
1776 },
a679a97d 1777
6d6f0db0
SR
1778 fbUpdateRequest: function (sock, incremental, x, y, w, h) {
1779 var buff = sock._sQ;
1780 var offset = sock._sQlen;
9ff86fb7 1781
6d6f0db0
SR
1782 if (typeof(x) === "undefined") { x = 0; }
1783 if (typeof(y) === "undefined") { y = 0; }
b1dee947 1784
6d6f0db0
SR
1785 buff[offset] = 3; // msg-type
1786 buff[offset + 1] = incremental ? 1 : 0;
9ff86fb7 1787
6d6f0db0
SR
1788 buff[offset + 2] = (x >> 8) & 0xFF;
1789 buff[offset + 3] = x & 0xFF;
9ff86fb7 1790
6d6f0db0
SR
1791 buff[offset + 4] = (y >> 8) & 0xFF;
1792 buff[offset + 5] = y & 0xFF;
9ff86fb7 1793
6d6f0db0
SR
1794 buff[offset + 6] = (w >> 8) & 0xFF;
1795 buff[offset + 7] = w & 0xFF;
9ff86fb7 1796
6d6f0db0
SR
1797 buff[offset + 8] = (h >> 8) & 0xFF;
1798 buff[offset + 9] = h & 0xFF;
b1dee947 1799
6d6f0db0
SR
1800 sock._sQlen += 10;
1801 sock.flush();
1802 }
1803};
b1dee947 1804
6d6f0db0
SR
1805RFB.genDES = function (password, challenge) {
1806 var passwd = [];
1807 for (var i = 0; i < password.length; i++) {
1808 passwd.push(password.charCodeAt(i));
1809 }
1810 return (new DES(passwd)).encrypt(challenge);
1811};
b1dee947 1812
6d6f0db0
SR
1813RFB.encodingHandlers = {
1814 RAW: function () {
1815 if (this._FBU.lines === 0) {
1816 this._FBU.lines = this._FBU.height;
1817 }
a7a89626 1818
6d6f0db0
SR
1819 this._FBU.bytes = this._FBU.width * this._fb_Bpp; // at least a line
1820 if (this._sock.rQwait("RAW", this._FBU.bytes)) { return false; }
1821 var cur_y = this._FBU.y + (this._FBU.height - this._FBU.lines);
1822 var curr_height = Math.min(this._FBU.lines,
1823 Math.floor(this._sock.rQlen() / (this._FBU.width * this._fb_Bpp)));
1824 this._display.blitImage(this._FBU.x, cur_y, this._FBU.width,
1825 curr_height, this._sock.get_rQ(),
1826 this._sock.get_rQi());
1827 this._sock.rQskipBytes(this._FBU.width * curr_height * this._fb_Bpp);
1828 this._FBU.lines -= curr_height;
1829
1830 if (this._FBU.lines > 0) {
1831 this._FBU.bytes = this._FBU.width * this._fb_Bpp; // At least another line
1832 } else {
1833 this._FBU.rects--;
1834 this._FBU.bytes = 0;
1835 }
b1dee947 1836
6d6f0db0
SR
1837 return true;
1838 },
1839
1840 COPYRECT: function () {
1841 this._FBU.bytes = 4;
1842 if (this._sock.rQwait("COPYRECT", 4)) { return false; }
1843 this._display.copyImage(this._sock.rQshift16(), this._sock.rQshift16(),
1844 this._FBU.x, this._FBU.y, this._FBU.width,
1845 this._FBU.height);
1846
1847 this._FBU.rects--;
1848 this._FBU.bytes = 0;
1849 return true;
1850 },
1851
1852 RRE: function () {
1853 var color;
1854 if (this._FBU.subrects === 0) {
1855 this._FBU.bytes = 4 + this._fb_Bpp;
1856 if (this._sock.rQwait("RRE", 4 + this._fb_Bpp)) { return false; }
1857 this._FBU.subrects = this._sock.rQshift32();
1858 color = this._sock.rQshiftBytes(this._fb_Bpp); // Background
1859 this._display.fillRect(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, color);
1860 }
b1dee947 1861
6d6f0db0
SR
1862 while (this._FBU.subrects > 0 && this._sock.rQlen() >= (this._fb_Bpp + 8)) {
1863 color = this._sock.rQshiftBytes(this._fb_Bpp);
1864 var x = this._sock.rQshift16();
1865 var y = this._sock.rQshift16();
1866 var width = this._sock.rQshift16();
1867 var height = this._sock.rQshift16();
1868 this._display.fillRect(this._FBU.x + x, this._FBU.y + y, width, height, color);
1869 this._FBU.subrects--;
1870 }
f00193e0 1871
6d6f0db0
SR
1872 if (this._FBU.subrects > 0) {
1873 var chunk = Math.min(this._rre_chunk_sz, this._FBU.subrects);
1874 this._FBU.bytes = (this._fb_Bpp + 8) * chunk;
1875 } else {
b1dee947
SR
1876 this._FBU.rects--;
1877 this._FBU.bytes = 0;
6d6f0db0 1878 }
b1dee947 1879
6d6f0db0
SR
1880 return true;
1881 },
b1dee947 1882
6d6f0db0
SR
1883 HEXTILE: function () {
1884 var rQ = this._sock.get_rQ();
1885 var rQi = this._sock.get_rQi();
b1dee947 1886
6d6f0db0
SR
1887 if (this._FBU.tiles === 0) {
1888 this._FBU.tiles_x = Math.ceil(this._FBU.width / 16);
1889 this._FBU.tiles_y = Math.ceil(this._FBU.height / 16);
1890 this._FBU.total_tiles = this._FBU.tiles_x * this._FBU.tiles_y;
1891 this._FBU.tiles = this._FBU.total_tiles;
1892 }
b1dee947 1893
6d6f0db0
SR
1894 while (this._FBU.tiles > 0) {
1895 this._FBU.bytes = 1;
1896 if (this._sock.rQwait("HEXTILE subencoding", this._FBU.bytes)) { return false; }
1897 var subencoding = rQ[rQi]; // Peek
1898 if (subencoding > 30) { // Raw
1899 this._fail("Unexpected server message",
1900 "Illegal hextile subencoding: " + subencoding);
1901 return false;
b1dee947
SR
1902 }
1903
6d6f0db0
SR
1904 var subrects = 0;
1905 var curr_tile = this._FBU.total_tiles - this._FBU.tiles;
1906 var tile_x = curr_tile % this._FBU.tiles_x;
1907 var tile_y = Math.floor(curr_tile / this._FBU.tiles_x);
1908 var x = this._FBU.x + tile_x * 16;
1909 var y = this._FBU.y + tile_y * 16;
1910 var w = Math.min(16, (this._FBU.x + this._FBU.width) - x);
1911 var h = Math.min(16, (this._FBU.y + this._FBU.height) - y);
b1dee947 1912
6d6f0db0
SR
1913 // Figure out how much we are expecting
1914 if (subencoding & 0x01) { // Raw
1915 this._FBU.bytes += w * h * this._fb_Bpp;
1916 } else {
1917 if (subencoding & 0x02) { // Background
1918 this._FBU.bytes += this._fb_Bpp;
1919 }
1920 if (subencoding & 0x04) { // Foreground
1921 this._FBU.bytes += this._fb_Bpp;
1922 }
1923 if (subencoding & 0x08) { // AnySubrects
1924 this._FBU.bytes++; // Since we aren't shifting it off
1925 if (this._sock.rQwait("hextile subrects header", this._FBU.bytes)) { return false; }
1926 subrects = rQ[rQi + this._FBU.bytes - 1]; // Peek
1927 if (subencoding & 0x10) { // SubrectsColoured
1928 this._FBU.bytes += subrects * (this._fb_Bpp + 2);
1929 } else {
1930 this._FBU.bytes += subrects * 2;
b1dee947
SR
1931 }
1932 }
6d6f0db0 1933 }
b1dee947 1934
6d6f0db0 1935 if (this._sock.rQwait("hextile", this._FBU.bytes)) { return false; }
b1dee947 1936
6d6f0db0
SR
1937 // We know the encoding and have a whole tile
1938 this._FBU.subencoding = rQ[rQi];
1939 rQi++;
1940 if (this._FBU.subencoding === 0) {
1941 if (this._FBU.lastsubencoding & 0x01) {
1942 // Weird: ignore blanks are RAW
1943 Log.Debug(" Ignoring blank after RAW");
b1dee947 1944 } else {
6d6f0db0
SR
1945 this._display.fillRect(x, y, w, h, this._FBU.background);
1946 }
1947 } else if (this._FBU.subencoding & 0x01) { // Raw
1948 this._display.blitImage(x, y, w, h, rQ, rQi);
1949 rQi += this._FBU.bytes - 1;
1950 } else {
1951 if (this._FBU.subencoding & 0x02) { // Background
1952 if (this._fb_Bpp == 1) {
1953 this._FBU.background = rQ[rQi];
1954 } else {
1955 // fb_Bpp is 4
1956 this._FBU.background = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
a7a89626 1957 }
6d6f0db0
SR
1958 rQi += this._fb_Bpp;
1959 }
1960 if (this._FBU.subencoding & 0x04) { // Foreground
1961 if (this._fb_Bpp == 1) {
1962 this._FBU.foreground = rQ[rQi];
1963 } else {
1964 // this._fb_Bpp is 4
1965 this._FBU.foreground = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
b1dee947 1966 }
6d6f0db0
SR
1967 rQi += this._fb_Bpp;
1968 }
b1dee947 1969
6d6f0db0
SR
1970 this._display.startTile(x, y, w, h, this._FBU.background);
1971 if (this._FBU.subencoding & 0x08) { // AnySubrects
1972 subrects = rQ[rQi];
1973 rQi++;
b1dee947 1974
6d6f0db0
SR
1975 for (var s = 0; s < subrects; s++) {
1976 var color;
1977 if (this._FBU.subencoding & 0x10) { // SubrectsColoured
1978 if (this._fb_Bpp === 1) {
1979 color = rQ[rQi];
b1dee947 1980 } else {
6d6f0db0
SR
1981 // _fb_Bpp is 4
1982 color = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
b1dee947 1983 }
6d6f0db0
SR
1984 rQi += this._fb_Bpp;
1985 } else {
1986 color = this._FBU.foreground;
1987 }
1988 var xy = rQ[rQi];
1989 rQi++;
1990 var sx = (xy >> 4);
1991 var sy = (xy & 0x0f);
a7a89626 1992
6d6f0db0
SR
1993 var wh = rQ[rQi];
1994 rQi++;
1995 var sw = (wh >> 4) + 1;
1996 var sh = (wh & 0x0f) + 1;
a7a89626 1997
6d6f0db0 1998 this._display.subTile(sx, sy, sw, sh, color);
b1dee947 1999 }
a7a89626 2000 }
6d6f0db0 2001 this._display.finishTile();
a7a89626 2002 }
6d6f0db0
SR
2003 this._sock.set_rQi(rQi);
2004 this._FBU.lastsubencoding = this._FBU.subencoding;
2005 this._FBU.bytes = 0;
2006 this._FBU.tiles--;
2007 }
d065cad9 2008
6d6f0db0
SR
2009 if (this._FBU.tiles === 0) {
2010 this._FBU.rects--;
2011 }
b1dee947 2012
6d6f0db0
SR
2013 return true;
2014 },
b1dee947 2015
6d6f0db0
SR
2016 getTightCLength: function (arr) {
2017 var header = 1, data = 0;
2018 data += arr[0] & 0x7f;
2019 if (arr[0] & 0x80) {
2020 header++;
2021 data += (arr[1] & 0x7f) << 7;
2022 if (arr[1] & 0x80) {
b1dee947 2023 header++;
6d6f0db0 2024 data += arr[2] << 14;
b1dee947 2025 }
6d6f0db0
SR
2026 }
2027 return [header, data];
2028 },
2029
2030 display_tight: function (isTightPNG) {
2031 if (this._fb_depth === 1) {
2032 this._fail("Internal error",
2033 "Tight protocol handler only implements " +
2034 "true color mode");
2035 }
9b75bcaa 2036
6d6f0db0
SR
2037 this._FBU.bytes = 1; // compression-control byte
2038 if (this._sock.rQwait("TIGHT compression-control", this._FBU.bytes)) { return false; }
2039
2040 var checksum = function (data) {
2041 var sum = 0;
2042 for (var i = 0; i < data.length; i++) {
2043 sum += data[i];
2044 if (sum > 65536) sum -= 65536;
2045 }
2046 return sum;
2047 };
2048
2049 var resetStreams = 0;
2050 var streamId = -1;
2051 var decompress = function (data, expected) {
2052 for (var i = 0; i < 4; i++) {
2053 if ((resetStreams >> i) & 1) {
2054 this._FBU.zlibs[i].reset();
2055 Log.Info("Reset zlib stream " + i);
b1dee947 2056 }
6d6f0db0 2057 }
de84e098 2058
6d6f0db0
SR
2059 //var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
2060 var uncompressed = this._FBU.zlibs[streamId].inflate(data, true, expected);
2061 /*if (uncompressed.status !== 0) {
2062 Log.Error("Invalid data in zlib stream");
2063 }*/
2064
2065 //return uncompressed.data;
2066 return uncompressed;
2067 }.bind(this);
2068
2069 var indexedToRGBX2Color = function (data, palette, width, height) {
2070 // Convert indexed (palette based) image data to RGB
2071 // TODO: reduce number of calculations inside loop
2072 var dest = this._destBuff;
2073 var w = Math.floor((width + 7) / 8);
2074 var w1 = Math.floor(width / 8);
2075
2076 /*for (var y = 0; y < height; y++) {
2077 var b, x, dp, sp;
2078 var yoffset = y * width;
2079 var ybitoffset = y * w;
2080 var xoffset, targetbyte;
2081 for (x = 0; x < w1; x++) {
d1800d09
SR
2082 xoffset = yoffset + x * 8;
2083 targetbyte = data[ybitoffset + x];
6d6f0db0 2084 for (b = 7; b >= 0; b--) {
d1800d09
SR
2085 dp = (xoffset + 7 - b) * 3;
2086 sp = (targetbyte >> b & 1) * 3;
2087 dest[dp] = palette[sp];
2088 dest[dp + 1] = palette[sp + 1];
2089 dest[dp + 2] = palette[sp + 2];
2090 }
6d6f0db0
SR
2091 }
2092
2093 xoffset = yoffset + x * 8;
2094 targetbyte = data[ybitoffset + x];
2095 for (b = 7; b >= 8 - width % 8; b--) {
2096 dp = (xoffset + 7 - b) * 3;
2097 sp = (targetbyte >> b & 1) * 3;
2098 dest[dp] = palette[sp];
2099 dest[dp + 1] = palette[sp + 1];
2100 dest[dp + 2] = palette[sp + 2];
2101 }
2102 }*/
d1800d09 2103
6d6f0db0
SR
2104 for (var y = 0; y < height; y++) {
2105 var b, x, dp, sp;
2106 for (x = 0; x < w1; x++) {
2107 for (b = 7; b >= 0; b--) {
d1800d09
SR
2108 dp = (y * width + x * 8 + 7 - b) * 4;
2109 sp = (data[y * w + x] >> b & 1) * 3;
2110 dest[dp] = palette[sp];
2111 dest[dp + 1] = palette[sp + 1];
2112 dest[dp + 2] = palette[sp + 2];
2113 dest[dp + 3] = 255;
e16ad2fd
JM
2114 }
2115 }
b1dee947 2116
6d6f0db0
SR
2117 for (b = 7; b >= 8 - width % 8; b--) {
2118 dp = (y * width + x * 8 + 7 - b) * 4;
2119 sp = (data[y * w + x] >> b & 1) * 3;
2120 dest[dp] = palette[sp];
2121 dest[dp + 1] = palette[sp + 1];
2122 dest[dp + 2] = palette[sp + 2];
2123 dest[dp + 3] = 255;
d1800d09 2124 }
6d6f0db0 2125 }
d1800d09 2126
6d6f0db0
SR
2127 return dest;
2128 }.bind(this);
2129
2130 var indexedToRGBX = function (data, palette, width, height) {
2131 // Convert indexed (palette based) image data to RGB
2132 var dest = this._destBuff;
2133 var total = width * height * 4;
2134 for (var i = 0, j = 0; i < total; i += 4, j++) {
2135 var sp = data[j] * 3;
2136 dest[i] = palette[sp];
2137 dest[i + 1] = palette[sp + 1];
2138 dest[i + 2] = palette[sp + 2];
2139 dest[i + 3] = 255;
2140 }
2141
2142 return dest;
2143 }.bind(this);
2144
2145 var rQi = this._sock.get_rQi();
2146 var rQ = this._sock.rQwhole();
2147 var cmode, data;
2148 var cl_header, cl_data;
2149
2150 var handlePalette = function () {
2151 var numColors = rQ[rQi + 2] + 1;
2152 var paletteSize = numColors * this._fb_depth;
2153 this._FBU.bytes += paletteSize;
2154 if (this._sock.rQwait("TIGHT palette " + cmode, this._FBU.bytes)) { return false; }
2155
2156 var bpp = (numColors <= 2) ? 1 : 8;
2157 var rowSize = Math.floor((this._FBU.width * bpp + 7) / 8);
2158 var raw = false;
2159 if (rowSize * this._FBU.height < 12) {
2160 raw = true;
2161 cl_header = 0;
2162 cl_data = rowSize * this._FBU.height;
2163 //clength = [0, rowSize * this._FBU.height];
2164 } else {
2165 // begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
2166 var cl_offset = rQi + 3 + paletteSize;
2167 cl_header = 1;
2168 cl_data = 0;
2169 cl_data += rQ[cl_offset] & 0x7f;
2170 if (rQ[cl_offset] & 0x80) {
2171 cl_header++;
2172 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2173 if (rQ[cl_offset + 1] & 0x80) {
d1800d09 2174 cl_header++;
6d6f0db0 2175 cl_data += rQ[cl_offset + 2] << 14;
d1800d09 2176 }
e16ad2fd 2177 }
6d6f0db0
SR
2178 // end inline getTightCLength
2179 }
b1dee947 2180
6d6f0db0
SR
2181 this._FBU.bytes += cl_header + cl_data;
2182 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
b1dee947 2183
6d6f0db0
SR
2184 // Shift ctl, filter id, num colors, palette entries, and clength off
2185 this._sock.rQskipBytes(3);
2186 //var palette = this._sock.rQshiftBytes(paletteSize);
2187 this._sock.rQshiftTo(this._paletteBuff, paletteSize);
2188 this._sock.rQskipBytes(cl_header);
b1dee947 2189
6d6f0db0
SR
2190 if (raw) {
2191 data = this._sock.rQshiftBytes(cl_data);
2192 } else {
2193 data = decompress(this._sock.rQshiftBytes(cl_data), rowSize * this._FBU.height);
2194 }
b1dee947 2195
6d6f0db0
SR
2196 // Convert indexed (palette based) image data to RGB
2197 var rgbx;
2198 if (numColors == 2) {
2199 rgbx = indexedToRGBX2Color(data, this._paletteBuff, this._FBU.width, this._FBU.height);
2200 this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
2201 } else {
2202 rgbx = indexedToRGBX(data, this._paletteBuff, this._FBU.width, this._FBU.height);
2203 this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
2204 }
b1dee947 2205
b1dee947 2206
6d6f0db0
SR
2207 return true;
2208 }.bind(this);
2209
2210 var handleCopy = function () {
2211 var raw = false;
2212 var uncompressedSize = this._FBU.width * this._FBU.height * this._fb_depth;
2213 if (uncompressedSize < 12) {
2214 raw = true;
2215 cl_header = 0;
2216 cl_data = uncompressedSize;
2217 } else {
2218 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2219 var cl_offset = rQi + 1;
2220 cl_header = 1;
2221 cl_data = 0;
2222 cl_data += rQ[cl_offset] & 0x7f;
2223 if (rQ[cl_offset] & 0x80) {
2224 cl_header++;
2225 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2226 if (rQ[cl_offset + 1] & 0x80) {
d1800d09 2227 cl_header++;
6d6f0db0 2228 cl_data += rQ[cl_offset + 2] << 14;
d1800d09 2229 }
b1dee947 2230 }
6d6f0db0
SR
2231 // end inline getTightCLength
2232 }
2233 this._FBU.bytes = 1 + cl_header + cl_data;
2234 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
b1dee947 2235
6d6f0db0
SR
2236 // Shift ctl, clength off
2237 this._sock.rQshiftBytes(1 + cl_header);
b1dee947 2238
6d6f0db0
SR
2239 if (raw) {
2240 data = this._sock.rQshiftBytes(cl_data);
2241 } else {
2242 data = decompress(this._sock.rQshiftBytes(cl_data), uncompressedSize);
2243 }
b1dee947 2244
6d6f0db0 2245 this._display.blitRgbImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, data, 0, false);
b1dee947 2246
6d6f0db0
SR
2247 return true;
2248 }.bind(this);
b1dee947 2249
6d6f0db0 2250 var ctl = this._sock.rQpeek8();
b1dee947 2251
6d6f0db0
SR
2252 // Keep tight reset bits
2253 resetStreams = ctl & 0xF;
b1dee947 2254
6d6f0db0
SR
2255 // Figure out filter
2256 ctl = ctl >> 4;
2257 streamId = ctl & 0x3;
b1dee947 2258
6d6f0db0
SR
2259 if (ctl === 0x08) cmode = "fill";
2260 else if (ctl === 0x09) cmode = "jpeg";
2261 else if (ctl === 0x0A) cmode = "png";
2262 else if (ctl & 0x04) cmode = "filter";
2263 else if (ctl < 0x04) cmode = "copy";
2264 else return this._fail("Unexpected server message",
2265 "Illegal tight compression received, " +
2266 "ctl: " + ctl);
b1dee947 2267
6d6f0db0
SR
2268 if (isTightPNG && (cmode === "filter" || cmode === "copy")) {
2269 return this._fail("Unexpected server message",
2270 "filter/copy received in tightPNG mode");
2271 }
de84e098 2272
6d6f0db0
SR
2273 switch (cmode) {
2274 // fill use fb_depth because TPIXELs drop the padding byte
2275 case "fill": // TPIXEL
2276 this._FBU.bytes += this._fb_depth;
2277 break;
2278 case "jpeg": // max clength
2279 this._FBU.bytes += 3;
2280 break;
2281 case "png": // max clength
2282 this._FBU.bytes += 3;
2283 break;
2284 case "filter": // filter id + num colors if palette
2285 this._FBU.bytes += 2;
2286 break;
2287 case "copy":
2288 break;
2289 }
d065cad9 2290
6d6f0db0 2291 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
b1dee947 2292
6d6f0db0
SR
2293 // Determine FBU.bytes
2294 switch (cmode) {
2295 case "fill":
2296 // skip ctl byte
2297 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);
2298 this._sock.rQskipBytes(4);
2299 break;
2300 case "png":
2301 case "jpeg":
2302 // begin inline getTightCLength (returning two-item arrays is for peformance with GC)
2303 var cl_offset = rQi + 1;
2304 cl_header = 1;
2305 cl_data = 0;
2306 cl_data += rQ[cl_offset] & 0x7f;
2307 if (rQ[cl_offset] & 0x80) {
2308 cl_header++;
2309 cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
2310 if (rQ[cl_offset + 1] & 0x80) {
d1800d09 2311 cl_header++;
6d6f0db0 2312 cl_data += rQ[cl_offset + 2] << 14;
b1dee947 2313 }
6d6f0db0
SR
2314 }
2315 // end inline getTightCLength
2316 this._FBU.bytes = 1 + cl_header + cl_data; // ctl + clength size + jpeg-data
2317 if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
798340b9 2318
6d6f0db0
SR
2319 // We have everything, render it
2320 this._sock.rQskipBytes(1 + cl_header); // shift off clt + compact length
2321 data = this._sock.rQshiftBytes(cl_data);
2322 this._display.imageRect(this._FBU.x, this._FBU.y, "image/" + cmode, data);
2323 break;
2324 case "filter":
2325 var filterId = rQ[rQi + 1];
2326 if (filterId === 1) {
2327 if (!handlePalette()) { return false; }
b0ec6509 2328 } else {
6d6f0db0
SR
2329 // Filter 0, Copy could be valid here, but servers don't send it as an explicit filter
2330 // Filter 2, Gradient is valid but not use if jpeg is enabled
2331 this._fail("Unexpected server message",
2332 "Unsupported tight subencoding received, " +
2333 "filter: " + filterId);
b0ec6509 2334 }
6d6f0db0
SR
2335 break;
2336 case "copy":
2337 if (!handleCopy()) { return false; }
2338 break;
2339 }
b0ec6509 2340
6d6f0db0
SR
2341
2342 this._FBU.bytes = 0;
2343 this._FBU.rects--;
2344
2345 return true;
2346 },
2347
2348 TIGHT: function () { return this._encHandlers.display_tight(false); },
2349 TIGHT_PNG: function () { return this._encHandlers.display_tight(true); },
2350
2351 last_rect: function () {
2352 this._FBU.rects = 0;
2353 return true;
2354 },
2355
2356 handle_FB_resize: function () {
2357 this._fb_width = this._FBU.width;
2358 this._fb_height = this._FBU.height;
2359 this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
2360 this._display.resize(this._fb_width, this._fb_height);
2361 this._onFBResize(this, this._fb_width, this._fb_height);
2362 this._timing.fbu_rt_start = (new Date()).getTime();
2363 this._updateContinuousUpdates();
2364
2365 this._FBU.bytes = 0;
2366 this._FBU.rects -= 1;
2367 return true;
2368 },
2369
2370 ExtendedDesktopSize: function () {
2371 this._FBU.bytes = 1;
2372 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2373
2374 this._supportsSetDesktopSize = true;
2375 var number_of_screens = this._sock.rQpeek8();
2376
2377 this._FBU.bytes = 4 + (number_of_screens * 16);
2378 if (this._sock.rQwait("ExtendedDesktopSize", this._FBU.bytes)) { return false; }
2379
2380 this._sock.rQskipBytes(1); // number-of-screens
2381 this._sock.rQskipBytes(3); // padding
2382
2383 for (var i = 0; i < number_of_screens; i += 1) {
2384 // Save the id and flags of the first screen
2385 if (i === 0) {
2386 this._screen_id = this._sock.rQshiftBytes(4); // id
2387 this._sock.rQskipBytes(2); // x-position
2388 this._sock.rQskipBytes(2); // y-position
2389 this._sock.rQskipBytes(2); // width
2390 this._sock.rQskipBytes(2); // height
2391 this._screen_flags = this._sock.rQshiftBytes(4); // flags
2392 } else {
2393 this._sock.rQskipBytes(16);
798340b9 2394 }
6d6f0db0 2395 }
b0ec6509 2396
6d6f0db0
SR
2397 /*
2398 * The x-position indicates the reason for the change:
2399 *
2400 * 0 - server resized on its own
2401 * 1 - this client requested the resize
2402 * 2 - another client requested the resize
2403 */
b0ec6509 2404
6d6f0db0
SR
2405 // We need to handle errors when we requested the resize.
2406 if (this._FBU.x === 1 && this._FBU.y !== 0) {
2407 var msg = "";
2408 // The y-position indicates the status code from the server
2409 switch (this._FBU.y) {
2410 case 1:
2411 msg = "Resize is administratively prohibited";
2412 break;
2413 case 2:
2414 msg = "Out of resources";
2415 break;
2416 case 3:
2417 msg = "Invalid screen layout";
2418 break;
2419 default:
2420 msg = "Unknown reason";
2421 break;
2422 }
2423 this._notification("Server did not accept the resize request: "
2424 + msg, 'normal');
b1dee947 2425 return true;
6d6f0db0 2426 }
b1dee947 2427
6d6f0db0
SR
2428 this._encHandlers.handle_FB_resize();
2429 return true;
2430 },
b1dee947 2431
6d6f0db0
SR
2432 DesktopSize: function () {
2433 this._encHandlers.handle_FB_resize();
2434 return true;
2435 },
8db09746 2436
6d6f0db0
SR
2437 Cursor: function () {
2438 Log.Debug(">> set_cursor");
2439 var x = this._FBU.x; // hotspot-x
2440 var y = this._FBU.y; // hotspot-y
2441 var w = this._FBU.width;
2442 var h = this._FBU.height;
8db09746 2443
6d6f0db0
SR
2444 var pixelslength = w * h * this._fb_Bpp;
2445 var masklength = Math.floor((w + 7) / 8) * h;
a7a89626 2446
6d6f0db0
SR
2447 this._FBU.bytes = pixelslength + masklength;
2448 if (this._sock.rQwait("cursor encoding", this._FBU.bytes)) { return false; }
b1dee947 2449
6d6f0db0
SR
2450 this._display.changeCursor(this._sock.rQshiftBytes(pixelslength),
2451 this._sock.rQshiftBytes(masklength),
2452 x, y, w, h);
b1dee947 2453
6d6f0db0
SR
2454 this._FBU.bytes = 0;
2455 this._FBU.rects--;
8f06673a 2456
6d6f0db0
SR
2457 Log.Debug("<< set_cursor");
2458 return true;
2459 },
25e4928f 2460
6d6f0db0
SR
2461 QEMUExtendedKeyEvent: function () {
2462 this._FBU.rects--;
25e4928f 2463
6d6f0db0
SR
2464 var keyboardEvent = document.createEvent("keyboardEvent");
2465 if (keyboardEvent.code !== undefined) {
2466 this._qemuExtKeyEventSupported = true;
2467 this._keyboard.setQEMUVNCKeyboardHandler();
058be785 2468 }
6d6f0db0
SR
2469 },
2470
2471 JPEG_quality_lo: function () {
2472 Log.Error("Server sent jpeg_quality pseudo-encoding");
2473 },
2474
2475 compress_lo: function () {
2476 Log.Error("Server sent compress level pseudo-encoding");
2477 }
2478};