on 0d1c2ab help sign in
elk/runtime/Debugger.js
566 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 > 0) {
185 var lastEventTime = recordedEvents[position-1].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 if (currentEventIndex === 0) {
255 restartProgram();
256 return;
257 }
258 var closestSnapshotIndex =
259 Math.floor(currentEventIndex / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
260 resetProgram(currentEventIndex);
261 var continueIndex = currentEventIndex;
262 currentEventIndex = closestSnapshotIndex;
263 stepTo(continueIndex);
264 debugModule.setContinue(currentEventIndex);
265 }
266 }
268 function stepTo(index) {
269 if (!debugModule.getPaused()) {
270 debugModule.setPaused();
271 resetProgram();
272 }
274 if (index < 0 || index > getMaxSteps()) {
275 throw "Index out of bounds: " + index;
276 }
278 if (index < currentEventIndex) {
279 var closestSnapshotIndex = Math.floor(index / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
280 resetProgram(index);
281 currentEventIndex = closestSnapshotIndex;
282 }
284 while (currentEventIndex < index) {
285 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
286 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
288 currentEventIndex += 1;
289 }
290 }
292 function getMaxSteps() {
293 return debugModule.getRecordedEventsLength();
294 }
296 function redrawGraphics() {
297 var main = debugModule.debuggedModule.main
298 for (var i = main.kids.length ; i-- ; ) {
299 main.kids[i].recv(runtime.timer.now(), true, main.id);
300 }
301 }
303 function getHotSwapState() {
304 var continueIndex = currentEventIndex;
305 if (!debugModule.getPaused()) {
306 continueIndex = getMaxSteps();
307 }
308 return {
309 recordedEvents: debugModule.copyRecordedEvents(),
310 currentEventIndex: continueIndex
311 };
312 }
314 function dispose() {
315 var parentNode = runtime.node.parentNode;
316 parentNode.removeChild(debugModule.tracePath.canvas);
317 parentNode.removeChild(runtime.node);
318 }
320 if (hotSwapState) {
321 // The problem is that we want to previous paused state. But
322 // by the time JS reaches here, the old code has been swapped out
323 // and the new modules are being generated. So we can ask the
324 // debugging console what it thinks the pause state is and go
325 // from there.
326 var paused = top.debug.paused;
327 debugModule.setPaused();
328 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
329 var index = getMaxSteps();
330 runtime.debuggerStatus.eventCounter = 0;
331 debugModule.tracePath.clearTraces();
333 // draw new trace path
334 debugModule.tracePath.startRecording();
335 while(currentEventIndex < index) {
336 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
337 runtime.debuggerStatus.eventCounter += 1;
338 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
339 debugModule.snapshotOnCheckpoint();
340 currentEventIndex += 1;
341 }
342 debugModule.tracePath.stopRecording();
344 stepTo(hotSwapState.currentEventIndex);
345 if (!paused) {
346 debugModule.setContinue(hotSwapState.currentEventIndex);
347 }
348 }
350 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
352 var elmDebugger = {
353 restart: restartProgram,
354 pause: pauseProgram,
355 kontinue: continueProgram,
356 getMaxSteps: getMaxSteps,
357 stepTo: stepTo,
358 getPaused: debugModule.getPaused,
359 getHotSwapState: getHotSwapState,
360 dispose: dispose,
361 allNodes: debugModule.signalGraphNodes,
362 watchTracker: debugModule.watchTracker
363 };
365 return elmDebugger;
368function Point(x, y) {
369 this.x = x;
370 this.y = y;
372 this.translate = function(x, y) {
373 return new Point(this.x + x, this.y + y);
374 }
376 this.equals = function(p) {
377 return this.x == p.x && this.y == p.y;
378 }
381function tracePathInit(runtime, signalGraphMain) {
382 var List = Elm.List.make(runtime);
383 var Signal = Elm.Signal.make(runtime);
384 var tracePathNode = A2(Signal.lift, graphicsUpdate, signalGraphMain);
385 var tracePathCanvas = createCanvas();
386 var tracePositions = {};
387 var recordingTraces = true;
389 function findPositions(currentScene) {
390 var positions = {};
391 function processElement(elem, offset) {
392 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
393 {
394 List.map(F2(processForm)(offset))(elem.element.model.forms);
395 }
396 }
398 function processForm(offset, form) {
399 if (form.form.ctor == "FElement")
400 {
401 processElement(form.form._0, offset.translate(form.x, -form.y));
402 }
403 if (form.form.ctor == "FGroup")
404 {
405 var newOffset = offset.translate(form.x, -form.y);
406 List.map(F2(processForm)(newOffset))(form.form._1);
407 }
408 if (form.debugTracePathId)
409 {
410 positions[form.debugTracePathId] = new Point(form.x + offset.x, -form.y + offset.y);
411 }
412 }
414 processElement(currentScene, new Point(0, 0));
415 return positions;
416 }
418 function appendPositions(positions) {
419 for (var id in positions) {
420 var pos = positions[id];
421 if (tracePositions.hasOwnProperty(id)) {
422 tracePositions[id].push(pos);
423 }
424 else {
425 tracePositions[id] = [pos];
426 }
427 if (tracePositions[id].length < runtime.debuggerStatus.eventCounter) {
428 var padCount = runtime.debuggerStatus.eventCounter - tracePositions[id].length;
429 var lastTracePosition = tracePositions[id][tracePositions[id].length - 1];
430 for (var i = padCount; i--;) {
431 tracePositions[id].push(lastTracePosition)
432 }
433 }
434 assert(tracePositions[id].length === runtime.debuggerStatus.eventCounter,
435 "We don't have a 1-1 mapping of trace positions to events");
436 }
437 }
439 function graphicsUpdate(currentScene) {
440 if (!recordingTraces) {
441 return;
442 }
444 var ctx = tracePathCanvas.getContext('2d');
445 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
447 ctx.save();
448 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
449 appendPositions(findPositions(currentScene));
450 for (var id in tracePositions)
451 {
452 ctx.beginPath();
453 var points = tracePositions[id];
454 for (var i=0; i < points.length; i++)
455 {
456 var p = points[i];
457 if (i == 0) {
458 ctx.moveTo(p.x, p.y);
459 }
460 else {
461 ctx.lineTo(p.x, p.y);
462 }
463 }
464 ctx.lineWidth = 1;
465 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
466 ctx.stroke();
467 }
469 ctx.restore();
470 }
472 function clearTraces() {
473 tracePositions = {};
474 }
476 function stopRecording() {
477 recordingTraces = false;
478 }
480 function startRecording() {
481 recordingTraces = true;
482 }
484 function clearTracesAfter(position) {
485 var newTraces = {};
486 for (var id in tracePositions) {
487 newTraces[id] = tracePositions[id].slice(0,position);
488 }
489 tracePositions = newTraces;
490 }
492 return {
493 graphicsUpdate: graphicsUpdate,
494 canvas: tracePathCanvas,
495 clearTraces: clearTraces,
496 clearTracesAfter: clearTracesAfter,
497 stopRecording: stopRecording,
498 startRecording: startRecording
499 }
502function executeCallbacks(callbacks, reexecute) {
503 callbacks.forEach(function(timer) {
504 if (reexecute || !timer.executed) {
505 var func = timer.func;
506 timer.executed = true;
507 func();
508 }
509 });
512function createCanvas() {
513 var c = document.createElement('canvas');
514 c.width = window.innerWidth;
515 c.height = window.innerHeight;
516 c.style.position = "absolute";
517 c.style.top = "0";
518 c.style.left = "0";
519 c.style.pointerEvents = "none";
520 return c;
523function assert(bool, msg) {
524 if (!bool) {
525 throw "Assertion error: " + msg;
526 }
529function snapshotSignalGraph(signalGraphNodes) {
530 var nodeValues = [];
532 signalGraphNodes.forEach(function(node) {
533 nodeValues.push({ value: node.value, id: node.id });
534 });
536 return nodeValues;
537};
539function restoreSnapshot(signalGraphNodes, snapshot) {
540 assert(signalGraphNodes.length == snapshot.length,
541 "saved program state has wrong length");
542 for (var i=0; i < signalGraphNodes.length; i++) {
543 var node = signalGraphNodes[i];
544 var state = snapshot[i];
545 assert(node.id == state.id, "the nodes moved position");
547 node.value = state.value;
548 }
551function flattenSignalGraph(nodes) {
552 var nodesById = {};
554 function addAllToDict(node) {
555 nodesById[node.id] = node;
556 node.kids.forEach(addAllToDict);
557 }
558 nodes.forEach(addAllToDict);
560 var allNodes = Object.keys(nodesById).sort().map(function(key) {
561 return nodesById[key];
562 });
563 return allNodes;
564};
566}());