on 4b40219 help sign in
elk/runtime/Debugger.js
565 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;
178 if (position > 0) {
179 // If we're not unpausing at the head, then we need to dump the
180 // events that are ahead of where we're continuing.
181 var lastSnapshotPosition = Math.floor(position / EVENTS_PER_SAVE);
182 eventsUntilSnapshot = EVENTS_PER_SAVE - (position % EVENTS_PER_SAVE);
183 snapshots = snapshots.slice(0, lastSnapshotPosition + 1);
185 var lastEventTime = recordedEvents[position-1].timestep;
186 var scrubTime = runtime.timer.now() - lastEventTime;
187 runtime.timer.addDelay(scrubTime);
189 recordedEvents = recordedEvents.slice(0, position);
190 tracePath.clearTracesAfter(position);
191 runtime.debuggerStatus.eventCounter = position;
192 executeCallbacks(asyncCallbacks, false);
193 }
194 tracePath.startRecording();
195 }
197 function getPaused() {
198 return programPaused;
199 }
201 return {
202 debuggedModule: debuggedModule,
203 signalGraphNodes: signalGraphNodes,
204 initialSnapshot: snapshotSignalGraph(signalGraphNodes),
205 initialAsyncCallbacks: asyncCallbacks.slice(),
206 // API functions
207 clearAsyncCallbacks: clearAsyncCallbacks,
208 clearRecordedEvents: clearRecordedEvents,
209 getRecordedEventsLength: getRecordedEventsLength,
210 getRecordedEventAt: getRecordedEventAt,
211 copyRecordedEvents: copyRecordedEvents,
212 loadRecordedEvents: loadRecordedEvents,
213 clearSnapshots: clearSnapshots,
214 getSnapshotAt: getSnapshotAt,
215 snapshotOnCheckpoint: snapshotOnCheckpoint,
216 getPaused: getPaused,
217 setPaused: setPaused,
218 setContinue: setContinue,
219 tracePath: tracePath,
220 watchTracker: watchTracker
221 };
224function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
225 var currentEventIndex = 0;
227 function resetProgram(position) {
228 var closestSnapshot = debugModule.getSnapshotAt(position);
229 debugModule.clearAsyncCallbacks();
230 restoreSnapshot(debugModule.signalGraphNodes, closestSnapshot);
231 redrawGraphics();
232 }
234 function restartProgram() {
235 pauseProgram();
236 resetProgram(0);
237 debugModule.watchTracker.clear();
238 debugModule.tracePath.clearTraces();
239 debugModule.clearRecordedEvents();
240 debugModule.clearSnapshots();
241 debugModule.setContinue(0);
242 executeCallbacks(debugModule.initialAsyncCallbacks, true);
243 }
245 function pauseProgram() {
246 debugModule.setPaused();
247 currentEventIndex = debugModule.getRecordedEventsLength();
248 }
250 function continueProgram() {
251 if (debugModule.getPaused())
252 {
253 if (currentEventIndex === 0) {
254 restartProgram();
255 return;
256 }
257 var closestSnapshotIndex =
258 Math.floor(currentEventIndex / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
259 resetProgram(currentEventIndex);
260 var continueIndex = currentEventIndex;
261 currentEventIndex = closestSnapshotIndex;
262 stepTo(continueIndex);
263 debugModule.setContinue(currentEventIndex);
264 }
265 }
267 function stepTo(index) {
268 if (!debugModule.getPaused()) {
269 debugModule.setPaused();
270 resetProgram();
271 }
273 if (index < 0 || index > getMaxSteps()) {
274 throw "Index out of bounds: " + index;
275 }
277 if (index < currentEventIndex) {
278 var closestSnapshotIndex = Math.floor(index / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
279 resetProgram(index);
280 currentEventIndex = closestSnapshotIndex;
281 }
283 while (currentEventIndex < index) {
284 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
285 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
287 currentEventIndex += 1;
288 }
289 }
291 function getMaxSteps() {
292 return debugModule.getRecordedEventsLength();
293 }
295 function redrawGraphics() {
296 var main = debugModule.debuggedModule.main
297 for (var i = main.kids.length ; i-- ; ) {
298 main.kids[i].recv(runtime.timer.now(), true, main.id);
299 }
300 }
302 function getHotSwapState() {
303 var continueIndex = currentEventIndex;
304 if (!debugModule.getPaused()) {
305 continueIndex = getMaxSteps();
306 }
307 return {
308 recordedEvents: debugModule.copyRecordedEvents(),
309 currentEventIndex: continueIndex
310 };
311 }
313 function dispose() {
314 var parentNode = runtime.node.parentNode;
315 parentNode.removeChild(debugModule.tracePath.canvas);
316 parentNode.removeChild(runtime.node);
317 }
319 if (hotSwapState) {
320 // The problem is that we want to previous paused state. But
321 // by the time JS reaches here, the old code has been swapped out
322 // and the new modules are being generated. So we can ask the
323 // debugging console what it thinks the pause state is and go
324 // from there.
325 var paused = top.debug.paused;
326 debugModule.setPaused();
327 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
328 var index = getMaxSteps();
329 runtime.debuggerStatus.eventCounter = 0;
330 debugModule.tracePath.clearTraces();
332 // draw new trace path
333 debugModule.tracePath.startRecording();
334 while(currentEventIndex < index) {
335 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
336 runtime.debuggerStatus.eventCounter += 1;
337 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
338 debugModule.snapshotOnCheckpoint();
339 currentEventIndex += 1;
340 }
341 debugModule.tracePath.stopRecording();
343 stepTo(hotSwapState.currentEventIndex);
344 if (!paused) {
345 debugModule.setContinue(hotSwapState.currentEventIndex);
346 }
347 }
349 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
351 var elmDebugger = {
352 restart: restartProgram,
353 pause: pauseProgram,
354 kontinue: continueProgram,
355 getMaxSteps: getMaxSteps,
356 stepTo: stepTo,
357 getPaused: debugModule.getPaused,
358 getHotSwapState: getHotSwapState,
359 dispose: dispose,
360 allNodes: debugModule.signalGraphNodes,
361 watchTracker: debugModule.watchTracker
362 };
364 return elmDebugger;
367function Point(x, y) {
368 this.x = x;
369 this.y = y;
371 this.translate = function(x, y) {
372 return new Point(this.x + x, this.y + y);
373 }
375 this.equals = function(p) {
376 return this.x == p.x && this.y == p.y;
377 }
380function tracePathInit(runtime, signalGraphMain) {
381 var List = Elm.List.make(runtime);
382 var Signal = Elm.Signal.make(runtime);
383 var tracePathNode = A2(Signal.lift, graphicsUpdate, signalGraphMain);
384 var tracePathCanvas = createCanvas();
385 var tracePositions = {};
386 var recordingTraces = true;
388 function findPositions(currentScene) {
389 var positions = {};
390 function processElement(elem, offset) {
391 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
392 {
393 List.map(F2(processForm)(offset))(elem.element.model.forms);
394 }
395 }
397 function processForm(offset, form) {
398 if (form.form.ctor == "FElement")
399 {
400 processElement(form.form._0, offset.translate(form.x, -form.y));
401 }
402 if (form.form.ctor == "FGroup")
403 {
404 var newOffset = offset.translate(form.x, -form.y);
405 List.map(F2(processForm)(newOffset))(form.form._1);
406 }
407 if (form.debugTracePathId)
408 {
409 positions[form.debugTracePathId] = new Point(form.x + offset.x, -form.y + offset.y);
410 }
411 }
413 processElement(currentScene, new Point(0, 0));
414 return positions;
415 }
417 function appendPositions(positions) {
418 for (var id in positions) {
419 var pos = positions[id];
420 if (tracePositions.hasOwnProperty(id)) {
421 tracePositions[id].push(pos);
422 }
423 else {
424 tracePositions[id] = [pos];
425 }
426 if (tracePositions[id].length < runtime.debuggerStatus.eventCounter) {
427 var padCount = runtime.debuggerStatus.eventCounter - tracePositions[id].length;
428 var lastTracePosition = tracePositions[id][tracePositions[id].length - 1];
429 for (var i = padCount; i--;) {
430 tracePositions[id].push(lastTracePosition)
431 }
432 }
433 assert(tracePositions[id].length === runtime.debuggerStatus.eventCounter,
434 "We don't have a 1-1 mapping of trace positions to events");
435 }
436 }
438 function graphicsUpdate(currentScene) {
439 if (!recordingTraces) {
440 return;
441 }
443 var ctx = tracePathCanvas.getContext('2d');
444 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
446 ctx.save();
447 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
448 appendPositions(findPositions(currentScene));
449 for (var id in tracePositions)
450 {
451 ctx.beginPath();
452 var points = tracePositions[id];
453 for (var i=0; i < points.length; i++)
454 {
455 var p = points[i];
456 if (i == 0) {
457 ctx.moveTo(p.x, p.y);
458 }
459 else {
460 ctx.lineTo(p.x, p.y);
461 }
462 }
463 ctx.lineWidth = 1;
464 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
465 ctx.stroke();
466 }
468 ctx.restore();
469 }
471 function clearTraces() {
472 tracePositions = {};
473 }
475 function stopRecording() {
476 recordingTraces = false;
477 }
479 function startRecording() {
480 recordingTraces = true;
481 }
483 function clearTracesAfter(position) {
484 var newTraces = {};
485 for (var id in tracePositions) {
486 newTraces[id] = tracePositions[id].slice(0,position);
487 }
488 tracePositions = newTraces;
489 }
491 return {
492 graphicsUpdate: graphicsUpdate,
493 canvas: tracePathCanvas,
494 clearTraces: clearTraces,
495 clearTracesAfter: clearTracesAfter,
496 stopRecording: stopRecording,
497 startRecording: startRecording
498 }
501function executeCallbacks(callbacks, reexecute) {
502 callbacks.forEach(function(timer) {
503 if (reexecute || !timer.executed) {
504 var func = timer.func;
505 timer.executed = true;
506 func();
507 }
508 });
511function createCanvas() {
512 var c = document.createElement('canvas');
513 c.width = window.innerWidth;
514 c.height = window.innerHeight;
515 c.style.position = "absolute";
516 c.style.top = "0";
517 c.style.left = "0";
518 c.style.pointerEvents = "none";
519 return c;
522function assert(bool, msg) {
523 if (!bool) {
524 throw "Assertion error: " + msg;
525 }
528function snapshotSignalGraph(signalGraphNodes) {
529 var nodeValues = [];
531 signalGraphNodes.forEach(function(node) {
532 nodeValues.push({ value: node.value, id: node.id });
533 });
535 return nodeValues;
536};
538function restoreSnapshot(signalGraphNodes, snapshot) {
539 assert(signalGraphNodes.length == snapshot.length,
540 "saved program state has wrong length");
541 for (var i=0; i < signalGraphNodes.length; i++) {
542 var node = signalGraphNodes[i];
543 var state = snapshot[i];
544 assert(node.id == state.id, "the nodes moved position");
546 node.value = state.value;
547 }
550function flattenSignalGraph(nodes) {
551 var nodesById = {};
553 function addAllToDict(node) {
554 nodesById[node.id] = node;
555 node.kids.forEach(addAllToDict);
556 }
557 nodes.forEach(addAllToDict);
559 var allNodes = Object.keys(nodesById).sort().map(function(key) {
560 return nodesById[key];
561 });
562 return allNodes;
563};
565}());