on 1699f5a 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 /* =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 debugModule.setPausedAt(false, eventCounter);
203 }
204 }
206 function stepTo(index) {
207 if (!debugModule.getPaused()) {
208 debugModule.setPausedAt(true);
209 resetProgram();
210 }
212 if (index < 0 || index > getMaxSteps()) {
213 throw "Index out of bounds: " + index;
214 }
216 if (index < eventCounter) {
217 resetProgram();
218 eventCounter = 0;
219 debugModule.tracePath.clearTraces();
220 }
222 debugModule.tracePath.startRecording();
224 assert(index >= eventCounter, "index must be bad");
225 while (eventCounter < index) {
226 var nextEvent = debugModule.getRecordedEventAt(eventCounter);
227 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
229 eventCounter += 1;
230 }
231 assert(eventCounter == index, "while loop didn't work");
232 debugModule.tracePath.stopRecording();
233 }
235 function getMaxSteps() {
236 return debugModule.getRecordedEventsLength();
237 }
239 function doPlayback(eventList) {
240 var x = eventList.shift();
241 var time = x[2];
242 runtime.notify(x[0], x[1], x[2]);
244 if (eventList.length > 0) {
245 var delta = eventList[0][2] - time;
246 setTimeout(function() { doPlayback(eventList); }, delta);
247 }
248 }
250 function redrawGraphics() {
251 var main = debugModule.moduleInstance.main
252 for (var i = main.kids.length ; i-- ; ) {
253 main.kids[i].recv(Date.now(), true, main.id);
254 }
255 }
257 function getHotSwapState() {
258 var counter = eventCounter;
259 if (!debugModule.getPaused()) {
260 counter = getMaxSteps();
261 }
262 return {
263 recordedEvents: debugModule.copyRecordedEvents(),
264 eventCounter: counter
265 };
266 }
268 function dispose() {
269 var parentNode = runtime.node.parentNode;
270 parentNode.removeChild(debugModule.tracePath.canvas);
271 parentNode.removeChild(runtime.node);
272 }
274 if (hotSwapState) {
275 // The problem is that we want to previous paused state. But
276 // by the time JS reaches here, the old code has been swapped out
277 // and the new modules are being generated. So we can ask the
278 // debugging console what it thinks the pause state is and go
279 // from there.
280 var pauseState = top.debug.paused;
281 debugModule.setPausedAt(true);
282 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
284 // draw new trace path
285 debugModule.tracePath.startRecording();
286 stepTo(getMaxSteps());
287 debugModule.tracePath.stopRecording();
289 stepTo(hotSwapState.eventCounter);
290 debugModule.setPausedAt(pauseState, hotSwapState.eventCounter);
291 }
293 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
295 var elmDebugger = {
296 restart: restartProgram,
297 pause: pauseProgram,
298 kontinue: continueProgram,
299 getMaxSteps: getMaxSteps,
300 stepTo: stepTo,
301 getPaused: debugModule.getPaused,
302 getHotSwapState: getHotSwapState,
303 dispose: dispose,
304 allNodes: debugModule.moduleNodes,
305 watchTracker: debugModule.watchTracker,
306 mainNode: debugModule.moduleInstance.main
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, mainNode) {
326 var List = Elm.List.make(runtime);
327 var Signal = Elm.Signal.make(runtime);
328 var tracePathNode = A2(Signal.lift, graphicsUpdate, mainNode);
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 saveNodeValues(allNodes) {
464 var nodeValues = [];
466 allNodes.forEach(function(node) {
467 nodeValues.push({ value: node.value, id: node.id });
468 });
470 return nodeValues;
471};
474function restoreNodeValues(allNodes, nodeStates) {
475 assert(allNodes.length == nodeStates.length, "saved program state has wrong length");
476 for (var i=0; i < allNodes.length; i++) {
477 var node = allNodes[i];
478 var state = nodeStates[i];
479 assert(node.id == state.id, "the nodes moved position");
481 node.value = state.value;
482 }
485function flattenNodes(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}());