-
Notifications
You must be signed in to change notification settings - Fork 7
/
pytutor.js
4940 lines (4076 loc) · 238 KB
/
pytutor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Online Python Tutor
https://github.com/pgbovine/OnlinePythonTutor/
Copyright (C) Philip J. Guo ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* To import, put this at the top of your HTML page:
<!-- requirements for pytutor.js -->
<script type="text/javascript" src="js/d3.v2.min.js"></script>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery.ba-bbq.min.js"></script> <!-- for handling back button and URL hashes -->
<script type="text/javascript" src="js/jquery.jsPlumb-1.3.10-all-min.js "></script> <!-- for rendering SVG connectors
DO NOT UPGRADE ABOVE 1.3.10 OR ELSE BREAKAGE WILL OCCUR -->
<script type="text/javascript" src="js/jquery-ui-1.11.4/jquery-ui.min.js"></script> <!-- for sliders and other UI elements -->
<link type="text/css" href="js/jquery-ui-1.11.4/jquery-ui.css" rel="stylesheet" />
<!-- for annotation bubbles -->
<script type="text/javascript" src="js/jquery.qtip.min.js"></script>
<link type="text/css" href="css/jquery.qtip.css" rel="stylesheet" />
<script type="text/javascript" src="js/pytutor.js"></script>
<link rel="stylesheet" href="css/pytutor.css"/>
*/
/* Coding gotchas:
- NEVER use raw $(__) or d3.select(__) statements to select DOM elements.
ALWAYS use myViz.domRoot or myViz.domRootD3 for jQuery and D3, respectively.
Otherwise things will break in weird ways when you have more than one visualization
embedded within a webpage, due to multiple matches in the global namespace.
- always use generateID to generate unique CSS IDs, or else things will break
when multiple ExecutionVisualizer instances are displayed on a webpage
*/
var SVG_ARROW_POLYGON = '0,3 12,3 12,0 18,5 12,10 12,7 0,7';
var SVG_ARROW_HEIGHT = 10; // must match height of SVG_ARROW_POLYGON
var curVisualizerID = 1; // global to uniquely identify each ExecutionVisualizer instance
// domRootID is the string ID of the root element where to render this instance
// dat is data returned by the Python Tutor backend consisting of two fields:
// code - string of executed code
// trace - a full execution trace
//
// params is an object containing optional parameters, such as:
// jumpToEnd - if non-null, jump to the very end of execution if
// there's no error, or if there's an error, jump to the
// FIRST ENTRY with an error
// startingInstruction - the (zero-indexed) execution point to display upon rendering
// if this is set, then it *overrides* jumpToEnd
// hideOutput - hide "Program output" display
// codeDivHeight - maximum height of #pyCodeOutputDiv (in integer pixels)
// codeDivWidth - maximum width of #pyCodeOutputDiv (in integer pixels)
// editCodeBaseURL - the base URL to visit when the user clicks 'Edit code' (if null, then 'Edit code' link hidden)
// allowEditAnnotations - allow user to edit per-step annotations (default: false)
// embeddedMode - shortcut for allowEditAnnotations=false,
// codeDivWidth=this.DEFAULT_EMBEDDED_CODE_DIV_WIDTH,
// codeDivHeight=this.DEFAULT_EMBEDDED_CODE_DIV_HEIGHT
// (and don't activate keyboard shortcuts!)
// disableHeapNesting - if true, then render all heap objects at the top level (i.e., no nested objects)
// drawParentPointers - if true, then draw environment diagram parent pointers for all frames
// WARNING: there are hard-to-debug MEMORY LEAKS associated with activating this option
// textualMemoryLabels - render references using textual memory labels rather than as jsPlumb arrows.
// this is good for slow browsers or when used with disableHeapNesting
// to prevent "arrow overload"
// showOnlyOutputs - show only program outputs and NOT internal data structures
// updateOutputCallback - function to call (with 'this' as parameter)
// whenever this.updateOutput() is called
// (BEFORE rendering the output display)
// heightChangeCallback - function to call (with 'this' as parameter)
// whenever the HEIGHT of #dataViz changes
// verticalStack - if true, then stack code display ON TOP of visualization
// (else place side-by-side)
// visualizerIdOverride - override visualizer ID instead of auto-assigning it
// (BE CAREFUL ABOUT NOT HAVING DUPLICATE IDs ON THE SAME PAGE,
// OR ELSE ARROWS AND OTHER STUFF WILL GO HAYWIRE!)
// executeCodeWithRawInputFunc - function to call when you want to re-execute the given program
// with some new user input (somewhat hacky!)
// highlightLines - highlight current and previously executed lines (default: false)
// arrowLines - draw arrows pointing to current and previously executed lines (default: true)
// compactFuncLabels - render functions with a 'func' prefix and no type label
// showAllFrameLabels - display frame and parent frame labels for all functions (default: false)
// pyCrazyMode - run with Py2crazy, which provides expression-level
// granularity instead of line-level granularity (HIGHLY EXPERIMENTAL!)
// hideCode - hide the code display and show only the data structure viz
// tabularView - render a tabular view of ALL steps at once (EXPERIMENTAL)
// lang - to render labels in a style appropriate for other languages,
// and to display the proper language in langDisplayDiv:
// 'py2' for Python 2, 'py3' for Python 3, 'js' for JavaScript, 'java' for Java,
// 'ts' for TypeScript, 'ruby' for Ruby, 'c' for C, 'cpp' for C++
// [default is Python-style labels]
// debugMode - some extra debugging printouts
function ExecutionVisualizer(domRootID, dat, params) {
this.curInputCode = dat.code.main_code.rtrim(); // kill trailing spaces
this.curTrace = dat.trace;
this.sourceFiles = dat.code;
this.curFile = "";
this.DEFAULT_EMBEDDED_CODE_DIV_WIDTH = 350;
this.DEFAULT_EMBEDDED_CODE_DIV_HEIGHT = 400;
// if the final entry is raw_input or mouse_input, then trim it from the trace and
// set a flag to prompt for user input when execution advances to the
// end of the trace
if (this.curTrace.length > 0) {
var lastEntry = this.curTrace[this.curTrace.length - 1];
if (lastEntry.event == 'raw_input') {
this.promptForUserInput = true;
this.userInputPromptStr = htmlspecialchars(lastEntry.prompt);
this.curTrace.pop() // kill last entry so that it doesn't get displayed
}
else if (lastEntry.event == 'mouse_input') {
this.promptForMouseInput = true;
this.userInputPromptStr = htmlspecialchars(lastEntry.prompt);
this.curTrace.pop() // kill last entry so that it doesn't get displayed
}
}
this.curInstr = 0;
this.params = params;
if (!this.params) {
this.params = {}; // make it an empty object by default
}
var arrowLinesDef = (this.params.arrowLines !== undefined);
var highlightLinesDef = (this.params.highlightLines !== undefined);
if (!arrowLinesDef && !highlightLinesDef) {
// neither is set
this.params.highlightLines = false;
this.params.arrowLines = true;
}
else if (arrowLinesDef && highlightLinesDef) {
// both are set, so just use their set values
}
else if (arrowLinesDef) {
// only arrowLines set
this.params.highlightLines = !(this.params.arrowLines);
}
else {
// only highlightLines set
this.params.arrowLines = !(this.params.highlightLines);
}
this.compactFuncLabels = this.params.compactFuncLabels;
// audible!
if (this.params.pyCrazyMode) {
this.params.arrowLines = this.params.highlightLines = false;
}
if (this.params.visualizerIdOverride) {
this.visualizerID = this.params.visualizerIdOverride;
}
else {
// needs to be unique!
this.visualizerID = curVisualizerID;
curVisualizerID++;
}
this.leftGutterSvgInitialized = false;
this.arrowOffsetY = undefined;
this.codeRowHeight = undefined;
// avoid 'undefined' state
this.disableHeapNesting = (this.params.disableHeapNesting == true);
this.drawParentPointers = (this.params.drawParentPointers == true);
this.textualMemoryLabels = (this.params.textualMemoryLabels == true);
this.showOnlyOutputs = (this.params.showOnlyOutputs == true);
this.tabularView = (this.params.tabularView == true);
this.showAllFrameLabels = (this.params.showAllFrameLabels == true);
this.executeCodeWithRawInputFunc = this.params.executeCodeWithRawInputFunc;
// cool, we can create a separate jsPlumb instance for each visualization:
this.jsPlumbInstance = jsPlumb.getInstance({
Endpoint: ["Dot", {radius:3}],
EndpointStyles: [{fillStyle: connectorBaseColor}, {fillstyle: null} /* make right endpoint invisible */],
Anchors: ["RightMiddle", "LeftMiddle"],
PaintStyle: {lineWidth:1, strokeStyle: connectorBaseColor},
// bezier curve style:
//Connector: [ "Bezier", { curviness:15 }], /* too much 'curviness' causes lines to run together */
//Overlays: [[ "Arrow", { length: 14, width:10, foldback:0.55, location:0.35 }]],
// state machine curve style:
Connector: [ "StateMachine" ],
Overlays: [[ "Arrow", { length: 10, width:7, foldback:0.55, location:1 }]],
EndpointHoverStyles: [{fillStyle: connectorHighlightColor}, {fillstyle: null} /* make right endpoint invisible */],
HoverPaintStyle: {lineWidth: 1, strokeStyle: connectorHighlightColor},
});
// true iff trace ended prematurely since maximum instruction limit has
// been reached
var instrLimitReached = false;
// the root elements for jQuery and D3 selections, respectively.
// ALWAYS use these and never use raw $(__) or d3.select(__)
this.domRoot = $('#' + domRootID);
this.domRoot.data("vis",this); // bnm store a reference to this as div data for use later.
this.domRootD3 = d3.select('#' + domRootID);
// stick a new div.ExecutionVisualizer within domRoot and make that
// the new domRoot:
this.domRoot.html('<div class="ExecutionVisualizer"></div>');
this.domRoot = this.domRoot.find('div.ExecutionVisualizer');
this.domRootD3 = this.domRootD3.select('div.ExecutionVisualizer');
// initialize in renderPyCodeOutput()
this.codeOutputLines = null;
this.breakpoints = null; // set of execution points to set as breakpoints
this.sortedBreakpointsList = []; // sorted and synced with breakpointLines
this.classAttrsHidden = {}; // kludgy hack for 'show/hide attributes' for class objects
// API for adding a hook, created by David Pritchard
this.pytutor_hooks = {}; // keys, hook names; values, list of functions
if (this.params.lang === 'java') {
this.activateJavaFrontend(); // ohhhh yeah!
}
// how many lines does curTrace print to stdout max?
this.numStdoutLines = 0;
// go backwards from the end ... sometimes the final entry doesn't
// have an stdout
var lastStdout;
for (var i = this.curTrace.length-1; i >= 0; i--) {
lastStdout = this.curTrace[i].stdout;
if (lastStdout) {
break;
}
}
if (lastStdout) {
this.numStdoutLines = lastStdout.rtrim().split('\n').length;
}
this.try_hook("end_constructor", {myViz:this});
this.hasRendered = false;
this.render(); // go for it!
}
/* API for adding a hook, created by David Pritchard
https://github.com/daveagp
[this documentation is a bit deprecated since Philip made try_hook a
method of ExecutionVisualizer, but the general ideas remains]
An external user should call
add_pytutor_hook("hook_name_here", function(args) {...})
args will be a javascript object with several named properties;
this is meant to be similar to Python's keyword arguments.
The hooked function should return an array whose first element is a boolean:
true if it completely handled the situation (no further hooks
nor the base function should be called); false otherwise (wasn't handled).
If the hook semantically represents a function that returns something,
the second value of the returned array is that semantic return value.
E.g. for the Java visualizer a simplified version of a hook we use is:
add_pytutor_hook(
"isPrimitiveType",
function(args) {
var obj = args.obj; // unpack
if (obj instanceof Array && obj[0] == "CHAR-LITERAL")
return [true, true]; // yes we handled it, yes it's primitive
return [false]; // didn't handle it, let someone else
});
Hook callbacks can return false or undefined (i.e. no return
value) in lieu of [false].
NB: If multiple functions are added to a hook, the oldest goes first.
*/
ExecutionVisualizer.prototype.add_pytutor_hook = function(hook_name, func) {
if (this.pytutor_hooks[hook_name])
this.pytutor_hooks[hook_name].push(func);
else
this.pytutor_hooks[hook_name] = [func];
}
/*
[this documentation is a bit deprecated since Philip made try_hook a
method of ExecutionVisualizer, but the general ideas remains]
try_hook(hook_name, args): how the internal codebase invokes a hook.
args will be a javascript object with several named properties;
this is meant to be similar to Python's keyword arguments.
E.g.,
function isPrimitiveType(obj) {
var hook_result = try_hook("isPrimitiveType", {obj:obj});
if (hook_result[0]) return hook_result[1];
// go on as normal if the hook didn't handle it
Although add_pytutor_hook allows the hooked function to
return false or undefined, try_hook will always return
something with the strict format [false], [true] or [true, ...].
*/
ExecutionVisualizer.prototype.try_hook = function(hook_name, args) {
if (this.pytutor_hooks[hook_name]) {
for (var i=0; i<this.pytutor_hooks[hook_name].length; i++) {
// apply w/o "this", and pack sole arg into array as required by apply
var handled_and_result
= this.pytutor_hooks[hook_name][i].apply(null, [args]);
if (handled_and_result && handled_and_result[0])
return handled_and_result;
}
}
return [false];
}
// for managing state related to pesky jsPlumb connectors, need to reset
// before every call to renderDataStructures, or else all hell breaks
// loose. yeah, this is kludgy and stateful, but at least all of the
// relevant state gets shoved into one unified place
ExecutionVisualizer.prototype.resetJsPlumbManager = function() {
this.jsPlumbManager = {
heap_pointer_src_id: 1, // increment this to be unique for each heap_pointer_src_*
// Key: CSS ID of the div element representing the stack frame variable
// (for stack->heap connections) or heap object (for heap->heap connections)
// the format is: '<this.visualizerID>__heap_pointer_src_<src id>'
// Value: CSS ID of the div element representing the value rendered in the heap
// (the format is given by generateHeapObjID())
//
// The reason we need to prepend this.visualizerID is because jsPlumb needs
// GLOBALLY UNIQUE IDs for use as connector endpoints.
//
// TODO: jsPlumb might be able to directly take DOM elements rather
// than IDs, which makes the above point moot. But let's just stick
// with this for now until I want to majorly refactor :)
// the only elements in these sets are NEW elements to be rendered in this
// particular call to renderDataStructures.
connectionEndpointIDs: d3.map(),
heapConnectionEndpointIDs: d3.map(), // subset of connectionEndpointIDs for heap->heap connections
// analogous to connectionEndpointIDs, except for environment parent pointers
parentPointerConnectionEndpointIDs: d3.map(),
renderedHeapObjectIDs: d3.map(), // format given by generateHeapObjID()
};
}
// create a unique ID, which is often necessary so that jsPlumb doesn't get confused
// due to multiple ExecutionVisualizer instances being displayed simultaneously
ExecutionVisualizer.prototype.generateID = function(original_id) {
// (it's safer to start names with a letter rather than a number)
return 'v' + this.visualizerID + '__' + original_id;
}
// create a unique CSS ID for a heap object, which should include both
// its ID and the current step number. this is necessary if we want to
// display the same heap object at multiple execution steps.
ExecutionVisualizer.prototype.generateHeapObjID = function(objID, stepNum) {
return this.generateID('heap_object_' + objID + '_s' + stepNum);
}
ExecutionVisualizer.prototype.render = function() {
if (this.hasRendered) {
alert('ERROR: You should only call render() ONCE on an ExecutionVisualizer object.');
return;
}
var myViz = this; // to prevent confusion of 'this' inside of nested functions
var codeDisplayHTML =
'<div id="codeDisplayDiv">\
<div id="langDisplayDiv"></div>\
<div id="pyCodeOutputDiv"/>\
<div id="editCodeLinkDiv"><a id="editBtn">Edit code</a>\
<span id="liveModeSpan" style="display: none;">| <a id="editLiveModeBtn" href="#">Live programming</a></a>\
</div>\
<div id="legendDiv"/>\
<div id="executionSliderDocs"><font color="#e93f34">NEW!</font> Click on a line of code to set a breakpoint. Then use the Forward and Back buttons to jump there.</div>\
<div id="executionSlider"/>\
<div id="executionSliderFooter"/>\
<div id="vcrControls">\
<button id="jmpFirstInstr", type="button"><< First</button>\
<button id="jmpStepBack", type="button">< Back</button>\
<span id="curInstr">Step ? of ?</span>\
<button id="jmpStepFwd", type="button">Forward ></button>\
<button id="jmpLastInstr", type="button">Last >></button>\
</div>\
<div id="rawUserInputDiv">\
<span id="userInputPromptStr"/>\
<input type="text" id="raw_input_textbox" size="30"/>\
<button id="raw_input_submit_btn">Submit</button>\
</div>\
<div id="errorOutput"/>\
<div id="stepAnnotationDiv">\
<textarea class="annotationText" id="stepAnnotationEditor" cols="60" rows="3"></textarea>\
<div class="annotationText" id="stepAnnotationViewer"></div>\
</div>\
<div id="annotateLinkDiv"><button id="annotateBtn" type="button">Annotate this step</button></div>\
</div>';
var outputsHTML =
'<div id="htmlOutputDiv"></div>\
<div id="progOutputs">\
<div id="printOutputDocs">Print output (drag lower right corner to resize)</div>\n\
<textarea id="pyStdout" cols="40" rows="5" wrap="off" readonly></textarea>\
</div>';
var codeVizHTML =
'<div id="dataViz">\
<table id="stackHeapTable">\
<tr>\
<td id="stack_td">\
<div id="globals_area">\
<div id="stackHeader">Frames</div>\
</div>\
<div id="stack"></div>\
</td>\
<td id="heap_td">\
<div id="heap">\
<div id="heapHeader">Objects</div>\
</div>\
</td>\
</tr>\
</table>\
</div>';
// override
if (myViz.tabularView) {
codeVizHTML = '<div id="optTabularView"></div>';
}
var vizHeaderHTML =
'<div id="vizHeader">\
<textarea class="vizTitleText" id="vizTitleEditor" cols="60" rows="1"></textarea>\
<div class="vizTitleText" id="vizTitleViewer"></div>\
<textarea class="vizDescriptionText" id="vizDescriptionEditor" cols="75" rows="2"></textarea>\
<div class="vizDescriptionText" id="vizDescriptionViewer"></div>\
</div>';
if (this.params.verticalStack) {
this.domRoot.html(vizHeaderHTML + '<table border="0" class="visualizer"><tr><td class="vizLayoutTd" id="vizLayoutTdFirst"">' +
codeDisplayHTML + '</td></tr><tr><td class="vizLayoutTd" id="vizLayoutTdSecond">' +
codeVizHTML + '</td></tr></table>');
}
else {
this.domRoot.html(vizHeaderHTML + '<table border="0" class="visualizer"><tr><td class="vizLayoutTd" id="vizLayoutTdFirst">' +
codeDisplayHTML + '</td><td class="vizLayoutTd" id="vizLayoutTdSecond">' +
codeVizHTML + '</td></tr></table>');
}
if (this.showOnlyOutputs) {
myViz.domRoot.find('#dataViz').hide();
this.domRoot.find('#vizLayoutTdSecond').append(outputsHTML);
if (this.params.verticalStack) {
this.domRoot.find('#vizLayoutTdSecond').css('padding-top', '25px');
}
else {
this.domRoot.find('#vizLayoutTdSecond').css('padding-left', '25px');
}
}
else {
var stdoutHeight = '75px';
// heuristic for code with really small outputs
if (this.numStdoutLines <= 3) {
stdoutHeight = (18 * this.numStdoutLines) + 'px';
}
if (this.params.embeddedMode) {
stdoutHeight = '45px';
}
// position this under the code:
//this.domRoot.find('#vizLayoutTdFirst').append(outputsHTML);
// position this above visualization (started trying this on 2016-06-01)
this.domRoot.find('#vizLayoutTdSecond').prepend(outputsHTML);
// do this only after adding to DOM
this.domRoot.find('#pyStdout').width('350px')
.height(stdoutHeight)
.resizable();
}
if (this.params.arrowLines) {
this.domRoot.find('#legendDiv')
.append('<svg id="prevLegendArrowSVG"/> line that has just executed')
.append('<p style="margin-top: 4px"><svg id="curLegendArrowSVG"/> next line to execute</p>');
myViz.domRootD3.select('svg#prevLegendArrowSVG')
.append('polygon')
.attr('points', SVG_ARROW_POLYGON)
.attr('fill', lightArrowColor);
myViz.domRootD3.select('svg#curLegendArrowSVG')
.append('polygon')
.attr('points', SVG_ARROW_POLYGON)
.attr('fill', darkArrowColor);
}
else if (this.params.highlightLines) {
myViz.domRoot.find('#legendDiv')
.append('<span class="highlight-legend highlight-prev">line that has just executed</span> ')
.append('<span class="highlight-legend highlight-cur">next line to execute</span>')
}
else if (this.params.pyCrazyMode) {
myViz.domRoot.find('#legendDiv')
.append('<a href="https://github.com/pgbovine/Py2crazy">Py2crazy</a> mode!')
.append(' Stepping through (roughly) each executed expression. Color codes:<p/>')
.append('<span class="pycrazy-highlight-prev">expression that just executed</span><br/>')
.append('<span class="pycrazy-highlight-cur">next expression to execute</span>');
}
if (this.params.editCodeBaseURL) {
// kinda kludgy
var pyVer = '2'; // default
if (this.params.lang === 'js') {
pyVer = 'js';
} else if (this.params.lang === 'ts') {
pyVer = 'ts';
} else if (this.params.lang === 'java') {
pyVer = 'java';
} else if (this.params.lang === 'py3') {
pyVer = '3';
} else if (this.params.lang === 'c') {
pyVer = 'c';
} else if (this.params.lang === 'cpp') {
pyVer = 'cpp';
}
var urlStr = $.param.fragment(this.params.editCodeBaseURL,
{code: this.curInputCode, py: pyVer},
2);
this.domRoot.find('#editBtn').attr('href', urlStr);
}
else {
this.domRoot.find('#editCodeLinkDiv').hide(); // just hide for simplicity!
this.domRoot.find('#editBtn').attr('href', "#");
this.domRoot.find('#editBtn').click(function(){return false;}); // DISABLE the link!
}
if (this.params.lang !== undefined) {
if (this.params.lang === 'js') {
this.domRoot.find('#langDisplayDiv').html('JavaScript');
} else if (this.params.lang === 'ts') {
this.domRoot.find('#langDisplayDiv').html('TypeScript');
} else if (this.params.lang === 'ruby') {
this.domRoot.find('#langDisplayDiv').html('Ruby');
} else if (this.params.lang === 'java') {
this.domRoot.find('#langDisplayDiv').html('Java');
} else if (this.params.lang === 'py2') {
this.domRoot.find('#langDisplayDiv').html('Python 2.7');
} else if (this.params.lang === 'py3') {
this.domRoot.find('#langDisplayDiv').html('Python 3');
} else if (this.params.lang === 'c') {
this.domRoot.find('#langDisplayDiv').html('C (gcc 4.8, C11) <font color="#e93f34">EXPERIMENTAL!</font><br/>see <a href="https://github.com/pgbovine/opt-cpp-backend/issues" target="_blank">known bugs</a> and report to [email protected]');
} else if (this.params.lang === 'cpp') {
this.domRoot.find('#langDisplayDiv').html('C++ (gcc 4.8, C++11) <font color="#e93f34">EXPERIMENTAL!</font><br/>see <a href="https://github.com/pgbovine/opt-cpp-backend/issues" target="_blank">known bugs</a> and report to [email protected]');
} else {
this.domRoot.find('#langDisplayDiv').hide();
}
}
if (this.params.allowEditAnnotations !== undefined) {
this.allowEditAnnotations = this.params.allowEditAnnotations;
}
else {
this.allowEditAnnotations = false;
}
if (this.params.pyCrazyMode !== undefined) {
this.pyCrazyMode = this.params.pyCrazyMode;
}
else {
this.pyCrazyMode = false;
}
this.domRoot.find('#stepAnnotationEditor').hide();
if (this.params.embeddedMode) {
this.embeddedMode = true;
// nix this for now ...
//this.params.hideOutput = true; // put this before hideOutput handler
// don't override if they've already been set!
if (this.params.codeDivWidth === undefined) {
this.params.codeDivWidth = this.DEFAULT_EMBEDDED_CODE_DIV_WIDTH;
}
if (this.params.codeDivHeight === undefined) {
this.params.codeDivHeight = this.DEFAULT_EMBEDDED_CODE_DIV_HEIGHT;
}
this.allowEditAnnotations = false;
// add an extra label to link back to the main site, so that viewers
// on the embedded page know that they're seeing an OPT visualization
this.domRoot.find('#codeDisplayDiv').append('<div style="font-size: 8pt; margin-bottom: 20px;">Visualized using <a href="http://pythontutor.com" target="_blank" style="color: #3D58A2;">Online Python Tutor</a> by <a href="http://www.pgbovine.net/" target="_blank" style="color: #3D58A2;">Philip Guo</a></div>');
myViz.domRoot.find('#executionSliderDocs').hide(); // cut out extraneous docs
}
myViz.editAnnotationMode = false;
if (this.allowEditAnnotations) {
var ab = this.domRoot.find('#annotateBtn');
ab.click(function() {
if (myViz.editAnnotationMode) {
myViz.enterViewAnnotationsMode();
myViz.domRoot.find("#jmpFirstInstr,#jmpLastInstr,#jmpStepBack,#jmpStepFwd,#executionSlider,#editCodeLinkDiv,#stepAnnotationViewer").show();
myViz.domRoot.find('#stepAnnotationEditor').hide();
ab.html('Annotate this step');
}
else {
myViz.enterEditAnnotationsMode();
myViz.domRoot.find("#jmpFirstInstr,#jmpLastInstr,#jmpStepBack,#jmpStepFwd,#executionSlider,#editCodeLinkDiv,#stepAnnotationViewer").hide();
myViz.domRoot.find('#stepAnnotationEditor').show();
ab.html('Done annotating');
}
});
}
else {
this.domRoot.find('#annotateBtn').hide();
}
// not enough room for these extra buttons ...
if (this.params.codeDivWidth &&
this.params.codeDivWidth < 470) {
this.domRoot.find('#jmpFirstInstr').hide();
this.domRoot.find('#jmpLastInstr').hide();
}
if (this.params.codeDivWidth) {
// set width once
this.domRoot.find('#codeDisplayDiv').width(this.params.codeDivWidth);
// it will propagate to the slider
//this.domRoot.find("#pyStdout").css("width", this.params.codeDivWidth - 20 /* wee tweaks */);
}
// enable left-right draggable pane resizer (originally from David Pritchard)
this.domRoot.find('#codeDisplayDiv').resizable({
handles: "e",
minWidth: 250, //otherwise looks really goofy
resize: function(event, ui) { // old name: syncStdoutWidth, now not appropriate
// resize stdout box in unison
//myViz.domRoot.find("#pyStdout").css("width", $(this).width() - 20 /* wee tweaks */);
myViz.domRoot.find("#codeDisplayDiv").css("height", "auto"); // redetermine height if necessary
myViz.renderSliderBreakpoints(); // update breakpoint display accordingly on resize
if (myViz.params.updateOutputCallback) // report size change
myViz.params.updateOutputCallback(this);
}});
if (this.params.codeDivHeight) {
this.domRoot.find('#pyCodeOutputDiv')
.css('max-height', this.params.codeDivHeight + 'px');
}
// create a persistent globals frame
// (note that we need to keep #globals_area separate from #stack for d3 to work its magic)
this.domRoot.find("#globals_area").append('<div class="stackFrame" id="'
+ myViz.generateID('globals') + '"><div id="' + myViz.generateID('globals_header')
+ '" class="stackFrameHeader">' + this.getRealLabel('Global frame') + '</div><table class="stackFrameVarTable" id="'
+ myViz.generateID('global_table') + '"></table></div>');
if (this.params.hideOutput) {
this.domRoot.find('#progOutputs').hide();
}
this.domRoot.find("#jmpFirstInstr").click(function() {
myViz.renderStep(0);
});
this.domRoot.find("#jmpLastInstr").click(function() {
myViz.renderStep(myViz.curTrace.length - 1);
});
this.domRoot.find("#jmpStepBack").click(function() {
myViz.stepBack();
});
this.domRoot.find("#jmpStepFwd").click(function() {
myViz.stepForward();
});
// disable controls initially ...
this.domRoot.find("#vcrControls #jmpFirstInstr").attr("disabled", true);
this.domRoot.find("#vcrControls #jmpStepBack").attr("disabled", true);
this.domRoot.find("#vcrControls #jmpStepFwd").attr("disabled", true);
this.domRoot.find("#vcrControls #jmpLastInstr").attr("disabled", true);
// must postprocess curTrace prior to running precomputeCurTraceLayouts() ...
var lastEntry = this.curTrace[this.curTrace.length - 1];
this.instrLimitReached = (lastEntry.event == 'instruction_limit_reached');
if (this.instrLimitReached) {
this.curTrace.pop() // kill last entry
var warningMsg = lastEntry.exception_msg;
this.instrLimitReachedWarningMsg = warningMsg;
myViz.domRoot.find("#errorOutput").html(htmlspecialchars(warningMsg));
myViz.domRoot.find("#errorOutput").show();
}
// set up slider after postprocessing curTrace
var sliderDiv = this.domRoot.find('#executionSlider');
sliderDiv.slider({min: 0, max: this.curTrace.length - 1, step: 1});
//disable keyboard actions on the slider itself (to prevent double-firing of events)
sliderDiv.find(".ui-slider-handle").unbind('keydown');
// make skinnier and taller
sliderDiv.find(".ui-slider-handle").css('width', '0.8em');
sliderDiv.find(".ui-slider-handle").css('height', '1.4em');
this.domRoot.find(".ui-widget-content").css('font-size', '0.9em');
this.domRoot.find('#executionSlider').bind('slide', function(evt, ui) {
// this is SUPER subtle. if this value was changed programmatically,
// then evt.originalEvent will be undefined. however, if this value
// was changed by a user-initiated event, then this code should be
// executed ...
if (evt.originalEvent) {
myViz.renderStep(ui.value);
}
});
if (this.params.startingInstruction) {
this.params.jumpToEnd = false; // override! make sure to handle FIRST
// weird special case for something like:
// e=raw_input(raw_input("Enter something:"))
if (this.params.startingInstruction == this.curTrace.length) {
this.params.startingInstruction--;
}
// fail-soft with out-of-bounds startingInstruction values:
if (this.params.startingInstruction < 0) {
this.params.startingInstruction = 0;
}
if (this.params.startingInstruction >= this.curTrace.length) {
this.params.startingInstruction = this.curTrace.length - 1;
}
assert(0 <= this.params.startingInstruction &&
this.params.startingInstruction < this.curTrace.length);
this.curInstr = this.params.startingInstruction;
}
if (this.params.jumpToEnd) {
var firstErrorStep = -1;
for (var i = 0; i < this.curTrace.length; i++) {
var e = this.curTrace[i];
if (e.event == 'exception' || e.event == 'uncaught_exception') {
firstErrorStep = i;
break;
}
}
// set to first error step if relevant since that's more informative
// than simply jumping to the very end
if (firstErrorStep >= 0) {
this.curInstr = firstErrorStep;
} else {
this.curInstr = this.curTrace.length - 1;
}
}
if (this.params.hideCode) {
this.domRoot.find('#vizLayoutTdFirst').hide(); // gigantic hack!
}
this.try_hook("end_render", {myViz:this});
this.precomputeCurTraceLayouts();
if (!this.params.hideCode) {
this.renderPyCodeOutput();
}
// EXPERIMENTAL!
if (this.tabularView) {
this.renderTabularView();
// scroll vizLayoutTdFirst down to always align with the vertical
// scrolling ...
$(window).scroll(function() {
var codePane = myViz.domRoot.find('#vizLayoutTdFirst');
var docScrollTop = $(document).scrollTop();
var offset = codePane.offset().top;
var delta = docScrollTop - offset;
if (delta < 0) {
delta = 0;
}
// don't scroll past the bottom of the optTabularView table:
var optTable = myViz.domRoot.find('#optTabularView');
var optTableBottom = optTable.height() + optTable.offset().top;
var codeDisplayHeight = myViz.domRoot.find('#codeDisplayDiv').height();
if (delta - offset < optTableBottom - codeDisplayHeight) {
codePane.css('padding-top', delta);
}
});
}
var ruiDiv = myViz.domRoot.find('#rawUserInputDiv');
ruiDiv.find('#userInputPromptStr').html(myViz.userInputPromptStr);
ruiDiv.find('#raw_input_submit_btn').click(function() {
var userInput = ruiDiv.find('#raw_input_textbox').val();
// advance instruction count by 1 to get to the NEXT instruction
myViz.executeCodeWithRawInputFunc(userInput, myViz.curInstr + 1);
});
this.updateOutput();
this.hasRendered = true;
}
ExecutionVisualizer.prototype.showVizHeaderViewMode = function() {
var titleVal = this.domRoot.find('#vizTitleEditor').val().trim();
var descVal = this.domRoot.find('#vizDescriptionEditor').val().trim();
this.domRoot.find('#vizTitleEditor,#vizDescriptionEditor').hide();
if (!titleVal && !descVal) {
this.domRoot.find('#vizHeader').hide();
}
else {
this.domRoot.find('#vizHeader,#vizTitleViewer,#vizDescriptionViewer').show();
if (titleVal) {
this.domRoot.find('#vizTitleViewer').html(htmlsanitize(titleVal)); // help prevent HTML/JS injection attacks
}
if (descVal) {
this.domRoot.find('#vizDescriptionViewer').html(htmlsanitize(descVal)); // help prevent HTML/JS injection attacks
}
}
}
ExecutionVisualizer.prototype.showVizHeaderEditMode = function() {
this.domRoot.find('#vizHeader').show();
this.domRoot.find('#vizTitleViewer,#vizDescriptionViewer').hide();
this.domRoot.find('#vizTitleEditor,#vizDescriptionEditor').show();
}
ExecutionVisualizer.prototype.destroyAllAnnotationBubbles = function() {
var myViz = this;
// hopefully destroys all old bubbles and reclaims their memory
if (myViz.allAnnotationBubbles) {
$.each(myViz.allAnnotationBubbles, function(i, e) {
e.destroyQTip();
});
}
// remove this handler as well!
this.domRoot.find('#pyCodeOutputDiv').unbind('scroll');
myViz.allAnnotationBubbles = null;
}
ExecutionVisualizer.prototype.initStepAnnotation = function() {
var curEntry = this.curTrace[this.curInstr];
if (curEntry.stepAnnotation) {
this.domRoot.find("#stepAnnotationViewer").html(htmlsanitize(curEntry.stepAnnotation)); // help prevent HTML/JS injection attacks
this.domRoot.find("#stepAnnotationEditor").val(curEntry.stepAnnotation);
}
else {
this.domRoot.find("#stepAnnotationViewer").html('');
this.domRoot.find("#stepAnnotationEditor").val('');
}
}
ExecutionVisualizer.prototype.initAllAnnotationBubbles = function() {
var myViz = this;
// TODO: check for memory leaks
//console.log('initAllAnnotationBubbles');
myViz.destroyAllAnnotationBubbles();
var codelineIDs = [];
$.each(this.domRoot.find('#pyCodeOutput .cod'), function(i, e) {
codelineIDs.push($(e).attr('id'));
});
var heapObjectIDs = [];
$.each(this.domRoot.find('.heapObject'), function(i, e) {
heapObjectIDs.push($(e).attr('id'));
});
var variableIDs = [];
$.each(this.domRoot.find('.variableTr'), function(i, e) {
variableIDs.push($(e).attr('id'));
});
var frameIDs = [];
$.each(this.domRoot.find('.stackFrame'), function(i, e) {
frameIDs.push($(e).attr('id'));
});
myViz.allAnnotationBubbles = [];
$.each(codelineIDs, function(i,e) {myViz.allAnnotationBubbles.push(new AnnotationBubble(myViz, 'codeline', e));});
$.each(heapObjectIDs, function(i,e) {myViz.allAnnotationBubbles.push(new AnnotationBubble(myViz, 'object', e));});
$.each(variableIDs, function(i,e) {myViz.allAnnotationBubbles.push(new AnnotationBubble(myViz, 'variable', e));});
$.each(frameIDs, function(i,e) {myViz.allAnnotationBubbles.push(new AnnotationBubble(myViz, 'frame', e));});
this.domRoot.find('#pyCodeOutputDiv').scroll(function() {
$.each(myViz.allAnnotationBubbles, function(i, e) {
if (e.type == 'codeline') {
e.redrawCodelineBubble();
}
});
});
//console.log('initAllAnnotationBubbles', myViz.allAnnotationBubbles.length);
}
ExecutionVisualizer.prototype.enterViewAnnotationsMode = function() {
this.editAnnotationMode = false;
var curEntry = this.curTrace[this.curInstr];
// TODO: check for memory leaks!!!
var myViz = this;
if (!myViz.allAnnotationBubbles) {
if (curEntry.bubbleAnnotations) {
// If there is an existing annotations object, then initiate all annotations bubbles
// and display them in 'View' mode
myViz.initAllAnnotationBubbles();
$.each(myViz.allAnnotationBubbles, function(i, e) {
var txt = curEntry.bubbleAnnotations[e.domID];
if (txt) {
e.preseedText(txt);
}
});
}
}