on 9c54aeb help sign in
elk/runtime/Debugger.js
614 lines 18 kB history raw
1(function() {
2'use strict';
4if (!window.location.origin) {
5 window.location.origin =
6 window.location.protocol + "//" +
7 window.location.hostname +
8 (window.location.port ? (':' + window.location.port) : '');
9}
11Elm.Debugger = null;
12Elm.debuggerAttach = function(module, hotSwapState /* =undefined */) {
13 return {
14 make: function(runtime) {
15 var wrappedModule = debugModule(module, runtime);
16 Elm.Debugger = debuggerInit(wrappedModule, runtime, hotSwapState);
17 dispatchElmDebuggerInit();
18 return wrappedModule.debuggedModule;
19 }
20 };
21};
23var EVENTS_PER_SAVE = 100;
25function dispatchElmDebuggerInit() {
26 if (parent.window) {
27 var dispatch = function() {
28 parent.window.postMessage("elmDebuggerInit", window.location.origin);
29 };
30 if (parent.window.document.readyState === "complete") {
31 dispatch();
32 }
33 else {
34 parent.window.addEventListener("load", dispatch);
35 }
36 }
39function debugModule(module, runtime) {
40 var programPaused = false;
41 var recordedEvents = [];
42 var asyncCallbacks = [];
43 var snapshots = [];
44 var watchTracker = Elm.Native.Debug.make(runtime).watchTracker;
45 var pauseTime = 0;
46 var eventsUntilSnapshot = EVENTS_PER_SAVE;
47 runtime.debuggerStatus = runtime.debuggerStatus || {};
48 runtime.debuggerStatus.eventCounter = runtime.debuggerStatus.eventCounter || 0;
50 // runtime is the prototype of wrappedRuntime
51 // so we can access all runtime properties too
52 var wrappedRuntime = Object.create(runtime);
53 wrappedRuntime.notify = wrapNotify;
54 wrappedRuntime.runDelayed = wrapRunDelayed;
56 // make a copy of the wrappedRuntime
57 var assignedPropTracker = Object.create(wrappedRuntime);
58 var debuggedModule = module.make(assignedPropTracker);
60 // make sure the signal graph is actually a signal & extract the visual model
61 if ( !('recv' in debuggedModule.main) ) {
62 debuggedModule.main = Elm.Signal.make(runtime).constant(debuggedModule.main);
63 }
65 // The main module stores imported modules onto the runtime.
66 // To ensure only one instance of each module is created,
67 // we assign them back on the original runtime object.
68 Object.keys(assignedPropTracker).forEach(function(key) {
69 runtime[key] = assignedPropTracker[key];
70 });
72 var signalGraphNodes = flattenSignalGraph(wrappedRuntime.inputs);
73 var tracePath = tracePathInit(runtime, debuggedModule.main);
75 snapshots.push(snapshotSignalGraph(signalGraphNodes));
77 function wrapNotify(id, v) {
78 var timestep = runtime.timer.now();
80 if (programPaused) {
81 // ignore async events generated while playing back
82 // or user events while program is paused
83 return false;
84 }
85 else {
86 recordEvent(id, v, timestep);
87 var changed = runtime.notify(id, v, timestep);
88 snapshotOnCheckpoint();
89 if (parent.window) {
90 parent.window.postMessage("elmNotify", window.location.origin);
91 }
92 return changed;
93 }
94 };
96 function wrapRunDelayed(func, delayMs) {
97 if (programPaused) {
98 // Don't push timers and such to the callback stack while we're paused.
99 // It causes too many callbacks to be fired during unpausing.
100 return 0;
101 }
102 var cbObj = { func:func, delayMs:delayMs, timerId:0, executed:false };
103 var timerId = setTimeout(function() {
104 cbObj.executed = true;
105 func();
106 }, delayMs);
107 cbObj.timerId = timerId;
108 asyncCallbacks.push(cbObj);
109 return timerId;
110 }
112 function recordEvent(id, v, timestep) {
113 watchTracker.pushFrame();
114 recordedEvents.push({ id:id, value:v, timestep:timestep });
115 runtime.debuggerStatus.eventCounter += 1;
116 }
118 function clearAsyncCallbacks() {
119 asyncCallbacks.forEach(function(timer) {
120 if (!timer.executed) {
121 clearTimeout(timer.timerId);
122 }
123 });
124 }
126 function clearRecordedEvents() {
127 recordedEvents = [];
128 runtime.debuggerStatus.eventCounter = 0;
129 }
131 function getRecordedEventsLength() {
132 return recordedEvents.length;
133 }
135 function getRecordedEventAt(i) {
136 return recordedEvents[i];
137 }
139 function copyRecordedEvents() {
140 return recordedEvents.slice();
141 }
143 function loadRecordedEvents(events) {
144 recordedEvents = events.slice();
145 }
147 function clearSnapshots() {
148 snapshots = [snapshotSignalGraph(signalGraphNodes)];
149 }
151 function getSnapshotAt(i) {
152 var snapshotEvent = Math.floor(i / EVENTS_PER_SAVE);
153 assert(snapshotEvent < snapshots.length && snapshotEvent >= 0,
154 "Out of bounds index: " + snapshotEvent);
155 return snapshots[snapshotEvent];
156 }
158 function snapshotOnCheckpoint() {
159 if (eventsUntilSnapshot === 1) {
160 snapshots.push(snapshotSignalGraph(signalGraphNodes));
161 eventsUntilSnapshot = EVENTS_PER_SAVE;
162 } else {
163 eventsUntilSnapshot -= 1;
164 }
165 }
167 function setPaused() {
168 programPaused = true;
169 clearAsyncCallbacks();
170 pauseTime = Date.now();
171 tracePath.stopRecording();
172 preventInputEvents();
173 }
175 function setContinue(position) {
176 var pauseDelay = Date.now() - pauseTime;
177 runtime.timer.addDelay(pauseDelay);
178 programPaused = false;
180 // we need to dump the events that are ahead of where we're continuing.
181 var lastSnapshotPosition = Math.floor(position / EVENTS_PER_SAVE);
182 eventsUntilSnapshot = EVENTS_PER_SAVE - (position % EVENTS_PER_SAVE);
183 snapshots = snapshots.slice(0, lastSnapshotPosition + 1);
185 if (position < getRecordedEventsLength()) {
186 var lastEventTime = recordedEvents[position].timestep;
187 var scrubTime = runtime.timer.now() - lastEventTime;
188 runtime.timer.addDelay(scrubTime);
189 }
191 recordedEvents = recordedEvents.slice(0, position);
192 tracePath.clearTracesAfter(position);
193 runtime.debuggerStatus.eventCounter = position;
194 executeCallbacks(asyncCallbacks);
195 permitInputEvents();
197 tracePath.startRecording();
198 }
200 function getPaused() {
201 return programPaused;
202 }
204 function preventInputEvents(){
205 var events =
206 [ "click", "mousemove", "mouseup", "mousedown", "mouseclick"
207 , "keydown", "keypress", "keyup", "touchstart", "touchend"
208 , "touchcancel", "touchleave", "touchmove", "pointermove"
209 , "pointerdown", "pointerup", "pointerover", "pointerout"
210 , "pointerenter", "pointerleave", "pointercancel"
211 ];
213 var ignore = function(e) {
214 var evt = e ? e : window.event;
215 if (evt.stopPropagation) {
216 evt.stopPropagation();
217 }
218 if (evt.cabcelBubble !== null) {
219 evt.cabcelBubble = true;
220 }
221 if (evt.preventDefault) {
222 evt.preventDefault();
223 }
224 return false;
225 };
227 var ignoringDiv = document.getElementById("elmEventIgnorer");
228 if (!ignoringDiv) {
229 ignoringDiv = document.createElement("div");
230 ignoringDiv.id = "elmEventIgnorer";
231 ignoringDiv.style.position = "absolute";
232 ignoringDiv.style.top = "0px";
233 ignoringDiv.style.left = "0px";
234 ignoringDiv.style.width = "100%";
235 ignoringDiv.style.height = "100%";
237 for (var i = events.length; i-- ;) {
238 ignoringDiv.addEventListener(events[i], ignore, true);
239 }
240 runtime.node.appendChild(ignoringDiv);
241 }
242 }
244 function permitInputEvents(){
245 var ignoringDiv = document.getElementById("elmEventIgnorer");
246 ignoringDiv.parentNode.removeChild(ignoringDiv);
247 }
249 return {
250 debuggedModule: debuggedModule,
251 signalGraphNodes: signalGraphNodes,
252 initialSnapshot: snapshotSignalGraph(signalGraphNodes),
253 initialAsyncCallbacks: asyncCallbacks.slice(),
254 // API functions
255 clearAsyncCallbacks: clearAsyncCallbacks,
256 clearRecordedEvents: clearRecordedEvents,
257 getRecordedEventsLength: getRecordedEventsLength,
258 getRecordedEventAt: getRecordedEventAt,
259 copyRecordedEvents: copyRecordedEvents,
260 loadRecordedEvents: loadRecordedEvents,
261 clearSnapshots: clearSnapshots,
262 getSnapshotAt: getSnapshotAt,
263 snapshotOnCheckpoint: snapshotOnCheckpoint,
264 getPaused: getPaused,
265 setPaused: setPaused,
266 setContinue: setContinue,
267 tracePath: tracePath,
268 watchTracker: watchTracker
269 };
272// The debuggerHistory variable is passed in on hotswap. It represents
273// the a state of the debugger for it to assume during init. It contains
274// the paused state of the debugger, the recorded events, and the current
275// event being processed.
276function debuggerInit(debugModule, runtime, debuggerHistory /* =undefined */) {
277 var currentEventIndex = 0;
279 function resetProgram(position) {
280 var closestSnapshot = debugModule.getSnapshotAt(position);
281 debugModule.clearAsyncCallbacks();
282 restoreSnapshot(debugModule.signalGraphNodes, closestSnapshot);
283 redrawGraphics();
284 }
286 function restartProgram() {
287 pauseProgram();
288 resetProgram(0);
289 debugModule.watchTracker.clear();
290 debugModule.tracePath.clearTraces();
291 debugModule.clearRecordedEvents();
292 debugModule.clearSnapshots();
293 debugModule.setContinue(0);
294 executeCallbacks(debugModule.initialAsyncCallbacks);
295 }
297 function pauseProgram() {
298 debugModule.setPaused();
299 currentEventIndex = debugModule.getRecordedEventsLength();
300 }
302 function continueProgram() {
303 if (debugModule.getPaused())
304 {
305 var closestSnapshotIndex =
306 Math.floor(currentEventIndex / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
307 resetProgram(currentEventIndex);
308 var continueIndex = currentEventIndex;
309 currentEventIndex = closestSnapshotIndex;
310 stepTo(continueIndex);
311 debugModule.setContinue(currentEventIndex);
312 }
313 }
315 function stepTo(index) {
316 if (!debugModule.getPaused()) {
317 debugModule.setPaused();
318 resetProgram();
319 }
321 if (index < 0 || index > getMaxSteps()) {
322 throw "Index out of bounds: " + index;
323 }
325 if (index < currentEventIndex) {
326 var closestSnapshotIndex = Math.floor(index / EVENTS_PER_SAVE) * EVENTS_PER_SAVE;
327 resetProgram(index);
328 currentEventIndex = closestSnapshotIndex;
329 }
331 while (currentEventIndex < index) {
332 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
333 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
335 currentEventIndex += 1;
336 }
337 }
339 function getMaxSteps() {
340 return debugModule.getRecordedEventsLength();
341 }
343 function redrawGraphics() {
344 var main = debugModule.debuggedModule.main
345 for (var i = main.kids.length ; i-- ; ) {
346 main.kids[i].recv(runtime.timer.now(), true, main.id);
347 }
348 }
350 function getHotSwapState() {
351 var continueIndex = currentEventIndex;
352 if (!debugModule.getPaused()) {
353 continueIndex = getMaxSteps();
354 }
355 return {
356 paused: debugModule.getPaused(),
357 recordedEvents: debugModule.copyRecordedEvents(),
358 currentEventIndex: continueIndex
359 };
360 }
362 function dispose() {
363 var parentNode = runtime.node.parentNode;
364 parentNode.removeChild(debugModule.tracePath.canvas);
365 parentNode.removeChild(runtime.node);
366 }
368 if (debuggerHistory) {
369 // The problem is that we want to previous paused state. But
370 // by the time JS reaches here, the old code has been swapped out
371 // and the new modules are being generated. So we can ask the
372 // debugging console what it thinks the pause state is and go
373 // from there.
374 var paused = debuggerHistory.paused;
375 debugModule.setPaused();
376 debugModule.loadRecordedEvents(debuggerHistory.recordedEvents);
377 var index = getMaxSteps();
378 runtime.debuggerStatus.eventCounter = 0;
379 debugModule.tracePath.clearTraces();
381 // draw new trace path
382 debugModule.tracePath.startRecording();
383 while(currentEventIndex < index) {
384 var nextEvent = debugModule.getRecordedEventAt(currentEventIndex);
385 runtime.debuggerStatus.eventCounter += 1;
386 runtime.notify(nextEvent.id, nextEvent.value, nextEvent.timestep);
387 debugModule.snapshotOnCheckpoint();
388 currentEventIndex += 1;
389 }
390 debugModule.tracePath.stopRecording();
392 stepTo(debuggerHistory.currentEventIndex);
393 if (!paused) {
394 debugModule.setContinue(debuggerHistory.currentEventIndex);
395 }
396 }
398 runtime.node.parentNode.appendChild(debugModule.tracePath.canvas);
400 var elmDebugger = {
401 restart: restartProgram,
402 pause: pauseProgram,
403 kontinue: continueProgram,
404 getMaxSteps: getMaxSteps,
405 stepTo: stepTo,
406 getPaused: debugModule.getPaused,
407 getHotSwapState: getHotSwapState,
408 dispose: dispose,
409 allNodes: debugModule.signalGraphNodes,
410 watchTracker: debugModule.watchTracker
411 };
413 return elmDebugger;
416function Point(x, y) {
417 this.x = x;
418 this.y = y;
420 this.translate = function(x, y) {
421 return new Point(this.x + x, this.y + y);
422 }
424 this.equals = function(p) {
425 return this.x == p.x && this.y == p.y;
426 }
429function tracePathInit(runtime, signalGraphMain) {
430 var List = Elm.List.make(runtime);
431 var Signal = Elm.Signal.make(runtime);
432 var tracePathNode = A2(Signal.lift, graphicsUpdate, signalGraphMain);
433 var tracePathCanvas = createCanvas();
434 var tracePositions = {};
435 var recordingTraces = true;
437 function findPositions(currentScene) {
438 var positions = {};
439 function processElement(elem, offset) {
440 if (elem.element.ctor == "Custom" && elem.element.type == "Collage")
441 {
442 List.map(F2(processForm)(offset))(elem.element.model.forms);
443 }
444 }
446 function processForm(offset, form) {
447 if (form.form.ctor == "FElement")
448 {
449 processElement(form.form._0, offset.translate(form.x, -form.y));
450 }
451 if (form.form.ctor == "FGroup")
452 {
453 var newOffset = offset.translate(form.x, -form.y);
454 List.map(F2(processForm)(newOffset))(form.form._1);
455 }
456 if (form.debugTracePathId)
457 {
458 positions[form.debugTracePathId] = new Point(form.x + offset.x, -form.y + offset.y);
459 }
460 }
462 processElement(currentScene, new Point(0, 0));
463 return positions;
464 }
466 function appendPositions(positions) {
467 for (var id in positions) {
468 var pos = positions[id];
469 if (tracePositions.hasOwnProperty(id)) {
470 tracePositions[id].push(pos);
471 }
472 else {
473 tracePositions[id] = [pos];
474 }
475 if (tracePositions[id].length < runtime.debuggerStatus.eventCounter) {
476 var padCount = runtime.debuggerStatus.eventCounter - tracePositions[id].length;
477 var lastTracePosition = tracePositions[id][tracePositions[id].length - 1];
478 for (var i = padCount; i--;) {
479 tracePositions[id].push(lastTracePosition)
480 }
481 }
482 assert(tracePositions[id].length === runtime.debuggerStatus.eventCounter,
483 "We don't have a 1-1 mapping of trace positions to events");
484 }
485 }
487 function graphicsUpdate(currentScene) {
488 if (!recordingTraces) {
489 return;
490 }
492 var ctx = tracePathCanvas.getContext('2d');
493 ctx.clearRect(0, 0, tracePathCanvas.width, tracePathCanvas.height);
495 ctx.save();
496 ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
497 appendPositions(findPositions(currentScene));
498 for (var id in tracePositions)
499 {
500 ctx.beginPath();
501 var points = tracePositions[id];
502 for (var i=0; i < points.length; i++)
503 {
504 var p = points[i];
505 if (i == 0) {
506 ctx.moveTo(p.x, p.y);
507 }
508 else {
509 ctx.lineTo(p.x, p.y);
510 }
511 }
512 ctx.lineWidth = 1;
513 ctx.strokeStyle = "rgba(50, 50, 50, 0.4)";
514 ctx.stroke();
515 }
517 ctx.restore();
518 }
520 function clearTraces() {
521 tracePositions = {};
522 }
524 function stopRecording() {
525 recordingTraces = false;
526 }
528 function startRecording() {
529 recordingTraces = true;
530 }
532 function clearTracesAfter(position) {
533 var newTraces = {};
534 for (var id in tracePositions) {
535 newTraces[id] = tracePositions[id].slice(0,position);
536 }
537 tracePositions = newTraces;
538 }
540 return {
541 graphicsUpdate: graphicsUpdate,
542 canvas: tracePathCanvas,
543 clearTraces: clearTraces,
544 clearTracesAfter: clearTracesAfter,
545 stopRecording: stopRecording,
546 startRecording: startRecording
547 }
550function executeCallbacks(callbacks) {
551 callbacks.forEach(function(timer) {
552 if (!timer.executed) {
553 var func = timer.func;
554 timer.executed = true;
555 func();
556 }
557 });
560function createCanvas() {
561 var c = document.createElement('canvas');
562 c.width = window.innerWidth;
563 c.height = window.innerHeight;
564 c.style.position = "absolute";
565 c.style.top = "0";
566 c.style.left = "0";
567 c.style.pointerEvents = "none";
568 return c;
571function assert(bool, msg) {
572 if (!bool) {
573 throw "Assertion error: " + msg;
574 }
577function snapshotSignalGraph(signalGraphNodes) {
578 var nodeValues = [];
580 signalGraphNodes.forEach(function(node) {
581 nodeValues.push({ value: node.value, id: node.id });
582 });
584 return nodeValues;
585};
587function restoreSnapshot(signalGraphNodes, snapshot) {
588 assert(signalGraphNodes.length == snapshot.length,
589 "saved program state has wrong length");
590 for (var i=0; i < signalGraphNodes.length; i++) {
591 var node = signalGraphNodes[i];
592 var state = snapshot[i];
593 assert(node.id == state.id, "the nodes moved position");
595 node.value = state.value;
596 }
599function flattenSignalGraph(nodes) {
600 var nodesById = {};
602 function addAllToDict(node) {
603 nodesById[node.id] = node;
604 node.kids.forEach(addAllToDict);
605 }
606 nodes.forEach(addAllToDict);
608 var allNodes = Object.keys(nodesById).sort().map(function(key) {
609 return nodesById[key];
610 });
611 return allNodes;
612};
614}());