-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathjv-frontend.js
More file actions
executable file
·570 lines (464 loc) · 19.5 KB
/
jv-frontend.js
File metadata and controls
executable file
·570 lines (464 loc) · 19.5 KB
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
/*
This file, jv-frontend.js, is based on
opt-frontend.js from the Online Python Tutor.
Changes made by David Pritchard (daveagp@gmail.com);
see README for more details.
Summary of changes made:
- uses Java, not Python
- uses CodeMirror latest version
- lazier approach for loading examples
==== Header from opt-frontend.js ====
Online Python Tutor
https://github.com/pgbovine/OnlinePythonTutor/
Copyright (C) 2010-2013 Philip J. Guo (philip@pgbovine.net)
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.
*/
// Pre-reqs: pytutor.js and jquery.ba-bbq.min.js should be imported BEFORE this file
// backend scripts to execute (Python 2 and 3 variants, if available)
//var python2_backend_script = 'web_exec_py2.py';
//var python3_backend_script = 'web_exec_py3.py';
// uncomment below if you're running on Google App Engine using the built-in app.yaml
var python2_backend_script = 'exec';
var python3_backend_script = null;
var java_iframe_url = './iframe-embed.html';
var java_backend_script = './java_safe_ram_maketrace.php';
var appMode = 'edit'; // 'edit', 'display', or 'display_no_frills'
var preseededCode = null; // if you passed in a 'code=<code string>' in the URL, then set this var
var preseededCurInstr = null; // if you passed in a 'curInstr=<number>' in the URL, then set this var
var rawInputLst = []; // a list of strings inputted by the user in response to raw_input or mouse_input events
var myVisualizer = null; // singleton ExecutionVisualizer instance
// set keyboard bindings
$(document).keydown(function(k) {
//if (!keyStuckDown) {
if (k.keyCode == 37 && myVisualizer != null) { // left arrow
if (myVisualizer.stepBack()) {
k.preventDefault(); // don't horizontally scroll the display
keyStuckDown = true;
}
}
else if (k.keyCode == 39 && myVisualizer != null) { // right arrow
if (myVisualizer.stepForward()) {
k.preventDefault(); // don't horizontally scroll the display
keyStuckDown = true;
}
}
//}
});
$(document).keyup(function(k) {
keyStuckDown = false;
});
var keyStuckDown = false;
function enterEditMode() {
$.bbq.pushState({ mode: 'edit' }, 2 /* completely override other hash strings to keep URL clean */);
}
function enterDisplayNoFrillsMode() {
$.bbq.pushState({ mode: 'display_no_frills' }, 2 /* completely override other hash strings to keep URL clean */);
}
var pyInputCodeMirror; // CodeMirror object that contains the input text
function setCodeMirrorVal(dat) {
if (dat.indexOf("/*viz_options")>-1) {
var viz_options = dat.substring(dat.indexOf("/*viz_options")+13);
dat = dat.substring(0, dat.indexOf("/*viz_options"));
viz_options = viz_options.replace(/\s*(\*\/)?\s*$/, ""); // remove trailing spaces, */
viz_options = JSON.parse(viz_options);
setOptions(function(key){ return viz_options[key] });
}
else {
setOptions(function(key){ return undefined;});
}
pyInputCodeMirror.setValue(dat.rtrim());
$('#urlOutput,#embedCodeOutput').val('');
// also scroll to top to make the UI more usable on smaller monitors
$(document).scrollTop(0);
}
function getUserArgs() {
return $.map($('#argslist .arg input'), function(e){return e.value;});
}
function getUserStdin() {
return window.stdinarea.value;
}
$(document).ready(function() {
$("#embedLinkDiv").hide();
pyInputCodeMirror = CodeMirror(document.getElementById('codeInputPane'), {
mode: 'text/x-java',
lineNumbers: true,
matchBrackets: true,
tabSize: 3,
indentUnit: 3,
extraKeys: {
Tab: function(cm) {
var lo = cm.getCursor("start").line;
var hi = cm.getCursor("end").line;
for (var i = lo; i <= hi; i++)
cm.indentLine(i, "smart");
cm.setCursor(cm.getCursor("end"));
return true;
},
F5 : function() {return false;}
}
});
// setCodeMirrorVal(
// "public class ClassNameHere {\n" +
// " public static void main(String[] args) {\n \n }\n}");
pyInputCodeMirror.setSize(null, 'auto');
// be friendly to the browser's forward and back buttons
// thanks to http://benalman.com/projects/jquery-bbq-plugin/
$(window).bind("hashchange", function(e) {
appMode = $.bbq.getState('mode'); // assign this to the GLOBAL appMode
if (appMode === undefined || appMode == 'edit') {
$("#pyInputPane").show();
$("#pyOutputPane").hide();
$("#embedLinkDiv").hide();
// destroy all annotation bubbles (NB: kludgy)
if (myVisualizer) {
myVisualizer.destroyAllAnnotationBubbles();
}
}
else if (appMode == 'display') {
$("#pyInputPane").hide();
$("#pyOutputPane").show();
$("#embedLinkDiv").show();
$('#executeBtn').html("Visualize execution");
$('#executeBtn').attr('disabled', false);
// do this AFTER making #pyOutputPane visible, or else
// jsPlumb connectors won't render properly
myVisualizer.updateOutput();
// customize edit button click functionality AFTER rendering (NB: awkward!)
$('#pyOutputPane #editCodeLinkDiv').show();
$('#pyOutputPane #editBtn').click(function() {
$("#iframeURL-div").hide();
enterEditMode();
});
}
else if (appMode == 'display_no_frills') {
$("#pyInputPane").hide();
$("#pyOutputPane").show();
$("#embedLinkDiv").show();
}
else {
assert(false);
}
$('#urlOutput,#embedCodeOutput').val(''); // clear to avoid stale values
});
function executeCode(forceStartingInstr) {
var backend_script = java_backend_script;
/* if ($('#pythonVersionSelector').val() == '2') {
backend_script = python2_backend_script;
}
else if ($('#pythonVersionSelector').val() == '3') {
backend_script = python3_backend_script;
}
if (!backend_script) {
alert('Error: This server is not configured to run Python ' + $('#pythonVersionSelector').val());
return;
}*/
$('#executeBtn').html("Please wait ... processing your code");
$('#executeBtn').attr('disabled', true);
$("#pyOutputPane").hide();
$("#embedLinkDiv").hide();
var java_backend_options = {};
java_backend_options.showStringsAsValues = !$('#showStringsAsObjects').is(':checked');
java_backend_options.showAllFields = $('#showAllFields').is(':checked');
var package = {
user_script : pyInputCodeMirror.getValue(),
options: java_backend_options,
args: getUserArgs(),
stdin: getUserStdin()
};
$("#iframeURL-div").show();
// USC Wordpress approach from Spring '15
// $("#iframeURL").html('[visualize]'+encodeURIComponent(JSON.stringify(package))+'[/visualize]');
// but this is simpler assuming you are editing raw html:
var a = document.createElement('a');
// absolutize iframe-embed.html
a.href = java_iframe_url;
$('#iframeURL').val('<iframe style="width: 100%; height: 480;" src="'+a.href
+'?faking_cpp='+(faking_cpp?'true':'false')
+'#data='+encodeURIComponent(JSON.stringify(package))
+'&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=0&resizeContainer=true&highlightLines=true&rightStdout=true" '
+'frameborder="0" scrolling="no"></iframe>');
$.ajax({url: backend_script,
data: {data : JSON.stringify(package)},
/*,
raw_input_json: rawInputLst.length > 0 ? JSON.stringify(rawInputLst) : '',
options_json: JSON.stringify(options)*/
dataType: "json",
timeout: pytutor_ajax_timeout_millis, //ms
error: ajaxErrorHandler,
success: function(dataFromBackend) {
console.log(["Data from backend:", dataFromBackend]);
var trace = dataFromBackend.trace;
// don't enter visualize mode if there are killer errors:
if (!trace ||
(trace.length == 0) ||
(trace[trace.length - 1].event == 'uncaught_exception')) {
if (trace.length == 1) {
var errorLineNo = trace[0].line - 1; /* CodeMirror lines are zero-indexed */
if (errorLineNo !== undefined) {
// highlight the faulting line in pyInputCodeMirror
pyInputCodeMirror.focus();
pyInputCodeMirror.setCursor(errorLineNo, 0);
var marked = pyInputCodeMirror.addLineClass(errorLineNo, null, 'errorLine');
//console.log(marked);
var hook = function(marked) { return function() {
pyInputCodeMirror.removeLineClass(marked, null, 'errorLine'); // reset line back to normal
pyInputCodeMirror.off('change', hook); // cancel
}} (marked);
pyInputCodeMirror.on('change', hook);
}
alert(trace[0].exception_msg);
}
else if (trace[trace.length - 1].exception_msg) {
alert(trace[trace.length - 1].exception_msg);
}
else {
alert("Whoa, unknown error! Reload to try again, or report a bug to daveagp@gmail.com\n\n(Click the 'Generate URL' button to include a unique URL in your email bug report.)");
}
$('#executeBtn').html("Visualize execution");
$('#executeBtn').attr('disabled', false);
}
else {
var startingInstruction = 0;
// only do this at most ONCE, and then clear out preseededCurInstr
if (preseededCurInstr && preseededCurInstr < trace.length) { // NOP anyways if preseededCurInstr is 0
startingInstruction = preseededCurInstr;
preseededCurInstr = null;
}
// forceStartingInstr overrides everything else
if (forceStartingInstr !== undefined) {
startingInstruction = forceStartingInstr;
}
var frontend_options =
{startingInstruction: startingInstruction,
updateOutputCallback:
function() {
$('#urlOutput,#embedCodeOutput').val('');
},
disableHeapNesting: $('#disableNesting').is(':checked'),
drawParentPointers: false,
textualMemoryLabels: false,
showOnlyOutputs: false,
executeCodeWithRawInputFunc: executeCodeWithRawInput,
//allowEditAnnotations: true,
resizeLeftRight: true,
highlightLines: true,
stdin: getUserStdin(),
};
myVisualizer = new ExecutionVisualizer('pyOutputPane',
dataFromBackend,
frontend_options);
// also scroll to top to make the UI more usable on smaller monitors
$(document).scrollTop(0);
$.bbq.pushState({ mode: 'display' }, 2 /* completely override other hash strings to keep URL clean */);
}
}});
}
function executeCodeFromScratch() {
// reset these globals
rawInputLst = [];
executeCode();
}
function executeCodeWithRawInput(rawInputStr, curInstr) {
enterDisplayNoFrillsMode();
// set some globals
rawInputLst.push(rawInputStr);
executeCode(curInstr);
}
$("#executeBtn").attr('disabled', false);
$("#executeBtn").click(executeCodeFromScratch);
// canned examples
var examplesDir = "./example-code/";
var exampleCallback = function(url) {
return function() {$.get(url, setCodeMirrorVal); return false;};
}
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
// populate examples
var done = {};
for (var i=0; i<topics.length; i++) {
if (i != 0) $("#examplesHolder").append("<br>");
$("#examplesHolder").append(topics[i][0]);
$("#examplesHolder").append(" examples");
for (var j=0; j<topics[i][1].length; j++) {
$("#examplesHolder").append(" | ");
filename = topics[i][1][j];
var newItem = $("<a href='#'>" + filename + "</a>");
newItem.click(exampleCallback(examplesDir + filename + ".java"));
$("#examplesHolder").append(newItem);
done[filename] = true;
}
}
var populate_misc = function(index_page) {
$("#examplesHolder").append("<br>misc examples");
var first = true;
$(index_page).find("td > a").each(function() {
var filename = $(this).attr("href");
if (filename.endsWith(".java")) { // an example
filename = filename.substring(0, filename.length-5);
if (done[filename]) return;
var newItem = $("<a href='#'>" + filename + "</a>");
newItem.click(exampleCallback(examplesDir + filename + ".java"));
$("#examplesHolder").append(" | ");
$("#examplesHolder").append(newItem);
}
});
};
// fetch uncategorized
$.ajax({
url: "./example-code/",
success: populate_misc,
error: function() {console.log("warning: couldn't read examples directory index");}
});
// handle hash parameters passed in when loading the page
preseededCode = $.bbq.getState('code');
if (preseededCode) {
setCodeMirrorVal(preseededCode);
}
else {
// select a canned example on start-up:
exampleCallback(examplesDir+"(Default).java")();
}
var loadExample = $.bbq.getState('sampleFile');
if (loadExample) {
//console.log(loadExample);
if (loadExample.match(/[a-zA-Z]+/))
exampleCallback(examplesDir+loadExample+".java")();
}
// args, and only args, is parsed specially
setOptions(function(key){
var value = $.bbq.getState(key);
if (key=='args' && value != undefined) value = JSON.parse(value);
return value;
});
// log a generic AJAX error handler
var ajaxErrorHandler = function(jqXHR, textStatus, errorThrown) {
var errinfo = "textStatus: " + textStatus + "\nerrorThrown: " + errorThrown + "\nServer reply: " + jqXHR.responseText;
alert("Server error. Report a bug to daveagp@gmail.com (click 'Generate URL' and include it). Debug info (also copied to console):\n" + errinfo);
console.log(errinfo);
$('#executeBtn').html("Visualize execution");
$('#executeBtn').attr('disabled', false);
};
// $(document).ajaxError(ajaxErrorHandler);
// redraw connector arrows on window resize
$(window).resize(function() {
if (appMode == 'display') {
myVisualizer.redrawConnectors();
}
});
$('#genUrlBtn').bind('click', function() {
var myArgs = {code: pyInputCodeMirror.getValue(),
mode: appMode
/*
, cumulative: $('#cumulativeModeSelector').val(),
heapPrimitives: $('#heapPrimitivesSelector').val(),
drawParentPointers: $('#drawParentPointerSelector').val(),
textReferences: $('#textualMemoryLabelsSelector').val(),
showOnlyOutputs: $('#showOnlyOutputsSelector').val(),
py: $('#pythonVersionSelector').val()
*/};
// Set these to a value which coerces to true
if ($('#showStringsAsObjects').is(':checked'))
myArgs.showStringsAsObjects=1;
if ($('#showAllFields').is(':checked'))
myArgs.showAllFields=1;
if ($('#disableNesting').is(':checked'))
myArgs.disableNesting=1;
if ($('#verticalLists').is(':checked'))
myArgs.verticalLists=1;
if (getUserArgs().length > 0)
myArgs.args = JSON.stringify(getUserArgs());
if (getUserStdin().length > 0)
myArgs.stdin = getUserStdin();
if (appMode == 'display') {
myArgs.curInstr = myVisualizer.curInstr;
}
var urlStr = $.param.fragment(window.location.href, myArgs, 2 /* clobber all */);
$('#urlOutput').val(urlStr);
});
$('#genEmbedBtn').bind('click', function() {
assert(appMode == 'display');
var myArgs = {code: pyInputCodeMirror.getValue(),
cumulative: $('#cumulativeModeSelector').val(),
heapPrimitives: $('#heapPrimitivesSelector').val(),
drawParentPointers: $('#drawParentPointerSelector').val(),
textReferences: $('#textualMemoryLabelsSelector').val(),
showOnlyOutputs: $('#showOnlyOutputsSelector').val(),
py: $('#pythonVersionSelector').val(),
curInstr: myVisualizer.curInstr,
};
var embedUrlStr = $.param.fragment('http://pythontutor.com/iframe-embed.html', myArgs, 2 /* clobber all */);
var iframeStr = '<iframe width="800" height="500" frameborder="0" src="' + embedUrlStr + '"> </iframe>';
$('#embedCodeOutput').val(iframeStr);
});
});
var setOptions = function(lookup_function) {
var userArgs = lookup_function('args');
if (userArgs) {
if (!userArgs instanceof Array)
userArgs = JSON.parse(userArgs);
for (var i=0; i<userArgs.length; i++)
addArg(userArgs[i]);
}
else {
$('span.arg').remove();
}
var userStdin = lookup_function('stdin');
if (userStdin) {
$('#stdin-xdiv').show();
$('#stdinarea').val(userStdin);
}
else {
$('#stdin-xdiv').hide();
$('#stdinarea').val('');
}
// parse options
var optionNames = ['showStringsAsObjects', 'showAllFields', 'disableNesting', 'verticalLists'];
var someOption = false;
for (var i=0; i<optionNames.length; i++) {
var optionName = optionNames[i];
var value = lookup_function(optionName) ? true : false; // normalize
$('#'+optionName).prop('checked', value);
someOption |= value;
}
if (someOption)
$('#options').show();
else
$('#options').hide();
appMode = lookup_function('mode'); // assign this to the GLOBAL appMode
if ((appMode == "display") && preseededCode /* jump to display only with pre-seeded code */) {
preseededCurInstr = Number(lookup_function('curInstr'));
$("#executeBtn").trigger('click');
}
else {
if (appMode === undefined) {
// default mode is 'edit', don't trigger a "hashchange" event
appMode = 'edit';
}
else {
// fail-soft by killing all passed-in hashes and triggering a "hashchange"
// event, which will then go to 'edit' mode
$.bbq.removeState();
}
}
};
var oldSE = structurallyEquivalent;
var structurallyEquivalent = function(obj1, obj2) {
if ($('#verticalLists').is(':checked')) return false;
return oldSE(obj1, obj2);
}