-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathcommon.js
365 lines (335 loc) · 12.5 KB
/
common.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
"use strict";
// http://stackoverflow.com/questions/326596/how-do-i-wrap-a-function-in-javascript
var wrap = function(fn){
return function(){
try { return fn.apply(this, arguments);
} catch(ex){
console.error(ex.stack);
throw ex;
}
};
};
var assert = function(condition, message) {
if (!condition) {
message = message || "Assertion failed";
if (typeof Error !== "undefined") {
throw new Error(message);
}
throw message; // Fallback
}
}
// http://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-url-parameter
var args = function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
return query_string;
}();
// add logging functions
// in the url place level=debug for most verbose
(function(){
var found = false;
window.level = {};
var levels = ["debug","info","log","warn","error"];
for (var i in levels){
var level = levels[i];
// allow other modules to access levels via window.level[level]
window.level[level] = level;
if(args.level && args.level === level) { found = true; }
if(found) {
// returning the function in a bind.call allows to keep the line info
window[level] = function(){
return Function.prototype.bind.call(console[level], console);
}();
} else {
window[level] = function(x){ }
}
}
window.log_group = function(x){console.group(x)};
window.log_group_end = function(){console.groupEnd()};
})();
var modal_next_id = 1;
// Duplicated in ocaml in ui_common.ml. TODO: merge the logic?
function modalError(error_str) {
const modal_id = 'modal_error_id-' + modal_next_id.toString();
modal_next_id += 1;
const h = '<div class="modal fade in" id="' + modal_id
+ '" tabindex="-1" role="dialog" data-backdrop="static" style="display: block;"><div class="modal-dialog" role="document"><form class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button><h4>Critical error.</h4></div><div class="modal-body">The Kappa app has encountered a critical error:<pre><code>'
+ error_str
+ '</code></pre>The app will not behave properly after this, please save your files to avoid data loss and reload the app. Consider <a href="https://github.com/Kappa-Dev/KappaTools/issues">opening an issue</a>.</div><div class="modal-footer"><button type="button" class="btn btn-danger" data-dismiss="modal">Return to app</button></div></form></div></div>';
document.body.insertAdjacentHTML( 'afterbegin', h );
$('#' +modal_id).modal()
}
// https://medium.com/@graeme_boy/how-to-optimize-cpu-intensive-work-in-node-js-cdc09099ed41#.2vhd0cp4g
// http://www.codingdefined.com/2014/08/difference-between-fork-spawn-and-exec.html
// param {command,args,onStdout,onStderr,onClose}
var stdsimProcesses = [];
function spawnProcess(param){
const spawn = require('child_process').spawn;
const process = spawn(param.command, param.args);
process.on('spawn', () => {debug("[Process] SPAWNED", param.command)});
process.on('exit', (code) => {
var error_str = "[Process] EXIT " + param.command + " code: " + code + ' ' + process.stderr.read();
error(error_str);
modalError(error_str);
});
process.on('error', (error) => {
var error_str = "[Process] ERROR " + param.command + " error: " + error + ' ' + process.stderr.read();
error(error_str);
});
process.on('close', (code) => {error("[Process] CLOSE", param.command, "code:", code)});
process.on('message', () => {debug("[Process] MESSAGE", param.command)});
function spawnFailure(param,message){
if(param.onError){
// pid is logged here
console.error(message);
modalError(message);
param.onError();
}
return null;
}
try {
process.stdout.setEncoding('utf8');
console.debug(`spawned process ${param.command} ${param.args} pid ${process.pid}`);
if(param.onStdout) {
process.stdout.on('data',
function (data) {
console.debug(`received stdout from process with command ${param.command} pid ${process.pid}:`, data);
param.onStdout(data); } );
}
if(param.onStderr) {
process.stderr.on('data',function (data) {
console.error(`received stderr from process with command ${param.command} pid ${process.pid}:`, data);
param.onStderr(`${data}`);
} );
}
if(param.onClose){
process.on('close',param.onClose);
}
if(param.onError){
process.on('error',param.onError);
}
if(process && process.pid) {
return {
write : function(data){
console.debug(`send data to process with command ${param.command} pid ${process.pid}:`, data);
process.stdin.write(data); } ,
kill : function(){ process.kill(); }
};
} else {
return spawnFailure(param,
`spawned failed ${param.command} ${param.args} pid ${process.pid}`);
}
stdsimProcesses.push(process);
} catch(err){
return spawnFailure(param,err.message);
}
}
function jqueryOn(selector,event,handler){
$(document.body).on(event,
selector,
function (e) { handler(e); });
}
// http://stackoverflow.com/questions/22395357/how-to-compare-two-arrays-are-equal-using-javascript-or-jquery
function is_same(array1,array2){
var same =
(array1.length == array2.length)
&&
array1.every(function(element, index) {
return element === array2[index];
});
return same;
}
/* needed to add the stylesheet to the export */
var cssTextToken = "/* stylesheet : a5f23ffb-e635-435c-ae44-c10779c2a843 */";
function createSVGDefs(svg){
var svgDefs = svg.append('defs')
.append("style")
.attr("type","text/css")
.text(cssTextToken);
return svgDefs;
}
function plotPNG(plotDivId,title,plotName,plotStyleId){
try { var html = d3.select("#"+plotDivId)
.select("svg")
.attr("title", title)
.attr("version", 1.1)
.attr("xmlns", "http://www.w3.org/2000/svg")
.attr("xmlns:xlink", "http://www.w3.org/1999/xlink")
.node()
.outerHTML;
var style = plotStyleId?d3.select("#"+plotStyleId).text():"";
style = "<![CDATA["+style+"]]>";
html = html.replace(cssTextToken,style);
var imgsrc = 'data:image/svg+xml;base64,'+ btoa(html);
var canvas = document.createElement("canvas");
var width = parseInt(d3.select("#"+plotDivId)
.select("svg")
.style("width")
.replace("px", ""));
var height = parseInt(d3.select("#"+plotDivId)
.select("svg")
.style("height")
.replace("px", ""));
canvas.width = width; // get original canvas width
canvas.height = height; //get original canvas height
var context = canvas.getContext("2d");
var image = new Image(width, height);
image.onload = function() {
context.fillStyle = "white";
context.fillRect(0, 0, width, height);
context.drawImage(image, 0, 0, width, height);
var canvasdata = canvas.toDataURL("image/png");
var a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
a.download = plotName;
a.href = canvasdata;
a.click();
document.body.removeChild(a);
};
image.onerror = function(e){
console.error("Error when plotting PNG: ", e);
}
image.src = imgsrc;
} catch (e) {
alert(e);
}
}
function saveFile(data,mime,filename){
var blob = new Blob([data], {type: mime });
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.download = filename;
a.click();
document.body.removeChild(a);
}
function plotSVG(plotDivId,title,plotName,plotStyleId){
try { var html = d3.select("#"+plotDivId)
.select("svg")
//.attr("title", title)
.attr("version", 1.1)
.attr("xmlns", "http://www.w3.org/2000/svg")
.node()
.outerHTML;
var style = plotStyleId?d3.select("#"+plotStyleId).text():"";
style = "<![CDATA["+style+"]]>";
html = html.replace(cssTextToken,style);
var header =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
+ "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n"
+ "\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n";
html = header+html;
saveFile(html,"image/svg+xml",plotName);
} catch (e) {
alert(e);
}
}
// http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
function hashCode(s){
s = s+s+s+s+s+s+s;
var hash = 0;
if (s.length == 0) return hash;
var i = 0;
for (i = 0; i < s.length; i++) {
var char = s.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
// http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript
function hashColor(s){
var hashInt = hashCode(s);
if (hashInt < 0)
{ hashInt = 0xFFFFFFFF + hashInt + 1; }
var hashColor = hashInt.toString(16);
var hashString = String("000000" + hashColor).slice(-6);
return "#"+hashString;
}
function ajaxRequest(url,type,data,handler,timeout){
var parameter = { url : url , type : type };
if(timeout){
parameter.timeout = timeout;
}
if(data){ parameter.data = data; }
console.group("ajax request: ");
console.debug(parameter);
console.groupEnd();
$.ajax(parameter)
.done(function( data, textStatus, jqXHR )
{ var status = jqXHR.status;
var response_text = jqXHR.responseText;
wrap(handler(status,response_text));
})
.fail(function(jqXHR, textStatus, errorThrown )
{ var status = jqXHR.status;
var response_text = jqXHR.responseText;
if(textStatus==="timeout") {
wrap(handler(408,"Timeout"));
} else {
wrap(handler(status,response_text));
}
});
}
/* Apply an action to a modal window. */
function modal(id,action){
$(id).modal(action);
}
// http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript/2117523#2117523
/* Used primarily to create a client id */
function guid(){
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
/* Throw an exception */
function toss(e){ throw e; }
/* Return the data of an element. */
function elementData(element,label){
var result = $(element).data(label);
return result;
}
/* create a jquery ui sort */
function createSort(id,handler){
$("#"+id).sortable({
items : "li:not(.ui-sort-disabled)",
change : function() {
var list = $(this).closest('ul');
/* used to pin elements to the top */
var topAnchor = $(list).find('.ui-sort-top-anchor');
/* used to pin elements to the bottom */
var bottomAnchor = $(list).find('.ui-sort-bottom-anchor');
$(list).prepend($(topAnchor).detach());
$(list).append($(bottomAnchor).detach());
}
});
$("#"+id).on("sortupdate",handler);
}
/* apply a map over the child nodes */
function childrenValue(element,selector,map){
var result = [];
$(element).children(selector).each(function(index){ result.push(map(this)); })
return result;
}
function hideCodeMirror(){
$.each($('.CodeMirror'),(_,cm) => $(cm.CodeMirror.getWrapperElement()).hide());
}
function showCodeMirror(){
$.each($('.CodeMirror'),(_,cm) => $(cm.CodeMirror.getWrapperElement()).show());
}