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