on e3df4ad help sign in
elk/runtime/Debugger.js
562 lines 16 kB history raw
1(function() {
2'use strict';
4if (!window.location.origin) {
5 window.location.origin =
6 window.location.protocol + "//" +
7 window.location.hostname +
8 (window.location.port ? (':' + window.location.port) : '');
9}
11Elm.Debugger = null;
12Elm.debuggerAttach = function(module, hotSwapState /* =undefined */) {
13 return {
14 make: function(runtime) {
15 var wrappedModule = debugModule(module, runtime);
16 Elm.Debugger = debuggerInit(wrappedModule, runtime, hotSwapState);
17 dispatchElmDebuggerInit();
18 return wrappedModule.debuggedModule;
19 }
20 };
21};
23var EVENTS_PER_SAVE = 100;
25function dispatchElmDebuggerInit() {
26 if (parent.window) {
27 var dispatch = function() {
28 parent.window.postMessage("elmDebuggerInit", window.location.origin);
29 };
30 if (parent.window.document.readyState === "complete") {
31 dispatch();
32 }
33 else {
34 parent.window.addEventListener("load", dispatch);
35 }
36 }
39function debugModule(module, runtime) {
40 var programPaused = false;
41 var recordedEvents = [];
42 var asyncCallbacks = [];
43 var snapshots = [];
44 var watchTracker = Elm.Native.Debug.make(runtime).watchTracker;
45 var pauseTime = 0;
46 var eventsUntilSnapshot = EVENTS_PER_SAVE;
47 runtime.debuggerStatus = runtime.debuggerStatus || {};
48 runtime.debuggerStatus.eventCounter = runtime.debuggerStatus.eventCounter || 0;
50 // runtime is the prototype of wrappedRuntime
51 // so we can access all runtime properties too
52 var wrappedRuntime = Object.create(runtime);
53 wrappedRuntime.notify = wrapNotify;
54 wrappedRuntime.runDelayed = wrapRunDelayed;
56 // make a copy of the wrappedRuntime
57 var assignedPropTracker = Object.create(wrappedRuntime);
58 var debuggedModule = module.make(assignedPropTracker);
60 // make sure the signal graph is actually a signal & extract the visual model
61 if ( !('recv' in debuggedModule.main) ) {
62 debuggedModule.main = Elm.Signal.make(runtime).constant(debuggedModule.main);
63 }
65 // The main module stores imported modules onto the runtime.
66 // To ensure only one instance of each module is created,
67 // we assign them back on the original runtime object.
68 Object.keys(assignedPropTracker).forEach(function(key) {
69 runtime[key] = assignedPropTracker[key];
70 });
72 var signalGraphNodes = flattenSignalGraph(wrappedRuntime.inputs);
73 var tracePath = tracePathInit(runtime, debuggedModule.main);
75 snapshots.push(snapshotSignalGraph(signalGraphNodes));
77 function wrapNotify(id, v) {
78 var timestep = runtime.timer.now();
80 if (programPaused) {
81 // ignore async events generated while playing back
82 // or user events while program is paused
83 return false;
84 }
85 else {
86 recordEvent(id, v, timestep);
87 var changed = runtime.notify(id, v, timestep);
88 snapshotOnCheckpoint();
89 if (parent.window) {
90 parent.window.postMessage("elmNotify", window.location.origin);
91 }
92 return changed;
93 }
94 };
96 function wrapRunDelayed(func, delayMs) {
97 if (programPaused) {
98 // Don't push timers and such to the callback stack while we're paused.
99 // It causes too many callbacks to be fired during unpausing.
100 return 0;
101 }
102 var cbObj = { func:func, delayMs:delayMs, timerId:0, executed:false };
103 var timerId = setTimeout(function() {
104 cbObj.executed = true;
105 func();
106 }, delayMs);
107 cbObj.timerId = timerId;
108 asyncCallbacks.push(cbObj);
109 return timerId;
110 }
112 function recordEvent(id, v, timestep) {
113 watchTracker.pushFrame();
114 recordedEvents.push({ id:id, value:v, timestep:timestep });
115 runtime.debuggerStatus.eventCounter += 1;
116 }
118 function clearAsyncCallbacks() {
119 asyncCallbacks.forEach(function(timer) {
120 if (!timer.executed) {
121 clearTimeout(timer.timerId);
122 }
123 });
124 }
126 function clearRecordedEvents() {
127 recordedEvents = [];
128 runtime.debuggerStatus.eventCounter = 0;
129 }
131 function getRecordedEventsLength() {
132 return recordedEvents.length;
133 }
135 function getRecordedEventAt(i) {
136 return recordedEvents[i];
137 }
139 function copyRecordedEvents() {
140 return recordedEvents.slice();
141 }
143 function loadRecordedEvents(events) {
144 recordedEvents = events.slice();
145 }
147 function clearSnapshots() {
148 snapshots = [snapshotSignalGraph(signalGraphNodes)];
149 }
151 function getSnapshotAt(i) {
152 var snapshotEvent = Math.floor(i / EVENTS_PER_SAVE);
153 assert(snapshotEvent < snapshots.length && snapshotEvent >= 0,
154 "Out of bounds index: " + snapshotEvent);
155 return snapshots[snapshotEvent];
156 }
158 function snapshotOnCheckpoint() {
159 if (eventsUntilSnapshot === 1) {
160 snapshots.push(snapshotSignalGraph(signalGraphNodes));
161 eventsUntilSnapshot = EVENTS_PER_SAVE;
162 } else {
163 eventsUntilSnapshot -= 1;
164 }
165 }
167 function setPaused() {
168 programPaused = true;
169 clearAsyncCallbacks();
170 tracePath.stopRecording();
171 pauseTime = Date.now();
172 }
174 function setContinue(position) {
175 var pauseDelay = Date.now() - pauseTime;
176 runtime.timer.addDelay(pauseDelay);
177 programPaused = false;
179 // we need to dump the events that are ahead of where we're continuing.
180 var lastSnapshotPosition = Math.floor(position / EVENTS_PER_SAVE);
181 eventsUntilSnapshot = EVENTS_PER_SAVE - (position % EVENTS_PER_SAVE);
182 snapshots = snapshots.slice(0, lastSnapshotPosition + 1);
184 if (position < getRecordedEventsLength()) {
185 var lastEventTime = recordedEvents[position].timestep;
186 var scrubTime = runtime.timer.now() - lastEventTime;
187 runtime.timer.addDelay(scrubTime);
188 }
190 recordedEvents = recordedEvents.slice(0, position);
191 tracePath.clearTracesAfter(position);
192 runtime.debuggerStatus.eventCounter = position;
193 executeCallbacks(asyncCallbacks, false);
195 tracePath.startRecording();
196 }
198 function getPaused() {
199 return programPaused;
200 }
202 return {
203 debuggedModule: debuggedModule,
204 signalGraphNodes: signalGraphNodes,
205 initialSnapshot: snapshotSignalGraph(signalGraphNodes),
206 initialAsyncCallbacks: asyncCallbacks.slice(),
207 // API functions
208 clearAsyncCallbacks: clearAsyncCallbacks,
209 clearRecordedEvents: clearRecordedEvents,
210 getRecordedEventsLength: getRecordedEventsLength,
211 getRecordedEventAt: getRecordedEventAt,
212 copyRecordedEvents: copyRecordedEvents,
213 loadRecordedEvents: loadRecordedEvents,
214 clearSnapshots: clearSnapshots,
215 getSnapshotAt: getSnapshotAt,
216 snapshotOnCheckpoint: snapshotOnCheckpoint,
217 getPaused: getPaused,
218 setPaused: setPaused,
219 setContinue: setContinue,
220 tracePath: tracePath,
221 watchTracker: watchTracker
222 };
225function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
226 var currentEventIndex = 0;
228 function resetProgram(position) {
229 var closestSnapshot = debugModule.getSnapshotAt(position);
230 debugModule.clearAsyncCallbacks();
231 restoreSnapshot(debugModule.signalGraphNodes, closestSnapshot);
232 redrawGraphics();
233 }
235 function restartProgram() {
236 pauseProgram();
237 resetProgram(0);
238 debugModule.watchTracker.clear();
239 debugModule.tracePath.clearTraces();
240 debugModule.clearRecordedEvents();
241 debugModule.clearSnapshots();
242 debugModule.setContinue(0);
243 executeCallbacks(debugModule.initialAsyncCallbacks, true);
244 }
246 function pauseProgram() {
247 debugModule.setPaused();
248 currentEventIndex = debugModule.getRecordedEventsLength();
249 }
251 function continueProgram() {
252 if (debugModule.getPaused())
253 {
254 var closestSnapshotIndex =
255 Math.floor(currentEventIndex / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
256 resetProgram(currentEventIndex);
257 var continueIndex = currentEventIndex;
258 currentEventIndex = closestSnapshotIndex;
259 stepTo(continueIndex);
260 debugModule.setContinue(currentEventIndex);
261 }
262 }
264 function stepTo(index) {
265 if (!debugModule.getPaused()) {
266 debugModule.setPaused();
267 resetProgram();
268 }
270 if (index < 0 || index > getMaxSteps()) {
271 throw "Index out of bounds: " + index;
272 }
274 if (index < currentEventIndex) {
275 var closestSnapshotIndex = Math.floor(index / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
276 resetProgram(index);
277 currentEventIndex = closestSnapshotIndex;
278 }
280 while (currentEventIndex < index) {
281 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
282 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
284 currentEventIndex += 1;
285 }
286 }
288 function getMaxSteps() {
289 return debugModule.getRecordedEventsLength();
290 }
292 function redrawGraphics() {
293 var main = debugModule.debuggedModule.main
294 for (var i = main.kids.length ; i-- ; ) {
295 main.kids[i].recv(runtime.timer.now(), true, main.id);
296 }
297 }
299 function getHotSwapState() {
300 var continueIndex = currentEventIndex;
301 if (!debugModule.getPaused()) {
302 continueIndex = getMaxSteps();
303 }
304 return {
305 recordedEvents: debugModule.copyRecordedEvents(),
306 currentEventIndex: continueIndex
307 };
308 }
310 function dispose() {
311 var parentNode = runtime.node.parentNode;
312 parentNode.removeChild(debugModule.tracePath.canvas);
313 parentNode.removeChild(runtime.node);
314 }
316 if (hotSwapState) {
317 // The problem is that we want to previous paused state. But
318 // by the time JS reaches here, the old code has been swapped out
319 // and the new modules are being generated. So we can ask the
320 // debugging console what it thinks the pause state is and go
321 // from there.
322 var paused = top.debug.paused;
323 debugModule.setPaused();
324 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
325 var index = getMaxSteps();
326 runtime.debuggerStatus.eventCounter = 0;
327 debugModule.tracePath.clearTraces();
329 // draw new trace path
330 debugModule.tracePath.startRecording();
331 while(currentEventIndex < index) {
332 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
333 runtime.debuggerStatus.eventCounter += 1;
334 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
335 debugModule.snapshotOnCheckpoint();
336 currentEventIndex += 1;
337 }
338 debugModule.tracePath.stopRecording();
340 stepTo(hotSwapState.currentEventIndex);
341 if (!paused) {
342 debugModule.setContinue(hotSwapState.currentEventIndex);
343 }
344 }
346 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
348 var elmDebugger = {
349 restart: restartProgram,
350 pause: pauseProgram,
351 kontinue: continueProgram,
352 getMaxSteps: getMaxSteps,
353 stepTo: stepTo,
354 getPaused: debugModule.getPaused,
355 getHotSwapState: getHotSwapState,
356 dispose: dispose,
357 allNodes: debugModule.signalGraphNodes,
358 watchTracker: debugModule.watchTracker
359 };
361 return elmDebugger;
364function Point(x, y) {
365 this.x = x;
366 this.y = y;
368 this.translate = function(x, y) {
369 return new Point(this.x + x, this.y + y);
370 }
372 this.equals = function(p) {
373 return this.x == p.x && this.y == p.y;
374 }
377function tracePathInit(runtime, signalGraphMain) {
378 var List = Elm.List.make(runtime);
379 var Signal = Elm.Signal.make(runtime);
380 var tracePathNode = A2(Signal.lift, graphicsUpdate, signalGraphMain);
381 var tracePathCanvas = createCanvas();
382 var tracePositions = {};
383 var recordingTraces = true;
385 function findPositions(currentScene) {
386 var positions = {};
387 function processElement(elem, offset) {
388 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
389 {
390 List.map(F2(processForm)(offset))(elem.element.model.forms);
391 }
392 }
394 function processForm(offset, form) {
395 if (form.form.ctor == "FElement")
396 {
397 processElement(form.form._0, offset.translate(form.x, -form.y));
398 }
399 if (form.form.ctor == "FGroup")
400 {
401 var newOffset = offset.translate(form.x, -form.y);
402 List.map(F2(processForm)(newOffset))(form.form._1);
403 }
404 if (form.debugTracePathId)
405 {
406 positions[form.debugTracePathId] = new Point(form.x + offset.x, -form.y + offset.y);
407 }
408 }
410 processElement(currentScene, new Point(0, 0));
411 return positions;
412 }
414 function appendPositions(positions) {
415 for (var id in positions) {
416 var pos = positions[id];
417 if (tracePositions.hasOwnProperty(id)) {
418 tracePositions[id].push(pos);
419 }
420 else {
421 tracePositions[id] = [pos];
422 }
423 if (tracePositions[id].length < runtime.debuggerStatus.eventCounter) {
424 var padCount = runtime.debuggerStatus.eventCounter - tracePositions[id].length;
425 var lastTracePosition = tracePositions[id][tracePositions[id].length - 1];
426 for (var i = padCount; i--;) {
427 tracePositions[id].push(lastTracePosition)
428 }
429 }
430 assert(tracePositions[id].length === runtime.debuggerStatus.eventCounter,
431 "We don't have a 1-1 mapping of trace positions to events");
432 }
433 }
435 function graphicsUpdate(currentScene) {
436 if (!recordingTraces) {
437 return;
438 }
440 var ctx = tracePathCanvas.getContext('2d');
441 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
443 ctx.save();
444 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
445 appendPositions(findPositions(currentScene));
446 for (var id in tracePositions)
447 {
448 ctx.beginPath();
449 var points = tracePositions[id];
450 for (var i=0; i < points.length; i++)
451 {
452 var p = points[i];
453 if (i == 0) {
454 ctx.moveTo(p.x, p.y);
455 }
456 else {
457 ctx.lineTo(p.x, p.y);
458 }
459 }
460 ctx.lineWidth = 1;
461 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
462 ctx.stroke();
463 }
465 ctx.restore();
466 }
468 function clearTraces() {
469 tracePositions = {};
470 }
472 function stopRecording() {
473 recordingTraces = false;
474 }
476 function startRecording() {
477 recordingTraces = true;
478 }
480 function clearTracesAfter(position) {
481 var newTraces = {};
482 for (var id in tracePositions) {
483 newTraces[id] = tracePositions[id].slice(0,position);
484 }
485 tracePositions = newTraces;
486 }
488 return {
489 graphicsUpdate: graphicsUpdate,
490 canvas: tracePathCanvas,
491 clearTraces: clearTraces,
492 clearTracesAfter: clearTracesAfter,
493 stopRecording: stopRecording,
494 startRecording: startRecording
495 }
498function executeCallbacks(callbacks, reexecute) {
499 callbacks.forEach(function(timer) {
500 if (reexecute || !timer.executed) {
501 var func = timer.func;
502 timer.executed = true;
503 func();
504 }
505 });
508function createCanvas() {
509 var c = document.createElement('canvas');
510 c.width = window.innerWidth;
511 c.height = window.innerHeight;
512 c.style.position = "absolute";
513 c.style.top = "0";
514 c.style.left = "0";
515 c.style.pointerEvents = "none";
516 return c;
519function assert(bool, msg) {
520 if (!bool) {
521 throw "Assertion error: " + msg;
522 }
525function snapshotSignalGraph(signalGraphNodes) {
526 var nodeValues = [];
528 signalGraphNodes.forEach(function(node) {
529 nodeValues.push({ value: node.value, id: node.id });
530 });
532 return nodeValues;
533};
535function restoreSnapshot(signalGraphNodes, snapshot) {
536 assert(signalGraphNodes.length == snapshot.length,
537 "saved program state has wrong length");
538 for (var i=0; i < signalGraphNodes.length; i++) {
539 var node = signalGraphNodes[i];
540 var state = snapshot[i];
541 assert(node.id == state.id, "the nodes moved position");
543 node.value = state.value;
544 }
547function flattenSignalGraph(nodes) {
548 var nodesById = {};
550 function addAllToDict(node) {
551 nodesById[node.id] = node;
552 node.kids.forEach(addAllToDict);
553 }
554 nodes.forEach(addAllToDict);
556 var allNodes = Object.keys(nodesById).sort().map(function(key) {
557 return nodesById[key];
558 });
559 return allNodes;
560};
562}());