-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpline.js
More file actions
2177 lines (2000 loc) · 88.6 KB
/
pline.js
File metadata and controls
2177 lines (2000 loc) · 88.6 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
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//=== Pline web interface generator for command-line tools === //
// http://wasabiapp.org/pline
// Andres Veidenberg (andres.veidenberg[at]helsinki.fi), University of Helsinki, 2019
// Licensed under the MIT licence: https://opensource.org/licenses/MIT
// Compatible with IE 9+ and all the other web browsers
if(!window.ko) console.error('Pline dependancy missing: Knockout.js library');
//String.includes() polyfill
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (search instanceof RegExp) {
throw TypeError('first argument must not be a RegExp');
}
if (start === undefined) { start = 0; }
return this.indexOf(search, start) !== -1;
};
}
//includes() for multiple values
String.prototype.includesAny = function(){
for(var i in arguments){
if(this.includes(arguments[i])) return true;
}
return false;
}
//Pline object
var Pline = {
plugins: {}, //plugin datamodels container
pipeline: ko.observableArray(), //list of plugin IDS currently in the pipeline
submitted: ko.observable(false), //submit button pressed
sending: ko.observable(false), //sending input data to server
//global Pline settings
settings: {
sendmail: false, //enable email notifications (false|true|'pipelines'=only for pipelines)
email: '', //predefined email address
presets: true, //enable presets (stored plugin launch parameters)
UIcontainer: 'body', //default container element for plugin interfaces (CSS selector | DOM element)
pipelines: true, //enable pipelines (send multiple commands. false=show one plugin interface at a time)
pipes: true, //enable pipes in pipelines/commands (set false on unsopperted systems e.g. Windows)
sendAddress: '', //backend web server URL
sendData: {}, //default POST data, sent with each job (object: {key:value,...})
cleanup: false //true = remove interface after job has been sent to server
},
//pipeline config file import/export state
config:{
edit: ko.observable(), //save pipeline (configfile) mode
name: ko.observable(), //new configfile name
desc: ko.observable(), //new pipeline description
message: ko.observable(''), //open/save feedback
errors: ko.observableArray([]), //open/save errors
logErrors: function(){ //print errors to console
console.log('Pline pipeline loading failed: '+this.errors().join(' | '));
},
includeFiles: false, //include input filenames in the preset
imported: ko.observable({}) //name+description of the imported pipeline
},
//Pline public functions:
//parse & register new plugin
addPlugin: function(data, pluginpath){ //data = Pline.plugin(obj) | JSON(obj/str) | JSON URL(str)
if(!data){
console.log('Failed to import a Pline plugin: input missing (JSON or URL expected)!');
return;
}
var json, url, plugin;
if(typeof(data)=='string'){
if(data.includes('{')) json = data;
else url = data;
} else if(typeof(data)=='object'){
if(data instanceof Pline.plugin) plugin = data;
else json = data;
} else {
console.log('Failed to import a Pline plugin: wrong input type (JSON or URL expected)!');
return;
}
if(!plugin) plugin = new Pline.plugin(json, {path: pluginpath}); //init plugin
if(url){ //download JSON first
plugin.xhr = $.get(url).done(function(newJSON){
plugin.json = newJSON; //add data to the plugin instance
Pline.addPlugin(plugin, pluginpath);
}).fail(function(obj){ //not JSON
if (obj.responseText){
plugin.json = obj.responseText;
Pline.addPlugin(plugin, pluginpath); //re-parse
} else {
plugin.error('Failed to download the plugin JSON from '+url);
console.log(obj);
}
}).always(function(){
plugin.xhr = '';
});
return;
}
var status = plugin.initPlugin();
if(status){
if(status instanceof Pline.plugin) return status;
if(plugin.debug) console.groupCollapsed(plugin.title+' plugin parser log');
plugin.parseOptions();
plugin.ready = true;
plugin.log('Parsing: second pass', {title:true});
plugin.parseOptions(); //2nd parsing round
if(plugin.debug) console.groupEnd();
plugin.log('= Plugin parsed =', {title:true});
Pline.plugins[plugin.id] = plugin;
} else {
console.log('Plugin import failed. Datamodel dump: %o', plugin);
}
plugin.registerPlugin(); //hook function
return plugin;
},
//store the current pipeline (open plugins+inputvalues) to a JSON file
saveConfig: function(){
var self = this;
var name = self.config.name();
if(!name){
self.config.message('Please type a name for the new config.');
return;
}
var desc = self.config.desc();
self.config.edit(false);
//store the state of the current pipeline
var pipeline = [];
self.pipeline().forEach( function(pID){
var plugin = self.plugins[pID];
pipeline.push({
plugin: plugin.duplicate || pID, //original pluginID
name: plugin.jobName(),
inputs: plugin.readInputs()
});
});
//save JSON to Blob and init its download (filesave dialog)
var savedata = {name: name, desc: desc, pipeline: pipeline};
var blob = new Blob([JSON.stringify(savedata, null, 1)], {type: 'text/json'});
var filename = name.replace(/ /g, '_')+'.json';
if(navigator.msSaveOrOpenBlob){ //IE
navigator.msSaveBlob(blob, filename);
} else {
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function(){ //cleanup
URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}, 100);
}
self.config.message('Configuration file created.');
},
//read & open pipeline from a configfile
readConfig: function(filelist){
var self = this;
if(!filelist.length) return;
var file = filelist.item(0);
var reader = new FileReader();
reader.onload = function(){
try{
var json = JSON.parse(reader.result);
} catch {
self.config.errors.push('Unrecognized fileformat'); return;
}
if(typeof(json)!='object' || !json.pipeline){
self.config.errors.push('No pipeline data in the file'); return;
}
self.openPipeline(json);
};
reader.readAsText(file);
},
//restore a pipeline from JSON
openPipeline: function(json, targetEl){
var self = this;
self.config.errors.removeAll();
if(!json || !json.pipeline){
self.config.errors.push('Malformed pipeline JSON');
self.config.logErrors();
console.log(json);
return;
}
if(targetEl) Pline.settings.UIcontainer = targetEl;
Pline.clearPipeline();
self.config.imported({name: json.name||'', desc: json.desc||''});
//restore the pipeline steps from json
var plugin = false;
for(var i=0; i < json.pipeline.length; i++){
var step = json.pipeline[i];
if(!step.plugin || !step.inputs){
self.config.errors.push('Malformed pipeline step JSON');
break;
}
if(!self.plugins[step.plugin]){
self.config.errors.push('Missing plugin: '+step.plugin);
break;
} else {
plugin = self.plugins[step.plugin].draw(targetEl, 'clone'); //render plugin interface
setTimeout( function(step){ //fill the inputs
var data = {name: json.name, preset: step.inputs, URL: json.URL||false};
this.loadPreset(data, 'quiet');
if(step.name) this.jobName(step.name);
}.bind(plugin, step), 1000+(i*100));
}
}
if(!plugin) self.config.logErrors();
else setTimeout(function(){ self.config.message('Pipeline ready.'); }, 2000);
},
//remove all pipeline steps
clearPipeline: function(remove){
if(!Pline.pipeline().length) return;
if(remove) $('.pline', Pline.settings.UIcontainer).remove(); //remove Pline interface
else $('.pl-plugins', Pline.settings.UIcontainer).empty(); //remove plugin UIs
Pline.pipeline().forEach( function(name, i){ //remove plugin clones
if(i) delete Pline.plugins[name];
});
Pline.pipeline([]); //clear interface list
Pline.config.imported({}); //clear pipeline info
},
//utility function for making collapsible interface sections
makeSection: function(options){
var arrow = $('<span class="pl-rotateable'+(options.open?' pl-rotateddown':'')+'">►</span>'), infospan = '';
var titlespan = $('<span class="pl-action" title="'+(options.desc||'Click to toggle content')+'">'+(options.title||'View/hide')+'</span>');
var titlediv = $('<div class="pl-expandtitle'+(options.inline?' pl-inline':'')+'">').append(arrow, titlespan);
if(typeof(options.css)=='object') titlediv.css(options.css);
if(options.info){
infospan = $('<span class="pl-note" style="display:none;margin-left:20px">'+options.info+'</span>');
options.onshow = function(){infospan.fadeIn()};
options.onhide = function(){infospan.fadeOut()};
titlediv.append(infospan);
}
titlespan.click(function(){
var content = options.target||titlespan.parent().siblings(".insidediv, .pl-insidediv").first();
if(arrow.hasClass('pl-rotateddown')){
arrow.removeClass('pl-rotateddown');
if(options.keepw){ //keep container width after collapsing its content
content.css("min-width", content.width());
content.parent().css("min-width", content.parent().width());
}
if(options.minh) content.animate({height:options.minh});
else content.slideUp();
if(typeof(options.onhide)=='function') options.onhide();
}
else{
arrow.addClass('pl-rotateddown');
if(options.maxh){
if(isNaN(options.maxh)) options.maxh = content[0].scrollHeight;
content.animate({height:options.maxh});
}
else content.slideDown();
if(typeof(options.onshow)=='function') options.onshow();
}
});
return titlediv;
},
//make a pop-up menu
//btn=menu launcher DOM element; items=array[{title:str,click:func}]; arr=menu pointer direction ('top'|'bottom')
makeMenu: function(btn, items, arr){
if(!arr) arr = 'top';
if(!Array.isArray(items)){
items = [];
var plugins = Object.keys(Pline.plugins).sort();
plugins.forEach( function(pname){ //default menu: the plugins list
var plugin = Pline.plugins[pname];
if(plugin.duplicate) return true;
items.push({
text: '⚙ '+plugin.title,
title: 'Add '+plugin.title+' to the pipeline',
click: function(){ plugin.draw(); }
});
});
}
//build the menu
var ul = $('<ul>');
items.forEach( function(item){
if(typeof(item.text)!='string' || typeof(item.click)!='function') return;
$('<li title="'+(item.title||'')+'">'+item.text+'</li>').click(item.click).appendTo(ul);
});
var menu = $('<div class="pl-tooltip"></div>');
var tiparrow = $('<div class="pl-arrow"></div>');
menu.append(tiparrow, $('<div class="pl-tooltipcontentwrap"></div>').append('<div class="pl-tooltipcontent"></div>').append(ul));
$('body').append(menu);
btn = $(btn); //get menu launcher position
var targetx = btn.offset().left+((parseInt(btn.css('width')) - parseInt(menu.css('width')))/2)+10;
var targety = btn.offset().top;
if(arr=='bottom' && (targety-menu.outerHeight()-20 < 0)) arr = 'top'; //avoid clipping
if(arr=='top') targety += parseInt(btn.css('height'))+13; //adjust menu location
else if(arr=='bottom') targety -= menu.outerHeight()+4;
menu.addClass('pl-'+arr+'arrow');
menu.css({left: parseInt(targetx), top: parseInt(targety)}); //set menu position
menu.addClass('pl-opaque'); //show the menu
setTimeout(function(){ $('html').one('click', function(){ Pline.hideMenu(menu); }); }, 100); //hide the menu on click
return menu;
},
//hide the plugins menu
hideMenu: function(menu){
if(!menu || !menu.length) menu = $('.pl-tooltip');
menu.removeClass('pl-opaque');
setTimeout(function(){ menu.remove(); }, 200);
},
//search an array of objects with a key/val needle
indexOfObj: function(objarr, key, val){
if(!Array.isArray(objarr) || typeof(key) != 'string') return -1;
for(var i = 0; i < objarr.length; i++){
var oval = objarr[i][key];
if(typeof(oval) == 'function' && typeof(val) != 'function') oval = oval();
if(oval === val) return i;
}
return -1;
},
//replace Pline or plugin functions/variables with custom extensions
extend: function(extensions){ //extensions = {varName:func/obj/val}
$.each(extensions, function(name, extension){
var target = Pline[name]? Pline : Pline.plugin.prototype;
if(typeof(extension)=='object' && target[name]) Object.assign(target[name], extension);
else target[name] = extension;
});
}
}//Pline
//self-clear configfile exporting status
Pline.config.message.subscribe(function(txt){
if(txt) setTimeout(function(){ Pline.config.message(''); }, 3000);
});
Pline.config.edit.subscribe(function(editmode){
if(!editmode){ Pline.config.name(''); Pline.config.desc(''); }
});
//dynamic name of the currently open plugin/pipeline
Pline.title = ko.pureComputed(function(){
var pl = this.pipeline();
if(pl.length){
return this.config.imported().name || this.plugins[pl[0]].title + (pl.length>1? ' pipeline' : '');
} else {
return '';
}
}, Pline).extend({ throttle: 100 });
//dynamic submit button text & title
Pline.sBtn = ko.pureComputed(function(){
var pl = this.pipeline();
if(!pl.length){ //empty interface
return { text: '', title: '' };
}
if(Pline.sending()){
return { text: 'Sending...', title: 'Submitting the task' };
}
if(pl.length == 1){ //single plugin
var plugin = this.plugins[pl[0]];
var btntxt = plugin.ruleToFunc(plugin.submitBtn)() || 'RUN';
return { text: btntxt, title: 'Launch '+plugin.title };
}
//pipeline
return { text: 'Run pipeline', title: 'Launch the pipeline' };
}, Pline);
//datamodel for each Pline plugin
Pline.plugin = function(json, opt){
if(typeof(opt) != 'object'){
if(typeof(opt) == 'string') opt = {id:opt};
else opt = {};
}
var self = this;
//plugin state
self.id = opt.id||'';
self.title = 'plugin';
self.program = '';
self.version = '';
self.json = json; //json => obj
self.path = opt.path||''; //plugin json path
self.prefix = '-'; //params prefix
self.valueSep = ' '; //params name/value separator
self.jobName = ko.observable('analysis');
self.icon = {};
self.category = '';
self.outFiles = [];
self.stdout = ko.observable('output.log');
self.configFile = '';
self.configParam = '';
self.debug = false;
self.errors = [];
self.selopt = {};
self.ready = false;
self.step = opt.step||0;
self.duplicate = opt.duplicate||false; //false/id of the source plugin
self.pipe = ko.observableArray([]); //list of inputs using a pipe
//stored confirgurations (plugin option values)
self.presets = ko.observableArray([]); //list of presets
self.preset = ko.observable(); //selected preset object
self.preset.subscribe(function(){ self.loadPreset(); }); //activate new selected preset
self.preset.edit = ko.observable(); //add preset mode
self.preset.newname = ko.observable(); //new preset name
self.preset.status = ko.observable(''); //self-clearing status text
self.preset.status.subscribe(function(txt){if(txt) setTimeout(function(){ self.preset.status(''); }, 3000);});
self.options = {}; //datamodel for tracking input values
};
//construcor for creating plugin interface
Pline.plugin.prototype = {
//add plugin interface to the webpage
draw: function(targetEl, clone){ //targetEl(optional) = plugin interface container
var plugin = this;
var UItarget = plugin.UIcontainer = $(targetEl||Pline.settings.UIcontainer);
if(!$(UItarget).length){
plugin.showError('Plugin.draw() error: container element not found: '+UItarget);
return;
}
if(targetEl) Pline.settings.UIcontainer = targetEl;
Pline.submitted(false);
//plugins html container
var footerUI, btnUI;
if(!$(".pline", UItarget).length){ //first plugin draw. Make the container.
Pline.clearPipeline(); //clear any previous plugins
UItarget.append('<div class="pline"><div class="pl-plugins"></div></div>');
//footer elements
footerUI = $('<div class="pl-footerdiv">');
btnUI = $('<div class="pl-btndiv"><hr></div>');
//email notification interface
if(Pline.settings.sendmail){
var emailUI = '<div class="pl-email" data-bind="visible:'+
(typeof(Pline.settings.sendmail) == 'string'? 'Pline.pipeline().length>1' : 'Pline.settings.email') + '">'+
'<span class="pl-label" title="Fill in your email address to send a notification after the submitted job has finished running.">'+
'Notify me when done:</span> <input data-bind="value: Pline.settings.email || \'\'" placeholder="Email address" style="width:120px"></div>';
footerUI.append(emailUI);
}
//configuration file load/save interface
if(Pline.settings.presets){
var configUI = '<div class="pl-config" data-bind="visible: Pline.config.edit"><hr>'+
'<input type="text" data-bind="value: Pline.config.name" placeholder="Pipeline name"></input>'+
'<a class="pl-button pl-small pl-square" onclick="Pline.saveConfig()" title="Store the current pipeline to a file">Save</a>'+
'<a class="pl-button pl-small pl-round pl-red" title="Cancel" onclick="Pline.config.edit(false)">x</a><br>'+
'<input type="text" class="desc" data-bind="value: Pline.config.desc" placeholder="Description (optional)"></input>'+
'</div>'+
'<!-- ko if: Pline.config.errors().length --><div class="pl-errormsg">Errors: '+
'<span class="pl-icon pl-action pl-close" title="Close the messages" onclick="Pline.config.errors.removeAll()">ⓧ</span>'+
'<ul data-bind="foreach: Pline.config.errors"><li data-bind="text: $data"></li></ul></div><!-- /ko -->'+
'<div class="pl-config pl-message" data-bind="text: Pline.config.message, fadevisible: Pline.config.message"></div>';
var configFileInput = $('<input class="pl-fileinput" type="file" accept=".json" style="display:none" onchange="Pline.readConfig(this.files)">');
footerUI.append(configUI, configFileInput);
var configBtn = $('<a class="pl-button" title="Open or store a pipeline file">Import | Export</a>');
var configMenu = [
{text: 'Import pipeline', title: 'Restore a pipelne from a JSON file', click: function(){ configFileInput.click(); }},
{text: 'Export pipeline', title: 'Save the current pipelne to a JSON file', click: function(){ Pline.config.edit(true); }}
];
configBtn.click(function(){ Pline.makeMenu(configBtn, configMenu, 'bottom'); });
btnUI.append(configBtn);
}
//pipeline building button
if(Pline.settings.pipelines){
btnUI.append('<a class="pl-button" onclick="Pline.makeMenu(this, \'\', \'bottom\')" '+
'title="Add a pipeline step">Add step</a>');
}
//submit button
var submitbtn = $('<input type="submit" class="pl-button pl-submit" data-bind="value: Pline.sBtn().text, attr:{title: Pline.sBtn().title}">');
submitbtn.click(plugin.submitJob.bind(plugin));
btnUI.append(submitbtn);
$('.pline', UItarget).append(footerUI, btnUI);
}
var container = $(".pl-plugins", UItarget).last();
if(plugin.xhr){ //JSON not yet fetched
var errspan = plugin.showError('Plugin not yet ready', 'downloading the JSON...');
plugin.xhr.done(function(){ errspan.remove(); plugin.draw(UItarget); });
return plugin;
}
//existing plugin interfaces found in the container
if($('.pl-plugin', container).length){
if(Pline.settings.pipelines){ //add as a pipeline step
plugin = plugin.addPluginStep(); //returns cloned plugin
} else { //replace interface with the new plugin
Pline.clearPipeline();
}
} else if(clone){ //use a plugin duplicate
plugin = plugin.clonePlugin();
}
Pline.pipeline.push(plugin.id);
//add plugin interface
pluginUI = plugin.renderUI();
container.append(pluginUI);
//bind the interface to its datamodel
try{
ko.applyBindings(plugin, pluginUI[0]);
if(footerUI) ko.applyBindings(plugin, footerUI[0]);
if(btnUI) ko.applyBindings(plugin, btnUI[0]);
}catch(e){
plugin.showError('Plugin error when wiring up the interface', e);
}
return plugin;
},
//add the plugin as an additional interface (pipeline step)
addPluginStep: function(){
var step1_div = $('#'+Pline.pipeline()[0]);
if(!step1_div.hasClass('pl-pluginstep')){ //wrap the first plugin div as pipeline step
step1_div.addClass('pl-pluginstep').wrapInner('<div class="pl-insidediv"></div>').prepend('<span class="pl-nr">1</span>',
Pline.makeSection({title:Pline.plugins[Pline.pipeline()[0]].title, desc:'Click to toggle plugin options', keepw:true, inline:true}));
}
$('.pl-pluginstep > .pl-insidediv').slideUp().siblings().children('.pl-rotateable').removeClass('pl-rotateddown'); //collapse all previous steps
return this.clonePlugin();
},
//returns independent copy of the plugin instance
clonePlugin: function(){
var stepnr = Pline.pipeline().length;
return Pline.addPlugin(
new Pline.plugin( JSON.parse(JSON.stringify(this.json)), //clone current data
{id: this.id+stepnr, path: this.path, step: stepnr, duplicate: this.id} //modifications
),
this.path
);
},
//remove the last pipeline step
removePluginStep: function(){
if(Pline.pipeline().length < 2) return;
var stepname = Pline.pipeline.pop();
$('#'+stepname, this.UIcontainer).remove();
delete Pline.plugins[stepname]; //remove duplicated plugin
},
//store a new preset (set of current plugin input values)
addPreset: function(){
var self = this;
if(!self.preset.edit()){ self.preset.edit(true); return; } //go to 'add preset' mode
if(!self.preset.newname()){ self.preset.status('Please type a name for the new preset.'); return; }
var newpreset = {name:self.preset.newname(), preset:self.readInputs()};
self.presets.push(newpreset);
self.preset(newpreset); //mark as active preset
self.preset.edit(false);
self.preset.newname('');
self.editStorage(self.id+'_presets', self.presets()); //save all presets to localStorage
self.preset.status('Input values saved.');
return newpreset;
},
//get current values of option observables (read user input)
readInputs: function(){
var self = this;
var ovalues = {};
for(var oname in self.options){ //get values of all plugin option observables
var opt = self.options[oname];
if(!('peek' in opt)) continue; //skip non-observables
var optval = opt();
//store filenames in fileinputs (for local files)
if(Pline.config.includeFiles && opt.container && opt.container().length){
if(!ovalues._files_) ovalues._files_ = {};
ovalues._files_[oname] = optval;
}
if('hasWriteFunction' in opt) continue; //skip computed observables
if((opt.otype=='text' || opt.otype=='hidden' || !opt.defaultval) && !optval) continue; //empty input
if(opt.defaultval && optval == opt.defaultval) continue; //filled with default value
ovalues[oname] = optval; //store input value
}
return ovalues;
},
//remove a preset
removePreset: function(){
var self = this;
self.presets.remove(self.preset());
self.editStorage(self.id+'_presets', self.presets()); //update localStorage
self.preset.status('Preset removed.');
},
//read in a stored preset
restorePreset: function(preset, activate){
var self = this;
self.presets.remove(function(item){ return item.name == preset.name; }); //remove any duplicates
self.presets.push(preset);
if(activate) self.preset(preset); //=>loadPreset
},
//apply a preset
loadPreset: function(data, quiet){
var self = this;
if(!data) data = self.preset(); //preset obj: {name:presetName, preset:{obsName:val,...}}
if(self.preset.edit() || !data) return;
if(!data.preset){ Pline.config.errors.push('No preset data!'); return; }
if(data.preset._files_){
data.files = data.preset._files_;
delete data.preset._files_;
}
for(var optname in data.preset){ //restore option values from a preset
if(!self.options[optname]){
self.error('Cannot restore option value: option "'+optname+'" is missing from the plugin!', 'warning');
} else { self.options[optname](data.preset[optname]); }
}
if(data.files && data.URL){ //restore input files (from remote source)
$.each(data.files, function(optname, filename){
if(self.options[optname] && self.options[optname].container){
$.get(data.URL+filename).done( function(filedata){
var file = new Blob([filedata]);
file.name = filename;
self.options[optname].container([file]);
});
}
});
}
if(!quiet) self.preset.status('Input values restored.');
},
//read/write presets to localStorage
editStorage: function(key, data){
//check availability (e.g. private window)
try{
var s = window.localStorage;
s.setItem('tmp','tmp');
s.removeItem('tmp');
}
catch(e){ return false; }
//store/retrieve items
if(key && typeof(data)!='undefined'){ //write
if(data===null) s.removeItem(key);
else s.setItem(key, JSON.stringify(data));
} else if(key){ //read
try{ return JSON.parse(s.getItem(key)); }catch(e){ return; }
}
return true;
},
//API error feedback
error: function(errtxt, iswarning){
if(this.curopt) errtxt = errtxt+' (when parsing option "'+this.curopt+'")';
if(!this.ready && !iswarning) this.errors.push(errtxt);
console[iswarning?'log':'error']('%c '+this.title+' %c '+errtxt, 'color:white;background-color:orange;border-radius:3px', '');
return '';
},
//display an error message in the interface
showError: function(title, msg){
if(!title) title = 'Plugin error for '+this.title;
title += ':';
if(msg){
this.error(msg);
}
else{
if(!this.errors.length) return false;
msg = '<ul><li>'+this.errors.join('</li><li>')+'</li></ul>';
title += '<br>';
this.errors = [];
}
var container = $(".pl-plugins", this.UIcontainer);
if(!container.length) return false;
var errspan = $('<p class="pl-error">'+title+' '+msg+'</span>');
container.append(errspan);
return errspan;
},
//display a message on the submit button
btnText: function(msg){
if(!msg) return;
var btn = $(".pl-submit", this.UIcontainer)[0]||'';
if(btn){
btn.value = msg;
clearTimeout(this.btn_to);
this.btn_to = setTimeout(function(){
btn.value = Pline.sBtn().text;
}, 2000); //clear msg after 2sec.
}
},
//log debug messages
log: function(logtxt, opt){
if(!this.debug) return;
if(typeof(opt)=='string') opt = {name:opt};
else if(!opt) opt = {};
var optname = opt.name||this.curopt||'';
if(typeof(this.debug)=='string' && this.debug!=optname) return;
var logargs = [];
if(optname){ //add plugin option name
logtxt = '%c '+optname+' %c '+logtxt;
logargs.push('color:white;background-color:#888;border-radius:3px');
}
if(opt.title){ //add plugin name
logtxt = '%c '+this.title+(optname?' %c ':' %c %c ')+logtxt;
logargs.unshift('color:white;background-color:orange;border-radius:3px','');
}
if(optname||opt.title) logargs.push(''); //reset message color
if(opt.obj){ logtxt += ' %o'; logargs.push(opt.obj); } //add object data
logargs.unshift(logtxt); //add debug message
console.log.apply(null, logargs); //print out
},
//find option-bound observables
getOption: function(optname){
if(optname in this.options) return this.options[optname];
for(var trackname in this.options){ if(this.options[trackname].option && this.options[trackname].option == optname) return this.options[trackname]; }
this.log('getOption(): option "'+optname+'" not found');
return false;
},
// -- Plugin JSON data parser functions -- //
//parse the conditional API keywords to Javascript (observables/logic/quoted text)
parseToken: function(expr){
var self = this;
var inputexpr = expr;
//detect a tracked option (observable from datamodel). Returns: HTML (for data-bind)
var obsStr = function(name){
if(!name) return '';
var names = name.split('.'); //include subvariables (observable.observable())
var kostr = typeof(self.options[names[0]])=='function'? "$data.options['"+names[0]+"']" : '';
if(!kostr) return '';
if(names.length > 1) kostr += typeof(self.options[names[0]][names[1]])=='function'? "['"+names[1]+"']()" : '()';
//else if(self.options[name].otype=='text' && self.options[name].defaultval){ //consider the default value
// kostr = "("+kostr+"()||$data.options['"+name+"'].defaultval)";
//}
else kostr += '()';
//if(!self.ready) self.log('condition/value is using tracked name "'+name+'"');
return kostr;
};
var quote = function(exp){ //returns: "number"|"boolean"|"'quoted string'"
try{ JSON.parse(exp); }catch(e){ return "'"+exp+"'" }; return exp;
}
//API keywords
var apiDict1 = {' is not ':'!=', ' is equal to ':'==', ' is less than ':'<', ' is more than ':'>', ' is disabled':'.disabled()',
' is enabled':'.disabled()==false'};
var apiDict2 = {'is':'==', 'equals':'==', 'contains':'.includes(', 'not':'!', 'no':'!', 'invert':'!', 'off':'false', 'yes':'true',
'on':'true', 'ticked':'true', 'checked':'true', 'selected':'true', 'and':'&&', 'or':'||', 'type':'.datatype',
'disabled':'.disabled()', 'enabled':'.disabled()==false', 'disable':'false', 'this':self.curopt};
if(typeof(expr)=='string'){
expr = expr.trim(); //remove space padding
if(expr=='undefined') return "";
if(!expr.includes(' ')){ //parse single word
return expr.charAt(0)=="'"?quote(expr.replace(/'/g,'')):(apiDict2[expr]||obsStr(expr)||quote(expr));
}
//parse: 1)quoted text 2)spaced api words 3)api words
var tokenizer = new RegExp('".+"|\'.+\'|'+Object.keys(apiDict1).join('|')+'|[\\w\\-]+','g');
expr = expr.replace(tokenizer, function(word){
if(word.charAt(0)=='"' || word.charAt(0)=="'"){ //quoted text (no translation)
return word.replace(/"/g,"'");
} else { return (apiDict1[word]||apiDict2[word]||word); }
});
expr = expr.replace(/ (\.)/g, "$1").replace(/(!) /g, "$1"); //close gaps
//parse: 4)observable names 4)values/words
expr = expr.replace(/'.+'|[\w\-\.]+/g, function(word){
if(word.charAt(0)!="'"){ return (obsStr(word)||quote(word)); }
else{ return word; }
});
expr = expr.replace(/' '/g, " "); //join quoted words
expr = expr.replace(/\.includes\(\w+/g, '$&)'); //close includes() parentheses
//if(!self.ready && inputexpr!=expr) self.log('parseToken: '+inputexpr+' => '+expr);
return expr;
} else { return typeof(expr)=='undefined'? "" : JSON.stringify(expr); } //stringify numbers/booleans
},
//convert plugin API conditionals to Javascript conditionals (input/output: string)
parseRule: function(rule, result, rootvar){ //('conditional','resultValue'[,'parentObservable'])
if(typeof(result)=='undefined') result = "true";
var str = "";
if(Array.isArray(rule)){ //[rule1, rule2, ...] => apply sequentially
for(var i=0, tmp=''; i<rule.length; i++){
tmp = this.parseRule(rule[i], result, rootvar);
if(i<rule.length-1) tmp = tmp.split(":")[0]+":";
str += tmp;
}
}
else if(typeof(rule) == 'object'){ //unpack rule objects
if(Object.keys(rule).length>1){ //{rule1:res1, rule2:res2} => [{rule1:res1}, {rule2:res2}]
var ruleArr = [];
$.each(rule, function(subrule, subresult){
var ruleObj = {};
ruleObj[subrule] = subresult;
ruleArr.push(ruleObj);
});
str = this.parseRule(ruleArr, result, rootvar);
} else { //{'rule': result}
varname = Object.keys(rule)[0];
varresult = rule[varname]; //if {"varname":{varval:result}} else {"varname":result}
if(typeof(varresult) == 'object') str = this.parseRule(varresult, result, varname);
else str = this.parseRule(varname, varresult, rootvar);
}
}
else{ //parse a rule
if(typeof(rule) == 'number'){
try{
return JSON.parse(rule);
}catch(e){
self.error('parseRule("'+rule+'") => '+e);
return "";
}
} else if(typeof(rule) != 'string'){
return JSON.stringify(rule);
}
rule = this.parseToken(rule); //conditional
result = this.parseToken(result); //result value
rootvar = this.parseToken(rootvar); //current observable
var compare = function(rule){ //add '==' if needed (rule = rootvarValue)
return ~["!","=","<",">","~","."].indexOf(rule.charAt(0))? rule: "=="+rule;
}
str = rootvar? rootvar + compare(rule) : rule; //apply rule to current option value
var endresult = (!result||result=="true")? "false" : result=="false"? "true" : "\'\'";
if(result!=="true" || rootvar) str += "?" + result + ":" + endresult;
}
return str;
},
//API conditional (string) => JS conditional (string) => function
ruleToFunc: function(rule, appendstr){
var funcstr = this.parseRule(rule); //JSON rule => JS expression
if(typeof(funcstr) == 'string'){
funcstr = funcstr.replace(/\$data/g,"this").replace(/\w+\(\)/g, "this.$&")+(appendstr||'');
}
try{
var rfunc = new Function("return "+funcstr);
}catch(e){
return this.error("Faulty rule function ("+e+"): "+rule+" => "+funcstr);
}
this.log('Parsed rule function: '+funcstr);
return rfunc.bind(this);
},
//generate variable name (for an observable)
makeName: function(){
var namecount = Object.keys(this.options).filter(function(oname){ return oname.indexOf('trackName')==0; }).length;
return 'trackName'+(namecount+1);
},
//parse a single plugin option data object
parseOption: function(data, parentArr, obs){
var self = this;
if(typeof(data)!='object' || data.info) return true; //text or icon (no parsing needed)
if(!Object.keys(data).length){ //empty option object
self.error('empty option: '+data,'warning');
var optind = parentArr.indexOf(data);
if(~optind) parentArr.splice(optind, 1); //remove faulty option data
return false;
}
//valid option/input types
var types = {"text":"", "string":"text", "number":"text", "int":"text", "float":"text", "bool":"checkbox",
"tickbox":"checkbox", "checkbox":"", "hidden":"", "select":"", "file":"hidden"};
//parse {optType:optName} shorthand syntax
for(var k in data){
if(k in types){
if(!data.type) data.type = k; //fill in "type"
var optname = typeof(data[k])=='string'? data[k] : '';
if(!("title" in data) && k!="file") data.title = optname; //fill in "title"
if(!("option" in data) && k!='select'){ //fill in "option"
if(optname && (/[^a-zA-Z0-9_+-]/).test(optname)){ //optname contains strange chars
self.log('Cannot set "'+optname+'" as program argument name (you can use "name" attribute instead).');
} else data.option = optname; //valid argument name (or empty for positional arg.)
}
}
}
if(!("option" in data) && !data.name && !data.selection){
self.log('Dummy input: no name or option defined => '+JSON.stringify(data));
}
if(!data.type || !(data.type in types)) data.type = "text"; //default type
var otype = types[data.type] || data.type; //input element type (text|checkbox|hidden|select)
//delegated option (proxy input => value parsing => option value)
var valuebool = otype=='checkbox' && data.value; //checkbox with a value conversion
//values merged over multiple inputs
var valuemerge = false;
if("merge" in data){ //merged input values
if(data.merge === true) data.merge = ','; //default merged value separator
if(typeof(data.merge) == 'string'){
//merged options use both "option" (for the arg value) and "name" (for the inputs)
if(!data.option) self.log('Error: input merging needs argument name ("option" attr)!');
else if(data.type == 'file') self.log('Cannot merge file input values ("merge" attr ignored).')
else if(!data.addedOption) valuemerge = true;
}
if(!valuemerge) delete data.merge;
else if(data.option == data.name){
self.log('Note: "option" and "name" needs to be different for input merging.');
delete data.name; //will be renamed
}
}
if(data.option && !data.prefix){ //set parameter value prefix
var inline = data.option.match(/^\W+/);
if(inline && inline.length){ //prefix in the option name
data.option = data.option.replace(inline[0], '');
data.prefix = inline[0];
} else data.prefix = self.prefix; //default: global prefix ("-")
}
//option name and value tracking
if(!data.name){ //register tracking variable name
data.name = data.option && !valuemerge? data.option : self.makeName();
}
var trackname = self.curopt = data.name; //aliases
if(!(trackname in self.options)){ //set up observable for tracking input value changes
if(typeof(obs) == "function"){ //premade computed observable
self.options[trackname] = obs;
} else {
self.options[trackname] = ko.observable(obs||'');
}
} else { //option already registered (duplicate "name" in JSON)
self.log('Duplicate option ("name" attribute) already parsed. Skipping.');
return true;
}
var trackvar = self.options[trackname];
self.log('Parsing '+data.type+("option" in data? ' option '+data.option : ' input'));
//delegated checkbox (checkbox => formatted value)
if(valuebool){
if(!Array.isArray(data.value)) data.value = [data.value]; //checkbox data.value:[checkedVal, uncheckedVal]
if(data.value[0]!==true && data.value[0]!==false) data.value[0] += ''; //convert to string
if(data.value.length<2) data.value[1] = false;
else if(data.value[1]!==true && data.value[1]!==false) data.value[1] += '';
if(typeof(data.default)=='undefined') data.default = data.value[1];
else if(data.default!==true && data.default!==false){ data.default += ''; }
if(!data.value.includes(data.default)) self.error('The default checkbox state ('+data.default+') not in the list of its values: '+data.value, 'w');
//add the proxy checkbox input
var cbname = trackname+'_checkbox';
if(!~Pline.indexOfObj(parentArr, 'name', cbname)){ //add the checkbox element to json
var cbdata = Object.assign({}, data, {name:cbname, default:data.default===data.value[0], proxyInput:true}); //use current data
delete cbdata.value; delete cbdata.merge;
var opti = Pline.indexOfObj(parentArr, 'name', data.name)+1;
parentArr.splice(opti, 0, cbdata); //place after the current option (parsed by next parseOption() loop)
self.parseOption(cbdata, parentArr); //make observable
}
//turn the original option to the converted value holder from the proxy checkbox
trackvar = self.options[trackname] = ko.pureComputed({
read: function(){ //tickbox => formatted value (argname=val)
return self.options[cbname]()?data.value[0]:data.value[1];
},
write: function(val){ //option value => un/check tickbox
val===data.value[0]?self.options[cbname](true):self.options[cbname](false);
}
});
otype = data.type = 'hidden';
self.log('Using proxy checkbox: '+cbname);
}
if(!trackvar.otype) trackvar.otype = otype;
//auto-format numerical text input
if(~["number","float","int"].indexOf(data.type)){
trackvar.extend({format: data.type});
}
//hidden options
if(data.type == "hidden"){
if(!("default" in data)){ //.value == .default
if("value" in data && !valuebool) data.default = data.value
else if(!data.addedOption) data.default = true; //add missing value attr
}
}
//option defines an output filename
if(data.outfile){
if(!self.outfileopt) self.outfileopt = [];
self.outfileopt.push(data.outfile===true? trackname : data.outfile);
}
var delegated = valuemerge||valuebool; //option uses proxy input
//link option to its program argument
if("option" in data){
if(data.option.length){ //named argument
if(!("argname" in trackvar)){ //register argument name
if(data.option.includes(' ')) self.error('Space found in option name: "'+data.option+'"');
trackvar.argname = data.prefix+data.option; //links argname to input element (for input title attr)
if(data.title==data.option) data.title = trackvar.argname; //add prefix to the displayed option name
if(!delegated) trackvar.optname = data.option; //links argname to its observable (for getOption())
if(valuemerge){ //add to the list of inputs that will merge its values to the target option (program argument)
self.log('Adding to the list of merged inputs for option '+data.option);
data.proxyInput = true;
if(!self.mergeopt) self.mergeopt = {};
if(!self.mergeopt[data.option]) self.mergeopt[data.option] = {tnames:[trackname], valuesep:data.merge};
else self.mergeopt[data.option].tnames.push(trackname);
}