This repository was archived by the owner on Sep 21, 2022. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathcalibrator.js
More file actions
97 lines (83 loc) · 2.95 KB
/
Copy pathcalibrator.js
File metadata and controls
97 lines (83 loc) · 2.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
'use strict';
var q = require('q'),
fs = require('fs'),
path = require('path'),
Image = require('./image'),
GeminiError = require('./errors/gemini-error'),
clientScriptCalibrate = fs.readFileSync(path.join(__dirname, 'browser', 'client-scripts', 'gemini.calibrate.js'), 'utf8');
/**
* @constructor
*/
function Calibrator() {
this._cache = {};
}
/**
* @param {Browser} browser
* @returns {Promise.<CalibrationResult>}
*/
Calibrator.prototype.calibrate = function(browser) {
var _this = this;
if (this._cache[browser.id]) {
return q(this._cache[browser.id]);
}
return browser.open('about:blank')
.then(function() {
return browser.inject(clientScriptCalibrate);
})
.then(function() {
return browser.captureFullscreenImage();
})
.then(function(image) {
var find = ['#00ff00', '#00ff00', '#00ff00', '#ff0000'];
/**
* Compare pixel with given x,y to given pixel in the pattern
* @param {Object} coords
* @param {Object} positionData position data
* @param [Boolean] reverse should be true when traversing x from right to left
*/
function checkPattern(coords, positionData, reverse) {
if (Image.RGBToString(image.getRGBA(coords.x, coords.y)) === find[positionData.u]) {
if (++positionData.u === find.length) {
positionData.pos = {x: coords.x - (reverse? -1 : 1) * (find.length - 1), y: coords.y};
}
return;
}
positionData.u = 0;
}
var width = image.getSize().width,
height = image.getSize().height,
start = {u: 0},
end = {u: 0};
for (var y = 0; y < height && (!start.pos || !end.pos); y++) {
for (var x = 0; x < width; x++) {
if (!start.pos) {
checkPattern({x: x, y: y}, start);
}
if (!end.pos) {
checkPattern({x: width - x - 1, y: height - y - 1}, end, true);
}
}
}
if (!start.pos || !end.pos) {
return q.reject(new GeminiError(
'Could not calibrate. This could be due to calibration page has failed to open properly'
));
}
var calibration = {
top: start.pos.y,
left: start.pos.x,
right: width - 1 - end.pos.x,
bottom: height - 1 - end.pos.y
};
_this._cache[browser.id] = calibration;
return calibration;
});
};
/**
* @typedef {Object} CalibrationResult
* @property {Number} top
* @property {Number} left
* @property {Number} right
* @property {Number} bottom
*/
module.exports = Calibrator;