on 1cb66bf help sign in
elk/runtime/Debugger.js
555 lines 15 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;
24var eventCounter = 0;
26function dispatchElmDebuggerInit() {
27 if (parent.window) {
28 var dispatch = function() {
29 parent.window.postMessage("elmDebuggerInit", window.location.origin);
30 };
31 if (parent.window.document.readyState === "complete") {
32 dispatch();
33 }
34 else {
35 parent.window.addEventListener("load", dispatch);
36 }
37 }
40function debugModule(module, runtime) {
41 var programPaused = false;
42 var recordedEvents = [];
43 var asyncCallbacks = [];
44 var snapshots = [];
45 var watchTracker = Elm.Native.Debug.make(runtime).watchTracker;
46 var eventsUntilSnapshot = EVENTS_PER_SAVE;
48 // runtime is the prototype of wrappedRuntime
49 // so we can access all runtime properties too
50 var wrappedRuntime = Object.create(runtime);
51 wrappedRuntime.notify = wrapNotify;
52 wrappedRuntime.runDelayed = wrapRunDelayed;
54 // make a copy of the wrappedRuntime
55 var assignedPropTracker = Object.create(wrappedRuntime);
56 var debuggedModule = module.make(assignedPropTracker);
58 // make sure the signal graph is actually a signal & extract the visual model
59 if ( !('recv' in debuggedModule.main) ) {
60 debuggedModule.main = Elm.Signal.make(runtime).constant(debuggedModule.main);
61 }
63 // The main module stores imported modules onto the runtime.
64 // To ensure only one instance of each module is created,
65 // we assign them back on the original runtime object.
66 Object.keys(assignedPropTracker).forEach(function(key) {
67 runtime[key] = assignedPropTracker[key];
68 });
70 var signalGraphNodes = flattenSignalGraph(wrappedRuntime.inputs);
71 var tracePath = tracePathInit(runtime, debuggedModule.main);
73 snapshots.push(snapshotSignalGraph(signalGraphNodes));
75 function wrapNotify(id, v) {
76 var timestep = runtime.timer.now();
78 if (programPaused) {
79 // ignore async events generated while playing back
80 // or user events while program is paused
81 return false;
82 }
83 else {
84 recordEvent(id, v, timestep);
85 var changed = runtime.notify(id, v, timestep);
86 snapshotOnCheckpoint();
87 if (parent.window) {
88 parent.window.postMessage("elmNotify", window.location.origin);
89 }
90 return changed;
91 }
92 };
94 function wrapRunDelayed(func, delayMs) {
95 if (programPaused) {
96 // Don't push timers and such to the callback stack while we're paused.
97 // It causes too many callbacks to be fired during unpausing.
98 return 0;
99 }
100 var cbObj = { func:func, delayMs:delayMs, timerId:0, executed:false };
101 var timerId = setTimeout(function() {
102 cbObj.executed = true;
103 func();
104 }, delayMs);
105 cbObj.timerId = timerId;
106 asyncCallbacks.push(cbObj);
107 return timerId;
108 }
110 function recordEvent(id, v, timestep) {
111 watchTracker.pushFrame();
112 recordedEvents.push({ id:id, value:v, timestep:timestep });
113 eventCounter += 1;
114 }
116 function clearAsyncCallbacks() {
117 asyncCallbacks.forEach(function(timer) {
118 if (!timer.executed) {
119 clearTimeout(timer.timerId);
120 }
121 });
122 }
124 function clearRecordedEvents() {
125 recordedEvents = [];
126 eventCounter = 0;
127 }
129 function getRecordedEventsLength() {
130 return recordedEvents.length;
131 }
133 function getRecordedEventAt(i) {
134 return recordedEvents[i];
135 }
137 function copyRecordedEvents() {
138 return recordedEvents.slice();
139 }
141 function loadRecordedEvents(events) {
142 recordedEvents = events.slice();
143 }
145 function clearSnapshots() {
146 snapshots = [snapshotSignalGraph(signalGraphNodes)];
147 }
149 function getSnapshotAt(i) {
150 var snapshotEvent = Math.floor(i / EVENTS_PER_SAVE);
151 assert(snapshotEvent < snapshots.length && snapshotEvent >= 0,
152 "Out of bounds index: " + snapshotEvent);
153 return snapshots[snapshotEvent];
154 }
156 function snapshotOnCheckpoint() {
157 if (eventsUntilSnapshot === 1) {
158 snapshots.push(snapshotSignalGraph(signalGraphNodes));
159 eventsUntilSnapshot = EVENTS_PER_SAVE;
160 } else {
161 eventsUntilSnapshot -= 1;
162 }
163 }
165 function setPaused() {
166 programPaused = true;
167 clearAsyncCallbacks();
168 tracePath.stopRecording();
169 }
171 function setContinue(position) {
172 programPaused = false;
173 if (position > 0) {
174 // If we're not unpausing at the head, then we need to dump the
175 // events that are ahead of where we're continuing.
176 var lastSnapshotPosition = Math.floor(position / EVENTS_PER_SAVE);
177 eventsUntilSnapshot = EVENTS_PER_SAVE - (position % EVENTS_PER_SAVE);
178 snapshots = snapshots.slice(0, lastSnapshotPosition + 1);
180 var lastEventTime = recordedEvents[position-1].timestep;
181 var scrubTime = runtime.timer.now() - lastEventTime;
182 runtime.timer.addDelay(scrubTime);
184 recordedEvents = recordedEvents.slice(0, position);
185 tracePath.clearTracesAfter(position);
186 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 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 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 < eventCounter) {
417 var padCount = 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 === 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}());