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