Merge pull request #488 from kanaka/feature/more-perf-improvements

Performance Improvements
This commit is contained in:
Solly
2015-08-14 11:56:57 -04:00
26 changed files with 3316 additions and 1056 deletions

View File

@@ -15,6 +15,14 @@ var Display;
(function () {
"use strict";
var SUPPORTS_IMAGEDATA_CONSTRUCTOR = false;
try {
new ImageData(new Uint8ClampedArray(1), 1, 1);
SUPPORTS_IMAGEDATA_CONSTRUCTOR = true;
} catch (ex) {
// ignore failure
}
Display = function (defaults) {
this._drawCtx = null;
this._c_forceCanvas = false;
@@ -351,18 +359,41 @@ var Display;
this._renderQ = [];
},
fillRect: function (x, y, width, height, color) {
this._setFillColor(color);
this._drawCtx.fillRect(x - this._viewportLoc.x, y - this._viewportLoc.y, width, height);
fillRect: function (x, y, width, height, color, from_queue) {
if (this._renderQ.length !== 0 && !from_queue) {
this.renderQ_push({
'type': 'fill',
'x': x,
'y': y,
'width': width,
'height': height,
'color': color
});
} else {
this._setFillColor(color);
this._drawCtx.fillRect(x - this._viewportLoc.x, y - this._viewportLoc.y, width, height);
}
},
copyImage: function (old_x, old_y, new_x, new_y, w, h) {
var x1 = old_x - this._viewportLoc.x;
var y1 = old_y - this._viewportLoc.y;
var x2 = new_x - this._viewportLoc.x;
var y2 = new_y - this._viewportLoc.y;
copyImage: function (old_x, old_y, new_x, new_y, w, h, from_queue) {
if (this._renderQ.length !== 0 && !from_queue) {
this.renderQ_push({
'type': 'copy',
'old_x': old_x,
'old_y': old_y,
'x': new_x,
'y': new_y,
'width': w,
'height': h,
});
} else {
var x1 = old_x - this._viewportLoc.x;
var y1 = old_y - this._viewportLoc.y;
var x2 = new_x - this._viewportLoc.x;
var y2 = new_y - this._viewportLoc.y;
this._drawCtx.drawImage(this._target, x1, y1, w, h, x2, y2, w, h);
this._drawCtx.drawImage(this._target, x1, y1, w, h, x2, y2, w, h);
}
},
// start updating a tile
@@ -394,7 +425,7 @@ var Display;
data[i + 3] = 255;
}
} else {
this.fillRect(x, y, width, height, color);
this.fillRect(x, y, width, height, color, true);
}
},
@@ -425,7 +456,7 @@ var Display;
}
}
} else {
this.fillRect(this._tile_x + x, this._tile_y + y, w, h, color);
this.fillRect(this._tile_x + x, this._tile_y + y, w, h, color, true);
}
},
@@ -438,16 +469,34 @@ var Display;
// else: No-op -- already done by setSubTile
},
blitImage: function (x, y, width, height, arr, offset) {
if (this._true_color) {
blitImage: function (x, y, width, height, arr, offset, from_queue) {
if (this._renderQ.length !== 0 && !from_queue) {
this.renderQ_push({
'type': 'blit',
'data': arr,
'x': x,
'y': y,
'width': width,
'height': height,
});
} else if (this._true_color) {
this._bgrxImageData(x, y, this._viewportLoc.x, this._viewportLoc.y, width, height, arr, offset);
} else {
this._cmapImageData(x, y, this._viewportLoc.x, this._viewportLoc.y, width, height, arr, offset);
}
},
blitRgbImage: function (x, y , width, height, arr, offset) {
if (this._true_color) {
blitRgbImage: function (x, y , width, height, arr, offset, from_queue) {
if (this._renderQ.length !== 0 && !from_queue) {
this.renderQ_push({
'type': 'blitRgb',
'data': arr,
'x': x,
'y': y,
'width': width,
'height': height,
});
} else if (this._true_color) {
this._rgbImageData(x, y, this._viewportLoc.x, this._viewportLoc.y, width, height, arr, offset);
} else {
// probably wrong?
@@ -455,6 +504,26 @@ var Display;
}
},
blitRgbxImage: function (x, y, width, height, arr, offset, from_queue) {
if (this._renderQ.length !== 0 && !from_queue) {
// NB(directxman12): it's technically more performant here to use preallocated arrays, but it
// but it's a lot of extra work for not a lot of payoff -- if we're using the render queue,
// this probably isn't getting called *nearly* as much
var new_arr = new Uint8Array(width * height * 4);
new_arr.set(new Uint8Array(arr.buffer, 0, new_arr.length));
this.renderQ_push({
'type': 'blitRgbx',
'data': new_arr,
'x': x,
'y': y,
'width': width,
'height': height,
});
} else {
this._rgbxImageData(x, y, this._viewportLoc.x, this._viewportLoc.y, width, height, arr, offset);
}
},
blitStringImage: function (str, x, y) {
var img = new Image();
img.onload = function () {
@@ -632,6 +701,18 @@ var Display;
this._drawCtx.putImageData(img, x - vx, y - vy);
},
_rgbxImageData: function (x, y, vx, vy, width, height, arr, offset) {
// NB(directxman12): arr must be an Type Array view
var img;
if (SUPPORTS_IMAGEDATA_CONSTRUCTOR) {
img = new ImageData(new Uint8ClampedArray(arr.buffer, arr.byteOffset, width * height * 4), width, height);
} else {
img = this._drawCtx.createImageData(width, height);
img.data.set(new Uint8ClampedArray(arr.buffer, arr.byteOffset, width * height * 4));
}
this._drawCtx.putImageData(img, x - vx, y - vy);
},
_cmapImageData: function (x, y, vx, vy, width, height, arr, offset) {
var img = this._drawCtx.createImageData(width, height);
var data = img.data;
@@ -652,16 +733,19 @@ var Display;
var a = this._renderQ[0];
switch (a.type) {
case 'copy':
this.copyImage(a.old_x, a.old_y, a.x, a.y, a.width, a.height);
this.copyImage(a.old_x, a.old_y, a.x, a.y, a.width, a.height, true);
break;
case 'fill':
this.fillRect(a.x, a.y, a.width, a.height, a.color);
this.fillRect(a.x, a.y, a.width, a.height, a.color, true);
break;
case 'blit':
this.blitImage(a.x, a.y, a.width, a.height, a.data, 0);
this.blitImage(a.x, a.y, a.width, a.height, a.data, 0, true);
break;
case 'blitRgb':
this.blitRgbImage(a.x, a.y, a.width, a.height, a.data, 0);
this.blitRgbImage(a.x, a.y, a.width, a.height, a.data, 0, true);
break;
case 'blitRgbx':
this.blitRgbxImage(a.x, a.y, a.width, a.height, a.data, 0, true);
break;
case 'img':
if (a.img.complete) {

2409
include/inflator.js Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -12,21 +12,39 @@ var rfb, mode, test_state, frame_idx, frame_length,
iteration, iterations, istart_time,
// Pre-declarations for jslint
send_array, next_iteration, queue_next_packet, do_packet;
send_array, next_iteration, queue_next_packet, do_packet, enable_test_mode;
// Override send_array
send_array = function (arr) {
// Stub out send_array
};
enable_test_mode = function () {
rfb._sock._mode = VNC_frame_encoding;
rfb._sock.send = send_array;
rfb._sock.close = function () {};
rfb._sock.flush = function () {};
rfb._checkEvents = function () {};
rfb.connect = function (host, port, password, path) {
this._rfb_host = host;
this._rfb_port = port;
this._rfb_password = (password !== undefined) ? password : "";
this._rfb_path = (path !== undefined) ? path : "";
this._sock.init('binary', 'ws');
this._updateState('ProtocolVersion', "Starting VNC handshake");
};
};
next_iteration = function () {
rfb = new RFB({'target': $D('VNC_canvas'),
'onUpdateState': updateState});
enable_test_mode();
if (iteration === 0) {
frame_length = VNC_frame_data.length;
test_state = 'running';
} else {
rfb.disconnect();
}
if (test_state !== 'running') { return; }
iteration += 1;
@@ -91,9 +109,9 @@ do_packet = function () {
for (var i = 0; i < frame.length - start; i++) {
u8[i] = frame.charCodeAt(start + i);
}
rfb.recv_message({'data' : u8});
rfb._sock._recv_message({'data' : u8});
} else {
rfb.recv_message({'data' : frame.slice(start)});
rfb._sock._recv_message({'data' : frame.slice(start)});
}
frame_idx += 1;

View File

@@ -92,6 +92,9 @@ var RFB;
this._fb_height = 0;
this._fb_name = "";
this._destBuff = null;
this._paletteBuff = new Uint8Array(1024); // 256 * 4 (max palette size * max bytes-per-pixel)
this._rre_chunk_sz = 100;
this._timing = {
@@ -128,7 +131,7 @@ var RFB;
'view_only': false, // Disable client mouse/keyboard
'xvp_password_sep': '@', // Separator for XVP password fields
'disconnectTimeout': 3, // Time (s) to wait for disconnection
'wsProtocols': ['binary', 'base64'], // Protocols to use in the WebSocket connection
'wsProtocols': ['binary'], // Protocols to use in the WebSocket connection
'repeaterID': '', // [UltraVNC] RepeaterID to connect to
'viewportDrag': false, // Move the viewport on mouse drags
@@ -217,16 +220,8 @@ var RFB;
Util.Info("Using native WebSockets");
this._updateState('loaded', 'noVNC ready: native WebSockets, ' + rmode);
} else {
Util.Warn("Using web-socket-js bridge. Flash version: " + Util.Flash.version);
if (!Util.Flash || Util.Flash.version < 9) {
this._cleanupSocket('fatal');
throw new Exception("WebSockets or <a href='http://get.adobe.com/flashplayer'>Adobe Flash</a> is required");
} else if (document.location.href.substr(0, 7) === 'file://') {
this._cleanupSocket('fatal');
throw new Exception("'file://' URL is incompatible with Adobe Flash");
} else {
this._updateState('loaded', 'noVNC ready: WebSockets emulation, ' + rmode);
}
this._cleanupSocket('fatal');
throw new Error("WebSocket support is required to use noVNC");
}
Util.Debug("<< RFB.constructor");
@@ -264,14 +259,14 @@ var RFB;
if (this._rfb_state !== 'normal' || this._view_only) { return false; }
Util.Info("Sending Ctrl-Alt-Del");
var arr = [];
arr = arr.concat(RFB.messages.keyEvent(XK_Control_L, 1));
arr = arr.concat(RFB.messages.keyEvent(XK_Alt_L, 1));
arr = arr.concat(RFB.messages.keyEvent(XK_Delete, 1));
arr = arr.concat(RFB.messages.keyEvent(XK_Delete, 0));
arr = arr.concat(RFB.messages.keyEvent(XK_Alt_L, 0));
arr = arr.concat(RFB.messages.keyEvent(XK_Control_L, 0));
this._sock.send(arr);
RFB.messages.keyEvent(this._sock, XK_Control_L, 1);
RFB.messages.keyEvent(this._sock, XK_Alt_L, 1);
RFB.messages.keyEvent(this._sock, XK_Delete, 1);
RFB.messages.keyEvent(this._sock, XK_Delete, 0);
RFB.messages.keyEvent(this._sock, XK_Alt_L, 0);
RFB.messages.keyEvent(this._sock, XK_Control_L, 0);
this._sock.flush();
},
xvpOp: function (ver, op) {
@@ -297,21 +292,22 @@ var RFB;
// followed by an up key.
sendKey: function (code, down) {
if (this._rfb_state !== "normal" || this._view_only) { return false; }
var arr = [];
if (typeof down !== 'undefined') {
Util.Info("Sending key code (" + (down ? "down" : "up") + "): " + code);
arr = arr.concat(RFB.messages.keyEvent(code, down ? 1 : 0));
RFB.messages.keyEvent(this._sock, code, down ? 1 : 0);
} else {
Util.Info("Sending key code (down + up): " + code);
arr = arr.concat(RFB.messages.keyEvent(code, 1));
arr = arr.concat(RFB.messages.keyEvent(code, 0));
RFB.messages.keyEvent(this._sock, code, 1);
RFB.messages.keyEvent(this._sock, code, 0);
}
this._sock.send(arr);
this._sock.flush();
},
clipboardPasteFrom: function (text) {
if (this._rfb_state !== 'normal') { return; }
this._sock.send(RFB.messages.clientCutText(text));
RFB.messages.clientCutText(this._sock, text);
this._sock.flush();
},
setDesktopSize: function (width, height) {
@@ -362,8 +358,6 @@ var RFB;
_init_vars: function () {
// reset state
this._sock.init();
this._FBU.rects = 0;
this._FBU.subrects = 0; // RRE and HEXTILE
this._FBU.lines = 0; // RAW
@@ -380,8 +374,9 @@ var RFB;
}
for (i = 0; i < 4; i++) {
this._FBU.zlibs[i] = new TINF();
this._FBU.zlibs[i].init();
//this._FBU.zlibs[i] = new TINF();
//this._FBU.zlibs[i].init();
this._FBU.zlibs[i] = new inflator.Inflate();
}
},
@@ -578,16 +573,10 @@ var RFB;
}
},
_checkEvents: function () {
if (this._rfb_state === 'normal' && !this._viewportDragging && this._mouse_arr.length > 0) {
this._sock.send(this._mouse_arr);
this._mouse_arr = [];
}
},
_handleKeyPress: function (keysym, down) {
if (this._view_only) { return; } // View only, skip keyboard, events
this._sock.send(RFB.messages.keyEvent(keysym, down));
RFB.messages.keyEvent(this._sock, keysym, down);
this._sock.flush();
},
_handleMouseButton: function (x, y, down, bmask) {
@@ -611,10 +600,8 @@ var RFB;
if (this._view_only) { return; } // View only, skip mouse events
this._mouse_arr = this._mouse_arr.concat(
RFB.messages.pointerEvent(this._display.absX(x), this._display.absY(y), this._mouse_buttonMask));
this._sock.send(this._mouse_arr);
this._mouse_arr = [];
if (this._rfb_state !== "normal") { return; }
RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
},
_handleMouseMove: function (x, y) {
@@ -631,10 +618,8 @@ var RFB;
if (this._view_only) { return; } // View only, skip mouse events
this._mouse_arr = this._mouse_arr.concat(
RFB.messages.pointerEvent(this._display.absX(x), this._display.absY(y), this._mouse_buttonMask));
this._checkEvents();
if (this._rfb_state !== "normal") { return; }
RFB.messages.pointerEvent(this._sock, this._display.absX(x), this._display.absY(y), this._mouse_buttonMask);
},
// Message Handlers
@@ -758,7 +743,8 @@ var RFB;
if (this._sock.rQwait("auth challenge", 16)) { return false; }
var challenge = this._sock.rQshiftBytes(16);
// TODO(directxman12): make genDES not require an Array
var challenge = Array.prototype.slice.call(this._sock.rQshiftBytes(16));
var response = RFB.genDES(this._rfb_password, challenge);
this._sock.send(response);
this._updateState("SecurityResult");
@@ -900,6 +886,7 @@ var RFB;
/* Screen size */
this._fb_width = this._sock.rQshift16();
this._fb_height = this._sock.rQshift16();
this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
/* PIXEL_FORMAT */
var bpp = this._sock.rQshift8();
@@ -995,18 +982,13 @@ var RFB;
this._fb_depth = 1;
}
var response = RFB.messages.pixelFormat(this._fb_Bpp, this._fb_depth, this._true_color);
response = response.concat(
RFB.messages.clientEncodings(this._encodings, this._local_cursor, this._true_color));
response = response.concat(
RFB.messages.fbUpdateRequests(this._display.getCleanDirtyReset(),
this._fb_width, this._fb_height));
RFB.messages.pixelFormat(this._sock, this._fb_Bpp, this._fb_depth, this._true_color);
RFB.messages.clientEncodings(this._sock, this._encodings, this._local_cursor, this._true_color);
RFB.messages.fbUpdateRequests(this._sock, this._display.getCleanDirtyReset(), this._fb_width, this._fb_height);
this._timing.fbu_rt_start = (new Date()).getTime();
this._timing.pixels = 0;
this._sock.send(response);
this._checkEvents();
this._sock.flush();
if (this._encrypt) {
this._updateState('normal', 'Connected (encrypted) to: ' + this._fb_name);
@@ -1108,8 +1090,8 @@ var RFB;
case 0: // FramebufferUpdate
var ret = this._framebufferUpdate();
if (ret) {
this._sock.send(RFB.messages.fbUpdateRequests(this._display.getCleanDirtyReset(),
this._fb_width, this._fb_height));
RFB.messages.fbUpdateRequests(this._sock, this._display.getCleanDirtyReset(), this._fb_width, this._fb_height);
this._sock.flush();
}
return ret;
@@ -1181,7 +1163,14 @@ var RFB;
this._timing.last_fbu = (new Date()).getTime();
ret = this._encHandlers[this._FBU.encoding]();
var handler = this._encHandlers[this._FBU.encoding];
try {
//ret = this._encHandlers[this._FBU.encoding]();
ret = handler();
} catch (ex) {
console.log("missed " + this._FBU.encoding + ": " + handler);
ret = this._encHandlers[this._FBU.encoding]();
}
now = (new Date()).getTime();
this._timing.cur_fbu += (now - this._timing.last_fbu);
@@ -1276,64 +1265,111 @@ var RFB;
// Class Methods
RFB.messages = {
keyEvent: function (keysym, down) {
var arr = [4];
arr.push8(down);
arr.push16(0);
arr.push32(keysym);
return arr;
keyEvent: function (sock, keysym, down) {
var buff = sock._sQ;
var offset = sock._sQlen;
buff[offset] = 4; // msg-type
buff[offset + 1] = down;
buff[offset + 2] = 0;
buff[offset + 3] = 0;
buff[offset + 4] = (keysym >> 24);
buff[offset + 5] = (keysym >> 16);
buff[offset + 6] = (keysym >> 8);
buff[offset + 7] = keysym;
sock._sQlen += 8;
},
pointerEvent: function (x, y, mask) {
var arr = [5]; // msg-type
arr.push8(mask);
arr.push16(x);
arr.push16(y);
return arr;
pointerEvent: function (sock, x, y, mask) {
var buff = sock._sQ;
var offset = sock._sQlen;
buff[offset] = 5; // msg-type
buff[offset + 1] = mask;
buff[offset + 2] = x >> 8;
buff[offset + 3] = x;
buff[offset + 4] = y >> 8;
buff[offset + 5] = y;
sock._sQlen += 6;
},
// TODO(directxman12): make this unicode compatible?
clientCutText: function (text) {
var arr = [6]; // msg-type
arr.push8(0); // padding
arr.push8(0); // padding
arr.push8(0); // padding
arr.push32(text.length);
clientCutText: function (sock, text) {
var buff = sock._sQ;
var offset = sock._sQlen;
buff[offset] = 6; // msg-type
buff[offset + 1] = 0; // padding
buff[offset + 2] = 0; // padding
buff[offset + 3] = 0; // padding
var n = text.length;
buff[offset + 4] = n >> 24;
buff[offset + 5] = n >> 16;
buff[offset + 6] = n >> 8;
buff[offset + 7] = n;
for (var i = 0; i < n; i++) {
arr.push(text.charCodeAt(i));
buff[offset + 8 + i] = text.charCodeAt(i);
}
return arr;
sock._sQlen += 8 + n;
},
pixelFormat: function (bpp, depth, true_color) {
var arr = [0]; // msg-type
arr.push8(0); // padding
arr.push8(0); // padding
arr.push8(0); // padding
pixelFormat: function (sock, bpp, depth, true_color) {
var buff = sock._sQ;
var offset = sock._sQlen;
arr.push8(bpp * 8); // bits-per-pixel
arr.push8(depth * 8); // depth
arr.push8(0); // little-endian
arr.push8(true_color ? 1 : 0); // true-color
buff[offset] = 0; // msg-type
arr.push16(255); // red-max
arr.push16(255); // green-max
arr.push16(255); // blue-max
arr.push8(16); // red-shift
arr.push8(8); // green-shift
arr.push8(0); // blue-shift
buff[offset + 1] = 0; // padding
buff[offset + 2] = 0; // padding
buff[offset + 3] = 0; // padding
arr.push8(0); // padding
arr.push8(0); // padding
arr.push8(0); // padding
return arr;
buff[offset + 4] = bpp * 8; // bits-per-pixel
buff[offset + 5] = depth * 8; // depth
buff[offset + 6] = 0; // little-endian
buff[offset + 7] = true_color ? 1 : 0; // true-color
buff[offset + 8] = 0; // red-max
buff[offset + 9] = 255; // red-max
buff[offset + 10] = 0; // green-max
buff[offset + 11] = 255; // green-max
buff[offset + 12] = 0; // blue-max
buff[offset + 13] = 255; // blue-max
buff[offset + 14] = 16; // red-shift
buff[offset + 15] = 8; // green-shift
buff[offset + 16] = 0; // blue-shift
buff[offset + 17] = 0; // padding
buff[offset + 18] = 0; // padding
buff[offset + 19] = 0; // padding
sock._sQlen += 20;
},
clientEncodings: function (encodings, local_cursor, true_color) {
var i, encList = [];
clientEncodings: function (sock, encodings, local_cursor, true_color) {
var buff = sock._sQ;
var offset = sock._sQlen;
buff[offset] = 2; // msg-type
buff[offset + 1] = 0; // padding
// offset + 2 and offset + 3 are encoding count
var i, j = offset + 4, cnt = 0;
for (i = 0; i < encodings.length; i++) {
if (encodings[i][0] === "Cursor" && !local_cursor) {
Util.Debug("Skipping Cursor pseudo-encoding");
@@ -1341,23 +1377,25 @@ var RFB;
// TODO: remove this when we have tight+non-true-color
Util.Warn("Skipping tight as it is only supported with true color");
} else {
encList.push(encodings[i][1]);
var enc = encodings[i][1];
buff[j] = enc >> 24;
buff[j + 1] = enc >> 16;
buff[j + 2] = enc >> 8;
buff[j + 3] = enc;
j += 4;
cnt++;
}
}
var arr = [2]; // msg-type
arr.push8(0); // padding
buff[offset + 2] = cnt >> 8;
buff[offset + 3] = cnt;
arr.push16(encList.length); // encoding count
for (i = 0; i < encList.length; i++) {
arr.push32(encList[i]);
}
return arr;
sock._sQlen += j - offset;
},
fbUpdateRequests: function (cleanDirty, fb_width, fb_height) {
var arr = [];
fbUpdateRequests: function (sock, cleanDirty, fb_width, fb_height) {
var offsetIncrement = 0;
var cb = cleanDirty.cleanBox;
var w, h;
@@ -1365,7 +1403,7 @@ var RFB;
w = typeof cb.w === "undefined" ? fb_width : cb.w;
h = typeof cb.h === "undefined" ? fb_height : cb.h;
// Request incremental for clean box
arr = arr.concat(RFB.messages.fbUpdateRequest(1, cb.x, cb.y, w, h));
RFB.messages.fbUpdateRequest(sock, 1, cb.x, cb.y, w, h);
}
for (var i = 0; i < cleanDirty.dirtyBoxes.length; i++) {
@@ -1373,24 +1411,33 @@ var RFB;
// Force all (non-incremental) for dirty box
w = typeof db.w === "undefined" ? fb_width : db.w;
h = typeof db.h === "undefined" ? fb_height : db.h;
arr = arr.concat(RFB.messages.fbUpdateRequest(0, db.x, db.y, w, h));
RFB.messages.fbUpdateRequest(sock, 0, db.x, db.y, w, h);
}
return arr;
},
fbUpdateRequest: function (incremental, x, y, w, h) {
fbUpdateRequest: function (sock, incremental, x, y, w, h) {
var buff = sock._sQ;
var offset = sock._sQlen;
if (typeof(x) === "undefined") { x = 0; }
if (typeof(y) === "undefined") { y = 0; }
var arr = [3]; // msg-type
arr.push8(incremental);
arr.push16(x);
arr.push16(y);
arr.push16(w);
arr.push16(h);
buff[offset] = 3; // msg-type
buff[offset + 1] = incremental;
return arr;
buff[offset + 2] = (x >> 8) & 0xFF;
buff[offset + 3] = x & 0xFF;
buff[offset + 4] = (y >> 8) & 0xFF;
buff[offset + 5] = y & 0xFF;
buff[offset + 6] = (w >> 8) & 0xFF;
buff[offset + 7] = w & 0xFF;
buff[offset + 8] = (h >> 8) & 0xFF;
buff[offset + 9] = h & 0xFF;
sock._sQlen += 10;
}
};
@@ -1436,15 +1483,10 @@ var RFB;
COPYRECT: function () {
this._FBU.bytes = 4;
if (this._sock.rQwait("COPYRECT", 4)) { return false; }
this._display.renderQ_push({
'type': 'copy',
'old_x': this._sock.rQshift16(),
'old_y': this._sock.rQshift16(),
'x': this._FBU.x,
'y': this._FBU.y,
'width': this._FBU.width,
'height': this._FBU.height
});
this._display.copyImage(this._sock.rQshift16(), this._sock.rQshift16(),
this._FBU.x, this._FBU.y, this._FBU.width,
this._FBU.height);
this._FBU.rects--;
this._FBU.bytes = 0;
return true;
@@ -1549,11 +1591,21 @@ var RFB;
rQi += this._FBU.bytes - 1;
} else {
if (this._FBU.subencoding & 0x02) { // Background
this._FBU.background = rQ.slice(rQi, rQi + this._fb_Bpp);
if (this._fb_Bpp == 1) {
this._FBU.background = rQ[rQi];
} else {
// fb_Bpp is 4
this._FBU.background = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
}
rQi += this._fb_Bpp;
}
if (this._FBU.subencoding & 0x04) { // Foreground
this._FBU.foreground = rQ.slice(rQi, rQi + this._fb_Bpp);
if (this._fb_Bpp == 1) {
this._FBU.foreground = rQ[rQi];
} else {
// this._fb_Bpp is 4
this._FBU.foreground = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
}
rQi += this._fb_Bpp;
}
@@ -1565,7 +1617,12 @@ var RFB;
for (var s = 0; s < subrects; s++) {
var color;
if (this._FBU.subencoding & 0x10) { // SubrectsColoured
color = rQ.slice(rQi, rQi + this._fb_Bpp);
if (this._fb_Bpp === 1) {
color = rQ[rQi];
} else {
// _fb_Bpp is 4
color = [rQ[rQi], rQ[rQi + 1], rQ[rQi + 2], rQ[rQi + 3]];
}
rQi += this._fb_Bpp;
} else {
color = this._FBU.foreground;
@@ -1639,61 +1696,96 @@ var RFB;
}
}
var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
if (uncompressed.status !== 0) {
//var uncompressed = this._FBU.zlibs[streamId].uncompress(data, 0);
var uncompressed = this._FBU.zlibs[streamId].inflate(data, true);
/*if (uncompressed.status !== 0) {
Util.Error("Invalid data in zlib stream");
}
}*/
return uncompressed.data;
//return uncompressed.data;
return uncompressed;
}.bind(this);
var indexedToRGB = function (data, numColors, palette, width, height) {
var indexedToRGBX2Color = function (data, palette, width, height) {
// Convert indexed (palette based) image data to RGB
// TODO: reduce number of calculations inside loop
var dest = [];
var x, y, dp, sp;
if (numColors === 2) {
var w = Math.floor((width + 7) / 8);
var w1 = Math.floor(width / 8);
var dest = this._destBuff;
var w = Math.floor((width + 7) / 8);
var w1 = Math.floor(width / 8);
for (y = 0; y < height; y++) {
var b;
for (x = 0; x < w1; x++) {
for (b = 7; b >= 0; b--) {
dp = (y * width + x * 8 + 7 - b) * 3;
sp = (data[y * w + x] >> b & 1) * 3;
dest[dp] = palette[sp];
dest[dp + 1] = palette[sp + 1];
dest[dp + 2] = palette[sp + 2];
}
/*for (var y = 0; y < height; y++) {
var b, x, dp, sp;
var yoffset = y * width;
var ybitoffset = y * w;
var xoffset, targetbyte;
for (x = 0; x < w1; x++) {
xoffset = yoffset + x * 8;
targetbyte = data[ybitoffset + x];
for (b = 7; b >= 0; b--) {
dp = (xoffset + 7 - b) * 3;
sp = (targetbyte >> b & 1) * 3;
dest[dp] = palette[sp];
dest[dp + 1] = palette[sp + 1];
dest[dp + 2] = palette[sp + 2];
}
}
for (b = 7; b >= 8 - width % 8; b--) {
dp = (y * width + x * 8 + 7 - b) * 3;
xoffset = yoffset + x * 8;
targetbyte = data[ybitoffset + x];
for (b = 7; b >= 8 - width % 8; b--) {
dp = (xoffset + 7 - b) * 3;
sp = (targetbyte >> b & 1) * 3;
dest[dp] = palette[sp];
dest[dp + 1] = palette[sp + 1];
dest[dp + 2] = palette[sp + 2];
}
}*/
for (var y = 0; y < height; y++) {
var b, x, dp, sp;
for (x = 0; x < w1; x++) {
for (b = 7; b >= 0; b--) {
dp = (y * width + x * 8 + 7 - b) * 4;
sp = (data[y * w + x] >> b & 1) * 3;
dest[dp] = palette[sp];
dest[dp + 1] = palette[sp + 1];
dest[dp + 2] = palette[sp + 2];
dest[dp + 3] = 255;
}
}
} else {
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
dp = (y * width + x) * 3;
sp = data[y * width + x] * 3;
dest[dp] = palette[sp];
dest[dp + 1] = palette[sp + 1];
dest[dp + 2] = palette[sp + 2];
}
for (b = 7; b >= 8 - width % 8; b--) {
dp = (y * width + x * 8 + 7 - b) * 4;
sp = (data[y * w + x] >> b & 1) * 3;
dest[dp] = palette[sp];
dest[dp + 1] = palette[sp + 1];
dest[dp + 2] = palette[sp + 2];
dest[dp + 3] = 255;
}
}
return dest;
}.bind(this);
var indexedToRGBX = function (data, palette, width, height) {
// Convert indexed (palette based) image data to RGB
var dest = this._destBuff;
var total = width * height * 4;
for (var i = 0, j = 0; i < total; i += 4, j++) {
var sp = data[j] * 3;
dest[i] = palette[sp];
dest[i + 1] = palette[sp + 1];
dest[i + 2] = palette[sp + 2];
dest[i + 3] = 255;
}
return dest;
}.bind(this);
var rQ = this._sock.get_rQ();
var rQi = this._sock.get_rQi();
var cmode, clength, data;
var cmode, data;
var cl_header, cl_data;
var handlePalette = function () {
var numColors = rQ[rQi + 2] + 1;
@@ -1706,37 +1798,51 @@ var RFB;
var raw = false;
if (rowSize * this._FBU.height < 12) {
raw = true;
clength = [0, rowSize * this._FBU.height];
cl_header = 0;
cl_data = rowSize * this._FBU.height;
//clength = [0, rowSize * this._FBU.height];
} else {
clength = RFB.encodingHandlers.getTightCLength(this._sock.rQslice(3 + paletteSize,
3 + paletteSize + 3));
// begin inline getTightCLength (returning two-item arrays is bad for performance with GC)
var cl_offset = rQi + 3 + paletteSize;
cl_header = 1;
cl_data = 0;
cl_data += rQ[cl_offset] & 0x7f;
if (rQ[cl_offset] & 0x80) {
cl_header++;
cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
if (rQ[cl_offset + 1] & 0x80) {
cl_header++;
cl_data += rQ[cl_offset + 2] << 14;
}
}
// end inline getTightCLength
}
this._FBU.bytes += clength[0] + clength[1];
this._FBU.bytes += cl_header + cl_data;
if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
// Shift ctl, filter id, num colors, palette entries, and clength off
this._sock.rQskipBytes(3);
var palette = this._sock.rQshiftBytes(paletteSize);
this._sock.rQskipBytes(clength[0]);
//var palette = this._sock.rQshiftBytes(paletteSize);
this._sock.rQshiftTo(this._paletteBuff, paletteSize);
this._sock.rQskipBytes(cl_header);
if (raw) {
data = this._sock.rQshiftBytes(clength[1]);
data = this._sock.rQshiftBytes(cl_data);
} else {
data = decompress(this._sock.rQshiftBytes(clength[1]));
data = decompress(this._sock.rQshiftBytes(cl_data));
}
// Convert indexed (palette based) image data to RGB
var rgb = indexedToRGB(data, numColors, palette, this._FBU.width, this._FBU.height);
var rgbx;
if (numColors == 2) {
rgbx = indexedToRGBX2Color(data, this._paletteBuff, this._FBU.width, this._FBU.height);
this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
} else {
rgbx = indexedToRGBX(data, this._paletteBuff, this._FBU.width, this._FBU.height);
this._display.blitRgbxImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, rgbx, 0, false);
}
this._display.renderQ_push({
'type': 'blitRgb',
'data': rgb,
'x': this._FBU.x,
'y': this._FBU.y,
'width': this._FBU.width,
'height': this._FBU.height
});
return true;
}.bind(this);
@@ -1746,30 +1852,37 @@ var RFB;
var uncompressedSize = this._FBU.width * this._FBU.height * this._fb_depth;
if (uncompressedSize < 12) {
raw = true;
clength = [0, uncompressedSize];
cl_header = 0;
cl_data = uncompressedSize;
} else {
clength = RFB.encodingHandlers.getTightCLength(this._sock.rQslice(1, 4));
// begin inline getTightCLength (returning two-item arrays is for peformance with GC)
var cl_offset = rQi + 1;
cl_header = 1;
cl_data = 0;
cl_data += rQ[cl_offset] & 0x7f;
if (rQ[cl_offset] & 0x80) {
cl_header++;
cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
if (rQ[cl_offset + 1] & 0x80) {
cl_header++;
cl_data += rQ[cl_offset + 2] << 14;
}
}
// end inline getTightCLength
}
this._FBU.bytes = 1 + clength[0] + clength[1];
this._FBU.bytes = 1 + cl_header + cl_data;
if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
// Shift ctl, clength off
this._sock.rQshiftBytes(1 + clength[0]);
this._sock.rQshiftBytes(1 + cl_header);
if (raw) {
data = this._sock.rQshiftBytes(clength[1]);
data = this._sock.rQshiftBytes(cl_data);
} else {
data = decompress(this._sock.rQshiftBytes(clength[1]));
data = decompress(this._sock.rQshiftBytes(cl_data));
}
this._display.renderQ_push({
'type': 'blitRgb',
'data': data,
'x': this._FBU.x,
'y': this._FBU.y,
'width': this._FBU.width,
'height': this._FBU.height
});
this._display.blitRgbImage(this._FBU.x, this._FBU.y, this._FBU.width, this._FBU.height, data, 0, false);
return true;
}.bind(this);
@@ -1817,28 +1930,34 @@ var RFB;
// Determine FBU.bytes
switch (cmode) {
case "fill":
this._sock.rQskip8(); // shift off ctl
var color = this._sock.rQshiftBytes(this._fb_depth);
this._display.renderQ_push({
'type': 'fill',
'x': this._FBU.x,
'y': this._FBU.y,
'width': this._FBU.width,
'height': this._FBU.height,
'color': [color[2], color[1], color[0]]
});
// skip ctl byte
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);
this._sock.rQskipBytes(4);
break;
case "png":
case "jpeg":
clength = RFB.encodingHandlers.getTightCLength(this._sock.rQslice(1, 4));
this._FBU.bytes = 1 + clength[0] + clength[1]; // ctl + clength size + jpeg-data
// begin inline getTightCLength (returning two-item arrays is for peformance with GC)
var cl_offset = rQi + 1;
cl_header = 1;
cl_data = 0;
cl_data += rQ[cl_offset] & 0x7f;
if (rQ[cl_offset] & 0x80) {
cl_header++;
cl_data += (rQ[cl_offset + 1] & 0x7f) << 7;
if (rQ[cl_offset + 1] & 0x80) {
cl_header++;
cl_data += rQ[cl_offset + 2] << 14;
}
}
// end inline getTightCLength
this._FBU.bytes = 1 + cl_header + cl_data; // ctl + clength size + jpeg-data
if (this._sock.rQwait("TIGHT " + cmode, this._FBU.bytes)) { return false; }
// We have everything, render it
this._sock.rQskipBytes(1 + clength[0]); // shift off clt + compact length
this._sock.rQskipBytes(1 + cl_header); // shift off clt + compact length
var img = new Image();
img.src = "data: image/" + cmode +
RFB.extract_data_uri(this._sock.rQshiftBytes(clength[1]));
RFB.extract_data_uri(this._sock.rQshiftBytes(cl_data));
this._display.renderQ_push({
'type': 'img',
'img': img,
@@ -1881,6 +2000,7 @@ var RFB;
handle_FB_resize: function () {
this._fb_width = this._FBU.width;
this._fb_height = this._FBU.height;
this._destBuff = new Uint8Array(this._fb_width * this._fb_height * 4);
this._display.resize(this._fb_width, this._fb_height);
this._onFBResize(this, this._fb_width, this._fb_height);
this._timing.fbu_rt_start = (new Date()).getTime();
@@ -1903,9 +2023,9 @@ var RFB;
this._sock.rQskipBytes(1); // number-of-screens
this._sock.rQskipBytes(3); // padding
for (var i=0; i<number_of_screens; i += 1) {
for (var i = 0; i < number_of_screens; i += 1) {
// Save the id and flags of the first screen
if (i == 0) {
if (i === 0) {
this._screen_id = this._sock.rQshiftBytes(4); // id
this._sock.rQskipBytes(2); // x-position
this._sock.rQskipBytes(2); // y-position
@@ -1926,7 +2046,7 @@ var RFB;
*/
// We need to handle errors when we requested the resize.
if (this._FBU.x == 1 && this._FBU.y != 0) {
if (this._FBU.x === 1 && this._FBU.y !== 0) {
var msg = "";
// The y-position indicates the status code from the server
switch (this._FBU.y) {

View File

@@ -21,7 +21,7 @@ var UI;
window.onscriptsload = function () { UI.load(); };
Util.load_scripts(["webutil.js", "base64.js", "websock.js", "des.js",
"keysymdef.js", "keyboard.js", "input.js", "display.js",
"jsunzip.js", "rfb.js", "keysym.js"]);
"rfb.js", "keysym.js", "inflator.js"]);
UI = {

View File

@@ -1,109 +0,0 @@
* How to try
Assuming you have Web server (e.g. Apache) running at http://example.com/ .
- Download web_socket.rb from:
http://github.com/gimite/web-socket-ruby/tree/master
- Run sample Web Socket server (echo server) in example.com with: (#1)
$ ruby web-socket-ruby/samples/echo_server.rb example.com 10081
- If your server already provides socket policy file at port 843, modify the file to allow access to port 10081. Otherwise you can skip this step. See below for details.
- Publish the web-socket-js directory with your Web server (e.g. put it in ~/public_html).
- Change ws://localhost:10081 to ws://example.com:10081 in sample.html.
- Open sample.html in your browser.
- After "onopen" is shown, input something, click [Send] and confirm echo back.
#1: First argument of echo_server.rb means that it accepts Web Socket connection from HTML pages in example.com.
* Troubleshooting
If it doesn't work, try these:
1. Try Chrome and Firefox 3.x.
- It doesn't work on Chrome:
-- It's likely an issue of your code or the server. Debug your code as usual e.g. using console.log.
- It works on Chrome but it doesn't work on Firefox:
-- It's likely an issue of web-socket-js specific configuration (e.g. 3 and 4 below).
- It works on both Chrome and Firefox, but it doesn't work on your browser:
-- Check "Supported environment" section below. Your browser may not be supported by web-socket-js.
2. Add this line before your code:
WEB_SOCKET_DEBUG = true;
and use Developer Tools (Chrome/Safari) or Firebug (Firefox) to see if console.log outputs any errors.
3. Make sure you do NOT open your HTML page as local file e.g. file:///.../sample.html. web-socket-js doesn't work on local file. Open it via Web server e.g. http:///.../sample.html.
4. If you are NOT using web-socket-ruby as your WebSocket server, you need to place Flash socket policy file on your server. See "Flash socket policy file" section below for details.
5. Check if sample.html bundled with web-socket-js works.
6. Make sure the port used for WebSocket (10081 in example above) is not blocked by your server/client's firewall.
7. Install debugger version of Flash Player available here to see Flash errors:
http://www.adobe.com/support/flashplayer/downloads.html
* Supported environments
It should work on:
- Google Chrome 4 or later (just uses native implementation)
- Firefox 3.x, Internet Explorer 8 + Flash Player 9 or later
It may or may not work on other browsers such as Safari, Opera or IE 6. Patch for these browsers are appreciated, but I will not work on fixing issues specific to these browsers by myself.
* Flash socket policy file
This implementation uses Flash's socket, which means that your server must provide Flash socket policy file to declare the server accepts connections from Flash.
If you use web-socket-ruby available at
http://github.com/gimite/web-socket-ruby/tree/master
, you don't need anything special, because web-socket-ruby handles Flash socket policy file request. But if you already provide socket policy file at port 843, you need to modify the file to allow access to Web Socket port, because it precedes what web-socket-ruby provides.
If you use other Web Socket server implementation, you need to provide socket policy file yourself. See
http://www.lightsphere.com/dev/articles/flash_socket_policy.html
for details and sample script to run socket policy file server. node.js implementation is available here:
http://github.com/LearnBoost/Socket.IO-node/blob/master/lib/socket.io/transports/flashsocket.js
Actually, it's still better to provide socket policy file at port 843 even if you use web-socket-ruby. Flash always try to connect to port 843 first, so providing the file at port 843 makes startup faster.
* Cookie considerations
Cookie is sent if Web Socket host is the same as the origin of JavaScript. Otherwise it is not sent, because I don't know way to send right Cookie (which is Cookie of the host of Web Socket, I heard).
Note that it's technically possible that client sends arbitrary string as Cookie and any other headers (by modifying this library for example) once you place Flash socket policy file in your server. So don't trust Cookie and other headers if you allow connection from untrusted origin.
* Proxy considerations
The WebSocket spec (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol) specifies instructions for User Agents to support proxied connections by implementing the HTTP CONNECT method.
The AS3 Socket class doesn't implement this mechanism, which renders it useless for the scenarios where the user trying to open a socket is behind a proxy.
The class RFC2817Socket (by Christian Cantrell) effectively lets us implement this, as long as the proxy settings are known and provided by the interface that instantiates the WebSocket. As such, if you want to support proxied conncetions, you'll have to supply this information to the WebSocket constructor when Flash is being used. One way to go about it would be to ask the user for proxy settings information if the initial connection fails.
* How to host HTML file and SWF file in different domains
By default, HTML file and SWF file must be in the same domain. You can follow steps below to allow hosting them in different domain.
WARNING: If you use the method below, HTML files in ANY domains can send arbitrary TCP data to your WebSocket server, regardless of configuration in Flash socket policy file. Arbitrary TCP data means that they can even fake request headers including Origin and Cookie.
- Unzip WebSocketMainInsecure.zip to extract WebSocketMainInsecure.swf.
- Put WebSocketMainInsecure.swf on your server, instead of WebSocketMain.swf.
- In JavaScript, set WEB_SOCKET_SWF_LOCATION to URL of your WebSocketMainInsecure.swf.
* How to build WebSocketMain.swf
Install Flex 4 SDK:
http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4
$ cd flash-src
$ ./build.sh
* License
New BSD License.

File diff suppressed because one or more lines are too long

View File

@@ -1,391 +0,0 @@
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// License: New BSD License
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/rfc6455
(function() {
if (window.WEB_SOCKET_FORCE_FLASH) {
// Keeps going.
} else if (window.WebSocket) {
return;
} else if (window.MozWebSocket) {
// Firefox.
window.WebSocket = MozWebSocket;
return;
}
var logger;
if (window.WEB_SOCKET_LOGGER) {
logger = WEB_SOCKET_LOGGER;
} else if (window.console && window.console.log && window.console.error) {
// In some environment, console is defined but console.log or console.error is missing.
logger = window.console;
} else {
logger = {log: function(){ }, error: function(){ }};
}
// swfobject.hasFlashPlayerVersion("10.0.0") doesn't work with Gnash.
if (swfobject.getFlashPlayerVersion().major < 10) {
logger.error("Flash Player >= 10.0.0 is required.");
return;
}
if (location.protocol == "file:") {
logger.error(
"WARNING: web-socket-js doesn't work in file:///... URL " +
"unless you set Flash Security Settings properly. " +
"Open the page via Web server i.e. http://...");
}
/**
* Our own implementation of WebSocket class using Flash.
* @param {string} url
* @param {array or string} protocols
* @param {string} proxyHost
* @param {int} proxyPort
* @param {string} headers
*/
window.WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
var self = this;
self.__id = WebSocket.__nextId++;
WebSocket.__instances[self.__id] = self;
self.readyState = WebSocket.CONNECTING;
self.bufferedAmount = 0;
self.__events = {};
if (!protocols) {
protocols = [];
} else if (typeof protocols == "string") {
protocols = [protocols];
}
// Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
// Otherwise, when onopen fires immediately, onopen is called before it is set.
self.__createTask = setTimeout(function() {
WebSocket.__addTask(function() {
self.__createTask = null;
WebSocket.__flash.create(
self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
});
}, 0);
};
/**
* Send data to the web socket.
* @param {string} data The data to send to the socket.
* @return {boolean} True for success, false for failure.
*/
WebSocket.prototype.send = function(data) {
if (this.readyState == WebSocket.CONNECTING) {
throw "INVALID_STATE_ERR: Web Socket connection has not been established";
}
// We use encodeURIComponent() here, because FABridge doesn't work if
// the argument includes some characters. We don't use escape() here
// because of this:
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
// But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
// preserve all Unicode characters either e.g. "\uffff" in Firefox.
// Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
// additional testing.
var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
if (result < 0) { // success
return true;
} else {
this.bufferedAmount += result;
return false;
}
};
/**
* Close this web socket gracefully.
*/
WebSocket.prototype.close = function() {
if (this.__createTask) {
clearTimeout(this.__createTask);
this.__createTask = null;
this.readyState = WebSocket.CLOSED;
return;
}
if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
return;
}
this.readyState = WebSocket.CLOSING;
WebSocket.__flash.close(this.__id);
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {string} type
* @param {function} listener
* @param {boolean} useCapture
* @return void
*/
WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
if (!(type in this.__events)) {
this.__events[type] = [];
}
this.__events[type].push(listener);
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {string} type
* @param {function} listener
* @param {boolean} useCapture
* @return void
*/
WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
if (!(type in this.__events)) return;
var events = this.__events[type];
for (var i = events.length - 1; i >= 0; --i) {
if (events[i] === listener) {
events.splice(i, 1);
break;
}
}
};
/**
* Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
*
* @param {Event} event
* @return void
*/
WebSocket.prototype.dispatchEvent = function(event) {
var events = this.__events[event.type] || [];
for (var i = 0; i < events.length; ++i) {
events[i](event);
}
var handler = this["on" + event.type];
if (handler) handler.apply(this, [event]);
};
/**
* Handles an event from Flash.
* @param {Object} flashEvent
*/
WebSocket.prototype.__handleEvent = function(flashEvent) {
if ("readyState" in flashEvent) {
this.readyState = flashEvent.readyState;
}
if ("protocol" in flashEvent) {
this.protocol = flashEvent.protocol;
}
var jsEvent;
if (flashEvent.type == "open" || flashEvent.type == "error") {
jsEvent = this.__createSimpleEvent(flashEvent.type);
} else if (flashEvent.type == "close") {
jsEvent = this.__createSimpleEvent("close");
jsEvent.wasClean = flashEvent.wasClean ? true : false;
jsEvent.code = flashEvent.code;
jsEvent.reason = flashEvent.reason;
} else if (flashEvent.type == "message") {
var data = decodeURIComponent(flashEvent.message);
jsEvent = this.__createMessageEvent("message", data);
} else {
throw "unknown event type: " + flashEvent.type;
}
this.dispatchEvent(jsEvent);
};
WebSocket.prototype.__createSimpleEvent = function(type) {
if (document.createEvent && window.Event) {
var event = document.createEvent("Event");
event.initEvent(type, false, false);
return event;
} else {
return {type: type, bubbles: false, cancelable: false};
}
};
WebSocket.prototype.__createMessageEvent = function(type, data) {
if (document.createEvent && window.MessageEvent && !window.opera) {
var event = document.createEvent("MessageEvent");
event.initMessageEvent("message", false, false, data, null, null, window, null);
return event;
} else {
// IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
return {type: type, data: data, bubbles: false, cancelable: false};
}
};
/**
* Define the WebSocket readyState enumeration.
*/
WebSocket.CONNECTING = 0;
WebSocket.OPEN = 1;
WebSocket.CLOSING = 2;
WebSocket.CLOSED = 3;
// Field to check implementation of WebSocket.
WebSocket.__isFlashImplementation = true;
WebSocket.__initialized = false;
WebSocket.__flash = null;
WebSocket.__instances = {};
WebSocket.__tasks = [];
WebSocket.__nextId = 0;
/**
* Load a new flash security policy file.
* @param {string} url
*/
WebSocket.loadFlashPolicyFile = function(url){
WebSocket.__addTask(function() {
WebSocket.__flash.loadManualPolicyFile(url);
});
};
/**
* Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
*/
WebSocket.__initialize = function() {
if (WebSocket.__initialized) return;
WebSocket.__initialized = true;
if (WebSocket.__swfLocation) {
// For backword compatibility.
window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
}
if (!window.WEB_SOCKET_SWF_LOCATION) {
logger.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
return;
}
if (!window.WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR &&
!WEB_SOCKET_SWF_LOCATION.match(/(^|\/)WebSocketMainInsecure\.swf(\?.*)?$/) &&
WEB_SOCKET_SWF_LOCATION.match(/^\w+:\/\/([^\/]+)/)) {
var swfHost = RegExp.$1;
if (location.host != swfHost) {
logger.error(
"[WebSocket] You must host HTML and WebSocketMain.swf in the same host " +
"('" + location.host + "' != '" + swfHost + "'). " +
"See also 'How to host HTML file and SWF file in different domains' section " +
"in README.md. If you use WebSocketMainInsecure.swf, you can suppress this message " +
"by WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR = true;");
}
}
var container = document.createElement("div");
container.id = "webSocketContainer";
// Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
// Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
// But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
// Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
// the best we can do as far as we know now.
container.style.position = "absolute";
if (WebSocket.__isFlashLite()) {
container.style.left = "0px";
container.style.top = "0px";
} else {
container.style.left = "-100px";
container.style.top = "-100px";
}
var holder = document.createElement("div");
holder.id = "webSocketFlash";
container.appendChild(holder);
document.body.appendChild(container);
// See this article for hasPriority:
// http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
swfobject.embedSWF(
WEB_SOCKET_SWF_LOCATION,
"webSocketFlash",
"1" /* width */,
"1" /* height */,
"10.0.0" /* SWF version */,
null,
null,
{hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
null,
function(e) {
if (!e.success) {
logger.error("[WebSocket] swfobject.embedSWF failed");
}
}
);
};
/**
* Called by Flash to notify JS that it's fully loaded and ready
* for communication.
*/
WebSocket.__onFlashInitialized = function() {
// We need to set a timeout here to avoid round-trip calls
// to flash during the initialization process.
setTimeout(function() {
WebSocket.__flash = document.getElementById("webSocketFlash");
WebSocket.__flash.setCallerUrl(location.href);
WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
for (var i = 0; i < WebSocket.__tasks.length; ++i) {
WebSocket.__tasks[i]();
}
WebSocket.__tasks = [];
}, 0);
};
/**
* Called by Flash to notify WebSockets events are fired.
*/
WebSocket.__onFlashEvent = function() {
setTimeout(function() {
try {
// Gets events using receiveEvents() instead of getting it from event object
// of Flash event. This is to make sure to keep message order.
// It seems sometimes Flash events don't arrive in the same order as they are sent.
var events = WebSocket.__flash.receiveEvents();
for (var i = 0; i < events.length; ++i) {
WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
}
} catch (e) {
logger.error(e);
}
}, 0);
return true;
};
// Called by Flash.
WebSocket.__log = function(message) {
logger.log(decodeURIComponent(message));
};
// Called by Flash.
WebSocket.__error = function(message) {
logger.error(decodeURIComponent(message));
};
WebSocket.__addTask = function(task) {
if (WebSocket.__flash) {
task();
} else {
WebSocket.__tasks.push(task);
}
};
/**
* Test if the browser is running flash lite.
* @return {boolean} True if flash lite is running, false otherwise.
*/
WebSocket.__isFlashLite = function() {
if (!window.navigator || !window.navigator.mimeTypes) {
return false;
}
var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
return false;
}
return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
};
if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
// NOTE:
// This fires immediately if web_socket.js is dynamically loaded after
// the document is loaded.
swfobject.addDomLoadEvent(function() {
WebSocket.__initialize();
});
}
})();

View File

@@ -15,7 +15,7 @@
*/
/*jslint browser: true, bitwise: true */
/*global Util, Base64 */
/*global Util*/
// Load Flash WebSocket emulator if needed
@@ -34,29 +34,26 @@ if (window.WebSocket && !window.WEB_SOCKET_FORCE_FLASH) {
/* no builtin WebSocket so load web_socket.js */
Websock_native = false;
(function () {
window.WEB_SOCKET_SWF_LOCATION = Util.get_include_uri() +
"web-socket-js/WebSocketMain.swf";
if (Util.Engine.trident) {
Util.Debug("Forcing uncached load of WebSocketMain.swf");
window.WEB_SOCKET_SWF_LOCATION += "?" + Math.random();
}
Util.load_scripts(["web-socket-js/swfobject.js",
"web-socket-js/web_socket.js"]);
})();
}
function Websock() {
"use strict";
this._websocket = null; // WebSocket object
this._rQ = []; // Receive queue
this._rQi = 0; // Receive queue index
this._rQmax = 10000; // Max receive queue size before compacting
this._sQ = []; // Send queue
this._mode = 'base64'; // Current WebSocket mode: 'binary', 'base64'
this._rQi = 0; // Receive queue index
this._rQlen = 0; // Next write position in the receive queue
this._rQbufferSize = 1024 * 1024 * 4; // Receive queue buffer size (4 MiB)
this._rQmax = this._rQbufferSize / 8;
// called in init: this._rQ = new Uint8Array(this._rQbufferSize);
this._rQ = null; // Receive queue
this._sQbufferSize = 1024 * 10; // 10 KiB
// called in init: this._sQ = new Uint8Array(this._sQbufferSize);
this._sQlen = 0;
this._sQ = null; // Send queue
this._mode = 'binary'; // Current WebSocket mode: 'binary', 'base64'
this.maxBufferedAmount = 200;
this._eventHandlers = {
@@ -69,6 +66,22 @@ function Websock() {
(function () {
"use strict";
var typedArrayToString = (function () {
// This is only for PhantomJS, which doesn't like apply-ing
// with Typed Arrays
try {
var arr = new Uint8Array([1, 2, 3]);
String.fromCharCode.apply(null, arr);
return function (a) { return String.fromCharCode.apply(null, a); };
} catch (ex) {
return function (a) {
return String.fromCharCode.apply(
null, Array.prototype.slice.call(a));
};
}
})();
Websock.prototype = {
// Getters and Setters
get_sQ: function () {
@@ -89,7 +102,7 @@ function Websock() {
// Receive Queue
rQlen: function () {
return this._rQ.length - this._rQi;
return this._rQlen - this._rQi;
},
rQpeek8: function () {
@@ -108,15 +121,7 @@ function Websock() {
this._rQi += num;
},
rQunshift8: function (num) {
if (this._rQi === 0) {
this._rQ.unshift(num);
} else {
this._rQi--;
this._rQ[this._rQi] = num;
}
},
// TODO(directxman12): test performance with these vs a DataView
rQshift16: function () {
return (this._rQ[this._rQi++] << 8) +
this._rQ[this._rQi++];
@@ -131,22 +136,29 @@ function Websock() {
rQshiftStr: function (len) {
if (typeof(len) === 'undefined') { len = this.rQlen(); }
var arr = this._rQ.slice(this._rQi, this._rQi + len);
var arr = new Uint8Array(this._rQ.buffer, this._rQi, len);
this._rQi += len;
return String.fromCharCode.apply(null, arr);
return typedArrayToString(arr);
},
rQshiftBytes: function (len) {
if (typeof(len) === 'undefined') { len = this.rQlen(); }
this._rQi += len;
return this._rQ.slice(this._rQi - len, this._rQi);
return new Uint8Array(this._rQ.buffer, this._rQi - len, len);
},
rQshiftTo: function (target, len) {
if (len === undefined) { len = this.rQlen(); }
// TODO: make this just use set with views when using a ArrayBuffer to store the rQ
target.set(new Uint8Array(this._rQ.buffer, this._rQi, len));
this._rQi += len;
},
rQslice: function (start, end) {
if (end) {
return this._rQ.slice(this._rQi + start, this._rQi + end);
return new Uint8Array(this._rQ.buffer, this._rQi + start, end - start);
} else {
return this._rQ.slice(this._rQi + start);
return new Uint8Array(this._rQ.buffer, this._rQi + start, this._rQlen - this._rQi - start);
}
},
@@ -154,7 +166,7 @@ function Websock() {
// to be available in the receive queue. Return true if we need to
// wait (and possibly print a debug message), otherwise false.
rQwait: function (msg, num, goback) {
var rQlen = this._rQ.length - this._rQi; // Skip rQlen() function call
var rQlen = this._rQlen - this._rQi; // Skip rQlen() function call
if (rQlen < num) {
if (goback) {
if (this._rQi < goback) {
@@ -175,9 +187,9 @@ function Websock() {
}
if (this._websocket.bufferedAmount < this.maxBufferedAmount) {
if (this._sQ.length > 0) {
if (this._sQlen > 0) {
this._websocket.send(this._encode_message());
this._sQ = [];
this._sQlen = 0;
}
return true;
@@ -189,8 +201,9 @@ function Websock() {
},
send: function (arr) {
this._sQ = this._sQ.concat(arr);
return this.flush();
this._sQ.set(arr, this._sQlen);
this._sQlen += arr.length;
return this.flush();
},
send_string: function (str) {
@@ -208,10 +221,14 @@ function Websock() {
this._eventHandlers[evt] = handler;
},
_allocate_buffers: function () {
this._rQ = new Uint8Array(this._rQbufferSize);
this._sQ = new Uint8Array(this._sQbufferSize);
},
init: function (protocols, ws_schema) {
this._rQ = [];
this._allocate_buffers();
this._rQi = 0;
this._sQ = [];
this._websocket = null;
// Check for full typed array support
@@ -238,35 +255,21 @@ function Websock() {
// Default protocols if not specified
if (typeof(protocols) === "undefined") {
if (wsbt) {
protocols = ['binary', 'base64'];
} else {
protocols = 'base64';
}
protocols = 'binary';
}
if (Array.isArray(protocols) && protocols.indexOf('binary') > -1) {
protocols = 'binary';
}
if (!wsbt) {
if (protocols === 'binary') {
throw new Error('WebSocket binary sub-protocol requested but not supported');
}
throw new Error("noVNC no longer supports base64 WebSockets. " +
"Please use a browser which supports binary WebSockets.");
}
if (typeof(protocols) === 'object') {
var new_protocols = [];
for (var i = 0; i < protocols.length; i++) {
if (protocols[i] === 'binary') {
Util.Error('Skipping unsupported WebSocket binary sub-protocol');
} else {
new_protocols.push(protocols[i]);
}
}
if (new_protocols.length > 0) {
protocols = new_protocols;
} else {
throw new Error("Only WebSocket binary sub-protocol was requested and is not supported.");
}
}
if (protocols != 'binary') {
throw new Error("noVNC no longer supports base64 WebSockets. Please " +
"use the binary subprotocol instead.");
}
return protocols;
@@ -289,9 +292,16 @@ function Websock() {
this._mode = this._websocket.protocol;
Util.Info("Server choose sub-protocol: " + this._websocket.protocol);
} else {
this._mode = 'base64';
this._mode = 'binary';
Util.Error('Server select no sub-protocol!: ' + this._websocket.protocol);
}
if (this._mode != 'binary') {
throw new Error("noVNC no longer supports base64 WebSockets. Please " +
"use the binary subprotocol instead.");
}
this._eventHandlers.open();
Util.Debug("<< WebSock.onopen");
}).bind(this);
@@ -321,26 +331,16 @@ function Websock() {
// private methods
_encode_message: function () {
if (this._mode === 'binary') {
// Put in a binary arraybuffer
return (new Uint8Array(this._sQ)).buffer;
} else {
// base64 encode
return Base64.encode(this._sQ);
}
// Put in a binary arraybuffer
// according to the spec, you can send ArrayBufferViews with the send method
return new Uint8Array(this._sQ.buffer, 0, this._sQlen);
},
_decode_message: function (data) {
if (this._mode === 'binary') {
// push arraybuffer values onto the end
var u8 = new Uint8Array(data);
for (var i = 0; i < u8.length; i++) {
this._rQ.push(u8[i]);
}
} else {
// base64 decode and concat to end
this._rQ = this._rQ.concat(Base64.decode(data, 0));
}
// push arraybuffer values onto the end
var u8 = new Uint8Array(data);
this._rQ.set(u8, this._rQlen);
this._rQlen += u8.length;
},
_recv_message: function (e) {
@@ -349,8 +349,26 @@ function Websock() {
if (this.rQlen() > 0) {
this._eventHandlers.message();
// Compact the receive queue
if (this._rQ.length > this._rQmax) {
this._rQ = this._rQ.slice(this._rQi);
if (this._rQlen == this._rQi) {
this._rQlen = 0;
this._rQi = 0;
} else if (this._rQlen > this._rQmax) {
if (this._rQlen - this._rQi > 0.5 * this._rQbufferSize) {
var old_rQbuffer = this._rQ.buffer;
this._rQbufferSize *= 2;
this._rQmax = this._rQbufferSize / 8;
this._rQ = new Uint8Array(this._rQbufferSize);
this._rQ.set(new Uint8Array(old_rQbuffer, this._rQi));
} else {
if (this._rQ.copyWithin) {
// Firefox only, ATM
this._rQ.copyWithin(0, this._rQi);
} else {
this._rQ.set(new Uint8Array(this._rQ.buffer, this._rQi));
}
}
this._rQlen = this._rQlen - this._rQi;
this._rQi = 0;
}
} else {