/
LogoManager.js
290 lines (275 loc) · 9.46 KB
/
LogoManager.js
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import { gui_log } from "./gui_log";
import { i18n } from "./localization";
/**
* Takes an ImageData object and returns an MCM symbol as an array of strings.
*
* @param {ImageData} data
*/
function imageToCharacter(data) {
const char = [];
let line = "";
for (let i = 0, I = data.length; i < I; i += 4) {
const rgbPixel = data.slice(i, i + 3),
colorKey = rgbPixel.join("-");
line += this.constants.MCM_COLORMAP[colorKey]
|| this.constants.MCM_COLORMAP['default'];
if (line.length === 8) {
char.push(line);
line = "";
}
}
const fieldSize = this.font.constants.SIZES.MAX_NVM_FONT_CHAR_FIELD_SIZE;
if (char.length < fieldSize) {
const pad = this.constants.MCM_COLORMAP['default'].repeat(4);
for (let i = 0, I = fieldSize - char.length; i < I; i++) {
char.push(pad);
}
}
return char;
}
/**
* Takes an OSD symbol as an array of strings and replaces the in-memory character at charAddress with it.
*
* @param {Array<String>} lines
* @param {Number} charAddress
*/
function replaceChar(lines, charAddress) {
const characterBits = [],
characterBytes = [];
for (let n = 0, N = lines.length; n < N; n++) {
const line = lines[n];
for (let y = 0; y < 8; y = y + 2) {
characterBits.push(parseInt(line.slice(y, y + 2), 2));
}
characterBytes.push(parseInt(line, 2));
}
this.font.data.characters[charAddress] = characterBits;
this.font.data.characters_bytes[charAddress] = characterBytes;
this.font.data.character_image_urls[charAddress] = null;
this.font.draw(charAddress);
}
/**
* Validate image using defined constraints and display results on the UI.
*
* @param {HTMLImageElement} img
*/
function validateImage(img) {
return new Promise((resolveValidateImage, rejectValidateImage) => {
this.resetImageInfo();
for (const key in this.constraints) {
if (!this.constraints.hasOwnProperty(key)) {
continue;
}
const constraint = this.constraints[key],
satisfied = constraint.test(img);
if (satisfied) {
this.showConstraintSatisfied(constraint);
} else {
this.showConstraintNotSatisfied(constraint);
rejectValidateImage("Boot logo image constraint violation");
return;
}
}
resolveValidateImage();
});
}
const LogoManager = {
// dependencies set by init()
font: null,
logoStartIndex: null,
// DOM elements to cache
elements: {
preview: "#font-logo-preview",
uploadHint: "#font-logo-info-upload-hint",
},
// predefined values for handling the logo image
constants: {
TILES_NUM_HORIZ: 24,
TILES_NUM_VERT: 4,
MCM_COLORMAP: {
// background
'0-255-0': '01',
// black
'0-0-0': '00',
// white
'255-255-255': '10',
// fallback
'default': '01',
},
},
// config for logo image selection dialog
acceptFileTypes: [
{ description: 'images', extensions: ['png', 'bmp'] },
],
};
/**
* Initialize Logo Manager UI with dependencies.
*
* @param {FONT} font
* @param {number} logoStartIndex
*/
LogoManager.init = function (font, logoStartIndex) {
// custom logo image constraints
this.constraints = {
// test for image size
imageSize: {
el: "#font-logo-info-size",
// calculate logo image size at runtime as it may change conditionally in the future
expectedWidth: font.constants.SIZES.CHAR_WIDTH
* this.constants.TILES_NUM_HORIZ,
expectedHeight: font.constants.SIZES.CHAR_HEIGHT
* this.constants.TILES_NUM_VERT,
/**
* @param {HTMLImageElement} img
*/
test: img => {
const constraint = this.constraints.imageSize;
if (img.width !== constraint.expectedWidth
|| img.height !== constraint.expectedHeight) {
gui_log(i18n.getMessage("osdSetupCustomLogoImageSizeError", {
width: img.width,
height: img.height,
}));
return false;
}
return true;
},
},
// test for pixel colors
colorMap: {
el: "#font-logo-info-colors",
/**
* @param {HTMLImageElement} img
*/
test: img => {
const canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
for (let y = 0, Y = canvas.height; y < Y; y++) {
for (let x = 0, X = canvas.width; x < X; x++) {
const rgbPixel = ctx.getImageData(x, y, 1, 1).data.slice(0, 3),
colorKey = rgbPixel.join("-");
if (!this.constants.MCM_COLORMAP[colorKey]) {
gui_log(i18n.getMessage("osdSetupCustomLogoColorMapError", {
valueR: rgbPixel[0],
valueG: rgbPixel[1],
valueB: rgbPixel[2],
posX: x,
posY: y,
}));
return false;
}
}
}
return true;
},
},
};
// deps from osd.js
this.font = font;
this.logoStartIndex = logoStartIndex;
// inject logo size variables for dynamic translation strings
i18n.addResources({
logoWidthPx: `${this.constraints.imageSize.expectedWidth}`, // NOSONAR
logoHeightPx: `${this.constraints.imageSize.expectedHeight}`, // NOSONAR
});
// find/cache DOM elements
Object.keys(this.elements).forEach(key => {
this.elements[`$${key}`] = $(this.elements[key]);
});
Object.keys(this.constraints).forEach(key => {
this.constraints[key].$el = $(this.constraints[key].el);
});
// resize logo preview area to match tile size
this.elements.$preview
.width(this.constraints.imageSize.expectedWidth)
.height(this.constraints.imageSize.expectedHeight);
this.resetImageInfo();
};
LogoManager.resetImageInfo = function () {
this.hideUploadHint();
Object.values(this.constraints).forEach(constraint => {
const $el = constraint.$el;
$el.toggleClass("invalid", false);
$el.toggleClass("valid", false);
});
};
LogoManager.showConstraintNotSatisfied = constraint => {
constraint.$el.toggleClass("invalid", true);
};
LogoManager.showConstraintSatisfied = constraint => {
constraint.$el.toggleClass("valid", true);
};
LogoManager.showUploadHint = function () {
this.elements.$uploadHint.show();
};
LogoManager.hideUploadHint = function () {
this.elements.$uploadHint.hide();
};
/**
* Show a file open dialog and resolve to an Image object.
*
* @returns {Promise}
*/
LogoManager.openImage = function () {
return new Promise((resolveOpenImage, rejectOpenImage) => {
const dialogOptions = {
type: 'openFile',
accepts: this.acceptFileTypes,
};
chrome.fileSystem.chooseEntry(dialogOptions, fileEntry => {
if (checkChromeRuntimeError()) {
return;
}
// load and validate selected image
const img = new Image();
img.onload = () => {
validateImage.apply(this, [img])
.then(() => resolveOpenImage(img))
.catch(error => rejectOpenImage(error));
};
img.onerror = error => rejectOpenImage(error);
fileEntry.file(file => img.src = `file://${file.path}`);
});
});
};
/**
* Replaces the logo in the loaded font based on an image.
*
* @param {HTMLImageElement} img
*/
LogoManager.replaceLogoInFont = function (img) {
// loop through an image and replace font symbols
const canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
let charAddr = this.logoStartIndex;
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
for (let y = 0; y < this.constants.TILES_NUM_VERT; y++) {
for (let x = 0; x < this.constants.TILES_NUM_HORIZ; x++) {
const imageData = ctx.getImageData(
x * this.font.constants.SIZES.CHAR_WIDTH,
y * this.font.constants.SIZES.CHAR_HEIGHT,
this.font.constants.SIZES.CHAR_WIDTH,
this.font.constants.SIZES.CHAR_HEIGHT,
),
newChar = imageToCharacter.apply(this, [imageData.data]);
replaceChar.apply(this, [newChar, charAddr]);
charAddr++;
}
}
};
/**
* Draw the logo using the loaded font data.
*/
LogoManager.drawPreview = function () {
const $el = this.elements.$preview.empty();
for (let i = this.logoStartIndex, I = this.font.constants.MAX_CHAR_COUNT; i < I; i++) {
const url = this.font.data.character_image_urls[i];
$el.append(`<img src="${url}" title="0x${i.toString(16)}"></img>`);
}
};
export default LogoManager;