Repository navigation
Expand file tree
/
Copy pathcalibrator.js
More file actions
104 lines (91 loc) · 2.84 KB
/
Copy pathcalibrator.js
File metadata and controls
104 lines (91 loc) · 2.84 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
98
99
100
101
102
103
104
'use strict';
var q = require('q'),
fs = require('fs'),
path = require('path'),
_ = require('lodash'),
GeminiError = require('./errors/gemini-error'),
looksSame = require('looks-same'),
clientScriptCalibrate = fs.readFileSync(path.join(__dirname, 'browser', 'client-scripts', 'gemini.calibrate.min.js'), 'utf8'),
MIN_COLOR_LENGTH = 6;
/**
* @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', {resetZoom: false})
.then(function() {
return browser.evalScript(clientScriptCalibrate);
})
.then(function(features) {
return [features, browser.captureFullscreenImage()];
})
.spread(function(features, image) {
var imageFeatures = _this._detectImageFeatures(image);
if (!imageFeatures) {
return q.reject(new GeminiError(
'Could not calibrate. This could be due to calibration page has failed to open properly'
));
}
_.extend(features, {
top: imageFeatures.viewportStart.y,
left: imageFeatures.viewportStart.x,
usePixelRatio: (features.pixelRatio &&
features.pixelRatio > 1.0 &&
imageFeatures.colorLength > MIN_COLOR_LENGTH
)
});
_this._cache[browser.id] = features;
return features;
});
};
Calibrator.prototype._detectImageFeatures = function(image) {
var searchColor = {R: 148, G: 250, B: 0},
imageSize = image.getSize(),
start = null,
currentLength = 0;
for (var y = 0; y < imageSize.height; y++) {
for (var x = 0; x < imageSize.width; x++) {
var color = pickRGB(image.getRGBA(x, y));
if (looksSame.colors(color, searchColor)) {
currentLength++;
if (!start) {
start = {x: x, y: y};
}
} else if (currentLength >= MIN_COLOR_LENGTH) {
return {viewportStart: start, colorLength: currentLength};
} else {
currentLength = 0;
start = null;
}
}
}
if (!start) {
return null;
}
return {viewportStart: start, colorLength: currentLength};
};
function pickRGB(rgba) {
return {
R: rgba.r,
G: rgba.g,
B: rgba.b
};
}
/**
* @typedef {Object} CalibrationResult
* @property {Number} top
* @property {Number} left
* @property {Number} right
* @property {Number} bottom
*/
module.exports = Calibrator;