on 22e6655 help sign in
elk/runtime/Debugger.js
557 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 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 snapshotOnCheckpoint();
88 if (parent.window) {
89 parent.window.postMessage("elmNotify", window.location.origin);
90 }
91 return changed;
92 }
93 };
95 function wrapRunDelayed(func, delayMs) {
96 if (programPaused) {
97 // Don't push timers and such to the callback stack while we're paused.
98 // It causes too many callbacks to be fired during unpausing.
99 return 0;
100 }
101 var cbObj = { func:func, delayMs:delayMs, timerId:0, executed:false };
102 var timerId = setTimeout(function() {
103 cbObj.executed = true;
104 func();
105 }, delayMs);
106 cbObj.timerId = timerId;
107 asyncCallbacks.push(cbObj);
108 return timerId;
109 }
111 function recordEvent(id, v, timestep) {
112 watchTracker.pushFrame();
113 recordedEvents.push({ id:id, value:v, timestep:timestep });
114 eventCounter += 1;
115 }
117 function clearAsyncCallbacks() {
118 asyncCallbacks.forEach(function(timer) {
119 if (!timer.executed) {
120 clearTimeout(timer.timerId);
121 }
122 });
123 }
125 function clearRecordedEvents() {
126 recordedEvents = [];
127 eventCounter = 0;
128 }
130 function getRecordedEventsLength() {
131 return recordedEvents.length;
132 }
134 function getRecordedEventAt(i) {
135 return recordedEvents[i];
136 }
138 function copyRecordedEvents() {
139 return recordedEvents.slice();
140 }
142 function loadRecordedEvents(events) {
143 recordedEvents = events.slice();
144 }
146 function clearSnapshots() {
147 snapshots = [snapshotSignalGraph(signalGraphNodes)];
148 }
150 function getSnapshotAt(i) {
151 var snapshotEvent = Math.floor(i / EVENTS_PER_SAVE);
152 assert(snapshotEvent < snapshots.length && snapshotEvent >= 0,
153 "Out of bounds index: " + snapshotEvent);
154 return snapshots[snapshotEvent];
155 }
157 function snapshotOnCheckpoint() {
158 if (eventsUntilSnapshot === 1) {
159 snapshots.push(snapshotSignalGraph(signalGraphNodes));
160 eventsUntilSnapshot = EVENTS_PER_SAVE;
161 } else {
162 eventsUntilSnapshot -= 1;
163 }
164 }
166 function setPaused() {
167 programPaused = true;
168 clearAsyncCallbacks();
169 tracePath.stopRecording();
170 pauseTime = Date.now();
171 }
173 function setContinue(position) {
174 programPaused = false;
175 if (position > 0) {
176 // If we're not unpausing at the head, then we need to dump the
177 // events that are ahead of where we're continuing.
178 var lastSnapshotPosition = Math.floor(position / EVENTS_PER_SAVE);
179 eventsUntilSnapshot = EVENTS_PER_SAVE - (position % EVENTS_PER_SAVE);
180 snapshots = snapshots.slice(0, lastSnapshotPosition + 1);
182 var lastEventTime = recordedEvents[position-1].timestep;
183 var scrubTime = runtime.timer.now() - lastEventTime;
184 runtime.timer.addDelay(scrubTime);
186 recordedEvents = recordedEvents.slice(0, position);
187 tracePath.clearTracesAfter(position);
188 eventCounter = position;
189 executeCallbacks(asyncCallbacks, false);
190 }
191 tracePath.startRecording();
192 }
194 function getPaused() {
195 return programPaused;
196 }
198 return {
199 debuggedModule: debuggedModule,
200 signalGraphNodes: signalGraphNodes,
201 initialSnapshot: snapshotSignalGraph(signalGraphNodes),
202 initialAsyncCallbacks: asyncCallbacks.slice(),
203 // API functions
204 clearAsyncCallbacks: clearAsyncCallbacks,
205 clearRecordedEvents: clearRecordedEvents,
206 getRecordedEventsLength: getRecordedEventsLength,
207 getRecordedEventAt: getRecordedEventAt,
208 copyRecordedEvents: copyRecordedEvents,
209 loadRecordedEvents: loadRecordedEvents,
210 clearSnapshots: clearSnapshots,
211 getSnapshotAt: getSnapshotAt,
212 snapshotOnCheckpoint: snapshotOnCheckpoint,
213 getPaused: getPaused,
214 setPaused: setPaused,
215 setContinue: setContinue,
216 tracePath: tracePath,
217 watchTracker: watchTracker
218 };
221function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
222 var currentEventIndex = 0;
224 function resetProgram(position) {
225 var closestSnapshot = debugModule.getSnapshotAt(position);
226 debugModule.clearAsyncCallbacks();
227 restoreSnapshot(debugModule.signalGraphNodes, closestSnapshot);
228 redrawGraphics();
229 }
231 function restartProgram() {
232 pauseProgram();
233 resetProgram(0);
234 debugModule.watchTracker.clear();
235 debugModule.tracePath.clearTraces();
236 debugModule.clearRecordedEvents();
237 debugModule.clearSnapshots();
238 debugModule.setContinue(0);
239 executeCallbacks(debugModule.initialAsyncCallbacks, true);
240 }
242 function pauseProgram() {
243 debugModule.setPaused();
244 currentEventIndex = debugModule.getRecordedEventsLength();
245 }
247 function continueProgram() {
248 if (debugModule.getPaused())
249 {
250 if (currentEventIndex === 0) {
251 restartProgram();
252 return;
253 }
254 var closestSnapshotIndex =
255 Math.floor(currentEventIndex / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
256 resetProgram(currentEventIndex);
257 var continueIndex = currentEventIndex;
258 currentEventIndex = closestSnapshotIndex;
259 stepTo(continueIndex);
260 debugModule.setContinue(currentEventIndex);
261 }
262 }
264 function stepTo(index) {
265 if (!debugModule.getPaused()) {
266 debugModule.setPaused();
267 resetProgram();
268 }
270 if (index < 0 || index > getMaxSteps()) {
271 throw "Index out of bounds: " + index;
272 }
274 if (index < currentEventIndex) {
275 var closestSnapshotIndex = Math.floor(index / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
276 resetProgram(index);
277 currentEventIndex = closestSnapshotIndex;
278 }
280 while (currentEventIndex < index) {
281 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
282 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
284 currentEventIndex += 1;
285 }
286 }
288 function getMaxSteps() {
289 return debugModule.getRecordedEventsLength();
290 }
292 function redrawGraphics() {
293 var main = debugModule.debuggedModule.main
294 for (var i = main.kids.length ; i-- ; ) {
295 main.kids[i].recv(runtime.timer.now(), true, main.id);
296 }
297 }
299 function getHotSwapState() {
300 var continueIndex = currentEventIndex;
301 if (!debugModule.getPaused()) {
302 continueIndex = getMaxSteps();
303 }
304 return {
305 recordedEvents: debugModule.copyRecordedEvents(),
306 currentEventIndex: continueIndex
307 };
308 }
310 function dispose() {
311 var parentNode = runtime.node.parentNode;
312 parentNode.removeChild(debugModule.tracePath.canvas);
313 parentNode.removeChild(runtime.node);
314 }
316 if (hotSwapState) {
317 // The problem is that we want to previous paused state. But
318 // by the time JS reaches here, the old code has been swapped out
319 // and the new modules are being generated. So we can ask the
320 // debugging console what it thinks the pause state is and go
321 // from there.
322 var paused = top.debug.paused;
323 debugModule.setPaused();
324 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
325 var index = getMaxSteps();
326 eventCounter = 0;
327 debugModule.tracePath.clearTraces();
329 // draw new trace path
330 debugModule.tracePath.startRecording();
331 while(currentEventIndex < index) {
332 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
333 eventCounter += 1;
334 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
335 debugModule.snapshotOnCheckpoint();
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,
426 "We don't have a 1-1 mapping of trace positions to events");
427 }
428 }
430 function graphicsUpdate(currentScene) {
431 if (!recordingTraces) {
432 return;
433 }
435 var ctx = tracePathCanvas.getContext('2d');
436 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
438 ctx.save();
439 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
440 appendPositions(findPositions(currentScene));
441 for (var id in tracePositions)
442 {
443 ctx.beginPath();
444 var points = tracePositions[id];
445 for (var i=0; i < points.length; i++)
446 {
447 var p = points[i];
448 if (i == 0) {
449 ctx.moveTo(p.x, p.y);
450 }
451 else {
452 ctx.lineTo(p.x, p.y);
453 }
454 }
455 ctx.lineWidth = 1;
456 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
457 ctx.stroke();
458 }
460 ctx.restore();
461 }
463 function clearTraces() {
464 tracePositions = {};
465 }
467 function stopRecording() {
468 recordingTraces = false;
469 }
471 function startRecording() {
472 recordingTraces = true;
473 }
475 function clearTracesAfter(position) {
476 var newTraces = {};
477 for (var id in tracePositions) {
478 newTraces[id] = tracePositions[id].slice(0,position);
479 }
480 tracePositions = newTraces;
481 }
483 return {
484 graphicsUpdate: graphicsUpdate,
485 canvas: tracePathCanvas,
486 clearTraces: clearTraces,
487 clearTracesAfter: clearTracesAfter,
488 stopRecording: stopRecording,
489 startRecording: startRecording
490 }
493function executeCallbacks(callbacks, reexecute) {
494 callbacks.forEach(function(timer) {
495 if (reexecute || !timer.executed) {
496 var func = timer.func;
497 timer.executed = true;
498 func();
499 }
500 });
503function createCanvas() {
504 var c = document.createElement('canvas');
505 c.width = window.innerWidth;
506 c.height = window.innerHeight;
507 c.style.position = "absolute";
508 c.style.top = "0";
509 c.style.left = "0";
510 c.style.pointerEvents = "none";
511 return c;
514function assert(bool, msg) {
515 if (!bool) {
516 throw "Assertion error: " + msg;
517 }
520function snapshotSignalGraph(signalGraphNodes) {
521 var nodeValues = [];
523 signalGraphNodes.forEach(function(node) {
524 nodeValues.push({ value: node.value, id: node.id });
525 });
527 return nodeValues;
528};
530function restoreSnapshot(signalGraphNodes, snapshot) {
531 assert(signalGraphNodes.length == snapshot.length,
532 "saved program state has wrong length");
533 for (var i=0; i < signalGraphNodes.length; i++) {
534 var node = signalGraphNodes[i];
535 var state = snapshot[i];
536 assert(node.id == state.id, "the nodes moved position");
538 node.value = state.value;
539 }
542function flattenSignalGraph(nodes) {
543 var nodesById = {};
545 function addAllToDict(node) {
546 nodesById[node.id] = node;
547 node.kids.forEach(addAllToDict);
548 }
549 nodes.forEach(addAllToDict);
551 var allNodes = Object.keys(nodesById).sort().map(function(key) {
552 return nodesById[key];
553 });
554 return allNodes;
555};
557}());