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