mirror of
https://github.com/fcwu/docker-ubuntu-vnc-desktop
synced 2026-08-05 16:12:41 +02:00
refactor: clean code
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
// some useful assertions for noVNC
|
||||
chai.use(function (_chai, utils) {
|
||||
_chai.Assertion.addMethod('displayed', function (target_data) {
|
||||
var obj = this._obj;
|
||||
var ctx = obj._target.getContext('2d');
|
||||
var data_cl = ctx.getImageData(0, 0, obj._target.width, obj._target.height).data;
|
||||
// NB(directxman12): PhantomJS 1.x doesn't implement Uint8ClampedArray, so work around that
|
||||
var data = new Uint8Array(data_cl);
|
||||
var same = true;
|
||||
var len = data_cl.length;
|
||||
if (len != target_data.length) {
|
||||
same = false;
|
||||
} else {
|
||||
for (var i = 0; i < len; i++) {
|
||||
if (data[i] != target_data[i]) {
|
||||
same = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!same) {
|
||||
console.log("expected data: %o, actual data: %o", target_data, data);
|
||||
}
|
||||
this.assert(same,
|
||||
"expected #{this} to have displayed the image #{exp}, but instead it displayed #{act}",
|
||||
"expected #{this} not to have displayed the image #{act}",
|
||||
target_data,
|
||||
data);
|
||||
});
|
||||
|
||||
_chai.Assertion.addMethod('sent', function (target_data) {
|
||||
var obj = this._obj;
|
||||
obj.inspect = function () {
|
||||
var res = { _websocket: obj._websocket, rQi: obj._rQi, _rQ: new Uint8Array(obj._rQ.buffer, 0, obj._rQlen),
|
||||
_sQ: new Uint8Array(obj._sQ.buffer, 0, obj._sQlen) };
|
||||
res.prototype = obj;
|
||||
return res;
|
||||
};
|
||||
var data = obj._websocket._get_sent_data();
|
||||
var same = true;
|
||||
if (data.length != target_data.length) {
|
||||
same = false;
|
||||
} else {
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
if (data[i] != target_data[i]) {
|
||||
same = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!same) {
|
||||
console.log("expected data: %o, actual data: %o", target_data, data);
|
||||
}
|
||||
this.assert(same,
|
||||
"expected #{this} to have sent the data #{exp}, but it actually sent #{act}",
|
||||
"expected #{this} not to have sent the data #{act}",
|
||||
Array.prototype.slice.call(target_data),
|
||||
Array.prototype.slice.call(data));
|
||||
});
|
||||
|
||||
_chai.Assertion.addProperty('array', function () {
|
||||
utils.flag(this, 'array', true);
|
||||
});
|
||||
|
||||
_chai.Assertion.overwriteMethod('equal', function (_super) {
|
||||
return function assertArrayEqual(target) {
|
||||
if (utils.flag(this, 'array')) {
|
||||
var obj = this._obj;
|
||||
|
||||
var i;
|
||||
var same = true;
|
||||
|
||||
if (utils.flag(this, 'deep')) {
|
||||
for (i = 0; i < obj.length; i++) {
|
||||
if (!utils.eql(obj[i], target[i])) {
|
||||
same = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this.assert(same,
|
||||
"expected #{this} to have elements deeply equal to #{exp}",
|
||||
"expected #{this} not to have elements deeply equal to #{exp}",
|
||||
Array.prototype.slice.call(target));
|
||||
} else {
|
||||
for (i = 0; i < obj.length; i++) {
|
||||
if (obj[i] != target[i]) {
|
||||
same = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this.assert(same,
|
||||
"expected #{this} to have elements equal to #{exp}",
|
||||
"expected #{this} not to have elements equal to #{exp}",
|
||||
Array.prototype.slice.call(target));
|
||||
}
|
||||
} else {
|
||||
_super.apply(this, arguments);
|
||||
}
|
||||
};
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
var FakeWebSocket;
|
||||
|
||||
(function () {
|
||||
// PhantomJS can't create Event objects directly, so we need to use this
|
||||
function make_event(name, props) {
|
||||
var evt = document.createEvent('Event');
|
||||
evt.initEvent(name, true, true);
|
||||
if (props) {
|
||||
for (var prop in props) {
|
||||
evt[prop] = props[prop];
|
||||
}
|
||||
}
|
||||
return evt;
|
||||
}
|
||||
|
||||
FakeWebSocket = function (uri, protocols) {
|
||||
this.url = uri;
|
||||
this.binaryType = "arraybuffer";
|
||||
this.extensions = "";
|
||||
|
||||
if (!protocols || typeof protocols === 'string') {
|
||||
this.protocol = protocols;
|
||||
} else {
|
||||
this.protocol = protocols[0];
|
||||
}
|
||||
|
||||
this._send_queue = new Uint8Array(20000);
|
||||
|
||||
this.readyState = FakeWebSocket.CONNECTING;
|
||||
this.bufferedAmount = 0;
|
||||
|
||||
this.__is_fake = true;
|
||||
};
|
||||
|
||||
FakeWebSocket.prototype = {
|
||||
close: function (code, reason) {
|
||||
this.readyState = FakeWebSocket.CLOSED;
|
||||
if (this.onclose) {
|
||||
this.onclose(make_event("close", { 'code': code, 'reason': reason, 'wasClean': true }));
|
||||
}
|
||||
},
|
||||
|
||||
send: function (data) {
|
||||
if (this.protocol == 'base64') {
|
||||
data = Base64.decode(data);
|
||||
} else {
|
||||
data = new Uint8Array(data);
|
||||
}
|
||||
this._send_queue.set(data, this.bufferedAmount);
|
||||
this.bufferedAmount += data.length;
|
||||
},
|
||||
|
||||
_get_sent_data: function () {
|
||||
var res = new Uint8Array(this._send_queue.buffer, 0, this.bufferedAmount);
|
||||
this.bufferedAmount = 0;
|
||||
return res;
|
||||
},
|
||||
|
||||
_open: function (data) {
|
||||
this.readyState = FakeWebSocket.OPEN;
|
||||
if (this.onopen) {
|
||||
this.onopen(make_event('open'));
|
||||
}
|
||||
},
|
||||
|
||||
_receive_data: function (data) {
|
||||
this.onmessage(make_event("message", { 'data': data }));
|
||||
}
|
||||
};
|
||||
|
||||
FakeWebSocket.OPEN = WebSocket.OPEN;
|
||||
FakeWebSocket.CONNECTING = WebSocket.CONNECTING;
|
||||
FakeWebSocket.CLOSING = WebSocket.CLOSING;
|
||||
FakeWebSocket.CLOSED = WebSocket.CLOSED;
|
||||
|
||||
FakeWebSocket.__is_fake = true;
|
||||
|
||||
FakeWebSocket.replace = function () {
|
||||
if (!WebSocket.__is_fake) {
|
||||
var real_version = WebSocket;
|
||||
WebSocket = FakeWebSocket;
|
||||
FakeWebSocket.__real_version = real_version;
|
||||
}
|
||||
};
|
||||
|
||||
FakeWebSocket.restore = function () {
|
||||
if (WebSocket.__is_fake) {
|
||||
WebSocket = WebSocket.__real_version;
|
||||
}
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,133 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head><title>Input Test</title></head>
|
||||
<body>
|
||||
<br><br>
|
||||
|
||||
Canvas:
|
||||
<span id="button-selection" style="display: none;">
|
||||
<input id="button1" type="button" value="L"><input id="button2" type="button" value="M"><input id="button4" type="button" value="R">
|
||||
</span>
|
||||
<br>
|
||||
<canvas id="canvas" width="640" height="20"
|
||||
style="border-style: dotted; border-width: 1px;">
|
||||
Canvas not supported.
|
||||
</canvas>
|
||||
|
||||
<br>
|
||||
Results:<br>
|
||||
<textarea id="messages" style="font-size: 9;" cols=80 rows=25></textarea>
|
||||
</body>
|
||||
|
||||
<!--
|
||||
<script type='text/javascript'
|
||||
src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
|
||||
-->
|
||||
<script src="../core/util.js"></script>
|
||||
<script src="../app/webutil.js"></script>
|
||||
<script src="../core/base64.js"></script>
|
||||
<script src="../core/input/keysym.js"></script>
|
||||
<script src="../core/input/keysymdef.js"></script>
|
||||
<script src="../core/input/xtscancodes.js"></script>
|
||||
<script src="../core/input/util.js"></script>
|
||||
<script src="../core/input/devices.js"></script>
|
||||
<script src="../core/display.js"></script>
|
||||
<script>
|
||||
var msg_cnt = 0, iterations,
|
||||
width = 400, height = 200,
|
||||
canvas, keyboard, mouse;
|
||||
|
||||
var newline = "\n";
|
||||
if (Util.Engine.trident) {
|
||||
var newline = "<br>\n";
|
||||
}
|
||||
|
||||
function message(str) {
|
||||
console.log(str);
|
||||
cell = document.getElementById('messages');
|
||||
cell.textContent += msg_cnt + ": " + str + newline;
|
||||
cell.scrollTop = cell.scrollHeight;
|
||||
msg_cnt++;
|
||||
}
|
||||
|
||||
function mouseButton(x, y, down, bmask) {
|
||||
msg = 'mouse x,y: ' + x + ',' + y + ' down: ' + down;
|
||||
msg += ' bmask: ' + bmask;
|
||||
message(msg);
|
||||
}
|
||||
|
||||
function mouseMove(x, y) {
|
||||
msg = 'mouse x,y: ' + x + ',' + y;
|
||||
//console.log(msg);
|
||||
}
|
||||
|
||||
function rfbKeyPress(keysym, down) {
|
||||
var d = down ? "down" : " up ";
|
||||
var key = keysyms.lookup(keysym);
|
||||
var msg = "RFB keypress " + d + " keysym: " + keysym;
|
||||
if (key && key.keyname) {
|
||||
msg += " key name: " + key.keyname;
|
||||
}
|
||||
message(msg);
|
||||
}
|
||||
function rawKey(e) {
|
||||
msg = "raw key event " + e.type +
|
||||
" (key: " + e.keyCode + ", char: " + e.charCode +
|
||||
", which: " + e.which +")";
|
||||
message(msg);
|
||||
}
|
||||
|
||||
function selectButton(num) {
|
||||
var b, blist = [1,2,4];
|
||||
|
||||
if (typeof num === 'undefined') {
|
||||
// Show the default
|
||||
num = mouse.get_touchButton();
|
||||
} else if (num === mouse.get_touchButton()) {
|
||||
// Set all buttons off (no clicks)
|
||||
mouse.set_touchButton(0);
|
||||
num = 0;
|
||||
} else {
|
||||
// Turn on one button
|
||||
mouse.set_touchButton(num);
|
||||
}
|
||||
|
||||
for (b = 0; b < blist.length; b++) {
|
||||
if (blist[b] === num) {
|
||||
document.getElementById('button' + blist[b]).style.backgroundColor = "black";
|
||||
document.getElementById('button' + blist[b]).style.color = "lightgray";
|
||||
} else {
|
||||
document.getElementById('button' + blist[b]).style.backgroundColor = "";
|
||||
document.getElementById('button' + blist[b]).style.color = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.onload = function() {
|
||||
canvas = new Display({'target' : document.getElementById('canvas')});
|
||||
keyboard = new Keyboard({'target': document,
|
||||
'onKeyPress': rfbKeyPress});
|
||||
document.addEventListener('keypress', rawKey);
|
||||
document.addEventListener('keydown', rawKey);
|
||||
document.addEventListener('keyup', rawKey);
|
||||
mouse = new Mouse({'target': document.getElementById('canvas'),
|
||||
'onMouseButton': mouseButton,
|
||||
'onMouseMove': mouseMove});
|
||||
|
||||
canvas.resize(width, height, true);
|
||||
keyboard.grab();
|
||||
mouse.grab();
|
||||
message("Display initialized");
|
||||
|
||||
if (Util.isTouchDevice) {
|
||||
message("Touch device detected");
|
||||
document.getElementById('button-selection').style.display = "inline";
|
||||
document.getElementById('button1').onclick = function(){ selectButton(1) };
|
||||
document.getElementById('button2').onclick = function(){ selectButton(2) };
|
||||
document.getElementById('button4').onclick = function(){ selectButton(4) };
|
||||
selectButton();
|
||||
}
|
||||
|
||||
}
|
||||
</script>
|
||||
</html>
|
||||
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
* noVNC: HTML5 VNC client
|
||||
* Copyright (C) 2012 Joel Martin
|
||||
* Licensed under MPL 2.0 (see LICENSE.txt)
|
||||
*/
|
||||
|
||||
"use strict";
|
||||
/*jslint browser: true, white: false */
|
||||
/*global Util, VNC_frame_data, finish */
|
||||
|
||||
var rfb, mode, test_state, frame_idx, frame_length,
|
||||
iteration, iterations, istart_time, encoding,
|
||||
|
||||
// Pre-declarations for jslint
|
||||
send_array, next_iteration, end_iteration, queue_next_packet,
|
||||
do_packet, enable_test_mode;
|
||||
|
||||
// Override send_array
|
||||
send_array = function (arr) {
|
||||
// Stub out send_array
|
||||
};
|
||||
|
||||
// Immediate polyfill
|
||||
if (window.setImmediate === undefined) {
|
||||
var _immediateIdCounter = 1;
|
||||
var _immediateFuncs = {};
|
||||
|
||||
window.setImmediate = function (func) {
|
||||
var index = Util._immediateIdCounter++;
|
||||
_immediateFuncs[index] = func;
|
||||
window.postMessage("noVNC immediate trigger:" + index, "*");
|
||||
return index;
|
||||
};
|
||||
|
||||
window.clearImmediate = function (id) {
|
||||
_immediateFuncs[id];
|
||||
};
|
||||
|
||||
var _onMessage = function (event) {
|
||||
if ((typeof event.data !== "string") ||
|
||||
(event.data.indexOf("noVNC immediate trigger:") !== 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
var index = event.data.slice("noVNC immediate trigger:".length);
|
||||
|
||||
var callback = _immediateFuncs[index];
|
||||
if (callback === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
delete _immediateFuncs[index];
|
||||
|
||||
callback();
|
||||
};
|
||||
window.addEventListener("message", _onMessage);
|
||||
}
|
||||
|
||||
enable_test_mode = function () {
|
||||
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._rfb_connection_state = 'connecting';
|
||||
this._rfb_init_state = 'ProtocolVersion';
|
||||
};
|
||||
};
|
||||
|
||||
next_iteration = function () {
|
||||
rfb = new RFB({'target': document.getElementById('VNC_canvas'),
|
||||
'view_only': true,
|
||||
'onDisconnected': disconnected,
|
||||
'onNotification': notification});
|
||||
enable_test_mode();
|
||||
|
||||
// Missing in older recordings
|
||||
if (typeof VNC_frame_encoding === 'undefined') {
|
||||
var frame = VNC_frame_data[0];
|
||||
var start = frame.indexOf('{', 1) + 1;
|
||||
if (frame.slice(start).startsWith('UkZC')) {
|
||||
encoding = 'base64';
|
||||
} else {
|
||||
encoding = 'binary';
|
||||
}
|
||||
} else {
|
||||
encoding = VNC_frame_encoding;
|
||||
}
|
||||
|
||||
if (iteration === 0) {
|
||||
frame_length = VNC_frame_data.length;
|
||||
test_state = 'running';
|
||||
}
|
||||
|
||||
if (test_state !== 'running') { return; }
|
||||
|
||||
iteration += 1;
|
||||
if (iteration > iterations) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
frame_idx = 0;
|
||||
istart_time = (new Date()).getTime();
|
||||
rfb.connect('test', 0, "bogus");
|
||||
|
||||
queue_next_packet();
|
||||
|
||||
};
|
||||
|
||||
end_iteration = function () {
|
||||
if (rfb._display.pending()) {
|
||||
rfb._display.set_onFlush(function () {
|
||||
if (rfb._flushing) {
|
||||
rfb._onFlush();
|
||||
}
|
||||
end_iteration();
|
||||
});
|
||||
rfb._display.flush();
|
||||
} else {
|
||||
next_iteration();
|
||||
}
|
||||
};
|
||||
|
||||
queue_next_packet = function () {
|
||||
var frame, foffset, toffset, delay;
|
||||
if (test_state !== 'running') { return; }
|
||||
|
||||
frame = VNC_frame_data[frame_idx];
|
||||
while ((frame_idx < frame_length) && (frame.charAt(0) === "}")) {
|
||||
//Util.Debug("Send frame " + frame_idx);
|
||||
frame_idx += 1;
|
||||
frame = VNC_frame_data[frame_idx];
|
||||
}
|
||||
|
||||
if (frame === 'EOF') {
|
||||
Util.Debug("Finished, found EOF");
|
||||
end_iteration();
|
||||
return;
|
||||
}
|
||||
if (frame_idx >= frame_length) {
|
||||
Util.Debug("Finished, no more frames");
|
||||
end_iteration();
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode === 'realtime') {
|
||||
foffset = frame.slice(1, frame.indexOf('{', 1));
|
||||
toffset = (new Date()).getTime() - istart_time;
|
||||
delay = foffset - toffset;
|
||||
if (delay < 1) {
|
||||
delay = 1;
|
||||
}
|
||||
|
||||
setTimeout(do_packet, delay);
|
||||
} else {
|
||||
window.setImmediate(do_packet);
|
||||
}
|
||||
};
|
||||
|
||||
var bytes_processed = 0;
|
||||
|
||||
do_packet = function () {
|
||||
// Avoid having an excessive queue buildup
|
||||
if (rfb._flushing && (mode !== 'realtime')) {
|
||||
rfb._display.set_onFlush(function () {
|
||||
rfb._display.set_onFlush(rfb._onFlush.bind(rfb));
|
||||
rfb._onFlush();
|
||||
do_packet();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
//Util.Debug("Processing frame: " + frame_idx);
|
||||
var frame = VNC_frame_data[frame_idx],
|
||||
start = frame.indexOf('{', 1) + 1;
|
||||
var u8;
|
||||
if (encoding === 'base64') {
|
||||
u8 = Base64.decode(frame.slice(start));
|
||||
start = 0;
|
||||
} else {
|
||||
u8 = new Uint8Array(frame.length - start);
|
||||
for (var i = 0; i < frame.length - start; i++) {
|
||||
u8[i] = frame.charCodeAt(start + i);
|
||||
}
|
||||
}
|
||||
bytes_processed += u8.length;
|
||||
rfb._sock._recv_message({'data' : u8});
|
||||
frame_idx += 1;
|
||||
|
||||
queue_next_packet();
|
||||
};
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
var Spooky = require('spooky');
|
||||
var path = require('path');
|
||||
|
||||
var phantom_path = require('phantomjs-prebuilt').path;
|
||||
var casper_path = path.resolve(__dirname, '../node_modules/casperjs/bin/casperjs');
|
||||
process.env.PHANTOMJS_EXECUTABLE = phantom_path;
|
||||
var casper_opts = {
|
||||
child: {
|
||||
transport: 'http',
|
||||
command: casper_path
|
||||
},
|
||||
casper: {
|
||||
logLevel: 'debug',
|
||||
verbose: true
|
||||
}
|
||||
};
|
||||
|
||||
var provide_emitter = function(file_paths, debug_port) {
|
||||
if (debug_port) {
|
||||
casper_opts.child['remote-debugger-port'] = debug_port;
|
||||
var debug_url = ('https://localhost:' + debug_port +
|
||||
'/webkit/inspector/inspector.html?page=');
|
||||
console.info('[remote-debugger] Navigate to ' + debug_url + '1 and ' +
|
||||
'run `__run();` in the console to continue loading.' +
|
||||
'\n[remote-debugger] Navigate to ' + debug_url + '2 to ' +
|
||||
'view the actual page source.\n' +
|
||||
'[remote-debugger] Use the `debugger;` statement to ' +
|
||||
'trigger an initial breakpoint.');
|
||||
}
|
||||
|
||||
var spooky = new Spooky(casper_opts, function(err) {
|
||||
if (err) {
|
||||
if (err.stack) console.warn(err.stack);
|
||||
else console.warn(err);
|
||||
return;
|
||||
}
|
||||
spooky.start('about:blank');
|
||||
|
||||
file_paths.forEach(function(file_path, path_ind) {
|
||||
spooky.thenOpen('file://'+file_path);
|
||||
spooky.waitFor(function() {
|
||||
return this.getGlobal('__mocha_done') === true;
|
||||
},
|
||||
[{ path_ind: path_ind }, function() {
|
||||
var res_json = {
|
||||
file_ind: path_ind
|
||||
};
|
||||
|
||||
res_json.num_tests = this.evaluate(function() { return document.querySelectorAll('li.test').length; });
|
||||
res_json.num_passes = this.evaluate(function() { return document.querySelectorAll('li.test.pass').length; });
|
||||
res_json.num_fails = this.evaluate(function() { return document.querySelectorAll('li.test.fail').length; });
|
||||
res_json.num_slow = this.evaluate(function() { return document.querySelectorAll('li.test.pass:not(.fast):not(.pending)').length; });
|
||||
res_json.num_skipped = this.evaluate(function () { return document.querySelectorAll('li.test.pending').length; });
|
||||
res_json.duration = this.evaluate(function() { return document.querySelector('li.duration em').textContent; });
|
||||
|
||||
res_json.suites = this.evaluate(function() {
|
||||
var traverse_node = function(elem) {
|
||||
var res;
|
||||
if (elem.classList.contains('suite')) {
|
||||
res = {
|
||||
type: 'suite',
|
||||
name: elem.querySelector('h1').textContent,
|
||||
has_subfailures: elem.querySelectorAll('li.test.fail').length > 0,
|
||||
};
|
||||
|
||||
var child_elems = elem.querySelector('ul').children;
|
||||
res.children = Array.prototype.map.call(child_elems, traverse_node);
|
||||
return res;
|
||||
}
|
||||
else {
|
||||
var h2_content = elem.querySelector('h2').childNodes;
|
||||
res = {
|
||||
type: 'test',
|
||||
text: h2_content[0].textContent,
|
||||
};
|
||||
|
||||
if (elem.classList.contains('pass')) {
|
||||
res.pass = true;
|
||||
if (elem.classList.contains('pending')) {
|
||||
res.slow = false;
|
||||
res.skipped = true;
|
||||
}
|
||||
else {
|
||||
res.slow = !elem.classList.contains('fast');
|
||||
res.skipped = false;
|
||||
res.duration = h2_content[1].textContent;
|
||||
}
|
||||
}
|
||||
else {
|
||||
res.error = elem.querySelector('pre.error').textContent;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
};
|
||||
var top_suites = document.querySelectorAll('#mocha-report > li.suite');
|
||||
return Array.prototype.map.call(top_suites, traverse_node);
|
||||
});
|
||||
|
||||
res_json.replay = this.evaluate(function() { return document.querySelector('a.replay').textContent; });
|
||||
|
||||
this.emit('test_ready', res_json);
|
||||
}]);
|
||||
});
|
||||
spooky.run();
|
||||
});
|
||||
|
||||
return spooky;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
provide_emitter: provide_emitter,
|
||||
name: 'SpookyJS (CapserJS on PhantomJS)'
|
||||
};
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
#!/usr/bin/env node
|
||||
var ansi = require('ansi');
|
||||
var program = require('commander');
|
||||
var path = require('path');
|
||||
var fs = require('fs');
|
||||
|
||||
var make_list = function(val) {
|
||||
return val.split(',');
|
||||
};
|
||||
|
||||
program
|
||||
.option('-t, --tests <testlist>', 'Run the specified html-file-based test(s). \'testlist\' should be a comma-separated list', make_list, [])
|
||||
.option('-a, --print-all', 'Print all tests, not just the failures')
|
||||
.option('--disable-color', 'Explicitly disable color')
|
||||
.option('-c, --color', 'Explicitly enable color (default is to use color when not outputting to a pipe)')
|
||||
.option('-i, --auto-inject <includefiles>', 'Treat the test list as a set of mocha JS files, and automatically generate HTML files with which to test test. \'includefiles\' should be a comma-separated list of paths to javascript files to include in each of the generated HTML files', make_list, null)
|
||||
.option('-p, --provider <name>', 'Use the given provider (defaults to "casper"). Currently, may be "casper" or "zombie"', 'casper')
|
||||
.option('-g, --generate-html', 'Instead of running the tests, just return the path to the generated HTML file, then wait for user interaction to exit (should be used with .js tests).')
|
||||
.option('-o, --open-in-browser', 'Open the generated HTML files in a web browser using the "open" module (must be used with the "-g"/"--generate-html" option).')
|
||||
.option('--output-html', 'Instead of running the tests, just output the generated HTML source to STDOUT (should be used with .js tests)')
|
||||
.option('-d, --debug', 'Show debug output (the "console" event) from the provider')
|
||||
.option('-r, --relative', 'Use relative paths in the generated HTML file')
|
||||
.option('--debugger <port>', 'Enable the remote debugger for CasperJS')
|
||||
.parse(process.argv);
|
||||
|
||||
if (program.tests.length === 0) {
|
||||
program.tests = fs.readdirSync(__dirname).filter(function(f) { return (/^test\.(\w|\.|-)+\.js$/).test(f); });
|
||||
program.tests = program.tests.map(function (f) { return path.resolve(__dirname, f); }); // add full paths in
|
||||
console.log('using files %s', program.tests);
|
||||
}
|
||||
|
||||
var file_paths = [];
|
||||
|
||||
var all_js = program.tests.reduce(function(a,e) { return a && e.slice(-3) == '.js'; }, true);
|
||||
|
||||
var get_path = function (/* arguments */) {
|
||||
if (program.relative) {
|
||||
return path.join.apply(null, arguments);
|
||||
} else {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
args.unshift(__dirname, '..');
|
||||
return path.resolve.apply(null, args);
|
||||
}
|
||||
};
|
||||
|
||||
var get_path_cwd = function (/* arguments */) {
|
||||
if (program.relative) {
|
||||
var part_path = path.join.apply(null, arguments);
|
||||
return path.relative(path.join(__dirname, '..'), path.resolve(process.cwd(), part_path));
|
||||
} else {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
args.unshift(process.cwd());
|
||||
return path.resolve.apply(null, args);
|
||||
}
|
||||
};
|
||||
|
||||
if (all_js && !program.autoInject) {
|
||||
var all_modules = {};
|
||||
|
||||
// uses the first instance of the string 'requires local modules: '
|
||||
program.tests.forEach(function (testname) {
|
||||
var full_path = path.resolve(process.cwd(), testname);
|
||||
var content = fs.readFileSync(full_path).toString();
|
||||
var ind = content.indexOf('requires local modules: ');
|
||||
if (ind > -1) {
|
||||
ind += 'requires local modules: '.length;
|
||||
var eol = content.indexOf('\n', ind);
|
||||
var modules = content.slice(ind, eol).split(/,\s*/);
|
||||
modules.forEach(function (mod) {
|
||||
all_modules[get_path('core/', mod) + '.js'] = 1;
|
||||
});
|
||||
}
|
||||
|
||||
var fakes_ind = content.indexOf('requires test modules: ');
|
||||
if (fakes_ind > -1) {
|
||||
fakes_ind += 'requires test modules: '.length;
|
||||
var fakes_eol = content.indexOf('\n', fakes_ind);
|
||||
var fakes_modules = content.slice(fakes_ind, fakes_eol).split(/,\s*/);
|
||||
fakes_modules.forEach(function (mod) {
|
||||
all_modules[get_path('tests/', mod) + '.js'] = 1;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
program.autoInject = Object.keys(all_modules);
|
||||
}
|
||||
|
||||
if (program.autoInject) {
|
||||
var temp = require('temp');
|
||||
temp.track();
|
||||
|
||||
var template = {
|
||||
header: "<html>\n<head>\n<meta charset='utf-8' />\n<link rel='stylesheet' href='" + get_path('node_modules/mocha/mocha.css') + "'/>\n</head>\n<body><div id='mocha'></div>",
|
||||
script_tag: function(p) { return "<script src='" + p + "'></script>"; },
|
||||
footer: "<script>\nmocha.checkLeaks();\nmocha.globals(['navigator', 'create', 'ClientUtils', '__utils__', 'requestAnimationFrame', 'WebSocket']);\nmocha.run(function () { window.__mocha_done = true; });\n</script>\n</body>\n</html>"
|
||||
};
|
||||
|
||||
template.header += "\n" + template.script_tag(get_path('node_modules/chai/chai.js'));
|
||||
template.header += "\n" + template.script_tag(get_path('node_modules/mocha/mocha.js'));
|
||||
template.header += "\n" + template.script_tag(get_path('node_modules/sinon/pkg/sinon.js'));
|
||||
template.header += "\n" + template.script_tag(get_path('node_modules/sinon-chai/lib/sinon-chai.js'));
|
||||
template.header += "\n<script>mocha.setup('bdd');</script>";
|
||||
|
||||
|
||||
template.header = program.autoInject.reduce(function(acc, sn) {
|
||||
return acc + "\n" + template.script_tag(get_path_cwd(sn));
|
||||
}, template.header);
|
||||
|
||||
file_paths = program.tests.map(function(jsn, ind) {
|
||||
var templ = template.header;
|
||||
templ += "\n";
|
||||
templ += template.script_tag(get_path_cwd(jsn));
|
||||
templ += template.footer;
|
||||
|
||||
var tempfile = temp.openSync({ prefix: 'novnc-zombie-inject-', suffix: '-file_num-'+ind+'.html' });
|
||||
fs.writeSync(tempfile.fd, templ);
|
||||
fs.closeSync(tempfile.fd);
|
||||
return tempfile.path;
|
||||
});
|
||||
|
||||
}
|
||||
else {
|
||||
file_paths = program.tests.map(function(fn) {
|
||||
return path.resolve(process.cwd(), fn);
|
||||
});
|
||||
}
|
||||
|
||||
var use_ansi = false;
|
||||
if (program.color) use_ansi = true;
|
||||
else if (program.disableColor) use_ansi = false;
|
||||
else if (process.stdout.isTTY) use_ansi = true;
|
||||
|
||||
var cursor = ansi(process.stdout, { enabled: use_ansi });
|
||||
|
||||
if (program.outputHtml) {
|
||||
file_paths.forEach(function(path, path_ind) {
|
||||
fs.readFile(path, function(err, data) {
|
||||
if (err) {
|
||||
console.warn(error.stack);
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_ansi) {
|
||||
cursor
|
||||
.bold()
|
||||
.write(program.tests[path_ind])
|
||||
.reset()
|
||||
.write("\n")
|
||||
.write(Array(program.tests[path_ind].length+1).join('='))
|
||||
.write("\n\n");
|
||||
}
|
||||
|
||||
cursor
|
||||
.write(data)
|
||||
.write("\n\n");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (program.generateHtml) {
|
||||
var open_browser;
|
||||
if (program.openInBrowser) {
|
||||
open_browser = require('open');
|
||||
}
|
||||
|
||||
file_paths.forEach(function(path, path_ind) {
|
||||
cursor
|
||||
.bold()
|
||||
.write(program.tests[path_ind])
|
||||
.write(": ")
|
||||
.reset()
|
||||
.write(path)
|
||||
.write("\n");
|
||||
|
||||
if (program.openInBrowser) {
|
||||
open_browser(path);
|
||||
}
|
||||
});
|
||||
console.log('');
|
||||
}
|
||||
|
||||
if (program.generateHtml) {
|
||||
process.stdin.resume(); // pause until C-c
|
||||
process.on('SIGINT', function() {
|
||||
process.stdin.pause(); // exit
|
||||
});
|
||||
}
|
||||
|
||||
if (!program.outputHtml && !program.generateHtml) {
|
||||
var failure_count = 0;
|
||||
|
||||
var prov = require(path.resolve(__dirname, 'run_from_console.'+program.provider+'.js'));
|
||||
|
||||
cursor
|
||||
.write("Running tests ")
|
||||
.bold()
|
||||
.write(program.tests.join(', '))
|
||||
.reset()
|
||||
.grey()
|
||||
.write(' using provider '+prov.name)
|
||||
.reset()
|
||||
.write("\n");
|
||||
//console.log("Running tests %s using provider %s", program.tests.join(', '), prov.name);
|
||||
|
||||
var provider = prov.provide_emitter(file_paths, program.debugger);
|
||||
provider.on('test_ready', function(test_json) {
|
||||
console.log('');
|
||||
|
||||
filename = program.tests[test_json.file_ind];
|
||||
|
||||
cursor.bold();
|
||||
console.log('Results for %s:', filename);
|
||||
console.log(Array('Results for :'.length+filename.length+1).join('='));
|
||||
cursor.reset();
|
||||
|
||||
console.log('');
|
||||
|
||||
cursor
|
||||
.write(''+test_json.num_tests+' tests run, ')
|
||||
.green()
|
||||
.write(''+test_json.num_passes+' passed');
|
||||
if (test_json.num_slow > 0) {
|
||||
cursor
|
||||
.reset()
|
||||
.write(' (');
|
||||
cursor
|
||||
.yellow()
|
||||
.write(''+test_json.num_slow+' slow')
|
||||
.reset()
|
||||
.write(')');
|
||||
}
|
||||
cursor
|
||||
.reset()
|
||||
.write(', ');
|
||||
cursor
|
||||
.red()
|
||||
.write(''+test_json.num_fails+' failed');
|
||||
if (test_json.num_skipped > 0) {
|
||||
cursor
|
||||
.reset()
|
||||
.write(', ')
|
||||
.grey()
|
||||
.write(''+test_json.num_skipped+' skipped');
|
||||
}
|
||||
cursor
|
||||
.reset()
|
||||
.write(' -- duration: '+test_json.duration+"s\n");
|
||||
|
||||
console.log('');
|
||||
|
||||
if (test_json.num_fails > 0 || program.printAll) {
|
||||
var extract_error_lines = function (err) {
|
||||
// the split is to avoid a weird thing where in PhantomJS where we get a stack trace too
|
||||
var err_lines = err.split('\n');
|
||||
if (err_lines.length == 1) {
|
||||
return err_lines[0];
|
||||
} else {
|
||||
var ind;
|
||||
for (ind = 0; ind < err_lines.length; ind++) {
|
||||
var at_ind = err_lines[ind].trim().indexOf('at ');
|
||||
if (at_ind === 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return err_lines.slice(0, ind).join('\n');
|
||||
}
|
||||
};
|
||||
|
||||
var traverse_tree = function(indentation, node) {
|
||||
if (node.type == 'suite') {
|
||||
if (!node.has_subfailures && !program.printAll) return;
|
||||
|
||||
if (indentation === 0) {
|
||||
cursor.bold();
|
||||
console.log(node.name);
|
||||
console.log(Array(node.name.length+1).join('-'));
|
||||
cursor.reset();
|
||||
}
|
||||
else {
|
||||
cursor
|
||||
.write(Array(indentation+3).join('#'))
|
||||
.bold()
|
||||
.write(' '+node.name+' ')
|
||||
.reset()
|
||||
.write(Array(indentation+3).join('#'))
|
||||
.write("\n");
|
||||
}
|
||||
|
||||
console.log('');
|
||||
|
||||
for (var i = 0; i < node.children.length; i++) {
|
||||
traverse_tree(indentation+1, node.children[i]);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (!node.pass) {
|
||||
cursor.magenta();
|
||||
console.log('- failed: '+node.text+test_json.replay);
|
||||
cursor.red();
|
||||
console.log(' '+extract_error_lines(node.error));
|
||||
cursor.reset();
|
||||
console.log('');
|
||||
}
|
||||
else if (program.printAll) {
|
||||
if (node.skipped) {
|
||||
cursor
|
||||
.grey()
|
||||
.write('- skipped: '+node.text);
|
||||
}
|
||||
else {
|
||||
if (node.slow) cursor.yellow();
|
||||
else cursor.green();
|
||||
|
||||
cursor
|
||||
.write('- pass: '+node.text)
|
||||
.grey()
|
||||
.write(' ('+node.duration+') ');
|
||||
}
|
||||
/*if (node.slow) cursor.yellow();
|
||||
else cursor.green();*/
|
||||
cursor
|
||||
//.write(test_json.replay)
|
||||
.reset()
|
||||
.write("\n");
|
||||
console.log('');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for (var i = 0; i < test_json.suites.length; i++) {
|
||||
traverse_tree(0, test_json.suites[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (test_json.num_fails === 0) {
|
||||
cursor.fg.green();
|
||||
console.log('all tests passed :-)');
|
||||
cursor.reset();
|
||||
}
|
||||
});
|
||||
|
||||
if (program.debug) {
|
||||
provider.on('console', function(line) {
|
||||
// log to stderr
|
||||
console.error(line);
|
||||
});
|
||||
}
|
||||
|
||||
provider.on('error', function(line) {
|
||||
// log to stderr
|
||||
console.error('ERROR: ' + line);
|
||||
});
|
||||
|
||||
/*gprom.finally(function(ph) {
|
||||
ph.exit();
|
||||
// exit with a status code that actually gives information
|
||||
if (program.exitWithFailureCount) process.exit(failure_count);
|
||||
});*/
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
var Browser = require('zombie');
|
||||
var path = require('path');
|
||||
var EventEmitter = require('events').EventEmitter;
|
||||
var Q = require('q');
|
||||
|
||||
var provide_emitter = function(file_paths) {
|
||||
var emitter = new EventEmitter();
|
||||
|
||||
file_paths.reduce(function(prom, file_path, path_ind) {
|
||||
return prom.then(function(browser) {
|
||||
browser.visit('file://'+file_path, function() {
|
||||
if (browser.error) throw new Error(browser.errors);
|
||||
|
||||
var res_json = {};
|
||||
res_json.file_ind = path_ind;
|
||||
|
||||
res_json.num_tests = browser.querySelectorAll('li.test').length;
|
||||
res_json.num_fails = browser.querySelectorAll('li.test.fail').length;
|
||||
res_json.num_passes = browser.querySelectorAll('li.test.pass').length;
|
||||
res_json.num_slow = browser.querySelectorAll('li.test.pass:not(.fast)').length;
|
||||
res_json.num_skipped = browser.querySelectorAll('li.test.pending').length;
|
||||
res_json.duration = browser.text('li.duration em');
|
||||
|
||||
var traverse_node = function(elem) {
|
||||
var classList = elem.className.split(' ');
|
||||
var res;
|
||||
if (classList.indexOf('suite') > -1) {
|
||||
res = {
|
||||
type: 'suite',
|
||||
name: elem.querySelector('h1').textContent,
|
||||
has_subfailures: elem.querySelectorAll('li.test.fail').length > 0
|
||||
};
|
||||
|
||||
var child_elems = elem.querySelector('ul').children;
|
||||
res.children = Array.prototype.map.call(child_elems, traverse_node);
|
||||
return res;
|
||||
}
|
||||
else {
|
||||
var h2_content = elem.querySelector('h2').childNodes;
|
||||
res = {
|
||||
type: 'test',
|
||||
text: h2_content[0].textContent
|
||||
};
|
||||
|
||||
if (classList.indexOf('pass') > -1) {
|
||||
res.pass = true;
|
||||
if (classList.indexOf('pending') > -1) {
|
||||
res.slow = false;
|
||||
res.skipped = true;
|
||||
}
|
||||
else {
|
||||
res.slow = classList.indexOf('fast') < 0;
|
||||
res.skipped = false;
|
||||
res.duration = h2_content[1].textContent;
|
||||
}
|
||||
}
|
||||
else {
|
||||
res.error = elem.querySelector('pre.error').textContent;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
};
|
||||
|
||||
var top_suites = browser.querySelectorAll('#mocha-report > li.suite');
|
||||
res_json.suites = Array.prototype.map.call(top_suites, traverse_node);
|
||||
res_json.replay = browser.querySelector('a.replay').textContent;
|
||||
|
||||
emitter.emit('test_ready', res_json);
|
||||
});
|
||||
|
||||
return new Browser();
|
||||
});
|
||||
}, Q(new Browser()));
|
||||
|
||||
return emitter;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
provide_emitter: provide_emitter,
|
||||
name: 'ZombieJS'
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
// requires local modules: base64
|
||||
var assert = chai.assert;
|
||||
var expect = chai.expect;
|
||||
|
||||
describe('Base64 Tools', function() {
|
||||
"use strict";
|
||||
|
||||
var BIN_ARR = new Array(256);
|
||||
for (var i = 0; i < 256; i++) {
|
||||
BIN_ARR[i] = i;
|
||||
}
|
||||
|
||||
var B64_STR = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==";
|
||||
|
||||
|
||||
describe('encode', function() {
|
||||
it('should encode a binary string into Base64', function() {
|
||||
var encoded = Base64.encode(BIN_ARR);
|
||||
expect(encoded).to.equal(B64_STR);
|
||||
});
|
||||
});
|
||||
|
||||
describe('decode', function() {
|
||||
it('should decode a Base64 string into a normal string', function() {
|
||||
var decoded = Base64.decode(B64_STR);
|
||||
expect(decoded).to.deep.equal(BIN_ARR);
|
||||
});
|
||||
|
||||
it('should throw an error if we have extra characters at the end of the string', function() {
|
||||
expect(function () { Base64.decode(B64_STR+'abcdef'); }).to.throw(Error);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,536 @@
|
||||
// requires local modules: util, base64, display
|
||||
// requires test modules: assertions
|
||||
/* jshint expr: true */
|
||||
var expect = chai.expect;
|
||||
|
||||
describe('Display/Canvas Helper', function () {
|
||||
var checked_data = [
|
||||
0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255,
|
||||
0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255, 0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255,
|
||||
0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255,
|
||||
0x00, 0xff, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0x00, 0x00, 0xff, 255
|
||||
];
|
||||
checked_data = new Uint8Array(checked_data);
|
||||
|
||||
var basic_data = [0xff, 0x00, 0x00, 255, 0x00, 0xff, 0x00, 255, 0x00, 0x00, 0xff, 255, 0xff, 0xff, 0xff, 255];
|
||||
basic_data = new Uint8Array(basic_data);
|
||||
|
||||
function make_image_canvas (input_data) {
|
||||
var canvas = document.createElement('canvas');
|
||||
canvas.width = 4;
|
||||
canvas.height = 4;
|
||||
var ctx = canvas.getContext('2d');
|
||||
var data = ctx.createImageData(4, 4);
|
||||
for (var i = 0; i < checked_data.length; i++) { data.data[i] = input_data[i]; }
|
||||
ctx.putImageData(data, 0, 0);
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function make_image_png (input_data) {
|
||||
var canvas = make_image_canvas(input_data);
|
||||
var url = canvas.toDataURL();
|
||||
var data = url.split(",")[1];
|
||||
return Base64.decode(data);
|
||||
}
|
||||
|
||||
describe('checking for cursor uri support', function () {
|
||||
beforeEach(function () {
|
||||
this._old_browser_supports_cursor_uris = Util.browserSupportsCursorURIs;
|
||||
});
|
||||
|
||||
it('should disable cursor URIs if there is no support', function () {
|
||||
Util.browserSupportsCursorURIs = function () { return false; };
|
||||
var display = new Display({ target: document.createElement('canvas'), prefer_js: true, viewport: false });
|
||||
expect(display._cursor_uri).to.be.false;
|
||||
});
|
||||
|
||||
it('should enable cursor URIs if there is support', function () {
|
||||
Util.browserSupportsCursorURIs = function () { return true; };
|
||||
var display = new Display({ target: document.createElement('canvas'), prefer_js: true, viewport: false });
|
||||
expect(display._cursor_uri).to.be.true;
|
||||
});
|
||||
|
||||
it('respect the cursor_uri option if there is support', function () {
|
||||
Util.browserSupportsCursorURIs = function () { return false; };
|
||||
var display = new Display({ target: document.createElement('canvas'), prefer_js: true, viewport: false, cursor_uri: false });
|
||||
expect(display._cursor_uri).to.be.false;
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
Util.browserSupportsCursorURIs = this._old_browser_supports_cursor_uris;
|
||||
});
|
||||
});
|
||||
|
||||
describe('viewport handling', function () {
|
||||
var display;
|
||||
beforeEach(function () {
|
||||
display = new Display({ target: document.createElement('canvas'), prefer_js: false, viewport: true });
|
||||
display.resize(5, 5);
|
||||
display.viewportChangeSize(3, 3);
|
||||
display.viewportChangePos(1, 1);
|
||||
});
|
||||
|
||||
it('should take viewport location into consideration when drawing images', function () {
|
||||
display.resize(4, 4);
|
||||
display.viewportChangeSize(2, 2);
|
||||
display.drawImage(make_image_canvas(basic_data), 1, 1);
|
||||
display.flip();
|
||||
|
||||
var expected = new Uint8Array(16);
|
||||
var i;
|
||||
for (i = 0; i < 8; i++) { expected[i] = basic_data[i]; }
|
||||
for (i = 8; i < 16; i++) { expected[i] = 0; }
|
||||
expect(display).to.have.displayed(expected);
|
||||
});
|
||||
|
||||
it('should resize the target canvas when resizing the viewport', function() {
|
||||
display.viewportChangeSize(2, 2);
|
||||
expect(display._target.width).to.equal(2);
|
||||
expect(display._target.height).to.equal(2);
|
||||
});
|
||||
|
||||
it('should move the viewport if necessary', function() {
|
||||
display.viewportChangeSize(5, 5);
|
||||
expect(display.absX(0)).to.equal(0);
|
||||
expect(display.absY(0)).to.equal(0);
|
||||
expect(display._target.width).to.equal(5);
|
||||
expect(display._target.height).to.equal(5);
|
||||
});
|
||||
|
||||
it('should limit the viewport to the framebuffer size', function() {
|
||||
display.viewportChangeSize(6, 6);
|
||||
expect(display._target.width).to.equal(5);
|
||||
expect(display._target.height).to.equal(5);
|
||||
});
|
||||
|
||||
it('should redraw when moving the viewport', function () {
|
||||
display.flip = sinon.spy();
|
||||
display.viewportChangePos(-1, 1);
|
||||
expect(display.flip).to.have.been.calledOnce;
|
||||
});
|
||||
|
||||
it('should redraw when resizing the viewport', function () {
|
||||
display.flip = sinon.spy();
|
||||
display.viewportChangeSize(2, 2);
|
||||
expect(display.flip).to.have.been.calledOnce;
|
||||
});
|
||||
|
||||
it('should report clipping when framebuffer > viewport', function () {
|
||||
var clipping = display.clippingDisplay();
|
||||
expect(clipping).to.be.true;
|
||||
});
|
||||
|
||||
it('should report not clipping when framebuffer = viewport', function () {
|
||||
display.viewportChangeSize(5, 5);
|
||||
var clipping = display.clippingDisplay();
|
||||
expect(clipping).to.be.false;
|
||||
});
|
||||
|
||||
it('should show the entire framebuffer when disabling the viewport', function() {
|
||||
display.set_viewport(false);
|
||||
expect(display.absX(0)).to.equal(0);
|
||||
expect(display.absY(0)).to.equal(0);
|
||||
expect(display._target.width).to.equal(5);
|
||||
expect(display._target.height).to.equal(5);
|
||||
});
|
||||
|
||||
it('should ignore viewport changes when the viewport is disabled', function() {
|
||||
display.set_viewport(false);
|
||||
display.viewportChangeSize(2, 2);
|
||||
display.viewportChangePos(1, 1);
|
||||
expect(display.absX(0)).to.equal(0);
|
||||
expect(display.absY(0)).to.equal(0);
|
||||
expect(display._target.width).to.equal(5);
|
||||
expect(display._target.height).to.equal(5);
|
||||
});
|
||||
|
||||
it('should show the entire framebuffer just after enabling the viewport', function() {
|
||||
display.set_viewport(false);
|
||||
display.set_viewport(true);
|
||||
expect(display.absX(0)).to.equal(0);
|
||||
expect(display.absY(0)).to.equal(0);
|
||||
expect(display._target.width).to.equal(5);
|
||||
expect(display._target.height).to.equal(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resizing', function () {
|
||||
var display;
|
||||
beforeEach(function () {
|
||||
display = new Display({ target: document.createElement('canvas'), prefer_js: false, viewport: false });
|
||||
display.resize(4, 4);
|
||||
});
|
||||
|
||||
it('should change the size of the logical canvas', function () {
|
||||
display.resize(5, 7);
|
||||
expect(display._fb_width).to.equal(5);
|
||||
expect(display._fb_height).to.equal(7);
|
||||
});
|
||||
|
||||
it('should keep the framebuffer data', function () {
|
||||
display.fillRect(0, 0, 4, 4, [0, 0, 0xff]);
|
||||
display.resize(2, 2);
|
||||
display.flip();
|
||||
var expected = [];
|
||||
for (var i = 0; i < 4 * 2*2; i += 4) {
|
||||
expected[i] = 0xff;
|
||||
expected[i+1] = expected[i+2] = 0;
|
||||
expected[i+3] = 0xff;
|
||||
}
|
||||
expect(display).to.have.displayed(new Uint8Array(expected));
|
||||
});
|
||||
|
||||
describe('viewport', function () {
|
||||
beforeEach(function () {
|
||||
display.set_viewport(true);
|
||||
display.viewportChangeSize(3, 3);
|
||||
display.viewportChangePos(1, 1);
|
||||
});
|
||||
|
||||
it('should keep the viewport position and size if possible', function () {
|
||||
display.resize(6, 6);
|
||||
expect(display.absX(0)).to.equal(1);
|
||||
expect(display.absY(0)).to.equal(1);
|
||||
expect(display._target.width).to.equal(3);
|
||||
expect(display._target.height).to.equal(3);
|
||||
});
|
||||
|
||||
it('should move the viewport if necessary', function () {
|
||||
display.resize(3, 3);
|
||||
expect(display.absX(0)).to.equal(0);
|
||||
expect(display.absY(0)).to.equal(0);
|
||||
expect(display._target.width).to.equal(3);
|
||||
expect(display._target.height).to.equal(3);
|
||||
});
|
||||
|
||||
it('should shrink the viewport if necessary', function () {
|
||||
display.resize(2, 2);
|
||||
expect(display.absX(0)).to.equal(0);
|
||||
expect(display.absY(0)).to.equal(0);
|
||||
expect(display._target.width).to.equal(2);
|
||||
expect(display._target.height).to.equal(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('rescaling', function () {
|
||||
var display;
|
||||
var canvas;
|
||||
|
||||
beforeEach(function () {
|
||||
display = new Display({ target: document.createElement('canvas'), prefer_js: false, viewport: true });
|
||||
display.resize(4, 4);
|
||||
display.viewportChangeSize(3, 3);
|
||||
display.viewportChangePos(1, 1);
|
||||
canvas = display.get_target();
|
||||
document.body.appendChild(canvas);
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
document.body.removeChild(canvas);
|
||||
});
|
||||
|
||||
it('should not change the bitmap size of the canvas', function () {
|
||||
display.set_scale(2.0);
|
||||
expect(canvas.width).to.equal(3);
|
||||
expect(canvas.height).to.equal(3);
|
||||
});
|
||||
|
||||
it('should change the effective rendered size of the canvas', function () {
|
||||
display.set_scale(2.0);
|
||||
expect(canvas.clientWidth).to.equal(6);
|
||||
expect(canvas.clientHeight).to.equal(6);
|
||||
});
|
||||
|
||||
it('should not change when resizing', function () {
|
||||
display.set_scale(2.0);
|
||||
display.resize(5, 5);
|
||||
expect(display.get_scale()).to.equal(2.0);
|
||||
expect(canvas.width).to.equal(3);
|
||||
expect(canvas.height).to.equal(3);
|
||||
expect(canvas.clientWidth).to.equal(6);
|
||||
expect(canvas.clientHeight).to.equal(6);
|
||||
});
|
||||
});
|
||||
|
||||
describe('autoscaling', function () {
|
||||
var display;
|
||||
var canvas;
|
||||
|
||||
beforeEach(function () {
|
||||
display = new Display({ target: document.createElement('canvas'), prefer_js: false, viewport: true });
|
||||
display.resize(4, 3);
|
||||
canvas = display.get_target();
|
||||
document.body.appendChild(canvas);
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
document.body.removeChild(canvas);
|
||||
});
|
||||
|
||||
it('should preserve aspect ratio while autoscaling', function () {
|
||||
display.autoscale(16, 9);
|
||||
expect(canvas.clientWidth / canvas.clientHeight).to.equal(4 / 3);
|
||||
});
|
||||
|
||||
it('should use width to determine scale when the current aspect ratio is wider than the target', function () {
|
||||
display.autoscale(9, 16);
|
||||
expect(display.absX(9)).to.equal(4);
|
||||
expect(display.absY(18)).to.equal(8);
|
||||
expect(canvas.clientWidth).to.equal(9);
|
||||
expect(canvas.clientHeight).to.equal(7); // round 9 / (4 / 3)
|
||||
});
|
||||
|
||||
it('should use height to determine scale when the current aspect ratio is taller than the target', function () {
|
||||
display.autoscale(16, 9);
|
||||
expect(display.absX(9)).to.equal(3);
|
||||
expect(display.absY(18)).to.equal(6);
|
||||
expect(canvas.clientWidth).to.equal(12); // 16 * (4 / 3)
|
||||
expect(canvas.clientHeight).to.equal(9);
|
||||
|
||||
});
|
||||
|
||||
it('should not change the bitmap size of the canvas', function () {
|
||||
display.autoscale(16, 9);
|
||||
expect(canvas.width).to.equal(4);
|
||||
expect(canvas.height).to.equal(3);
|
||||
});
|
||||
|
||||
it('should not upscale when downscaleOnly is true', function () {
|
||||
display.autoscale(2, 2, true);
|
||||
expect(display.absX(9)).to.equal(18);
|
||||
expect(display.absY(18)).to.equal(36);
|
||||
expect(canvas.clientWidth).to.equal(2);
|
||||
expect(canvas.clientHeight).to.equal(2);
|
||||
|
||||
display.autoscale(16, 9, true);
|
||||
expect(display.absX(9)).to.equal(9);
|
||||
expect(display.absY(18)).to.equal(18);
|
||||
expect(canvas.clientWidth).to.equal(4);
|
||||
expect(canvas.clientHeight).to.equal(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('drawing', function () {
|
||||
|
||||
// TODO(directxman12): improve the tests for each of the drawing functions to cover more than just the
|
||||
// basic cases
|
||||
function drawing_tests (pref_js) {
|
||||
var display;
|
||||
beforeEach(function () {
|
||||
display = new Display({ target: document.createElement('canvas'), prefer_js: pref_js });
|
||||
display.resize(4, 4);
|
||||
});
|
||||
|
||||
it('should clear the screen on #clear without a logo set', function () {
|
||||
display.fillRect(0, 0, 4, 4, [0x00, 0x00, 0xff]);
|
||||
display._logo = null;
|
||||
display.clear();
|
||||
display.resize(4, 4);
|
||||
var empty = [];
|
||||
for (var i = 0; i < 4 * display._fb_width * display._fb_height; i++) { empty[i] = 0; }
|
||||
expect(display).to.have.displayed(new Uint8Array(empty));
|
||||
});
|
||||
|
||||
it('should draw the logo on #clear with a logo set', function (done) {
|
||||
display._logo = { width: 4, height: 4, type: "image/png", data: make_image_png(checked_data) };
|
||||
display.clear();
|
||||
display.set_onFlush(function () {
|
||||
expect(display).to.have.displayed(checked_data);
|
||||
expect(display._fb_width).to.equal(4);
|
||||
expect(display._fb_height).to.equal(4);
|
||||
done();
|
||||
});
|
||||
display.flush();
|
||||
});
|
||||
|
||||
it('should not draw directly on the target canvas', function () {
|
||||
display.fillRect(0, 0, 4, 4, [0, 0, 0xff]);
|
||||
display.flip();
|
||||
display.fillRect(0, 0, 4, 4, [0, 0xff, 0]);
|
||||
var expected = [];
|
||||
for (var i = 0; i < 4 * display._fb_width * display._fb_height; i += 4) {
|
||||
expected[i] = 0xff;
|
||||
expected[i+1] = expected[i+2] = 0;
|
||||
expected[i+3] = 0xff;
|
||||
}
|
||||
expect(display).to.have.displayed(new Uint8Array(expected));
|
||||
});
|
||||
|
||||
it('should support filling a rectangle with particular color via #fillRect', function () {
|
||||
display.fillRect(0, 0, 4, 4, [0, 0xff, 0]);
|
||||
display.fillRect(0, 0, 2, 2, [0xff, 0, 0]);
|
||||
display.fillRect(2, 2, 2, 2, [0xff, 0, 0]);
|
||||
display.flip();
|
||||
expect(display).to.have.displayed(checked_data);
|
||||
});
|
||||
|
||||
it('should support copying an portion of the canvas via #copyImage', function () {
|
||||
display.fillRect(0, 0, 4, 4, [0, 0xff, 0]);
|
||||
display.fillRect(0, 0, 2, 2, [0xff, 0, 0x00]);
|
||||
display.copyImage(0, 0, 2, 2, 2, 2);
|
||||
display.flip();
|
||||
expect(display).to.have.displayed(checked_data);
|
||||
});
|
||||
|
||||
it('should support drawing images via #imageRect', function (done) {
|
||||
display.imageRect(0, 0, "image/png", make_image_png(checked_data));
|
||||
display.flip();
|
||||
display.set_onFlush(function () {
|
||||
expect(display).to.have.displayed(checked_data);
|
||||
done();
|
||||
});
|
||||
display.flush();
|
||||
});
|
||||
|
||||
it('should support drawing tile data with a background color and sub tiles', function () {
|
||||
display.startTile(0, 0, 4, 4, [0, 0xff, 0]);
|
||||
display.subTile(0, 0, 2, 2, [0xff, 0, 0]);
|
||||
display.subTile(2, 2, 2, 2, [0xff, 0, 0]);
|
||||
display.finishTile();
|
||||
display.flip();
|
||||
expect(display).to.have.displayed(checked_data);
|
||||
});
|
||||
|
||||
it('should support drawing BGRX blit images with true color via #blitImage', function () {
|
||||
var data = [];
|
||||
for (var i = 0; i < 16; i++) {
|
||||
data[i * 4] = checked_data[i * 4 + 2];
|
||||
data[i * 4 + 1] = checked_data[i * 4 + 1];
|
||||
data[i * 4 + 2] = checked_data[i * 4];
|
||||
data[i * 4 + 3] = checked_data[i * 4 + 3];
|
||||
}
|
||||
display.blitImage(0, 0, 4, 4, data, 0);
|
||||
display.flip();
|
||||
expect(display).to.have.displayed(checked_data);
|
||||
});
|
||||
|
||||
it('should support drawing RGB blit images with true color via #blitRgbImage', function () {
|
||||
var data = [];
|
||||
for (var i = 0; i < 16; i++) {
|
||||
data[i * 3] = checked_data[i * 4];
|
||||
data[i * 3 + 1] = checked_data[i * 4 + 1];
|
||||
data[i * 3 + 2] = checked_data[i * 4 + 2];
|
||||
}
|
||||
display.blitRgbImage(0, 0, 4, 4, data, 0);
|
||||
display.flip();
|
||||
expect(display).to.have.displayed(checked_data);
|
||||
});
|
||||
|
||||
it('should support drawing solid colors with color maps', function () {
|
||||
display._true_color = false;
|
||||
display.set_colourMap({ 0: [0xff, 0, 0], 1: [0, 0xff, 0] });
|
||||
display.fillRect(0, 0, 4, 4, 1);
|
||||
display.fillRect(0, 0, 2, 2, 0);
|
||||
display.fillRect(2, 2, 2, 2, 0);
|
||||
display.flip();
|
||||
expect(display).to.have.displayed(checked_data);
|
||||
});
|
||||
|
||||
it('should support drawing blit images with color maps', function () {
|
||||
display._true_color = false;
|
||||
display.set_colourMap({ 1: [0xff, 0, 0], 0: [0, 0xff, 0] });
|
||||
var data = [1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1].map(function (elem) { return [elem]; });
|
||||
display.blitImage(0, 0, 4, 4, data, 0);
|
||||
display.flip();
|
||||
expect(display).to.have.displayed(checked_data);
|
||||
});
|
||||
|
||||
it('should support drawing an image object via #drawImage', function () {
|
||||
var img = make_image_canvas(checked_data);
|
||||
display.drawImage(img, 0, 0);
|
||||
display.flip();
|
||||
expect(display).to.have.displayed(checked_data);
|
||||
});
|
||||
}
|
||||
|
||||
describe('(prefering native methods)', function () { drawing_tests.call(this, false); });
|
||||
describe('(prefering JavaScript)', function () { drawing_tests.call(this, true); });
|
||||
});
|
||||
|
||||
describe('the render queue processor', function () {
|
||||
var display;
|
||||
beforeEach(function () {
|
||||
display = new Display({ target: document.createElement('canvas'), prefer_js: false });
|
||||
display.resize(4, 4);
|
||||
sinon.spy(display, '_scan_renderQ');
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
window.requestAnimationFrame = this.old_requestAnimationFrame;
|
||||
});
|
||||
|
||||
it('should try to process an item when it is pushed on, if nothing else is on the queue', function () {
|
||||
display._renderQ_push({ type: 'noop' }); // does nothing
|
||||
expect(display._scan_renderQ).to.have.been.calledOnce;
|
||||
});
|
||||
|
||||
it('should not try to process an item when it is pushed on if we are waiting for other items', function () {
|
||||
display._renderQ.length = 2;
|
||||
display._renderQ_push({ type: 'noop' });
|
||||
expect(display._scan_renderQ).to.not.have.been.called;
|
||||
});
|
||||
|
||||
it('should wait until an image is loaded to attempt to draw it and the rest of the queue', function () {
|
||||
var img = { complete: false, addEventListener: sinon.spy() }
|
||||
display._renderQ = [{ type: 'img', x: 3, y: 4, img: img },
|
||||
{ type: 'fill', x: 1, y: 2, width: 3, height: 4, color: 5 }];
|
||||
display.drawImage = sinon.spy();
|
||||
display.fillRect = sinon.spy();
|
||||
|
||||
display._scan_renderQ();
|
||||
expect(display.drawImage).to.not.have.been.called;
|
||||
expect(display.fillRect).to.not.have.been.called;
|
||||
expect(img.addEventListener).to.have.been.calledOnce;
|
||||
|
||||
display._renderQ[0].img.complete = true;
|
||||
display._scan_renderQ();
|
||||
expect(display.drawImage).to.have.been.calledOnce;
|
||||
expect(display.fillRect).to.have.been.calledOnce;
|
||||
expect(img.addEventListener).to.have.been.calledOnce;
|
||||
});
|
||||
|
||||
it('should call callback when queue is flushed', function () {
|
||||
display.set_onFlush(sinon.spy());
|
||||
display.fillRect(0, 0, 4, 4, [0, 0xff, 0]);
|
||||
expect(display.get_onFlush()).to.not.have.been.called;
|
||||
display.flush();
|
||||
expect(display.get_onFlush()).to.have.been.calledOnce;
|
||||
});
|
||||
|
||||
it('should draw a blit image on type "blit"', function () {
|
||||
display.blitImage = sinon.spy();
|
||||
display._renderQ_push({ type: 'blit', x: 3, y: 4, width: 5, height: 6, data: [7, 8, 9] });
|
||||
expect(display.blitImage).to.have.been.calledOnce;
|
||||
expect(display.blitImage).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9], 0);
|
||||
});
|
||||
|
||||
it('should draw a blit RGB image on type "blitRgb"', function () {
|
||||
display.blitRgbImage = sinon.spy();
|
||||
display._renderQ_push({ type: 'blitRgb', x: 3, y: 4, width: 5, height: 6, data: [7, 8, 9] });
|
||||
expect(display.blitRgbImage).to.have.been.calledOnce;
|
||||
expect(display.blitRgbImage).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9], 0);
|
||||
});
|
||||
|
||||
it('should copy a region on type "copy"', function () {
|
||||
display.copyImage = sinon.spy();
|
||||
display._renderQ_push({ type: 'copy', x: 3, y: 4, width: 5, height: 6, old_x: 7, old_y: 8 });
|
||||
expect(display.copyImage).to.have.been.calledOnce;
|
||||
expect(display.copyImage).to.have.been.calledWith(7, 8, 3, 4, 5, 6);
|
||||
});
|
||||
|
||||
it('should fill a rect with a given color on type "fill"', function () {
|
||||
display.fillRect = sinon.spy();
|
||||
display._renderQ_push({ type: 'fill', x: 3, y: 4, width: 5, height: 6, color: [7, 8, 9]});
|
||||
expect(display.fillRect).to.have.been.calledOnce;
|
||||
expect(display.fillRect).to.have.been.calledWith(3, 4, 5, 6, [7, 8, 9]);
|
||||
});
|
||||
|
||||
it('should draw an image from an image object on type "img" (if complete)', function () {
|
||||
display.drawImage = sinon.spy();
|
||||
display._renderQ_push({ type: 'img', x: 3, y: 4, img: { complete: true } });
|
||||
expect(display.drawImage).to.have.been.calledOnce;
|
||||
expect(display.drawImage).to.have.been.calledWith({ complete: true }, 3, 4);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,266 @@
|
||||
// requires local modules: input/keysym, input/keysymdef, input/util
|
||||
|
||||
var assert = chai.assert;
|
||||
var expect = chai.expect;
|
||||
|
||||
describe('Helpers', function() {
|
||||
"use strict";
|
||||
describe('keysymFromKeyCode', function() {
|
||||
it('should map known keycodes to keysyms', function() {
|
||||
expect(KeyboardUtil.keysymFromKeyCode(0x41, false), 'a').to.be.equal(0x61);
|
||||
expect(KeyboardUtil.keysymFromKeyCode(0x41, true), 'A').to.be.equal(0x41);
|
||||
expect(KeyboardUtil.keysymFromKeyCode(0xd, false), 'enter').to.be.equal(0xFF0D);
|
||||
expect(KeyboardUtil.keysymFromKeyCode(0x11, false), 'ctrl').to.be.equal(0xFFE3);
|
||||
expect(KeyboardUtil.keysymFromKeyCode(0x12, false), 'alt').to.be.equal(0xFFE9);
|
||||
expect(KeyboardUtil.keysymFromKeyCode(0xe1, false), 'altgr').to.be.equal(0xFE03);
|
||||
expect(KeyboardUtil.keysymFromKeyCode(0x1b, false), 'esc').to.be.equal(0xFF1B);
|
||||
expect(KeyboardUtil.keysymFromKeyCode(0x26, false), 'up').to.be.equal(0xFF52);
|
||||
});
|
||||
it('should return null for unknown keycodes', function() {
|
||||
expect(KeyboardUtil.keysymFromKeyCode(0xc0, false), 'DK æ').to.be.null;
|
||||
expect(KeyboardUtil.keysymFromKeyCode(0xde, false), 'DK ø').to.be.null;
|
||||
});
|
||||
});
|
||||
|
||||
describe('keysyms.fromUnicode', function() {
|
||||
it('should map ASCII characters to keysyms', function() {
|
||||
expect(keysyms.fromUnicode('a'.charCodeAt())).to.have.property('keysym', 0x61);
|
||||
expect(keysyms.fromUnicode('A'.charCodeAt())).to.have.property('keysym', 0x41);
|
||||
});
|
||||
it('should map Latin-1 characters to keysyms', function() {
|
||||
expect(keysyms.fromUnicode('ø'.charCodeAt())).to.have.property('keysym', 0xf8);
|
||||
|
||||
expect(keysyms.fromUnicode('é'.charCodeAt())).to.have.property('keysym', 0xe9);
|
||||
});
|
||||
it('should map characters that are in Windows-1252 but not in Latin-1 to keysyms', function() {
|
||||
expect(keysyms.fromUnicode('Š'.charCodeAt())).to.have.property('keysym', 0x01a9);
|
||||
});
|
||||
it('should map characters which aren\'t in Latin1 *or* Windows-1252 to keysyms', function() {
|
||||
expect(keysyms.fromUnicode('ŵ'.charCodeAt())).to.have.property('keysym', 0x1000175);
|
||||
});
|
||||
it('should map unknown codepoints to the Unicode range', function() {
|
||||
expect(keysyms.fromUnicode('\n'.charCodeAt())).to.have.property('keysym', 0x100000a);
|
||||
expect(keysyms.fromUnicode('\u262D'.charCodeAt())).to.have.property('keysym', 0x100262d);
|
||||
});
|
||||
// This requires very recent versions of most browsers... skipping for now
|
||||
it.skip('should map UCS-4 codepoints to the Unicode range', function() {
|
||||
//expect(keysyms.fromUnicode('\u{1F686}'.codePointAt())).to.have.property('keysym', 0x101f686);
|
||||
});
|
||||
});
|
||||
|
||||
describe('substituteCodepoint', function() {
|
||||
it('should replace characters which don\'t have a keysym', function() {
|
||||
expect(KeyboardUtil.substituteCodepoint('Ș'.charCodeAt())).to.equal('Ş'.charCodeAt());
|
||||
expect(KeyboardUtil.substituteCodepoint('ș'.charCodeAt())).to.equal('ş'.charCodeAt());
|
||||
expect(KeyboardUtil.substituteCodepoint('Ț'.charCodeAt())).to.equal('Ţ'.charCodeAt());
|
||||
expect(KeyboardUtil.substituteCodepoint('ț'.charCodeAt())).to.equal('ţ'.charCodeAt());
|
||||
});
|
||||
it('should pass other characters through unchanged', function() {
|
||||
expect(KeyboardUtil.substituteCodepoint('T'.charCodeAt())).to.equal('T'.charCodeAt());
|
||||
});
|
||||
});
|
||||
|
||||
describe('nonCharacterKey', function() {
|
||||
it('should recognize the right keys', function() {
|
||||
expect(KeyboardUtil.nonCharacterKey({keyCode: 0xd}), 'enter').to.be.defined;
|
||||
expect(KeyboardUtil.nonCharacterKey({keyCode: 0x08}), 'backspace').to.be.defined;
|
||||
expect(KeyboardUtil.nonCharacterKey({keyCode: 0x09}), 'tab').to.be.defined;
|
||||
expect(KeyboardUtil.nonCharacterKey({keyCode: 0x10}), 'shift').to.be.defined;
|
||||
expect(KeyboardUtil.nonCharacterKey({keyCode: 0x11}), 'ctrl').to.be.defined;
|
||||
expect(KeyboardUtil.nonCharacterKey({keyCode: 0x12}), 'alt').to.be.defined;
|
||||
expect(KeyboardUtil.nonCharacterKey({keyCode: 0xe0}), 'meta').to.be.defined;
|
||||
});
|
||||
it('should not recognize character keys', function() {
|
||||
expect(KeyboardUtil.nonCharacterKey({keyCode: 'A'}), 'A').to.be.null;
|
||||
expect(KeyboardUtil.nonCharacterKey({keyCode: '1'}), '1').to.be.null;
|
||||
expect(KeyboardUtil.nonCharacterKey({keyCode: '.'}), '.').to.be.null;
|
||||
expect(KeyboardUtil.nonCharacterKey({keyCode: ' '}), 'space').to.be.null;
|
||||
});
|
||||
});
|
||||
|
||||
describe('getKeysym', function() {
|
||||
it('should prefer char', function() {
|
||||
expect(KeyboardUtil.getKeysym({char : 'a', charCode: 'Š'.charCodeAt(), keyCode: 0x42, which: 0x43})).to.have.property('keysym', 0x61);
|
||||
});
|
||||
it('should use charCode if no char', function() {
|
||||
expect(KeyboardUtil.getKeysym({char : '', charCode: 'Š'.charCodeAt(), keyCode: 0x42, which: 0x43})).to.have.property('keysym', 0x01a9);
|
||||
expect(KeyboardUtil.getKeysym({charCode: 'Š'.charCodeAt(), keyCode: 0x42, which: 0x43})).to.have.property('keysym', 0x01a9);
|
||||
expect(KeyboardUtil.getKeysym({char : 'hello', charCode: 'Š'.charCodeAt(), keyCode: 0x42, which: 0x43})).to.have.property('keysym', 0x01a9);
|
||||
});
|
||||
it('should use keyCode if no charCode', function() {
|
||||
expect(KeyboardUtil.getKeysym({keyCode: 0x42, which: 0x43, shiftKey: false})).to.have.property('keysym', 0x62);
|
||||
expect(KeyboardUtil.getKeysym({keyCode: 0x42, which: 0x43, shiftKey: true})).to.have.property('keysym', 0x42);
|
||||
});
|
||||
it('should use which if no keyCode', function() {
|
||||
expect(KeyboardUtil.getKeysym({which: 0x43, shiftKey: false})).to.have.property('keysym', 0x63);
|
||||
expect(KeyboardUtil.getKeysym({which: 0x43, shiftKey: true})).to.have.property('keysym', 0x43);
|
||||
});
|
||||
it('should substitute where applicable', function() {
|
||||
expect(KeyboardUtil.getKeysym({char : 'Ș'})).to.have.property('keysym', 0x1aa);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Modifier Sync', function() { // return a list of fake events necessary to fix modifier state
|
||||
describe('Toggle all modifiers', function() {
|
||||
var sync = KeyboardUtil.ModifierSync();
|
||||
it ('should do nothing if all modifiers are up as expected', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
ctrlKey: false,
|
||||
altKey: false,
|
||||
altGraphKey: false,
|
||||
shiftKey: false,
|
||||
metaKey: false})
|
||||
).to.have.lengthOf(0);
|
||||
});
|
||||
it ('should synthesize events if all keys are unexpectedly down', function() {
|
||||
var result = sync.keydown({
|
||||
keyCode: 0x41,
|
||||
ctrlKey: true,
|
||||
altKey: true,
|
||||
altGraphKey: true,
|
||||
shiftKey: true,
|
||||
metaKey: true
|
||||
});
|
||||
expect(result).to.have.lengthOf(5);
|
||||
var keysyms = {};
|
||||
for (var i = 0; i < result.length; ++i) {
|
||||
keysyms[result[i].keysym] = (result[i].type == 'keydown');
|
||||
}
|
||||
expect(keysyms[0xffe3]);
|
||||
expect(keysyms[0xffe9]);
|
||||
expect(keysyms[0xfe03]);
|
||||
expect(keysyms[0xffe1]);
|
||||
expect(keysyms[0xffe7]);
|
||||
});
|
||||
it ('should do nothing if all modifiers are down as expected', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
ctrlKey: true,
|
||||
altKey: true,
|
||||
altGraphKey: true,
|
||||
shiftKey: true,
|
||||
metaKey: true
|
||||
})).to.have.lengthOf(0);
|
||||
});
|
||||
});
|
||||
describe('Toggle Ctrl', function() {
|
||||
var sync = KeyboardUtil.ModifierSync();
|
||||
it('should sync if modifier is suddenly down', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
ctrlKey: true,
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xffe3), type: 'keydown'}]);
|
||||
});
|
||||
it('should sync if modifier is suddenly up', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
ctrlKey: false
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xffe3), type: 'keyup'}]);
|
||||
});
|
||||
});
|
||||
describe('Toggle Alt', function() {
|
||||
var sync = KeyboardUtil.ModifierSync();
|
||||
it('should sync if modifier is suddenly down', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
altKey: true,
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xffe9), type: 'keydown'}]);
|
||||
});
|
||||
it('should sync if modifier is suddenly up', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
altKey: false
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xffe9), type: 'keyup'}]);
|
||||
});
|
||||
});
|
||||
describe('Toggle AltGr', function() {
|
||||
var sync = KeyboardUtil.ModifierSync();
|
||||
it('should sync if modifier is suddenly down', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
altGraphKey: true,
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xfe03), type: 'keydown'}]);
|
||||
});
|
||||
it('should sync if modifier is suddenly up', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
altGraphKey: false
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xfe03), type: 'keyup'}]);
|
||||
});
|
||||
});
|
||||
describe('Toggle Shift', function() {
|
||||
var sync = KeyboardUtil.ModifierSync();
|
||||
it('should sync if modifier is suddenly down', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
shiftKey: true,
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xffe1), type: 'keydown'}]);
|
||||
});
|
||||
it('should sync if modifier is suddenly up', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
shiftKey: false
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xffe1), type: 'keyup'}]);
|
||||
});
|
||||
});
|
||||
describe('Toggle Meta', function() {
|
||||
var sync = KeyboardUtil.ModifierSync();
|
||||
it('should sync if modifier is suddenly down', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
metaKey: true,
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xffe7), type: 'keydown'}]);
|
||||
});
|
||||
it('should sync if modifier is suddenly up', function() {
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
metaKey: false
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xffe7), type: 'keyup'}]);
|
||||
});
|
||||
});
|
||||
describe('Modifier keyevents', function() {
|
||||
it('should not sync a modifier on its own events', function() {
|
||||
expect(KeyboardUtil.ModifierSync().keydown({
|
||||
keyCode: 0x11,
|
||||
ctrlKey: false
|
||||
})).to.be.deep.equal([]);
|
||||
expect(KeyboardUtil.ModifierSync().keydown({
|
||||
keyCode: 0x11,
|
||||
ctrlKey: true
|
||||
}), 'B').to.be.deep.equal([]);
|
||||
})
|
||||
it('should update state on modifier keyevents', function() {
|
||||
var sync = KeyboardUtil.ModifierSync();
|
||||
sync.keydown({
|
||||
keyCode: 0x11,
|
||||
});
|
||||
expect(sync.keydown({
|
||||
keyCode: 0x41,
|
||||
ctrlKey: true,
|
||||
})).to.be.deep.equal([]);
|
||||
});
|
||||
it('should sync other modifiers on ctrl events', function() {
|
||||
expect(KeyboardUtil.ModifierSync().keydown({
|
||||
keyCode: 0x11,
|
||||
altKey: true
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xffe9), type: 'keydown'}]);
|
||||
})
|
||||
});
|
||||
describe('sync modifiers on non-key events', function() {
|
||||
it('should generate sync events when receiving non-keyboard events', function() {
|
||||
expect(KeyboardUtil.ModifierSync().syncAny({
|
||||
altKey: true
|
||||
})).to.be.deep.equal([{keysym: keysyms.lookup(0xffe9), type: 'keydown'}]);
|
||||
});
|
||||
});
|
||||
describe('do not treat shift as a modifier key', function() {
|
||||
it('should not treat shift as a shortcut modifier', function() {
|
||||
expect(KeyboardUtil.hasShortcutModifier([], {0xffe1 : true})).to.be.false;
|
||||
});
|
||||
it('should not treat shift as a char modifier', function() {
|
||||
expect(KeyboardUtil.hasCharModifier([], {0xffe1 : true})).to.be.false;
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,842 @@
|
||||
// requires local modules: input/devices, input/util, input/keysymdef, input/keysym
|
||||
var assert = chai.assert;
|
||||
var expect = chai.expect;
|
||||
|
||||
/* jshint newcap: false, expr: true */
|
||||
describe('Key Event Pipeline Stages', function() {
|
||||
"use strict";
|
||||
describe('Decode Keyboard Events', function() {
|
||||
it('should pass events to the next stage', function(done) {
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt).to.be.an.object;
|
||||
done();
|
||||
}).keydown({keyCode: 0x41});
|
||||
});
|
||||
it('should pass the right keysym through', function(done) {
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt.keysym).to.be.deep.equal(keysyms.lookup(0x61));
|
||||
done();
|
||||
}).keypress({keyCode: 0x41});
|
||||
});
|
||||
it('should pass the right keyid through', function(done) {
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt).to.have.property('keyId', 0x41);
|
||||
done();
|
||||
}).keydown({keyCode: 0x41});
|
||||
});
|
||||
it('should not sync modifiers on a keypress', function() {
|
||||
// Firefox provides unreliable modifier state on keypress events
|
||||
var count = 0;
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
++count;
|
||||
}).keypress({keyCode: 0x41, ctrlKey: true});
|
||||
expect(count).to.be.equal(1);
|
||||
});
|
||||
it('should sync modifiers if necessary', function(done) {
|
||||
var count = 0;
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
switch (count) {
|
||||
case 0: // fake a ctrl keydown
|
||||
expect(evt).to.be.deep.equal({keysym: keysyms.lookup(0xffe3), type: 'keydown'});
|
||||
++count;
|
||||
break;
|
||||
case 1:
|
||||
expect(evt).to.be.deep.equal({keyId: 0x41, type: 'keydown', keysym: keysyms.lookup(0x61)});
|
||||
done();
|
||||
break;
|
||||
}
|
||||
}).keydown({keyCode: 0x41, ctrlKey: true});
|
||||
});
|
||||
it('should forward keydown events with the right type', function(done) {
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt).to.be.deep.equal({keyId: 0x41, type: 'keydown'});
|
||||
done();
|
||||
}).keydown({keyCode: 0x41});
|
||||
});
|
||||
it('should forward keyup events with the right type', function(done) {
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt).to.be.deep.equal({keyId: 0x41, keysym: keysyms.lookup(0x61), type: 'keyup'});
|
||||
done();
|
||||
}).keyup({keyCode: 0x41});
|
||||
});
|
||||
it('should forward keypress events with the right type', function(done) {
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt).to.be.deep.equal({keyId: 0x41, keysym: keysyms.lookup(0x61), type: 'keypress'});
|
||||
done();
|
||||
}).keypress({keyCode: 0x41});
|
||||
});
|
||||
it('should generate stalls if a char modifier is down while a key is pressed', function(done) {
|
||||
var count = 0;
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync([0xfe03]), function(evt) {
|
||||
switch (count) {
|
||||
case 0: // fake altgr
|
||||
expect(evt).to.be.deep.equal({keysym: keysyms.lookup(0xfe03), type: 'keydown'});
|
||||
++count;
|
||||
break;
|
||||
case 1: // stall before processing the 'a' keydown
|
||||
expect(evt).to.be.deep.equal({type: 'stall'});
|
||||
++count;
|
||||
break;
|
||||
case 2: // 'a'
|
||||
expect(evt).to.be.deep.equal({
|
||||
type: 'keydown',
|
||||
keyId: 0x41,
|
||||
keysym: keysyms.lookup(0x61)
|
||||
});
|
||||
|
||||
done();
|
||||
break;
|
||||
}
|
||||
}).keydown({keyCode: 0x41, altGraphKey: true});
|
||||
|
||||
});
|
||||
describe('suppress the right events at the right time', function() {
|
||||
it('should suppress anything while a shortcut modifier is down', function() {
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {});
|
||||
|
||||
obj.keydown({keyCode: 0x11}); // press ctrl
|
||||
expect(obj.keydown({keyCode: 'A'.charCodeAt()})).to.be.true;
|
||||
expect(obj.keydown({keyCode: ' '.charCodeAt()})).to.be.true;
|
||||
expect(obj.keydown({keyCode: '1'.charCodeAt()})).to.be.true;
|
||||
expect(obj.keydown({keyCode: 0x3c})).to.be.true; // < key on DK Windows
|
||||
expect(obj.keydown({keyCode: 0xde})).to.be.true; // Ø key on DK
|
||||
});
|
||||
it('should suppress non-character keys', function() {
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {});
|
||||
|
||||
expect(obj.keydown({keyCode: 0x08}), 'a').to.be.true;
|
||||
expect(obj.keydown({keyCode: 0x09}), 'b').to.be.true;
|
||||
expect(obj.keydown({keyCode: 0x11}), 'd').to.be.true;
|
||||
expect(obj.keydown({keyCode: 0x12}), 'e').to.be.true;
|
||||
});
|
||||
it('should not suppress shift', function() {
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {});
|
||||
|
||||
expect(obj.keydown({keyCode: 0x10}), 'd').to.be.false;
|
||||
});
|
||||
it('should generate event for shift keydown', function() {
|
||||
var called = false;
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt).to.have.property('keysym');
|
||||
called = true;
|
||||
}).keydown({keyCode: 0x10});
|
||||
expect(called).to.be.true;
|
||||
});
|
||||
it('should not suppress character keys', function() {
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {});
|
||||
|
||||
expect(obj.keydown({keyCode: 'A'.charCodeAt()})).to.be.false;
|
||||
expect(obj.keydown({keyCode: ' '.charCodeAt()})).to.be.false;
|
||||
expect(obj.keydown({keyCode: '1'.charCodeAt()})).to.be.false;
|
||||
expect(obj.keydown({keyCode: 0x3c})).to.be.false; // < key on DK Windows
|
||||
expect(obj.keydown({keyCode: 0xde})).to.be.false; // Ø key on DK
|
||||
});
|
||||
it('should not suppress if a char modifier is down', function() {
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync([0xfe03]), function(evt) {});
|
||||
|
||||
obj.keydown({keyCode: 0xe1}); // press altgr
|
||||
expect(obj.keydown({keyCode: 'A'.charCodeAt()})).to.be.false;
|
||||
expect(obj.keydown({keyCode: ' '.charCodeAt()})).to.be.false;
|
||||
expect(obj.keydown({keyCode: '1'.charCodeAt()})).to.be.false;
|
||||
expect(obj.keydown({keyCode: 0x3c})).to.be.false; // < key on DK Windows
|
||||
expect(obj.keydown({keyCode: 0xde})).to.be.false; // Ø key on DK
|
||||
});
|
||||
});
|
||||
describe('Keypress and keyup events', function() {
|
||||
it('should always suppress event propagation', function() {
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {});
|
||||
|
||||
expect(obj.keypress({keyCode: 'A'.charCodeAt()})).to.be.true;
|
||||
expect(obj.keypress({keyCode: 0x3c})).to.be.true; // < key on DK Windows
|
||||
expect(obj.keypress({keyCode: 0x11})).to.be.true;
|
||||
|
||||
expect(obj.keyup({keyCode: 'A'.charCodeAt()})).to.be.true;
|
||||
expect(obj.keyup({keyCode: 0x3c})).to.be.true; // < key on DK Windows
|
||||
expect(obj.keyup({keyCode: 0x11})).to.be.true;
|
||||
});
|
||||
it('should never generate stalls', function() {
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt.type).to.not.be.equal('stall');
|
||||
});
|
||||
|
||||
obj.keypress({keyCode: 'A'.charCodeAt()});
|
||||
obj.keypress({keyCode: 0x3c});
|
||||
obj.keypress({keyCode: 0x11});
|
||||
|
||||
obj.keyup({keyCode: 'A'.charCodeAt()});
|
||||
obj.keyup({keyCode: 0x3c});
|
||||
obj.keyup({keyCode: 0x11});
|
||||
});
|
||||
});
|
||||
describe('mark events if a char modifier is down', function() {
|
||||
it('should not mark modifiers on a keydown event', function() {
|
||||
var times_called = 0;
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync([0xfe03]), function(evt) {
|
||||
switch (times_called++) {
|
||||
case 0: //altgr
|
||||
break;
|
||||
case 1: // 'a'
|
||||
expect(evt).to.not.have.property('escape');
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
obj.keydown({keyCode: 0xe1}); // press altgr
|
||||
obj.keydown({keyCode: 'A'.charCodeAt()});
|
||||
});
|
||||
|
||||
it('should indicate on events if a single-key char modifier is down', function(done) {
|
||||
var times_called = 0;
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync([0xfe03]), function(evt) {
|
||||
switch (times_called++) {
|
||||
case 0: //altgr
|
||||
break;
|
||||
case 1: // 'a'
|
||||
expect(evt).to.be.deep.equal({
|
||||
type: 'keypress',
|
||||
keyId: 'A'.charCodeAt(),
|
||||
keysym: keysyms.lookup('a'.charCodeAt()),
|
||||
escape: [0xfe03]
|
||||
});
|
||||
done();
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
obj.keydown({keyCode: 0xe1}); // press altgr
|
||||
obj.keypress({keyCode: 'A'.charCodeAt()});
|
||||
});
|
||||
it('should indicate on events if a multi-key char modifier is down', function(done) {
|
||||
var times_called = 0;
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync([0xffe9, 0xffe3]), function(evt) {
|
||||
switch (times_called++) {
|
||||
case 0: //ctrl
|
||||
break;
|
||||
case 1: //alt
|
||||
break;
|
||||
case 2: // 'a'
|
||||
expect(evt).to.be.deep.equal({
|
||||
type: 'keypress',
|
||||
keyId: 'A'.charCodeAt(),
|
||||
keysym: keysyms.lookup('a'.charCodeAt()),
|
||||
escape: [0xffe9, 0xffe3]
|
||||
});
|
||||
done();
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
obj.keydown({keyCode: 0x11}); // press ctrl
|
||||
obj.keydown({keyCode: 0x12}); // press alt
|
||||
obj.keypress({keyCode: 'A'.charCodeAt()});
|
||||
});
|
||||
it('should not consider a char modifier to be down on the modifier key itself', function() {
|
||||
var obj = KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync([0xfe03]), function(evt) {
|
||||
expect(evt).to.not.have.property('escape');
|
||||
});
|
||||
|
||||
obj.keydown({keyCode: 0xe1}); // press altgr
|
||||
|
||||
});
|
||||
});
|
||||
describe('add/remove keysym', function() {
|
||||
it('should remove keysym from keydown if a char key and no modifier', function() {
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt).to.be.deep.equal({keyId: 0x41, type: 'keydown'});
|
||||
}).keydown({keyCode: 0x41});
|
||||
});
|
||||
it('should not remove keysym from keydown if a shortcut modifier is down', function() {
|
||||
var times_called = 0;
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
switch (times_called++) {
|
||||
case 1:
|
||||
expect(evt).to.be.deep.equal({keyId: 0x41, keysym: keysyms.lookup(0x61), type: 'keydown'});
|
||||
break;
|
||||
}
|
||||
}).keydown({keyCode: 0x41, ctrlKey: true});
|
||||
expect(times_called).to.be.equal(2);
|
||||
});
|
||||
it('should not remove keysym from keydown if a char modifier is down', function() {
|
||||
var times_called = 0;
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync([0xfe03]), function(evt) {
|
||||
switch (times_called++) {
|
||||
case 2:
|
||||
expect(evt).to.be.deep.equal({keyId: 0x41, keysym: keysyms.lookup(0x61), type: 'keydown'});
|
||||
break;
|
||||
}
|
||||
}).keydown({keyCode: 0x41, altGraphKey: true});
|
||||
expect(times_called).to.be.equal(3);
|
||||
});
|
||||
it('should not remove keysym from keydown if key is noncharacter', function() {
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt, 'bacobjpace').to.be.deep.equal({keyId: 0x09, keysym: keysyms.lookup(0xff09), type: 'keydown'});
|
||||
}).keydown({keyCode: 0x09});
|
||||
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt, 'ctrl').to.be.deep.equal({keyId: 0x11, keysym: keysyms.lookup(0xffe3), type: 'keydown'});
|
||||
}).keydown({keyCode: 0x11});
|
||||
});
|
||||
it('should never remove keysym from keypress', function() {
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt).to.be.deep.equal({keyId: 0x41, keysym: keysyms.lookup(0x61), type: 'keypress'});
|
||||
}).keypress({keyCode: 0x41});
|
||||
});
|
||||
it('should never remove keysym from keyup', function() {
|
||||
KeyboardUtil.KeyEventDecoder(KeyboardUtil.ModifierSync(), function(evt) {
|
||||
expect(evt).to.be.deep.equal({keyId: 0x41, keysym: keysyms.lookup(0x61), type: 'keyup'});
|
||||
}).keyup({keyCode: 0x41});
|
||||
});
|
||||
});
|
||||
// on keypress, keyup(?), always set keysym
|
||||
// on keydown, only do it if we don't expect a keypress: if noncharacter OR modifier is down
|
||||
});
|
||||
|
||||
describe('Verify that char modifiers are active', function() {
|
||||
it('should pass keydown events through if there is no stall', function(done) {
|
||||
var obj = KeyboardUtil.VerifyCharModifier(function(evt){
|
||||
expect(evt).to.deep.equal({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x41)});
|
||||
done();
|
||||
})({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x41)});
|
||||
});
|
||||
it('should pass keyup events through if there is no stall', function(done) {
|
||||
var obj = KeyboardUtil.VerifyCharModifier(function(evt){
|
||||
expect(evt).to.deep.equal({type: 'keyup', keyId: 0x41, keysym: keysyms.lookup(0x41)});
|
||||
done();
|
||||
})({type: 'keyup', keyId: 0x41, keysym: keysyms.lookup(0x41)});
|
||||
});
|
||||
it('should pass keypress events through if there is no stall', function(done) {
|
||||
var obj = KeyboardUtil.VerifyCharModifier(function(evt){
|
||||
expect(evt).to.deep.equal({type: 'keypress', keyId: 0x41, keysym: keysyms.lookup(0x41)});
|
||||
done();
|
||||
})({type: 'keypress', keyId: 0x41, keysym: keysyms.lookup(0x41)});
|
||||
});
|
||||
it('should not pass stall events through', function(done){
|
||||
var obj = KeyboardUtil.VerifyCharModifier(function(evt){
|
||||
// should only be called once, for the keydown
|
||||
expect(evt).to.deep.equal({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x41)});
|
||||
done();
|
||||
});
|
||||
|
||||
obj({type: 'stall'});
|
||||
obj({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x41)});
|
||||
});
|
||||
it('should merge keydown and keypress events if they come after a stall', function(done) {
|
||||
var next_called = false;
|
||||
var obj = KeyboardUtil.VerifyCharModifier(function(evt){
|
||||
// should only be called once, for the keydown
|
||||
expect(next_called).to.be.false;
|
||||
next_called = true;
|
||||
expect(evt).to.deep.equal({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x44)});
|
||||
done();
|
||||
});
|
||||
|
||||
obj({type: 'stall'});
|
||||
obj({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
obj({type: 'keypress', keyId: 0x43, keysym: keysyms.lookup(0x44)});
|
||||
expect(next_called).to.be.false;
|
||||
});
|
||||
it('should preserve modifier attribute when merging if keysyms differ', function(done) {
|
||||
var next_called = false;
|
||||
var obj = KeyboardUtil.VerifyCharModifier(function(evt){
|
||||
// should only be called once, for the keydown
|
||||
expect(next_called).to.be.false;
|
||||
next_called = true;
|
||||
expect(evt).to.deep.equal({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x44), escape: [0xffe3]});
|
||||
done();
|
||||
});
|
||||
|
||||
obj({type: 'stall'});
|
||||
obj({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
obj({type: 'keypress', keyId: 0x43, keysym: keysyms.lookup(0x44), escape: [0xffe3]});
|
||||
expect(next_called).to.be.false;
|
||||
});
|
||||
it('should not preserve modifier attribute when merging if keysyms are the same', function() {
|
||||
var obj = KeyboardUtil.VerifyCharModifier(function(evt){
|
||||
expect(evt).to.not.have.property('escape');
|
||||
});
|
||||
|
||||
obj({type: 'stall'});
|
||||
obj({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
obj({type: 'keypress', keyId: 0x43, keysym: keysyms.lookup(0x42), escape: [0xffe3]});
|
||||
});
|
||||
it('should not merge keydown and keypress events if there is no stall', function(done) {
|
||||
var times_called = 0;
|
||||
var obj = KeyboardUtil.VerifyCharModifier(function(evt){
|
||||
switch(times_called) {
|
||||
case 0:
|
||||
expect(evt).to.deep.equal({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
break;
|
||||
case 1:
|
||||
expect(evt).to.deep.equal({type: 'keypress', keyId: 0x43, keysym: keysyms.lookup(0x44)});
|
||||
done();
|
||||
break;
|
||||
}
|
||||
|
||||
++times_called;
|
||||
});
|
||||
|
||||
obj({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
obj({type: 'keypress', keyId: 0x43, keysym: keysyms.lookup(0x44)});
|
||||
});
|
||||
it('should not merge keydown and keypress events if separated by another event', function(done) {
|
||||
var times_called = 0;
|
||||
var obj = KeyboardUtil.VerifyCharModifier(function(evt){
|
||||
switch(times_called) {
|
||||
case 0:
|
||||
expect(evt,1).to.deep.equal({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
break;
|
||||
case 1:
|
||||
expect(evt,2).to.deep.equal({type: 'keyup', keyId: 0x43, keysym: keysyms.lookup(0x44)});
|
||||
break;
|
||||
case 2:
|
||||
expect(evt,3).to.deep.equal({type: 'keypress', keyId: 0x45, keysym: keysyms.lookup(0x46)});
|
||||
done();
|
||||
break;
|
||||
}
|
||||
|
||||
++times_called;
|
||||
});
|
||||
|
||||
obj({type: 'stall'});
|
||||
obj({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
obj({type: 'keyup', keyId: 0x43, keysym: keysyms.lookup(0x44)});
|
||||
obj({type: 'keypress', keyId: 0x45, keysym: keysyms.lookup(0x46)});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Track Key State', function() {
|
||||
it('should do nothing on keyup events if no keys are down', function() {
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
expect(true).to.be.false;
|
||||
});
|
||||
obj({type: 'keyup', keyId: 0x41});
|
||||
});
|
||||
it('should insert into the queue on keydown if no keys are down', function() {
|
||||
var times_called = 0;
|
||||
var elem = null;
|
||||
var keysymsdown = {};
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
++times_called;
|
||||
if (elem.type == 'keyup') {
|
||||
expect(evt).to.have.property('keysym');
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
delete keysymsdown[evt.keysym.keysym];
|
||||
}
|
||||
else {
|
||||
expect(evt).to.be.deep.equal(elem);
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
}
|
||||
elem = null;
|
||||
});
|
||||
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)};
|
||||
keysymsdown[keysyms.lookup(0x42).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keyup', keyId: 0x41};
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
expect(times_called).to.be.equal(2);
|
||||
});
|
||||
it('should insert into the queue on keypress if no keys are down', function() {
|
||||
var times_called = 0;
|
||||
var elem = null;
|
||||
var keysymsdown = {};
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
++times_called;
|
||||
if (elem.type == 'keyup') {
|
||||
expect(evt).to.have.property('keysym');
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
delete keysymsdown[evt.keysym.keysym];
|
||||
}
|
||||
else {
|
||||
expect(evt).to.be.deep.equal(elem);
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
}
|
||||
elem = null;
|
||||
});
|
||||
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keypress', keyId: 0x41, keysym: keysyms.lookup(0x42)};
|
||||
keysymsdown[keysyms.lookup(0x42).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keyup', keyId: 0x41};
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
expect(times_called).to.be.equal(2);
|
||||
});
|
||||
it('should add keysym to last key entry if keyId matches', function() {
|
||||
// this implies that a single keyup will release both keysyms
|
||||
var times_called = 0;
|
||||
var elem = null;
|
||||
var keysymsdown = {};
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
++times_called;
|
||||
if (elem.type == 'keyup') {
|
||||
expect(evt).to.have.property('keysym');
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
delete keysymsdown[evt.keysym.keysym];
|
||||
}
|
||||
else {
|
||||
expect(evt).to.be.deep.equal(elem);
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
elem = null;
|
||||
}
|
||||
});
|
||||
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keypress', keyId: 0x41, keysym: keysyms.lookup(0x42)};
|
||||
keysymsdown[keysyms.lookup(0x42).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keypress', keyId: 0x41, keysym: keysyms.lookup(0x43)};
|
||||
keysymsdown[keysyms.lookup(0x43).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keyup', keyId: 0x41};
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(4);
|
||||
});
|
||||
it('should create new key entry if keyId matches and keysym does not', function() {
|
||||
// this implies that a single keyup will release both keysyms
|
||||
var times_called = 0;
|
||||
var elem = null;
|
||||
var keysymsdown = {};
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
++times_called;
|
||||
if (elem.type == 'keyup') {
|
||||
expect(evt).to.have.property('keysym');
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
delete keysymsdown[evt.keysym.keysym];
|
||||
}
|
||||
else {
|
||||
expect(evt).to.be.deep.equal(elem);
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
elem = null;
|
||||
}
|
||||
});
|
||||
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keydown', keyId: 0, keysym: keysyms.lookup(0x42)};
|
||||
keysymsdown[keysyms.lookup(0x42).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keydown', keyId: 0, keysym: keysyms.lookup(0x43)};
|
||||
keysymsdown[keysyms.lookup(0x43).keysym] = true;
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(2);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keyup', keyId: 0};
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(3);
|
||||
elem = {type: 'keyup', keyId: 0};
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(4);
|
||||
});
|
||||
it('should merge key entry if keyIds are zero and keysyms match', function() {
|
||||
// this implies that a single keyup will release both keysyms
|
||||
var times_called = 0;
|
||||
var elem = null;
|
||||
var keysymsdown = {};
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
++times_called;
|
||||
if (elem.type == 'keyup') {
|
||||
expect(evt).to.have.property('keysym');
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
delete keysymsdown[evt.keysym.keysym];
|
||||
}
|
||||
else {
|
||||
expect(evt).to.be.deep.equal(elem);
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
elem = null;
|
||||
}
|
||||
});
|
||||
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keydown', keyId: 0, keysym: keysyms.lookup(0x42)};
|
||||
keysymsdown[keysyms.lookup(0x42).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keydown', keyId: 0, keysym: keysyms.lookup(0x42)};
|
||||
keysymsdown[keysyms.lookup(0x42).keysym] = true;
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(2);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keyup', keyId: 0};
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(3);
|
||||
});
|
||||
it('should add keysym as separate entry if keyId does not match last event', function() {
|
||||
// this implies that separate keyups are required
|
||||
var times_called = 0;
|
||||
var elem = null;
|
||||
var keysymsdown = {};
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
++times_called;
|
||||
if (elem.type == 'keyup') {
|
||||
expect(evt).to.have.property('keysym');
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
delete keysymsdown[evt.keysym.keysym];
|
||||
}
|
||||
else {
|
||||
expect(evt).to.be.deep.equal(elem);
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
elem = null;
|
||||
}
|
||||
});
|
||||
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keypress', keyId: 0x41, keysym: keysyms.lookup(0x42)};
|
||||
keysymsdown[keysyms.lookup(0x42).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keypress', keyId: 0x42, keysym: keysyms.lookup(0x43)};
|
||||
keysymsdown[keysyms.lookup(0x43).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keyup', keyId: 0x41};
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(4);
|
||||
elem = {type: 'keyup', keyId: 0x42};
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(4);
|
||||
});
|
||||
it('should add keysym as separate entry if keyId does not match last event and first is zero', function() {
|
||||
// this implies that separate keyups are required
|
||||
var times_called = 0;
|
||||
var elem = null;
|
||||
var keysymsdown = {};
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
++times_called;
|
||||
if (elem.type == 'keyup') {
|
||||
expect(evt).to.have.property('keysym');
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
delete keysymsdown[evt.keysym.keysym];
|
||||
}
|
||||
else {
|
||||
expect(evt).to.be.deep.equal(elem);
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
elem = null;
|
||||
}
|
||||
});
|
||||
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keydown', keyId: 0, keysym: keysyms.lookup(0x42)};
|
||||
keysymsdown[keysyms.lookup(0x42).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keydown', keyId: 0x42, keysym: keysyms.lookup(0x43)};
|
||||
keysymsdown[keysyms.lookup(0x43).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
expect(times_called).to.be.equal(2);
|
||||
elem = {type: 'keyup', keyId: 0};
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(3);
|
||||
elem = {type: 'keyup', keyId: 0x42};
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(4);
|
||||
});
|
||||
it('should add keysym as separate entry if keyId does not match last event and second is zero', function() {
|
||||
// this implies that a separate keyups are required
|
||||
var times_called = 0;
|
||||
var elem = null;
|
||||
var keysymsdown = {};
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
++times_called;
|
||||
if (elem.type == 'keyup') {
|
||||
expect(evt).to.have.property('keysym');
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
delete keysymsdown[evt.keysym.keysym];
|
||||
}
|
||||
else {
|
||||
expect(evt).to.be.deep.equal(elem);
|
||||
expect (keysymsdown[evt.keysym.keysym]).to.not.be.undefined;
|
||||
elem = null;
|
||||
}
|
||||
});
|
||||
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)};
|
||||
keysymsdown[keysyms.lookup(0x42).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keydown', keyId: 0, keysym: keysyms.lookup(0x43)};
|
||||
keysymsdown[keysyms.lookup(0x43).keysym] = true;
|
||||
obj(elem);
|
||||
expect(elem).to.be.null;
|
||||
elem = {type: 'keyup', keyId: 0x41};
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(3);
|
||||
elem = {type: 'keyup', keyId: 0};
|
||||
obj(elem);
|
||||
expect(times_called).to.be.equal(4);
|
||||
});
|
||||
it('should pop matching key event on keyup', function() {
|
||||
var times_called = 0;
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
switch (times_called++) {
|
||||
case 0:
|
||||
case 1:
|
||||
case 2:
|
||||
expect(evt.type).to.be.equal('keydown');
|
||||
break;
|
||||
case 3:
|
||||
expect(evt).to.be.deep.equal({type: 'keyup', keyId: 0x42, keysym: keysyms.lookup(0x62)});
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
obj({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x61)});
|
||||
obj({type: 'keydown', keyId: 0x42, keysym: keysyms.lookup(0x62)});
|
||||
obj({type: 'keydown', keyId: 0x43, keysym: keysyms.lookup(0x63)});
|
||||
obj({type: 'keyup', keyId: 0x42});
|
||||
expect(times_called).to.equal(4);
|
||||
});
|
||||
it('should pop the first zero keyevent on keyup with zero keyId', function() {
|
||||
var times_called = 0;
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
switch (times_called++) {
|
||||
case 0:
|
||||
case 1:
|
||||
case 2:
|
||||
expect(evt.type).to.be.equal('keydown');
|
||||
break;
|
||||
case 3:
|
||||
expect(evt).to.be.deep.equal({type: 'keyup', keyId: 0, keysym: keysyms.lookup(0x61)});
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
obj({type: 'keydown', keyId: 0, keysym: keysyms.lookup(0x61)});
|
||||
obj({type: 'keydown', keyId: 0, keysym: keysyms.lookup(0x62)});
|
||||
obj({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x63)});
|
||||
obj({type: 'keyup', keyId: 0x0});
|
||||
expect(times_called).to.equal(4);
|
||||
});
|
||||
it('should pop the last keyevents keysym if no match is found for keyId', function() {
|
||||
var times_called = 0;
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
switch (times_called++) {
|
||||
case 0:
|
||||
case 1:
|
||||
case 2:
|
||||
expect(evt.type).to.be.equal('keydown');
|
||||
break;
|
||||
case 3:
|
||||
expect(evt).to.be.deep.equal({type: 'keyup', keyId: 0x44, keysym: keysyms.lookup(0x63)});
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
obj({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x61)});
|
||||
obj({type: 'keydown', keyId: 0x42, keysym: keysyms.lookup(0x62)});
|
||||
obj({type: 'keydown', keyId: 0x43, keysym: keysyms.lookup(0x63)});
|
||||
obj({type: 'keyup', keyId: 0x44});
|
||||
expect(times_called).to.equal(4);
|
||||
});
|
||||
describe('Firefox sends keypress even when keydown is suppressed', function() {
|
||||
it('should discard the keypress', function() {
|
||||
var times_called = 0;
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
expect(times_called).to.be.equal(0);
|
||||
++times_called;
|
||||
});
|
||||
|
||||
obj({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
expect(times_called).to.be.equal(1);
|
||||
obj({type: 'keypress', keyId: 0x41, keysym: keysyms.lookup(0x43)});
|
||||
});
|
||||
});
|
||||
describe('releaseAll', function() {
|
||||
it('should do nothing if no keys have been pressed', function() {
|
||||
var times_called = 0;
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
++times_called;
|
||||
});
|
||||
obj({type: 'releaseall'});
|
||||
expect(times_called).to.be.equal(0);
|
||||
});
|
||||
it('should release the keys that have been pressed', function() {
|
||||
var times_called = 0;
|
||||
var obj = KeyboardUtil.TrackKeyState(function(evt) {
|
||||
switch (times_called++) {
|
||||
case 2:
|
||||
expect(evt).to.be.deep.equal({type: 'keyup', keyId: 0, keysym: keysyms.lookup(0x41)});
|
||||
break;
|
||||
case 3:
|
||||
expect(evt).to.be.deep.equal({type: 'keyup', keyId: 0, keysym: keysyms.lookup(0x42)});
|
||||
break;
|
||||
}
|
||||
});
|
||||
obj({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x41)});
|
||||
obj({type: 'keydown', keyId: 0x42, keysym: keysyms.lookup(0x42)});
|
||||
expect(times_called).to.be.equal(2);
|
||||
obj({type: 'releaseall'});
|
||||
expect(times_called).to.be.equal(4);
|
||||
obj({type: 'releaseall'});
|
||||
expect(times_called).to.be.equal(4);
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('Escape Modifiers', function() {
|
||||
describe('Keydown', function() {
|
||||
it('should pass through when a char modifier is not down', function() {
|
||||
var times_called = 0;
|
||||
KeyboardUtil.EscapeModifiers(function(evt) {
|
||||
expect(times_called).to.be.equal(0);
|
||||
++times_called;
|
||||
expect(evt).to.be.deep.equal({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
})({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
expect(times_called).to.be.equal(1);
|
||||
});
|
||||
it('should generate fake undo/redo events when a char modifier is down', function() {
|
||||
var times_called = 0;
|
||||
KeyboardUtil.EscapeModifiers(function(evt) {
|
||||
switch(times_called++) {
|
||||
case 0:
|
||||
expect(evt).to.be.deep.equal({type: 'keyup', keyId: 0, keysym: keysyms.lookup(0xffe9)});
|
||||
break;
|
||||
case 1:
|
||||
expect(evt).to.be.deep.equal({type: 'keyup', keyId: 0, keysym: keysyms.lookup(0xffe3)});
|
||||
break;
|
||||
case 2:
|
||||
expect(evt).to.be.deep.equal({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42), escape: [0xffe9, 0xffe3]});
|
||||
break;
|
||||
case 3:
|
||||
expect(evt).to.be.deep.equal({type: 'keydown', keyId: 0, keysym: keysyms.lookup(0xffe9)});
|
||||
break;
|
||||
case 4:
|
||||
expect(evt).to.be.deep.equal({type: 'keydown', keyId: 0, keysym: keysyms.lookup(0xffe3)});
|
||||
break;
|
||||
}
|
||||
})({type: 'keydown', keyId: 0x41, keysym: keysyms.lookup(0x42), escape: [0xffe9, 0xffe3]});
|
||||
expect(times_called).to.be.equal(5);
|
||||
});
|
||||
});
|
||||
describe('Keyup', function() {
|
||||
it('should pass through when a char modifier is down', function() {
|
||||
var times_called = 0;
|
||||
KeyboardUtil.EscapeModifiers(function(evt) {
|
||||
expect(times_called).to.be.equal(0);
|
||||
++times_called;
|
||||
expect(evt).to.be.deep.equal({type: 'keyup', keyId: 0x41, keysym: keysyms.lookup(0x42), escape: [0xfe03]});
|
||||
})({type: 'keyup', keyId: 0x41, keysym: keysyms.lookup(0x42), escape: [0xfe03]});
|
||||
expect(times_called).to.be.equal(1);
|
||||
});
|
||||
it('should pass through when a char modifier is not down', function() {
|
||||
var times_called = 0;
|
||||
KeyboardUtil.EscapeModifiers(function(evt) {
|
||||
expect(times_called).to.be.equal(0);
|
||||
++times_called;
|
||||
expect(evt).to.be.deep.equal({type: 'keyup', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
})({type: 'keyup', keyId: 0x41, keysym: keysyms.lookup(0x42)});
|
||||
expect(times_called).to.be.equal(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,134 @@
|
||||
// requires local modules: util
|
||||
/* jshint expr: true */
|
||||
|
||||
var assert = chai.assert;
|
||||
var expect = chai.expect;
|
||||
|
||||
describe('Utils', function() {
|
||||
"use strict";
|
||||
|
||||
describe('logging functions', function () {
|
||||
beforeEach(function () {
|
||||
sinon.spy(console, 'log');
|
||||
sinon.spy(console, 'debug');
|
||||
sinon.spy(console, 'warn');
|
||||
sinon.spy(console, 'error');
|
||||
sinon.spy(console, 'info');
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
console.log.restore();
|
||||
console.debug.restore();
|
||||
console.warn.restore();
|
||||
console.error.restore();
|
||||
console.info.restore();
|
||||
});
|
||||
|
||||
it('should use noop for levels lower than the min level', function () {
|
||||
Util.init_logging('warn');
|
||||
Util.Debug('hi');
|
||||
Util.Info('hello');
|
||||
expect(console.log).to.not.have.been.called;
|
||||
});
|
||||
|
||||
it('should use console.debug for Debug', function () {
|
||||
Util.init_logging('debug');
|
||||
Util.Debug('dbg');
|
||||
expect(console.debug).to.have.been.calledWith('dbg');
|
||||
});
|
||||
|
||||
it('should use console.info for Info', function () {
|
||||
Util.init_logging('debug');
|
||||
Util.Info('inf');
|
||||
expect(console.info).to.have.been.calledWith('inf');
|
||||
});
|
||||
|
||||
it('should use console.warn for Warn', function () {
|
||||
Util.init_logging('warn');
|
||||
Util.Warn('wrn');
|
||||
expect(console.warn).to.have.been.called;
|
||||
expect(console.warn).to.have.been.calledWith('wrn');
|
||||
});
|
||||
|
||||
it('should use console.error for Error', function () {
|
||||
Util.init_logging('error');
|
||||
Util.Error('err');
|
||||
expect(console.error).to.have.been.called;
|
||||
expect(console.error).to.have.been.calledWith('err');
|
||||
});
|
||||
});
|
||||
|
||||
describe('language selection', function () {
|
||||
var origNavigator;
|
||||
beforeEach(function () {
|
||||
// window.navigator is a protected read-only property in many
|
||||
// environments, so we need to redefine it whilst running these
|
||||
// tests.
|
||||
origNavigator = Object.getOwnPropertyDescriptor(window, "navigator");
|
||||
if (origNavigator === undefined) {
|
||||
// Object.getOwnPropertyDescriptor() doesn't work
|
||||
// properly in any version of IE
|
||||
this.skip();
|
||||
}
|
||||
|
||||
Object.defineProperty(window, "navigator", {value: {}});
|
||||
if (window.navigator.languages !== undefined) {
|
||||
// Object.defineProperty() doesn't work properly in old
|
||||
// versions of Chrome
|
||||
this.skip();
|
||||
}
|
||||
|
||||
window.navigator.languages = [];
|
||||
});
|
||||
afterEach(function () {
|
||||
Object.defineProperty(window, "navigator", origNavigator);
|
||||
});
|
||||
|
||||
it('should use English by default', function() {
|
||||
expect(Util.Localisation.language).to.equal('en');
|
||||
});
|
||||
it('should use English if no user language matches', function() {
|
||||
window.navigator.languages = ["nl", "de"];
|
||||
Util.Localisation.setup(["es", "fr"]);
|
||||
expect(Util.Localisation.language).to.equal('en');
|
||||
});
|
||||
it('should use the most preferred user language', function() {
|
||||
window.navigator.languages = ["nl", "de", "fr"];
|
||||
Util.Localisation.setup(["es", "fr", "de"]);
|
||||
expect(Util.Localisation.language).to.equal('de');
|
||||
});
|
||||
it('should prefer sub-languages languages', function() {
|
||||
window.navigator.languages = ["pt-BR"];
|
||||
Util.Localisation.setup(["pt", "pt-BR"]);
|
||||
expect(Util.Localisation.language).to.equal('pt-BR');
|
||||
});
|
||||
it('should fall back to language "parents"', function() {
|
||||
window.navigator.languages = ["pt-BR"];
|
||||
Util.Localisation.setup(["fr", "pt", "de"]);
|
||||
expect(Util.Localisation.language).to.equal('pt');
|
||||
});
|
||||
it('should not use specific language when user asks for a generic language', function() {
|
||||
window.navigator.languages = ["pt", "de"];
|
||||
Util.Localisation.setup(["fr", "pt-BR", "de"]);
|
||||
expect(Util.Localisation.language).to.equal('de');
|
||||
});
|
||||
it('should handle underscore as a separator', function() {
|
||||
window.navigator.languages = ["pt-BR"];
|
||||
Util.Localisation.setup(["pt_BR"]);
|
||||
expect(Util.Localisation.language).to.equal('pt_BR');
|
||||
});
|
||||
it('should handle difference in case', function() {
|
||||
window.navigator.languages = ["pt-br"];
|
||||
Util.Localisation.setup(["pt-BR"]);
|
||||
expect(Util.Localisation.language).to.equal('pt-BR');
|
||||
});
|
||||
});
|
||||
|
||||
// TODO(directxman12): test the conf_default and conf_defaults methods
|
||||
// TODO(directxman12): test decodeUTF8
|
||||
// TODO(directxman12): test the event methods (addEvent, removeEvent, stopEvent)
|
||||
// TODO(directxman12): figure out a good way to test getPosition and getEventPosition
|
||||
// TODO(directxman12): figure out how to test the browser detection functions properly
|
||||
// (we can't really test them against the browsers, except for Gecko
|
||||
// via PhantomJS, the default test driver)
|
||||
});
|
||||
@@ -0,0 +1,425 @@
|
||||
// requires local modules: websock, util
|
||||
// requires test modules: fake.websocket, assertions
|
||||
/* jshint expr: true */
|
||||
var assert = chai.assert;
|
||||
var expect = chai.expect;
|
||||
|
||||
describe('Websock', function() {
|
||||
"use strict";
|
||||
|
||||
describe('Queue methods', function () {
|
||||
var sock;
|
||||
var RQ_TEMPLATE = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]);
|
||||
|
||||
beforeEach(function () {
|
||||
sock = new Websock();
|
||||
// skip init
|
||||
sock._allocate_buffers();
|
||||
sock._rQ.set(RQ_TEMPLATE);
|
||||
sock._rQlen = RQ_TEMPLATE.length;
|
||||
});
|
||||
describe('rQlen', function () {
|
||||
it('should return the length of the receive queue', function () {
|
||||
sock.set_rQi(0);
|
||||
|
||||
expect(sock.rQlen()).to.equal(RQ_TEMPLATE.length);
|
||||
});
|
||||
|
||||
it("should return the proper length if we read some from the receive queue", function () {
|
||||
sock.set_rQi(1);
|
||||
|
||||
expect(sock.rQlen()).to.equal(RQ_TEMPLATE.length - 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rQpeek8', function () {
|
||||
it('should peek at the next byte without poping it off the queue', function () {
|
||||
var bef_len = sock.rQlen();
|
||||
var peek = sock.rQpeek8();
|
||||
expect(sock.rQpeek8()).to.equal(peek);
|
||||
expect(sock.rQlen()).to.equal(bef_len);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rQshift8', function () {
|
||||
it('should pop a single byte from the receive queue', function () {
|
||||
var peek = sock.rQpeek8();
|
||||
var bef_len = sock.rQlen();
|
||||
expect(sock.rQshift8()).to.equal(peek);
|
||||
expect(sock.rQlen()).to.equal(bef_len - 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rQshift16', function () {
|
||||
it('should pop two bytes from the receive queue and return a single number', function () {
|
||||
var bef_len = sock.rQlen();
|
||||
var expected = (RQ_TEMPLATE[0] << 8) + RQ_TEMPLATE[1];
|
||||
expect(sock.rQshift16()).to.equal(expected);
|
||||
expect(sock.rQlen()).to.equal(bef_len - 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rQshift32', function () {
|
||||
it('should pop four bytes from the receive queue and return a single number', function () {
|
||||
var bef_len = sock.rQlen();
|
||||
var expected = (RQ_TEMPLATE[0] << 24) +
|
||||
(RQ_TEMPLATE[1] << 16) +
|
||||
(RQ_TEMPLATE[2] << 8) +
|
||||
RQ_TEMPLATE[3];
|
||||
expect(sock.rQshift32()).to.equal(expected);
|
||||
expect(sock.rQlen()).to.equal(bef_len - 4);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rQshiftStr', function () {
|
||||
it('should shift the given number of bytes off of the receive queue and return a string', function () {
|
||||
var bef_len = sock.rQlen();
|
||||
var bef_rQi = sock.get_rQi();
|
||||
var shifted = sock.rQshiftStr(3);
|
||||
expect(shifted).to.be.a('string');
|
||||
expect(shifted).to.equal(String.fromCharCode.apply(null, Array.prototype.slice.call(new Uint8Array(RQ_TEMPLATE.buffer, bef_rQi, 3))));
|
||||
expect(sock.rQlen()).to.equal(bef_len - 3);
|
||||
});
|
||||
|
||||
it('should shift the entire rest of the queue off if no length is given', function () {
|
||||
sock.rQshiftStr();
|
||||
expect(sock.rQlen()).to.equal(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rQshiftBytes', function () {
|
||||
it('should shift the given number of bytes of the receive queue and return an array', function () {
|
||||
var bef_len = sock.rQlen();
|
||||
var bef_rQi = sock.get_rQi();
|
||||
var shifted = sock.rQshiftBytes(3);
|
||||
expect(shifted).to.be.an.instanceof(Uint8Array);
|
||||
expect(shifted).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, bef_rQi, 3));
|
||||
expect(sock.rQlen()).to.equal(bef_len - 3);
|
||||
});
|
||||
|
||||
it('should shift the entire rest of the queue off if no length is given', function () {
|
||||
sock.rQshiftBytes();
|
||||
expect(sock.rQlen()).to.equal(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('rQslice', function () {
|
||||
beforeEach(function () {
|
||||
sock.set_rQi(0);
|
||||
});
|
||||
|
||||
it('should not modify the receive queue', function () {
|
||||
var bef_len = sock.rQlen();
|
||||
sock.rQslice(0, 2);
|
||||
expect(sock.rQlen()).to.equal(bef_len);
|
||||
});
|
||||
|
||||
it('should return an array containing the given slice of the receive queue', function () {
|
||||
var sl = sock.rQslice(0, 2);
|
||||
expect(sl).to.be.an.instanceof(Uint8Array);
|
||||
expect(sl).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, 0, 2));
|
||||
});
|
||||
|
||||
it('should use the rest of the receive queue if no end is given', function () {
|
||||
var sl = sock.rQslice(1);
|
||||
expect(sl).to.have.length(RQ_TEMPLATE.length - 1);
|
||||
expect(sl).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, 1));
|
||||
});
|
||||
|
||||
it('should take the current rQi in to account', function () {
|
||||
sock.set_rQi(1);
|
||||
expect(sock.rQslice(0, 2)).to.array.equal(new Uint8Array(RQ_TEMPLATE.buffer, 1, 2));
|
||||
});
|
||||
});
|
||||
|
||||
describe('rQwait', function () {
|
||||
beforeEach(function () {
|
||||
sock.set_rQi(0);
|
||||
});
|
||||
|
||||
it('should return true if there are not enough bytes in the receive queue', function () {
|
||||
expect(sock.rQwait('hi', RQ_TEMPLATE.length + 1)).to.be.true;
|
||||
});
|
||||
|
||||
it('should return false if there are enough bytes in the receive queue', function () {
|
||||
expect(sock.rQwait('hi', RQ_TEMPLATE.length)).to.be.false;
|
||||
});
|
||||
|
||||
it('should return true and reduce rQi by "goback" if there are not enough bytes', function () {
|
||||
sock.set_rQi(5);
|
||||
expect(sock.rQwait('hi', RQ_TEMPLATE.length, 4)).to.be.true;
|
||||
expect(sock.get_rQi()).to.equal(1);
|
||||
});
|
||||
|
||||
it('should raise an error if we try to go back more than possible', function () {
|
||||
sock.set_rQi(5);
|
||||
expect(function () { sock.rQwait('hi', RQ_TEMPLATE.length, 6); }).to.throw(Error);
|
||||
});
|
||||
|
||||
it('should not reduce rQi if there are enough bytes', function () {
|
||||
sock.set_rQi(5);
|
||||
sock.rQwait('hi', 1, 6);
|
||||
expect(sock.get_rQi()).to.equal(5);
|
||||
});
|
||||
});
|
||||
|
||||
describe('flush', function () {
|
||||
beforeEach(function () {
|
||||
sock._websocket = {
|
||||
send: sinon.spy()
|
||||
};
|
||||
});
|
||||
|
||||
it('should actually send on the websocket', function () {
|
||||
sock._websocket.bufferedAmount = 8;
|
||||
sock._websocket.readyState = WebSocket.OPEN
|
||||
sock._sQ = new Uint8Array([1, 2, 3]);
|
||||
sock._sQlen = 3;
|
||||
var encoded = sock._encode_message();
|
||||
|
||||
sock.flush();
|
||||
expect(sock._websocket.send).to.have.been.calledOnce;
|
||||
expect(sock._websocket.send).to.have.been.calledWith(encoded);
|
||||
});
|
||||
|
||||
it('should not call send if we do not have anything queued up', function () {
|
||||
sock._sQlen = 0;
|
||||
sock._websocket.bufferedAmount = 8;
|
||||
|
||||
sock.flush();
|
||||
|
||||
expect(sock._websocket.send).not.to.have.been.called;
|
||||
});
|
||||
});
|
||||
|
||||
describe('send', function () {
|
||||
beforeEach(function () {
|
||||
sock.flush = sinon.spy();
|
||||
});
|
||||
|
||||
it('should add to the send queue', function () {
|
||||
sock.send([1, 2, 3]);
|
||||
var sq = sock.get_sQ();
|
||||
expect(new Uint8Array(sq.buffer, sock._sQlen - 3, 3)).to.array.equal(new Uint8Array([1, 2, 3]));
|
||||
});
|
||||
|
||||
it('should call flush', function () {
|
||||
sock.send([1, 2, 3]);
|
||||
expect(sock.flush).to.have.been.calledOnce;
|
||||
});
|
||||
});
|
||||
|
||||
describe('send_string', function () {
|
||||
beforeEach(function () {
|
||||
sock.send = sinon.spy();
|
||||
});
|
||||
|
||||
it('should call send after converting the string to an array', function () {
|
||||
sock.send_string("\x01\x02\x03");
|
||||
expect(sock.send).to.have.been.calledWith([1, 2, 3]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('lifecycle methods', function () {
|
||||
var old_WS;
|
||||
before(function () {
|
||||
old_WS = WebSocket;
|
||||
});
|
||||
|
||||
var sock;
|
||||
beforeEach(function () {
|
||||
sock = new Websock();
|
||||
WebSocket = sinon.spy();
|
||||
WebSocket.OPEN = old_WS.OPEN;
|
||||
WebSocket.CONNECTING = old_WS.CONNECTING;
|
||||
WebSocket.CLOSING = old_WS.CLOSING;
|
||||
WebSocket.CLOSED = old_WS.CLOSED;
|
||||
|
||||
WebSocket.prototype.binaryType = 'arraybuffer';
|
||||
});
|
||||
|
||||
describe('opening', function () {
|
||||
it('should pick the correct protocols if none are given' , function () {
|
||||
|
||||
});
|
||||
|
||||
it('should open the actual websocket', function () {
|
||||
sock.open('ws://localhost:8675', 'binary');
|
||||
expect(WebSocket).to.have.been.calledWith('ws://localhost:8675', 'binary');
|
||||
});
|
||||
|
||||
// it('should initialize the event handlers')?
|
||||
});
|
||||
|
||||
describe('closing', function () {
|
||||
beforeEach(function () {
|
||||
sock.open('ws://');
|
||||
sock._websocket.close = sinon.spy();
|
||||
});
|
||||
|
||||
it('should close the actual websocket if it is open', function () {
|
||||
sock._websocket.readyState = WebSocket.OPEN;
|
||||
sock.close();
|
||||
expect(sock._websocket.close).to.have.been.calledOnce;
|
||||
});
|
||||
|
||||
it('should close the actual websocket if it is connecting', function () {
|
||||
sock._websocket.readyState = WebSocket.CONNECTING;
|
||||
sock.close();
|
||||
expect(sock._websocket.close).to.have.been.calledOnce;
|
||||
});
|
||||
|
||||
it('should not try to close the actual websocket if closing', function () {
|
||||
sock._websocket.readyState = WebSocket.CLOSING;
|
||||
sock.close();
|
||||
expect(sock._websocket.close).not.to.have.been.called;
|
||||
});
|
||||
|
||||
it('should not try to close the actual websocket if closed', function () {
|
||||
sock._websocket.readyState = WebSocket.CLOSED;
|
||||
sock.close();
|
||||
expect(sock._websocket.close).not.to.have.been.called;
|
||||
});
|
||||
|
||||
it('should reset onmessage to not call _recv_message', function () {
|
||||
sinon.spy(sock, '_recv_message');
|
||||
sock.close();
|
||||
sock._websocket.onmessage(null);
|
||||
try {
|
||||
expect(sock._recv_message).not.to.have.been.called;
|
||||
} finally {
|
||||
sock._recv_message.restore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('event handlers', function () {
|
||||
beforeEach(function () {
|
||||
sock._recv_message = sinon.spy();
|
||||
sock.on('open', sinon.spy());
|
||||
sock.on('close', sinon.spy());
|
||||
sock.on('error', sinon.spy());
|
||||
sock.open('ws://');
|
||||
});
|
||||
|
||||
it('should call _recv_message on a message', function () {
|
||||
sock._websocket.onmessage(null);
|
||||
expect(sock._recv_message).to.have.been.calledOnce;
|
||||
});
|
||||
|
||||
it('should call the open event handler on opening', function () {
|
||||
sock._websocket.onopen();
|
||||
expect(sock._eventHandlers.open).to.have.been.calledOnce;
|
||||
});
|
||||
|
||||
it('should call the close event handler on closing', function () {
|
||||
sock._websocket.onclose();
|
||||
expect(sock._eventHandlers.close).to.have.been.calledOnce;
|
||||
});
|
||||
|
||||
it('should call the error event handler on error', function () {
|
||||
sock._websocket.onerror();
|
||||
expect(sock._eventHandlers.error).to.have.been.calledOnce;
|
||||
});
|
||||
});
|
||||
|
||||
after(function () {
|
||||
WebSocket = old_WS;
|
||||
});
|
||||
});
|
||||
|
||||
describe('WebSocket Receiving', function () {
|
||||
var sock;
|
||||
beforeEach(function () {
|
||||
sock = new Websock();
|
||||
sock._allocate_buffers();
|
||||
});
|
||||
|
||||
it('should support adding binary Uint8Array data to the receive queue', function () {
|
||||
var msg = { data: new Uint8Array([1, 2, 3]) };
|
||||
sock._mode = 'binary';
|
||||
sock._recv_message(msg);
|
||||
expect(sock.rQshiftStr(3)).to.equal('\x01\x02\x03');
|
||||
});
|
||||
|
||||
it('should call the message event handler if present', function () {
|
||||
sock._eventHandlers.message = sinon.spy();
|
||||
var msg = { data: new Uint8Array([1, 2, 3]).buffer };
|
||||
sock._mode = 'binary';
|
||||
sock._recv_message(msg);
|
||||
expect(sock._eventHandlers.message).to.have.been.calledOnce;
|
||||
});
|
||||
|
||||
it('should not call the message event handler if there is nothing in the receive queue', function () {
|
||||
sock._eventHandlers.message = sinon.spy();
|
||||
var msg = { data: new Uint8Array([]).buffer };
|
||||
sock._mode = 'binary';
|
||||
sock._recv_message(msg);
|
||||
expect(sock._eventHandlers.message).not.to.have.been.called;
|
||||
});
|
||||
|
||||
it('should compact the receive queue', function () {
|
||||
// NB(sross): while this is an internal implementation detail, it's important to
|
||||
// test, otherwise the receive queue could become very large very quickly
|
||||
sock._rQ = new Uint8Array([0, 1, 2, 3, 4, 5, 0, 0, 0, 0]);
|
||||
sock._rQlen = 6;
|
||||
sock.set_rQi(6);
|
||||
sock._rQmax = 3;
|
||||
var msg = { data: new Uint8Array([1, 2, 3]).buffer };
|
||||
sock._mode = 'binary';
|
||||
sock._recv_message(msg);
|
||||
expect(sock._rQlen).to.equal(3);
|
||||
expect(sock.get_rQi()).to.equal(0);
|
||||
});
|
||||
|
||||
it('should automatically resize the receive queue if the incoming message is too large', function () {
|
||||
sock._rQ = new Uint8Array(20);
|
||||
sock._rQlen = 0;
|
||||
sock.set_rQi(0);
|
||||
sock._rQbufferSize = 20;
|
||||
sock._rQmax = 2;
|
||||
var msg = { data: new Uint8Array(30).buffer };
|
||||
sock._mode = 'binary';
|
||||
sock._recv_message(msg);
|
||||
expect(sock._rQlen).to.equal(30);
|
||||
expect(sock.get_rQi()).to.equal(0);
|
||||
expect(sock._rQ.length).to.equal(240); // keep the invariant that rQbufferSize / 8 >= rQlen
|
||||
});
|
||||
|
||||
it('should call the error event handler on an exception', function () {
|
||||
sock._eventHandlers.error = sinon.spy();
|
||||
sock._eventHandlers.message = sinon.stub().throws();
|
||||
var msg = { data: new Uint8Array([1, 2, 3]).buffer };
|
||||
sock._mode = 'binary';
|
||||
sock._recv_message(msg);
|
||||
expect(sock._eventHandlers.error).to.have.been.calledOnce;
|
||||
});
|
||||
});
|
||||
|
||||
describe('Data encoding', function () {
|
||||
before(function () { FakeWebSocket.replace(); });
|
||||
after(function () { FakeWebSocket.restore(); });
|
||||
|
||||
describe('as binary data', function () {
|
||||
var sock;
|
||||
beforeEach(function () {
|
||||
sock = new Websock();
|
||||
sock.open('ws://', 'binary');
|
||||
sock._websocket._open();
|
||||
});
|
||||
|
||||
it('should only send the send queue up to the send queue length', function () {
|
||||
sock._sQ = new Uint8Array([1, 2, 3, 4, 5]);
|
||||
sock._sQlen = 3;
|
||||
var res = sock._encode_message();
|
||||
expect(res).to.array.equal(new Uint8Array([1, 2, 3]));
|
||||
});
|
||||
|
||||
it('should properly pass the encoded data off to the actual WebSocket', function () {
|
||||
sock.send([1, 2, 3]);
|
||||
expect(sock._websocket._get_sent_data()).to.array.equal(new Uint8Array([1, 2, 3]));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>VNC Performance Benchmark</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Passes: <input id='passes' style='width:50' value=3>
|
||||
|
||||
<input id='startButton' type='button' value='Start' style='width:100px'
|
||||
onclick="do_test();" disabled>
|
||||
|
||||
<br><br>
|
||||
|
||||
Results:<br>
|
||||
<textarea id="messages" style="font-size: 9;" cols=80 rows=15></textarea>
|
||||
|
||||
<br><br>
|
||||
|
||||
<div id="VNC_screen">
|
||||
<div id="VNC_status_bar" class="VNC_status_bar" style="margin-top: 0px;">
|
||||
<table border=0 width=100%><tr>
|
||||
<td><div id="VNC_status">Loading</div></td>
|
||||
</tr></table>
|
||||
</div>
|
||||
<canvas id="VNC_canvas" width="640px" height="20px">
|
||||
Canvas not supported.
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
|
||||
<!--
|
||||
<script type='text/javascript'
|
||||
src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
|
||||
-->
|
||||
|
||||
<script type="text/javascript">
|
||||
var INCLUDE_URI= "../";
|
||||
</script>
|
||||
<script src="../core/util.js"></script>
|
||||
<script src="../app/webutil.js"></script>
|
||||
|
||||
<script>
|
||||
var fname = WebUtil.getQueryVar('data', null);
|
||||
if (fname) {
|
||||
msg("Loading " + fname);
|
||||
|
||||
// Load supporting scripts
|
||||
WebUtil.load_scripts({
|
||||
'core': ["base64.js", "websock.js", "des.js", "input/keysym.js",
|
||||
"input/keysymdef.js", "input/xtscancodes.js", "input/util.js",
|
||||
"input/devices.js", "display.js", "rfb.js", "inflator.js"],
|
||||
'tests': ["playback.js"],
|
||||
'recordings': [fname]});
|
||||
} else {
|
||||
msg("Must specifiy data=FOO.js in query string.");
|
||||
}
|
||||
|
||||
var start_time, VNC_frame_data, pass, passes, encIdx,
|
||||
encOrder = ['raw', 'rre', 'hextile', 'tightpng', 'copyrect'],
|
||||
encTot = {}, encMin = {}, encMax = {},
|
||||
passCur, passTot, passMin, passMax;
|
||||
|
||||
function msg(str) {
|
||||
console.log(str);
|
||||
var cell = document.getElementById('messages');
|
||||
cell.textContent += str + "\n";
|
||||
cell.scrollTop = cell.scrollHeight;
|
||||
}
|
||||
function dbgmsg(str) {
|
||||
if (Util.get_logging() === 'debug') {
|
||||
msg(str);
|
||||
}
|
||||
}
|
||||
|
||||
disconnected = function (rfb, reason) {
|
||||
if (reason) {
|
||||
msg("noVNC sent '" + state +
|
||||
"' state during pass " + pass +
|
||||
", iteration " + iteration +
|
||||
" frame " + frame_idx);
|
||||
test_state = 'failed';
|
||||
}
|
||||
}
|
||||
|
||||
notification = function (rfb, mesg, level, options) {
|
||||
document.getElementById('VNC_status').textContent = mesg;
|
||||
}
|
||||
|
||||
function do_test() {
|
||||
document.getElementById('startButton').value = "Running";
|
||||
document.getElementById('startButton').disabled = true;
|
||||
|
||||
mode = 'perftest'; // full-speed
|
||||
passes = document.getElementById('passes').value;
|
||||
pass = 1;
|
||||
encIdx = 0;
|
||||
|
||||
// Render each encoding once for each pass
|
||||
iterations = 1;
|
||||
|
||||
// Initialize stats counters
|
||||
for (i = 0; i < encOrder.length; i++) {
|
||||
enc = encOrder[i];
|
||||
encTot[i] = 0;
|
||||
encMin[i] = 2<<23; // Something sufficiently large
|
||||
encMax[i] = 0;
|
||||
}
|
||||
passCur = 0;
|
||||
passTot = 0;
|
||||
passMin = 2<<23;
|
||||
passMax = 0;
|
||||
|
||||
// Fire away
|
||||
next_encoding();
|
||||
}
|
||||
|
||||
function next_encoding() {
|
||||
var encName;
|
||||
|
||||
if (encIdx >= encOrder.length) {
|
||||
// Accumulate pass stats
|
||||
if (passCur < passMin) {
|
||||
passMin = passCur;
|
||||
}
|
||||
if (passCur > passMax) {
|
||||
passMax = passCur;
|
||||
}
|
||||
msg("Pass " + pass + " took " + passCur + " ms");
|
||||
|
||||
passCur = 0;
|
||||
encIdx = 0;
|
||||
pass += 1;
|
||||
if (pass > passes) {
|
||||
// We are finished
|
||||
// Shut-off event interception
|
||||
rfb.get_mouse().ungrab();
|
||||
rfb.get_keyboard().ungrab();
|
||||
document.getElementById('startButton').disabled = false;
|
||||
document.getElementById('startButton').value = "Start";
|
||||
finish_passes();
|
||||
return; // We are finished, terminate
|
||||
}
|
||||
}
|
||||
|
||||
encName = encOrder[encIdx];
|
||||
dbgmsg("Rendering pass " + pass + " encoding '" + encName + "'");
|
||||
|
||||
VNC_frame_data = VNC_frame_data_multi[encName];
|
||||
iteration = 0;
|
||||
start_time = (new Date()).getTime();
|
||||
|
||||
next_iteration();
|
||||
}
|
||||
|
||||
// Finished rendering current encoding
|
||||
function finish() {
|
||||
var total_time, end_time = (new Date()).getTime();
|
||||
total_time = end_time - start_time;
|
||||
|
||||
dbgmsg("Encoding " + encOrder[encIdx] + " took " + total_time + "ms");
|
||||
|
||||
passCur += total_time;
|
||||
passTot += total_time;
|
||||
|
||||
// Accumulate stats
|
||||
encTot[encIdx] += total_time;
|
||||
if (total_time < encMin[encIdx]) {
|
||||
encMin[encIdx] = total_time;
|
||||
}
|
||||
if (total_time > encMax[encIdx]) {
|
||||
encMax[encIdx] = total_time;
|
||||
}
|
||||
|
||||
encIdx += 1;
|
||||
next_encoding();
|
||||
}
|
||||
|
||||
function finish_passes() {
|
||||
var i, enc, avg, passAvg;
|
||||
msg("STATS (for " + passes + " passes)");
|
||||
// Encoding stats
|
||||
for (i = 0; i < encOrder.length; i++) {
|
||||
enc = encOrder[i];
|
||||
avg = (encTot[i] / passes).toFixed(1);
|
||||
msg(" " + enc + ": " + encTot[i] + " ms, " +
|
||||
encMin[i] + "/" + avg + "/" + encMax[i] +
|
||||
" (min/avg/max)");
|
||||
|
||||
}
|
||||
// Print pass stats
|
||||
passAvg = (passTot / passes).toFixed(1);
|
||||
msg("\n All passes: " + passTot + " ms, " +
|
||||
passMin + "/" + passAvg + "/" + passMax +
|
||||
" (min/avg/max)");
|
||||
}
|
||||
|
||||
window.onscriptsload = function() {
|
||||
var i, enc;
|
||||
dbgmsg("Frame lengths:");
|
||||
for (i = 0; i < encOrder.length; i++) {
|
||||
enc = encOrder[i];
|
||||
dbgmsg(" " + enc + ": " + VNC_frame_data_multi[enc].length);
|
||||
}
|
||||
document.getElementById('startButton').disabled = false;
|
||||
}
|
||||
</script>
|
||||
</html>
|
||||
@@ -0,0 +1,134 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>VNC Playback</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
Iterations: <input id='iterations' style='width:50'>
|
||||
Perftest:<input type='radio' id='mode1' name='mode' checked>
|
||||
Realtime:<input type='radio' id='mode2' name='mode'>
|
||||
|
||||
<input id='startButton' type='button' value='Start' style='width:100px'
|
||||
onclick="start();" disabled>
|
||||
|
||||
<br><br>
|
||||
|
||||
Results:<br>
|
||||
<textarea id="messages" style="font-size: 9;" cols=80 rows=25></textarea>
|
||||
|
||||
<br><br>
|
||||
|
||||
<div id="VNC_screen">
|
||||
<div id="VNC_status_bar" class="VNC_status_bar" style="margin-top: 0px;">
|
||||
<table border=0 width=100%><tr>
|
||||
<td><div id="VNC_status">Loading</div></td>
|
||||
</tr></table>
|
||||
</div>
|
||||
<canvas id="VNC_canvas" width="640px" height="20px">
|
||||
Canvas not supported.
|
||||
</canvas>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
|
||||
<!--
|
||||
<script type='text/javascript'
|
||||
src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
|
||||
-->
|
||||
|
||||
<script type="text/javascript">
|
||||
var INCLUDE_URI= "../";
|
||||
</script>
|
||||
<script src="../core/util.js"></script>
|
||||
<script src="../app/webutil.js"></script>
|
||||
|
||||
<script>
|
||||
var fname, start_time;
|
||||
|
||||
function message(str) {
|
||||
console.log(str);
|
||||
var cell = document.getElementById('messages');
|
||||
cell.textContent += str + "\n";
|
||||
cell.scrollTop = cell.scrollHeight;
|
||||
}
|
||||
|
||||
fname = WebUtil.getQueryVar('data', null);
|
||||
if (fname) {
|
||||
message("Loading " + fname);
|
||||
// Load supporting scripts
|
||||
WebUtil.load_scripts({
|
||||
'core': ["base64.js", "websock.js", "des.js", "input/keysym.js",
|
||||
"input/keysymdef.js", "input/xtscancodes.js", "input/util.js",
|
||||
"input/devices.js", "display.js", "rfb.js", "inflator.js"],
|
||||
'tests': ["playback.js"],
|
||||
'recordings': [fname]});
|
||||
|
||||
} else {
|
||||
message("Must specify data=FOO in query string.");
|
||||
}
|
||||
|
||||
disconnected = function (rfb, reason) {
|
||||
if (reason) {
|
||||
message("noVNC sent '" + state + "' state during iteration " + iteration + " frame " + frame_idx);
|
||||
test_state = 'failed';
|
||||
}
|
||||
}
|
||||
|
||||
notification = function (rfb, mesg, level, options) {
|
||||
document.getElementById('VNC_status').textContent = mesg;
|
||||
}
|
||||
|
||||
function start() {
|
||||
document.getElementById('startButton').value = "Running";
|
||||
document.getElementById('startButton').disabled = true;
|
||||
|
||||
iterations = document.getElementById('iterations').value;
|
||||
iteration = 0;
|
||||
start_time = (new Date()).getTime();
|
||||
|
||||
if (document.getElementById('mode1').checked) {
|
||||
message("Starting performance playback (fullspeed) [" + iterations + " iteration(s)]");
|
||||
mode = 'perftest';
|
||||
} else {
|
||||
message("Starting realtime playback [" + iterations + " iteration(s)]");
|
||||
mode = 'realtime';
|
||||
}
|
||||
|
||||
//recv_message = rfb.testMode(send_array, VNC_frame_encoding);
|
||||
|
||||
next_iteration();
|
||||
}
|
||||
|
||||
function finish() {
|
||||
// Finished with all iterations
|
||||
var total_time, end_time = (new Date()).getTime();
|
||||
total_time = end_time - start_time;
|
||||
|
||||
iter_time = parseInt(total_time / iterations, 10);
|
||||
message(iterations + " iterations took " + total_time + "ms, " +
|
||||
iter_time + "ms per iteration");
|
||||
// Shut-off event interception
|
||||
rfb.get_mouse().ungrab();
|
||||
rfb.get_keyboard().ungrab();
|
||||
document.getElementById('startButton').disabled = false;
|
||||
document.getElementById('startButton').value = "Start";
|
||||
|
||||
}
|
||||
|
||||
window.onscriptsload = function () {
|
||||
iterations = WebUtil.getQueryVar('iterations', 3);
|
||||
document.getElementById('iterations').value = iterations;
|
||||
mode = WebUtil.getQueryVar('mode', 3);
|
||||
if (mode === 'realtime') {
|
||||
document.getElementById('mode2').checked = true;
|
||||
} else {
|
||||
document.getElementById('mode1').checked = true;
|
||||
}
|
||||
if (fname) {
|
||||
message("VNC_frame_data.length: " + VNC_frame_data.length);
|
||||
}
|
||||
document.getElementById('startButton').disabled = false;
|
||||
}
|
||||
</script>
|
||||
</html>
|
||||
Reference in New Issue
Block a user