/
BidirectionalTool.ts
1358 lines (1146 loc) · 39.5 KB
/
BidirectionalTool.ts
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
import { vec2, vec3 } from 'gl-matrix';
import { getEnabledElement, utilities as csUtils } from '@cornerstonejs/core';
import type { Types } from '@cornerstonejs/core';
import { getCalibratedLengthUnitsAndScale } from '../../utilities/getCalibratedUnits';
import { roundNumber } from '../../utilities';
import { AnnotationTool } from '../base';
import throttle from '../../utilities/throttle';
import {
addAnnotation,
getAnnotations,
removeAnnotation,
} from '../../stateManagement/annotation/annotationState';
import { isAnnotationLocked } from '../../stateManagement/annotation/annotationLocking';
import { isAnnotationVisible } from '../../stateManagement/annotation/annotationVisibility';
import {
triggerAnnotationCompleted,
triggerAnnotationModified,
} from '../../stateManagement/annotation/helpers/state';
import {
drawLine as drawLineSvg,
drawHandles as drawHandlesSvg,
drawLinkedTextBox as drawLinkedTextBoxSvg,
} from '../../drawingSvg';
import { state } from '../../store';
import { Events } from '../../enums';
import { getViewportIdsWithToolToRender } from '../../utilities/viewportFilters';
import * as lineSegment from '../../utilities/math/line';
import { getTextBoxCoordsCanvas } from '../../utilities/drawing';
import {
resetElementCursor,
hideElementCursor,
} from '../../cursors/elementCursor';
import {
EventTypes,
ToolHandle,
TextBoxHandle,
PublicToolProps,
ToolProps,
SVGDrawingHelper,
} from '../../types';
import { BidirectionalAnnotation } from '../../types/ToolSpecificAnnotationTypes';
import triggerAnnotationRenderForViewportIds from '../../utilities/triggerAnnotationRenderForViewportIds';
import { StyleSpecifier } from '../../types/AnnotationStyle';
const { transformWorldToIndex } = csUtils;
/**
* BidirectionalTool let you draw annotations that measures the length and
* width at the same time in `mm` unit. It is consisted of two perpendicular lines and
* a text box. You can use the BidirectionalTool in all planes even in oblique
* reconstructed planes. Note: annotation tools in cornerstone3DTools exists in the exact location
* in the physical 3d space, as a result, by default, all annotations that are
* drawing in the same frameOfReference will get shared between viewports that
* are in the same frameOfReference.
*
* The resulting annotation's data (statistics) and metadata (the
* state of the viewport while drawing was happening) will get added to the
* ToolState manager and can be accessed from the ToolState by calling getAnnotations
* or similar methods.
*
* ```js
* cornerstoneTools.addTool(BidirectionalTool)
*
* const toolGroup = ToolGroupManager.createToolGroup('toolGroupId')
*
* toolGroup.addTool(BidirectionalTool.toolName)
*
* toolGroup.addViewport('viewportId', 'renderingEngineId')
*
* toolGroup.setToolActive(BidirectionalTool.toolName, {
* bindings: [
* {
* mouseButton: MouseBindings.Primary, // Left Click
* },
* ],
* })
* ```
*
* Read more in the Docs section of the website.
*/
class BidirectionalTool extends AnnotationTool {
static toolName;
touchDragCallback: any;
mouseDragCallback: any;
_throttledCalculateCachedStats: any;
editData: {
annotation: any;
viewportIdsToRender: string[];
handleIndex?: number;
movingTextBox: boolean;
newAnnotation?: boolean;
hasMoved?: boolean;
} | null;
isDrawing: boolean;
isHandleOutsideImage: boolean;
preventHandleOutsideImage: boolean;
constructor(
toolProps: PublicToolProps = {},
defaultToolProps: ToolProps = {
supportedInteractionTypes: ['Mouse', 'Touch'],
configuration: {
preventHandleOutsideImage: false,
getTextLines: defaultGetTextLines,
},
}
) {
super(toolProps, defaultToolProps);
this._throttledCalculateCachedStats = throttle(
this._calculateCachedStats,
100,
{ trailing: true }
);
}
/**
* Based on the current position of the mouse and the current imageId to create
* a Bidirectional Annotation and stores it in the annotationManager
*
* @param evt - EventTypes.NormalizedMouseEventType
* @returns The annotation object.
*
*/
addNewAnnotation(
evt: EventTypes.InteractionEventType
): BidirectionalAnnotation {
const eventDetail = evt.detail;
const { currentPoints, element } = eventDetail;
const worldPos = currentPoints.world;
const enabledElement = getEnabledElement(element);
const { viewport, renderingEngine } = enabledElement;
this.isDrawing = true;
const camera = viewport.getCamera();
const { viewPlaneNormal, viewUp } = camera;
const referencedImageId = this.getReferencedImageId(
viewport,
worldPos,
viewPlaneNormal,
viewUp
);
const FrameOfReferenceUID = viewport.getFrameOfReferenceUID();
const annotation: BidirectionalAnnotation = {
highlighted: true,
invalidated: true,
metadata: {
toolName: this.getToolName(),
viewPlaneNormal: <Types.Point3>[...viewPlaneNormal],
viewUp: <Types.Point3>[...viewUp],
FrameOfReferenceUID,
referencedImageId,
},
data: {
handles: {
points: [
// long
<Types.Point3>[...worldPos],
<Types.Point3>[...worldPos],
// short
<Types.Point3>[...worldPos],
<Types.Point3>[...worldPos],
],
textBox: {
hasMoved: false,
worldPosition: <Types.Point3>[0, 0, 0],
worldBoundingBox: {
topLeft: <Types.Point3>[0, 0, 0],
topRight: <Types.Point3>[0, 0, 0],
bottomLeft: <Types.Point3>[0, 0, 0],
bottomRight: <Types.Point3>[0, 0, 0],
},
},
activeHandleIndex: null,
},
label: '',
cachedStats: {},
},
};
addAnnotation(annotation, element);
const viewportIdsToRender = getViewportIdsWithToolToRender(
element,
this.getToolName()
);
this.editData = {
annotation,
viewportIdsToRender,
handleIndex: 1,
movingTextBox: false,
newAnnotation: true,
hasMoved: false,
};
this._activateDraw(element);
hideElementCursor(element);
evt.preventDefault();
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
return annotation;
}
/**
* It returns if the canvas point is near the provided annotation in the provided
* element or not. A proximity is passed to the function to determine the
* proximity of the point to the annotation in number of pixels.
*
* @param element - HTML Element
* @param annotation - Annotation
* @param canvasCoords - Canvas coordinates
* @param proximity - Proximity to tool to consider
* @returns Boolean, whether the canvas point is near tool
*/
isPointNearTool = (
element: HTMLDivElement,
annotation: BidirectionalAnnotation,
canvasCoords: Types.Point2,
proximity: number
): boolean => {
const enabledElement = getEnabledElement(element);
const { viewport } = enabledElement;
const { data } = annotation;
const { points } = data.handles;
// Check long axis
let canvasPoint1 = viewport.worldToCanvas(points[0]);
let canvasPoint2 = viewport.worldToCanvas(points[1]);
let line = {
start: {
x: canvasPoint1[0],
y: canvasPoint1[1],
},
end: {
x: canvasPoint2[0],
y: canvasPoint2[1],
},
};
let distanceToPoint = lineSegment.distanceToPoint(
[line.start.x, line.start.y],
[line.end.x, line.end.y],
[canvasCoords[0], canvasCoords[1]]
);
if (distanceToPoint <= proximity) {
return true;
}
// Check short axis
canvasPoint1 = viewport.worldToCanvas(points[2]);
canvasPoint2 = viewport.worldToCanvas(points[3]);
line = {
start: {
x: canvasPoint1[0],
y: canvasPoint1[1],
},
end: {
x: canvasPoint2[0],
y: canvasPoint2[1],
},
};
distanceToPoint = lineSegment.distanceToPoint(
[line.start.x, line.start.y],
[line.end.x, line.end.y],
[canvasCoords[0], canvasCoords[1]]
);
if (distanceToPoint <= proximity) {
return true;
}
return false;
};
/**
* Handles the toolSelected callback for bidirectional tool
* @param evt - EventTypes.MouseDownEventType
* @param annotation - Bidirectional annotation
* @param interactionType - interaction type (mouse, touch)
*/
toolSelectedCallback = (
evt: EventTypes.InteractionEventType,
annotation: BidirectionalAnnotation
): void => {
const eventDetail = evt.detail;
const { element } = eventDetail;
annotation.highlighted = true;
const viewportIdsToRender = getViewportIdsWithToolToRender(
element,
this.getToolName()
);
this.editData = {
annotation,
viewportIdsToRender,
movingTextBox: false,
};
this._activateModify(element);
const enabledElement = getEnabledElement(element);
const { renderingEngine } = enabledElement;
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
hideElementCursor(element);
evt.preventDefault();
};
/**
* Executes the callback for when mouse has selected a handle (anchor point) of
* the bidirectional tool or when the text box has been selected.
*
* @param evt - EventTypes.MouseDownEventType
* @param annotation - Bidirectional annotation
* @param handle - Handle index or selected textBox information
* @param interactionType - interaction type (mouse, touch)
*/
handleSelectedCallback = (
evt: EventTypes.InteractionEventType,
annotation: BidirectionalAnnotation,
handle: ToolHandle
): void => {
const eventDetail = evt.detail;
const { element } = eventDetail;
const data = annotation.data;
annotation.highlighted = true;
let movingTextBox = false;
let handleIndex;
if ((handle as TextBoxHandle).worldPosition) {
movingTextBox = true;
} else {
handleIndex = data.handles.points.findIndex((p) => p === handle);
}
// Find viewports to render on drag.
const viewportIdsToRender = getViewportIdsWithToolToRender(
element,
this.getToolName()
);
hideElementCursor(element);
this.editData = {
annotation,
viewportIdsToRender,
handleIndex,
movingTextBox,
};
this._activateModify(element);
const enabledElement = getEnabledElement(element);
const { renderingEngine } = enabledElement;
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
evt.preventDefault();
};
/**
* Handles the mouse up action for the bidirectional tool. It can be at the end
* of the annotation drawing (MouseUpEventType) or when the user clicks and release
* the mouse button instantly which let to the annotation to draw without holding
* the mouse button (MouseClickEventType).
*
* @param evt - mouse up or mouse click event types
*/
_endCallback = (evt: EventTypes.InteractionEventType): void => {
const eventDetail = evt.detail;
const { element } = eventDetail;
const { annotation, viewportIdsToRender, newAnnotation, hasMoved } =
this.editData;
const { data } = annotation;
if (newAnnotation && !hasMoved) {
return;
}
data.handles.activeHandleIndex = null;
this._deactivateModify(element);
this._deactivateDraw(element);
resetElementCursor(element);
const { renderingEngine } = getEnabledElement(element);
if (this.editData.handleIndex !== undefined) {
const { points } = data.handles;
const firstLineSegmentLength = vec3.distance(points[0], points[1]);
const secondLineSegmentLength = vec3.distance(points[2], points[3]);
if (secondLineSegmentLength > firstLineSegmentLength) {
// Switch points so [0,1] is the long axis and [2,3] is the short axis.
const longAxis = [[...points[2]], [...points[3]]];
const shortAxisPoint0 = [...points[0]];
const shortAxisPoint1 = [...points[1]];
// shortAxis[0->1] should be perpendicular (counter-clockwise) to longAxis[0->1]
const longAxisVector = vec2.create();
vec2.set(
longAxisVector,
longAxis[1][0] - longAxis[0][0],
longAxis[1][1] - longAxis[1][0]
);
const counterClockWisePerpendicularToLongAxis = vec2.create();
vec2.set(
counterClockWisePerpendicularToLongAxis,
-longAxisVector[1],
longAxisVector[0]
);
const currentShortAxisVector = vec2.create();
vec2.set(
currentShortAxisVector,
shortAxisPoint1[0] - shortAxisPoint0[0],
shortAxisPoint1[1] - shortAxisPoint0[0]
);
let shortAxis;
if (
vec2.dot(
currentShortAxisVector,
counterClockWisePerpendicularToLongAxis
) > 0
) {
shortAxis = [shortAxisPoint0, shortAxisPoint1];
} else {
shortAxis = [shortAxisPoint1, shortAxisPoint0];
}
data.handles.points = [
longAxis[0],
longAxis[1],
shortAxis[0],
shortAxis[1],
];
}
}
if (
this.isHandleOutsideImage &&
this.configuration.preventHandleOutsideImage
) {
removeAnnotation(annotation.annotationUID);
}
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
if (newAnnotation) {
triggerAnnotationCompleted(annotation);
}
this.editData = null;
this.isDrawing = false;
};
/**
* @param evt - mouse move event type or mouse drag
*/
_dragDrawCallback = (evt: EventTypes.InteractionEventType): void => {
this.isDrawing = true;
const eventDetail = evt.detail;
const { currentPoints, element } = eventDetail;
const enabledElement = getEnabledElement(element);
const { renderingEngine, viewport } = enabledElement;
const { worldToCanvas } = viewport;
const { annotation, viewportIdsToRender, handleIndex } = this.editData;
const { data } = annotation;
const worldPos = currentPoints.world;
// Update first move handle
data.handles.points[handleIndex] = [...worldPos];
const canvasCoordPoints = data.handles.points.map(worldToCanvas);
const canvasCoords = {
longLineSegment: {
start: {
x: canvasCoordPoints[0][0],
y: canvasCoordPoints[0][1],
},
end: {
x: canvasCoordPoints[1][0],
y: canvasCoordPoints[1][1],
},
},
shortLineSegment: {
start: {
x: canvasCoordPoints[2][0],
y: canvasCoordPoints[2][1],
},
end: {
x: canvasCoordPoints[3][0],
y: canvasCoordPoints[3][1],
},
},
};
// ~~ calculate worldPos of our short axis handles
// short axis is perpendicular to long axis, and we set its length to be 2/3 of long axis
// (meaning each)
const dist = vec2.distance(canvasCoordPoints[0], canvasCoordPoints[1]);
const shortAxisDistFromCenter = dist / 3;
// Calculate long line's incline
const dx =
canvasCoords.longLineSegment.start.x - canvasCoords.longLineSegment.end.x;
const dy =
canvasCoords.longLineSegment.start.y - canvasCoords.longLineSegment.end.y;
const length = Math.sqrt(dx * dx + dy * dy);
const vectorX = dx / length;
const vectorY = dy / length;
// middle point between long line segment's points
const xMid =
(canvasCoords.longLineSegment.start.x +
canvasCoords.longLineSegment.end.x) /
2;
const yMid =
(canvasCoords.longLineSegment.start.y +
canvasCoords.longLineSegment.end.y) /
2;
// short points 1/3 distance from center of long points
const startX = xMid + shortAxisDistFromCenter * vectorY;
const startY = yMid - shortAxisDistFromCenter * vectorX;
const endX = xMid - shortAxisDistFromCenter * vectorY;
const endY = yMid + shortAxisDistFromCenter * vectorX;
// Update perpendicular line segment's points
data.handles.points[2] = viewport.canvasToWorld([startX, startY]);
data.handles.points[3] = viewport.canvasToWorld([endX, endY]);
annotation.invalidated = true;
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
this.editData.hasMoved = true;
};
/**
* Mouse drag to edit annotation callback
* @param evt - mouse drag event
*/
_dragModifyCallback = (evt: EventTypes.InteractionEventType): void => {
this.isDrawing = true;
const eventDetail = evt.detail;
const { element } = eventDetail;
const enabledElement = getEnabledElement(element);
const { renderingEngine } = enabledElement;
const { annotation, viewportIdsToRender, handleIndex, movingTextBox } =
this.editData;
const { data } = annotation;
if (movingTextBox) {
const { deltaPoints } = eventDetail;
const worldPosDelta = deltaPoints.world;
const { textBox } = data.handles;
const { worldPosition } = textBox;
worldPosition[0] += worldPosDelta[0];
worldPosition[1] += worldPosDelta[1];
worldPosition[2] += worldPosDelta[2];
textBox.hasMoved = true;
} else if (handleIndex === undefined) {
// Moving tool
const { deltaPoints } = eventDetail;
const worldPosDelta = deltaPoints.world;
const points = data.handles.points;
points.forEach((point) => {
point[0] += worldPosDelta[0];
point[1] += worldPosDelta[1];
point[2] += worldPosDelta[2];
});
annotation.invalidated = true;
} else {
this._dragModifyHandle(evt);
annotation.invalidated = true;
}
triggerAnnotationRenderForViewportIds(renderingEngine, viewportIdsToRender);
};
/**
* Mouse dragging a handle callback
* @param evt - mouse drag event
*/
_dragModifyHandle = (evt: EventTypes.InteractionEventType): void => {
const eventDetail = evt.detail;
const { currentPoints, element } = eventDetail;
const enabledElement = getEnabledElement(element);
const { viewport } = enabledElement;
const { annotation, handleIndex: movingHandleIndex } = this.editData;
const { data } = annotation;
// Moving handle
const worldPos = currentPoints.world;
const canvasCoordHandlesCurrent = [
viewport.worldToCanvas(data.handles.points[0]),
viewport.worldToCanvas(data.handles.points[1]),
viewport.worldToCanvas(data.handles.points[2]),
viewport.worldToCanvas(data.handles.points[3]),
];
const firstLineSegment = {
start: {
x: canvasCoordHandlesCurrent[0][0],
y: canvasCoordHandlesCurrent[0][1],
},
end: {
x: canvasCoordHandlesCurrent[1][0],
y: canvasCoordHandlesCurrent[1][1],
},
};
const secondLineSegment = {
start: {
x: canvasCoordHandlesCurrent[2][0],
y: canvasCoordHandlesCurrent[2][1],
},
end: {
x: canvasCoordHandlesCurrent[3][0],
y: canvasCoordHandlesCurrent[3][1],
},
};
// Handle we've selected's proposed point
const proposedPoint = <Types.Point3>[...worldPos];
const proposedCanvasCoord = viewport.worldToCanvas(proposedPoint);
if (movingHandleIndex === 0 || movingHandleIndex === 1) {
const fixedHandleIndex = movingHandleIndex === 0 ? 1 : 0;
const fixedHandleCanvasCoord =
canvasCoordHandlesCurrent[fixedHandleIndex];
const fixedHandleToProposedCoordVec = vec2.set(
vec2.create(),
proposedCanvasCoord[0] - fixedHandleCanvasCoord[0],
proposedCanvasCoord[1] - fixedHandleCanvasCoord[1]
);
const fixedHandleToOldCoordVec = vec2.set(
vec2.create(),
canvasCoordHandlesCurrent[movingHandleIndex][0] -
fixedHandleCanvasCoord[0],
canvasCoordHandlesCurrent[movingHandleIndex][1] -
fixedHandleCanvasCoord[1]
);
// normalize vector
vec2.normalize(
fixedHandleToProposedCoordVec,
fixedHandleToProposedCoordVec
);
vec2.normalize(fixedHandleToOldCoordVec, fixedHandleToOldCoordVec);
// Check whether this
const proposedFirstLineSegment = {
start: {
x: fixedHandleCanvasCoord[0],
y: fixedHandleCanvasCoord[1],
},
end: {
x: proposedCanvasCoord[0],
y: proposedCanvasCoord[1],
},
};
// Note: this is the case when we are modifying the long axis line segment
// and we make it shorter and shorter until its second half size becomes zero
// which basically means that any more modification would make the long axis
// second half disappear. In this case, we just bail out and do not update
// since we don't want to disrupt the bidirectional shape.
if (
this._movingLongAxisWouldPutItThroughShortAxis(
proposedFirstLineSegment,
secondLineSegment
)
) {
return;
}
const centerOfRotation = fixedHandleCanvasCoord;
const angle = this._getSignedAngle(
fixedHandleToOldCoordVec,
fixedHandleToProposedCoordVec
);
// rotate handles around the center of rotation, first translate to origin,
// then rotate, then translate back
let firstPointX = canvasCoordHandlesCurrent[2][0];
let firstPointY = canvasCoordHandlesCurrent[2][1];
let secondPointX = canvasCoordHandlesCurrent[3][0];
let secondPointY = canvasCoordHandlesCurrent[3][1];
// translate to origin
firstPointX -= centerOfRotation[0];
firstPointY -= centerOfRotation[1];
secondPointX -= centerOfRotation[0];
secondPointY -= centerOfRotation[1];
// rotate
const rotatedFirstPoint =
firstPointX * Math.cos(angle) - firstPointY * Math.sin(angle);
const rotatedFirstPointY =
firstPointX * Math.sin(angle) + firstPointY * Math.cos(angle);
const rotatedSecondPoint =
secondPointX * Math.cos(angle) - secondPointY * Math.sin(angle);
const rotatedSecondPointY =
secondPointX * Math.sin(angle) + secondPointY * Math.cos(angle);
// translate back
firstPointX = rotatedFirstPoint + centerOfRotation[0];
firstPointY = rotatedFirstPointY + centerOfRotation[1];
secondPointX = rotatedSecondPoint + centerOfRotation[0];
secondPointY = rotatedSecondPointY + centerOfRotation[1];
// update handles
const newFirstPoint = viewport.canvasToWorld([firstPointX, firstPointY]);
const newSecondPoint = viewport.canvasToWorld([
secondPointX,
secondPointY,
]);
// the fixed handle is the one that is not being moved so we
// don't need to update it
data.handles.points[movingHandleIndex] = proposedPoint;
data.handles.points[2] = newFirstPoint;
data.handles.points[3] = newSecondPoint;
} else {
// Translation manipulator
const translateHandleIndex = movingHandleIndex === 2 ? 3 : 2;
const canvasCoordsCurrent = {
longLineSegment: {
start: firstLineSegment.start,
end: firstLineSegment.end,
},
shortLineSegment: {
start: secondLineSegment.start,
end: secondLineSegment.end,
},
};
const longLineSegmentVec = vec2.subtract(
vec2.create(),
[
canvasCoordsCurrent.longLineSegment.end.x,
canvasCoordsCurrent.longLineSegment.end.y,
],
[
canvasCoordsCurrent.longLineSegment.start.x,
canvasCoordsCurrent.longLineSegment.start.y,
]
);
const longLineSegmentVecNormalized = vec2.normalize(
vec2.create(),
longLineSegmentVec
);
const proposedToCurrentVec = vec2.subtract(
vec2.create(),
[proposedCanvasCoord[0], proposedCanvasCoord[1]],
[
canvasCoordHandlesCurrent[movingHandleIndex][0],
canvasCoordHandlesCurrent[movingHandleIndex][1],
]
);
const movementLength = vec2.length(proposedToCurrentVec);
const angle = this._getSignedAngle(
longLineSegmentVecNormalized,
proposedToCurrentVec
);
const movementAlongLineSegmentLength = Math.cos(angle) * movementLength;
const newTranslatedPoint = vec2.scaleAndAdd(
vec2.create(),
[
canvasCoordHandlesCurrent[translateHandleIndex][0],
canvasCoordHandlesCurrent[translateHandleIndex][1],
],
longLineSegmentVecNormalized,
movementAlongLineSegmentLength
);
// don't update if it passes through the other line segment
if (
this._movingLongAxisWouldPutItThroughShortAxis(
{
start: {
x: proposedCanvasCoord[0],
y: proposedCanvasCoord[1],
},
end: {
x: newTranslatedPoint[0],
y: newTranslatedPoint[1],
},
},
{
start: {
x: canvasCoordsCurrent.longLineSegment.start.x,
y: canvasCoordsCurrent.longLineSegment.start.y,
},
end: {
x: canvasCoordsCurrent.longLineSegment.end.x,
y: canvasCoordsCurrent.longLineSegment.end.y,
},
}
)
) {
return;
}
const intersectionPoint = lineSegment.intersectLine(
[proposedCanvasCoord[0], proposedCanvasCoord[1]],
[newTranslatedPoint[0], newTranslatedPoint[1]],
[firstLineSegment.start.x, firstLineSegment.start.y],
[firstLineSegment.end.x, firstLineSegment.end.y]
);
// don't update if it doesn't intersect
if (!intersectionPoint) {
return;
}
data.handles.points[translateHandleIndex] = viewport.canvasToWorld(
newTranslatedPoint as Types.Point2
);
data.handles.points[movingHandleIndex] = proposedPoint;
}
};
/**
* Cancels an ongoing drawing of a bidirectional annotation
* @param element - HTML Element
*/
cancel = (element: HTMLDivElement) => {
// If it is mid-draw or mid-modify
if (this.isDrawing) {
this.isDrawing = false;
this._deactivateDraw(element);
this._deactivateModify(element);
resetElementCursor(element);
const { annotation, viewportIdsToRender, newAnnotation } = this.editData;
const { data } = annotation;
annotation.highlighted = false;
data.handles.activeHandleIndex = null;
const { renderingEngine } = getEnabledElement(element);
triggerAnnotationRenderForViewportIds(
renderingEngine,
viewportIdsToRender
);
if (newAnnotation) {
triggerAnnotationCompleted(annotation);
}
this.editData = null;
return annotation.annotationUID;
}
};
_activateDraw = (element) => {
state.isInteractingWithTool = true;
element.addEventListener(Events.MOUSE_UP, this._endCallback);
element.addEventListener(Events.MOUSE_DRAG, this._dragDrawCallback);
element.addEventListener(Events.MOUSE_MOVE, this._dragDrawCallback);
element.addEventListener(Events.MOUSE_CLICK, this._endCallback);
element.addEventListener(
Events.TOUCH_TAP,
this._endCallback as EventListener
);
element.addEventListener(
Events.TOUCH_END,
this._endCallback as EventListener
);
element.addEventListener(
Events.TOUCH_DRAG,
this._dragDrawCallback as EventListener
);
};
_deactivateDraw = (element) => {
state.isInteractingWithTool = false;
element.removeEventListener(Events.MOUSE_UP, this._endCallback);
element.removeEventListener(Events.MOUSE_DRAG, this._dragDrawCallback);
element.removeEventListener(Events.MOUSE_MOVE, this._dragDrawCallback);
element.removeEventListener(Events.MOUSE_CLICK, this._endCallback);
element.removeEventListener(
Events.TOUCH_TAP,
this._endCallback as EventListener
);
element.removeEventListener(
Events.TOUCH_END,
this._endCallback as EventListener
);
element.removeEventListener(
Events.TOUCH_DRAG,
this._dragDrawCallback as EventListener
);
};
_activateModify = (element) => {
state.isInteractingWithTool = true;
element.addEventListener(Events.MOUSE_UP, this._endCallback);
element.addEventListener(Events.MOUSE_DRAG, this._dragModifyCallback);
element.addEventListener(Events.MOUSE_CLICK, this._endCallback);
element.addEventListener(
Events.TOUCH_END,
this._endCallback as EventListener
);
element.addEventListener(
Events.TOUCH_DRAG,
this._dragModifyCallback as EventListener
);
element.addEventListener(
Events.TOUCH_TAP,
this._endCallback as EventListener
);
};
_deactivateModify = (element) => {
state.isInteractingWithTool = false;
element.removeEventListener(Events.MOUSE_UP, this._endCallback);
element.removeEventListener(Events.MOUSE_DRAG, this._dragModifyCallback);
element.removeEventListener(Events.MOUSE_CLICK, this._endCallback);
element.removeEventListener(
Events.TOUCH_END,
this._endCallback as EventListener
);
element.removeEventListener(
Events.TOUCH_DRAG,
this._dragModifyCallback as EventListener
);
element.removeEventListener(
Events.TOUCH_TAP,
this._endCallback as EventListener
);
};
/**
* it is used to draw the bidirectional annotation in each
* request animation frame. It calculates the updated cached statistics if
* data is invalidated and cache it.
*
* @param enabledElement - The Cornerstone's enabledElement.
* @param svgDrawingHelper - The svgDrawingHelper providing the context for drawing.