on f74f266 help sign in
elk/runtime/Debugger.js
469 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);
125 // make sure the signal graph is actually a signal & extract the visual model
126 if ( !('recv' in moduleInstance.main) ) {
127 moduleInstance.main = Elm.Signal.make(runtime).constant(moduleInstance.main);
128 }
130 // The main module stores imported modules onto the runtime.
131 // To ensure only one instance of each module is created,
132 // we assign them back on the original runtime object.
133 Object.keys(assignedPropTracker).forEach(function(key) {
134 runtime[key] = assignedPropTracker[key];
135 });
137 var moduleNodes = flattenNodes(wrappedRuntime.inputs);
138 var tracePath = tracePathInit(runtime, moduleInstance.main);
140 return {
141 moduleInstance: moduleInstance,
142 moduleNodes: moduleNodes,
143 initialNodeValues: saveNodeValues(moduleNodes),
144 initialAsyncCallbacks: asyncCallbacks.slice(),
145 // API functions
146 clearAsyncCallbacks: clearAsyncCallbacks,
147 clearRecordedEvents: clearRecordedEvents,
148 getRecordedEventsLength: getRecordedEventsLength,
149 getRecordedEventAt: getRecordedEventAt,
150 copyRecordedEvents: copyRecordedEvents,
151 loadRecordedEvents: loadRecordedEvents,
152 getPaused: getPaused,
153 setPaused: setPaused,
154 tracePath: tracePath,
155 watchTracker: watchTracker,
156 };
159function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
160 var eventCounter = 0;
162 function resetProgram() {
163 debugModule.clearAsyncCallbacks();
164 restoreNodeValues(debugModule.moduleNodes, debugModule.initialNodeValues);
165 redrawGraphics();
166 }
168 function restartProgram() {
169 resetProgram();
170 debugModule.watchTracker.clear();
171 debugModule.tracePath.clearTraces();
172 debugModule.clearRecordedEvents();
173 debugModule.setPaused(false);
174 executeCallbacks(debugModule.initialAsyncCallbacks, true);
175 }
177 function pauseProgram() {
178 debugModule.setPaused(true);
179 eventCounter = debugModule.getRecordedEventsLength();
180 }
182 function continueProgram() {
183 if (debugModule.getPaused())
184 {
185 debugModule.setPaused(false);
186 }
187 }
189 function stepTo(index) {
190 if (!debugModule.getPaused()) {
191 debugModule.setPaused(true);
192 resetProgram();
193 }
195 if (index < 0 || index > getMaxSteps()) {
196 throw "Index out of bounds: " + index;
197 }
199 if (index < eventCounter) {
200 resetProgram();
201 eventCounter = 0;
202 }
204 assert(index >= eventCounter, "index must be bad");
205 while (eventCounter < index) {
206 var nextEvent = debugModule.getRecordedEventAt(eventCounter);
207 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
209 eventCounter += 1;
210 }
211 assert(eventCounter == index, "while loop didn't work");
212 }
214 function getMaxSteps() {
215 return debugModule.getRecordedEventsLength();
216 }
218 function doPlayback(eventList) {
219 var x = eventList.shift();
220 var time = x[2];
221 runtime.notify(x[0], x[1], x[2]);
223 if (eventList.length > 0) {
224 var delta = eventList[0][2] - time;
225 setTimeout(function() { doPlayback(eventList); }, delta);
226 }
227 }
229 function redrawGraphics() {
230 var graphicsNode = debugModule.moduleInstance.main.kids[0];
231 graphicsNode.recv(Date.now(), true, debugModule.moduleInstance.main.id);
232 }
234 function getHotSwapState() {
235 var counter = eventCounter;
236 if (!debugModule.getPaused()) {
237 counter = getMaxSteps();
238 }
239 return {
240 recordedEvents: debugModule.copyRecordedEvents(),
241 eventCounter: counter
242 };
243 }
245 function dispose() {
246 var parentNode = runtime.node.parentNode;
247 parentNode.removeChild(debugModule.tracePath.canvas);
248 parentNode.removeChild(runtime.node);
249 }
251 if (hotSwapState) {
252 debugModule.setPaused(true);
253 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
255 // draw new trace path
256 debugModule.tracePath.startRecording();
257 stepTo(getMaxSteps());
258 debugModule.tracePath.stopRecording();
260 stepTo(hotSwapState.eventCounter);
261 }
263 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
265 var elmDebugger = {
266 restart: restartProgram,
267 pause: pauseProgram,
268 kontinue: continueProgram,
269 getMaxSteps: getMaxSteps,
270 stepTo: stepTo,
271 getPaused: debugModule.getPaused,
272 getHotSwapState: getHotSwapState,
273 dispose: dispose,
274 allNodes: debugModule.moduleNodes,
275 watchTracker: debugModule.watchTracker,
276 mainNode: debugModule.moduleInstance.main
277 };
279 return elmDebugger;
282function Point(x, y) {
283 this.x = x;
284 this.y = y;
286 this.translate = function(x, y) {
287 return new Point(this.x + x, this.y + y);
288 }
290 this.equals = function(p) {
291 return this.x == p.x && this.y == p.y;
292 }
295function tracePathInit(runtime, mainNode) {
296 var List = Elm.List.make(runtime);
297 var Signal = Elm.Signal.make(runtime);
298 var tracePathNode = A2(Signal.lift, graphicsUpdate, mainNode);
299 var tracePathCanvas = createCanvas();
300 var tracePositions = {};
301 var recordingTraces = true;
303 function findPositions(currentScene) {
304 var positions = {};
305 function processElement(elem, offset) {
306 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
307 {
308 List.map(F2(processForm)(offset))(elem.element.model.forms);
309 }
310 else if (elem.element.ctor == "Image" && elem.props.debugTracePathId)
311 {
312 positions[elem.props.debugTracePathId] = new Point(offset.x, offset.y);
313 }
314 }
316 function processForm(offset, form) {
317 if (form.form.ctor == "FElement")
318 {
319 processElement(form.form._0, offset.translate(form.x, -form.y));
320 }
321 }
323 processElement(currentScene, new Point(0, 0));
324 return positions;
325 }
327 function appendPositions(positions) {
328 for (var id in positions) {
329 var pos = positions[id];
330 if (tracePositions.hasOwnProperty(id)) {
331 var points = tracePositions[id];
332 if (!pos.equals(points[points.length-1])) {
333 points.push(pos);
334 }
335 }
336 else {
337 tracePositions[id] = [pos];
338 }
339 }
340 }
342 function graphicsUpdate(currentScene) {
343 if (!recordingTraces) {
344 return;
345 }
347 var ctx = tracePathCanvas.getContext('2d');
348 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
350 ctx.save();
351 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
352 appendPositions(findPositions(currentScene));
353 for (var id in tracePositions)
354 {
355 ctx.beginPath();
356 var points = tracePositions[id];
357 for (var i=0; i < points.length; i++)
358 {
359 var p = points[i];
360 if (i == 0) {
361 ctx.moveTo(p.x, p.y);
362 }
363 else {
364 ctx.lineTo(p.x, p.y);
365 }
366 }
367 ctx.lineWidth = 1;
368 ctx.strokeStyle = "#888a85";
369 ctx.stroke();
371 for (var i=0; i < points.length; i++)
372 {
373 var p = points[i];
374 ctx.beginPath();
375 ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
376 ctx.fillStyle = "#2e3436";
377 ctx.fill();
378 }
379 }
381 ctx.restore();
382 }
384 function clearTraces() {
385 tracePositions = {};
386 }
388 function stopRecording() {
389 recordingTraces = false;
390 }
392 function startRecording() {
393 recordingTraces = true;
394 }
396 return {
397 graphicsUpdate: graphicsUpdate,
398 canvas: tracePathCanvas,
399 clearTraces: clearTraces,
400 stopRecording: stopRecording,
401 startRecording: startRecording
402 }
406function executeCallbacks(callbacks, reexecute) {
407 callbacks.forEach(function(timer) {
408 if (reexecute || !timer.executed) {
409 var func = timer.func;
410 func();
411 }
412 });
415function createCanvas() {
416 var c = document.createElement('canvas');
417 c.width = window.innerWidth;
418 c.height = window.innerHeight;
419 c.style.position = "absolute";
420 c.style.top = "0";
421 c.style.left = "0";
422 c.style.pointerEvents = "none";
423 return c;
426function assert(bool, msg) {
427 if (!bool) {
428 throw "Assertion error: " + msg;
429 }
432function saveNodeValues(allNodes) {
433 var nodeValues = [];
435 allNodes.forEach(function(node) {
436 nodeValues.push({ value: node.value, id: node.id });
437 });
439 return nodeValues;
440};
443function restoreNodeValues(allNodes, nodeStates) {
444 assert(allNodes.length == nodeStates.length, "saved program state has wrong length");
445 for (var i=0; i < allNodes.length; i++) {
446 var node = allNodes[i];
447 var state = nodeStates[i];
448 assert(node.id == state.id, "the nodes moved position");
450 node.value = state.value;
451 }
454function flattenNodes(nodes) {
455 var nodesById = {};
457 function addAllToDict(node) {
458 nodesById[node.id] = node;
459 node.kids.forEach(addAllToDict);
460 }
461 nodes.forEach(addAllToDict);
463 var allNodes = Object.keys(nodesById).sort().map(function(key) {
464 return nodesById[key];
465 });
466 return allNodes;
467};
469}());