Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathGlowScript.html
More file actions
Latest commit
418 lines (379 loc) · 15.5 KB
/
Copy pathGlowScript.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--UsingGlowScriptlocally,basedontheworkofVesaLappalainenvesal@jyu.fi-->
<title>GlowScript Offline</title>
<metahttp-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
.api {
height:5000px;
border:1px solid #ddd;
border-radius:4px;
}
.splitp {
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>
<bodyclass="GlowScriptBody">
<linktype="text/css" href="glowscript_libraries/jquery-ui.custom.css" rel="stylesheet" />
<linktype="text/css" href="glowscript_libraries/ide.css" rel="stylesheet" />
<scripttype="text/javascript" src="glowscript_libraries/jquery.min.js"></script>
<scripttype="text/javascript" src="glowscript_libraries/jquery-ui.custom.min.js"></script>
<scripttype="text/javascript" src="glowscript_libraries/editor.js"></script>
<scripttype="text/javascript" src="glowscript_libraries/RSrun.3.2.min.js"></script>
<scripttype="text/javascript" src="glowscript_libraries/glow.3.2.min.js" charset="UTF-8"></script>
<scripttype="text/javascript" src="glowscript_libraries/split.min.js"></script>
<scripttype="text/javascript" src="glowscript_libraries/Roboto_Medium_ttf_sans.js"></script>
<scripttype="text/javascript" src="glowscript_libraries/NimbusRomNo9L_Med_otf_serif.js"></script>
</body>
<buttononclick="runCode()">Run</button>
<buttononclick="saveCode()">Save</button>
<ahref="VPythonDocs/index.html" target="_blank">Help</a>
<buttonid="export" onclick="exportCode()">Export</button>
<inputtype="file" id="read_local_file"/>
<script>
constgsversion='3.2'
letprintpane=false
letexporting=false// not currently in export mode
letlastprintwidth=null
letusertext
letlang
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
functionlocalCompile(compReady,errordiv){
errordiv.innerHTML=""
letcompiler_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
}
letembedScript
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
constpatt=newRegExp('line(\\s*)([0-9]*):')
letm=err.match(patt)
if(m!==null){
varcolonindex=m.index+4+m[1].length+m[2].length
varn=parseFloat(m[2])-1
err=err.slice(0,m.index)+'line '+n+err.slice(colonindex)
}
errordiv.innerHTML="<p>"+err+"</p>"
return
}
compReady(embedScript)
})
}
letwp='Web VPython '+gsversion
letjs='JavaScript '+gsversion
constr0=newRegExp('\\s*from\\s*vpython\\s*import\\s*\\*\\s*\n')// no version number
constr1=newRegExp('\\s*Web\\s*VPython\\s*([[1-9]\\.[1-9])\\s*\n')
constr2=newRegExp('\\s*\\sGlowScript\\s*([[1-9]\\.[1-9])\\s*VPython\\s*\n')
constr3=newRegExp('\\s*\\sGlowScript\\s*([[1-9]\\.[1-9])\\s*JavaScript\\s*\n')
constr4=newRegExp('\\s*JavaScript\\s*([[1-9]\\.[1-9])\\s*\n')
constr5=newRegExp('\\s*GlowScript\\s*([[1-9]\\.[1-9])\\s*\n')
letlangtype=[[r0,wp],[r1,wp],[r2,wp],[r3,js],[r4,js],[r5,js]]
functiongetHeader(exporting){
usertext=GSedit.getValue()
letend=usertext.indexOf('\n')
letfirstline=usertext.slice(0,end+1)
lang=null
for(leti=0;i<langtype.length;i++){
letm=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)
returnusertext
}
letgsErrordiv
letsavecode=null
functionrunCode(){
usertext=getHeader(false)
splitAdjust()
gsErrordiv=$("#gserrors")[0]
localCompile(ready,gsErrordiv)
}
asyncfunctionrunprog(prog){
try{
eval(prog)
await__main__()
}catch(err){
reportScriptError(prog,err)
}
}
functionready(program){
varw=$("#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)
}
functionexportCode(){
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)
}
}
functionshowcode(sc){
// In creating the string embedHTML it was necessary to break 'script' into 'scr'+'ipt' to avoid problems parsing GlowScript.html
letexporturl="https://www.glowscript.org/"
letdivid="glowscript"
letjqversion='2.1'
letembedHTML=(
'<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')
}
varstartcursor
varendcursor
varresetCursor=function(){
GSedit.editarea[0].focus()
GSedit.editarea[0].setSelectionRange(startcursor,endcursor)
}
functiongsErrorHandler(err){
gsErrordiv.innerHTML="<p>"+err+"</p>"
}
functionreadSingleFile(evt){
exporting=false
varok=true
if(GSedit.changed()){
vars="To continue without saving, click OK.\nTo save, click Cancel, then click Save."
if(confirm(s))ok=true
elseok=false
}
if(ok){
savecode=null
$("#export").html('Export')
varf,reader
f=evt.target.files[0]
if(f){
reader=newFileReader()
reader.onload=function(e){
varcontent=e.target.result
GSedit.setValue(content)
}
reader.readAsText(f)
}
}
}
document.getElementById('read_local_file').addEventListener('change',readSingleFile,false)
</script>
<divid="gserrors" style="font-family:Verdana;font-size:13px;color:#c00">
</div>
<divclass='api'>
<divid='sourcetext' class="split split-horizontal"></div>
<divid='glows' class="split split-horizontal"></div>
<divid='printing' class="split split-horizontal"></div>
</div>
<script>
// Splits library: https://github.com/nathancahill/Split.js
varlastwindowwidth=window.innerWidth
varsplits=Split(['#sourcetext','#glows',"#printing"],{sizes: [50,50,0],onDrag:splitdrag})
// splits.getSizes() returns current percentage widths; splits.setSizes([w1,w2]) resets them
varsource=''
GSedit.init("#sourcetext",source,0.5*lastwindowwidth,false)// not readonly
functionsplitdrag(){
vars=splits.getSizes()// returns [width1, width2, width3]
lastprintwidth=splits.getSizes()[2]
GSedit.setwidth(0.01*s[0]*window.innerWidth)
}
functionsplitAdjust(){// p is true if print pane should be open
varcurrent=splits.getSizes()
varw1=current[0]*lastwindowwidth/window.innerWidth
varw2=current[1]
varw3=current[2]
varrest=100-w1
lastwindowwidth=window.innerWidth
if(printpane){
if(lastprintwidth===null)splits.setSizes([w1,0.7*rest,0.3*rest])
elsesplits.setSizes([w1,rest-lastprintwidth,lastprintwidth])
lastprintwidth=splits.getSizes()[2]
}elsesplits.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
functionQuit(e){// Some browsers just say "Do you want to leave this site? Changes you made may not have been saved."
vars="To continue without saving, click OK.\nTo save, click Cancel, then click save."
e.returnValue=s
returns
}
// https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server
functiondownload(filename,text){
varelement=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);
}
varlastname=''// the file name chosen the last time the user saved code
functionsaveCode(){
varname=prompt("Enter the file name (without extension)",lastname)
if(name===null)return
lastname=name
varextension='.py'
if(!GSedit.isPython())extension='.js'
if(exporting)extension='.html'
download(name+extension,GSedit.getValue())
}
functionreportScriptError(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
varfeedback=err.toString()+'<br>'
varprog=program.split('\n')
//for(var i=0; i<prog.length; i++) console.log(i, prog[i])
varunpack=/[]*at[]([^]*)[^>]*>:(\d*):(\d*)/
vartraceback=[]
if(err.cursor){
//console.log('err.cursor',err.cursor)
// This is a syntax error from narcissus; extract the source
varc=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.
varrawStack
if(typeoferr.stack=='string')rawStack=err.stack.split('\n')
elserawStack=err.stack
//for (var i=0; i<rawStack.length; i++) console.log(i, rawStack[i])
// TODO: Selection and highlighting in the dialog
varfirst=true
vari,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
varline=prog[jsline-1]
if(window.__GSlang=='javascript'){// Currently unable to embed line numbers in JavaScript programs
traceback.push(line)
traceback.push("")
break
}
varL=undefined
varend=undefined
for(varc=jschar;c>=0;c--){// look for preceding "linenumber";
if(line[c]==';'){
if(c>0&&line[c-1]=='"'){
varend=c-1// rightmost digit in "23";
c--
}
}elseif(line[c]=='"'&&end!==undefined){
L=line.slice(c+1,end)
break
}elseif(c===0){
jsline--
line=prog[jsline-1]
c=line.length
}
}
if(L===undefined)continue
varN=Number(L)
if(first)traceback.push('At or near line '+N+': '+window.__original.text[N-1])
elsetraceback.push('Called from line '+N+': '+window.__original.text[N-1])
first=false
traceback.push("")
if(caller=='__$main')break
}
}catch(ignore){
}
}
for(vari=0;i<traceback.length;i++)feedback+='<br>'+traceback[i]
gsErrordiv=$("#gserrors")[0]
gsErrorHandler(feedback)
}
</script>
</html>