on fb4e298 help sign in
elk/runtime/Debugger.js
520 lines 13 kB history raw
2(function() {
3'use strict';
5if (!window.location.origin) {
6 window.location.origin =
7 window.location.protocol + "//" +
8 window.location.hostname +
9 (window.location.port ? (':' + window.location.port) : '');
12Elm.Debugger = null;
13Elm.debuggerAttach = function(module, hotSwapState /* =undefined */) {
14 return {
15 make: function(runtime) {
16 var wrappedModule = debugModule(module, runtime);
17 Elm.Debugger = debuggerInit(wrappedModule, runtime, hotSwapState);
18 dispatchElmDebuggerInit();
19 return wrappedModule.moduleInstance;
20 }
21 };
22};
24function dispatchElmDebuggerInit() {
25 if (parent.window) {
26 var dispatch = function(_) {
27 parent.window.postMessage("elmDebuggerInit", window.location.origin);
28 };
29 if (parent.window.document.readyState === "complete") {
30 dispatch();
31 }
32 else {
33 parent.window.addEventListener("load", dispatch);
34 }
35 }
38function debugModule(module, runtime) {
39 var programPaused = false;
40 var recordedEvents = [];
41 var asyncCallbacks = [];
42 var watchTracker = Elm.Native.Debug.make(runtime).watchTracker;
43 var timerOffset = 0;
44 var now = 0;
46 function wrapNotify(id, v) {
47 var timestep = Date.now();
49 if (programPaused) {
50 // ignore async events generated while playing back
51 // or user events while program is paused
52 return false;
53 }
54 else {
55 var changed = runtime.notify(id, v, timestep);
56 recordEvent(id, v, timestep);
57 if (parent.window) {
58 parent.window.postMessage("elmNotify", window.location.origin);
59 }
60 return changed;
61 }
62 };
64 function wrapRunDelayed(func, delayMs) {
65 if (programPaused) {
66 // Don't push timers and such to the callback stack while we're paused.
67 // It causes too many callbacks to be fired during unpausing.
68 return 0;
69 }
70 var cbObj = { func:func, delayMs:delayMs, timerId:0, executed:false };
71 var timerId = setTimeout(function() {
72 cbObj.executed = true;
73 func(timerOffset);
74 }, delayMs);
75 cbObj.timerId = timerId;
76 asyncCallbacks.push(cbObj);
77 return timerId;
78 }
80 function recordEvent(id, v, timestep) {
81 watchTracker.pushFrame();
82 recordedEvents.push({ id:id, value:v, timestep:timestep });
83 }
85 function clearAsyncCallbacks() {
86 asyncCallbacks.forEach(function(timer) {
87 if (!timer.executed) {
88 clearTimeout(timer.timerId);
89 }
90 });
91 }
93 function clearRecordedEvents() {
94 recordedEvents = [];
95 }
97 function getRecordedEventsLength() {
98 return recordedEvents.length;
99 }
101 function getRecordedEventAt(i) {
102 return recordedEvents[i];
103 }
105 function copyRecordedEvents() {
106 return recordedEvents.slice();
107 }
109 function loadRecordedEvents(events) {
110 recordedEvents = events.slice();
111 }
113 function resetTimeOffset() {
114 timerOffset = 0;
115 }
117 function setPaused() {
118 programPaused = true;
119 clearAsyncCallbacks();
120 tracePath.stopRecording();
121 now = Date.now();
122 }
124 function setContinue(position) {
125 timerOffset += Date.now() - now;
126 programPaused = false;
127 if (position > 0) {
128 // If we're not unpausing at the head, then we need to dump the
129 // events that are ahead of where we're continuing.
130 recordedEvents = recordedEvents.slice(0,position);
131 executeCallbacks(asyncCallbacks, false, timerOffset);
132 }
133 tracePath.startRecording();
134 }
136 function getPaused() {
137 return programPaused;
138 }
140 // runtime is the prototype of wrappedRuntime
141 // so we can access all runtime properties too
142 var wrappedRuntime = Object.create(runtime);
143 wrappedRuntime.notify = wrapNotify;
144 wrappedRuntime.runDelayed = wrapRunDelayed;
146 var assignedPropTracker = Object.create(wrappedRuntime);
147 var moduleInstance = module.make(assignedPropTracker);
149 // make sure the signal graph is actually a signal & extract the visual model
150 if ( !('recv' in moduleInstance.main) ) {
151 moduleInstance.main = Elm.Signal.make(runtime).constant(moduleInstance.main);
152 }
154 // The main module stores imported modules onto the runtime.
155 // To ensure only one instance of each module is created,
156 // we assign them back on the original runtime object.
157 Object.keys(assignedPropTracker).forEach(function(key) {
158 runtime[key] = assignedPropTracker[key];
159 });
161 var moduleNodes = flattenNodes(wrappedRuntime.inputs);
162 var tracePath = tracePathInit(runtime, moduleInstance.main);
164 return {
165 moduleInstance: moduleInstance,
166 moduleNodes: moduleNodes,
167 initialNodeValues: saveNodeValues(moduleNodes),
168 initialAsyncCallbacks: asyncCallbacks.slice(),
169 // API functions
170 clearAsyncCallbacks: clearAsyncCallbacks,
171 clearRecordedEvents: clearRecordedEvents,
172 getRecordedEventsLength: getRecordedEventsLength,
173 getRecordedEventAt: getRecordedEventAt,
174 copyRecordedEvents: copyRecordedEvents,
175 loadRecordedEvents: loadRecordedEvents,
176 resetTimeOffset: resetTimeOffset,
177 getPaused: getPaused,
178 setPaused: setPaused,
179 setContinue: setContinue,
180 tracePath: tracePath,
181 watchTracker: watchTracker,
182 };
185function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
186 var eventCounter = 0;
188 function resetProgram() {
189 debugModule.clearAsyncCallbacks();
190 restoreNodeValues(debugModule.moduleNodes, debugModule.initialNodeValues);
191 redrawGraphics();
192 }
194 function restartProgram() {
195 resetProgram();
196 debugModule.watchTracker.clear();
197 debugModule.tracePath.clearTraces();
198 debugModule.clearRecordedEvents();
199 debugModule.setContinue(0);
200 debugModule.resetTimeOffset();
201 executeCallbacks(debugModule.initialAsyncCallbacks, true, 0);
202 }
204 function pauseProgram() {
205 debugModule.setPaused();
206 eventCounter = debugModule.getRecordedEventsLength();
207 }
209 function continueProgram() {
210 if (debugModule.getPaused())
211 {
212 if(eventCounter === 0) {
213 restartProgram();
214 return;
215 }
216 resetProgram();
217 var index = eventCounter;
218 eventCounter = 0;
219 debugModule.tracePath.clearTraces();
220 debugModule.tracePath.startRecording();
221 stepTo(index);
222 debugModule.setContinue(eventCounter);
223 }
224 }
226 function stepTo(index) {
227 if (!debugModule.getPaused()) {
228 debugModule.setPaused();
229 resetProgram();
230 }
232 if (index < 0 || index > getMaxSteps()) {
233 throw "Index out of bounds: " + index;
234 }
236 if (index < eventCounter) {
237 resetProgram();
238 eventCounter = 0;
239 }
241 assert(index >= eventCounter, "index must be bad");
242 while (eventCounter < index) {
243 var nextEvent = debugModule.getRecordedEventAt(eventCounter);
244 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
246 eventCounter += 1;
247 }
248 assert(eventCounter == index, "while loop didn't work");
249 }
251 function getMaxSteps() {
252 return debugModule.getRecordedEventsLength();
253 }
255 function doPlayback(eventList) {
256 var x = eventList.shift();
257 var time = x[2];
258 runtime.notify(x[0], x[1], x[2]);
260 if (eventList.length > 0) {
261 var delta = eventList[0][2] - time;
262 setTimeout(function() { doPlayback(eventList); }, delta);
263 }
264 }
266 function redrawGraphics() {
267 var main = debugModule.moduleInstance.main
268 for (var i = main.kids.length ; i-- ; ) {
269 main.kids[i].recv(Date.now(), true, main.id);
270 }
271 }
273 function getHotSwapState() {
274 var counter = eventCounter;
275 if (!debugModule.getPaused()) {
276 counter = getMaxSteps();
277 }
278 return {
279 recordedEvents: debugModule.copyRecordedEvents(),
280 eventCounter: counter
281 };
282 }
284 function dispose() {
285 var parentNode = runtime.node.parentNode;
286 parentNode.removeChild(debugModule.tracePath.canvas);
287 parentNode.removeChild(runtime.node);
288 }
290 if (hotSwapState) {
291 // The problem is that we want to previous paused state. But
292 // by the time JS reaches here, the old code has been swapped out
293 // and the new modules are being generated. So we can ask the
294 // debugging console what it thinks the pause state is and go
295 // from there.
296 var paused = top.debug.paused;
297 debugModule.setPaused();
298 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
300 // draw new trace path
301 debugModule.tracePath.startRecording();
302 stepTo(getMaxSteps());
303 debugModule.tracePath.stopRecording();
305 stepTo(hotSwapState.eventCounter);
306 if (paused) {
307 debugModule.setPaused();
308 } else {
309 debugModule.setContinue(hotSwapState.eventCounter);
310 }
311 }
313 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
315 var elmDebugger = {
316 restart: restartProgram,
317 pause: pauseProgram,
318 kontinue: continueProgram,
319 getMaxSteps: getMaxSteps,
320 stepTo: stepTo,
321 getPaused: debugModule.getPaused,
322 getHotSwapState: getHotSwapState,
323 dispose: dispose,
324 allNodes: debugModule.moduleNodes,
325 watchTracker: debugModule.watchTracker,
326 mainNode: debugModule.moduleInstance.main
327 };
329 return elmDebugger;
332function Point(x, y) {
333 this.x = x;
334 this.y = y;
336 this.translate = function(x, y) {
337 return new Point(this.x + x, this.y + y);
338 }
340 this.equals = function(p) {
341 return this.x == p.x && this.y == p.y;
342 }
345function tracePathInit(runtime, mainNode) {
346 var List = Elm.List.make(runtime);
347 var Signal = Elm.Signal.make(runtime);
348 var tracePathNode = A2(Signal.lift, graphicsUpdate, mainNode);
349 var tracePathCanvas = createCanvas();
350 var tracePositions = {};
351 var recordingTraces = true;
353 function findPositions(currentScene) {
354 var positions = {};
355 function processElement(elem, offset) {
356 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
357 {
358 List.map(F2(processForm)(offset))(elem.element.model.forms);
359 }
360 if (elem.props.debugTracePathId)
361 {
362 positions[elem.props.debugTracePathId] = new Point(offset.x, offset.y);
363 }
364 }
366 function processForm(offset, form) {
367 if (form.form.ctor == "FElement")
368 {
369 processElement(form.form._0, offset.translate(form.x, -form.y));
370 }
371 }
373 processElement(currentScene, new Point(0, 0));
374 return positions;
375 }
377 function appendPositions(positions) {
378 for (var id in positions) {
379 var pos = positions[id];
380 if (tracePositions.hasOwnProperty(id)) {
381 var points = tracePositions[id];
382 if (!pos.equals(points[points.length-1])) {
383 points.push(pos);
384 }
385 }
386 else {
387 tracePositions[id] = [pos];
388 }
389 }
390 }
392 function graphicsUpdate(currentScene) {
393 if (!recordingTraces) {
394 return;
395 }
397 var ctx = tracePathCanvas.getContext('2d');
398 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
400 ctx.save();
401 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
402 appendPositions(findPositions(currentScene));
403 for (var id in tracePositions)
404 {
405 ctx.beginPath();
406 var points = tracePositions[id];
407 for (var i=0; i < points.length; i++)
408 {
409 var p = points[i];
410 if (i == 0) {
411 ctx.moveTo(p.x, p.y);
412 }
413 else {
414 ctx.lineTo(p.x, p.y);
415 }
416 }
417 ctx.lineWidth = 1;
418 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
419 ctx.stroke();
421 for (var i=0; i < points.length; i++)
422 {
423 var p = points[i];
424 ctx.beginPath();
425 ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
426 ctx.fillStyle = "rgba(50, 50, 50, 0.4)";
427 ctx.fill();
428 }
429 }
431 ctx.restore();
432 }
434 function clearTraces() {
435 tracePositions = {};
436 }
438 function stopRecording() {
439 recordingTraces = false;
440 }
442 function startRecording() {
443 recordingTraces = true;
444 }
446 return {
447 graphicsUpdate: graphicsUpdate,
448 canvas: tracePathCanvas,
449 clearTraces: clearTraces,
450 stopRecording: stopRecording,
451 startRecording: startRecording
452 }
456function executeCallbacks(callbacks, reexecute, offset) {
457 callbacks.forEach(function(timer) {
458 if (reexecute || !timer.executed) {
459 var func = timer.func;
460 timer.executed = true;
461 func(offset);
462 }
463 });
466function createCanvas() {
467 var c = document.createElement('canvas');
468 c.width = window.innerWidth;
469 c.height = window.innerHeight;
470 c.style.position = "absolute";
471 c.style.top = "0";
472 c.style.left = "0";
473 c.style.pointerEvents = "none";
474 return c;
477function assert(bool, msg) {
478 if (!bool) {
479 throw "Assertion error: " + msg;
480 }
483function saveNodeValues(allNodes) {
484 var nodeValues = [];
486 allNodes.forEach(function(node) {
487 nodeValues.push({ value: node.value, id: node.id });
488 });
490 return nodeValues;
491};
494function restoreNodeValues(allNodes, nodeStates) {
495 assert(allNodes.length == nodeStates.length, "saved program state has wrong length");
496 for (var i=0; i < allNodes.length; i++) {
497 var node = allNodes[i];
498 var state = nodeStates[i];
499 assert(node.id == state.id, "the nodes moved position");
501 node.value = state.value;
502 }
505function flattenNodes(nodes) {
506 var nodesById = {};
508 function addAllToDict(node) {
509 nodesById[node.id] = node;
510 node.kids.forEach(addAllToDict);
511 }
512 nodes.forEach(addAllToDict);
514 var allNodes = Object.keys(nodesById).sort().map(function(key) {
515 return nodesById[key];
516 });
517 return allNodes;
518};
520}());