on bb9ffcf help sign in
elk/runtime/Debugger.js
555 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.DebugStatus = runtime.DebugStatus || {};
48 runtime.DebugStatus.eventCounter = runtime.DebugStatus.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.DebugStatus.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.DebugStatus.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 timerDelay = Date.now() - pauseTime;
176 runtime.timer.addDelay(timerDelay);
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);
184 recordedEvents = recordedEvents.slice(0, position);
185 tracePath.clearTracesAfter(position);
186 runtime.DebugStatus.eventCounter = position;
187 executeCallbacks(asyncCallbacks, false);
188 }
189 tracePath.startRecording();
190 }
192 function getPaused() {
193 return programPaused;
194 }
196 return {
197 debuggedModule: debuggedModule,
198 signalGraphNodes: signalGraphNodes,
199 initialSnapshot: snapshotSignalGraph(signalGraphNodes),
200 initialAsyncCallbacks: asyncCallbacks.slice(),
201 // API functions
202 clearAsyncCallbacks: clearAsyncCallbacks,
203 clearRecordedEvents: clearRecordedEvents,
204 getRecordedEventsLength: getRecordedEventsLength,
205 getRecordedEventAt: getRecordedEventAt,
206 copyRecordedEvents: copyRecordedEvents,
207 loadRecordedEvents: loadRecordedEvents,
208 clearSnapshots: clearSnapshots,
209 getSnapshotAt: getSnapshotAt,
210 snapshotOnCheckpoint: snapshotOnCheckpoint,
211 getPaused: getPaused,
212 setPaused: setPaused,
213 setContinue: setContinue,
214 tracePath: tracePath,
215 watchTracker: watchTracker
216 };
219function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
220 var currentEventIndex = 0;
222 function resetProgram(position) {
223 var closestSnapshot = debugModule.getSnapshotAt(position);
224 debugModule.clearAsyncCallbacks();
225 restoreSnapshot(debugModule.signalGraphNodes, closestSnapshot);
226 redrawGraphics();
227 }
229 function restartProgram() {
230 pauseProgram();
231 resetProgram(0);
232 debugModule.watchTracker.clear();
233 debugModule.tracePath.clearTraces();
234 debugModule.clearRecordedEvents();
235 debugModule.clearSnapshots();
236 debugModule.setContinue(0);
237 executeCallbacks(debugModule.initialAsyncCallbacks, true);
238 }
240 function pauseProgram() {
241 debugModule.setPaused();
242 currentEventIndex = debugModule.getRecordedEventsLength();
243 }
245 function continueProgram() {
246 if (debugModule.getPaused())
247 {
248 if (currentEventIndex === 0) {
249 restartProgram();
250 return;
251 }
252 var closestSnapshotIndex =
253 Math.floor(currentEventIndex / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
254 resetProgram(currentEventIndex);
255 var continueIndex = currentEventIndex;
256 currentEventIndex = closestSnapshotIndex;
257 stepTo(continueIndex);
258 debugModule.setContinue(currentEventIndex);
259 }
260 }
262 function stepTo(index) {
263 if (!debugModule.getPaused()) {
264 debugModule.setPaused();
265 resetProgram();
266 }
268 if (index < 0 || index > getMaxSteps()) {
269 throw "Index out of bounds: " + index;
270 }
272 if (index < currentEventIndex) {
273 var closestSnapshotIndex = Math.floor(index / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
274 resetProgram(index);
275 currentEventIndex = closestSnapshotIndex;
276 }
278 while (currentEventIndex < index) {
279 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
280 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
282 currentEventIndex += 1;
283 }
284 }
286 function getMaxSteps() {
287 return debugModule.getRecordedEventsLength();
288 }
290 function redrawGraphics() {
291 var main = debugModule.debuggedModule.main
292 for (var i = main.kids.length ; i-- ; ) {
293 main.kids[i].recv(runtime.timer.now(), true, main.id);
294 }
295 }
297 function getHotSwapState() {
298 var continueIndex = currentEventIndex;
299 if (!debugModule.getPaused()) {
300 continueIndex = getMaxSteps();
301 }
302 return {
303 recordedEvents: debugModule.copyRecordedEvents(),
304 currentEventIndex: continueIndex
305 };
306 }
308 function dispose() {
309 var parentNode = runtime.node.parentNode;
310 parentNode.removeChild(debugModule.tracePath.canvas);
311 parentNode.removeChild(runtime.node);
312 }
314 if (hotSwapState) {
315 // The problem is that we want to previous paused state. But
316 // by the time JS reaches here, the old code has been swapped out
317 // and the new modules are being generated. So we can ask the
318 // debugging console what it thinks the pause state is and go
319 // from there.
320 var paused = top.debug.paused;
321 debugModule.setPaused();
322 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
323 var index = getMaxSteps();
324 runtime.DebugStatus.eventCounter = 0;
325 debugModule.tracePath.clearTraces();
327 // draw new trace path
328 debugModule.tracePath.startRecording();
329 while(currentEventIndex < index) {
330 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
331 runtime.DebugStatus.eventCounter += 1;
332 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
333 debugModule.snapshotOnCheckpoint();
334 currentEventIndex += 1;
335 }
336 debugModule.tracePath.stopRecording();
338 stepTo(hotSwapState.currentEventIndex);
339 if (!paused) {
340 debugModule.setContinue(hotSwapState.currentEventIndex);
341 }
342 }
344 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
346 var elmDebugger = {
347 restart: restartProgram,
348 pause: pauseProgram,
349 kontinue: continueProgram,
350 getMaxSteps: getMaxSteps,
351 stepTo: stepTo,
352 getPaused: debugModule.getPaused,
353 getHotSwapState: getHotSwapState,
354 dispose: dispose,
355 allNodes: debugModule.signalGraphNodes,
356 watchTracker: debugModule.watchTracker
357 };
359 return elmDebugger;
362function Point(x, y) {
363 this.x = x;
364 this.y = y;
366 this.translate = function(x, y) {
367 return new Point(this.x + x, this.y + y);
368 }
370 this.equals = function(p) {
371 return this.x == p.x && this.y == p.y;
372 }
375function tracePathInit(runtime, signalGraphMain) {
376 var List = Elm.List.make(runtime);
377 var Signal = Elm.Signal.make(runtime);
378 var tracePathNode = A2(Signal.lift, graphicsUpdate, signalGraphMain);
379 var tracePathCanvas = createCanvas();
380 var tracePositions = {};
381 var recordingTraces = true;
383 function findPositions(currentScene) {
384 var positions = {};
385 function processElement(elem, offset) {
386 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
387 {
388 List.map(F2(processForm)(offset))(elem.element.model.forms);
389 }
390 if (elem.props.debugTracePathId)
391 {
392 positions[elem.props.debugTracePathId] = new Point(offset.x, offset.y);
393 }
394 }
396 function processForm(offset, form) {
397 if (form.form.ctor == "FElement")
398 {
399 processElement(form.form._0, offset.translate(form.x, -form.y));
400 }
401 }
403 processElement(currentScene, new Point(0, 0));
404 return positions;
405 }
407 function appendPositions(positions) {
408 for (var id in positions) {
409 var pos = positions[id];
410 if (tracePositions.hasOwnProperty(id)) {
411 tracePositions[id].push(pos);
412 }
413 else {
414 tracePositions[id] = [pos];
415 }
416 if (tracePositions[id].length < runtime.DebugStatus.eventCounter) {
417 var padCount = runtime.DebugStatus.eventCounter - tracePositions[id].length;
418 var lastTracePosition = tracePositions[id][tracePositions[id].length - 1];
419 for (var i = padCount; i--;) {
420 tracePositions[id].push(lastTracePosition)
421 }
422 }
423 assert(tracePositions[id].length === runtime.DebugStatus.eventCounter,
424 "We don't have a 1-1 mapping of trace positions to events");
425 }
426 }
428 function graphicsUpdate(currentScene) {
429 if (!recordingTraces) {
430 return;
431 }
433 var ctx = tracePathCanvas.getContext('2d');
434 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
436 ctx.save();
437 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
438 appendPositions(findPositions(currentScene));
439 for (var id in tracePositions)
440 {
441 ctx.beginPath();
442 var points = tracePositions[id];
443 for (var i=0; i < points.length; i++)
444 {
445 var p = points[i];
446 if (i == 0) {
447 ctx.moveTo(p.x, p.y);
448 }
449 else {
450 ctx.lineTo(p.x, p.y);
451 }
452 }
453 ctx.lineWidth = 1;
454 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
455 ctx.stroke();
456 }
458 ctx.restore();
459 }
461 function clearTraces() {
462 tracePositions = {};
463 }
465 function stopRecording() {
466 recordingTraces = false;
467 }
469 function startRecording() {
470 recordingTraces = true;
471 }
473 function clearTracesAfter(position) {
474 var newTraces = {};
475 for (var id in tracePositions) {
476 newTraces[id] = tracePositions[id].slice(0,position);
477 }
478 tracePositions = newTraces;
479 }
481 return {
482 graphicsUpdate: graphicsUpdate,
483 canvas: tracePathCanvas,
484 clearTraces: clearTraces,
485 clearTracesAfter: clearTracesAfter,
486 stopRecording: stopRecording,
487 startRecording: startRecording
488 }
491function executeCallbacks(callbacks, reexecute) {
492 callbacks.forEach(function(timer) {
493 if (reexecute || !timer.executed) {
494 var func = timer.func;
495 timer.executed = true;
496 func();
497 }
498 });
501function createCanvas() {
502 var c = document.createElement('canvas');
503 c.width = window.innerWidth;
504 c.height = window.innerHeight;
505 c.style.position = "absolute";
506 c.style.top = "0";
507 c.style.left = "0";
508 c.style.pointerEvents = "none";
509 return c;
512function assert(bool, msg) {
513 if (!bool) {
514 throw "Assertion error: " + msg;
515 }
518function snapshotSignalGraph(signalGraphNodes) {
519 var nodeValues = [];
521 signalGraphNodes.forEach(function(node) {
522 nodeValues.push({ value: node.value, id: node.id });
523 });
525 return nodeValues;
526};
528function restoreSnapshot(signalGraphNodes, snapshot) {
529 assert(signalGraphNodes.length == snapshot.length,
530 "saved program state has wrong length");
531 for (var i=0; i < signalGraphNodes.length; i++) {
532 var node = signalGraphNodes[i];
533 var state = snapshot[i];
534 assert(node.id == state.id, "the nodes moved position");
536 node.value = state.value;
537 }
540function flattenSignalGraph(nodes) {
541 var nodesById = {};
543 function addAllToDict(node) {
544 nodesById[node.id] = node;
545 node.kids.forEach(addAllToDict);
546 }
547 nodes.forEach(addAllToDict);
549 var allNodes = Object.keys(nodesById).sort().map(function(key) {
550 return nodesById[key];
551 });
552 return allNodes;
553};
555}());