-
Notifications
You must be signed in to change notification settings - Fork 5
/
contentscript.js
552 lines (496 loc) · 18.9 KB
/
contentscript.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// TODO:
// - Statistics, info panel
// - Why did Equinox zoom box work ok?
// - Simple vs advanced tab
// - Also affect mouse cursor
// - Option to follow mouse cursor
// - Might be more starfish shaped:
// - Misshapen macular degenation blob, add blur to outside
// - Stargardt's add brightness, some good holes in it, loss of contrast sensitivity
var oldViewData = {};
var flutterCount = 0;
const kSvgDocClassName = 'noCoffeeSvgFilterDoc';
const kSvgBodyClassName = 'noCoffeeSvgFilterBody';
const kSvgOverlayClassName = 'noCoffeeSvgOverlay';
const kBlockerClassName = 'noCoffeeVisionBlockingDiv';
const kCloudyClassName = 'noCoffeeVisionCloudyDiv';
const kMaxFloaters = 15;
const kMaxFloaterTravel = 10; // Percent of screen
const kMinFloaterTravelTime = 3; // Seconds
const kMaxFloaterTravelTime = 20; // Seconds
const kMaxFloaterTravelDelayTime = 20; // Seconds
const kMaxFloaterRotation = 40;
const kMinFloaterWidth = 10;
const kMinFloaterOpacity = 0.1;
const kMaxFloaterOpacity = 0.4;
const kFlutterDist = 15;
function createSvgFilter(filterMarkup, className) {
let svgMarkup =
'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">' +
'<defs>' +
'<filter id="' + className + Date.now() + '" >' +
filterMarkup +
'</filter>' +
'</defs>' +
'</svg>';
let containerElt = document.createElement('div');
containerElt.style.visibility = 'hidden';
containerElt.className = className;
containerElt.innerHTML = svgMarkup;
return containerElt;
}
function getSvgColorMatrixFilter(colorMatrixValues) {
if (!colorMatrixValues) {
return '';
}
let str = '<feColorMatrix type="matrix" values="' + colorMatrixValues + '" />';
return str;
}
function getSvgGhostingFilter(ghostingLevel) {
if (!ghostingLevel) {
return '';
}
let str =
'<feOffset result="offOut" in="SourceGraphic" dx="' + ghostingLevel + '" dy="0" />' +
'<feBlend in="SourceGraphic" in2="offOut" mode="multiply" />';
return str;
}
function getSvgFlutterFilter(flutter) {
if (!flutter || !flutter.flutterLevel) {
return '';
}
let horizMovement = kFlutterDist / flutter.zoom;
let str =
'<feOffset result="offOut" in="SourceGraphic" dx="' + horizMovement + '" dy="0" />';
return str;
}
function oneFlutter(bodyCssFilter) {
if (--flutterCount <= 0) {
stopFluttering();
}
document.body.style.webkitFilter = document.body.style.webkitFilter ? '' : bodyCssFilter;
}
function stopFluttering() {
document.body.webkitFilter = '';
clearInterval(window.flutterInterval);
window.flutterInterval = 0;
}
function startFluttering(flutter, bodyCssFilter) {
if (!window.flutterInterval) {
window.flutterCount = Math.random() * flutter.flutterLevel * 1.5 + 5;
window.flutterInterval = setInterval(function() { oneFlutter(bodyCssFilter); }, 10);
}
}
function maybeStartFluttering(flutter, bodyCssFilter) {
let randomized = Math.random() * 1000;
if (randomized < flutter.flutterLevel) {
startFluttering(flutter, bodyCssFilter);
}
}
function initFlutter(flutter, bodyCssFilter) {
startFluttering(flutter, bodyCssFilter);
window.addEventListener('scroll', function() { maybeStartFluttering(flutter, bodyCssFilter); });
window.addEventListener('mousemove', function() { maybeStartFluttering(flutter, bodyCssFilter); });
}
function createFloater(floater) {
let floaterImg = document.createElement('img');
floaterImg.style.position = 'fixed';
floaterImg.style.width = floater.width;
floaterImg.style.left = floater.x + '%';
floaterImg.style.top = floater.y + '%';
floaterImg.style.opacity = floater.opacity.toString();
floaterImg.style.webkitTransform = 'rotate(' + floater.rotation + 'deg)';
floaterImg.style.zIndex = '999999';
floaterImg.src = browser.runtime.getURL('overlays/floater-' + floater.imageNum + '.png');
floaterImg.id = 'noCoffeeFloater-' + floater.imageNum;
floaterImg.addEventListener('webkitTransitionEnd', // Start new animation some time after last finished
function() { animateFloater(floater, floaterImg); }, false);
return floaterImg;
}
function resetFloaters(blockerDiv, floaters) {
let floaterMix = [];
let count;
for (count = 0; count < kMaxFloaters; count++) {
floaterMix[count] = count + 1;
}
for (count = 0; count < floaters.numFloaters; count++) {
let nextItemIndex = Math.floor(Math.random() * (kMaxFloaters - count));
let nextItem = floaterMix[nextItemIndex];
floaterMix[nextItemIndex] = floaterMix[kMaxFloaters - count - 1]; // Don't use same floater twice
let floater = {
imageNum: nextItem,
opacity: Math.random() * (kMaxFloaterOpacity - kMinFloaterOpacity) + kMinFloaterOpacity,
width: (Math.max(kMinFloaterWidth, Math.random() * floaters.maxWidth)) / getZoom(),
x: Math.random() * 100,
y: Math.random() * 100,
rotation: Math.random() * 360
};
let floaterImg = createFloater(floater);
blockerDiv.appendChild(floaterImg);
animateFloater(floater, floaterImg);
}
}
function animateFloater(floater, floaterImg) {
let delay = Math.random() * kMaxFloaterTravelDelayTime;
setTimeout(function() {
let id = 'noCoffeeFloaterAnimationStyle-' + floater.imageNum;
let lastAnimation = document.getElementById(id);
if (lastAnimation) {
// Stabilize the coordinates to the new location so it doesn't jump back when we remove the old style
let rect = floaterImg.getBoundingClientRect();
floaterImg.left = rect.left + 'px';
floaterImg.top = rect.top + 'px';
// Remove the old style
deleteNodeIfExists(lastAnimation);
}
let floaterStyleElt = document.createElement('style');
floaterStyleElt.id = id;
let direction = Math.random() * 360;
let newRotation = floater.rotation + Math.random() * kMaxFloaterRotation * 2 - kMaxFloaterRotation;
let distance = Math.random() * kMaxFloaterTravel;
let left = floater.x + Math.sin(direction) * distance;
let top = floater.y + Math.cos(direction) * distance;
let seconds = Math.random() * (kMaxFloaterTravelTime - kMinFloaterTravelTime) + kMinFloaterTravelTime;
floaterStyleElt.innerText = '#' + floaterImg.id + ' { ' +
'top: ' + top + '% !important; ' +
'left: ' + left + '% !important; ' +
'-webkit-transform: rotate(' + newRotation + 'deg) !important;' +
'-webkit-transition: all ' + seconds + 's;' +
'}';
floaterImg.parentNode.appendChild(floaterStyleElt);
}, delay * 1000);
}
function createCloudyDiv(cloudy) {
if (!cloudy || !cloudy.cloudyLevel) {
return null;
}
let cloudyDiv = document.createElement('div');
cloudyDiv.className = kCloudyClassName;
let size = 100 * cloudy.zoom;
let style =
'z-index:2147483646 !important; ' +
'-webkit-transform: scale(' + (1 / cloudy.zoom) + '); ' +
'-webkit-transform-origin: 0 0;' +
'pointer-events: none; ' +
'position: fixed; left: 0; top: 0; height: ' + size + '%; width: ' + size + '%; ' +
'background-image: url(' + browser.runtime.getURL('overlays/cataracts.png') + '); ' +
'background-repeat: no-repeat; background-size: 100% 100%; ' +
'background-position: 0 0; -webkit-filter: opacity(' + cloudy.cloudyLevel + '%);';
cloudyDiv.setAttribute('style', style);
return cloudyDiv;
}
function createBlockerDiv(block) {
if (!block) {
return null;
}
let blockerDiv = document.createElement('div');
blockerDiv.className = kBlockerClassName;
let style =
'z-index:2147483646 !important; ' +
'pointer-events: none; ' +
'position: fixed; ';
if (block.image) {
style += "background-image: url('" + block.image + "'); " +
'background-repeat: no-repeat; background-size: 100% 100%; ' +
'left: ' + block.xPosition + '; top: ' + block.yPosition + '; -webkit-filter: opacity(' + block.opacity + '%);';
// "-webkit-filter: url(#noCoffeeDisplacementFilter);
if (block.displacement && false) { // Don't try to do this yet
blockerDiv.innerHTML =
'<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid meet">' +
'<defs>' +
'<filter id="noCoffeeDisplacementFilter" filterUnits="userSpaceOnUse">' +
'<feImage xlink:href="' + block.image + '" result="noCoffeeSource"/>' +
'<feImage xlink:href="' + block.image + '" result="noCoffeeDisplacementMap"/>' +
'<feDisplacementMap scale="1" xChannelSelector="R" yChannelSelector="R" in="noCoffeeSource" in2="noCoffeeDisplacementMap"/>' +
'</filter>' +
'</defs>' +
'<use filter="url(#noCoffeeDisplacementFilter)" />' +
'</svg>';
}
} else if (block.innerStrength) {
style += 'left: 0; top: 0; height: 100%; width: 100%;';
if (block.type === 'radial') {
style += 'background-image: -webkit-radial-gradient(circle, ' +
block.innerColor + ' ' + block.innerStrength + '%, ' +
block.outerColor + ' ' + block.outerStrength + '%);';
} else {
style += 'background-image: -webkit-linear-gradient(left, ' +
block.innerColor + ' ' + block.innerStrength + '%, ' +
block.outerColor + ' ' + block.outerStrength + '%);';
}
}
if (block.floaters) {
resetFloaters(blockerDiv, block.floaters);
}
if (block.zoom) {
let size = 100 * block.zoom;
style += '-webkit-transform: scale(' + 1 / block.zoom + '); -webkit-transform-origin: 0 0; ' +
'width: ' + size + '%; height: ' + size + '%; left: 0; top: 0;';
}
blockerDiv.setAttribute('style', style);
return blockerDiv;
}
function createSvgSnowOverlay(snow) {
if (!snow || !snow.amount) {
return null;
}
let svgOverlay = document.createElement('div');
svgOverlay.className = kSvgOverlayClassName;
let size = 100 * snow.zoom;
let startPos = (100 - size) / 2;
svgOverlay.setAttribute('style',
'-webkit-transform: scale(' + (1 / snow.zoom) + '); ' +
'z-index:2147483645 !important; ' +
'pointer-events: none; ' +
'position: fixed; left: ' + startPos + '%; top: ' + startPos + '%; height: ' + size + '%; width: ' + size + '%; ');
svgOverlay.innerHTML =
'<svg xmlns="http://www.w3.org/2000/svg" style="width: 100%; height: 100%" preserveAspectRatio="xMidYMid meet">' +
'<defs>' +
'<filter id="noCoffeeSnowFilter" filterUnits="userSpaceOnUse" x="0" y="0">' +
'<feTurbulence type="fractalNoise" baseFrequency=".25" numOctaves="1" seed="4" stitchTiles="noStitch" width="159" height="120">' +
'<animate attributeType="XML" attributeName="seed" from="500" to="1" dur="70s" repeatCount="indefinite" />' +
'</feTurbulence>' +
'<feComponentTransfer>' +
'<feFuncA type="discrete" tableValues="0 0 ' + snow.amount + ' 1"/>' +
'</feComponentTransfer>' +
'<feTile x="0" y="0" width="100%" height="100%" result="tiled"/>' +
'</filter>' +
'</defs>' +
'<use filter="url(#noCoffeeSnowFilter)" />' +
'</svg>';
return svgOverlay;
}
// Return style object
function getView(viewData) {
let view = {
doc: {
cssFilter: '',
svgFilterElt: undefined
},
body: {
cssFilter: '',
svgFilterElt: undefined
},
svgOverlayElt: undefined,
blockerDiv: undefined
};
// Create new svg color filter -- old one will be removed
// Needs to go on doc element so that background of page is always affected
let svgColorFilterMarkup = getSvgColorMatrixFilter(viewData.colorMatrixValues);
if (svgColorFilterMarkup) {
view.doc.svgFilterElt = createSvgFilter(svgColorFilterMarkup, kSvgDocClassName);
let id = view.doc.svgFilterElt.querySelector('filter').id;
view.doc.cssFilter += 'url(#' + id + ') ';
}
// Create new svg ghosting filter -- old one will be removed
// Ghosting filter needs to go on body -- learned through trial and error. Seems to be a bug in Chrome.
let svgGhostingFilterMarkup = getSvgGhostingFilter(viewData.ghosting);
let svgFlutterFilterMarkup = getSvgFlutterFilter(viewData.flutter);
stopFluttering();
if (svgGhostingFilterMarkup || svgFlutterFilterMarkup) {
view.body.svgFilterElt = createSvgFilter(svgFlutterFilterMarkup || svgGhostingFilterMarkup, kSvgBodyClassName);
let id = view.body.svgFilterElt.querySelector('filter').id;
view.body.cssFilter += 'url(#' + id + ')';
if (svgFlutterFilterMarkup) {
initFlutter(viewData.flutter, view.body.cssFilter);
}
}
// Create new svg overlay div -- old one will be removed
if (!deepEquals(oldViewData.snow, viewData.snow)) {
view.svgOverlayElt = createSvgSnowOverlay(viewData.snow);
}
// Create new cloudy div -- old one will be removed
if (!deepEquals(oldViewData.cloudy, viewData.cloudy)) {
view.cloudyDiv = createCloudyDiv(viewData.cloudy);
}
// Create new blocker div -- old one will be removed
if (!deepEquals(oldViewData.block, viewData.block)) {
view.blockerDiv = createBlockerDiv(viewData.block);
}
if (viewData.blur) {
view.doc.cssFilter += 'blur(' + viewData.blur + 'px) ';
}
if (viewData.contrast != 100) {
view.doc.cssFilter += 'contrast(' + viewData.contrast + '%) ';
}
if (viewData.brightness) {
view.doc.cssFilter += 'brightness(' + viewData.brightness + '%) ';
}
return view;
}
function getZoom() {
return window.outerWidth / window.innerWidth; // Works in Chrome
}
// Computed values based on user settings
function getViewData(settings) {
let zoom = getZoom();
// When there is any ghosting, add a little blur
let blurPlusExtra = settings.blurLevel + (settings.ghostingLevel > 0 ? 3 : 0) + (settings.cloudyLevel / 2.5);
let viewData = {
blur: (blurPlusExtra / zoom) / 2,
contrast: settings.contrastLevel ? 60 - settings.contrastLevel : 100,
colorMatrixValues: settings.colorDeficiencyMatrixValues,
brightness: settings.brightnessLevel * 1.2,
ghosting: settings.ghostingLevel / zoom,
snow: { zoom: zoom, amount: 0.03 * settings.snowLevel },
cloudy: { zoom: zoom, cloudyLevel: settings.cloudyLevel * 6 },
flutter: { zoom: zoom, flutterLevel: settings.flutterLevel }
};
if (settings.blockStrength) {
switch (settings.blockType) {
case 'centralBlock': // Macular degeneration
viewData.block = {
type: 'radial',
innerStrength: settings.blockStrength / 2,
outerStrength: settings.blockStrength + 10,
innerColor: 'rgba(150,150,150,' + (0.9 + settings.blockStrength / 1000) + ')',
outerColor: 'transparent'
};
break;
case 'peripheralBlock': // Glaucoma or retinitis pigmentosa
viewData.block = {
block: zoom,
type: 'radial',
innerStrength: (100 - settings.blockStrength) - 30,
outerStrength: (100 - settings.blockStrength) * 1.5 - 20,
innerColor: 'transparent',
outerColor: 'black'
};
break;
case 'sideBlock': // Hemianopia
viewData.block = {
type: 'linear',
innerStrength: settings.blockStrength / 2,
outerStrength: settings.blockStrength + 10,
innerColor: 'black',
outerColor: 'transparent'
};
break;
case 'spotBlock': // Diabetic retinopathy
viewData.blur += settings.blockStrength / 70; // Extra blur for diabetic retinopathy
viewData.block = {
outerWidth: window.top.outerWidth, // We rerender when zoom or window size changes
outerHeight: window.top.outerHeight,
xPosition: '0px',
yPosition: '0px',
image: browser.runtime.getURL('overlays/diabetic-retinopathy.png'),
opacity: settings.blockStrength,
extraOpacity: settings.blockStrength * 2,
displacement: false,
zoom: zoom
};
break;
case 'cornerBlock': // Retinal detachment
viewData.block = {
outerWidth: window.top.outerWidth, // We rerender when zoom or window size chnages
outerHeight: window.top.outerHeight,
xPosition: (settings.blockStrength / 2.5 - 40) + '%',
yPosition: (settings.blockStrength / 2.5 - 40) + '%',
image: browser.runtime.getURL('overlays/retinal-detachment.png'),
opacity: 100,
displacement: true,
zoom: zoom
};
// Fall-through -- retinal detachment comes with floaters
case 'floaterBlock': // Floaters
if (typeof viewData.block === 'undefined') {
viewData.block = {};
}
viewData.block.floaters = {
numFloaters: Math.min(Math.round(settings.blockStrength / 6.5 + 1), kMaxFloaters),
maxVelocity: 2,
maxWidth: settings.blockStrength + 50
};
viewData.block.zoom = zoom;
break;
default:
viewData.block = null;
break;
}
}
return viewData;
}
function deleteNodeIfExists(node) {
if (node) { node.parentNode.removeChild(node); }
}
function deepEquals(obj1, obj2) {
if (!obj1 || !obj2) {
return obj1 === obj2;
}
if (typeof obj1 !== typeof obj2) {
return false;
}
if (typeof obj1 === 'object') {
let item;
for (item in obj1) {
if (!deepEquals(obj1[item], obj2[item])) {
return false; // Recurse for sub-sobjects
}
}
for (let item2 in obj2) {
if (typeof obj1[item2] === 'undefined') {
return false;
}
}
return true;
}
return obj1 === obj2;
}
function refresh(viewData) {
let view = getView(viewData);
if (typeof view.doc.svgFilterElt !== 'undefined') {
deleteNodeIfExists(document.querySelector('.' + kSvgDocClassName)); // Delete old one
if (view.doc.svgFilterElt) {
document.body.appendChild(view.doc.svgFilterElt);
}
}
if (typeof view.body.svgFilterElt !== 'undefined') {
deleteNodeIfExists(document.querySelector('.' + kSvgBodyClassName)); // Delete old one
if (view.body.svgFilterElt) {
document.body.appendChild(view.body.svgFilterElt);
}
}
if (typeof view.svgOverlayElt !== 'undefined') {
deleteNodeIfExists(document.querySelector('.' + kSvgOverlayClassName)); // Delete old one
if (view.svgOverlayElt) {
document.body.appendChild(view.svgOverlayElt);
}
}
if (typeof view.cloudyDiv !== 'undefined') {
deleteNodeIfExists(document.querySelector('.' + kCloudyClassName)); // Delete old one
if (view.cloudyDiv) {
document.body.appendChild(view.cloudyDiv);
}
}
if (typeof view.blockerDiv !== 'undefined') {
deleteNodeIfExists(document.querySelector('.' + kBlockerClassName)); // Delete old one
if (view.blockerDiv) {
document.body.appendChild(view.blockerDiv);
}
}
document.documentElement.style.webkitFilter = view.doc.cssFilter;
document.body.style.webkitFilter = view.body.cssFilter;
}
// Setup refresh listener
browser.runtime.onMessage.addListener(
function(request) {
if (request.type === 'refresh') {
let viewData = getViewData(request.settings);
if (!deepEquals(viewData, oldViewData)) {
refresh(viewData); // View data has changed -- re-render
oldViewData = viewData;
}
}
});
function initIfStillNecessaryAndBodyExists() {
if (document.body && !isInitialized) {
browser.runtime.sendMessage({type: 'getSettings'}, function() {});
isInitialized = true;
}
}
var isInitialized = false;
setTimeout(initIfStillNecessaryAndBodyExists, 0);
// Refresh once on first load
document.addEventListener('readystatechange', function() {
initIfStillNecessaryAndBodyExists();
});