-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathGlowScript.html
More file actions
418 lines (379 loc) · 15.5 KB
/
GlowScript.html
File metadata and controls
418 lines (379 loc) · 15.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
<!DOCTYPE html>
<html>
<head>
<c-- Using GlowScript locally, based on the work of Vesa Lappalainen vesal@jyu.fi -->
<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>
const gsversion = '3.2'
let printpane = false
let exporting = false // not currently in export mode
let lastprintwidth = null
let usertext
let lang
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(compReady, errordiv) {
errordiv.innerHTML = ""
let compiler_url
if (lang == 'vpython') {
compiler_url = "glowscript_libraries/RScompiler." + gsversion + ".min.js"
} else
compiler_url = "glowscript_libraries/compiler." + gsversion + ".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
}
let embedScript
try {
embedScript = window.glowscript_compile(usertext, {lang: lang, version: gsversion})
// 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
const patt = new RegExp('line(\\s*)([0-9]*):')
let 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)
})
}
let wp = 'Web VPython '+gsversion
let js = 'JavaScript '+gsversion
const r0 = new RegExp('\\s*from\\s*vpython\\s*import\\s*\\*\\s*\n') // no version number
const r1 = new RegExp('\\s*Web\\s*VPython\\s*([[1-9]\\.[1-9])\\s*\n')
const r2 = new RegExp('\\s*\\sGlowScript\\s*([[1-9]\\.[1-9])\\s*VPython\\s*\n')
const r3 = new RegExp('\\s*\\sGlowScript\\s*([[1-9]\\.[1-9])\\s*JavaScript\\s*\n')
const r4 = new RegExp('\\s*JavaScript\\s*([[1-9]\\.[1-9])\\s*\n')
const r5 = new RegExp('\\s*GlowScript\\s*([[1-9]\\.[1-9])\\s*\n')
let langtype = [ [r0, wp], [r1, wp], [r2, wp], [r3, js], [r4, js], [r5,js] ]
function getHeader(exporting) {
usertext = GSedit.getValue()
let end = usertext.indexOf('\n')
let firstline = usertext.slice(0,end+1)
lang = null
for (let i=0; i<langtype.length; i++) {
let m = firstline.match(langtype[i][0])
if (m !== null) {
usertext = langtype[i][1] + usertext.slice(end)
lang = 'vpython'
if (i>2) lang = 'javascript'
break
}
}
if (lang == null) {
usertext = wp+'\n'+usertext
lang = 'vpython'
}
GSedit.setValue(usertext)
return usertext
}
let gsErrordiv
let savecode = null
function runCode() {
usertext = getHeader(false)
splitAdjust()
gsErrordiv = $("#gserrors")[0]
localCompile(ready, gsErrordiv)
}
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(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
let exporturl = "https://www.glowscript.org/"
let divid = "glowscript"
let jqversion = '2.1'
let embedHTML = (
'<div id="' + divid + '" class="glowscript">\n' +
'<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' + '\n' +
'<link type="text/css" href="'+exporturl+'css/redmond/' + jqversion + '/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/' + jqversion + '/jquery.min.js"></scr'+'ipt>\n' +
'<scr'+'ipt type="text/javascript" src="' + exporturl + 'lib/jquery/' + jqversion + '/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)
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>