-
Notifications
You must be signed in to change notification settings - Fork 44
/
opencpu-0.3.js
388 lines (334 loc) · 11.2 KB
/
opencpu-0.3.js
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
/**
* Javascript client library for OpenCPU
* Version 0.3
* Depends: jQuery
* Requires HTML5 FormData support for file uploads
* http://github.com/jeroenooms/opencpu.js
*
* Include this file in your apps and packages.
* You only need to use opencpu.seturl if this page is hosted outside of the OpenCPU package. For example:
* opencpu.seturl("/ocpu/library/mypackage/R")
* opencpu.seturl("https://public.opencpu.org/ocpu/library/mypackage/R")
* opencpu.seturl("../R") //default value
*/
(function ( $ ) {
//global variable
var r_cors = false;
var r_path = document.createElement('a');
r_path.href = "../R";
//new Session()
function Session(loc, key){
this.loc = loc;
this.key = key;
this.getKey = function(){
return key;
}
this.getLoc = function(){
return loc;
}
this.getFile = function(path){
return this.getLoc() + "files/" + path;
}
this.getObject = function(name){
var name = name || ".val";
return this.getLoc() + "R/" + name;
}
}
//for POSTing raw code snippets
//new Snippet("rnorm(100)")
function Snippet(code){
this.code = code;
this.getCode = function(){
return code;
}
}
//for POSTing files
//new Upload($('#file')[0].files)
function Upload(file){
if(file instanceof File){
this.file = file;
} else if(file instanceof FileList){
this.file = file[0];
} else if (file.files instanceof FileList){
this.file = file.files[0];
} else if (file.length > 0 && file[0].files instanceof FileList){
this.file = file[0].files[0];
} else {
throw 'invalid new Upload(file). Argument file must be a HTML <input type="file"></input>';
}
this.getFile = function(){
return file;
}
}
function stringify(x){
if(x instanceof Session){
return x.getKey();
} else if(x instanceof Snippet){
return x.getCode();
} else if(x instanceof Upload){
return x.getFile();
} else if(x instanceof File){
return x;
} else if(x instanceof FileList){
return x[0];
} else if(x && x.files instanceof FileList){
return x.files[0];
} else if(x && x.length && x[0].files instanceof FileList){
return x[0].files[0];
} else {
return JSON.stringify(x);
}
}
//low level call
function r_fun_ajax(fun, settings, handler){
//validate input
if(!fun) throw "r_fun_call called without fun";
var settings = settings || {};
var handler = handler || function(){};
//set global settings
settings.url = settings.url || (r_path.href + "/" + fun);
settings.type = settings.type || "POST";
settings.data = settings.data || {};
settings.dataType = settings.dataType || "text";
//ajax call
var jqxhr = $.ajax(settings).done(function(){
var loc = jqxhr.getResponseHeader('Location') || console.log("Location response header missing.");
var key = jqxhr.getResponseHeader('X-ocpu-session') || console.log("X-ocpu-session response header missing.");
//in case of cors we translate the relative path
if(r_cors){
loc = r_path.protocol + "//" + r_path.host + loc;
}
handler(new Session(loc, key));
}).fail(function(){
console.log("OpenCPU error HTTP " + jqxhr.status + "\n" + jqxhr.responseText)
});
//function chaining
return jqxhr;
}
//call a function using uson arguments
function r_fun_call_json(fun, args, handler){
return r_fun_ajax(fun, {
data: JSON.stringify(args || {}),
contentType : 'application/json',
}, handler);
}
//call function using url encoding
//needs to wrap arguments in quotes, etc
function r_fun_call_urlencoded(fun, args, handler){
var data = {};
$.each(args, function(key, val){
data[key] = stringify(val);
});
return r_fun_ajax(fun, {
data: $.param(data),
contentType : 'x-www-form-urlencoded',
}, handler);
}
//call a function using multipart/form-data
//use for file uploads. Requires HTML5
function r_fun_call_multipart(fun, args, handler){
testhtml5();
var formdata = new FormData();
$.each(args, function(key, value) {
formdata.append(key, stringify(value));
});
return r_fun_ajax(fun, {
data: formdata,
contentType : 'multipart/form-data',
cache: false,
contentType: false,
processData: false
}, handler);
}
//Automatically determines type based on argument classes.
function r_fun_call(fun, args, handler){
var hasfiles = false;
var hascode = false;
var args = args || {};
//find argument types
$.each(args, function(key, value){
if(value instanceof File || value instanceof Upload || value instanceof FileList){
hasfiles = true;
} else if (value instanceof Snippet || value instanceof Session){
hascode = true;
}
});
//determine type
if(hasfiles){
return r_fun_call_multipart(fun, args, handler);
} else if(hascode || r_cors){
//note: cors with application/json requires preflighting, which is supported but annoying.
return r_fun_call_urlencoded(fun, args, handler);
} else {
return r_fun_call_json(fun, args, handler);
}
}
//call a function and return JSON
function r_fun_json(fun, args, handler){
return r_fun_call(fun, args, function(tmp){
$.get(tmp.getLoc() + "R/.val/json", function(data){
handler && handler(data);
}).fail(function(){
console.log("Failed to get JSON response for " + loc);
});
});
}
//post form data (including files)
$.fn.r_post_form = function(fun, handler) {
testhtml5();
var targetform = this;
var postdata = new FormData(targetform[0]);
return r_fun_ajax(fun, {
data: postdata,
cache: false,
contentType: false,
processData: false
}, handler);
}
//plotting widget
//to be called on an (empty) div.
$.fn.r_fun_plot = function(fun, args) {
var targetdiv = this;
var myplot = initplot(targetdiv);
//reset state
myplot.setlocation();
myplot.spinner.show();
// call the function
return r_fun_call(fun, args, function(tmp) {
myplot.setlocation(tmp.getLoc());
}).always(function(){
myplot.spinner.hide();
});
}
function initplot(targetdiv){
if(targetdiv.data("ocpuplot")){
return targetdiv.data("ocpuplot");
}
var ocpuplot = function(){
//local variables
var Location
var pngwidth;
var pngheight;
var plotdiv = $('<div />').attr({
style: "width: 100%; height:100%; min-width: 100px; min-height: 100px; position:absolute; background-repeat:no-repeat; background-size: 100% 100%;"
}).appendTo(targetdiv).css("background-image", "none");
var spinner = $('<span />').attr({
style : "position: absolute; top: 20px; left: 20px; z-index:1000; font-family: monospace;"
}).text("loading...").appendTo(plotdiv);
var pdf = $('<a />').attr({
target: "_blank",
style: "position: absolute; top: 10px; right: 10px; z-index:1000; text-decoration:underline; font-family: monospace;"
}).text("pdf").appendTo(plotdiv);
var svg = $('<a />').attr({
target: "_blank",
style: "position: absolute; top: 30px; right: 10px; z-index:1000; text-decoration:underline; font-family: monospace;"
}).text("svg").appendTo(plotdiv);
var png = $('<a />').attr({
target: "_blank",
style: "position: absolute; top: 50px; right: 10px; z-index:1000; text-decoration:underline; font-family: monospace;"
}).text("png").appendTo(plotdiv);
function updatepng(){
if(!Location) return;
pngwidth = plotdiv.width();
pngheight = plotdiv.height();
plotdiv.css("background-image", "url(" + Location + "graphics/last/png?width=" + pngwidth + "&height=" + pngheight + ")");
}
function setlocation(newloc){
Location = newloc;
if(!Location){
pdf.hide();
svg.hide();
png.hide();
plotdiv.css("background-image", "");
} else {
pdf.attr("href", Location + "graphics/last/pdf?width=11.69&height=8.27&paper=a4r").show();
svg.attr("href", Location + "graphics/last/svg?width=11.69&height=8.27").show();
png.attr("href", Location + "graphics/last/png?width=800&height=600").show();
updatepng();
}
}
// function to update the png image
var onresize = debounce(function(e) {
if(pngwidth == plotdiv.width() && pngheight == plotdiv.height()){
return;
}
if(plotdiv.is(":visible")){
updatepng();
}
}, 500);
// register update handlers
plotdiv.on("resize", onresize);
$(window).on("resize", onresize);
//return objects
return {
setlocation: setlocation,
spinner : spinner
}
}();
targetdiv.data("ocpuplot", ocpuplot);
return ocpuplot;
}
// from understore.js
function debounce(func, wait, immediate) {
var result;
var timeout = null;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate)
result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow)
result = func.apply(context, args);
return result;
}
}
function testhtml5(){
if( window.FormData === undefined ) {
alert("Uploading of files requires HTML5. It looks like you are using an outdated browser that does not support this. Please install Firefox, Chrome or Internet Explorer 10+");
throw "HTML5 required.";
}
}
//export
window.opencpu = window.opencpu || {};
var opencpu = window.opencpu;
//global settings
opencpu.seturl = function(newpath){
if(!newpath.match("/R$")){
alert("ERROR! Trying to set R url to: " + newpath +". Path to an OpenCPU R package must end with '/R'");
} else {
r_path = document.createElement('a');
r_path.href = newpath;
r_path.href = r_path.href; //IE needs this
if(location.protocol != r_path.protocol || location.host != r_path.host){
r_cors = true;
if (!('withCredentials' in new XMLHttpRequest())) {
alert("This browser does not support CORS. Try using Firefox or Chrome.");
}
}
if(r_cors){
console.log("Setting path to CORS server " + r_path.href);
} else {
console.log("Setting path to local (non-CORS) server " + r_path.href)
}
$.get(r_path.href, function(resdata){
console.log("Path updated. Available objects/functions:\n" + resdata);
});
}
}
//exported functions
opencpu.r_fun_call = r_fun_call;
opencpu.r_fun_json = r_fun_json;
//exported constructors
opencpu.Session = Session;
opencpu.Snippet = Snippet;
opencpu.Upload = Upload;
//for innernetz exploder
if (typeof console == "undefined") {
this.console = {log: function() {}};
}
}( jQuery ));