on b241e45 help sign in
elk/runtime/Debugger.js
564 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;
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 pauseTime = 0;
47 var eventsUntilSnapshot = EVENTS_PER_SAVE;
49 // runtime is the prototype of wrappedRuntime
50 // so we can access all runtime properties too
51 var wrappedRuntime = Object.create(runtime);
52 wrappedRuntime.notify = wrapNotify;
53 wrappedRuntime.runDelayed = wrapRunDelayed;
55 // make a copy of the wrappedRuntime
56 var assignedPropTracker = Object.create(wrappedRuntime);
57 var debuggedModule = module.make(assignedPropTracker);
59 // make sure the signal graph is actually a signal & extract the visual model
60 if ( !('recv' in debuggedModule.main) ) {
61 debuggedModule.main = Elm.Signal.make(runtime).constant(debuggedModule.main);
62 }
64 // The main module stores imported modules onto the runtime.
65 // To ensure only one instance of each module is created,
66 // we assign them back on the original runtime object.
67 Object.keys(assignedPropTracker).forEach(function(key) {
68 runtime[key] = assignedPropTracker[key];
69 });
71 var signalGraphNodes = flattenSignalGraph(wrappedRuntime.inputs);
72 var tracePath = tracePathInit(runtime, debuggedModule.main);
74 snapshots.push(snapshotSignalGraph(signalGraphNodes));
76 function wrapNotify(id, v) {
77 var timestep = runtime.timer.now();
79 if (programPaused) {
80 // ignore async events generated while playing back
81 // or user events while program is paused
82 return false;
83 }
84 else {
85 recordEvent(id, v, timestep);
86 var changed = runtime.notify(id, v, timestep);
87 if (eventsUntilSnapshot === 1) {
88 saveSnapshot();
89 eventsUntilSnapshot = EVENTS_PER_SAVE;
90 } else {
91 eventsUntilSnapshot -= 1;
92 }
93 if (parent.window) {
94 parent.window.postMessage("elmNotify", window.location.origin);
95 }
96 return changed;
97 }
98 };
100 function wrapRunDelayed(func, delayMs) {
101 if (programPaused) {
102 // Don't push timers and such to the callback stack while we're paused.
103 // It causes too many callbacks to be fired during unpausing.
104 return 0;
105 }
106 var cbObj = { func:func, delayMs:delayMs, timerId:0, executed:false };
107 var timerId = setTimeout(function() {
108 cbObj.executed = true;
109 func();
110 }, delayMs);
111 cbObj.timerId = timerId;
112 asyncCallbacks.push(cbObj);
113 return timerId;
114 }
116 function recordEvent(id, v, timestep) {
117 watchTracker.pushFrame();
118 recordedEvents.push({ id:id, value:v, timestep:timestep });
119 eventCounter += 1;
120 }
122 function clearAsyncCallbacks() {
123 asyncCallbacks.forEach(function(timer) {
124 if (!timer.executed) {
125 clearTimeout(timer.timerId);
126 }
127 });
128 }
130 function clearRecordedEvents() {
131 recordedEvents = [];
132 eventCounter = 0;
133 }
135 function getRecordedEventsLength() {
136 return recordedEvents.length;
137 }
139 function getRecordedEventAt(i) {
140 return recordedEvents[i];
141 }
143 function copyRecordedEvents() {
144 return recordedEvents.slice();
145 }
147 function loadRecordedEvents(events) {
148 recordedEvents = events.slice();
149 }
151 function clearSnapshots() {
152 snapshots = [snapshotSignalGraph(signalGraphNodes)];
153 }
155 function getSnapshotAt(i) {
156 var snapshotEvent = Math.floor(i / EVENTS_PER_SAVE);
157 assert(snapshotEvent < snapshots.length && snapshotEvent >= 0, "Out of bounds index: " + snapshotEvent);
158 return snapshots[snapshotEvent];
159 }
161 function saveSnapshot() {
162 snapshots.push(snapshotSignalGraph(signalGraphNodes));
163 }
165 function setPaused() {
166 programPaused = true;
167 clearAsyncCallbacks();
168 tracePath.stopRecording();
169 pauseTime = Date.now();
170 }
172 function setContinue(position) {
173 var timerDelay = Date.now() - pauseTime;
174 runtime.timer.addDelay(timerDelay);
175 programPaused = false;
176 if (position > 0) {
177 // If we're not unpausing at the head, then we need to dump the
178 // events that are ahead of where we're continuing.
179 var lastSnapshotPosition = Math.ceil(position / EVENTS_PER_SAVE);
180 eventsUntilSnapshot = EVENTS_PER_SAVE - (position % EVENTS_PER_SAVE);
181 snapshots = snapshots.slice(0, lastSnapshotPosition);
182 recordedEvents = recordedEvents.slice(0, position);
183 tracePath.clearTracesAfter(position);
184 eventCounter = position;
185 executeCallbacks(asyncCallbacks, false);
186 }
187 tracePath.startRecording();
188 }
190 function getPaused() {
191 return programPaused;
192 }
194 return {
195 debuggedModule: debuggedModule,
196 signalGraphNodes: signalGraphNodes,
197 initialSnapshot: snapshotSignalGraph(signalGraphNodes),
198 initialAsyncCallbacks: asyncCallbacks.slice(),
199 // API functions
200 clearAsyncCallbacks: clearAsyncCallbacks,
201 clearRecordedEvents: clearRecordedEvents,
202 getRecordedEventsLength: getRecordedEventsLength,
203 getRecordedEventAt: getRecordedEventAt,
204 copyRecordedEvents: copyRecordedEvents,
205 loadRecordedEvents: loadRecordedEvents,
206 clearSnapshots: clearSnapshots,
207 getSnapshotAt: getSnapshotAt,
208 saveSnapshot: saveSnapshot,
209 getPaused: getPaused,
210 setPaused: setPaused,
211 setContinue: setContinue,
212 tracePath: tracePath,
213 watchTracker: watchTracker
214 };
217function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
218 var currentEventIndex = 0;
220 function resetProgram(position) {
221 var closestSnapshot = debugModule.getSnapshotAt(position);
222 debugModule.clearAsyncCallbacks();
223 restoreSnapshot(debugModule.signalGraphNodes, closestSnapshot);
224 redrawGraphics();
225 }
227 function restartProgram() {
228 resetProgram(0);
229 debugModule.watchTracker.clear();
230 debugModule.tracePath.clearTraces();
231 debugModule.clearRecordedEvents();
232 debugModule.clearSnapshots();
233 debugModule.setContinue(0);
234 executeCallbacks(debugModule.initialAsyncCallbacks, true);
235 }
237 function pauseProgram() {
238 debugModule.setPaused();
239 currentEventIndex = debugModule.getRecordedEventsLength();
240 }
242 function continueProgram() {
243 if (debugModule.getPaused())
244 {
245 if (currentEventIndex === 0) {
246 restartProgram();
247 return;
248 }
249 var closestSnapshotIndex = Math.floor(currentEventIndex / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
250 resetProgram(currentEventIndex);
251 var continueIndex = currentEventIndex;
252 currentEventIndex = closestSnapshotIndex;
253 stepTo(continueIndex);
254 debugModule.setContinue(currentEventIndex);
255 }
256 }
258 function stepTo(index) {
259 if (!debugModule.getPaused()) {
260 debugModule.setPaused();
261 resetProgram();
262 }
264 if (index < 0 || index > getMaxSteps()) {
265 throw "Index out of bounds: " + index;
266 }
268 if (index < currentEventIndex) {
269 var closestSnapshotIndex = Math.floor(index / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
270 resetProgram(index);
271 currentEventIndex = closestSnapshotIndex;
272 }
274 while (currentEventIndex < index) {
275 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
276 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
278 currentEventIndex += 1;
279 }
280 }
282 function getMaxSteps() {
283 return debugModule.getRecordedEventsLength();
284 }
286 function redrawGraphics() {
287 var main = debugModule.debuggedModule.main
288 for (var i = main.kids.length ; i-- ; ) {
289 main.kids[i].recv(runtime.timer.now(), true, main.id);
290 }
291 }
293 function getHotSwapState() {
294 var continueIndex = currentEventIndex;
295 if (!debugModule.getPaused()) {
296 continueIndex = getMaxSteps();
297 }
298 return {
299 recordedEvents: debugModule.copyRecordedEvents(),
300 currentEventIndex: continueIndex
301 };
302 }
304 function dispose() {
305 var parentNode = runtime.node.parentNode;
306 parentNode.removeChild(debugModule.tracePath.canvas);
307 parentNode.removeChild(runtime.node);
308 }
310 if (hotSwapState) {
311 // The problem is that we want to previous paused state. But
312 // by the time JS reaches here, the old code has been swapped out
313 // and the new modules are being generated. So we can ask the
314 // debugging console what it thinks the pause state is and go
315 // from there.
316 var paused = top.debug.paused;
317 debugModule.setPaused();
318 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
319 var index = getMaxSteps();
320 var eventsUntilSnapshot = EVENTS_PER_SAVE;
321 eventCounter = 0;
322 debugModule.tracePath.clearTraces();
324 // draw new trace path
325 debugModule.tracePath.startRecording();
326 while(currentEventIndex < index) {
327 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
328 eventCounter += 1;
329 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
330 if (eventsUntilSnapshot === 1) {
331 debugModule.saveSnapshot();
332 eventsUntilSnapshot = EVENTS_PER_SAVE;
333 } else {
334 eventsUntilSnapshot -= 1;
335 }
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 if (elem.props.debugTracePathId)
393 {
394 positions[elem.props.debugTracePathId] = new Point(offset.x, offset.y);
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 }
405 processElement(currentScene, new Point(0, 0));
406 return positions;
407 }
409 function appendPositions(positions) {
410 for (var id in positions) {
411 var pos = positions[id];
412 if (tracePositions.hasOwnProperty(id)) {
413 tracePositions[id].push(pos);
414 }
415 else {
416 tracePositions[id] = [pos];
417 }
418 if (tracePositions[id].length < eventCounter) {
419 var padCount = eventCounter - tracePositions[id].length;
420 var lastTracePosition = tracePositions[id][tracePositions[id].length - 1];
421 for (var i = padCount; i--;) {
422 tracePositions[id].push(lastTracePosition)
423 }
424 }
425 assert(tracePositions[id].length === eventCounter, "We don't have a 1-1 mapping of trace positions to events")
426 }
427 }
429 function graphicsUpdate(currentScene) {
430 if (!recordingTraces) {
431 return;
432 }
434 var ctx = tracePathCanvas.getContext('2d');
435 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
437 ctx.save();
438 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
439 appendPositions(findPositions(currentScene));
440 for (var id in tracePositions)
441 {
442 ctx.beginPath();
443 var points = tracePositions[id];
444 for (var i=0; i < points.length; i++)
445 {
446 var p = points[i];
447 if (i == 0) {
448 ctx.moveTo(p.x, p.y);
449 }
450 else {
451 ctx.lineTo(p.x, p.y);
452 }
453 }
454 ctx.lineWidth = 1;
455 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
456 ctx.stroke();
458 for (var i=0; i < points.length; i++)
459 {
460 var p = points[i];
461 ctx.beginPath();
462 ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
463 ctx.fillStyle = "rgba(50, 50, 50, 0.4)";
464 ctx.fill();
465 }
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, "saved program state has wrong length");
540 for (var i=0; i < signalGraphNodes.length; i++) {
541 var node = signalGraphNodes[i];
542 var state = snapshot[i];
543 assert(node.id == state.id, "the nodes moved position");
545 node.value = state.value;
546 }
549function flattenSignalGraph(nodes) {
550 var nodesById = {};
552 function addAllToDict(node) {
553 nodesById[node.id] = node;
554 node.kids.forEach(addAllToDict);
555 }
556 nodes.forEach(addAllToDict);
558 var allNodes = Object.keys(nodesById).sort().map(function(key) {
559 return nodesById[key];
560 });
561 return allNodes;
562};
564}());