on ae7d29c help sign in
elk/runtime/Debugger.js
501 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 signalGraphMain: debugModule.debuggedModule.main
308 };
310 return elmDebugger;
313function Point(x, y) {
314 this.x = x;
315 this.y = y;
317 this.translate = function(x, y) {
318 return new Point(this.x + x, this.y + y);
319 }
321 this.equals = function(p) {
322 return this.x == p.x && this.y == p.y;
323 }
326function tracePathInit(runtime, signalGraphMain) {
327 var List = Elm.List.make(runtime);
328 var Signal = Elm.Signal.make(runtime);
329 var tracePathNode = A2(Signal.lift, graphicsUpdate, signalGraphMain);
330 var tracePathCanvas = createCanvas();
331 var tracePositions = {};
332 var recordingTraces = true;
334 function findPositions(currentScene) {
335 var positions = {};
336 function processElement(elem, offset) {
337 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
338 {
339 List.map(F2(processForm)(offset))(elem.element.model.forms);
340 }
341 if (elem.props.debugTracePathId)
342 {
343 positions[elem.props.debugTracePathId] = new Point(offset.x, offset.y);
344 }
345 }
347 function processForm(offset, form) {
348 if (form.form.ctor == "FElement")
349 {
350 processElement(form.form._0, offset.translate(form.x, -form.y));
351 }
352 }
354 processElement(currentScene, new Point(0, 0));
355 return positions;
356 }
358 function appendPositions(positions) {
359 for (var id in positions) {
360 var pos = positions[id];
361 if (tracePositions.hasOwnProperty(id)) {
362 var points = tracePositions[id];
363 if (!pos.equals(points[points.length-1])) {
364 points.push(pos);
365 }
366 }
367 else {
368 tracePositions[id] = [pos];
369 }
370 }
371 }
373 function graphicsUpdate(currentScene) {
374 if (!recordingTraces) {
375 return;
376 }
378 var ctx = tracePathCanvas.getContext('2d');
379 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
381 ctx.save();
382 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
383 appendPositions(findPositions(currentScene));
384 for (var id in tracePositions)
385 {
386 ctx.beginPath();
387 var points = tracePositions[id];
388 for (var i=0; i < points.length; i++)
389 {
390 var p = points[i];
391 if (i == 0) {
392 ctx.moveTo(p.x, p.y);
393 }
394 else {
395 ctx.lineTo(p.x, p.y);
396 }
397 }
398 ctx.lineWidth = 1;
399 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
400 ctx.stroke();
402 for (var i=0; i < points.length; i++)
403 {
404 var p = points[i];
405 ctx.beginPath();
406 ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
407 ctx.fillStyle = "rgba(50, 50, 50, 0.4)";
408 ctx.fill();
409 }
410 }
412 ctx.restore();
413 }
415 function clearTraces() {
416 tracePositions = {};
417 }
419 function stopRecording() {
420 recordingTraces = false;
421 }
423 function startRecording() {
424 recordingTraces = true;
425 }
427 return {
428 graphicsUpdate: graphicsUpdate,
429 canvas: tracePathCanvas,
430 clearTraces: clearTraces,
431 stopRecording: stopRecording,
432 startRecording: startRecording
433 }
437function executeCallbacks(callbacks, reexecute) {
438 callbacks.forEach(function(timer) {
439 if (reexecute || !timer.executed) {
440 var func = timer.func;
441 timer.executed = true;
442 func();
443 }
444 });
447function createCanvas() {
448 var c = document.createElement('canvas');
449 c.width = window.innerWidth;
450 c.height = window.innerHeight;
451 c.style.position = "absolute";
452 c.style.top = "0";
453 c.style.left = "0";
454 c.style.pointerEvents = "none";
455 return c;
458function assert(bool, msg) {
459 if (!bool) {
460 throw "Assertion error: " + msg;
461 }
464function snapshotSignalGraph(signalGraphNodes) {
465 var nodeValues = [];
467 signalGraphNodes.forEach(function(node) {
468 nodeValues.push({ value: node.value, id: node.id });
469 });
471 return nodeValues;
472};
475function restoreSnapshot(signalGraphNodes, snapshot) {
476 assert(signalGraphNodes.length == snapshot.length, "saved program state has wrong length");
477 for (var i=0; i < signalGraphNodes.length; i++) {
478 var node = signalGraphNodes[i];
479 var state = snapshot[i];
480 assert(node.id == state.id, "the nodes moved position");
482 node.value = state.value;
483 }
486function flattenSignalGraph(nodes) {
487 var nodesById = {};
489 function addAllToDict(node) {
490 nodesById[node.id] = node;
491 node.kids.forEach(addAllToDict);
492 }
493 nodes.forEach(addAllToDict);
495 var allNodes = Object.keys(nodesById).sort().map(function(key) {
496 return nodesById[key];
497 });
498 return allNodes;
499};
501}());