on 8e44dcb help sign in
elk/runtime/Debugger.js
496 lines 13 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) {
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};
23function dispatchElmDebuggerInit() {
24 if (parent.window) {
25 var dispatch = function() {
26 parent.window.postMessage("elmDebuggerInit", window.location.origin);
27 };
28 if (parent.window.document.readyState === "complete") {
29 dispatch();
30 }
31 else {
32 parent.window.addEventListener("load", dispatch);
33 }
34 }
37function debugModule(module, runtime) {
38 var programPaused = false;
39 var recordedEvents = [];
40 var asyncCallbacks = [];
41 var watchTracker = Elm.Native.Debug.make(runtime).watchTracker;
42 var pauseTime = 0;
44 // runtime is the prototype of wrappedRuntime
45 // so we can access all runtime properties too
46 var wrappedRuntime = Object.create(runtime);
47 wrappedRuntime.notify = wrapNotify;
48 wrappedRuntime.runDelayed = wrapRunDelayed;
50 // make a copy of the wrappedRuntime
51 var assignedPropTracker = Object.create(wrappedRuntime);
52 var debuggedModule = module.make(assignedPropTracker);
54 // make sure the signal graph is actually a signal & extract the visual model
55 if ( !('recv' in debuggedModule.main) ) {
56 debuggedModule.main = Elm.Signal.make(runtime).constant(debuggedModule.main);
57 }
59 // The main module stores imported modules onto the runtime.
60 // To ensure only one instance of each module is created,
61 // we assign them back on the original runtime object.
62 Object.keys(assignedPropTracker).forEach(function(key) {
63 runtime[key] = assignedPropTracker[key];
64 });
66 var signalGraphNodes = flattenSignalGraph(wrappedRuntime.inputs);
67 var tracePath = tracePathInit(runtime, debuggedModule.main);
69 function wrapNotify(id, v) {
70 var timestep = runtime.timer.now();
72 if (programPaused) {
73 // ignore async events generated while playing back
74 // or user events while program is paused
75 return false;
76 }
77 else {
78 var changed = runtime.notify(id, v, timestep);
79 recordEvent(id, v, timestep);
80 if (parent.window) {
81 parent.window.postMessage("elmNotify", window.location.origin);
82 }
83 return changed;
84 }
85 };
87 function wrapRunDelayed(func, delayMs) {
88 if (programPaused) {
89 // Don't push timers and such to the callback stack while we're paused.
90 // It causes too many callbacks to be fired during unpausing.
91 return 0;
92 }
93 var cbObj = { func:func, delayMs:delayMs, timerId:0, executed:false };
94 var timerId = setTimeout(function() {
95 cbObj.executed = true;
96 func();
97 }, delayMs);
98 cbObj.timerId = timerId;
99 asyncCallbacks.push(cbObj);
100 return timerId;
101 }
103 function recordEvent(id, v, timestep) {
104 watchTracker.pushFrame();
105 recordedEvents.push({ id:id, value:v, timestep:timestep });
106 }
108 function clearAsyncCallbacks() {
109 asyncCallbacks.forEach(function(timer) {
110 if (!timer.executed) {
111 clearTimeout(timer.timerId);
112 }
113 });
114 }
116 function clearRecordedEvents() {
117 recordedEvents = [];
118 }
120 function getRecordedEventsLength() {
121 return recordedEvents.length;
122 }
124 function getRecordedEventAt(i) {
125 return recordedEvents[i];
126 }
128 function copyRecordedEvents() {
129 return recordedEvents.slice();
130 }
132 function loadRecordedEvents(events) {
133 recordedEvents = events.slice();
134 }
136 function setPaused() {
137 programPaused = true;
138 clearAsyncCallbacks();
139 tracePath.stopRecording();
140 pauseTime = Date.now();
141 }
143 function setContinue(position) {
144 var timerDelay = Date.now() - pauseTime;
145 runtime.timer.addDelay(timerDelay);
146 programPaused = false;
147 if (position > 0) {
148 // If we're not unpausing at the head, then we need to dump the
149 // events that are ahead of where we're continuing.
150 recordedEvents = recordedEvents.slice(0, position);
151 executeCallbacks(asyncCallbacks, false);
152 }
153 tracePath.startRecording();
154 }
156 function getPaused() {
157 return programPaused;
158 }
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.setContinue(hotSwapState.currentEventIndex);
289 }
290 }
292 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
294 var elmDebugger = {
295 restart: restartProgram,
296 pause: pauseProgram,
297 kontinue: continueProgram,
298 getMaxSteps: getMaxSteps,
299 stepTo: stepTo,
300 getPaused: debugModule.getPaused,
301 getHotSwapState: getHotSwapState,
302 dispose: dispose,
303 allNodes: debugModule.signalGraphNodes,
304 watchTracker: debugModule.watchTracker
305 };
307 return elmDebugger;
310function Point(x, y) {
311 this.x = x;
312 this.y = y;
314 this.translate = function(x, y) {
315 return new Point(this.x + x, this.y + y);
316 }
318 this.equals = function(p) {
319 return this.x == p.x && this.y == p.y;
320 }
323function tracePathInit(runtime, signalGraphMain) {
324 var List = Elm.List.make(runtime);
325 var Signal = Elm.Signal.make(runtime);
326 var tracePathNode = A2(Signal.lift, graphicsUpdate, signalGraphMain);
327 var tracePathCanvas = createCanvas();
328 var tracePositions = {};
329 var recordingTraces = true;
331 function findPositions(currentScene) {
332 var positions = {};
333 function processElement(elem, offset) {
334 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
335 {
336 List.map(F2(processForm)(offset))(elem.element.model.forms);
337 }
338 if (elem.props.debugTracePathId)
339 {
340 positions[elem.props.debugTracePathId] = new Point(offset.x, offset.y);
341 }
342 }
344 function processForm(offset, form) {
345 if (form.form.ctor == "FElement")
346 {
347 processElement(form.form._0, offset.translate(form.x, -form.y));
348 }
349 }
351 processElement(currentScene, new Point(0, 0));
352 return positions;
353 }
355 function appendPositions(positions) {
356 for (var id in positions) {
357 var pos = positions[id];
358 if (tracePositions.hasOwnProperty(id)) {
359 var points = tracePositions[id];
360 if (!pos.equals(points[points.length-1])) {
361 points.push(pos);
362 }
363 }
364 else {
365 tracePositions[id] = [pos];
366 }
367 }
368 }
370 function graphicsUpdate(currentScene) {
371 if (!recordingTraces) {
372 return;
373 }
375 var ctx = tracePathCanvas.getContext('2d');
376 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
378 ctx.save();
379 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
380 appendPositions(findPositions(currentScene));
381 for (var id in tracePositions)
382 {
383 ctx.beginPath();
384 var points = tracePositions[id];
385 for (var i=0; i < points.length; i++)
386 {
387 var p = points[i];
388 if (i == 0) {
389 ctx.moveTo(p.x, p.y);
390 }
391 else {
392 ctx.lineTo(p.x, p.y);
393 }
394 }
395 ctx.lineWidth = 1;
396 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
397 ctx.stroke();
399 for (var i=0; i < points.length; i++)
400 {
401 var p = points[i];
402 ctx.beginPath();
403 ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
404 ctx.fillStyle = "rgba(50, 50, 50, 0.4)";
405 ctx.fill();
406 }
407 }
409 ctx.restore();
410 }
412 function clearTraces() {
413 tracePositions = {};
414 }
416 function stopRecording() {
417 recordingTraces = false;
418 }
420 function startRecording() {
421 recordingTraces = true;
422 }
424 return {
425 graphicsUpdate: graphicsUpdate,
426 canvas: tracePathCanvas,
427 clearTraces: clearTraces,
428 stopRecording: stopRecording,
429 startRecording: startRecording
430 }
433function executeCallbacks(callbacks, reexecute) {
434 callbacks.forEach(function(timer) {
435 if (reexecute || !timer.executed) {
436 var func = timer.func;
437 timer.executed = true;
438 func();
439 }
440 });
443function createCanvas() {
444 var c = document.createElement('canvas');
445 c.width = window.innerWidth;
446 c.height = window.innerHeight;
447 c.style.position = "absolute";
448 c.style.top = "0";
449 c.style.left = "0";
450 c.style.pointerEvents = "none";
451 return c;
454function assert(bool, msg) {
455 if (!bool) {
456 throw "Assertion error: " + msg;
457 }
460function snapshotSignalGraph(signalGraphNodes) {
461 var nodeValues = [];
463 signalGraphNodes.forEach(function(node) {
464 nodeValues.push({ value: node.value, id: node.id });
465 });
467 return nodeValues;
468};
470function restoreSnapshot(signalGraphNodes, snapshot) {
471 assert(signalGraphNodes.length == snapshot.length, "saved program state has wrong length");
472 for (var i=0; i < signalGraphNodes.length; i++) {
473 var node = signalGraphNodes[i];
474 var state = snapshot[i];
475 assert(node.id == state.id, "the nodes moved position");
477 node.value = state.value;
478 }
481function flattenSignalGraph(nodes) {
482 var nodesById = {};
484 function addAllToDict(node) {
485 nodesById[node.id] = node;
486 node.kids.forEach(addAllToDict);
487 }
488 nodes.forEach(addAllToDict);
490 var allNodes = Object.keys(nodesById).sort().map(function(key) {
491 return nodesById[key];
492 });
493 return allNodes;
494};
496}());