forked from vpython/glowscript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGlowScript.html
447 lines (411 loc) · 17.2 KB
/
GlowScript.html
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
<!DOCTYPE html>
<html>
<head>
<!-- Using GlowScript locally, based on the work of Vesa Lappalainen [email protected] -->
<title>GlowScript Offline</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
.api {
height: 5000px;
border: 1px solid #ddd;
border-radius: 4px;
}
.split p {
padding: 20px;
}
.split {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
overflow-y: auto;
overflow-x: hidden;
}
.gutter {
background-color: #ccc;
background-repeat: no-repeat;
background-position: 50%;
}
.gutter.gutter-horizontal {
cursor: ew-resize;
}
.split.split-horizontal, .gutter.gutter-horizontal {
height: 100%;
float: left;
}
</style>
</head>
<body class="GlowScriptBody">
<link type="text/css" href="glowscript_libraries/jquery-ui.custom.css" rel="stylesheet" />
<link type="text/css" href="glowscript_libraries/ide.css" rel="stylesheet" />
<script type="text/javascript" src="glowscript_libraries/jquery.min.js"></script>
<script type="text/javascript" src="glowscript_libraries/jquery-ui.custom.min.js"></script>
<script type="text/javascript" src="glowscript_libraries/editor.js"></script>
<script type="text/javascript" src="glowscript_libraries/RSrun.3.2.min.js"></script>
<script type="text/javascript" src="glowscript_libraries/glow.3.2.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="glowscript_libraries/split.min.js"></script>
<script type="text/javascript" src="glowscript_libraries/Roboto_Medium_ttf_sans.js"></script>
<script type="text/javascript" src="glowscript_libraries/NimbusRomNo9L_Med_otf_serif.js"></script>
</body>
<button onclick="runCode()">Run</button>
<button onclick="saveCode()">Save</button>
<a href="VPythonDocs/index.html" target="_blank">Help</a>
<button id="export" onclick="exportCode()">Export</button>
<input type="file" id="read_local_file"/>
<script>
var gsversion = '3.2'
var printpane = false
var exporting = false // not currently in export mode
var lastprintwidth = null
window.Jupyter_VPython = undefined
if (!navigator.onLine) window.Jupyter_VPython = 'glowscript_data/' // get textures when offline
// TAB at end of line should lengthen the line; implement Ctrl-1 and Ctrl-2
// localCompile is a modification of https://github.com/vpython/glowscript/blob/master/ide/ide.js
function localCompile(header, compReady, errordiv) {
header.source = 'GlowScript '+gsversion+' VPython\n'+header.source
errordiv.innerHTML = ""
var compiler_url
if (header.lang == 'vpython') {
compiler_url = "glowscript_libraries/RScompiler." + header.version + ".min.js"
} else compiler_url = "glowscript_libraries/compiler." + header.version + ".min.js"
window.glowscript_compile = undefined
$.ajax({
url: compiler_url,
dataType: "script",
cache: true,
crossDomain: true // use script tag rather than xhr
}).fail(function (xhr, err, exc) {
(xhr)
alert(err + " getting " + xhr.url + ": " + exc)
}).done(function () {
if (!window.glowscript_compile) {
alert("Failed to load compiler from " + compiler_url)
return
}
var embedScript
try {
embedScript = window.glowscript_compile(header.source, {lang: header.lang,
version: header.version.substr(0,3)})
} catch(err) { // need to decrement 3 -> 2 in Error: Missing right parenthesis, see line 3: b = box(pos=37
err = err.toString() // gets the error message
var patt = new RegExp('line(\\s*)([0-9]*):')
var m = err.match(patt)
if (m !== null) {
var colonindex = m.index + 4 + m[1].length + m[2].length
var n = parseFloat(m[2])-1
err = err.slice(0,m.index)+'line '+n+err.slice(colonindex)
}
errordiv.innerHTML = "<p>"+err+"</p>"
return
}
compReady(embedScript)
})
}
function parseVersionHeader( source ) {
var sourceLines = source.split("\n")
var header = sourceLines[0]
// Remove a newline or similar character at the end of header:
if (header.charCodeAt(header.length-1) < 32)
header = header.substring(0,header.length-1)
var rest = source.substring( header.length+1 )
var ret = {
version: null,
lang: '', // 'vpython' (default) or 'rapydscript' or 'javascript' or a string that is neither (e.g. when editing header)
source: rest,
ok: false,
unpackaged: false,
isCurrent: false
}
header = header.split(" ")
if (header.length === undefined) return ret
if (header[0] == ' ') return ret
var elements = []
for (var i=0; i<header.length; i++) { // remove empty strings corresponding to spaces
if (header[i] != '') elements.push(header[i])
}
if (elements.length < 2 || elements.length > 3) return ret
if (elements[0] != 'GlowScript') return ret
ret.lang = 'javascript' // the default if no language is specified
if (elements.length == 3) {
ret.lang = elements[2].toLowerCase()
if (!(ret.lang == 'javascript' || ret.lang == 'vpython')) return ret
}
var ver = elements[1]
if (ver != gsversion) alert('The version number, '+ver+', should be '+gsversion)
var okv = true
return {
version: ver,
lang: ret.lang,
source: rest,
}
}
function getHeader(exporting) {
var text = GSedit.getValue()
var end = text.indexOf('\n')
var i = text.slice(0,end).indexOf("GlowScript") // Look for "GlowScipt" in first line
var j = text.slice(0,end).indexOf("vpython") // Look for "vpython" in first line
if (i < 0 && j) text = "GlowScript "+gsversion+" VPython" + "\n" + text
var header = parseVersionHeader(text)
printpane = false
if (header.source.search(/print\s*\(/) >= 0) { // if the program uses print() or GSprint(), expand 3rd pane
printpane = true
if (!exporting) {
var end = header.source.indexOf('\n')
var insert
var w = (lastprintwidth === null) ? 300 : 0.01*lastprintwidth*window.innerWidth
if (header.lang == 'vpython')
insert = "print_options(place=$('#printing'), width="+w+", height=window.innerHeight, clear=True)\n"
else insert = "print_options({place:$('#printing'), width:"+w+", height:window.innerHeight, clear:true})\n"
header.source = insert + header.source
}
}
// Look for mention of MathJax in program and attempt to get it (need internet access; files too big to include in package)
if (header.source.indexOf('MathJax') >= 0) {
alert('Cannot currently use MathJax in GlowScript Offline.')
}
return header
}
var gsErrordiv
var savecode = null
function runCode() {
var header = getHeader(false)
splitAdjust()
gsErrordiv = $("#gserrors")[0]
localCompile(header, ready, gsErrordiv, false)
}
async function runprog(prog) {
try {
eval(prog)
await __main__()
} catch(err) {
reportScriptError(prog, err)
}
}
function ready(program) {
var w = $("#glows")
w[0].innerHTML = "" // Comment this and the next if get a solution for too many WebGL contexts
w[0].innerHTML = '<div id="glowscript" class="glowscript"></div>'
window.__context = { glowscript_container: $("#glowscript") }
runprog(program)
}
function exportCode() {
if (savecode !== null) { // Restore operation
exporting = false
GSedit.setValue(savecode)
savecode = null
$("#export").html('Export')
} else { // Export operation
exporting = true
var header = getHeader(true)
gsErrordiv = $("#gserrors")[0]
localCompile(header, showcode, gsErrordiv)
}
}
function showcode(sc) {
// In creating the string embedHTML it was necessary to break 'script' into 'scr'+'ipt' to avoid problems parsing GlowScript.html
var exporturl = "https://s3.amazonaws.com/glowscript/"
var verdir = '2.1'
var divid = "glowscript"
var embedHTML = (
'<div id="' + divid + '" class="glowscript">\n' +
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' +
'<link type="text/css" href="'+exporturl+'css/redmond/' + verdir + '/jquery-ui.custom.css" rel="stylesheet" />\n' +
'<link type="text/css" href="' + exporturl + 'css/ide.css" rel="stylesheet" />\n' +
'<scr'+'ipt type="text/javascript" src="' + exporturl + 'lib/jquery/' + verdir + '/jquery.min.js"></scr'+'ipt>\n' +
'<scr'+'ipt type="text/javascript" src="' + exporturl + 'lib/jquery/' + verdir + '/jquery-ui.custom.min.js"></scr'+'ipt>\n' +
'<scr'+'ipt type="text/javascript" src="' + exporturl + 'package/glow.' + gsversion + '.min.js"></scr'+'ipt>\n' +
'<scr'+'ipt type="text/javascript" src="' + exporturl + 'package/RSrun.' + gsversion + '.min.js"></scr'+'ipt>\n' +
'<scr'+'ipt type="text/javascript"><!--//--><![CDATA[//><!--\n' +
';(function() {' +
sc +
'\n;$(function(){ window.__context = { glowscript_container: $("#glowscript").removeAttr("id") }; __main__() })})()\n' +
'\n//--><!]]></scr'+'ipt>' +
'\n</div>')
savecode = GSedit.getValue()
GSedit.setValue(embedHTML)
startcursor = 0
endcursor = embedHTML.length
setTimeout(resetCursor, 30) // experimentally, can't correctly update cursor position here
$("#export").html('Restore')
}
var startcursor
var endcursor
var resetCursor = function() {
GSedit.editarea[0].focus()
GSedit.editarea[0].setSelectionRange(startcursor,endcursor)
}
function gsErrorHandler(err) {
gsErrordiv.innerHTML = "<p>"+err+"</p>"
}
function readSingleFile(evt) {
exporting = false
var ok = true
if (GSedit.changed()) {
var s = "To continue without saving, click OK.\nTo save, click Cancel, then click Save."
if (confirm(s)) ok = true
else ok = false
}
if (ok) {
savecode = null
$("#export").html('Export')
var f, reader
f = evt.target.files[0]
if (f) {
reader = new FileReader()
reader.onload = function(e) {
var content = e.target.result
GSedit.setValue(content)
}
reader.readAsText(f)
}
}
}
document.getElementById('read_local_file').addEventListener('change', readSingleFile, false)
</script>
<div id="gserrors" style="font-family:Verdana;font-size:13px;color:#c00">
</div>
<div class='api'>
<div id='sourcetext' class="split split-horizontal"></div>
<div id='glows' class="split split-horizontal"></div>
<div id='printing' class="split split-horizontal"></div>
</div>
<script>
// Splits library: https://github.com/nathancahill/Split.js
var lastwindowwidth = window.innerWidth
var splits = Split(['#sourcetext', '#glows', "#printing"], {sizes: [50,50,0], onDrag:splitdrag})
// splits.getSizes() returns current percentage widths; splits.setSizes([w1,w2]) resets them
var source = ''
GSedit.init("#sourcetext", source, 0.5*lastwindowwidth, false) // not readonly
function splitdrag() {
var s = splits.getSizes() // returns [width1, width2, width3]
lastprintwidth = splits.getSizes()[2]
GSedit.setwidth(0.01*s[0]*window.innerWidth)
}
function splitAdjust() { // p is true if print pane should be open
var current = splits.getSizes()
var w1 = current[0]*lastwindowwidth/window.innerWidth
var w2 = current[1]
var w3 = current[2]
var rest = 100-w1
lastwindowwidth = window.innerWidth
if (printpane) {
if (lastprintwidth === null) splits.setSizes([w1,0.7*rest,0.3*rest])
else splits.setSizes([w1,rest-lastprintwidth,lastprintwidth])
lastprintwidth = splits.getSizes()[2]
} else splits.setSizes([w1,rest,0])
GSresize(0.01*w1*window.innerWidth)
print_options({height:window.innerHeight})
}
$(window).resize(function () {
splitAdjust()
})
window.onbeforeunload = undefined // execute window.onbeforeunload = Quit if GSedit.changed() is true
function Quit(e) { // Some browsers just say "Do you want to leave this site? Changes you made may not have been saved."
var s = "To continue without saving, click OK.\nTo save, click Cancel, then click save."
e.returnValue = s
return s
}
// https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
var lastname = '' // the file name chosen the last time the user saved code
function saveCode() {
var name = prompt("Enter the file name (without extension)", lastname)
if (name === null) return
lastname = name
var extension = '.py'
if (!GSedit.isPython()) extension = '.js'
if (exporting) extension = '.html'
download(name+extension, GSedit.getValue())
}
function reportScriptError(program, err) { // This machinery only gives trace information on Chrome
// The trace information provided by browsers other than Chrome does not include the line number
// of the user's program, only the line numbers of the GlowScript libraries. For that reason
// none of the following cross browser stack trace reporters are useful for GlowScript:
// Single-page multibrowser stack trace: https://gist.github.com/samshull/1088402
// stacktrase.js https://github.com/stacktracejs/stacktrace.js https://www.stacktracejs.com/#!/docs/stacktrace-js
// tracekit.js; https://github.com/csnover/TraceKit
var feedback = err.toString()+'<br>'
var prog = program.split('\n')
//for(var i=0; i<prog.length; i++) console.log(i, prog[i])
var unpack = /[ ]*at[ ]([^ ]*)[^>]*>:(\d*):(\d*)/
var traceback = []
if (err.cursor) {
//console.log('err.cursor',err.cursor)
// This is a syntax error from narcissus; extract the source
var c = err.cursor
while (c > 0 && err.source[c - 1] != '\n') c--;
traceback.push(err.source.substr(c).split("\n")[0])
//traceback.push(new Array((err.cursor - c) + 1).join(" ") + "^") // not working properly
} else {
// This is a runtime exception; extract the call stack if possible
try {
// Strange behavior: sometimes err.stack is an array of end-of-line-terminated strings,
// and at other times it is one long string; in the latter case we have to create rawStack
// as an array of strings.
var rawStack
if (typeof err.stack == 'string') rawStack = err.stack.split('\n')
else rawStack = err.stack
//for (var i=0; i<rawStack.length; i++) console.log(i, rawStack[i])
// TODO: Selection and highlighting in the dialog
var first = true
var i, m, caller, jsline, jschar
for (i=1; i<rawStack.length; i++) {
m = rawStack[i].match(unpack)
if (m === null) continue
caller = m[1]
jsline = m[2]
jschar = m[3]
if (caller.slice(0,3) == 'RS_') continue
if (caller == 'compileAndRun') break
if (caller == 'main') break
var line = prog[jsline-1]
if (window.__GSlang == 'javascript') { // Currently unable to embed line numbers in JavaScript programs
traceback.push(line)
traceback.push("")
break
}
var L = undefined
var end = undefined
for (var c=jschar; c>=0; c--) { // look for preceding "linenumber";
if (line[c] == ';') {
if (c > 0 && line[c-1] == '"') {
var end = c-1 // rightmost digit in "23";
c--
}
} else if (line[c] == '"' && end !== undefined) {
L = line.slice(c+1,end)
break
} else if (c === 0) {
jsline--
line = prog[jsline-1]
c = line.length
}
}
if (L === undefined) continue
var N = Number(L)-1
if (first) traceback.push('At or near line '+N+': '+window.__original.text[N-1])
else traceback.push('Called from line '+N+': '+window.__original.text[N-1])
first = false
traceback.push("")
if (caller == '__$main') break
}
} catch (ignore) {
}
}
for (var i= 0; i<traceback.length; i++) feedback += '<br>'+traceback[i]
gsErrordiv = $("#gserrors")[0]
gsErrorHandler(feedback)
}
</script>
</html>