/
pixel-perfect-actor.js
543 lines (444 loc) · 14.2 KB
/
pixel-perfect-actor.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
/* See license.txt for terms of usage */
"use strict";
/**
* This module is loaded on the backend (can be a remote device) where
* some module or features (such as Tracing console) don't have to
* be available.
*/
const { Cu } = require("chrome");
// Remote Debugging Protocol API
const { DebuggerServer } = Cu.import("resource://gre/modules/devtools/dbg-server.jsm", {});
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const protocol = devtools["require"]("devtools/server/protocol");
const { method, RetVal, ActorClass, Actor, Arg } = protocol;
const Events = require("sdk/event/core");
const DomEvents = require("sdk/dom/events");
const { makeInfallible } = devtools["require"]("devtools/toolkit/DevToolsUtils.js");
// For debugging purposes. Note that the tracing module isn't available
// on the backend (in case of remote device debugging).
// const baseUrl = "resource://pixelperfectplugin-at-openhouseconcepts-dot-com/";
// const { getTrace } = Cu.import(baseUrl + "node_modules/firebug.sdk/lib/core/actor.js");
// const Trace = getTrace();
const Trace = {sysout: () => {}};
/**
* Helper actor state watcher.
*/
function expectState(expectedState, method) {
return function(...args) {
if (this.state !== expectedState) {
Trace.sysout("actor.expectState; ERROR wrong state, expected '" +
expectedState + "', but current state is '" + this.state + "'" +
", method: " + method);
let msg = "Wrong State: Expected '" + expectedState + "', but current " +
"state is '" + this.state + "'";
return Promise.reject(new Error(msg));
}
try {
return method.apply(this, args);
} catch (err) {
Cu.reportError("actor.js; expectState EXCEPTION " + err, err);
}
};
}
/**
* @actor This object represents an actor that is dynamically injected
* (registered) to the debuggee target (back-end). The debuggee target
* can be a running instance of the browser on local machine or remote
* device such as mobile phone. The communication with this object is
* always done through RDP (Remote Debugging Protocol). Read more about
* {@link https://wiki.mozilla.org/Remote_Debugging_Protocol|RDP}.
*
* This object implements the following logic that runs on that back-end:
* 1. Rendering of registered layers on top of the current page
* 2. Drag and drop of layers (changing location on the page). This user
* operation fires events back to the chrome scope, so the UI (coordinates)
* can be properly updated.
*
* Layers are not inserted into the page. They exist inside
* a 'Canvas Frame' that is overlapping the page to avoid page DOM
* modification (which can be dangerous). The Canvas Frame is supported
* by the platform and originally used by HTML Inspector highlighter.
*/
var PixelPerfectActor = ActorClass(
/** @lends PixelPerfectActor */
{
typeName: "pixelPerfectActor",
/**
* Events emitted by this actor.
*/
events: {
"dragstart": { data: Arg(0, "json") },
"drag": { data: Arg(0, "json") },
"dragend": { data: Arg(0, "json") }
},
// Initialization
initialize: function(conn, parent) {
Trace.sysout("PixelPerfectActor.initialize; parent: " +
parent.actorID + ", conn: " + conn.prefix, this);
Actor.prototype.initialize.call(this, conn);
this.parent = parent;
this.state = "detached";
this.layers = [];
// Layers (displayed in anonymous canvas content) need to be recreated
// when page navigation happens.
this.onNavigate = this.onNavigate.bind(this);
// Event handlers
this.onMouseDown = this.onMouseDown.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);
this.onMouseClick = this.onMouseClick.bind(this);
},
/**
* The destroy is only called automatically by the framework (parent actor)
* if an actor is instantiated by a parent actor.
*/
destroy: function() {
Trace.sysout("PixelPerfectActor.destroy; state: " + this.state, arguments);
if (this.state === "attached") {
this.detach();
}
Actor.prototype.destroy.call(this);
},
/**
* Automatically executed by the framework when the parent connection
* is closed.
*/
disconnect: function() {
Trace.sysout("PixelPerfectActor.disconnect; state: " + this.state, arguments);
if (this.state === "attached") {
this.detach();
}
},
/**
* Attach to this actor. Executed when the front (client) is attaching
* to this actor.
*/
attach: method(expectState("detached", function() {
Trace.sysout("PixelPerfectActor.attach;", arguments);
this.state = "attached";
Events.on(this.parent, "navigate", this.onNavigate);
}), {
request: {},
response: {
type: "attached"
}
}),
/**
* Set UI stylesheet for anonymous content (sent from the client).
*/
loadSheet: method(expectState("attached", function(source) {
Trace.sysout("PixelPerfectActor.loadSheet;", arguments);
this.uaSource = source;
this.buildAnonumousContent();
}), {
request: {
source: Arg(0, "string")
},
response: {
type: "sheet-loaded"
}
}),
/**
* Detach from this actor. Executed when the front (client) detaches
* from this actor.
*/
detach: method(expectState("attached", function() {
Trace.sysout("PixelPerfectActor.detach;", arguments);
this.state = "detached";
this.destroyLayers();
this.layers = [];
// Remove tab actor listeners
Events.off(this.parent, "navigate", this.onNavigate);
let win = this.parent.window;
let doc = win.document;
// Remove drag-drop listeners
DomEvents.removeListener(doc, "mousedown", this.onMouseDown);
DomEvents.removeListener(doc, "mousemove", this.onMouseMove);
DomEvents.removeListener(doc, "mouseup", this.onMouseUp);
DomEvents.removeListener(doc, "click", this.onMouseClick);
}), {
request: {},
response: {
type: "detached"
}
}),
// Remote Actor API
addLayer: method(function(layer) {
Trace.sysout("PixelPerfectActor.addLayer; " + layer.id, layer);
this.layers.push(layer);
this.buildLayer(layer);
}, {
request: {
layer: Arg(0, "json")
},
response: {
type: "layer-added"
}
}),
removeLayer: method(function(id) {
Trace.sysout("PixelPerfectActor.removeLayer; " + id);
let layer = this.getLayer(id);
this.destroyLayer(layer);
for (let i=0; i<this.layers.length; i++) {
if (this.layers[i].id == id) {
this.layers.splice(i, 1);
break;
}
}
}, {
request: {
id: Arg(0, "string")
},
response: {
type: "layer-removed"
}
}),
modifyLayer: method(function(id, props) {
let layer = this.getLayer(id);
for (let p in props) {
layer[p] = props[p];
}
this.updateLayer(layer);
}, {
request: {
id: Arg(0, "string"),
props: Arg(1, "json")
},
response: {
type: "layer-modified"
}
}),
/**
* Change layer order (affects also rendering order)
*/
moveLayer: method(function(aFrom, aTo) {
var removed = this.layers.splice(aFrom, 1)[0];
this.layers.splice(aTo, 0, removed);
// Rebuild layers
this.destroyLayers();
this.buildLayers();
}, {
request: {
aFrom: Arg(0, "number"),
aTo: Arg(1, "number")
},
response: {
type: "layer-moved"
}
}),
/**
* Return properties of specified layer (including properties of the
* associated anonymous content).
*/
getLayerInfo: method(function(id) {
let layer = this.getLayer(id);
// Get all properties of a layer.
let result = {};
for (let p in layer) {
result[p] = layer[p];
}
// Get all properties of associate anonymous content
let boxAnonId = "box" + layer.id;
let imageAnonId = layer.id;
let content = layer.content;
result.content = {
box: {
style: content.getAttributeForElement(boxAnonId, "style"),
lock: content.getAttributeForElement(boxAnonId, "lock"),
invert: content.getAttributeForElement(boxAnonId, "invert"),
},
image: {
style: content.getAttributeForElement(imageAnonId, "style"),
}
}
return result;
}, {
request: {
id: Arg(0, "string"),
},
response: RetVal("json"),
}),
// Events
/**
* Page navigation handler. Layers need to be built again when
* navigation happens.
*/
onNavigate: function({isTopLevel}) {
Trace.sysout("PixelPerfectActor.onNavigate " + isTopLevel);
// xxxHonza: remove anonymous content created for the
// previous page. We need onPreNavigate, perhaps?
if (isTopLevel) {
// Reset all anonymous content built for the previous page.
this.layers.forEach(layer => layer.content = null);
this.buildAnonumousContent();
}
},
// Anonymous Content Builders (canvas frame)
buildAnonumousContent: function() {
let win = this.parent.window;
let doc = win.document;
// For now css is injected in content as a user agent sheet because
// <style scoped> doesn't work inside anonymous content (see bug 1086532).
// See also: CanvasFrameAnonymousContentHelper
installHelperSheet(win, this.uaSource);
// Build all registered layers.
this.buildLayers();
// Use CanvasFrameAnonymousContentHelper object as soon as
// it's exposed for extensions.
DomEvents.on(doc, "mousedown", this.onMouseDown);
DomEvents.on(doc, "mousemove", this.onMouseMove);
DomEvents.on(doc, "mouseup", this.onMouseUp);
DomEvents.on(doc, "click", this.onMouseClick);
},
buildLayers: makeInfallible(function() {
this.layers.forEach(layer => {
this.buildLayer(layer);
});
}),
destroyLayers: makeInfallible(function() {
this.layers.forEach(layer => {
this.destroyLayer(layer);
});
}),
buildLayer: makeInfallible(function(layer) {
// Bail out if the layer already has an anonymous content built.
if (layer.content) {
return;
}
let doc = this.parent.window.document;
// Anonymous content.
let content = doc.createElement("div");
// Box for layer image.
let imageBox = doc.createElement("div");
imageBox.setAttribute("id", "box" + layer.id);
imageBox.setAttribute("class", "pixelperfect-layer-box");
content.appendChild(imageBox);
// Layer image
let imageNode = doc.createElement("img");
imageNode.src = layer.url;
imageNode.setAttribute("id", layer.id);
imageNode.setAttribute("class", "pixelperfect-layer-image");
imageBox.appendChild(imageNode);
layer.content = doc.insertAnonymousContent(content);
this.updateLayer(layer);
}),
updateLayer: makeInfallible(function(layer) {
let content = layer.content;
if (!content) {
this.buildLayer(layer);
return;
}
// Update image box styles
let boxStyle = "";
boxStyle += "left:" + parseInt(layer.x, 10) + "px;";
boxStyle += "top:" + parseInt(layer.y, 10) + "px;";
boxStyle += "display:" + (layer.visible ? "block" : "none") + ";";
content.setAttributeForElement("box" + layer.id, "style", boxStyle);
if (layer.lock) {
content.setAttributeForElement("box" + layer.id, "lock", "true");
} else {
content.removeAttributeForElement("box" + layer.id, "lock");
}
if (layer.invert) {
content.setAttributeForElement("box" + layer.id, "invert", "true");
} else {
content.removeAttributeForElement("box" + layer.id, "invert");
}
// Update image styles
let imageStyle = "";
imageStyle += "opacity:" + (parseInt(layer.opacity, 10) / 100) + ";";
imageStyle += "transform:" + (layer.scale ? "scale(" + layer.scale + ")" : "none") + ";";
content.setAttributeForElement(layer.id, "style", imageStyle);
}),
destroyLayer: function(layer) {
if (layer.content) {
let doc = this.parent.window.document;
doc.removeAnonymousContent(layer.content);
layer.content = null;
}
},
// Mouse Event Handlers (for drag and drop)
onMouseDown: function(event) {
let target = event.originalTarget;
let layer = this.getLayer(target.id);
if (!layer) {
return;
}
if (layer.lock) {
return;
}
this.draggedLayer = layer;
this.offsetX = event.pageX - layer.x;
this.offsetY = event.pageY - layer.y;
let content = this.draggedLayer.content;
content.setAttributeForElement("box" + this.draggedLayer.id, "drag", "true");
Events.emit(this, "dragstart", {
id: this.draggedLayer.id,
});
cancelEvent(event);
},
onMouseMove: function(event) {
if (!this.draggedLayer) {
return;
}
this.draggedLayer.x = event.pageX - this.offsetX;
this.draggedLayer.y = event.pageY - this.offsetY;
this.updateLayer(this.draggedLayer);
Events.emit(this, "drag", {
id: this.draggedLayer.id,
x: this.draggedLayer.x,
y: this.draggedLayer.y
});
cancelEvent(event);
},
onMouseUp: function(event) {
if (!this.draggedLayer) {
return;
}
this.updateLayer(this.draggedLayer);
Events.emit(this, "dragend", {
id: this.draggedLayer.id,
x: this.draggedLayer.x,
y: this.draggedLayer.y
});
let content = this.draggedLayer.content;
content.removeAttributeForElement("box" + this.draggedLayer.id, "drag");
this.draggedLayer = null;
cancelEvent(event);
},
onMouseClick: function(event) {
if (this.draggedLayer) {
cancelEvent(event);
}
//xxxHonza: select the clicked layer, so it can be moved by keyboard?
},
// Layer Helpers
getLayer: function(id) {
for (let i=0; i<this.layers.length; i++) {
if (this.layers[i].id == id) {
return this.layers[i];
}
}
}
});
// Helpers
/**
* Inject a helper stylesheet in the window.
*/
let installedHelperSheets = new WeakMap;
function installHelperSheet(win, source, type="agent") {
if (installedHelperSheets.has(win.document)) {
return;
}
let {Style} = require("sdk/stylesheet/style");
let {attach} = require("sdk/content/mod");
let style = Style({source, type});
attach(style, win);
installedHelperSheets.set(win.document, style);
}
function cancelEvent(event) {
event.stopPropagation();
event.preventDefault();
}
// Exports from this module
exports.PixelPerfectActor = PixelPerfectActor;