on 0a1ccbb 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 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 pauseDelay = Date.now() - pauseTime;
175 runtime.timer.addDelay(pauseDelay);
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 var scrubTime = runtime.timer.now() - lastEventTime;
186 runtime.timer.addDelay(scrubTime);
188 recordedEvents = recordedEvents.slice(0, position);
189 tracePath.clearTracesAfter(position);
190 eventCounter = position;
191 executeCallbacks(asyncCallbacks, false);
192 }
193 tracePath.startRecording();
194 }
196 function getPaused() {
197 return programPaused;
198 }
200 return {
201 debuggedModule: debuggedModule,
202 signalGraphNodes: signalGraphNodes,
203 initialSnapshot: snapshotSignalGraph(signalGraphNodes),
204 initialAsyncCallbacks: asyncCallbacks.slice(),
205 // API functions
206 clearAsyncCallbacks: clearAsyncCallbacks,
207 clearRecordedEvents: clearRecordedEvents,
208 getRecordedEventsLength: getRecordedEventsLength,
209 getRecordedEventAt: getRecordedEventAt,
210 copyRecordedEvents: copyRecordedEvents,
211 loadRecordedEvents: loadRecordedEvents,
212 clearSnapshots: clearSnapshots,
213 getSnapshotAt: getSnapshotAt,
214 snapshotOnCheckpoint: snapshotOnCheckpoint,
215 getPaused: getPaused,
216 setPaused: setPaused,
217 setContinue: setContinue,
218 tracePath: tracePath,
219 watchTracker: watchTracker
220 };
223function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
224 var currentEventIndex = 0;
226 function resetProgram(position) {
227 var closestSnapshot = debugModule.getSnapshotAt(position);
228 debugModule.clearAsyncCallbacks();
229 restoreSnapshot(debugModule.signalGraphNodes, closestSnapshot);
230 redrawGraphics();
231 }
233 function restartProgram() {
234 pauseProgram();
235 resetProgram(0);
236 debugModule.watchTracker.clear();
237 debugModule.tracePath.clearTraces();
238 debugModule.clearRecordedEvents();
239 debugModule.clearSnapshots();
240 debugModule.setContinue(0);
241 executeCallbacks(debugModule.initialAsyncCallbacks, true);
242 }
244 function pauseProgram() {
245 debugModule.setPaused();
246 currentEventIndex = debugModule.getRecordedEventsLength();
247 }
249 function continueProgram() {
250 if (debugModule.getPaused())
251 {
252 if (currentEventIndex === 0) {
253 restartProgram();
254 return;
255 }
256 var closestSnapshotIndex =
257 Math.floor(currentEventIndex / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
258 resetProgram(currentEventIndex);
259 var continueIndex = currentEventIndex;
260 currentEventIndex = closestSnapshotIndex;
261 stepTo(continueIndex);
262 debugModule.setContinue(currentEventIndex);
263 }
264 }
266 function stepTo(index) {
267 if (!debugModule.getPaused()) {
268 debugModule.setPaused();
269 resetProgram();
270 }
272 if (index < 0 || index > getMaxSteps()) {
273 throw "Index out of bounds: " + index;
274 }
276 if (index < currentEventIndex) {
277 var closestSnapshotIndex = Math.floor(index / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
278 resetProgram(index);
279 currentEventIndex = closestSnapshotIndex;
280 }
282 while (currentEventIndex < index) {
283 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
284 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
286 currentEventIndex += 1;
287 }
288 }
290 function getMaxSteps() {
291 return debugModule.getRecordedEventsLength();
292 }
294 function redrawGraphics() {
295 var main = debugModule.debuggedModule.main
296 for (var i = main.kids.length ; i-- ; ) {
297 main.kids[i].recv(runtime.timer.now(), true, main.id);
298 }
299 }
301 function getHotSwapState() {
302 var continueIndex = currentEventIndex;
303 if (!debugModule.getPaused()) {
304 continueIndex = getMaxSteps();
305 }
306 return {
307 recordedEvents: debugModule.copyRecordedEvents(),
308 currentEventIndex: continueIndex
309 };
310 }
312 function dispose() {
313 var parentNode = runtime.node.parentNode;
314 parentNode.removeChild(debugModule.tracePath.canvas);
315 parentNode.removeChild(runtime.node);
316 }
318 if (hotSwapState) {
319 // The problem is that we want to previous paused state. But
320 // by the time JS reaches here, the old code has been swapped out
321 // and the new modules are being generated. So we can ask the
322 // debugging console what it thinks the pause state is and go
323 // from there.
324 var paused = top.debug.paused;
325 debugModule.setPaused();
326 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
327 var index = getMaxSteps();
328 eventCounter = 0;
329 debugModule.tracePath.clearTraces();
331 // draw new trace path
332 debugModule.tracePath.startRecording();
333 while(currentEventIndex < index) {
334 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
335 eventCounter += 1;
336 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
337 debugModule.snapshotOnCheckpoint();
338 currentEventIndex += 1;
339 }
340 debugModule.tracePath.stopRecording();
342 stepTo(hotSwapState.currentEventIndex);
343 if (!paused) {
344 debugModule.setContinue(hotSwapState.currentEventIndex);
345 }
346 }
348 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
350 var elmDebugger = {
351 restart: restartProgram,
352 pause: pauseProgram,
353 kontinue: continueProgram,
354 getMaxSteps: getMaxSteps,
355 stepTo: stepTo,
356 getPaused: debugModule.getPaused,
357 getHotSwapState: getHotSwapState,
358 dispose: dispose,
359 allNodes: debugModule.signalGraphNodes,
360 watchTracker: debugModule.watchTracker
361 };
363 return elmDebugger;
366function Point(x, y) {
367 this.x = x;
368 this.y = y;
370 this.translate = function(x, y) {
371 return new Point(this.x + x, this.y + y);
372 }
374 this.equals = function(p) {
375 return this.x == p.x && this.y == p.y;
376 }
379function tracePathInit(runtime, signalGraphMain) {
380 var List = Elm.List.make(runtime);
381 var Signal = Elm.Signal.make(runtime);
382 var tracePathNode = A2(Signal.lift, graphicsUpdate, signalGraphMain);
383 var tracePathCanvas = createCanvas();
384 var tracePositions = {};
385 var recordingTraces = true;
387 function findPositions(currentScene) {
388 var positions = {};
389 function processElement(elem, offset) {
390 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
391 {
392 List.map(F2(processForm)(offset))(elem.element.model.forms);
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 if (form.form.ctor == "FGroup")
402 {
403 var newOffset = offset.translate(form.x, -form.y);
404 List.map(F2(processForm)(newOffset))(form.form._1);
405 }
406 if (form.debugTracePathId)
407 {
408 positions[form.debugTracePathId] = new Point(form.x + offset.x, -form.y + offset.y);
409 }
410 }
412 processElement(currentScene, new Point(0, 0));
413 return positions;
414 }
416 function appendPositions(positions) {
417 for (var id in positions) {
418 var pos = positions[id];
419 if (tracePositions.hasOwnProperty(id)) {
420 tracePositions[id].push(pos);
421 }
422 else {
423 tracePositions[id] = [pos];
424 }
425 if (tracePositions[id].length < eventCounter) {
426 var padCount = eventCounter - tracePositions[id].length;
427 var lastTracePosition = tracePositions[id][tracePositions[id].length - 1];
428 for (var i = padCount; i--;) {
429 tracePositions[id].push(lastTracePosition)
430 }
431 }
432 assert(tracePositions[id].length === eventCounter,
433 "We don't have a 1-1 mapping of trace positions to events");
434 }
435 }
437 function graphicsUpdate(currentScene) {
438 if (!recordingTraces) {
439 return;
440 }
442 var ctx = tracePathCanvas.getContext('2d');
443 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
445 ctx.save();
446 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
447 appendPositions(findPositions(currentScene));
448 for (var id in tracePositions)
449 {
450 ctx.beginPath();
451 var points = tracePositions[id];
452 for (var i=0; i < points.length; i++)
453 {
454 var p = points[i];
455 if (i == 0) {
456 ctx.moveTo(p.x, p.y);
457 }
458 else {
459 ctx.lineTo(p.x, p.y);
460 }
461 }
462 ctx.lineWidth = 1;
463 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
464 ctx.stroke();
465 }
467 ctx.restore();
468 }
470 function clearTraces() {
471 tracePositions = {};
472 }
474 function stopRecording() {
475 recordingTraces = false;
476 }
478 function startRecording() {
479 recordingTraces = true;
480 }
482 function clearTracesAfter(position) {
483 var newTraces = {};
484 for (var id in tracePositions) {
485 newTraces[id] = tracePositions[id].slice(0,position);
486 }
487 tracePositions = newTraces;
488 }
490 return {
491 graphicsUpdate: graphicsUpdate,
492 canvas: tracePathCanvas,
493 clearTraces: clearTraces,
494 clearTracesAfter: clearTracesAfter,
495 stopRecording: stopRecording,
496 startRecording: startRecording
497 }
500function executeCallbacks(callbacks, reexecute) {
501 callbacks.forEach(function(timer) {
502 if (reexecute || !timer.executed) {
503 var func = timer.func;
504 timer.executed = true;
505 func();
506 }
507 });
510function createCanvas() {
511 var c = document.createElement('canvas');
512 c.width = window.innerWidth;
513 c.height = window.innerHeight;
514 c.style.position = "absolute";
515 c.style.top = "0";
516 c.style.left = "0";
517 c.style.pointerEvents = "none";
518 return c;
521function assert(bool, msg) {
522 if (!bool) {
523 throw "Assertion error: " + msg;
524 }
527function snapshotSignalGraph(signalGraphNodes) {
528 var nodeValues = [];
530 signalGraphNodes.forEach(function(node) {
531 nodeValues.push({ value: node.value, id: node.id });
532 });
534 return nodeValues;
535};
537function restoreSnapshot(signalGraphNodes, snapshot) {
538 assert(signalGraphNodes.length == snapshot.length,
539 "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}());