on 494dfdb help sign in
elk/runtime/Debugger.js
514 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 now = 0;
45 function wrapNotify(id, v) {
46 var timestep = Date.now();
48 if (programPaused) {
49 // ignore async events generated while playing back
50 // or user events while program is paused
51 return false;
52 }
53 else {
54 var changed = runtime.notify(id, v, timestep);
55 recordEvent(id, v, timestep);
56 if (parent.window) {
57 parent.window.postMessage("elmNotify", window.location.origin);
58 }
59 return changed;
60 }
61 };
63 function wrapRunDelayed(func, delayMs) {
64 if (programPaused) {
65 // Don't push timers and such to the callback stack while we're paused.
66 // It causes too many callbacks to be fired during unpausing.
67 return 0;
68 }
69 var cbObj = { func:func, delayMs:delayMs, timerId:0, executed:false };
70 var timerId = setTimeout(function() {
71 cbObj.executed = true;
72 func();
73 }, delayMs);
74 cbObj.timerId = timerId;
75 asyncCallbacks.push(cbObj);
76 return timerId;
77 }
79 function recordEvent(id, v, timestep) {
80 watchTracker.pushFrame();
81 recordedEvents.push({ id:id, value:v, timestep:timestep });
82 }
84 function clearAsyncCallbacks() {
85 asyncCallbacks.forEach(function(timer) {
86 if (!timer.executed) {
87 clearTimeout(timer.timerId);
88 }
89 });
90 }
92 function clearRecordedEvents() {
93 recordedEvents = [];
94 }
96 function getRecordedEventsLength() {
97 return recordedEvents.length;
98 }
100 function getRecordedEventAt(i) {
101 return recordedEvents[i];
102 }
104 function copyRecordedEvents() {
105 return recordedEvents.slice();
106 }
108 function loadRecordedEvents(events) {
109 recordedEvents = events.slice();
110 }
112 function setPaused() {
113 programPaused = true;
114 clearAsyncCallbacks();
115 tracePath.stopRecording();
116 now = Date.now();
117 }
119 function setContinue(position) {
120 var timerDelay = Date.now() - now;
121 Elm.timer.addDelay(timerDelay);
122 programPaused = false;
123 if (position > 0) {
124 // If we're not unpausing at the head, then we need to dump the
125 // events that are ahead of where we're continuing.
126 recordedEvents = recordedEvents.slice(0,position);
127 executeCallbacks(asyncCallbacks, false);
128 }
129 tracePath.startRecording();
130 }
132 function getPaused() {
133 return programPaused;
134 }
136 // runtime is the prototype of wrappedRuntime
137 // so we can access all runtime properties too
138 var wrappedRuntime = Object.create(runtime);
139 wrappedRuntime.notify = wrapNotify;
140 wrappedRuntime.runDelayed = wrapRunDelayed;
142 var assignedPropTracker = Object.create(wrappedRuntime);
143 var moduleInstance = module.make(assignedPropTracker);
145 // make sure the signal graph is actually a signal & extract the visual model
146 if ( !('recv' in moduleInstance.main) ) {
147 moduleInstance.main = Elm.Signal.make(runtime).constant(moduleInstance.main);
148 }
150 // The main module stores imported modules onto the runtime.
151 // To ensure only one instance of each module is created,
152 // we assign them back on the original runtime object.
153 Object.keys(assignedPropTracker).forEach(function(key) {
154 runtime[key] = assignedPropTracker[key];
155 });
157 var moduleNodes = flattenNodes(wrappedRuntime.inputs);
158 var tracePath = tracePathInit(runtime, moduleInstance.main);
160 return {
161 moduleInstance: moduleInstance,
162 moduleNodes: moduleNodes,
163 initialNodeValues: saveNodeValues(moduleNodes),
164 initialAsyncCallbacks: asyncCallbacks.slice(),
165 // API functions
166 clearAsyncCallbacks: clearAsyncCallbacks,
167 clearRecordedEvents: clearRecordedEvents,
168 getRecordedEventsLength: getRecordedEventsLength,
169 getRecordedEventAt: getRecordedEventAt,
170 copyRecordedEvents: copyRecordedEvents,
171 loadRecordedEvents: loadRecordedEvents,
172 getPaused: getPaused,
173 setPaused: setPaused,
174 setContinue: setContinue,
175 tracePath: tracePath,
176 watchTracker: watchTracker,
177 };
180function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
181 var eventCounter = 0;
183 function resetProgram() {
184 debugModule.clearAsyncCallbacks();
185 restoreNodeValues(debugModule.moduleNodes, debugModule.initialNodeValues);
186 redrawGraphics();
187 }
189 function restartProgram() {
190 resetProgram();
191 debugModule.watchTracker.clear();
192 debugModule.tracePath.clearTraces();
193 debugModule.clearRecordedEvents();
194 debugModule.setContinue(0);
195 executeCallbacks(debugModule.initialAsyncCallbacks, true);
196 }
198 function pauseProgram() {
199 debugModule.setPaused();
200 eventCounter = debugModule.getRecordedEventsLength();
201 }
203 function continueProgram() {
204 if (debugModule.getPaused())
205 {
206 if(eventCounter === 0) {
207 restartProgram();
208 return;
209 }
210 resetProgram();
211 var index = eventCounter;
212 eventCounter = 0;
213 debugModule.tracePath.clearTraces();
214 debugModule.tracePath.startRecording();
215 stepTo(index);
216 debugModule.setContinue(eventCounter);
217 }
218 }
220 function stepTo(index) {
221 if (!debugModule.getPaused()) {
222 debugModule.setPaused();
223 resetProgram();
224 }
226 if (index < 0 || index > getMaxSteps()) {
227 throw "Index out of bounds: " + index;
228 }
230 if (index < eventCounter) {
231 resetProgram();
232 eventCounter = 0;
233 }
235 assert(index >= eventCounter, "index must be bad");
236 while (eventCounter < index) {
237 var nextEvent = debugModule.getRecordedEventAt(eventCounter);
238 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
240 eventCounter += 1;
241 }
242 assert(eventCounter == index, "while loop didn't work");
243 }
245 function getMaxSteps() {
246 return debugModule.getRecordedEventsLength();
247 }
249 function doPlayback(eventList) {
250 var x = eventList.shift();
251 var time = x[2];
252 runtime.notify(x[0], x[1], x[2]);
254 if (eventList.length > 0) {
255 var delta = eventList[0][2] - time;
256 setTimeout(function() { doPlayback(eventList); }, delta);
257 }
258 }
260 function redrawGraphics() {
261 var main = debugModule.moduleInstance.main
262 for (var i = main.kids.length ; i-- ; ) {
263 main.kids[i].recv(Date.now(), true, main.id);
264 }
265 }
267 function getHotSwapState() {
268 var counter = eventCounter;
269 if (!debugModule.getPaused()) {
270 counter = getMaxSteps();
271 }
272 return {
273 recordedEvents: debugModule.copyRecordedEvents(),
274 eventCounter: counter
275 };
276 }
278 function dispose() {
279 var parentNode = runtime.node.parentNode;
280 parentNode.removeChild(debugModule.tracePath.canvas);
281 parentNode.removeChild(runtime.node);
282 }
284 if (hotSwapState) {
285 // The problem is that we want to previous paused state. But
286 // by the time JS reaches here, the old code has been swapped out
287 // and the new modules are being generated. So we can ask the
288 // debugging console what it thinks the pause state is and go
289 // from there.
290 var paused = top.debug.paused;
291 debugModule.setPaused();
292 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
294 // draw new trace path
295 debugModule.tracePath.startRecording();
296 stepTo(getMaxSteps());
297 debugModule.tracePath.stopRecording();
299 stepTo(hotSwapState.eventCounter);
300 if (paused) {
301 debugModule.setPaused();
302 } else {
303 debugModule.setContinue(hotSwapState.eventCounter);
304 }
305 }
307 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
309 var elmDebugger = {
310 restart: restartProgram,
311 pause: pauseProgram,
312 kontinue: continueProgram,
313 getMaxSteps: getMaxSteps,
314 stepTo: stepTo,
315 getPaused: debugModule.getPaused,
316 getHotSwapState: getHotSwapState,
317 dispose: dispose,
318 allNodes: debugModule.moduleNodes,
319 watchTracker: debugModule.watchTracker,
320 mainNode: debugModule.moduleInstance.main
321 };
323 return elmDebugger;
326function Point(x, y) {
327 this.x = x;
328 this.y = y;
330 this.translate = function(x, y) {
331 return new Point(this.x + x, this.y + y);
332 }
334 this.equals = function(p) {
335 return this.x == p.x && this.y == p.y;
336 }
339function tracePathInit(runtime, mainNode) {
340 var List = Elm.List.make(runtime);
341 var Signal = Elm.Signal.make(runtime);
342 var tracePathNode = A2(Signal.lift, graphicsUpdate, mainNode);
343 var tracePathCanvas = createCanvas();
344 var tracePositions = {};
345 var recordingTraces = true;
347 function findPositions(currentScene) {
348 var positions = {};
349 function processElement(elem, offset) {
350 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
351 {
352 List.map(F2(processForm)(offset))(elem.element.model.forms);
353 }
354 if (elem.props.debugTracePathId)
355 {
356 positions[elem.props.debugTracePathId] = new Point(offset.x, offset.y);
357 }
358 }
360 function processForm(offset, form) {
361 if (form.form.ctor == "FElement")
362 {
363 processElement(form.form._0, offset.translate(form.x, -form.y));
364 }
365 }
367 processElement(currentScene, new Point(0, 0));
368 return positions;
369 }
371 function appendPositions(positions) {
372 for (var id in positions) {
373 var pos = positions[id];
374 if (tracePositions.hasOwnProperty(id)) {
375 var points = tracePositions[id];
376 if (!pos.equals(points[points.length-1])) {
377 points.push(pos);
378 }
379 }
380 else {
381 tracePositions[id] = [pos];
382 }
383 }
384 }
386 function graphicsUpdate(currentScene) {
387 if (!recordingTraces) {
388 return;
389 }
391 var ctx = tracePathCanvas.getContext('2d');
392 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
394 ctx.save();
395 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
396 appendPositions(findPositions(currentScene));
397 for (var id in tracePositions)
398 {
399 ctx.beginPath();
400 var points = tracePositions[id];
401 for (var i=0; i < points.length; i++)
402 {
403 var p = points[i];
404 if (i == 0) {
405 ctx.moveTo(p.x, p.y);
406 }
407 else {
408 ctx.lineTo(p.x, p.y);
409 }
410 }
411 ctx.lineWidth = 1;
412 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
413 ctx.stroke();
415 for (var i=0; i < points.length; i++)
416 {
417 var p = points[i];
418 ctx.beginPath();
419 ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
420 ctx.fillStyle = "rgba(50, 50, 50, 0.4)";
421 ctx.fill();
422 }
423 }
425 ctx.restore();
426 }
428 function clearTraces() {
429 tracePositions = {};
430 }
432 function stopRecording() {
433 recordingTraces = false;
434 }
436 function startRecording() {
437 recordingTraces = true;
438 }
440 return {
441 graphicsUpdate: graphicsUpdate,
442 canvas: tracePathCanvas,
443 clearTraces: clearTraces,
444 stopRecording: stopRecording,
445 startRecording: startRecording
446 }
450function executeCallbacks(callbacks, reexecute) {
451 callbacks.forEach(function(timer) {
452 if (reexecute || !timer.executed) {
453 var func = timer.func;
454 timer.executed = true;
455 func();
456 }
457 });
460function createCanvas() {
461 var c = document.createElement('canvas');
462 c.width = window.innerWidth;
463 c.height = window.innerHeight;
464 c.style.position = "absolute";
465 c.style.top = "0";
466 c.style.left = "0";
467 c.style.pointerEvents = "none";
468 return c;
471function assert(bool, msg) {
472 if (!bool) {
473 throw "Assertion error: " + msg;
474 }
477function saveNodeValues(allNodes) {
478 var nodeValues = [];
480 allNodes.forEach(function(node) {
481 nodeValues.push({ value: node.value, id: node.id });
482 });
484 return nodeValues;
485};
488function restoreNodeValues(allNodes, nodeStates) {
489 assert(allNodes.length == nodeStates.length, "saved program state has wrong length");
490 for (var i=0; i < allNodes.length; i++) {
491 var node = allNodes[i];
492 var state = nodeStates[i];
493 assert(node.id == state.id, "the nodes moved position");
495 node.value = state.value;
496 }
499function flattenNodes(nodes) {
500 var nodesById = {};
502 function addAllToDict(node) {
503 nodesById[node.id] = node;
504 node.kids.forEach(addAllToDict);
505 }
506 nodes.forEach(addAllToDict);
508 var allNodes = Object.keys(nodesById).sort().map(function(key) {
509 return nodesById[key];
510 });
511 return allNodes;
512};
514}());