/
volumewidget.js
1130 lines (1036 loc) · 41.3 KB
/
volumewidget.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
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
/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */
(function(CATMAID) {
"use strict";
/**
* Stores information about widget mode switches.
*/
var Context = function(onExit) {
this.onExit = onExit;
};
/**
* Manage spatial volumes with this widget.
*/
var VolumeManagerWidget = function(options) {
options = options || {};
// Stores information about current widget mode
this.currentContext = null;
// Access to the displayed DataTable
this.datatable = null;
this.entriesPerPage = options.entriesPerPage || 25;
// volume type
this.newVolumeType = options.defaultVolumeType || "box";
// Minimum number of nodes a volume filtered skeleton has to have.
this.minFilterNodes = 2;
// Minimum length a volume filtered skeleton has to have.
this.minFilterCable = 0;
// A skeleton source that is selected to provide skeleton ID constraints for
// listing skeletons in a volume.
this.selectedSkeletonConstraintSource = 'none';
CATMAID.skeletonListSources.on(CATMAID.SkeletonSourceManager.EVENT_SOURCE_ADDED,
this.updateSkeletonConstraintSources, this);
CATMAID.skeletonListSources.on(CATMAID.SkeletonSourceManager.EVENT_SOURCE_REMOVED,
this.updateSkeletonConstraintSources, this);
};
VolumeManagerWidget.prototype.getName = function() {
return "Volume Manager";
};
VolumeManagerWidget.prototype.getWidgetConfiguration = function() {
return {
controlsID: 'volume_manager_controls',
/**
* Create controls to refresh volumes.
*/
createControls: function(controls) {
var refresh = document.createElement('button');
refresh.appendChild(document.createTextNode('Refresh'));
refresh.onclick = this.redraw.bind(this);
controls.appendChild(refresh);
var add = document.createElement('button');
add.appendChild(document.createTextNode('Add new volume'));
add.onclick = this.addVolume.bind(this);
controls.appendChild(add);
var hiddenFileButton = CATMAID.DOM.createFileButton(false, false,
(function(event) {
var files = event.target.files;
if (0 === files.length) {
CATMAID.error("Choose at least one file!");
} else {
this.addVolumesFromSTL(Array.from(files).filter(function(file){
if (file.name.endsWith("stl")){
return true;
} else {
this.addVolumeFromFile(file);
}
},this)).catch(CATMAID.handleError);
}
}).bind(this));
hiddenFileButton.setAttribute('multiple', true);
controls.appendChild(hiddenFileButton);
var openFile = document.createElement('button');
openFile.setAttribute('title','Supports Json and ascii-stl files');
openFile.appendChild(document.createTextNode('Add from file'));
openFile.onclick = hiddenFileButton.click.bind(hiddenFileButton);
controls.appendChild(openFile);
var annotate = document.createElement('button');
annotate.appendChild(document.createTextNode('Annotate'));
annotate.setAttribute('title', 'Annotate all selected volumes');
annotate.onclick = this.annotateSelectedVolumes.bind(this);
controls.appendChild(annotate);
let self = this;
CATMAID.DOM.appendNumericField(
controls,
"Min skeleton nodes", "If \"List skeletons\" is clicked for a " +
"volume, only skeletons with at least this many nodes will be shown.",
2,
undefined,
function() {
let value = parseInt(this.value, 10);
if (value === undefined || Number.isNaN(value)) {
CATMAID.warn("Minimum skeleton nodes need to be a number");
return;
}
self.minFilterNodes = value;
},
5,
"#");
CATMAID.DOM.appendNumericField(
controls,
"Min skeleton length (nm)", "If \"List skeletons\" is clicked for a " +
"volume, only skeletons with at least a cable length of this will be shown.",
0,
undefined,
function() {
let value = parseFloat(this.value);
if (value === undefined || Number.isNaN(value)) {
CATMAID.warn("Minimum skeleton length need to be a number");
return;
}
self.minFilterCable = value;
},
8,
"nm");
// The skeleton source
var sourceSelect = CATMAID.DOM.appendSelect(
controls,
"skeleton-constraint-source",
"Skeleton constraints",
[{title: '(none)', value: 'none'}],
"Only list skeletons for a volume from this skeleton source",
'none',
function(e) {
self.selectedSkeletonConstraintSource = this.value;
});
this.updateSkeletonConstraintSourceSelect(sourceSelect);
},
contentID: 'volume_manger_content',
/**
* Create content, which is basically a DataTable instance, getting Data
* from the back-end.
*/
createContent: function(container) {
var table = document.createElement('table');
table.style.width = "100%";
var header = table.createTHead();
var hrow = header.insertRow(0);
var columns = ['', 'Name', 'Id', 'Comment', 'User', 'Creation time',
'Editor', 'Edition time', 'Action'];
columns.forEach(function(c) {
hrow.insertCell().appendChild(document.createTextNode(c));
});
var tableContainer = document.createElement('div');
tableContainer.setAttribute('class', 'volume-list');
tableContainer.appendChild(table);
container.appendChild(tableContainer);
this.datatable = $(table).DataTable({
lengthMenu: [CATMAID.pageLengthOptions, CATMAID.pageLengthLabels],
ajax: function(data, callback, settings) {
CATMAID.fetch(project.id + "/volumes/")
.then(function(volumeData) {
let volumes = volumeData.map(function(volume) {
return new CATMAID.Volume(volume);
});
callback({
draw: data.draw,
data: volumes
});
})
.catch(CATMAID.handleError);
},
columns: [
{
render: function(data, type, row, meta) {
return '<input type="checkbox" data-role="select" ' +
(row.selected ? 'checked' : '') + ' />';
}
},
{data: "title"},
{data: "id"},
{data: "comment"},
{
data: "user_id",
render: function(data, type, row, meta) {
return CATMAID.User.safe_get(data).login;
}
},
{data: "creation_time"},
{
data: "editor_id",
render: function(data, type, row, meta) {
return CATMAID.User.safe_get(data).login;
}
},
{data: "edition_time"},
{
data: null,
orderable: false,
defaultContent: '<a href="#" data-action="remove">Remove</a> ' +
'<a href="#" data-action="list-skeletons">List skeletons</a> ' +
'<a href="#" data-action="list-connectors">List connectors</a>' +
'<a href="#" data-action="export-STL">Export STL</a>'
}
],
})
.on('change', 'input[data-role=select]', function() {
var table = $(this).closest('table');
var tr = $(this).closest('tr');
var data = $(table).DataTable().row(tr).data();
data.selected = this.checked;
});
// Remove volume if 'remove' was clicked
$(table).on('click', 'a[data-action="remove"]', function() {
var tr = $(this).closest("tr");
var volume = self.datatable.row(tr).data();
var confirmDialog = new CATMAID.OptionsDialog("Remove volume", {
"Yes": function() {
CATMAID.fetch(project.id + '/volumes/' + volume.id + '/', 'DELETE')
.then(function(json) {
CATMAID.msg('Success', 'Volume ' + json.volume_id + ' removed');
self.redraw();
})
.catch(CATMAID.handleError);
},
"No": CATMAID.noop
});
confirmDialog.appendMessage("Are you sure you want to delete volume "
+ volume.id + " (" + volume.name + ")?");
confirmDialog.show(500,'auto');
// Prevent event from bubbling up.
return false;
});
// Skeleton intersection list
$(table).on('click', 'a[data-action="list-skeletons"]', function() {
var tr = $(this).closest("tr");
var volume = self.datatable.row(tr).data();
CATMAID.Volumes.get(project.id, volume.id)
.then(function(volume) {
let bb = volume.bbox;
let skeletonConstraints;
if (self.selectedSkeletonConstraintSource &&
self.selectedSkeletonConstraintSource!== 'none') {
let source = CATMAID.skeletonListSources.getSource(
self.selectedSkeletonConstraintSource);
if (!source) {
throw new CATMAID.ValueError("Can't find skeleton source: " +
self.selectedSkeletonConstraintSource);
}
let skeletonIds = source.getSelectedSkeletons();
if (skeletonIds.length > 0) {
skeletonConstraints = skeletonIds;
}
}
return CATMAID.Skeletons.inBoundingBox(project.id, bb.min.x,
bb.min.y, bb.min.z, bb.max.x, bb.max.y, bb.max.z,
self.minFilterNodes, self.minFilterCable, skeletonConstraints);
})
.then(function(skeletonIds) {
if (!skeletonIds || skeletonIds.length === 0) {
CATMAID.warn('Found no intersecting skeletons');
} else {
var handles = CATMAID.WindowMaker.create('selection-table');
if (!handles) {
throw new CATMAID.ValueError("Could not create Selection Table");
}
handles.widget.addSkeletons(skeletonIds)
.then(function() {
CATMAID.msg('Success', 'Found ' + skeletonIds.length + ' skeletons');
})
.catch(CATMAID.handleError);
}
})
.catch(CATMAID.handleError);
// Prevent event from bubbling up.
return false;
});
// Connector intersection list
$(table).on('click', 'a[data-action="list-connectors"]', function() {
var tr = $(this).closest("tr");
var volume = self.datatable.row(tr).data();
CATMAID.Volumes.get(project.id, volume.id)
.then(function(volume) {
let bb = volume.bbox;
let skeletonConstraints;
if (self.selectedSkeletonConstraintSource &&
self.selectedSkeletonConstraintSource!== 'none') {
let source = CATMAID.skeletonListSources.getSource(
self.selectedSkeletonConstraintSource);
if (!source) {
throw new CATMAID.ValueError("Can't find skeleton source: " +
self.selectedSkeletonConstraintSource);
}
let skeletonIds = source.getSelectedSkeletons();
if (skeletonIds.length > 0) {
skeletonConstraints = skeletonIds;
}
}
return CATMAID.Connectors.inBoundingBox(project.id, bb.min.x,
bb.min.y, bb.min.z, bb.max.x, bb.max.y, bb.max.z, undefined,
true, true, skeletonConstraints);
})
.then(function(connectorData) {
if (!connectorData || connectorData.length === 0) {
CATMAID.warn('Found no connectors in volume');
} else {
var connectorListHandles = CATMAID.ConnectorList.fromRawData(connectorData);
// Add a node filter for the selected volume
var strategy = CATMAID.NodeFilterStrategy['volume'];
var rule = new CATMAID.NodeFilterRule(strategy, {
'volumeId': volume.id
});
connectorListHandles.widget.filterRules.push(rule);
}
})
.catch(CATMAID.handleError);
// Prevent event from bubbling up.
return false;
});
// Connector intersection list
$(table).on('click', 'a[data-action="export-STL"]', function() {
var tr = $(this).closest("tr");
var volume = self.datatable.row(tr).data();
var headers = {Accept: ['model/x.stl-ascii', 'model/stl']};
CATMAID.fetch("/" + project.id + "/volumes/" + volume.id + "/export.stl", "GET", undefined, true, undefined, undefined, undefined, headers)
.then(function(volume_file) {
var blob = new Blob([volume_file], {type: 'model/x.stl-ascii'});
saveAs(blob, volume.name + '.stl');
})
.catch(CATMAID.handleError);
// Prevent event from bubbling up.
return false;
});
// Display a volume if clicked
var self = this;
$(table).on('dblclick', 'tbody td', function() {
var tr = $(this).closest("tr");
var volume = self.datatable.row(tr).data();
self.loadVolume(volume.id)
.then(self.editVolume.bind(self))
.catch(CATMAID.handleError);
});
}
};
};
/**
* Remove all displayed volumes.
*/
VolumeManagerWidget.prototype.destroy = function() {
if (this.currentContext) {
CATMAID.tools.callIfFn(this.currentContext.onExit);
this.currentContext = null;
}
SkeletonAnnotations.off(CATMAID.SkeletonSourceManager.EVENT_SOURCE_ADDED,
this.updateSkeletonConstraintSources, this);
SkeletonAnnotations.off(CATMAID.SkeletonSourceManager.EVENT_SOURCE_REMOVED,
this.updateSkeletonConstraintSources, this);
};
/**
* Update volume listing.
*/
VolumeManagerWidget.prototype.redraw = function(container) {
if (!this.datatable) {
return;
}
// Get list of available volumes
this.datatable.ajax.reload();
};
/**
*
*/
VolumeManagerWidget.prototype.updateSkeletonConstraintSources = function() {
let sourceSelectSelector = "select#volume_manager_controls_skeleton-constraint-source";
let sourceSelect = document.querySelector(sourceSelectSelector);
if (!sourceSelect) {
return;
}
this.updateSkeletonConstraintSourceSelect(sourceSelect);
this.selectedSkeletonConstraintSource = sourceSelect.value;
};
/**
* Update a particular select element with the most recent sources.
*/
VolumeManagerWidget.prototype.updateSkeletonConstraintSourceSelect = function(sourceSelect) {
// Find index of current value in new source list
let availableSources = CATMAID.skeletonListSources.getSourceNames();
let newIndexInNewSources = -1;
for (let i=0; i<availableSources.length; ++i) {
if (availableSources[i] === this.selectedSkeletonConstraintSource) {
newIndexInNewSources = i;
break;
}
}
var sourceOptions = availableSources.reduce(function(o, name) {
o.push({
title: name,
value: name
});
return o;
}, [{title: '(none)', value: 'none'}]);
CATMAID.DOM.appendOptionsToSelect(sourceSelect, sourceOptions,
this.selectedSkeletonConstraintSource, true);
};
/**
* Return a promise for a volume from the back-end.
*/
VolumeManagerWidget.prototype.loadVolume = function(volumeId) {
return CATMAID.fetch(project.id + '/volumes/' + volumeId + '/', 'GET')
.then(function(json) {
// Expect box for now
var type = 'box';
// Try to create volume instance
var bbox = json.bbox;
var volumeType = volumeTypes[type];
return volumeType.createVolume({
minX: bbox.min.x,
minY: bbox.min.y,
minZ: bbox.min.z,
maxX: bbox.max.x,
maxY: bbox.max.y,
maxZ: bbox.max.z,
title: json.name,
comment: json.comment,
id: json.id
});
});
};
/**
* Request volume details, show edit controls and display a bounding box
* overlay. If no volume ID is given, a new volume is assumed.
*/
VolumeManagerWidget.prototype.editVolume = function(volume) {
var self = this;
var createNewVolume = !volume;
if (this.currentContext) {
CATMAID.tools.callIfFn(this.currentContext.onExit);
}
var $content = $('#volume_manger_content');
// Hide table
$("div.volume-list", $content).hide();
// Display inline editor for properties of new volume
var $addContent = $(document.createElement('div'));
$addContent.addClass('settings-container volume-properties');
var vid = this.datatable ? this.datatable.length + 1 : 1;
var volumeType, volumeHelper;
if (volume) {
volumeType = getVolumeType(volume);
volumeHelper = volumeTypes[volumeType];
} else {
volumeType = this.newVolumeType;
volumeHelper = volumeTypes[volumeType];
if (!volumeType) {
throw CATMAID.ValueError("Couldn't find volume type: " +
this.newVolumeType);
}
volume = volumeHelper.createVolume({});
}
var title = function(e) { volume.title = this.value; };
var comment = function(e) { volume.comment = this.value; };
if (createNewVolume) {
var typeSelect = CATMAID.DOM.createSelectSetting("Type",
{
"Box": "box",
"Convex Hull": "convexhull",
"Alpha shape": "alphashape"
},
"The geometry type of this volume.", undefined, volumeType);
$addContent.append(typeSelect);
$('select', typeSelect).on('change', function() {
$("div.volume-properties", $content).remove();
self.newVolumeType = this.value;
self.editVolume();
});
}
$addContent.append(CATMAID.DOM.createInputSetting("Name", volume.title,
"This name will be used whereever CATMAID refers to this volume in " +
"its user interface.", title));
$addContent.append(CATMAID.DOM.createInputSetting("Comment", volume.comment,
"Additional information regarding this volume.", comment));
var volumeSettings = volumeHelper.createSettings(volume);
if (!createNewVolume) {
$('input', volumeSettings).attr('disabled', 'disabled');
}
$addContent.append(volumeSettings);
// Create volume update and close handlers (used for preview)
var handlers = volumeHelper.createHandlers(volume);
var onUpdate = handlers[0];
var closeVolumeEdit = handlers[1];
var onClose = function(save, onSuccess, onCancel) {
if (CATMAID.tools.isFn(closeVolumeEdit)) {
var onSuccessWrapper = function() {
volume.off(volume.EVENT_PROPERTY_CHANGED, volumeChanged);
CATMAID.tools.callIfFn(onSuccess);
};
closeVolumeEdit(save, onSuccessWrapper, onCancel);
}
};
$addContent.append($('<div class="clear" />'));
$addContent.append($('<div />')
.append($('<button>Cancel</Cancel>')
.on('click', function(e) {
onClose(false, function() {
// Show table
$("div.volume-list", $content).show();
$("div.volume-properties", $content).remove();
});
}))
.append($('<button>Save</Cancel>')
.on('click', function(e) {
$.blockUI({message: '<img src="' + CATMAID.staticURL +
'images/busy.gif" /> <span>Please wait, creating volume</span>'});
function save() {
try {
onClose(true, function() {
volume.save()
.then(function(result) {
// Show table, remove volume settings
$("div.volume-list", $content).show();
$("div.volume-properties", $content).remove();
}).catch(CATMAID.handleError)
.then(function() {
$.unblockUI();
self.redraw();
});
}, function() {
CATMAID.warn("Couldn't save volume");
$.unblockUI();
});
} catch(e) {
$.unblockUI();
CATMAID.error("Couldn't create volume: " + e);
}
}
setTimeout(save, 100);
})));
$content.append($addContent);
function volumeChanged(field, newValue, oldValue) {
if (CATMAID.tools.isFn(onUpdate)) {
onUpdate(field, newValue, oldValue);
}
}
volume.on(volume.EVENT_PROPERTY_CHANGED, volumeChanged);
this.currentContext = new Context(onClose);
};
/**
* Load volumes from a passed in file path. The file format is expected to be
* JSON. A list of objects with a type and a properties field. For instance:
*
* [{
* "type": "box",
* "properties": {
* "minX": 0,
* "minY": 0,
* "minZ": 0,
* "maxX": 1,
* "maxY": 1,
* "maxZ": 1,
* }
* }]
*
* @param {String} files The file to load
*/
VolumeManagerWidget.prototype.addVolumeFromFile = function(file) {
var self = this;
var reader = new FileReader();
reader.onload = function(e) {
var volumes = JSON.parse(e.target.result);
// Try to load volumes and record invalid ones
var invalidVolumes = volumes.filter(function(v) {
var volumeType = volumeTypes[v.type];
var properties = v.properties;
if (volumeType && properties) {
volumeType.createVolume(properties);
} else {
// Return true for invalid volume types
return !volumeType;
}
});
};
reader.readAsText(file);
};
VolumeManagerWidget.prototype.addVolumesFromSTL = function(files) {
var self = this;
var data = new FormData();
files.forEach(function(file){
data.append(file.name, file, file.name);
});
return new Promise(function(resolve, reject) {
CATMAID.fetch(project.id + "/volumes/import", "POST", data, undefined, undefined, undefined, undefined, {"Content-type" : null})
.then(function(data){
CATMAID.msg("success", Object.keys(data).length + " mesh(s) loaded");
self.redraw();
})
.catch(CATMAID.handleError);
});
};
/**
* Add a new volume. Edit it its properties directly in the widget.
*/
VolumeManagerWidget.prototype.addVolume = function() {
this.editVolume(null);
};
/**
* Annotate all currently selected volumes.
*/
VolumeManagerWidget.prototype.annotateSelectedVolumes = function() {
if (!this.datatable) {
return;
}
let allVolumes = this.datatable.rows({'search': 'applied' }).data().toArray();
let selectedVolumeIds = allVolumes.filter(function(v) {
return v.selected;
}).map(function(v) {
return v.id;
});
if (selectedVolumeIds.length === 0) {
CATMAID.warn("No volumes selected");
return;
}
// Retrieve class instance IDs for volumes
CATMAID.fetch(project.id + '/volumes/entities/', 'POST', {
volume_ids: selectedVolumeIds
})
.then(function(ciMapping) {
return CATMAID.annotate(Object.values(ciMapping));
})
.then(function() {
CATMAID.msg("Success", "Annotations added");
})
.catch(CATMAID.handleError);
};
var getVolumeType = function(volume) {
if (volume instanceof CATMAID.AlphaShapeVolume) {
return "alphashape";
} else if (volume instanceof CATMAID.ConvexHullVolume) {
return "convexhull";
} else if (volume instanceof CATMAID.BoxVolume) {
return "box";
} else {
throw new CATMAID.ValueError("Unknown volume type");
}
};
var addPreviewControls = function(content, volume) {
// Option to control preview
var preview = CATMAID.DOM.createCheckboxSetting(
"Preview in 3D viewer", volume.preview, "If checked the first " +
"available 3D viewer will be used to preview the meshes before saving.",
function(e) { volume.set("preview", this.checked); });
content.append(preview);
// Inject color picker into preview checkbox label
var $previewColor = CATMAID.DOM.createInputSetting(
"Preview color", volume.previewColor,
"Set the color of the volume 3D preview.");
content.append($previewColor);
CATMAID.ColorPicker.enable($('input', $previewColor), {
initialColor: volume.previewColor,
initialAlpha: volume.previewOpacity,
onColorChange: function(color, alpha, colorChanged, alphaChanged) {
if (colorChanged) {
var hexColor = CATMAID.tools.rgbToHex(
Math.round(255 * color.r),
Math.round(255 * color.g),
Math.round(255 * color.b));
volume.set('previewColor', hexColor);
}
if (alphaChanged) {
volume.set('previewOpacity', alpha);
}
}
});
};
var getPreviewHandlers = function(volume) {
// Give some feedback in case of problems
var checkGeneratedMesh = function(volume, mesh) {
var meshNeedsUpdate = false;
if (!mesh || 0 === mesh.length) {
CATMAID.warn("Neither points nor mesh could be generated");
meshNeedsUpdate = true;
} else if (!mesh[0] || 0 === mesh[0].length) {
CATMAID.warn("Couldn't find points for volume generation");
meshNeedsUpdate = true;
} else if (!mesh[1] || 0 === mesh[1].length) {
CATMAID.warn("Couldn't generate volume from degenerative points");
meshNeedsUpdate = true;
}
volume.meshNeedsSync = meshNeedsUpdate;
return !meshNeedsUpdate;
};
var onUpdate = function(field, newValue, oldValue) {
// Recalculate mesh if preview was just enabled
if (volume.preview && "preview" === field) {
volume.meshNeedsSync = true;
}
// Re-create mesh if the updated field is no 'basic' property to avoid
// unnecessary re-calculation.
if (volume.preview && volume.meshNeedsSync) {
$.blockUI({message: '<img src="' + CATMAID.staticURL +
'images/busy.gif" /> <span>Please wait, creating volume</span>'});
var onSuccess = function(volume, mesh) {
checkGeneratedMesh(volume, mesh);
$.unblockUI();
};
var updateMesh = volume.updateTriangleMesh.bind(volume, onSuccess,
$.unblockUI.bind($));
setTimeout(updateMesh, 100);
} else if (!volume.preview && "preview" === field) {
// Preview just got disabled
volume.clearPreviewData();
}
};
var onClose = function(save, onSuccess, onCancel) {
if (save) {
var onSuccessWrapper = function(volume, mesh) {
if (checkGeneratedMesh(volume, mesh)) {
CATMAID.tools.callIfFn(onSuccess);
} else {
CATMAID.tools.callIfFn(onCancel);
}
// Remove previewed meshes from 3D viewer
volume.clearPreviewData();
};
if (volume.meshNeedsSync) {
volume.updateTriangleMesh(onSuccessWrapper);
} else {
onSuccessWrapper(volume, volume.mesh);
}
} else {
// Remove previewed meshes from 3D viewer
volume.clearPreviewData();
CATMAID.tools.callIfFn(onSuccess);
}
};
return [onUpdate, onClose];
};
/**
* Either convex hull or alpha-shape, which are almost identical. The
* alpha-shape has an extra parameter, the alpha.
*/
var makeVolume = function(name, theclass, withAlpha) {
return {
name: name,
createSettings: function(volume) {
// TODO source is never used?
var source = function(e) {
var source = CATMAID.skeletonListSources.getSource(this.value);
volume.set("neuronSource", source);
};
var ruleType = function(e) { };
var $settings = $('<div />');
var $content = CATMAID.DOM.addSettingsContainer($settings,
name + " rule settings", false);
addPreviewControls($content, volume);
// The skeleton source
var availableSources = CATMAID.skeletonListSources.getSourceNames();
var sourceOptions = availableSources.reduce(function(o, name) {
o[name] = name;
return o;
}, {});
// Set a default source, if there is no source set yet
if (!volume.neuronSourceName && availableSources.length > 0) {
volume.set("neuronSourceName", availableSources[0]);
}
$content.append(CATMAID.DOM.createCheckboxSetting("Respect node radius",
volume.respectRadius, "If checked, every valid node with a radius will " +
"trigger the creation of 12 additional equally distibuted points around it, " +
"having a distance of the node's radius.",
function(e) { volume.set("respectRadius", this.checked); }));
$content.append(CATMAID.DOM.createSelectSetting("Skeleton source",
sourceOptions, "The selection to draw points from", function(e) {
volume.set("neuronSourceName", this.value);
}, volume.neuronSourceName));
if (withAlpha) {
var defaultAlphaStep = 10.0;
var alphaInputWrapper = CATMAID.DOM.createNumericInputSetting("Alpha (nm)",
volume.alpha, defaultAlphaStep,
"Only triangles with a circumsphere radius less than alpha will be used",
function(e) {
volume.set("alpha", Number(this.value));
});
$content.append(alphaInputWrapper);
// Also update on mouse clicks and mouse wheel
var alphaInput = alphaInputWrapper.find('input');
alphaInput.on('mouseup mousewheel', function() {
volume.set("alpha", Number(this.value));
});
$content.append(CATMAID.DOM.createNumericInputSetting("",
defaultAlphaStep, 10.0, "Set the alpha change step for the numeric input above",
function(e) {
alphaInput.prop('step', Number(this.value));
}));
$content.append(CATMAID.DOM.createCheckboxSetting("Filter triangles",
volume.filterTriangles, "If checked, the alpha filter will be " +
"applied to individual triangles of the mesh. Otherwise, alpha " +
"is used to filter the tetrahedra of the 3D triangulation.",
function(e) { volume.set("filterTriangles", this.checked); }));
}
// Get available filter strategeis
var nodeFilters = Object.keys(CATMAID.SkeletonFilterStrategy).reduce(function(o, p) {
o[CATMAID.SkeletonFilterStrategy[p].name] = p;
return o;
}, {});
CATMAID.DOM.appendNewNodeFilterControls('skeleton', nodeFilters,
$content, function(rule, strategt) {
if (datatable) {
volume.rules.push(rule);
// To trigger events, override with itself
volume.set("rules", volume.rules, true);
// Trigger table update
datatable.rows().invalidate();
datatable.ajax.reload();
}
});
// Get available rules
var table = document.createElement('table');
table.style.width = "100%";
var header = table.createTHead();
var hrow = header.insertRow(0);
var columns = ['On', 'Name', 'Merge mode', 'Options', 'Is skeleton', 'Has name'];
columns.forEach(function(c) {
hrow.insertCell().appendChild(document.createTextNode(c));
});
var self = this;
var tableContainer = document.createElement('div');
tableContainer.appendChild(table);
$content.append(tableContainer);
var datatable = $(table).DataTable({
dom: "tp",
ajax: function(data, callback, settings) {
var rules = volume.rules;
callback({
draw: data.draw,
recordsTotal: rules.length,
recordsFiltered: rules.length,
data: rules
});
},
order: [],
columns: [
{
orderable: false,
render: function(data, type, row, meta) {
var checked = !row.skip;
return '<input type="checkbox" ' + (checked ? 'checked /> ' : '/>');
}
},
{
orderable: false,
data: "strategy.name"
},
{
orderable: false,
render: function(data, type, row, meta) {
return row.mergeMode === CATMAID.UNION ? "Union" :
(row.mergeMode === CATMAID.INTERSECTION ? "Intersection" : row.mergeMode);
}
},
{
orderable: false,
render: function(data, type, row, meta) {
return row.options ? JSON.stringify(row.options) : "-";
}
},
{
orderable: false,
render: function(data, type, row, meta) {
return row.validOnlyForSkid ? row.validOnlyForSkid : "-";
}
},
{
orderable: false,
render: function(data, type, row, meta) {
return row.validOnlyForName ? row.validOnlyForName : "-";
}
}
],
language: {
emptyTable: "No filters added yet (defaults to take all nodes)"
}
});
// Updated skipping of rules
$(table).on('change', 'td', function(e) {
var tr = $(this).closest("tr");
var rule = datatable.row(tr).data();
rule.skip = !e.target.checked;
// Trigger events
volume.set("rules", volume.rules, true);
});
if (volume.preview) {
volume.updateTriangleMesh();
}
return $settings;
},
createVolume: function(options) {
var volume = new CATMAID[theclass](options);
volume.init();
return volume;
},
/**
* Create an array of handlers: [onVolumeUpdate, onVolumeClose]
*/
createHandlers: function(volume) {
return getPreviewHandlers(volume);
},
};
};
var volumeTypes = {
"box": {
name: "Box",
createSettings: function(volume) {
var $settings = $('<div />');
var $content = CATMAID.DOM.addSettingsContainer($settings,
"Box settings", false);
// Regular box properties
var minX = function(e) { volume.set("minX", Number(this.value)); };
var minY = function(e) { volume.set("minY", Number(this.value)); };
var minZ = function(e) { volume.set("minZ", Number(this.value)); };
var maxX = function(e) { volume.set("maxX", Number(this.value)); };
var maxY = function(e) { volume.set("maxY", Number(this.value)); };
var maxZ = function(e) { volume.set("maxZ", Number(this.value)); };
let inputMinX = CATMAID.DOM.createInputSetting("Min X", volume.minX,
"X coordinate of the boxes minimum corner.", minX);
let inputMinY = CATMAID.DOM.createInputSetting("Min Y", volume.minY,
"Y coordinate of the boxes minimum corner.", minY);
let inputMinZ = CATMAID.DOM.createInputSetting("Min Z", volume.minZ,
"Z coordinate of the boxes minimum corner.", minZ);
let inputMaxX = CATMAID.DOM.createInputSetting("Max X", volume.maxX,
"X coordinate of the boxes maximum corner.", maxX);
let inputMaxY = CATMAID.DOM.createInputSetting("Max Y", volume.maxY,
"Y coordinate of the boxes maximum corner.", maxY);
let inputMaxZ = CATMAID.DOM.createInputSetting("Max Z", volume.maxZ,
"Z coordinate of the boxes maximum corner.", maxZ);
// Helper to create a cube at the current location with a particular
// edge length.