Repository navigation
Expand file tree
/
Copy pathopt-frontend-common.js
More file actions
2237 lines (1864 loc) · 78.9 KB
/
Copy pathopt-frontend-common.js
File metadata and controls
2237 lines (1864 loc) · 78.9 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
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 (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.
*/
// include this file BEFORE any OPT frontend file
// backend scripts to execute (Python 2 and 3 variants, if available)
// make two copies of ../web_exec.py and give them the following names,
// then change the first line (starting with #!) to the proper version
// of the Python interpreter (i.e., Python 2 or Python 3).
// Note that your hosting provider might have stringent rules for what
// kind of scripts are allowed to execute. For instance, my provider
// (Webfaction) seems to let scripts execute only if permissions are
// something like:
// -rwxr-xr-x 1 pgbovine pgbovine 2.5K Jul 5 22:46 web_exec_py2.py*
// (most notably, only the owner of the file should have write
// permissions)
//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 = 'exec';
// KRAZY experimental KODE!!! Use a custom hacked CPython interpreter
var python2crazy_backend_script = 'web_exec_py2-crazy.py';
// On Google App Engine, simply run dev_appserver.py with the
// crazy custom py2crazy CPython interpreter to get 2crazy mode
//var python2crazy_backend_script = 'exec';
// empty dummy just to do logging on the Apache's server
var js_backend_script = 'web_exec_js.py';
var ts_backend_script = 'web_exec_ts.py';
var java_backend_script = 'web_exec_java.py';
var ruby_backend_script = 'web_exec_ruby.py';
var c_backend_script = 'web_exec_c.py';
var cpp_backend_script = 'web_exec_cpp.py';
// this is customized to my own Linode server:
// these are the REAL endpoints, accessed via jsonp. code is in ../../v4-cokapi/
if (window.location.protocol === 'https:') {
// my certificate for https is registered via cokapi.com, so use it for now:
var JS_JSONP_ENDPOINT = 'https://cokapi.com:8001/exec_js_jsonp';
var TS_JSONP_ENDPOINT = 'https://cokapi.com:8001/exec_ts_jsonp';
var JAVA_JSONP_ENDPOINT = 'https://cokapi.com:8001/exec_java_jsonp';
var RUBY_JSONP_ENDPOINT = 'https://cokapi.com:8001/exec_ruby_jsonp';
var C_JSONP_ENDPOINT = 'https://cokapi.com:8001/exec_c_jsonp';
var CPP_JSONP_ENDPOINT = 'https://cokapi.com:8001/exec_cpp_jsonp';
} else {
var JS_JSONP_ENDPOINT = 'http://104.237.139.253:3000/exec_js_jsonp'; // for deployment
var TS_JSONP_ENDPOINT = 'http://104.237.139.253:3000/exec_ts_jsonp'; // for deployment
var JAVA_JSONP_ENDPOINT = 'http://104.237.139.253:3000/exec_java_jsonp'; // for deployment
var RUBY_JSONP_ENDPOINT = 'http://104.237.139.253:3000/exec_ruby_jsonp'; // for deployment
var C_JSONP_ENDPOINT = 'http://104.237.139.253:3000/exec_c_jsonp'; // for deployment
var CPP_JSONP_ENDPOINT = 'http://104.237.139.253:3000/exec_cpp_jsonp'; // for deployment
}
function langToBackendScript(lang) {
var backend_script = null;
if (lang == '2') {
backend_script = python2_backend_script;
} else if (lang == '3') {
backend_script = python3_backend_script;
} else if (lang == '2crazy') {
backend_script = python2crazy_backend_script;
} else if (lang == 'js') {
backend_script = js_backend_script;
} else if (lang == 'ts') {
backend_script = ts_backend_script;
} else if (lang == 'ruby') {
backend_script = ruby_backend_script;
} else if (lang == 'java') {
backend_script = java_backend_script;
} else if (lang == 'c') {
backend_script = c_backend_script;
} else if (lang == 'cpp') {
backend_script = cpp_backend_script;
}
assert(backend_script);
return backend_script;
}
var domain = "http://pythontutor.com/"; // for deployment
var isExecutingCode = false; // nasty, nasty global
var appMode = 'edit'; // 'edit' or 'display'. also support
// 'visualize' for backward compatibility (same as 'display')
var pyInputCodeMirror; // CodeMirror object that contains the input code
var pyInputAceEditor; // Ace editor object that contains the input code
var useCodeMirror = false; // true -> use CodeMirror, false -> use Ace
// a list of previous consecutive executions with "compile"-time exceptions
var prevExecutionExceptionObjLst = [];
var CODE_SNAPSHOT_DEBOUNCE_MS = 1000;
// From http://stackoverflow.com/a/8809472
function generateUUID(){
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x7|0x8)).toString(16);
});
return uuid;
};
var sessionUUID = generateUUID(); // remains constant throughout one page load ("session")
// OMG nasty wtf?!?
// From: http://stackoverflow.com/questions/21159301/quotaexceedederror-dom-exception-22-an-attempt-was-made-to-add-something-to-st
// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and just silently drop any calls to setItem
// to avoid the entire page breaking, without having to do a check at each usage of Storage.
if (typeof localStorage === 'object') {
try {
localStorage.setItem('localStorage', 1);
localStorage.removeItem('localStorage');
} catch (e) {
Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function() {};
alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
}
}
var dmp = new diff_match_patch();
var curCode = '';
var deltaObj = undefined;
function initDeltaObj() {
// make sure the editor already exists
// (editor doesn't exist when you're, say, doing an iframe embed)
if (!pyInputAceEditor && !pyInputCodeMirror) {
return;
}
// v is the version number
// 1 (version 1 was released on 2014-11-05)
// 2 (version 2 was released on 2015-09-16, added a startTime field)
deltaObj = {start: pyInputGetValue(), deltas: [], v: 2,
startTime: new Date().getTime()};
}
function initAceEditor(height) {
pyInputAceEditor = ace.edit('codeInputPane');
var s = pyInputAceEditor.getSession();
// tab -> 4 spaces
s.setTabSize(4);
s.setUseSoftTabs(true);
// disable extraneous indicators:
s.setFoldStyle('manual'); // no code folding indicators
s.getDocument().setNewLineMode('unix'); // canonicalize all newlines to unix format
pyInputAceEditor.setHighlightActiveLine(false);
pyInputAceEditor.setShowPrintMargin(false);
pyInputAceEditor.setBehavioursEnabled(false);
pyInputAceEditor.$blockScrolling = Infinity; // kludgy to shut up weird warnings
// auto-grow height as fit
pyInputAceEditor.setOptions({minLines: 18, maxLines: 1000});
$('#codeInputPane').css('width', '700px');
$('#codeInputPane').css('height', height + 'px'); // VERY IMPORTANT so that it works on I.E., ugh!
initDeltaObj();
pyInputAceEditor.on('change', function(e) {
$.doTimeout('pyInputAceEditorChange', CODE_SNAPSHOT_DEBOUNCE_MS, snapshotCodeDiff); // debounce
clearFrontendError();
s.clearAnnotations();
});
// don't do real-time syntax checks:
// https://github.com/ajaxorg/ace/wiki/Syntax-validation
s.setOption("useWorker", false);
setAceMode();
pyInputAceEditor.focus();
}
var JAVA_BLANK_TEMPLATE = 'public class YourClassNameHere {\n\
public static void main(String[] args) {\n\
\n\
}\n\
}'
var CPP_BLANK_TEMPLATE = 'int main() {\n\
\n\
return 0;\n\
}'
function setAceMode() {
var selectorVal = $('#pythonVersionSelector').val();
var mod;
var tabSize = 2;
var editorVal = $.trim(pyInputGetValue());
if (editorVal === JAVA_BLANK_TEMPLATE || editorVal === CPP_BLANK_TEMPLATE) {
editorVal = '';
pyInputSetValue(editorVal);
}
if (selectorVal === 'java') {
mod = 'java';
if (editorVal === '') {
pyInputSetValue(JAVA_BLANK_TEMPLATE);
}
} else if (selectorVal === 'js') {
mod = 'javascript';
} else if (selectorVal === 'ts') {
mod = 'typescript';
} else if (selectorVal === 'ruby') {
mod = 'ruby';
} else if (selectorVal === 'c' || selectorVal == 'cpp') {
mod = 'c_cpp';
if (editorVal === '') {
pyInputSetValue(CPP_BLANK_TEMPLATE);
}
} else {
mod = 'python';
tabSize = 4; // PEP8
}
assert(mod);
var s = pyInputAceEditor.getSession();
s.setMode("ace/mode/" + mod);
s.setTabSize(tabSize);
s.setUseSoftTabs(true);
// clear all error displays when switching modes
var s = pyInputAceEditor.getSession();
s.clearAnnotations();
clearFrontendError();
}
function snapshotCodeDiff() {
if (!deltaObj) {
return;
}
var newCode = pyInputGetValue();
var timestamp = new Date().getTime();
//console.log('Orig:', curCode);
//console.log('New:', newCode);
if (curCode != newCode) {
var diff = dmp.diff_toDelta(dmp.diff_main(curCode, newCode));
//var patch = dmp.patch_toText(dmp.patch_make(curCode, newCode));
var delta = {t: timestamp, d: diff};
deltaObj.deltas.push(delta);
curCode = newCode;
logEventCodeopticon({type: 'editCode', delta: delta});
if (typeof TogetherJS !== 'undefined' && TogetherJS.running) {
TogetherJS.send({type: "editCode", delta: delta});
}
}
}
function reconstructCode() {
var cur = '';
var dmp = new diff_match_patch();
var deltas = [];
var patches = [];
var prevTimestamp = undefined;
$.each(deltaObj.deltas, function(i, e) {
if (prevTimestamp) {
assert(e.t >= prevTimestamp);
prevTimestamp = e.t;
}
deltas.push(e.d);
patches.push(e.p);
});
console.log(patches);
console.log(deltas);
//var d = dmp.diff_fromDelta('', "+x = 1")
//var p = dmp.patch_make(d)
//dmp.patch_apply(p, '')
//x = dmp.patch_fromText("@@ -0,0 +1,5 @@\n+x = 1\n")
//dmp.patch_apply(x, '')
//x = dmp.patch_fromText("@@ -1,5 +1,12 @@\n x = 1\n+%0Ax = 2%0A\n")
//dmp.patch_apply(x, 'x = 1')
}
// BEGIN - shared session stuff
// grab this as early as possible before TogetherJS munges the URL
var togetherjsInUrl = ($.bbq.getState('togetherjs') !== undefined);
// XXX: to deploy, substitute in the online TogetherJS server URL here
var TogetherJSConfig_hubBase = "http://localhost:30035/"; // local
// TogetherJS common configuration
var TogetherJSConfig_disableWebRTC = true;
var TogetherJSConfig_suppressJoinConfirmation = true;
var TogetherJSConfig_dontShowClicks = false;
// stop popping up boring intro dialog box:
var TogetherJSConfig_seenIntroDialog = true;
// suppress annoying pop-ups:
var TogetherJSConfig_suppressInvite = true;
var TogetherJSConfig_suppressJoinConfirmation = true;
// clone clicks ONLY in certain elements to keep things simple:
var TogetherJSConfig_cloneClicks = '#pyInputPane select';
var TogetherJSConfig_siteName = "Online Python Tutor shared session";
var TogetherJSConfig_toolName = "Online Python Tutor shared session";
// more nasty global state vars
var updateOutputSignalFromRemote = false;
var executeCodeSignalFromRemote = false;
var togetherjsSyncRequested = false;
var pendingCodeOutputScrollTop = null;
TogetherJSConfig_ignoreForms = ['.togetherjsIgnore']; // do NOT sync these elements
function requestSync() {
if (typeof TogetherJS !== 'undefined' && TogetherJS.running) {
togetherjsSyncRequested = true;
TogetherJS.send({type: "requestSync"});
}
}
function syncAppState(appState) {
setToggleOptions(appState);
// VERY VERY subtle -- temporarily prevent TogetherJS from sending
// form update events while we set the input value. otherwise
// this will send an incorrect delta to the other end and screw things
// up because the initial states of the two forms aren't equal.
var orig = TogetherJS.config.get('ignoreForms');
TogetherJS.config('ignoreForms', true);
pyInputSetValue(appState.code);
TogetherJS.config('ignoreForms', orig);
if (appState.rawInputLst) {
rawInputLst = $.parseJSON(appState.rawInputLstJSON);
}
else {
rawInputLst = [];
}
}
// get OPT ready for integration with TogetherJS
function initTogetherJS() {
if (typeof TogetherJS === "undefined") {
return;
}
if (togetherjsInUrl) {
$("#ssDiv").hide(); // hide ASAP!
$("#togetherjsStatus").html("Please wait ... loading shared session");
}
// clear your name from the cache every time to prevent privacy leaks
if (supports_html5_storage()) {
localStorage.removeItem('togetherjs.settings.name');
}
// This event triggers when you first join a session and say 'hello',
// and then one of your peers says hello back to you. If they have the
// exact same name as you, then change your own name to avoid ambiguity.
// Remember, they were here first (that's why they're saying 'hello-back'),
// so they keep their own name, but you need to change yours :)
TogetherJS.hub.on("togetherjs.hello-back", function(msg) {
// do NOT use a msg.sameUrl guard since that will miss some signals
// due to our funky URLs
var p = TogetherJS.require("peers");
var peerNames = p.getAllPeers().map(function(e) {return e.name});
if (msg.name == p.Self.name) {
var newName = undefined;
var toks = msg.name.split(' ');
var count = Number(toks[1]);
// make sure the name is truly unique, incrementing count as necessary
do {
if (!isNaN(count)) {
newName = toks[0] + ' ' + String(count + 1); // e.g., "Tutor 3"
count++;
}
else {
// the original name was something like "Tutor", so make
// newName into, say, "Tutor 2"
newName = p.Self.name + ' 2';
count = 2;
}
} while ($.inArray(newName, peerNames) >= 0); // i.e., is newName in peerNames?
p.Self.update({name: newName}); // change our own name
}
});
TogetherJS.hub.on("updateOutput", function(msg) {
// do NOT use a msg.sameUrl guard since that will miss some signals
// due to our funky URLs
if (isExecutingCode) {
return;
}
if (myVisualizer) {
// to prevent this call to updateOutput from firing its own TogetherJS event
updateOutputSignalFromRemote = true;
try {
myVisualizer.renderStep(msg.step);
}
finally {
updateOutputSignalFromRemote = false;
}
}
});
TogetherJS.hub.on("executeCode", function(msg) {
// do NOT use a msg.sameUrl guard since that will miss some signals
// due to our funky URLs
if (isExecutingCode) {
return;
}
executeCodeSignalFromRemote = true;
try {
executeCode(msg.forceStartingInstr, msg.rawInputLst);
}
finally {
executeCodeSignalFromRemote = false;
}
});
TogetherJS.hub.on("hashchange", function(msg) {
// do NOT use a msg.sameUrl guard since that will miss some signals
// due to our funky URLs
if (isExecutingCode) {
return;
}
console.log("TogetherJS RECEIVE hashchange", msg.appMode);
if (msg.appMode != appMode) {
updateAppDisplay(msg.appMode);
if (appMode == 'edit' && msg.codeInputScrollTop !== undefined &&
pyInputGetScrollTop() != msg.codeInputScrollTop) {
// hack: give it a bit of time to settle first ...
$.doTimeout('pyInputCodeMirrorInit', 200, function() {
pyInputSetScrollTop(msg.codeInputScrollTop);
});
}
}
});
TogetherJS.hub.on("codemirror-edit", function(msg) {
// do NOT use a msg.sameUrl guard since that will miss some signals
// due to our funky URLs
$("#codeInputWarnings").hide();
$("#someoneIsTypingDiv").show();
$.doTimeout('codeMirrorWarningTimeout', 1000, function() { // debounce
$("#codeInputWarnings").show();
$("#someoneIsTypingDiv").hide();
});
});
TogetherJS.hub.on("requestSync", function(msg) {
// do NOT use a msg.sameUrl guard since that will miss some signals
// due to our funky URLs
if (TogetherJS.running) {
TogetherJS.send({type: "myAppState",
myAppState: getAppState(),
codeInputScrollTop: pyInputGetScrollTop(),
pyCodeOutputDivScrollTop: myVisualizer ?
myVisualizer.domRoot.find('#pyCodeOutputDiv').scrollTop() :
undefined});
}
});
TogetherJS.hub.on("myAppState", function(msg) {
// do NOT use a msg.sameUrl guard since that will miss some signals
// due to our funky URLs
// if we didn't explicitly request a sync, then don't do anything
if (!togetherjsSyncRequested) {
return;
}
togetherjsSyncRequested = false;
var learnerAppState = msg.myAppState;
if (learnerAppState.mode == 'display') {
if (appStateEq(getAppState(), learnerAppState)) {
// update curInstr only
console.log("on:myAppState - app states equal, renderStep", learnerAppState.curInstr);
myVisualizer.renderStep(learnerAppState.curInstr);
if (msg.pyCodeOutputDivScrollTop !== undefined) {
myVisualizer.domRoot.find('#pyCodeOutputDiv').scrollTop(msg.pyCodeOutputDivScrollTop);
}
}
else if (!isExecutingCode) { // if already executing from a prior signal, ignore
console.log("on:myAppState - app states unequal, executing", learnerAppState);
syncAppState(learnerAppState);
executeCodeSignalFromRemote = true;
try {
if (msg.pyCodeOutputDivScrollTop !== undefined) {
pendingCodeOutputScrollTop = msg.pyCodeOutputDivScrollTop; // NASTY global
}
executeCode(learnerAppState.curInstr);
}
finally {
executeCodeSignalFromRemote = false;
}
}
}
else {
assert(learnerAppState.mode == 'edit');
if (!appStateEq(getAppState(), learnerAppState)) {
console.log("on:myAppState - edit mode sync");
syncAppState(learnerAppState);
enterEditMode();
}
}
if (msg.codeInputScrollTop !== undefined) {
// give pyInputCodeMirror/pyInputAceEditor a bit of time to settle with
// its new value. this is hacky; ideally we have a callback function for
// when setValue() completes.
$.doTimeout('pyInputCodeMirrorInit', 200, function() {
pyInputSetScrollTop(msg.codeInputScrollTop);
});
}
});
TogetherJS.hub.on("syncAppState", function(msg) {
syncAppState(msg.myAppState);
});
TogetherJS.hub.on("codeInputScroll", function(msg) {
// do NOT use a msg.sameUrl guard since that will miss some signals
// due to our funky URLs
if (useCodeMirror) {
pyInputSetScrollTop(msg.scrollTop);
}
else {
// don't sync for Ace since I can't get it working properly yet
}
});
TogetherJS.hub.on("pyCodeOutputDivScroll", function(msg) {
// do NOT use a msg.sameUrl guard since that will miss some signals
// due to our funky URLs
if (myVisualizer) {
myVisualizer.domRoot.find('#pyCodeOutputDiv').scrollTop(msg.scrollTop);
}
});
$("#sharedSessionBtn").click(startSharedSession);
$("#stopTogetherJSBtn").click(TogetherJS); // toggles off
// fired when TogetherJS is activated. might fire on page load if there's
// already an open session from a prior page load in the recent past.
TogetherJS.on("ready", function () {
console.log("TogetherJS ready");
$("#sharedSessionDisplayDiv").show();
$("#adInfo").hide();
$("#ssDiv").hide();
$("#adHeader").hide();
// send this to the server for the purposes of logging, but other
// clients shouldn't do anything with this data
if (TogetherJS.running) {
TogetherJS.send({type: "initialAppState",
myAppState: getAppState(),
user_uuid: supports_html5_storage() ? localStorage.getItem('opt_uuid') : undefined,
// so that you can tell whether someone else
// shared a TogetherJS URL with you to invite you
// into this shared session:
togetherjsInUrl: togetherjsInUrl});
}
requestSync(); // immediately try to sync upon startup so that if
// others are already in the session, we will be
// synced up. and if nobody is here, then this is a NOP.
TogetherjsReadyHandler(); // needs to be defined in each frontend
redrawConnectors(); // update all arrows at the end
});
// emitted when TogetherJS is closed. This is not emitted when the
// webpage simply closes or navigates elsewhere, ONLY when TogetherJS
// is explicitly stopped via a call to TogetherJS()
TogetherJS.on("close", function () {
console.log("TogetherJS close");
$("#togetherjsStatus").html(''); // clear it
$("#sharedSessionDisplayDiv").hide();
$("#adInfo").show();
$("#ssDiv").show();
$("#adHeader").show();
TogetherjsCloseHandler(); // needs to be defined in each frontend
redrawConnectors(); // update all arrows at the end
});
}
function TogetherjsReadyHandler() {
alert("ERROR: need to override TogetherjsReadyHandler()");
}
function TogetherjsCloseHandler() {
alert("ERROR: need to override TogetherjsCloseHandler()");
}
function startSharedSession() {
$("#ssDiv").hide(); // hide ASAP!
$("#togetherjsStatus").html("Please wait ... loading shared session");
TogetherJS();
}
function populateTogetherJsShareUrl() {
// without anything after the '#' in the hash
var cleanUrl = $.param.fragment(location.href, {}, 2 /* override */);
var urlToShare = cleanUrl + 'togetherjs=' + TogetherJS.shareId();
$("#togetherjsStatus").html('<div>\
Send the URL below to invite someone to join this shared session:\
</div>\
<input type="text" style="font-size: 10pt; \
font-weight: bold; padding: 4px;\
margin-top: 3pt; \
margin-bottom: 6pt;" \
id="togetherjsURL" size="80" readonly="readonly"/>\
<button id="syncBtn" type="button">Force sync</button>\
');
$("#togetherjsURL").val(urlToShare).attr('size', urlToShare.length + 20);
$("#syncBtn").click(requestSync);
// deployed on 2015-03-06
$("#togetherjsStatus").append(emailNotificationHtml);
// append post shared session survey
//
// survey for shared sessions, deployed on 2014-06-06, taken down on
// 2015-03-06 due to lack of useful responses
/*
$("#togetherjsStatus").append(postSessionSurvey);
$('.star-rating :radio').change(function() {
if (TogetherJS.running) {
TogetherJS.send({type: "surveyHowUsefulStars",
stars: Number(this.value)});
}
});
$('#submitSessionSurveyBtn').click(function() {
var resp = $('#sharedSessionWhatLearned').val();
if (TogetherJS.running && resp) {
TogetherJS.send({type: "surveyFreetextQuestion",
question: "What did you just learn?",
answer: $('#sharedSessionWhatLearned').val()});
$("#sharedSessionWhatLearned").val('');
$("#sharedSessionWhatLearnedThanks").show();
$.doTimeout('sharedSessionWhatLearnedThanksFadeOut', 1000, function() {
$("#sharedSessionWhatLearnedThanks").fadeOut(2000);
});
}
});
*/
}
// END - shared session stuff
var myVisualizer = null; // singleton ExecutionVisualizer instance
var rawInputLst = []; // a list of strings inputted by the user in response to raw_input or mouse_input events
// each frontend must implement its own executeCode function
function executeCode() {
alert("Configuration error. Need to override executeCode(). This is an empty stub.");
}
function redrawConnectors() {
if (appMode == 'display' || appMode == 'visualize' /* deprecated */) {
if (myVisualizer) {
myVisualizer.redrawConnectors();
}
}
}
function setFronendError(lines) {
$("#frontendErrorOutput").html(lines.map(htmlspecialchars).join('<br/>'));
}
function clearFrontendError() {
$("#frontendErrorOutput").html('');
}
// From http://diveintohtml5.info/storage.html
function supports_html5_storage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
}
// abstraction so that we can use either CodeMirror or Ace as our code editor
function pyInputGetValue() {
if (useCodeMirror) {
return pyInputCodeMirror.getValue();
}
else {
return pyInputAceEditor.getValue();
}
}
function pyInputSetValue(dat) {
if (useCodeMirror) {
pyInputCodeMirror.setValue(dat.rtrim() /* kill trailing spaces */);
}
else {
pyInputAceEditor.setValue(dat.rtrim() /* kill trailing spaces */,
-1 /* do NOT select after setting text */);
}
$('#urlOutput,#embedCodeOutput').val('');
clearFrontendError();
// also scroll to top to make the UI more usable on smaller monitors
$(document).scrollTop(0);
}
var codeMirrorScroller = '#codeInputPane .CodeMirror-scroll';
function pyInputGetScrollTop() {
if (useCodeMirror) {
return $(codeMirrorScroller).scrollTop();
}
else {
return pyInputAceEditor.getSession().getScrollTop();
}
}
function pyInputSetScrollTop(st) {
if (useCodeMirror) {
$(codeMirrorScroller).scrollTop(st);
}
else {
pyInputAceEditor.getSession().setScrollTop(st);
}
}
var num414Tries = 0; // hacky global
// run at the END so that everything else can be initialized first
function genericOptFrontendReady() {
initTogetherJS(); // initialize early
// be friendly to the browser's forward and back buttons
// thanks to http://benalman.com/projects/jquery-bbq-plugin/
$(window).bind("hashchange", function(e) {
// if you've got some preseeded code, then parse the entire query
// string from scratch just like a page reload
if ($.bbq.getState('code')) {
parseQueryString();
}
// otherwise just do an incremental update
else {
var newMode = $.bbq.getState('mode');
//console.log('hashchange:', newMode, window.location.hash);
updateAppDisplay(newMode);
}
if (typeof TogetherJS !== 'undefined' && TogetherJS.running && !isExecutingCode) {
TogetherJS.send({type: "hashchange",
appMode: appMode,
codeInputScrollTop: pyInputGetScrollTop(),
myAppState: getAppState()});
}
});
if (useCodeMirror) {
pyInputCodeMirror = CodeMirror(document.getElementById('codeInputPane'), {
mode: 'python',
lineNumbers: true,
tabSize: 4,
indentUnit: 4,
// convert tab into four spaces:
extraKeys: {Tab: function(cm) {cm.replaceSelection(" ", "end");}}
});
pyInputCodeMirror.setSize(null, '420px');
}
else {
initAceEditor(420);
}
if (useCodeMirror) {
// for shared sessions
pyInputCodeMirror.on("change", function(cm, change) {
// only trigger when the user explicitly typed something
if (change.origin != 'setValue') {
if (typeof TogetherJS !== 'undefined' && TogetherJS.running) {
TogetherJS.send({type: "codemirror-edit"});
}
}
});
}
else {
pyInputAceEditor.getSession().on("change", function(e) {
// unfortunately, Ace doesn't detect whether a change was caused
// by a setValue call
if (typeof TogetherJS !== 'undefined' && TogetherJS.running) {
TogetherJS.send({type: "codemirror-edit"});
}
});
}
if (useCodeMirror) {
$(codeMirrorScroller).scroll(function(e) {
if (typeof TogetherJS !== 'undefined' && TogetherJS.running) {
var elt = $(this);
$.doTimeout('codeInputScroll', 100, function() { // debounce
// note that this will send a signal back and forth both ways
// (there's no easy way to prevent this), but it shouldn't keep
// bouncing back and forth indefinitely since no the second signal
// causes no additional scrolling
TogetherJS.send({type: "codeInputScroll",
scrollTop: elt.scrollTop()});
});
}
});
}
else {
// don't sync for Ace since I can't get it working properly yet
/*
pyInputAceEditor.getSession().on('changeScrollTop', function() {
if (typeof TogetherJS !== 'undefined' && TogetherJS.running) {
$.doTimeout('codeInputScroll', 100, function() { // debounce
// note that this will send a signal back and forth both ways
// (there's no easy way to prevent this), but it shouldn't keep
// bouncing back and forth indefinitely since no the second signal
// causes no additional scrolling
TogetherJS.send({type: "codeInputScroll",
scrollTop: pyInputGetScrollTop()});
});
}
});
*/
}
// first initialize options from HTML LocalStorage. very important
// that this code runs first so that options get overridden by query
// string options and anything else the user wants to override with.
if (supports_html5_storage()) {
var lsKeys = ['cumulative',
'heapPrimitives',
'py',
'textReferences'];
// restore toggleState if available
var lsOptions = {};
$.each(lsKeys, function(i, k) {
var v = localStorage.getItem(k);
if (v) {
lsOptions[k] = v;
}
});
setToggleOptions(lsOptions);
// store in localStorage whenever user explicitly changes any toggle option:
$('#cumulativeModeSelector,#heapPrimitivesSelector,#textualMemoryLabelsSelector,#pythonVersionSelector').change(function() {
var ts = getToggleState();
$.each(ts, function(k, v) {
localStorage.setItem(k, v);
});
});
// generate a unique UUID per "user" (as indicated by a single browser
// instance on a user's machine, which can be more precise than IP
// addresses due to sharing of IP addresses within, say, a school
// computer lab)
// added on 2015-01-27 for more precise user identification
if (!localStorage.getItem('opt_uuid')) {
localStorage.setItem('opt_uuid', generateUUID());
}
}
parseQueryString();
$(window).resize(redrawConnectors);
$('#genUrlBtn').bind('click', function() {
var myArgs = getAppState();
var urlStr = $.param.fragment(window.location.href, myArgs, 2 /* clobber all */);
urlStr = urlStr.replace(/\)/g, '%29') // replace ) with %29 so that links embed well in Markdown
$('#urlOutput').val(urlStr);
});
// register a generic AJAX error handler
$(document).ajaxError(function(evt, jqxhr, settings, exception) {
// ignore errors related to togetherjs stuff:
if (settings.url.indexOf('togetherjs') > -1) {
return; // get out early
}
// ugh other idiosyncratic stuff
if (settings.url.indexOf('name_lookup.py') > -1) {
return; // get out early
}
if (settings.url.indexOf('syntax_err_survey.py') > -1) {
return; // get out early
}
if (settings.url.indexOf('viz_interaction.py') > -1) {
return; // get out early
}
/*
This jqxhr.responseText might be indicative of the URL being too
long, since the error message returned by the server is something
like this in nginx:
<html>
<head><title>414 Request-URI Too Large</title></head>
<body bgcolor="white">
<center><h1>414 Request-URI Too Large</h1></center>
<hr><center>nginx</center>
</body>
</html>
Note that you'll probably need to customize this check for your server. */