on 0cc63b4 help sign in
elk/runtime/Debugger.js
463 lines 12 kB history raw
2(function() {
3'use strict';
5Elm.Debugger = null;
6Elm.debuggerAttach = function(module, hotSwapState /* =undefined */) {
7 return {
8 make: function(runtime) {
9 var wrappedModule = debugModule(module, runtime);
10 Elm.Debugger = debuggerInit(wrappedModule, runtime, hotSwapState);
11 dispatchElmDebuggerInit();
12 return wrappedModule.moduleInstance;
13 }
14 };
15};
17function dispatchElmDebuggerInit() {
18 if (parent.window) {
19 var dispatch = function(_) {
20 parent.window.postMessage("elmDebuggerInit", window.location.origin);
21 };
22 if (parent.window.document.readyState === "complete") {
23 dispatch();
24 }
25 else {
26 parent.window.addEventListener("load", dispatch);
27 }
28 }
31function debugModule(module, runtime) {
32 var programPaused = false;
33 var recordedEvents = [];
34 var asyncCallbacks = [];
35 var watchTracker = Elm.Native.Debug.make(runtime).watchTracker;
37 function wrapNotify(id, v) {
38 var timestep = Date.now();
40 if (programPaused) {
41 // ignore async events generated while playing back
42 // or user events while program is paused
43 return false;
44 }
45 else {
46 var changed = runtime.notify(id, v, timestep);
47 recordEvent(id, v, timestep);
48 if (parent.window) {
49 parent.window.postMessage("elmNotify", window.location.origin);
50 }
51 return changed;
52 }
53 };
55 function wrapRunDelayed(func, delayMs) {
56 var cbObj = { func:func, delayMs:delayMs, timerId:0, executed:false };
57 var timerId = setTimeout(function() {
58 cbObj.executed = true;
59 func();
60 }, delayMs);
61 cbObj.timerId = timerId;
62 asyncCallbacks.push(cbObj);
63 return timerId;
64 }
66 function recordEvent(id, v, timestep) {
67 watchTracker.pushFrame();
68 recordedEvents.push({ id:id, value:v, timestep:timestep });
69 }
71 function clearAsyncCallbacks() {
72 asyncCallbacks.forEach(function(timer) {
73 if (!timer.executed) {
74 clearTimeout(timer.timerId);
75 }
76 });
77 }
79 function clearRecordedEvents() {
80 recordedEvents = [];
81 }
83 function getRecordedEventsLength() {
84 return recordedEvents.length;
85 }
87 function getRecordedEventAt(i) {
88 return recordedEvents[i];
89 }
91 function copyRecordedEvents() {
92 return recordedEvents.slice();
93 }
95 function loadRecordedEvents(events) {
96 recordedEvents = events.slice();
97 }
99 function setPaused(v) {
100 programPaused = v;
101 if (programPaused) {
102 clearAsyncCallbacks();
103 tracePath.stopRecording();
104 }
105 else {
106 // executeCallbacks should only be called when continuing, not when restarting.
107 //executeCallbacks(asyncCallbacks, false);
108 tracePath.startRecording();
109 }
110 }
112 function getPaused() {
113 return programPaused;
114 }
116 // runtime is the prototype of wrappedRuntime
117 // so we can access all runtime properties too
118 var wrappedRuntime = Object.create(runtime);
119 wrappedRuntime.notify = wrapNotify;
120 wrappedRuntime.runDelayed = wrapRunDelayed;
122 var assignedPropTracker = Object.create(wrappedRuntime);
123 var moduleInstance = module.make(assignedPropTracker);
124 // The main module stores imported modules onto the runtime.
125 // To ensure only one instance of each module is created,
126 // we assign them back on the original runtime object.
127 Object.keys(assignedPropTracker).forEach(function(key) {
128 runtime[key] = assignedPropTracker[key];
129 });
131 var moduleNodes = flattenNodes(wrappedRuntime.inputs);
132 var tracePath = tracePathInit(runtime, moduleInstance.main);
134 return {
135 moduleInstance: moduleInstance,
136 moduleNodes: moduleNodes,
137 initialNodeValues: saveNodeValues(moduleNodes),
138 initialAsyncCallbacks: asyncCallbacks.slice(),
139 // API functions
140 clearAsyncCallbacks: clearAsyncCallbacks,
141 clearRecordedEvents: clearRecordedEvents,
142 getRecordedEventsLength: getRecordedEventsLength,
143 getRecordedEventAt: getRecordedEventAt,
144 copyRecordedEvents: copyRecordedEvents,
145 loadRecordedEvents: loadRecordedEvents,
146 getPaused: getPaused,
147 setPaused: setPaused,
148 tracePath: tracePath,
149 watchTracker: watchTracker,
150 };
153function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
154 var eventCounter = 0;
156 function resetProgram() {
157 debugModule.clearAsyncCallbacks();
158 restoreNodeValues(debugModule.moduleNodes, debugModule.initialNodeValues);
159 redrawGraphics();
160 }
162 function restartProgram() {
163 resetProgram();
164 debugModule.watchTracker.clear();
165 debugModule.tracePath.clearTraces();
166 debugModule.clearRecordedEvents();
167 debugModule.setPaused(false);
168 executeCallbacks(debugModule.initialAsyncCallbacks, true);
169 }
171 function pauseProgram() {
172 debugModule.setPaused(true);
173 eventCounter = debugModule.getRecordedEventsLength();
174 }
176 function continueProgram() {
177 if (debugModule.getPaused())
178 {
179 debugModule.setPaused(false);
180 }
181 }
183 function stepTo(index) {
184 if (!debugModule.getPaused()) {
185 debugModule.setPaused(true);
186 resetProgram();
187 }
189 if (index < 0 || index > getMaxSteps()) {
190 throw "Index out of bounds: " + index;
191 }
193 if (index < eventCounter) {
194 resetProgram();
195 eventCounter = 0;
196 }
198 assert(index >= eventCounter, "index must be bad");
199 while (eventCounter < index) {
200 var nextEvent = debugModule.getRecordedEventAt(eventCounter);
201 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
203 eventCounter += 1;
204 }
205 assert(eventCounter == index, "while loop didn't work");
206 }
208 function getMaxSteps() {
209 return debugModule.getRecordedEventsLength();
210 }
212 function doPlayback(eventList) {
213 var x = eventList.shift();
214 var time = x[2];
215 runtime.notify(x[0], x[1], x[2]);
217 if (eventList.length > 0) {
218 var delta = eventList[0][2] - time;
219 setTimeout(function() { doPlayback(eventList); }, delta);
220 }
221 }
223 function redrawGraphics() {
224 var graphicsNode = debugModule.moduleInstance.main.kids[0];
225 graphicsNode.recv(Date.now(), true, debugModule.moduleInstance.main.id);
226 }
228 function getHotSwapState() {
229 var counter = eventCounter;
230 if (!debugModule.getPaused()) {
231 counter = getMaxSteps();
232 }
233 return {
234 recordedEvents: debugModule.copyRecordedEvents(),
235 eventCounter: counter
236 };
237 }
239 function dispose() {
240 var parentNode = runtime.node.parentNode;
241 parentNode.removeChild(debugModule.tracePath.canvas);
242 parentNode.removeChild(runtime.node);
243 }
245 if (hotSwapState) {
246 debugModule.setPaused(true);
247 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
249 // draw new trace path
250 debugModule.tracePath.startRecording();
251 stepTo(getMaxSteps());
252 debugModule.tracePath.stopRecording();
254 stepTo(hotSwapState.eventCounter);
255 }
257 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
259 var elmDebugger = {
260 restart: restartProgram,
261 pause: pauseProgram,
262 kontinue: continueProgram,
263 getMaxSteps: getMaxSteps,
264 stepTo: stepTo,
265 getPaused: debugModule.getPaused,
266 getHotSwapState: getHotSwapState,
267 dispose: dispose,
268 allNodes: debugModule.moduleNodes,
269 watchTracker: debugModule.watchTracker,
270 mainNode: debugModule.moduleInstance.main
271 };
273 return elmDebugger;
276function Point(x, y) {
277 this.x = x;
278 this.y = y;
280 this.translate = function(x, y) {
281 return new Point(this.x + x, this.y + y);
282 }
284 this.equals = function(p) {
285 return this.x == p.x && this.y == p.y;
286 }
289function tracePathInit(runtime, mainNode) {
290 var List = Elm.List.make(runtime);
291 var Signal = Elm.Signal.make(runtime);
292 var tracePathNode = A2(Signal.lift, graphicsUpdate, mainNode);
293 var tracePathCanvas = createCanvas();
294 var tracePositions = {};
295 var recordingTraces = true;
297 function findPositions(currentScene) {
298 var positions = {};
299 function processElement(elem, offset) {
300 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
301 {
302 List.map(F2(processForm)(offset))(elem.element.model.forms);
303 }
304 else if (elem.element.ctor == "Image" && elem.props.debugTracePathId)
305 {
306 positions[elem.props.debugTracePathId] = new Point(offset.x, offset.y);
307 }
308 }
310 function processForm(offset, form) {
311 if (form.form.ctor == "FElement")
312 {
313 processElement(form.form._0, offset.translate(form.x, -form.y));
314 }
315 }
317 processElement(currentScene, new Point(0, 0));
318 return positions;
319 }
321 function appendPositions(positions) {
322 for (var id in positions) {
323 var pos = positions[id];
324 if (tracePositions.hasOwnProperty(id)) {
325 var points = tracePositions[id];
326 if (!pos.equals(points[points.length-1])) {
327 points.push(pos);
328 }
329 }
330 else {
331 tracePositions[id] = [pos];
332 }
333 }
334 }
336 function graphicsUpdate(currentScene) {
337 if (!recordingTraces) {
338 return;
339 }
341 var ctx = tracePathCanvas.getContext('2d');
342 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
344 ctx.save();
345 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
346 appendPositions(findPositions(currentScene));
347 for (var id in tracePositions)
348 {
349 ctx.beginPath();
350 var points = tracePositions[id];
351 for (var i=0; i < points.length; i++)
352 {
353 var p = points[i];
354 if (i == 0) {
355 ctx.moveTo(p.x, p.y);
356 }
357 else {
358 ctx.lineTo(p.x, p.y);
359 }
360 }
361 ctx.lineWidth = 1;
362 ctx.strokeStyle = "#888a85";
363 ctx.stroke();
365 for (var i=0; i < points.length; i++)
366 {
367 var p = points[i];
368 ctx.beginPath();
369 ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
370 ctx.fillStyle = "#2e3436";
371 ctx.fill();
372 }
373 }
375 ctx.restore();
376 }
378 function clearTraces() {
379 tracePositions = {};
380 }
382 function stopRecording() {
383 recordingTraces = false;
384 }
386 function startRecording() {
387 recordingTraces = true;
388 }
390 return {
391 graphicsUpdate: graphicsUpdate,
392 canvas: tracePathCanvas,
393 clearTraces: clearTraces,
394 stopRecording: stopRecording,
395 startRecording: startRecording
396 }
400function executeCallbacks(callbacks, reexecute) {
401 callbacks.forEach(function(timer) {
402 if (reexecute || !timer.executed) {
403 var func = timer.func;
404 func();
405 }
406 });
409function createCanvas() {
410 var c = document.createElement('canvas');
411 c.width = window.innerWidth;
412 c.height = window.innerHeight;
413 c.style.position = "absolute";
414 c.style.top = "0";
415 c.style.left = "0";
416 c.style.pointerEvents = "none";
417 return c;
420function assert(bool, msg) {
421 if (!bool) {
422 throw "Assertion error: " + msg;
423 }
426function saveNodeValues(allNodes) {
427 var nodeValues = [];
429 allNodes.forEach(function(node) {
430 nodeValues.push({ value: node.value, id: node.id });
431 });
433 return nodeValues;
434};
437function restoreNodeValues(allNodes, nodeStates) {
438 assert(allNodes.length == nodeStates.length, "saved program state has wrong length");
439 for (var i=0; i < allNodes.length; i++) {
440 var node = allNodes[i];
441 var state = nodeStates[i];
442 assert(node.id == state.id, "the nodes moved position");
444 node.value = state.value;
445 }
448function flattenNodes(nodes) {
449 var nodesById = {};
451 function addAllToDict(node) {
452 nodesById[node.id] = node;
453 node.kids.forEach(addAllToDict);
454 }
455 nodes.forEach(addAllToDict);
457 var allNodes = Object.keys(nodesById).sort().map(function(key) {
458 return nodesById[key];
459 });
460 return allNodes;
461};
463}());