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