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