on c5602e2 help sign in
elk/runtime/Debugger.js
500 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) {
14 return {
15 make: function(runtime) {
16 var wrappedModule = debugModule(module, runtime);
17 Elm.Debugger = debuggerInit(wrappedModule, runtime, hotSwapState);
18 dispatchElmDebuggerInit();
19 return wrappedModule.debuggedModule;
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 pauseTime = 0;
45 function wrapNotify(id, v) {
46 var timestep = runtime.timer.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 pauseTime = Date.now();
117 }
119 function setContinue(position) {
120 var timerDelay = Date.now() - pauseTime;
121 runtime.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 debuggedModule = module.make(assignedPropTracker);
145 // make sure the signal graph is actually a signal & extract the visual model
146 if ( !('recv' in debuggedModule.main) ) {
147 debuggedModule.main = Elm.Signal.make(runtime).constant(debuggedModule.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 signalGraphNodes = flattenSignalGraph(wrappedRuntime.inputs);
158 var tracePath = tracePathInit(runtime, debuggedModule.main);
160 return {
161 debuggedModule: debuggedModule,
162 signalGraphNodes: signalGraphNodes,
163 initialSnapshot: snapshotSignalGraph(signalGraphNodes),
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) {
181 var currentEventIndex = 0;
183 function resetProgram() {
184 debugModule.clearAsyncCallbacks();
185 restoreSnapshot(debugModule.signalGraphNodes, debugModule.initialSnapshot);
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 currentEventIndex = debugModule.getRecordedEventsLength();
201 }
203 function continueProgram() {
204 if (debugModule.getPaused())
205 {
206 if (currentEventIndex === 0) {
207 restartProgram();
208 return;
209 }
210 resetProgram();
211 var continueIndex = currentEventIndex;
212 currentEventIndex = 0;
213 debugModule.tracePath.clearTraces();
214 debugModule.tracePath.startRecording();
215 stepTo(continueIndex);
216 debugModule.setContinue(currentEventIndex);
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 < currentEventIndex) {
231 resetProgram();
232 currentEventIndex = 0;
233 }
235 while (currentEventIndex < index) {
236 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
237 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
239 currentEventIndex += 1;
240 }
241 }
243 function getMaxSteps() {
244 return debugModule.getRecordedEventsLength();
245 }
247 function redrawGraphics() {
248 var main = debugModule.debuggedModule.main
249 for (var i = main.kids.length ; i-- ; ) {
250 main.kids[i].recv(runtime.timer.now(), true, main.id);
251 }
252 }
254 function getHotSwapState() {
255 var continueIndex = currentEventIndex;
256 if (!debugModule.getPaused()) {
257 continueIndex = getMaxSteps();
258 }
259 return {
260 recordedEvents: debugModule.copyRecordedEvents(),
261 currentEventIndex: continueIndex
262 };
263 }
265 function dispose() {
266 var parentNode = runtime.node.parentNode;
267 parentNode.removeChild(debugModule.tracePath.canvas);
268 parentNode.removeChild(runtime.node);
269 }
271 if (hotSwapState) {
272 // The problem is that we want to previous paused state. But
273 // by the time JS reaches here, the old code has been swapped out
274 // and the new modules are being generated. So we can ask the
275 // debugging console what it thinks the pause state is and go
276 // from there.
277 var paused = top.debug.paused;
278 debugModule.setPaused();
279 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
281 // draw new trace path
282 debugModule.tracePath.startRecording();
283 stepTo(getMaxSteps());
284 debugModule.tracePath.stopRecording();
286 stepTo(hotSwapState.currentEventIndex);
287 if (paused) {
288 debugModule.setPaused();
289 } else {
290 debugModule.setContinue(hotSwapState.currentEventIndex);
291 }
292 }
294 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
296 var elmDebugger = {
297 restart: restartProgram,
298 pause: pauseProgram,
299 kontinue: continueProgram,
300 getMaxSteps: getMaxSteps,
301 stepTo: stepTo,
302 getPaused: debugModule.getPaused,
303 getHotSwapState: getHotSwapState,
304 dispose: dispose,
305 allNodes: debugModule.signalGraphNodes,
306 watchTracker: debugModule.watchTracker
307 };
309 return elmDebugger;
312function Point(x, y) {
313 this.x = x;
314 this.y = y;
316 this.translate = function(x, y) {
317 return new Point(this.x + x, this.y + y);
318 }
320 this.equals = function(p) {
321 return this.x == p.x && this.y == p.y;
322 }
325function tracePathInit(runtime, signalGraphMain) {
326 var List = Elm.List.make(runtime);
327 var Signal = Elm.Signal.make(runtime);
328 var tracePathNode = A2(Signal.lift, graphicsUpdate, signalGraphMain);
329 var tracePathCanvas = createCanvas();
330 var tracePositions = {};
331 var recordingTraces = true;
333 function findPositions(currentScene) {
334 var positions = {};
335 function processElement(elem, offset) {
336 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
337 {
338 List.map(F2(processForm)(offset))(elem.element.model.forms);
339 }
340 if (elem.props.debugTracePathId)
341 {
342 positions[elem.props.debugTracePathId] = new Point(offset.x, offset.y);
343 }
344 }
346 function processForm(offset, form) {
347 if (form.form.ctor == "FElement")
348 {
349 processElement(form.form._0, offset.translate(form.x, -form.y));
350 }
351 }
353 processElement(currentScene, new Point(0, 0));
354 return positions;
355 }
357 function appendPositions(positions) {
358 for (var id in positions) {
359 var pos = positions[id];
360 if (tracePositions.hasOwnProperty(id)) {
361 var points = tracePositions[id];
362 if (!pos.equals(points[points.length-1])) {
363 points.push(pos);
364 }
365 }
366 else {
367 tracePositions[id] = [pos];
368 }
369 }
370 }
372 function graphicsUpdate(currentScene) {
373 if (!recordingTraces) {
374 return;
375 }
377 var ctx = tracePathCanvas.getContext('2d');
378 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
380 ctx.save();
381 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
382 appendPositions(findPositions(currentScene));
383 for (var id in tracePositions)
384 {
385 ctx.beginPath();
386 var points = tracePositions[id];
387 for (var i=0; i < points.length; i++)
388 {
389 var p = points[i];
390 if (i == 0) {
391 ctx.moveTo(p.x, p.y);
392 }
393 else {
394 ctx.lineTo(p.x, p.y);
395 }
396 }
397 ctx.lineWidth = 1;
398 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
399 ctx.stroke();
401 for (var i=0; i < points.length; i++)
402 {
403 var p = points[i];
404 ctx.beginPath();
405 ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
406 ctx.fillStyle = "rgba(50, 50, 50, 0.4)";
407 ctx.fill();
408 }
409 }
411 ctx.restore();
412 }
414 function clearTraces() {
415 tracePositions = {};
416 }
418 function stopRecording() {
419 recordingTraces = false;
420 }
422 function startRecording() {
423 recordingTraces = true;
424 }
426 return {
427 graphicsUpdate: graphicsUpdate,
428 canvas: tracePathCanvas,
429 clearTraces: clearTraces,
430 stopRecording: stopRecording,
431 startRecording: startRecording
432 }
436function executeCallbacks(callbacks, reexecute) {
437 callbacks.forEach(function(timer) {
438 if (reexecute || !timer.executed) {
439 var func = timer.func;
440 timer.executed = true;
441 func();
442 }
443 });
446function createCanvas() {
447 var c = document.createElement('canvas');
448 c.width = window.innerWidth;
449 c.height = window.innerHeight;
450 c.style.position = "absolute";
451 c.style.top = "0";
452 c.style.left = "0";
453 c.style.pointerEvents = "none";
454 return c;
457function assert(bool, msg) {
458 if (!bool) {
459 throw "Assertion error: " + msg;
460 }
463function snapshotSignalGraph(signalGraphNodes) {
464 var nodeValues = [];
466 signalGraphNodes.forEach(function(node) {
467 nodeValues.push({ value: node.value, id: node.id });
468 });
470 return nodeValues;
471};
474function restoreSnapshot(signalGraphNodes, snapshot) {
475 assert(signalGraphNodes.length == snapshot.length, "saved program state has wrong length");
476 for (var i=0; i < signalGraphNodes.length; i++) {
477 var node = signalGraphNodes[i];
478 var state = snapshot[i];
479 assert(node.id == state.id, "the nodes moved position");
481 node.value = state.value;
482 }
485function flattenSignalGraph(nodes) {
486 var nodesById = {};
488 function addAllToDict(node) {
489 nodesById[node.id] = node;
490 node.kids.forEach(addAllToDict);
491 }
492 nodes.forEach(addAllToDict);
494 var allNodes = Object.keys(nodesById).sort().map(function(key) {
495 return nodesById[key];
496 });
497 return allNodes;
498};
500}());