on 94fb30c help sign in
elk/runtime/Debugger.js
478 lines 12 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 var cbObj = { func:func, delayMs:delayMs, timerId:0, executed:false };
64 var timerId = setTimeout(function() {
65 cbObj.executed = true;
66 func();
67 }, delayMs);
68 cbObj.timerId = timerId;
69 asyncCallbacks.push(cbObj);
70 return timerId;
71 }
73 function recordEvent(id, v, timestep) {
74 watchTracker.pushFrame();
75 recordedEvents.push({ id:id, value:v, timestep:timestep });
76 }
78 function clearAsyncCallbacks() {
79 asyncCallbacks.forEach(function(timer) {
80 if (!timer.executed) {
81 clearTimeout(timer.timerId);
82 }
83 });
84 }
86 function clearRecordedEvents() {
87 recordedEvents = [];
88 }
90 function getRecordedEventsLength() {
91 return recordedEvents.length;
92 }
94 function getRecordedEventAt(i) {
95 return recordedEvents[i];
96 }
98 function copyRecordedEvents() {
99 return recordedEvents.slice();
100 }
102 function loadRecordedEvents(events) {
103 recordedEvents = events.slice();
104 }
106 function setPaused(v) {
107 programPaused = v;
108 if (programPaused) {
109 clearAsyncCallbacks();
110 tracePath.stopRecording();
111 }
112 else {
113 // executeCallbacks should only be called when continuing, not when restarting.
114 //executeCallbacks(asyncCallbacks, false);
115 tracePath.startRecording();
116 }
117 }
119 function getPaused() {
120 return programPaused;
121 }
123 // runtime is the prototype of wrappedRuntime
124 // so we can access all runtime properties too
125 var wrappedRuntime = Object.create(runtime);
126 wrappedRuntime.notify = wrapNotify;
127 wrappedRuntime.runDelayed = wrapRunDelayed;
129 var assignedPropTracker = Object.create(wrappedRuntime);
130 var moduleInstance = module.make(assignedPropTracker);
132 // make sure the signal graph is actually a signal & extract the visual model
133 if ( !('recv' in moduleInstance.main) ) {
134 moduleInstance.main = Elm.Signal.make(runtime).constant(moduleInstance.main);
135 }
137 // The main module stores imported modules onto the runtime.
138 // To ensure only one instance of each module is created,
139 // we assign them back on the original runtime object.
140 Object.keys(assignedPropTracker).forEach(function(key) {
141 runtime[key] = assignedPropTracker[key];
142 });
144 var moduleNodes = flattenNodes(wrappedRuntime.inputs);
145 var tracePath = tracePathInit(runtime, moduleInstance.main);
147 return {
148 moduleInstance: moduleInstance,
149 moduleNodes: moduleNodes,
150 initialNodeValues: saveNodeValues(moduleNodes),
151 initialAsyncCallbacks: asyncCallbacks.slice(),
152 // API functions
153 clearAsyncCallbacks: clearAsyncCallbacks,
154 clearRecordedEvents: clearRecordedEvents,
155 getRecordedEventsLength: getRecordedEventsLength,
156 getRecordedEventAt: getRecordedEventAt,
157 copyRecordedEvents: copyRecordedEvents,
158 loadRecordedEvents: loadRecordedEvents,
159 getPaused: getPaused,
160 setPaused: setPaused,
161 tracePath: tracePath,
162 watchTracker: watchTracker,
163 };
166function debuggerInit(debugModule, runtime, hotSwapState /* =undefined */) {
167 var eventCounter = 0;
169 function resetProgram() {
170 debugModule.clearAsyncCallbacks();
171 restoreNodeValues(debugModule.moduleNodes, debugModule.initialNodeValues);
172 redrawGraphics();
173 }
175 function restartProgram() {
176 resetProgram();
177 debugModule.watchTracker.clear();
178 debugModule.tracePath.clearTraces();
179 debugModule.clearRecordedEvents();
180 debugModule.setPaused(false);
181 executeCallbacks(debugModule.initialAsyncCallbacks, true);
182 }
184 function pauseProgram() {
185 debugModule.setPaused(true);
186 eventCounter = debugModule.getRecordedEventsLength();
187 }
189 function continueProgram() {
190 if (debugModule.getPaused())
191 {
192 debugModule.setPaused(false);
193 }
194 }
196 function stepTo(index) {
197 if (!debugModule.getPaused()) {
198 debugModule.setPaused(true);
199 resetProgram();
200 }
202 if (index < 0 || index > getMaxSteps()) {
203 throw "Index out of bounds: " + index;
204 }
206 if (index < eventCounter) {
207 resetProgram();
208 eventCounter = 0;
209 }
211 assert(index >= eventCounter, "index must be bad");
212 while (eventCounter < index) {
213 var nextEvent = debugModule.getRecordedEventAt(eventCounter);
214 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
216 eventCounter += 1;
217 }
218 assert(eventCounter == index, "while loop didn't work");
219 }
221 function getMaxSteps() {
222 return debugModule.getRecordedEventsLength();
223 }
225 function doPlayback(eventList) {
226 var x = eventList.shift();
227 var time = x[2];
228 runtime.notify(x[0], x[1], x[2]);
230 if (eventList.length > 0) {
231 var delta = eventList[0][2] - time;
232 setTimeout(function() { doPlayback(eventList); }, delta);
233 }
234 }
236 function redrawGraphics() {
237 var main = debugModule.moduleInstance.main
238 for (var i = main.kids.length ; i-- ; ) {
239 main.kids[i].recv(Date.now(), true, main.id);
240 }
241 }
243 function getHotSwapState() {
244 var counter = eventCounter;
245 if (!debugModule.getPaused()) {
246 counter = getMaxSteps();
247 }
248 return {
249 recordedEvents: debugModule.copyRecordedEvents(),
250 eventCounter: counter
251 };
252 }
254 function dispose() {
255 var parentNode = runtime.node.parentNode;
256 parentNode.removeChild(debugModule.tracePath.canvas);
257 parentNode.removeChild(runtime.node);
258 }
260 if (hotSwapState) {
261 debugModule.setPaused(true);
262 debugModule.loadRecordedEvents(hotSwapState.recordedEvents);
264 // draw new trace path
265 debugModule.tracePath.startRecording();
266 stepTo(getMaxSteps());
267 debugModule.tracePath.stopRecording();
269 stepTo(hotSwapState.eventCounter);
270 }
272 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
274 var elmDebugger = {
275 restart: restartProgram,
276 pause: pauseProgram,
277 kontinue: continueProgram,
278 getMaxSteps: getMaxSteps,
279 stepTo: stepTo,
280 getPaused: debugModule.getPaused,
281 getHotSwapState: getHotSwapState,
282 dispose: dispose,
283 allNodes: debugModule.moduleNodes,
284 watchTracker: debugModule.watchTracker,
285 mainNode: debugModule.moduleInstance.main
286 };
288 return elmDebugger;
291function Point(x, y) {
292 this.x = x;
293 this.y = y;
295 this.translate = function(x, y) {
296 return new Point(this.x + x, this.y + y);
297 }
299 this.equals = function(p) {
300 return this.x == p.x && this.y == p.y;
301 }
304function tracePathInit(runtime, mainNode) {
305 var List = Elm.List.make(runtime);
306 var Signal = Elm.Signal.make(runtime);
307 var tracePathNode = A2(Signal.lift, graphicsUpdate, mainNode);
308 var tracePathCanvas = createCanvas();
309 var tracePositions = {};
310 var recordingTraces = true;
312 function findPositions(currentScene) {
313 var positions = {};
314 function processElement(elem, offset) {
315 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
316 {
317 List.map(F2(processForm)(offset))(elem.element.model.forms);
318 }
319 if (elem.props.debugTracePathId)
320 {
321 positions[elem.props.debugTracePathId] = new Point(offset.x, offset.y);
322 }
323 }
325 function processForm(offset, form) {
326 if (form.form.ctor == "FElement")
327 {
328 processElement(form.form._0, offset.translate(form.x, -form.y));
329 }
330 }
332 processElement(currentScene, new Point(0, 0));
333 return positions;
334 }
336 function appendPositions(positions) {
337 for (var id in positions) {
338 var pos = positions[id];
339 if (tracePositions.hasOwnProperty(id)) {
340 var points = tracePositions[id];
341 if (!pos.equals(points[points.length-1])) {
342 points.push(pos);
343 }
344 }
345 else {
346 tracePositions[id] = [pos];
347 }
348 }
349 }
351 function graphicsUpdate(currentScene) {
352 if (!recordingTraces) {
353 return;
354 }
356 var ctx = tracePathCanvas.getContext('2d');
357 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
359 ctx.save();
360 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
361 appendPositions(findPositions(currentScene));
362 for (var id in tracePositions)
363 {
364 ctx.beginPath();
365 var points = tracePositions[id];
366 for (var i=0; i < points.length; i++)
367 {
368 var p = points[i];
369 if (i == 0) {
370 ctx.moveTo(p.x, p.y);
371 }
372 else {
373 ctx.lineTo(p.x, p.y);
374 }
375 }
376 ctx.lineWidth = 1;
377 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
378 ctx.stroke();
380 for (var i=0; i < points.length; i++)
381 {
382 var p = points[i];
383 ctx.beginPath();
384 ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
385 ctx.fillStyle = "rgba(50, 50, 50, 0.4)";
386 ctx.fill();
387 }
388 }
390 ctx.restore();
391 }
393 function clearTraces() {
394 tracePositions = {};
395 }
397 function stopRecording() {
398 recordingTraces = false;
399 }
401 function startRecording() {
402 recordingTraces = true;
403 }
405 return {
406 graphicsUpdate: graphicsUpdate,
407 canvas: tracePathCanvas,
408 clearTraces: clearTraces,
409 stopRecording: stopRecording,
410 startRecording: startRecording
411 }
415function executeCallbacks(callbacks, reexecute) {
416 callbacks.forEach(function(timer) {
417 if (reexecute || !timer.executed) {
418 var func = timer.func;
419 func();
420 }
421 });
424function createCanvas() {
425 var c = document.createElement('canvas');
426 c.width = window.innerWidth;
427 c.height = window.innerHeight;
428 c.style.position = "absolute";
429 c.style.top = "0";
430 c.style.left = "0";
431 c.style.pointerEvents = "none";
432 return c;
435function assert(bool, msg) {
436 if (!bool) {
437 throw "Assertion error: " + msg;
438 }
441function saveNodeValues(allNodes) {
442 var nodeValues = [];
444 allNodes.forEach(function(node) {
445 nodeValues.push({ value: node.value, id: node.id });
446 });
448 return nodeValues;
449};
452function restoreNodeValues(allNodes, nodeStates) {
453 assert(allNodes.length == nodeStates.length, "saved program state has wrong length");
454 for (var i=0; i < allNodes.length; i++) {
455 var node = allNodes[i];
456 var state = nodeStates[i];
457 assert(node.id == state.id, "the nodes moved position");
459 node.value = state.value;
460 }
463function flattenNodes(nodes) {
464 var nodesById = {};
466 function addAllToDict(node) {
467 nodesById[node.id] = node;
468 node.kids.forEach(addAllToDict);
469 }
470 nodes.forEach(addAllToDict);
472 var allNodes = Object.keys(nodesById).sort().map(function(key) {
473 return nodesById[key];
474 });
475 return allNodes;
476};
478}());