on d6201ee help sign in
elk/runtime/Debugger.js
471 lines 12 kB history raw
2(function() {
3'use strict';
5Elm.Debugger = null;
6Elm.debuggerAttach = function(module, hotSwapState /* =undefined */) {
7 return {
8 make: function(runtime) {
9 var wrappedModule = debugModule(module, runtime);
10 Elm.Debugger = debuggerInit(wrappedModule, runtime, hotSwapState);
11 dispatchElmDebuggerInit();
12 return wrappedModule.moduleInstance;
13 }
14 };
15};
17function dispatchElmDebuggerInit() {
18 if (parent.window) {
19 var dispatch = function(_) {
20 parent.window.postMessage("elmDebuggerInit", window.location.origin);
21 };
22 if (parent.window.document.readyState === "complete") {
23 dispatch();
24 }
25 else {
26 parent.window.addEventListener("load", dispatch);
27 }
28 }
31function debugModule(module, runtime) {
32 var programPaused = false;
33 var recordedEvents = [];
34 var asyncCallbacks = [];
35 var watchTracker = Elm.Native.Debug.make(runtime).watchTracker;
37 function wrapNotify(id, v) {
38 var timestep = Date.now();
40 if (programPaused) {
41 // ignore async events generated while playing back
42 // or user events while program is paused
43 return false;
44 }
45 else {
46 var changed = runtime.notify(id, v, timestep);
47 recordEvent(id, v, timestep);
48 if (parent.window) {
49 parent.window.postMessage("elmNotify", window.location.origin);
50 }
51 return changed;
52 }
53 };
55 function wrapRunDelayed(func, delayMs) {
56 var cbObj = { func:func, delayMs:delayMs, timerId:0, executed:false };
57 var timerId = setTimeout(function() {
58 cbObj.executed = true;
59 func();
60 }, delayMs);
61 cbObj.timerId = timerId;
62 asyncCallbacks.push(cbObj);
63 return timerId;
64 }
66 function recordEvent(id, v, timestep) {
67 watchTracker.pushFrame();
68 recordedEvents.push({ id:id, value:v, timestep:timestep });
69 }
71 function clearAsyncCallbacks() {
72 asyncCallbacks.forEach(function(timer) {
73 if (!timer.executed) {
74 clearTimeout(timer.timerId);
75 }
76 });
77 }
79 function clearRecordedEvents() {
80 recordedEvents = [];
81 }
83 function getRecordedEventsLength() {
84 return recordedEvents.length;
85 }
87 function getRecordedEventAt(i) {
88 return recordedEvents[i];
89 }
91 function copyRecordedEvents() {
92 return recordedEvents.slice();
93 }
95 function loadRecordedEvents(events) {
96 recordedEvents = events.slice();
97 }
99 function setPaused(v) {
100 programPaused = v;
101 if (programPaused) {
102 clearAsyncCallbacks();
103 tracePath.stopRecording();
104 }
105 else {
106 // executeCallbacks should only be called when continuing, not when restarting.
107 //executeCallbacks(asyncCallbacks, false);
108 tracePath.startRecording();
109 }
110 }
112 function getPaused() {
113 return programPaused;
114 }
116 // runtime is the prototype of wrappedRuntime
117 // so we can access all runtime properties too
118 var wrappedRuntime = Object.create(runtime);
119 wrappedRuntime.notify = wrapNotify;
120 wrappedRuntime.runDelayed = wrapRunDelayed;
122 var assignedPropTracker = Object.create(wrappedRuntime);
123 var moduleInstance = module.make(assignedPropTracker);
125 // make sure the signal graph is actually a signal & extract the visual model
126 if ( !('recv' in moduleInstance.main) ) {
127 moduleInstance.main = Elm.Signal.make(runtime).constant(moduleInstance.main);
128 }
130 // The main module stores imported modules onto the runtime.
131 // To ensure only one instance of each module is created,
132 // we assign them back on the original runtime object.
133 Object.keys(assignedPropTracker).forEach(function(key) {
134 runtime[key] = assignedPropTracker[key];
135 });
137 var moduleNodes = flattenNodes(wrappedRuntime.inputs);
138 var tracePath = tracePathInit(runtime, moduleInstance.main);
140 return {
141 moduleInstance: moduleInstance,
142 moduleNodes: moduleNodes,
143 initialNodeValues: saveNodeValues(moduleNodes),
144 initialAsyncCallbacks: asyncCallbacks.slice(),
145 // API functions
146 clearAsyncCallbacks: clearAsyncCallbacks,
147 clearRecordedEvents: clearRecordedEvents,
148 getRecordedEventsLength: getRecordedEventsLength,
149 getRecordedEventAt: getRecordedEventAt,
150 copyRecordedEvents: copyRecordedEvents,
151 loadRecordedEvents: loadRecordedEvents,
152 getPaused: getPaused,
153 setPaused: setPaused,
154 tracePath: tracePath,
155 watchTracker: watchTracker,
156 };
159function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
160 var eventCounter = 0;
162 function resetProgram() {
163 debugModule.clearAsyncCallbacks();
164 restoreNodeValues(debugModule.moduleNodes, debugModule.initialNodeValues);
165 redrawGraphics();
166 }
168 function restartProgram() {
169 resetProgram();
170 debugModule.watchTracker.clear();
171 debugModule.tracePath.clearTraces();
172 debugModule.clearRecordedEvents();
173 debugModule.setPaused(false);
174 executeCallbacks(debugModule.initialAsyncCallbacks, true);
175 }
177 function pauseProgram() {
178 debugModule.setPaused(true);
179 eventCounter = debugModule.getRecordedEventsLength();
180 }
182 function continueProgram() {
183 if (debugModule.getPaused())
184 {
185 debugModule.setPaused(false);
186 }
187 }
189 function stepTo(index) {
190 if (!debugModule.getPaused()) {
191 debugModule.setPaused(true);
192 resetProgram();
193 }
195 if (index < 0 || index > getMaxSteps()) {
196 throw "Index out of bounds: " + index;
197 }
199 if (index < eventCounter) {
200 resetProgram();
201 eventCounter = 0;
202 }
204 assert(index >= eventCounter, "index must be bad");
205 while (eventCounter < index) {
206 var nextEvent = debugModule.getRecordedEventAt(eventCounter);
207 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
209 eventCounter += 1;
210 }
211 assert(eventCounter == index, "while loop didn't work");
212 }
214 function getMaxSteps() {
215 return debugModule.getRecordedEventsLength();
216 }
218 function doPlayback(eventList) {
219 var x = eventList.shift();
220 var time = x[2];
221 runtime.notify(x[0], x[1], x[2]);
223 if (eventList.length > 0) {
224 var delta = eventList[0][2] - time;
225 setTimeout(function() { doPlayback(eventList); }, delta);
226 }
227 }
229 function redrawGraphics() {
230 var main = debugModule.moduleInstance.main
231 for (var i = main.kids.length ; i-- ; ) {
232 main.kids[i].recv(Date.now(), true, main.id);
233 }
234 }
236 function getHotSwapState() {
237 var counter = eventCounter;
238 if (!debugModule.getPaused()) {
239 counter = getMaxSteps();
240 }
241 return {
242 recordedEvents: debugModule.copyRecordedEvents(),
243 eventCounter: counter
244 };
245 }
247 function dispose() {
248 var parentNode = runtime.node.parentNode;
249 parentNode.removeChild(debugModule.tracePath.canvas);
250 parentNode.removeChild(runtime.node);
251 }
253 if (hotSwapState) {
254 debugModule.setPaused(true);
255 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
257 // draw new trace path
258 debugModule.tracePath.startRecording();
259 stepTo(getMaxSteps());
260 debugModule.tracePath.stopRecording();
262 stepTo(hotSwapState.eventCounter);
263 }
265 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
267 var elmDebugger = {
268 restart: restartProgram,
269 pause: pauseProgram,
270 kontinue: continueProgram,
271 getMaxSteps: getMaxSteps,
272 stepTo: stepTo,
273 getPaused: debugModule.getPaused,
274 getHotSwapState: getHotSwapState,
275 dispose: dispose,
276 allNodes: debugModule.moduleNodes,
277 watchTracker: debugModule.watchTracker,
278 mainNode: debugModule.moduleInstance.main
279 };
281 return elmDebugger;
284function Point(x, y) {
285 this.x = x;
286 this.y = y;
288 this.translate = function(x, y) {
289 return new Point(this.x + x, this.y + y);
290 }
292 this.equals = function(p) {
293 return this.x == p.x && this.y == p.y;
294 }
297function tracePathInit(runtime, mainNode) {
298 var List = Elm.List.make(runtime);
299 var Signal = Elm.Signal.make(runtime);
300 var tracePathNode = A2(Signal.lift, graphicsUpdate, mainNode);
301 var tracePathCanvas = createCanvas();
302 var tracePositions = {};
303 var recordingTraces = true;
305 function findPositions(currentScene) {
306 var positions = {};
307 function processElement(elem, offset) {
308 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
309 {
310 List.map(F2(processForm)(offset))(elem.element.model.forms);
311 }
312 else if (elem.element.ctor == "Image" && elem.props.debugTracePathId)
313 {
314 positions[elem.props.debugTracePathId] = new Point(offset.x, offset.y);
315 }
316 }
318 function processForm(offset, form) {
319 if (form.form.ctor == "FElement")
320 {
321 processElement(form.form._0, offset.translate(form.x, -form.y));
322 }
323 }
325 processElement(currentScene, new Point(0, 0));
326 return positions;
327 }
329 function appendPositions(positions) {
330 for (var id in positions) {
331 var pos = positions[id];
332 if (tracePositions.hasOwnProperty(id)) {
333 var points = tracePositions[id];
334 if (!pos.equals(points[points.length-1])) {
335 points.push(pos);
336 }
337 }
338 else {
339 tracePositions[id] = [pos];
340 }
341 }
342 }
344 function graphicsUpdate(currentScene) {
345 if (!recordingTraces) {
346 return;
347 }
349 var ctx = tracePathCanvas.getContext('2d');
350 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
352 ctx.save();
353 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
354 appendPositions(findPositions(currentScene));
355 for (var id in tracePositions)
356 {
357 ctx.beginPath();
358 var points = tracePositions[id];
359 for (var i=0; i < points.length; i++)
360 {
361 var p = points[i];
362 if (i == 0) {
363 ctx.moveTo(p.x, p.y);
364 }
365 else {
366 ctx.lineTo(p.x, p.y);
367 }
368 }
369 ctx.lineWidth = 1;
370 ctx.strokeStyle = "#888a85";
371 ctx.stroke();
373 for (var i=0; i < points.length; i++)
374 {
375 var p = points[i];
376 ctx.beginPath();
377 ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
378 ctx.fillStyle = "#2e3436";
379 ctx.fill();
380 }
381 }
383 ctx.restore();
384 }
386 function clearTraces() {
387 tracePositions = {};
388 }
390 function stopRecording() {
391 recordingTraces = false;
392 }
394 function startRecording() {
395 recordingTraces = true;
396 }
398 return {
399 graphicsUpdate: graphicsUpdate,
400 canvas: tracePathCanvas,
401 clearTraces: clearTraces,
402 stopRecording: stopRecording,
403 startRecording: startRecording
404 }
408function executeCallbacks(callbacks, reexecute) {
409 callbacks.forEach(function(timer) {
410 if (reexecute || !timer.executed) {
411 var func = timer.func;
412 func();
413 }
414 });
417function createCanvas() {
418 var c = document.createElement('canvas');
419 c.width = window.innerWidth;
420 c.height = window.innerHeight;
421 c.style.position = "absolute";
422 c.style.top = "0";
423 c.style.left = "0";
424 c.style.pointerEvents = "none";
425 return c;
428function assert(bool, msg) {
429 if (!bool) {
430 throw "Assertion error: " + msg;
431 }
434function saveNodeValues(allNodes) {
435 var nodeValues = [];
437 allNodes.forEach(function(node) {
438 nodeValues.push({ value: node.value, id: node.id });
439 });
441 return nodeValues;
442};
445function restoreNodeValues(allNodes, nodeStates) {
446 assert(allNodes.length == nodeStates.length, "saved program state has wrong length");
447 for (var i=0; i < allNodes.length; i++) {
448 var node = allNodes[i];
449 var state = nodeStates[i];
450 assert(node.id == state.id, "the nodes moved position");
452 node.value = state.value;
453 }
456function flattenNodes(nodes) {
457 var nodesById = {};
459 function addAllToDict(node) {
460 nodesById[node.id] = node;
461 node.kids.forEach(addAllToDict);
462 }
463 nodes.forEach(addAllToDict);
465 var allNodes = Object.keys(nodesById).sort().map(function(key) {
466 return nodesById[key];
467 });
468 return allNodes;
469};
471}());