forked from ome/omero-iviewer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathol3-viewer.js
More file actions
executable file
·1764 lines (1624 loc) · 67.2 KB
/
Copy pathol3-viewer.js
File metadata and controls
executable file
·1764 lines (1624 loc) · 67.2 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
//
// Copyright (C) 2017 University of Dundee & Open Microscopy Environment.
// All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// dependencies
import Context from '../app/context';
import Misc from '../utils/misc';
import {Converters} from '../utils/converters';
import Ui from '../utils/ui';
import {inject, customElement, bindable, BindingEngine} from 'aurelia-framework';
import Viewer from './viewer/Viewer';
import Ol3ViewerLinkedEvents from './ol3-viewer-linked-events';
import * as FileSaver from '../../node_modules/file-saver';
import {draggable} from 'jquery-ui/ui/widgets/draggable';
import {resizable} from 'jquery-ui/ui/widgets/resizable';
import {
IMAGE_CONFIG_RELOAD, IVIEWER, PLUGIN_PREFIX, PROJECTION,
REGIONS_DRAWING_MODE, RENDER_STATUS, VIEWER_ELEMENT_PREFIX,
REQUEST_PARAMS
} from '../utils/constants';
import {
IMAGE_CANVAS_DATA, IMAGE_DIMENSION_CHANGE, IMAGE_DIMENSION_PLAY,
IMAGE_SETTINGS_CHANGE, IMAGE_SETTINGS_REFRESH,
IMAGE_VIEWER_CONTROLS_VISIBILITY, IMAGE_VIEWER_INTERACTION,
IMAGE_VIEWER_RESIZE, IMAGE_VIEWPORT_CAPTURE, IMAGE_VIEWPORT_LINK,
REGIONS_CHANGE_MODES, REGIONS_COPY_SHAPES, REGIONS_DRAW_SHAPE,
REGIONS_GENERATE_SHAPES, REGIONS_HISTORY_ACTION, REGIONS_HISTORY_ENTRY,
REGIONS_MODIFY_SHAPES, REGIONS_PROPERTY_CHANGED, REGIONS_SET_PROPERTY,
REGIONS_SHOW_COMMENTS, REGIONS_STORED_SHAPES, REGIONS_STORE_SHAPES,
VIEWER_IMAGE_SETTINGS, VIEWER_PROJECTIONS_SYNC, VIEWER_SET_SYNC_GROUP,
ENABLE_SHAPE_POPUP, TILE_LOAD_ERROR, RENDER_COMPLETE,
EventSubscriber
} from '../events/events';
const MOVIE_DELAY = 250;
/**
* The openlayers 3 viewer wrapped for better aurelia integration
* @extends {EventSubscriber}
*/
@customElement('ol3-viewer')
@inject(Context, Element, BindingEngine)
export default class Ol3Viewer extends EventSubscriber {
/**
* handles mdi group syncing
* @memberof Ol3Viewer
* @type {Ol3ViewerLinkedEvents}
*/
linked_events = new Ol3ViewerLinkedEvents(this);
/**
* the image config reference to work with (bound via template)
* @memberof Ol3Viewer
* @type {ImageConfig}
*/
@bindable image_config = null;
/**
* the image info ready observers
* @memberof Ol3Viewer
* @type {Object}
*/
image_info_ready_observer = null;
/**
* watches for selection changes
* @memberof Ol3Viewer
* @type {Object}
*/
image_config_selection_observer = null;
/**
* the internal instance of the ol3.Viewer
* @memberof Ol3Viewer
* @type {ol3.Viewer}
*/
viewer = null;
/**
* the info needed for the play loop
* @memberof Ol3Viewer
* @type {number}
*/
player_info = {dim: null, forwards: null, handle: null};
/**
* events we subscribe to
* @memberof Ol3Viewer
* @type {Array.<string,function>}
*/
sub_list = [
[ENABLE_SHAPE_POPUP,
(params={}) => this.enableShapePopup(params)],
[IMAGE_VIEWER_INTERACTION,
(params={}) => this.handleViewerInteraction(params)],
[IMAGE_VIEWER_CONTROLS_VISIBILITY,
(params={}) => this.toggleControlsVisibility(params)],
[IMAGE_VIEWER_RESIZE,
(params={}) => this.resizeViewer(params)],
[IMAGE_DIMENSION_CHANGE,
(params={}) => this.changeDimension(params)],
[IMAGE_DIMENSION_PLAY,
(params={}) => this.playDimension(params)],
[RENDER_COMPLETE,
(params={}) => this.handleRenderComplete(params)],
[IMAGE_SETTINGS_CHANGE,
(params={}) => this.changeImageSettings(params)],
[REGIONS_PROPERTY_CHANGED,
(params={}) => this.getRegionsPropertyChange(params)],
[REGIONS_SET_PROPERTY,
(params={}) => this.setRegionsProperty(params)],
[VIEWER_IMAGE_SETTINGS,
(params={}) => this.getImageSettings(params)],
[VIEWER_PROJECTIONS_SYNC,
(params={}) => this.syncImageSettingsProjections(params)],
[REGIONS_CHANGE_MODES,
(params={}) => this.changeRegionsModes(params)],
[REGIONS_DRAW_SHAPE,
(params={}) => this.drawShape(params)],
[REGIONS_GENERATE_SHAPES,
(params={}) => this.generateShapes(params)],
[REGIONS_STORE_SHAPES,
(params={}) => this.storeShapes(params)],
[REGIONS_STORED_SHAPES,
(params={}) => this.afterShapeStorage(params)],
[REGIONS_MODIFY_SHAPES,
(params={}) => this.modifyShapes(params)],
[REGIONS_HISTORY_ENTRY,
(params={}) => this.addHistoryEntry(params)],
[REGIONS_HISTORY_ACTION,
(params={}) => this.affectHistoryAction(params)],
[REGIONS_COPY_SHAPES,
(params={}) => this.copyShapeDefinitions(params)],
[REGIONS_SHOW_COMMENTS,
(params={}) => this.showComments(params)],
[IMAGE_VIEWPORT_CAPTURE,
(params={}) => this.captureViewport(params)],
[IMAGE_VIEWPORT_LINK,
(params={}) => this.linkViewport(params)],
[IMAGE_CANVAS_DATA,
(params={}) => this.saveCanvasData(params)],
[VIEWER_SET_SYNC_GROUP,
(params={}) => this.setSyncGroup(params)],
[TILE_LOAD_ERROR,
(params={}) => Ui.showModalMessage("Failed to load tiles.<br>Please try refreshing the page.", "OK")],
[IMAGE_SETTINGS_REFRESH,
(params={}) => this.refreshImageSettings(params)]];
/**
* @constructor
* @param {Context} context the application context (injected)
* @param {Element} element the associated dom element (injected)
* @param {BindingEngine} bindingEngine injected instance of BindingEngine
*/
constructor(context, element, bindingEngine) {
super(context.eventbus)
this.context = context;
this.element = element;
this.bindingEngine = bindingEngine;
}
/**
* Returns the viewer's container element
*
* @return {Object} the viewer's html container(jquery)
* @memberof Ol3Viewer
*/
getContainer() {
return $(this.element).parent();
}
/**
* Get the possible x & y coordinates for newly opened viewers.
* These represent 4 positions in a 2 x 2 grid in centre of the frame.
*
* @memberof Ol3Viewer
* @param {jQuery object} frame that contains viewers
* @param {Object} viewer_size of the image with {width, height}
* @return {list} of Objects with top and left coordinates
*/
getInitialViewerPositions(frame, viewer_size) {
let left = frame.position().left;
let top = frame.position().top;
let width = frame.width();
let height = frame.height();
let viewer_w = parseInt(viewer_size.width);
let viewer_h = parseInt(viewer_size.height);
return [
{top: Math.max(0, top + (height/2) - viewer_h), left: left + (width/2) - viewer_w},
{top: Math.max(0, top + (height/2) - viewer_h), left: left + (width/2)},
{top: top + (height/2), left: left + (width/2) - viewer_w},
{top: top + (height/2), left: left + (width/2)},
]
}
/**
* Get the best position for newly opened viewer.
* Try each of 4 positions in a 2 x 2 grid in centre of the frame,
* returning {top: '0px', left: '0px'} for first empty place.
*
* @memberof Ol3Viewer
* @param {jQuery object} frame that contains viewers
* @param {Object} viewer_size of the image with {width, height}
* @return {Object} with top and left coordinates
*/
getNewViewerPosition(frame, viewer_size) {
let positions = this.getInitialViewerPositions(frame, viewer_size);
let context = this.image_config.context;
let viewer_width = parseInt(viewer_size.width);
let viewer_height = parseInt(viewer_size.height);
// Try each of the 4 positions in a 2 x 2 grid, looking for a space
let new_pos;
for (let i=0; i<positions.length; i++) {
let pos = positions[i];
// Are any viewers occupying the centrepoint of this grid position?
let viewers = context.getImageConfigsAtPosition(pos.left + viewer_width/2,
pos.top + viewer_height/2);
if (viewers.length === 0) {
// if not, we use this position for the newly opened window
new_pos = {left: pos.left + 'px', top: pos.top + 'px'};
break;
}
}
return new_pos;
}
/**
* Overridden aurelia lifecycle method:
* fired when PAL (dom abstraction) is ready for use
*
* @memberof Ol3Viewer
*/
attached() {
let frame = $('.frame');
let minX = 0, maxX = 0, minY = 0, maxY = 0;;
let container = this.getContainer();
let config_ids = Array.from(this.image_config.context.image_configs.keys());
let config_index = config_ids.indexOf(this.image_config.id);
// set previous position for mdi 'replacement'
if (this.image_config.position === null) {
let viewer_width = parseInt(this.image_config.size.width);
let viewer_height = parseInt(this.image_config.size.height);
minX = frame.position().left+10;
maxX = frame.position().left+frame.width() - viewer_width;
minY = frame.position().top+10;
maxY = frame.position().top+frame.height() - viewer_height;
// Try each of the 4 positions in a 2 x 2 grid, looking for a space
let new_pos = this.getNewViewerPosition(frame, this.image_config.size);
// If all occupied, use random spot
if (!new_pos) {
new_pos = {
top: Misc.getRandomInteger(minY,maxY) + 'px',
left: Misc.getRandomInteger(minX,maxX) + 'px'
};
}
this.image_config.position = new_pos;
}
// make viewer windows draggable/resizable within boundaries
container.draggable({
handle: '.viewer-handle',
start: () => {
minX = frame.position().left + 100 - parseInt(this.image_config.size.width, 10);
minY = 0;
// Width is smaller when thumbs expanded. Fix by adding pos.left
maxX = frame.width() + frame.position().left - 100;
maxY = frame.height() - 100;
},
drag: (event, ui) => {
// Help keep header within draggable area
ui.position.top = Math.max(minY, ui.position.top);
ui.position.top = Math.min(maxY, ui.position.top);
ui.position.left = Math.max(minX, ui.position.left);
ui.position.left = Math.min(maxX, ui.position.left);
},
stop: (event, ui) => {
this.image_config.position.top = ui.position.top + 'px';
this.image_config.position.left = ui.position.left + 'px';
}
});
container.resizable({
containment: "parent", handles: 'se',
stop: (e, ui) => {
this.image_config.size.width = ui.size.width + 'px';
this.image_config.size.height = ui.size.height + 'px';
this.resizeViewer();
}
});
this.createObservers();
}
/**
* Creates Observers (used internally)
*
* @private
* @memberof Ol3Viewer
*/
createObservers() {
let imageDataReady = () => {
// refresh image settings only
if (this.image_config.image_info.refresh) {
this.viewer.changeImageModel(
this.image_config.image_info.model);
let channels = this.image_config.image_info.channels;
let updates = [];
for (let i=0;i<channels.length;i++) {
let chan = channels[i];
let chanUpdate = {
index: i,
active: chan.active,
start: chan.window.start,
end: chan.window.end,
color: chan.color,
inverted: chan.inverted
};
if (typeof chan.family === 'string' && chan.family !== "" &&
typeof chan.coefficient === 'number' &&
!isNaN(chan.coefficient)) {
chanUpdate.family = chan.family;
chanUpdate.coefficient = chan.coefficient;
}
updates.push(chanUpdate);
};
this.viewer.changeChannelRange(updates);
// Viewer must know its current settings are the saved settings
this.saveImageSettings();
this.image_config.image_info.refresh = false;
return;
}
// create viewer instance, register event subscriptions
this.initViewer();
this.subscribe();
// listen to when the regions info data is ready
this.regions_info_ready_observer =
this.bindingEngine.propertyObserver(
this.image_config.regions_info, 'ready').subscribe(
(newValue, oldValue) => {
if (this.viewer === null) return;
this.viewer.removeRegions();
if (newValue) {
this.initRegions();
delete this.image_config.regions_info.tmp_data;
}
});
// mdi needs to switch image config when using controls
this.getContainer().find('.ol-control').on(
'mousedown',
() => this.context.selectConfig(this.image_config.id))
};
// listen via the observer for image ready changes
this.image_info_ready_observer =
this.bindingEngine.propertyObserver(
this.image_config.image_info, 'ready').subscribe(
(newValue, oldValue) => {
if (!oldValue && newValue) imageDataReady();
});
// listens to image config changes for mdi
this.image_config_selection_observer =
this.bindingEngine.propertyObserver(
this.context, 'selected_config').subscribe(
(newValue, oldValue) => {
this.resizeViewer({config_id: newValue, delay: 200});
if (!this.context.useMDI ||
oldValue !== this.image_config.id ||
newValue === null ||
!this.image_config.regions_info.hasBeenModified()) {
return;
}
let sameImageConfs =
this.context.getImageConfigsForGivenImage(
this.image_config.image_info.image_id,
this.image_config.id);
if (sameImageConfs.length === 0) return;
// we have another image config for the same image
// let's prompt the user with a warning about rois
Ui.showConfirmationDialog(
'Save ROIs?',
'You have changed ROI(s) on an image ' +
'that\'s been opened multiple times.<br>' +
'Do you want to save now to avoid ' +
'inconsistence (and a potential loss ' +
'of some of your changes)?' ,
() => this.storeShapes(
{"config_id": this.image_config.id}));
});
}
/**
* Overridden aurelia lifecycle method:
* called whenever the view is bound within aurelia
* in other words an 'init' hook that happens before 'attached'
*
* @memberof Ol3Viewer
*/
bind() {
// we 'tag' the element to belong to a certain image config
this.element.parentNode.id = this.image_config.id;
// define the container element
this.container = VIEWER_ELEMENT_PREFIX + this.image_config.id;
}
/**
* Overridden aurelia lifecycle method:
* fired when PAL (dom abstraction) is unmounted
*
* @memberof Ol3Viewer
*/
detached() {
if (this.context.useMDI) {
let container = this.getContainer();
container.find('.ol-control').off('mousedown');
try {container.draggable("destroy")} catch(ignored) {}
try {container.resizable("destroy")} catch(ignored) {}
}
if (this.viewer) {
this.viewer.destroyViewer();
this.viewer = null;
}
}
/**
* Overridden aurelia lifecycle method:
* called whenever the view is unbound within aurelia
* in other words a 'destruction' hook that happens after 'detached'
*
* @memberof Ol3Viewer
*/
unbind() {
if (this.image_config_selection_observer) {
this.image_config_selection_observer.dispose();
this.image_config_selection_observer = null;
}
if (this.image_info_ready_observer) {
this.image_info_ready_observer.dispose();
this.image_info_ready_observer = null;
}
if (this.regions_info_ready_observer) {
this.regions_info_ready_observer.dispose();
this.regions_info_ready_observer = null;
}
this.unsubscribe();
this.viewer = null;
this.image_config = null;
}
/**
* Instantiates a new ol3 viewer once image data is ready
*
* @memberof Ol3Viewer
*/
initViewer() {
// tweak initParams for ol3viewer to reflect iviewer app name
let ol3initParams = Object.assign({}, this.context.initParams);
ol3initParams[PLUGIN_PREFIX] = this.context.getPrefixedURI(IVIEWER);
// create viewer instance
this.viewer =
new Viewer(
this.image_config.image_info.image_id, {
eventbus : this.context.eventbus,
server : this.context.server,
data: this.image_config.image_info.tmp_data,
initParams : ol3initParams,
container: this.container
});
delete this.image_config.image_info.tmp_data;
// hide controls for mdi when more than 1 image configs
if (this.context.useMDI && this.context.image_configs.size > 1)
this.toggleControlsVisibility({
config_id: this.image_config.id, flag: false
});
// only the first request should be affected, besides mirror controls
let mirrorEnabled = this.context.getInitialRequestParam(REQUEST_PARAMS.ENABLE_MIRROR)
this.context.resetInitParams();
this.context.initParams[REQUEST_PARAMS.ENABLE_MIRROR] = mirrorEnabled
// use existing interpolation setting
this.viewer.enableSmoothing(this.context.interpolate);
// zoom to fit
this.viewer.zoomToFit();
// initialize regions if rois tab active
if (this.context.isRoisTabActive()) this.initRegions();
this.resizeViewer({window_resize: true, delay: 100});
}
/**
* Handles dimension changes which come in the form of an event notification
*
* @memberof Ol3Viewer
* @param {Object} params the event notification parameters
*/
changeDimension(params = {}) {
// we ignore notifications that don't concern us
// and need a dim identifier as well an array value
if (this.viewer === null ||
typeof params.dim !== 'string' ||
!Misc.isArray(params.value) ||
params.value.length === 0) return;
if (params.config_id === this.image_config.id) {
this.viewer.setDimensionIndex(params.dim, params.value);
// cache the Z/T change to the context
let toCache = {};
toCache[params.dim] = params.value[0];
let imageId = this.viewer.getId();
this.context.setCachedImageSettings(imageId, toCache);
}
else {
this.linked_events.syncAction(params, "setDimensionIndex");
}
}
/**
* Handles the following image changes:
* - channel range (start, end, color)
* - color/grayscale
* - projection
* - interpolation
*
* @memberof Ol3Viewer
* @param {Object} params the event notification parameters
*/
changeImageSettings(params = {}) {
if (this.viewer === null) return;
let isSameConfig = params.config_id === this.image_config.id;
if (typeof params.model === 'string') {
if (isSameConfig) this.viewer.changeImageModel(params.model);
else this.linked_events.syncAction(params, "changeImageSettings");
} else if (isSameConfig && typeof params.projection === 'string') {
this.viewer.changeImageProjection(
params.projection,
Object.assign({}, params.projection_opts));
this.context.publish(VIEWER_PROJECTIONS_SYNC, params);
} else if (Misc.isArray(params.ranges) && params.ranges.length > 0) {
if (isSameConfig) this.viewer.changeChannelRange(params.ranges);
else this.linked_events.syncAction(params, "changeImageSettings");
} else if (typeof params.interpolate === 'boolean')
this.viewer.enableSmoothing(params.interpolate);
// Save settings to cache
if (isSameConfig) {
this.cacheImageSettings(params);
}
}
/**
* Cache the current settings to the context
*
* @memberof Ol3Viewer
* @param {Object} params the event notification parameters
*/
cacheImageSettings(params = {}) {
if (this.viewer === null) return;
let settings = this.viewer.captureViewParameters();
let toCache = {
channels: settings.channels,
model: settings.model,
}
if (params.projection) {
// Use the params for projection instead of settings since it's
// in the format we need for the viewer
toCache.projection = params.projection;
toCache.projection_opts = params.projection_opts;
}
let imageId = this.viewer.getId();
this.context.setCachedImageSettings(imageId, toCache);
}
/**
* Settings have changed so we need to refresh
*
* @memberof Ol3Viewer
* @param {Object} params the event notification parameters
*/
refreshImageSettings(params = {}) {
if (this.viewer === null || this.image_config === null ||
this.image_config.id !== params.config_id) return;
this.viewer.refreshBirdsEye(500);
this.saveImageSettings(params);
}
/**
* Viewer needs to know when saved settings have changed since it uses the
* difference between current and saved settings to build render query string
*
* @memberof Ol3Viewer
* @param {Object} params the event notification parameters
*/
saveImageSettings(params = {}) {
if (this.viewer === null) return;
this.viewer.updateSavedSettings();
}
/**
* Syncs projection (toggle, settings)
* @memberof Ol3Viewer
* @param {Object} params the event notification parameters
*/
syncImageSettingsProjections(params = {}) {
// we are syncing only with configs other than the originating
if (typeof params.config_id !== 'number' ||
params.config_id === this.image_config.id) return;
this.linked_events.syncAction(params, "setProjection");
}
/**
* In case of a resize we are forced to issue a redraw for the ol3 Viewer
* which is especially important for the regions layer
*
* @memberof Ol3Viewer
* @param {Object} params the event notification parameters
*/
resizeViewer(params={}) {
if (this.viewer === null ||
(typeof params.config === 'number' &&
!isNaN(params.config_id) && params.config !== -1 &&
params.config_id !== this.image_config.id)) return;
// while dragging does not concern us
if (typeof params.is_dragging !== 'boolean') params.is_dragging = false;
if (params.is_dragging) return;
this.viewer.redraw(params.delay);
}
/**
* Handles regions property changes received from the ol3 viewer,e.g.
* selection, modification, deletetion
*
* @param {Object} params the event notification parameters
* @memberof Ol3Viewer
*/
getRegionsPropertyChange(params = {}) {
// the shapes has to be an array.
// if the properties and values are an array they have to be in a 1:1
// relationship to the shapes, otherwise they have to be a simple string
// or at least not undefined in which case one property/value respectively
// belongs to multiple shapes
if (typeof params !== 'object' ||
params.config_id !== this.image_config.id ||
!Misc.isArray(params.shapes) || params.shapes.length === 0 ||
(!Misc.isArray(params.properties) &&
typeof params.properties !== 'string') ||
(Misc.isArray(params.properties) &&
params.properties.length !== params.shapes.length) ||
(!Misc.isArray(params.values) &&
typeof params.values === 'undefined') ||
(Misc.isArray(params.values) &&
params.values.length !== params.shapes.length)) return;
// loop over all shapes, trying to set the property
for (let i in params.shapes) {
let shape = params.shapes[i];
let refOrCopy =
this.image_config.regions_info.data ?
this.image_config.regions_info.getShape(shape) : null;
let hasBeenModified = refOrCopy ? refOrCopy.modified : null;
let prop = Misc.isArray(params.properties) ?
params.properties[i] : params.properties;
let value = Misc.isArray(params.values) ?
params.values[i] : params.values;
if (prop === 'selected' || prop === 'modified' ||
prop === 'deleted' || prop === 'visible')
this.image_config.regions_info.setPropertyForShape(
shape, prop, value);
// in the case of new shapes that get deleted we will need
// a deep copy since they get removed from the map
if (refOrCopy && prop === 'deleted')
refOrCopy = Object.assign({}, refOrCopy);
if (typeof params.callback === 'function')
params.callback(refOrCopy, hasBeenModified);
// update measurement info (if shape was modified)
if (prop === 'modified') {
let measurements =
this.viewer.getLengthAndAreaForShapes([shape], true);
if (Misc.isArray(measurements) &&
measurements.length > 0 &&
measurements[0].id === shape) {
refOrCopy.Area = measurements[0].Area;
refOrCopy.Length = measurements[0].Length;
}
}
}
}
/**
* Handles regions property changes such as visibility and selection
* by delegation to sub handlers
*
* @param {Object} params the event notification parameters
* @memberof Ol3Viewer
*/
setRegionsProperty(params = {}) {
// at a minimum we need a viewer and params with a property
if (this.viewer === null ||
typeof params !== 'object' ||
typeof params.property !== 'string'||
params.config_id !== this.image_config.id) return
// delegate to individual handler
let prop = params.property.toLowerCase();
if (prop === 'visible')
this.viewer.setRegionsVisibility(params.value, params.shapes);
else if (prop === 'selected')
this.changeShapeSelection(params);
else if (prop === 'state')
this.deleteShapes(params);
}
/**
* Generates shape for both, pasting and propagation
*
* @param {Object} params the event notification parameters
* @memberof Ol3Viewer
*/
generateShapes(params = {}) {
//we want only notifications that concern us
// and need at least a viewer one shape definition in an array
if (params.config_id !== this.image_config.id ||
this.viewer === null ||
!Misc.isArray(params.shapes) ||
params.shapes.length === 0) return;
if (typeof params.number !== 'number') params.number = 1;
if (typeof params.roi_id !== 'number')
params.roi_id = this.image_config.regions_info.getNewRegionsId();
let theDims =
Misc.isArray(params.theDims) && params.theDims.length !== 0 ?
params.theDims : null;
params.shapes.map((def) => {
try {
if (!def.deleted) {
let deepCopy = Object.assign({},def);
// we are modified so let's update the definition
// before we generate from it
if (deepCopy.modified) {
let upToDateDef =
this.viewer.getShapeDefinition(deepCopy.shape_id);
if (upToDateDef)
deepCopy =
Converters.amendShapeDefinition(upToDateDef);
}
delete deepCopy['shape_id'];
if (typeof params.paste === 'boolean' && params.paste)
deepCopy['roi_id'] =
this.image_config.regions_info.getNewRegionsId();
else deepCopy['roi_id'] = params.roi_id;
let opts = {
'number': params.number,
'position': params.position,
'is_compatible': params.is_compatible,
'extent': this.viewer.getSmallestViewExtent(),
'theDims': theDims
};
if (typeof params.add_history === 'boolean')
opts['add_history'] = params.add_history;
if (typeof params.hist_id === 'number')
opts['hist_id'] = params.hist_id;
this.viewer.generateShapes(deepCopy, opts);
};
} catch(ignored) {}
});
}
/**
* Changes the deleted state of shapes
*
* @param {Object} params the event notification parameters
* @memberof Ol3Viewer
*/
deleteShapes(params = {}) {
//we want only notifications that concern us
// and need at least a viewer instance and
//one shape id in the array as well as a value
// for the action, either delete or undo
if (params.config_id !== this.image_config.id ||
this.viewer === null ||
typeof params.value !== 'string' ||
!Misc.isArray(params.shapes) || params.shapes.length === 0) return;
if (params.value === 'delete')
this.viewer.deleteShapes(params.shapes, false, params.callback);
else if (params.value === 'undo')
this.viewer.deleteShapes(params.shapes, true);
}
/**
* Changes the selected state of shapes
* by delegation to sub handlers
*
* @param {Object} params the event notification parameters
* @memberof Ol3Viewer
*/
changeShapeSelection(params = {}) {
//we want only notifications that concern us
// and need at least a viewer instance and one shape id in the array
if (params.config_id !== this.image_config.id ||
this.viewer === null ||
!Misc.isArray(params.shapes) ||
params.shapes.length === 0) return;
// switch to plane/time/channel that shape to be selected is on
let shapeSelection = params.shapes[params.shapes.length-1];
// for de-selecting (value is false) the last selected shape is chosen (if exists)
if (!params.value) {
let numberOfSelectedShapes =
this.image_config.regions_info.selected_shapes.length;
if (numberOfSelectedShapes > 0) {
let lastSelected =
this.image_config.regions_info.selected_shapes[
numberOfSelectedShapes-1];
// if last-selected is not being de-selected, select it
if (lastSelected !== shapeSelection) {
shapeSelection = lastSelected;
} else if (numberOfSelectedShapes > 1) {
// or previous shape...
shapeSelection =
this.image_config.regions_info.selected_shapes[
numberOfSelectedShapes-2];
} else {
// or nothing
shapeSelection = null;
}
} else shapeSelection = null;
}
let delay = 0;
if (shapeSelection) {
let viewerT = this.viewer.getDimensionIndex('t');
let viewerZ = this.viewer.getDimensionIndex('z');
let viewerC = this.viewer.getDimensionIndex('c');
// Update this.image_config.image_info to load a new Z/T plane...
let shape =
this.image_config.regions_info.getShape(shapeSelection);
let correctPlane = true;
let shapeT = typeof shape.TheT === 'number' ? shape.TheT : -1;
if (shapeT !== -1 && shapeT !== viewerT) {
this.image_config.image_info.dimensions.t = shapeT;
correctPlane = false;
delay += 25;
}
let shapeZ = typeof shape.TheZ === 'number' ? shape.TheZ : -1;
if (shapeZ !== -1 && shapeZ !== viewerZ) {
this.image_config.image_info.dimensions.z = shapeZ;
correctPlane = false;
delay += 25;
}
if (correctPlane) {
// remove initial_shape_id, so we don't get directed to shape again when browsing
// a new plane, (when ROIs are loaded and initRegions() is called again)
this.image_config.image_info.initial_shape_id = undefined;
} else {
// browsing to new plane - this will select Shape when ROIs load
this.image_config.image_info.initial_shape_id = shape['@id'];
}
let shapeC = typeof shape.TheC === 'number' ? shape.TheC : -1;
if (shapeC !== -1 && viewerC.indexOf(shapeC) === -1) {
this.image_config.image_info.channels[shapeC].active = true;
delay += 25;
}
}
setTimeout(() => {
this.abortDrawing();
this.viewer.selectShapes(
params.shapes, params.value, params.clear,
params.center ? shapeSelection : null, params.zoomToShape);
// If we've just selected a bunch of shapes, hide the ShapeEditPopup
if (params.shapes.length > 1) {
this.viewer.viewer_.getOverlays().forEach(o => {
if (o.hideShapeEditPopup) {
o.hideShapeEditPopup();
}
});
}
}, delay);
}
/**
* Queries the present image settings of the viewer
*
* @param {Object} params the event notification parameters
* @memberof Ol3Viewer
*/
getImageSettings(params = {}) {
// we ignore notifications that don't concern us
if (params.config_id !== this.image_config.id ||
this.viewer === null ||
typeof params.callback !== 'function') return;
params.callback(this.viewer.captureViewParameters());
this.viewer.redraw();
}
/**
* Changes the regions modes
*
* @param {Object} params the event notification parameters
* @memberof Ol3Viewer
*/
changeRegionsModes(params={}) {
// we don't do this if it does not concern us
// or we don't have the right params
if (params.config_id !== this.image_config.id ||
this.viewer === null ||
typeof params !== 'object' ||
!Misc.isArray(params.modes)) return;
this.image_config.regions_info.regions_modes =
this.viewer.setRegionsModes(params.modes);
}
/**
* Initializes the ol3 regions layer
*
* @memberof Ol3Viewer
*/
initRegions() {
if (this.viewer === null ||
this.image_config === null ||
this.image_config.regions_info === null ||
!this.image_config.regions_info.ready ||
!Misc.isArray(this.image_config.regions_info.tmp_data)) return;
this.viewer.addRegions(this.image_config.regions_info.tmp_data);
this.changeRegionsModes(
{ modes: this.image_config.regions_info.regions_modes});
this.viewer.showShapeComments(
this.image_config.regions_info.show_comments);
let updateMeasurements = () => {
if (this.viewer === null) return;
let ids =
this.image_config.regions_info.unsophisticatedShapeFilter();
let measurements = this.viewer.getLengthAndAreaForShapes(ids);
for (let i=0;i<measurements.length;i++) {
let measurement = measurements[i];
if (typeof measurement !== 'object' ||
measurement === null || typeof measurement.id !== 'string')
continue;
let shape =
this.image_config.regions_info.getShape(measurement.id);
if (shape !== null) {
shape.Area = measurement.Area;
shape.Length = measurement.Length;
}
}
};
// If we have initial_roi_id for this viewer, select it...
let roi_id;
let shape_id;
if (this.image_config.image_info.initial_shape_id) {
shape_id = this.image_config.image_info.initial_shape_id;
roi_id = this.image_config.regions_info.getRoiFromShapeId(shape_id);
} else if (this.image_config.image_info.initial_roi_id) {
roi_id = this.image_config.image_info.initial_roi_id;
}
if (roi_id) {
let roi = this.image_config.regions_info.data.get(roi_id);
let shape_ids;
if (shape_id) {
shape_ids = [`${roi_id}:${shape_id}`];
} else {
// select first shape in ROI
shape_ids = [`${roi.id}:${roi.shapes.keys().next().value}`];
}
// select shapes...
this.changeShapeSelection({
config_id: this.image_config.id,
property: "selected",
shapes: shape_ids,
clear: true,
value: true,
center: true,